diff --git a/dist/index.es.js b/dist/index.es.js index 30e4794..54fba85 100644 --- a/dist/index.es.js +++ b/dist/index.es.js @@ -1,6 +1,8 @@ import * as React from 'react'; import React__default, { useReducer, useRef, useDebugValue, useEffect, useLayoutEffect as useLayoutEffect$1, useState, useMemo, forwardRef, useCallback, useContext, createContext, useImperativeHandle, memo, Suspense } from 'react'; import * as ReactDOM from 'react-dom/client'; +import { Line2, LineMaterial, LineGeometry, OrbitControls as OrbitControls$1, RoundedBoxGeometry, isWebGL2Available, ConvexGeometry } from 'three-stdlib'; +import { mergeBufferGeometries } from 'three-stdlib/utils/BufferGeometryUtils'; function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); @@ -19,7 +21,7 @@ function _objectSpread2$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { - _defineProperty$3(target, key, source[key]); + _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); @@ -53,7 +55,7 @@ function _createClass(Constructor, protoProps, staticProps) { return Constructor; } -function _defineProperty$3(obj, key, value) { +function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -201,7 +203,7 @@ function _nonIterableRest() { * Copyright 2010-2022 Three.js Authors * SPDX-License-Identifier: MIT */ -const REVISION = '139'; +const REVISION = '142'; const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; const CullFaceNone = 0; @@ -470,13 +472,7 @@ class EventDispatcher { } -const _lut$1 = []; - -for ( let i = 0; i < 256; i ++ ) { - - _lut$1[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); - -} +const _lut$1 = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ]; let _seed = 1234567; @@ -559,7 +555,7 @@ function pingpong( x, length = 1 ) { } // http://en.wikipedia.org/wiki/Smoothstep -function smoothstep$1( x, min, max ) { +function smoothstep( x, min, max ) { if ( x <= min ) return 0; if ( x >= max ) return 1; @@ -737,7 +733,7 @@ function denormalize$1( value, array ) { } -function normalize$1( value, array ) { +function normalize( value, array ) { switch ( array.constructor ) { @@ -781,7 +777,7 @@ var MathUtils = /*#__PURE__*/Object.freeze({ lerp: lerp, damp: damp, pingpong: pingpong, - smoothstep: smoothstep$1, + smoothstep: smoothstep, smootherstep: smootherstep, randInt: randInt, randFloat: randFloat, @@ -793,7 +789,7 @@ var MathUtils = /*#__PURE__*/Object.freeze({ ceilPowerOfTwo: ceilPowerOfTwo, floorPowerOfTwo: floorPowerOfTwo, setQuaternionFromProperEuler: setQuaternionFromProperEuler, - normalize: normalize$1, + normalize: normalize, denormalize: denormalize$1 }); @@ -801,6 +797,8 @@ class Vector2 { constructor( x = 0, y = 0 ) { + Vector2.prototype.isVector2 = true; + this.x = x; this.y = y; @@ -1278,12 +1276,12 @@ class Vector2 { } -Vector2.prototype.isVector2 = true; - class Matrix3 { constructor() { + Matrix3.prototype.isMatrix3 = true; + this.elements = [ 1, 0, 0, @@ -1616,8 +1614,6 @@ class Matrix3 { } -Matrix3.prototype.isMatrix3 = true; - function arrayNeedsUint32( array ) { // assumes larger values usually on last @@ -1783,6 +1779,12 @@ class Color { constructor( r, g, b ) { + this.isColor = true; + + this.r = 1; + this.g = 1; + this.b = 1; + if ( g === undefined && b === undefined ) { // r is THREE.Color, hex or string @@ -2321,15 +2323,18 @@ class Color { } + *[ Symbol.iterator ]() { + + yield this.r; + yield this.g; + yield this.b; + + } + } Color.NAMES = _colorKeywords; -Color.prototype.isColor = true; -Color.prototype.r = 1; -Color.prototype.g = 1; -Color.prototype.b = 1; - let _canvas; class ImageUtils { @@ -2459,6 +2464,8 @@ class Source { constructor( data = null ) { + this.isSource = true; + this.uuid = generateUUID$1(); this.data = data; @@ -2555,7 +2562,7 @@ function serializeImage( image ) { // images of DataTexture return { - data: Array.prototype.slice.call( image.data ), + data: Array.from( image.data ), width: image.width, height: image.height, type: image.data.constructor.name @@ -2572,8 +2579,6 @@ function serializeImage( image ) { } -Source.prototype.isSource = true; - let textureId = 0; class Texture extends EventDispatcher { @@ -2582,6 +2587,8 @@ class Texture extends EventDispatcher { super(); + this.isTexture = true; + Object.defineProperty( this, 'id', { value: textureId ++ } ); this.uuid = generateUUID$1(); @@ -2862,12 +2869,12 @@ class Texture extends EventDispatcher { Texture.DEFAULT_IMAGE = null; Texture.DEFAULT_MAPPING = UVMapping; -Texture.prototype.isTexture = true; - class Vector4 { constructor( x = 0, y = 0, z = 0, w = 1 ) { + Vector4.prototype.isVector4 = true; + this.x = x; this.y = y; this.z = z; @@ -3525,8 +3532,6 @@ class Vector4 { } -Vector4.prototype.isVector4 = true; - /* In options, we can specify: * Texture parameters for an auto-generated target texture @@ -3538,6 +3543,8 @@ class WebGLRenderTarget extends EventDispatcher { super(); + this.isWebGLRenderTarget = true; + this.width = width; this.height = height; this.depth = 1; @@ -3606,7 +3613,8 @@ class WebGLRenderTarget extends EventDispatcher { // ensure image object is not shared, see #20328 - this.texture.image = Object.assign( {}, source.texture.image ); + const image = Object.assign( {}, source.texture.image ); + this.texture.source = new Source( image ); this.depthBuffer = source.depthBuffer; this.stencilBuffer = source.stencilBuffer; @@ -3627,14 +3635,14 @@ class WebGLRenderTarget extends EventDispatcher { } -WebGLRenderTarget.prototype.isWebGLRenderTarget = true; - class DataArrayTexture extends Texture { constructor( data = null, width = 1, height = 1, depth = 1 ) { super( null ); + this.isDataArrayTexture = true; + this.image = { data, width, height, depth }; this.magFilter = NearestFilter; @@ -3650,14 +3658,14 @@ class DataArrayTexture extends Texture { } -DataArrayTexture.prototype.isDataArrayTexture = true; - class WebGLArrayRenderTarget extends WebGLRenderTarget { constructor( width, height, depth ) { super( width, height ); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; this.texture = new DataArrayTexture( null, width, height, depth ); @@ -3668,8 +3676,6 @@ class WebGLArrayRenderTarget extends WebGLRenderTarget { } -WebGLArrayRenderTarget.prototype.isWebGLArrayRenderTarget = true; - class Data3DTexture extends Texture { constructor( data = null, width = 1, height = 1, depth = 1 ) { @@ -3684,6 +3690,8 @@ class Data3DTexture extends Texture { super( null ); + this.isData3DTexture = true; + this.image = { data, width, height, depth }; this.magFilter = NearestFilter; @@ -3699,14 +3707,14 @@ class Data3DTexture extends Texture { } -Data3DTexture.prototype.isData3DTexture = true; - class WebGL3DRenderTarget extends WebGLRenderTarget { constructor( width, height, depth ) { super( width, height ); + this.isWebGL3DRenderTarget = true; + this.depth = depth; this.texture = new Data3DTexture( null, width, height, depth ); @@ -3717,14 +3725,14 @@ class WebGL3DRenderTarget extends WebGLRenderTarget { } -WebGL3DRenderTarget.prototype.isWebGL3DRenderTarget = true; - class WebGLMultipleRenderTargets extends WebGLRenderTarget { constructor( width, height, count, options = {} ) { super( width, height, options ); + this.isWebGLMultipleRenderTargets = true; + const texture = this.texture; this.texture = []; @@ -3778,13 +3786,15 @@ class WebGLMultipleRenderTargets extends WebGLRenderTarget { this.depthBuffer = source.depthBuffer; this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; + + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); this.texture.length = 0; for ( let i = 0, il = source.texture.length; i < il; i ++ ) { this.texture[ i ] = source.texture[ i ].clone(); + this.texture[ i ].isRenderTargetTexture = true; } @@ -3794,12 +3804,12 @@ class WebGLMultipleRenderTargets extends WebGLRenderTarget { } -WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true; - class Quaternion { constructor( x = 0, y = 0, z = 0, w = 1 ) { + this.isQuaternion = true; + this._x = x; this._y = y; this._z = z; @@ -4478,14 +4488,23 @@ class Quaternion { _onChangeCallback() {} -} + *[ Symbol.iterator ]() { -Quaternion.prototype.isQuaternion = true; + yield this._x; + yield this._y; + yield this._z; + yield this._w; + + } + +} class Vector3 { constructor( x = 0, y = 0, z = 0 ) { + Vector3.prototype.isVector3 = true; + this.x = x; this.y = y; this.z = z; @@ -5228,8 +5247,6 @@ class Vector3 { } -Vector3.prototype.isVector3 = true; - const _vector$c = /*@__PURE__*/ new Vector3(); const _quaternion$4 = /*@__PURE__*/ new Quaternion(); @@ -5237,6 +5254,8 @@ class Box3 { constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { + this.isBox3 = true; + this.min = min; this.max = max; @@ -5702,8 +5721,6 @@ class Box3 { } -Box3.prototype.isBox3 = true; - const _points = [ /*@__PURE__*/ new Vector3(), /*@__PURE__*/ new Vector3(), @@ -6483,6 +6500,8 @@ class Matrix4 { constructor() { + Matrix4.prototype.isMatrix4 = true; + this.elements = [ 1, 0, 0, 0, @@ -7351,8 +7370,6 @@ class Matrix4 { } -Matrix4.prototype.isMatrix4 = true; - const _v1$5 = /*@__PURE__*/ new Vector3(); const _m1$2 = /*@__PURE__*/ new Matrix4(); const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); @@ -7368,6 +7385,8 @@ class Euler { constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) { + this.isEuler = true; + this._x = x; this._y = y; this._z = z; @@ -7656,9 +7675,24 @@ class Euler { _onChangeCallback() {} -} + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._order; + + } + + // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53 -Euler.prototype.isEuler = true; + toVector3() { + + console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' ); + + } + +} Euler.DefaultOrder = 'XYZ'; Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; @@ -7745,6 +7779,8 @@ class Object3D extends EventDispatcher { super(); + this.isObject3D = true; + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); this.uuid = generateUUID$1(); @@ -8633,11 +8669,9 @@ class Object3D extends EventDispatcher { } -Object3D.DefaultUp = new Vector3( 0, 1, 0 ); +Object3D.DefaultUp = /*@__PURE__*/ new Vector3( 0, 1, 0 ); Object3D.DefaultMatrixAutoUpdate = true; -Object3D.prototype.isObject3D = true; - const _v0$1 = /*@__PURE__*/ new Vector3(); const _v1$3 = /*@__PURE__*/ new Vector3(); const _v2$2 = /*@__PURE__*/ new Vector3(); @@ -8942,6 +8976,8 @@ class Material extends EventDispatcher { super(); + this.isMaterial = true; + Object.defineProperty( this, 'id', { value: materialId ++ } ); this.uuid = generateUUID$1(); @@ -8949,8 +8985,6 @@ class Material extends EventDispatcher { this.name = ''; this.type = 'Material'; - this.fog = true; - this.blending = NormalBlending; this.side = FrontSide; this.vertexColors = false; @@ -9154,6 +9188,22 @@ class Material extends EventDispatcher { } + if ( this.iridescence !== undefined ) data.iridescence = this.iridescence; + if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR; + if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + + if ( this.iridescenceMap && this.iridescenceMap.isTexture ) { + + data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid; + + } + + if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) { + + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid; + + } + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid; if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; @@ -9282,6 +9332,8 @@ class Material extends EventDispatcher { if ( this.toneMapped === false ) data.toneMapped = false; + if ( this.fog === false ) data.fog = false; + if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData; // TODO: Copied from Object3D.toJSON @@ -9326,8 +9378,6 @@ class Material extends EventDispatcher { this.name = source.name; - this.fog = source.fog; - this.blending = source.blending; this.side = source.side; this.vertexColors = source.vertexColors; @@ -9415,22 +9465,14 @@ class Material extends EventDispatcher { } -Material.prototype.isMaterial = true; - -Material.fromType = function ( /*type*/ ) { - - // TODO: Behavior added in Materials.js - - return null; - -}; - class MeshBasicMaterial extends Material { constructor( parameters ) { super(); + this.isMeshBasicMaterial = true; + this.type = 'MeshBasicMaterial'; this.color = new Color( 0xffffff ); // emissive @@ -9457,6 +9499,8 @@ class MeshBasicMaterial extends Material { this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; + this.fog = true; + this.setValues( parameters ); } @@ -9489,14 +9533,14 @@ class MeshBasicMaterial extends Material { this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; } } -MeshBasicMaterial.prototype.isMeshBasicMaterial = true; - const _vector$9 = /*@__PURE__*/ new Vector3(); const _vector2$1 = /*@__PURE__*/ new Vector2(); @@ -9510,6 +9554,8 @@ class BufferAttribute { } + this.isBufferAttribute = true; + this.name = ''; this.array = array; @@ -9878,7 +9924,7 @@ class BufferAttribute { const data = { itemSize: this.itemSize, type: this.array.constructor.name, - array: Array.prototype.slice.call( this.array ), + array: Array.from( this.array ), normalized: this.normalized }; @@ -9892,8 +9938,6 @@ class BufferAttribute { } -BufferAttribute.prototype.isBufferAttribute = true; - // class Int8BufferAttribute extends BufferAttribute { @@ -9972,11 +10016,12 @@ class Float16BufferAttribute extends BufferAttribute { super( new Uint16Array( array ), itemSize, normalized ); + this.isFloat16BufferAttribute = true; + } } -Float16BufferAttribute.prototype.isFloat16BufferAttribute = true; class Float32BufferAttribute extends BufferAttribute { @@ -10000,9 +10045,9 @@ class Float64BufferAttribute extends BufferAttribute { let _id$1 = 0; -const _m1$3 = /*@__PURE__*/ new Matrix4(); -const _obj$1 = /*@__PURE__*/ new Object3D(); -const _offset$1 = /*@__PURE__*/ new Vector3(); +const _m1 = /*@__PURE__*/ new Matrix4(); +const _obj = /*@__PURE__*/ new Object3D(); +const _offset = /*@__PURE__*/ new Vector3(); const _box$1 = /*@__PURE__*/ new Box3(); const _boxMorphTargets = /*@__PURE__*/ new Box3(); const _vector$8 = /*@__PURE__*/ new Vector3(); @@ -10013,6 +10058,8 @@ class BufferGeometry extends EventDispatcher { super(); + this.isBufferGeometry = true; + Object.defineProperty( this, 'id', { value: _id$1 ++ } ); this.uuid = generateUUID$1(); @@ -10164,9 +10211,9 @@ class BufferGeometry extends EventDispatcher { applyQuaternion( q ) { - _m1$3.makeRotationFromQuaternion( q ); + _m1.makeRotationFromQuaternion( q ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10176,9 +10223,9 @@ class BufferGeometry extends EventDispatcher { // rotate geometry around world x-axis - _m1$3.makeRotationX( angle ); + _m1.makeRotationX( angle ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10188,9 +10235,9 @@ class BufferGeometry extends EventDispatcher { // rotate geometry around world y-axis - _m1$3.makeRotationY( angle ); + _m1.makeRotationY( angle ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10200,9 +10247,9 @@ class BufferGeometry extends EventDispatcher { // rotate geometry around world z-axis - _m1$3.makeRotationZ( angle ); + _m1.makeRotationZ( angle ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10212,9 +10259,9 @@ class BufferGeometry extends EventDispatcher { // translate geometry - _m1$3.makeTranslation( x, y, z ); + _m1.makeTranslation( x, y, z ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10224,9 +10271,9 @@ class BufferGeometry extends EventDispatcher { // scale geometry - _m1$3.makeScale( x, y, z ); + _m1.makeScale( x, y, z ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10234,11 +10281,11 @@ class BufferGeometry extends EventDispatcher { lookAt( vector ) { - _obj$1.lookAt( vector ); + _obj.lookAt( vector ); - _obj$1.updateMatrix(); + _obj.updateMatrix(); - this.applyMatrix4( _obj$1.matrix ); + this.applyMatrix4( _obj.matrix ); return this; @@ -10248,9 +10295,9 @@ class BufferGeometry extends EventDispatcher { this.computeBoundingBox(); - this.boundingBox.getCenter( _offset$1 ).negate(); + this.boundingBox.getCenter( _offset ).negate(); - this.translate( _offset$1.x, _offset$1.y, _offset$1.z ); + this.translate( _offset.x, _offset.y, _offset.z ); return this; @@ -10430,8 +10477,8 @@ class BufferGeometry extends EventDispatcher { if ( morphTargetsRelative ) { - _offset$1.fromBufferAttribute( position, j ); - _vector$8.add( _offset$1 ); + _offset.fromBufferAttribute( position, j ); + _vector$8.add( _offset ); } @@ -11113,8 +11160,6 @@ class BufferGeometry extends EventDispatcher { } -BufferGeometry.prototype.isBufferGeometry = true; - const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4(); const _ray$2 = /*@__PURE__*/ new Ray(); const _sphere$3 = /*@__PURE__*/ new Sphere(); @@ -11144,6 +11189,8 @@ class Mesh extends Object3D { super(); + this.isMesh = true; + this.type = 'Mesh'; this.geometry = geometry; @@ -11153,9 +11200,9 @@ class Mesh extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); if ( source.morphTargetInfluences !== undefined ) { @@ -11180,43 +11227,29 @@ class Mesh extends Object3D { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); - - if ( keys.length > 0 ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + if ( keys.length > 0 ) { - if ( morphAttribute !== undefined ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( morphAttribute !== undefined ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - const name = morphAttribute[ m ].name || String( m ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - } else { - - const morphTargets = geometry.morphTargets; - - if ( morphTargets !== undefined && morphTargets.length > 0 ) { - - console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - - } - } } @@ -11253,128 +11286,124 @@ class Mesh extends Object3D { let intersection; - if ( geometry.isBufferGeometry ) { - - const index = geometry.index; - const position = geometry.attributes.position; - const morphPosition = geometry.morphAttributes.position; - const morphTargetsRelative = geometry.morphTargetsRelative; - const uv = geometry.attributes.uv; - const uv2 = geometry.attributes.uv2; - const groups = geometry.groups; - const drawRange = geometry.drawRange; - - if ( index !== null ) { + const index = geometry.index; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + const uv = geometry.attributes.uv; + const uv2 = geometry.attributes.uv2; + const groups = geometry.groups; + const drawRange = geometry.drawRange; - // indexed buffer geometry + if ( index !== null ) { - if ( Array.isArray( material ) ) { + // indexed buffer geometry - for ( let i = 0, il = groups.length; i < il; i ++ ) { + if ( Array.isArray( material ) ) { - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + for ( let i = 0, il = groups.length; i < il; i ++ ) { - const start = Math.max( group.start, drawRange.start ); - const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - for ( let j = start, jl = end; j < jl; j += 3 ) { + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); - const a = index.getX( j ); - const b = index.getX( j + 1 ); - const c = index.getX( j + 2 ); + for ( let j = start, jl = end; j < jl; j += 3 ) { - intersection = checkBufferGeometryIntersection$1( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = index.getX( j ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); - if ( intersection ) { + intersection = checkBufferGeometryIntersection$1( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); } } - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, il = end; i < il; i += 3 ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const a = index.getX( i ); - const b = index.getX( i + 1 ); - const c = index.getX( i + 2 ); + for ( let i = start, il = end; i < il; i += 3 ) { - intersection = checkBufferGeometryIntersection$1( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = index.getX( i ); + const b = index.getX( i + 1 ); + const c = index.getX( i + 2 ); - if ( intersection ) { + intersection = checkBufferGeometryIntersection$1( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); } } - } else if ( position !== undefined ) { + } - // non-indexed buffer geometry + } else if ( position !== undefined ) { - if ( Array.isArray( material ) ) { + // non-indexed buffer geometry - for ( let i = 0, il = groups.length; i < il; i ++ ) { + if ( Array.isArray( material ) ) { - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + for ( let i = 0, il = groups.length; i < il; i ++ ) { - const start = Math.max( group.start, drawRange.start ); - const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - for ( let j = start, jl = end; j < jl; j += 3 ) { + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); - const a = j; - const b = j + 1; - const c = j + 2; + for ( let j = start, jl = end; j < jl; j += 3 ) { - intersection = checkBufferGeometryIntersection$1( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = j; + const b = j + 1; + const c = j + 2; - if ( intersection ) { + intersection = checkBufferGeometryIntersection$1( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); } } - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, il = end; i < il; i += 3 ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); - const a = i; - const b = i + 1; - const c = i + 2; + for ( let i = start, il = end; i < il; i += 3 ) { - intersection = checkBufferGeometryIntersection$1( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = i; + const b = i + 1; + const c = i + 2; - if ( intersection ) { + intersection = checkBufferGeometryIntersection$1( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); } @@ -11382,18 +11411,12 @@ class Mesh extends Object3D { } - } else if ( geometry.isGeometry ) { - - console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - } } } -Mesh.prototype.isMesh = true; - function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) { let intersect; @@ -11762,6 +11785,8 @@ class ShaderMaterial extends Material { super(); + this.isShaderMaterial = true; + this.type = 'ShaderMaterial'; this.defines = {}; @@ -11827,6 +11852,7 @@ class ShaderMaterial extends Material { this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; this.lights = source.lights; this.clipping = source.clipping; @@ -11932,14 +11958,14 @@ class ShaderMaterial extends Material { } -ShaderMaterial.prototype.isShaderMaterial = true; - class Camera extends Object3D { constructor() { super(); + this.isCamera = true; + this.type = 'Camera'; this.matrixWorldInverse = new Matrix4(); @@ -11996,14 +12022,14 @@ class Camera extends Object3D { } -Camera.prototype.isCamera = true; - class PerspectiveCamera extends Camera { constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { super(); + this.isPerspectiveCamera = true; + this.type = 'PerspectiveCamera'; this.fov = fov; @@ -12225,8 +12251,6 @@ class PerspectiveCamera extends Camera { } -PerspectiveCamera.prototype.isPerspectiveCamera = true; - const fov = 90, aspect = 1; class CubeCamera extends Object3D { @@ -12294,11 +12318,9 @@ class CubeCamera extends Object3D { const currentRenderTarget = renderer.getRenderTarget(); - const currentOutputEncoding = renderer.outputEncoding; const currentToneMapping = renderer.toneMapping; const currentXrEnabled = renderer.xr.enabled; - renderer.outputEncoding = LinearEncoding; renderer.toneMapping = NoToneMapping; renderer.xr.enabled = false; @@ -12328,7 +12350,6 @@ class CubeCamera extends Object3D { renderer.setRenderTarget( currentRenderTarget ); - renderer.outputEncoding = currentOutputEncoding; renderer.toneMapping = currentToneMapping; renderer.xr.enabled = currentXrEnabled; @@ -12347,6 +12368,8 @@ class CubeTexture extends Texture { super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.isCubeTexture = true; + this.flipY = false; } @@ -12365,14 +12388,14 @@ class CubeTexture extends Texture { } -CubeTexture.prototype.isCubeTexture = true; - class WebGLCubeRenderTarget extends WebGLRenderTarget { constructor( size, options = {} ) { super( size, size, options ); + this.isWebGLCubeRenderTarget = true; + const image = { width: size, height: size, depth: 1 }; const images = [ image, image, image, image, image, image ]; @@ -12501,8 +12524,6 @@ class WebGLCubeRenderTarget extends WebGLRenderTarget { } -WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true; - const _vector1 = /*@__PURE__*/ new Vector3(); const _vector2 = /*@__PURE__*/ new Vector3(); const _normalMatrix = /*@__PURE__*/ new Matrix3(); @@ -12511,6 +12532,8 @@ class Plane { constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { + this.isPlane = true; + // normal is assumed to be normalized this.normal = normal; @@ -12702,12 +12725,10 @@ class Plane { } -Plane.prototype.isPlane = true; - const _sphere$2 = /*@__PURE__*/ new Sphere(); const _vector$7 = /*@__PURE__*/ new Vector3(); -class Frustum$1 { +class Frustum { constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) { @@ -13202,7 +13223,9 @@ var begin_vertex = "vec3 transformed = vec3( position );"; var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; -var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; +var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\nvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = mix(F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence);\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; + +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\nconst mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n);\nvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n vec3 sqrtF0 = sqrt( fresnel0 );\n return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n}\nvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n}\nfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n}\nvec3 evalSensitivity( float OPD, vec3 shift ) {\n float phase = 2.0 * PI * OPD * 1.0e-9;\n vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( -pow2( phase ) * var );\n xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[0] ) * exp( -4.5282e+09 * pow2( phase ) );\n xyz /= 1.0685e-7;\n vec3 srgb = XYZ_TO_REC709 * xyz;\n return srgb;\n}\nvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n vec3 I;\n float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n if ( cosTheta2Sq < 0.0 ) {\n return vec3( 1.0 );\n }\n float cosTheta2 = sqrt( cosTheta2Sq );\n float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n float R12 = F_Schlick( R0, 1.0, cosTheta1 );\n float R21 = R12;\n float T121 = 1.0 - R12;\n float phi12 = 0.0;\n if ( iridescenceIOR < outsideIOR ) phi12 = PI;\n float phi21 = PI - phi12;\n vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n vec3 phi23 = vec3( 0.0 );\n if ( baseIOR[0] < iridescenceIOR ) phi23[0] = PI;\n if ( baseIOR[1] < iridescenceIOR ) phi23[1] = PI;\n if ( baseIOR[2] < iridescenceIOR ) phi23[2] = PI;\n float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n vec3 phi = vec3( phi21 ) + phi23;\n vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n vec3 r123 = sqrt( R123 );\n vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n vec3 C0 = R12 + Rs;\n I = C0;\n vec3 Cm = Rs - T121;\n for ( int m = 1; m <= 2; ++m ) {\n Cm *= r123;\n vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n I += Cm * Sm;\n }\n return max( I, vec3( 0.0 ) );\n}\n#endif"; var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; @@ -13222,9 +13245,9 @@ var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\ var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; -var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; -var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 ) + 0.5;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; @@ -13278,11 +13301,11 @@ var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; -var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; -var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; -var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; +var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\nfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\nif ( material.iridescenceThickness == 0.0 ) {\n\tmaterial.iridescence = 0.0;\n} else {\n\tmaterial.iridescence = saturate( material.iridescence );\n}\nif ( material.iridescence > 0.0 ) {\n\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; @@ -13334,6 +13357,8 @@ var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 cle var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; @@ -13360,7 +13385,7 @@ var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; -var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif"; +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif"; var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; @@ -13438,7 +13463,7 @@ const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive; const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; -const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; @@ -13466,6 +13491,7 @@ const ShaderChunk = { begin_vertex: begin_vertex, beginnormal_vertex: beginnormal_vertex, bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, bumpmap_pars_fragment: bumpmap_pars_fragment, clipping_planes_fragment: clipping_planes_fragment, clipping_planes_pars_fragment: clipping_planes_pars_fragment, @@ -13531,6 +13557,7 @@ const ShaderChunk = { clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, output_fragment: output_fragment, packing: packing, premultiplied_alpha_fragment: premultiplied_alpha_fragment, @@ -13603,12 +13630,12 @@ const UniformsLib = { common: { - diffuse: { value: new Color( 0xffffff ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, map: { value: null }, - uvTransform: { value: new Matrix3() }, - uv2Transform: { value: new Matrix3() }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + uv2Transform: { value: /*@__PURE__*/ new Matrix3() }, alphaMap: { value: null }, alphaTest: { value: 0 } @@ -13661,7 +13688,7 @@ const UniformsLib = { normalmap: { normalMap: { value: null }, - normalScale: { value: new Vector2( 1, 1 ) } + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } }, @@ -13696,7 +13723,7 @@ const UniformsLib = { fogDensity: { value: 0.00025 }, fogNear: { value: 1 }, fogFar: { value: 2000 }, - fogColor: { value: new Color( 0xffffff ) } + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } }, @@ -13781,27 +13808,27 @@ const UniformsLib = { points: { - diffuse: { value: new Color( 0xffffff ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, size: { value: 1.0 }, scale: { value: 1.0 }, map: { value: null }, alphaMap: { value: null }, alphaTest: { value: 0 }, - uvTransform: { value: new Matrix3() } + uvTransform: { value: /*@__PURE__*/ new Matrix3() } }, sprite: { - diffuse: { value: new Color( 0xffffff ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, - center: { value: new Vector2( 0.5, 0.5 ) }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, rotation: { value: 0.0 }, map: { value: null }, alphaMap: { value: null }, alphaTest: { value: 0 }, - uvTransform: { value: new Matrix3() } + uvTransform: { value: /*@__PURE__*/ new Matrix3() } } @@ -13811,7 +13838,7 @@ const ShaderLib = { basic: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13827,7 +13854,7 @@ const ShaderLib = { lambert: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13837,7 +13864,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) } + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } } ] ), @@ -13848,7 +13875,7 @@ const ShaderLib = { phong: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13861,8 +13888,8 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) }, - specular: { value: new Color( 0x111111 ) }, + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, shininess: { value: 30 } } ] ), @@ -13874,7 +13901,7 @@ const ShaderLib = { standard: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, @@ -13888,7 +13915,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) }, + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, roughness: { value: 1.0 }, metalness: { value: 0.0 }, envMapIntensity: { value: 1 } // temporary @@ -13902,7 +13929,7 @@ const ShaderLib = { toon: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, @@ -13914,7 +13941,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) } + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } } ] ), @@ -13925,7 +13952,7 @@ const ShaderLib = { matcap: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, @@ -13943,7 +13970,7 @@ const ShaderLib = { points: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.points, UniformsLib.fog ] ), @@ -13955,7 +13982,7 @@ const ShaderLib = { dashed: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.fog, { @@ -13972,7 +13999,7 @@ const ShaderLib = { depth: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap ] ), @@ -13984,7 +14011,7 @@ const ShaderLib = { normal: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, @@ -14001,7 +14028,7 @@ const ShaderLib = { sprite: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.sprite, UniformsLib.fog ] ), @@ -14014,7 +14041,7 @@ const ShaderLib = { background: { uniforms: { - uvTransform: { value: new Matrix3() }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, t2D: { value: null }, }, @@ -14022,13 +14049,10 @@ const ShaderLib = { fragmentShader: ShaderChunk.background_frag }, - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ cube: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.envmap, { opacity: { value: 1.0 } @@ -14053,11 +14077,11 @@ const ShaderLib = { distanceRGBA: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap, { - referencePosition: { value: new Vector3() }, + referencePosition: { value: /*@__PURE__*/ new Vector3() }, nearDistance: { value: 1 }, farDistance: { value: 1000 } } @@ -14070,11 +14094,11 @@ const ShaderLib = { shadow: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.lights, UniformsLib.fog, { - color: { value: new Color( 0x00000 ) }, + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, opacity: { value: 1.0 } }, ] ), @@ -14088,31 +14112,37 @@ const ShaderLib = { ShaderLib.physical = { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ ShaderLib.standard.uniforms, { clearcoat: { value: 0 }, clearcoatMap: { value: null }, clearcoatRoughness: { value: 0 }, clearcoatRoughnessMap: { value: null }, - clearcoatNormalScale: { value: new Vector2( 1, 1 ) }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, clearcoatNormalMap: { value: null }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, sheen: { value: 0 }, - sheenColor: { value: new Color( 0x000000 ) }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, sheenColorMap: { value: null }, sheenRoughness: { value: 1 }, sheenRoughnessMap: { value: null }, transmission: { value: 0 }, transmissionMap: { value: null }, - transmissionSamplerSize: { value: new Vector2() }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, transmissionSamplerMap: { value: null }, thickness: { value: 0 }, thicknessMap: { value: null }, attenuationDistance: { value: 0 }, - attenuationColor: { value: new Color( 0x000000 ) }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, specularIntensity: { value: 1 }, specularIntensityMap: { value: null }, - specularColor: { value: new Color( 1, 1, 1 ) }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, specularColorMap: { value: null }, } ] ), @@ -14231,6 +14261,8 @@ function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipli } + boxMesh.layers.enableAll(); + // push to the pre-sorted opaque render list renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); @@ -14291,6 +14323,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipli } + planeMesh.layers.enableAll(); // push to the pre-sorted opaque render list renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); @@ -14364,9 +14397,9 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - updateBuffers = needsUpdate( geometry, index ); + updateBuffers = needsUpdate( object, geometry, program, index ); - if ( updateBuffers ) saveCache( geometry, index ); + if ( updateBuffers ) saveCache( object, geometry, program, index ); } else { @@ -14386,12 +14419,6 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - if ( object.isInstancedMesh === true ) { - - updateBuffers = true; - - } - if ( index !== null ) { attributes.update( index, 34963 ); @@ -14505,25 +14532,40 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - function needsUpdate( geometry, index ) { + function needsUpdate( object, geometry, program, index ) { const cachedAttributes = currentState.attributes; const geometryAttributes = geometry.attributes; let attributesNum = 0; - for ( const key in geometryAttributes ) { + const programAttributes = program.getAttributes(); - const cachedAttribute = cachedAttributes[ key ]; - const geometryAttribute = geometryAttributes[ key ]; + for ( const name in programAttributes ) { - if ( cachedAttribute === undefined ) return true; + const programAttribute = programAttributes[ name ]; - if ( cachedAttribute.attribute !== geometryAttribute ) return true; + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { - if ( cachedAttribute.data !== geometryAttribute.data ) return true; + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; - attributesNum ++; + } + + if ( cachedAttribute === undefined ) return true; + + if ( cachedAttribute.attribute !== geometryAttribute ) return true; + + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; + + attributesNum ++; + + } } @@ -14535,28 +14577,43 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - function saveCache( geometry, index ) { + function saveCache( object, geometry, program, index ) { const cache = {}; const attributes = geometry.attributes; let attributesNum = 0; - for ( const key in attributes ) { + const programAttributes = program.getAttributes(); - const attribute = attributes[ key ]; + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; - const data = {}; - data.attribute = attribute; + if ( programAttribute.location >= 0 ) { - if ( attribute.data ) { + let attribute = attributes[ name ]; - data.data = attribute.data; + if ( attribute === undefined ) { - } + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; + + } - cache[ key ] = data; + const data = {}; + data.attribute = attribute; - attributesNum ++; + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } } @@ -15374,6 +15431,8 @@ class OrthographicCamera extends Camera { super(); + this.isOrthographicCamera = true; + this.type = 'OrthographicCamera'; this.zoom = 1; @@ -15499,8 +15558,6 @@ class OrthographicCamera extends Camera { } -OrthographicCamera.prototype.isOrthographicCamera = true; - const LOD_MIN = 4; // The standard deviations (radians) associated with the extra mips. These are @@ -15513,7 +15570,7 @@ const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; // samples and exit early, but not recompile the shader. const MAX_SAMPLES = 20; -const _flatCamera$1 = /*@__PURE__*/ new OrthographicCamera(); +const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); const _clearColor = /*@__PURE__*/ new Color(); let _oldTarget = null; @@ -15725,7 +15782,7 @@ class PMREMGenerator { _allocateTargets() { const width = 3 * Math.max( this._cubeSize, 16 * 7 ); - const height = 4 * this._cubeSize - 32; + const height = 4 * this._cubeSize; const params = { magFilter: LinearFilter, @@ -15763,7 +15820,7 @@ class PMREMGenerator { _compileMaterial( material ) { const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); - this._renderer.compile( tmpMesh, _flatCamera$1 ); + this._renderer.compile( tmpMesh, _flatCamera ); } @@ -15896,7 +15953,7 @@ class PMREMGenerator { _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); renderer.setRenderTarget( cubeUVRenderTarget ); - renderer.render( mesh, _flatCamera$1 ); + renderer.render( mesh, _flatCamera ); } @@ -16030,7 +16087,7 @@ class PMREMGenerator { _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); renderer.setRenderTarget( targetOut ); - renderer.render( blurMesh, _flatCamera$1 ); + renderer.render( blurMesh, _flatCamera ); } @@ -16066,9 +16123,9 @@ function _createPlanes( lodMax ) { sigmas.push( sigma ); - const texelSize = 1.0 / ( sizeLod - 1 ); - const min = - texelSize / 2; - const max = 1 + texelSize / 2; + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; const cubeFaces = 6; @@ -16942,6 +16999,8 @@ function denormalize( morph, attribute ) { const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array; if ( array instanceof Int8Array ) denominator = 127; + else if ( array instanceof Uint8Array ) denominator = 255; + else if ( array instanceof Uint16Array ) denominator = 65535; else if ( array instanceof Int16Array ) denominator = 32767; else if ( array instanceof Int32Array ) denominator = 2147483647; else console.error( 'THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array ); @@ -17350,10 +17409,10 @@ function WebGLObjects( gl, geometries, attributes, info ) { * */ -const emptyTexture = new Texture(); -const emptyArrayTexture = new DataArrayTexture(); -const empty3dTexture = new Data3DTexture(); -const emptyCubeTexture = new CubeTexture(); +const emptyTexture = /*@__PURE__*/ new Texture(); +const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); +const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); +const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); // --- Utilities --- @@ -17370,7 +17429,7 @@ const mat2array = new Float32Array( 4 ); // Flattening for arrays of vectors and matrices -function flatten$1( array, nBlocks, blockSize ) { +function flatten( array, nBlocks, blockSize ) { const firstElem = array[ 0 ]; @@ -17405,7 +17464,7 @@ function flatten$1( array, nBlocks, blockSize ) { } -function arraysEqual$1( a, b ) { +function arraysEqual( a, b ) { if ( a.length !== b.length ) return false; @@ -17419,7 +17478,7 @@ function arraysEqual$1( a, b ) { } -function copyArray$2( a, b ) { +function copyArray( a, b ) { for ( let i = 0, l = b.length; i < l; i ++ ) { @@ -17490,11 +17549,11 @@ function setValueV2f( gl, v ) { } else { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform2fv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17530,11 +17589,11 @@ function setValueV3f( gl, v ) { } else { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform3fv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17559,11 +17618,11 @@ function setValueV4f( gl, v ) { } else { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform4fv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17578,21 +17637,21 @@ function setValueM2( gl, v ) { if ( elements === undefined ) { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniformMatrix2fv( this.addr, false, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } else { - if ( arraysEqual$1( cache, elements ) ) return; + if ( arraysEqual( cache, elements ) ) return; mat2array.set( elements ); gl.uniformMatrix2fv( this.addr, false, mat2array ); - copyArray$2( cache, elements ); + copyArray( cache, elements ); } @@ -17605,21 +17664,21 @@ function setValueM3( gl, v ) { if ( elements === undefined ) { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniformMatrix3fv( this.addr, false, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } else { - if ( arraysEqual$1( cache, elements ) ) return; + if ( arraysEqual( cache, elements ) ) return; mat3array.set( elements ); gl.uniformMatrix3fv( this.addr, false, mat3array ); - copyArray$2( cache, elements ); + copyArray( cache, elements ); } @@ -17632,21 +17691,21 @@ function setValueM4( gl, v ) { if ( elements === undefined ) { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniformMatrix4fv( this.addr, false, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } else { - if ( arraysEqual$1( cache, elements ) ) return; + if ( arraysEqual( cache, elements ) ) return; mat4array.set( elements ); gl.uniformMatrix4fv( this.addr, false, mat4array ); - copyArray$2( cache, elements ); + copyArray( cache, elements ); } @@ -17672,11 +17731,11 @@ function setValueV2i( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform2iv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17684,11 +17743,11 @@ function setValueV3i( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform3iv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17696,11 +17755,11 @@ function setValueV4i( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform4iv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17724,11 +17783,11 @@ function setValueV2ui( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform2uiv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17736,11 +17795,11 @@ function setValueV3ui( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform3uiv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17748,11 +17807,11 @@ function setValueV4ui( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform4uiv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17889,7 +17948,7 @@ function setValueV1fArray( gl, v ) { function setValueV2fArray( gl, v ) { - const data = flatten$1( v, this.size, 2 ); + const data = flatten( v, this.size, 2 ); gl.uniform2fv( this.addr, data ); @@ -17897,7 +17956,7 @@ function setValueV2fArray( gl, v ) { function setValueV3fArray( gl, v ) { - const data = flatten$1( v, this.size, 3 ); + const data = flatten( v, this.size, 3 ); gl.uniform3fv( this.addr, data ); @@ -17905,7 +17964,7 @@ function setValueV3fArray( gl, v ) { function setValueV4fArray( gl, v ) { - const data = flatten$1( v, this.size, 4 ); + const data = flatten( v, this.size, 4 ); gl.uniform4fv( this.addr, data ); @@ -17915,7 +17974,7 @@ function setValueV4fArray( gl, v ) { function setValueM2Array( gl, v ) { - const data = flatten$1( v, this.size, 4 ); + const data = flatten( v, this.size, 4 ); gl.uniformMatrix2fv( this.addr, false, data ); @@ -17923,7 +17982,7 @@ function setValueM2Array( gl, v ) { function setValueM3Array( gl, v ) { - const data = flatten$1( v, this.size, 9 ); + const data = flatten( v, this.size, 9 ); gl.uniformMatrix3fv( this.addr, false, data ); @@ -17931,7 +17990,7 @@ function setValueM3Array( gl, v ) { function setValueM4Array( gl, v ) { - const data = flatten$1( v, this.size, 16 ); + const data = flatten( v, this.size, 16 ); gl.uniformMatrix4fv( this.addr, false, data ); @@ -18116,64 +18175,62 @@ function getPureArraySetter( type ) { // --- Uniform Classes --- -function SingleUniform( id, activeInfo, addr ) { +class SingleUniform { - this.id = id; - this.addr = addr; - this.cache = []; - this.setValue = getSingularSetter( activeInfo.type ); + constructor( id, activeInfo, addr ) { - // this.path = activeInfo.name; // DEBUG + this.id = id; + this.addr = addr; + this.cache = []; + this.setValue = getSingularSetter( activeInfo.type ); -} - -function PureArrayUniform( id, activeInfo, addr ) { + // this.path = activeInfo.name; // DEBUG - this.id = id; - this.addr = addr; - this.cache = []; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); - - // this.path = activeInfo.name; // DEBUG + } } -PureArrayUniform.prototype.updateCache = function ( data ) { +class PureArrayUniform { - const cache = this.cache; + constructor( id, activeInfo, addr ) { - if ( data instanceof Float32Array && cache.length !== data.length ) { + this.id = id; + this.addr = addr; + this.cache = []; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - this.cache = new Float32Array( data.length ); + // this.path = activeInfo.name; // DEBUG } - copyArray$2( cache, data ); +} -}; +class StructuredUniform { -function StructuredUniform( id ) { + constructor( id ) { - this.id = id; + this.id = id; - this.seq = []; - this.map = {}; + this.seq = []; + this.map = {}; -} + } + + setValue( gl, value, textures ) { -StructuredUniform.prototype.setValue = function ( gl, value, textures ) { + const seq = this.seq; - const seq = this.seq; + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); - const u = seq[ i ]; - u.setValue( gl, value[ u.id ], textures ); + } } -}; +} // --- Top-level --- @@ -18250,75 +18307,76 @@ function parseUniform( activeInfo, addr, container ) { // Root Container -function WebGLUniforms( gl, program ) { +class WebGLUniforms { - this.seq = []; - this.map = {}; + constructor( gl, program ) { - const n = gl.getProgramParameter( program, 35718 ); + this.seq = []; + this.map = {}; - for ( let i = 0; i < n; ++ i ) { + const n = gl.getProgramParameter( program, 35718 ); - const info = gl.getActiveUniform( program, i ), - addr = gl.getUniformLocation( program, info.name ); + for ( let i = 0; i < n; ++ i ) { - parseUniform( info, addr, this ); + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); - } + parseUniform( info, addr, this ); -} + } -WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) { + } - const u = this.map[ name ]; + setValue( gl, name, value, textures ) { - if ( u !== undefined ) u.setValue( gl, value, textures ); + const u = this.map[ name ]; -}; + if ( u !== undefined ) u.setValue( gl, value, textures ); -WebGLUniforms.prototype.setOptional = function ( gl, object, name ) { + } - const v = object[ name ]; + setOptional( gl, object, name ) { - if ( v !== undefined ) this.setValue( gl, name, v ); + const v = object[ name ]; -}; + if ( v !== undefined ) this.setValue( gl, name, v ); + } -// Static interface + static upload( gl, seq, values, textures ) { -WebGLUniforms.upload = function ( gl, seq, values, textures ) { + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + const u = seq[ i ], + v = values[ u.id ]; - const u = seq[ i ], - v = values[ u.id ]; + if ( v.needsUpdate !== false ) { - if ( v.needsUpdate !== false ) { + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); - // note: always updating when .needsUpdate is undefined - u.setValue( gl, v.value, textures ); + } } } -}; + static seqWithValue( seq, values ) { + + const r = []; -WebGLUniforms.seqWithValue = function ( seq, values ) { + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - const r = []; + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + } - const u = seq[ i ]; - if ( u.id in values ) r.push( u ); + return r; } - return r; - -}; +} function WebGLShader( gl, type, string ) { @@ -18343,7 +18401,8 @@ function handleSource( string, errorLine ) { for ( let i = from; i < to; i ++ ) { - lines2.push( ( i + 1 ) + ': ' + lines[ i ] ); + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); } @@ -18374,12 +18433,20 @@ function getShaderErrors( gl, shader, type ) { if ( status && errors === '' ) return ''; - const errorLine = parseInt( /ERROR: 0:(\d+)/.exec( errors )[ 1 ] ); + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { - // --enable-privileged-webgl-extension - // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + + } else { + + return errors; + + } } @@ -18701,7 +18768,7 @@ function generateCubeUVSize( parameters ) { if ( imageHeight === null ) return null; - const maxMip = Math.log2( imageHeight / 32 + 1 ) + 3; + const maxMip = Math.log2( imageHeight ) - 2; const texelHeight = 1.0 / imageHeight; @@ -18780,7 +18847,6 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - '#define MAX_BONES ' + parameters.maxBones, ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', @@ -18799,6 +18865,9 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', @@ -18825,7 +18894,6 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', @@ -18955,6 +19023,10 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', @@ -19011,7 +19083,7 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ), - parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n' @@ -19345,8 +19417,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities const isWebGL2 = capabilities.isWebGL2; const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; - const floatVertexTextures = capabilities.floatVertexTextures; - const maxVertexUniforms = capabilities.maxVertexUniforms; const vertexTextures = capabilities.vertexTextures; let precision = capabilities.precision; @@ -19368,42 +19438,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities SpriteMaterial: 'sprite' }; - function getMaxBones( object ) { - - const skeleton = object.skeleton; - const bones = skeleton.bones; - - if ( floatVertexTextures ) { - - return 1024; - - } else { - - // default for when object is not specified - // ( for example when prebuilding shader to be used with multiple objects ) - // - // - leave some extra space for other uniforms - // - limit here is ANGLE's 254 max uniform vectors - // (up to 54 should be safe) - - const nVertexUniforms = maxVertexUniforms; - const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - - const maxBones = Math.min( nVertexMatrices, bones.length ); - - if ( maxBones < bones.length ) { - - console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' ); - return 0; - - } - - return maxBones; - - } - - } - function getParameters( material, lights, shadows, scene, object ) { const fog = scene.fog; @@ -19418,8 +19452,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities // heuristics to create shader parameters according to lights in the scene // (not to blow over maxLights budget) - const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0; - if ( material.precision !== null ) { precision = capabilities.getMaxPrecision( material.precision ); @@ -19471,6 +19503,7 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities const useAlphaTest = material.alphaTest > 0; const useClearcoat = material.clearcoat > 0; + const useIridescence = material.iridescence > 0; const parameters = { @@ -19516,6 +19549,10 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap, clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap, + iridescence: useIridescence, + iridescenceMap: useIridescence && !! material.iridescenceMap, + iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap, + displacementMap: !! material.displacementMap, roughnessMap: !! material.roughnessMap, metalnessMap: !! material.metalnessMap, @@ -19543,11 +19580,11 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ), vertexColors: material.vertexColors, vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, - vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap, - uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap, + vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap, + uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap, fog: !! fog, - useFog: material.fog, + useFog: material.fog === true, fogExp2: ( fog && fog.isFogExp2 ), flatShading: !! material.flatShading, @@ -19555,9 +19592,7 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities sizeAttenuation: material.sizeAttenuation, logarithmicDepthBuffer: logarithmicDepthBuffer, - skinning: object.isSkinnedMesh === true && maxBones > 0, - maxBones: maxBones, - useVertexTexture: floatVertexTextures, + skinning: object.isSkinnedMesh === true, morphTargets: geometry.morphAttributes.position !== undefined, morphNormals: geometry.morphAttributes.normal !== undefined, @@ -19591,7 +19626,8 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities doubleSided: material.side === DoubleSide, flipSided: material.side === BackSide, - depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false, + useDepthPacking: !! material.depthPacking, + depthPacking: material.depthPacking || 0, index0AttributeName: material.index0AttributeName, @@ -19662,7 +19698,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities array.push( parameters.vertexUvs ); array.push( parameters.fogExp2 ); array.push( parameters.sizeAttenuation ); - array.push( parameters.maxBones ); array.push( parameters.morphTargetsCount ); array.push( parameters.morphAttributeCount ); array.push( parameters.numDirLights ); @@ -19677,6 +19712,7 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities array.push( parameters.toneMapping ); array.push( parameters.numClippingPlanes ); array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); } @@ -19720,32 +19756,38 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities _programLayers.enable( 16 ); if ( parameters.clearcoatNormalMap ) _programLayers.enable( 17 ); - if ( parameters.displacementMap ) + if ( parameters.iridescence ) _programLayers.enable( 18 ); - if ( parameters.specularMap ) + if ( parameters.iridescenceMap ) _programLayers.enable( 19 ); - if ( parameters.roughnessMap ) + if ( parameters.iridescenceThicknessMap ) _programLayers.enable( 20 ); - if ( parameters.metalnessMap ) + if ( parameters.displacementMap ) _programLayers.enable( 21 ); - if ( parameters.gradientMap ) + if ( parameters.specularMap ) _programLayers.enable( 22 ); - if ( parameters.alphaMap ) + if ( parameters.roughnessMap ) _programLayers.enable( 23 ); - if ( parameters.alphaTest ) + if ( parameters.metalnessMap ) _programLayers.enable( 24 ); - if ( parameters.vertexColors ) + if ( parameters.gradientMap ) _programLayers.enable( 25 ); - if ( parameters.vertexAlphas ) + if ( parameters.alphaMap ) _programLayers.enable( 26 ); - if ( parameters.vertexUvs ) + if ( parameters.alphaTest ) _programLayers.enable( 27 ); - if ( parameters.vertexTangents ) + if ( parameters.vertexColors ) _programLayers.enable( 28 ); - if ( parameters.uvsVertexOnly ) + if ( parameters.vertexAlphas ) _programLayers.enable( 29 ); - if ( parameters.fog ) + if ( parameters.vertexUvs ) _programLayers.enable( 30 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 31 ); + if ( parameters.uvsVertexOnly ) + _programLayers.enable( 32 ); + if ( parameters.fog ) + _programLayers.enable( 33 ); array.push( _programLayers.mask ); _programLayers.disableAll(); @@ -19758,48 +19800,46 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities _programLayers.enable( 2 ); if ( parameters.skinning ) _programLayers.enable( 3 ); - if ( parameters.useVertexTexture ) - _programLayers.enable( 4 ); if ( parameters.morphTargets ) - _programLayers.enable( 5 ); + _programLayers.enable( 4 ); if ( parameters.morphNormals ) - _programLayers.enable( 6 ); + _programLayers.enable( 5 ); if ( parameters.morphColors ) - _programLayers.enable( 7 ); + _programLayers.enable( 6 ); if ( parameters.premultipliedAlpha ) - _programLayers.enable( 8 ); + _programLayers.enable( 7 ); if ( parameters.shadowMapEnabled ) - _programLayers.enable( 9 ); + _programLayers.enable( 8 ); if ( parameters.physicallyCorrectLights ) - _programLayers.enable( 10 ); + _programLayers.enable( 9 ); if ( parameters.doubleSided ) - _programLayers.enable( 11 ); + _programLayers.enable( 10 ); if ( parameters.flipSided ) + _programLayers.enable( 11 ); + if ( parameters.useDepthPacking ) _programLayers.enable( 12 ); - if ( parameters.depthPacking ) - _programLayers.enable( 13 ); if ( parameters.dithering ) - _programLayers.enable( 14 ); + _programLayers.enable( 13 ); if ( parameters.specularIntensityMap ) - _programLayers.enable( 15 ); + _programLayers.enable( 14 ); if ( parameters.specularColorMap ) - _programLayers.enable( 16 ); + _programLayers.enable( 15 ); if ( parameters.transmission ) - _programLayers.enable( 17 ); + _programLayers.enable( 16 ); if ( parameters.transmissionMap ) - _programLayers.enable( 18 ); + _programLayers.enable( 17 ); if ( parameters.thicknessMap ) - _programLayers.enable( 19 ); + _programLayers.enable( 18 ); if ( parameters.sheen ) - _programLayers.enable( 20 ); + _programLayers.enable( 19 ); if ( parameters.sheenColorMap ) - _programLayers.enable( 21 ); + _programLayers.enable( 20 ); if ( parameters.sheenRoughnessMap ) - _programLayers.enable( 22 ); + _programLayers.enable( 21 ); if ( parameters.decodeVideoTexture ) - _programLayers.enable( 23 ); + _programLayers.enable( 22 ); if ( parameters.opaque ) - _programLayers.enable( 24 ); + _programLayers.enable( 23 ); array.push( _programLayers.mask ); @@ -20704,7 +20744,6 @@ function WebGLLights( extensions, capabilities ) { uniforms.direction.setFromMatrixPosition( light.matrixWorld ); uniforms.direction.transformDirection( viewMatrix ); - uniforms.direction.normalize(); hemiLength ++; @@ -20830,6 +20869,8 @@ class MeshDepthMaterial extends Material { super(); + this.isMeshDepthMaterial = true; + this.type = 'MeshDepthMaterial'; this.depthPacking = BasicDepthPacking; @@ -20845,8 +20886,6 @@ class MeshDepthMaterial extends Material { this.wireframe = false; this.wireframeLinewidth = 1; - this.fog = false; - this.setValues( parameters ); } @@ -20874,14 +20913,14 @@ class MeshDepthMaterial extends Material { } -MeshDepthMaterial.prototype.isMeshDepthMaterial = true; - class MeshDistanceMaterial extends Material { constructor( parameters ) { super(); + this.isMeshDistanceMaterial = true; + this.type = 'MeshDistanceMaterial'; this.referencePosition = new Vector3(); @@ -20896,8 +20935,6 @@ class MeshDistanceMaterial extends Material { this.displacementScale = 1; this.displacementBias = 0; - this.fog = false; - this.setValues( parameters ); } @@ -20924,15 +20961,13 @@ class MeshDistanceMaterial extends Material { } -MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true; - const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; function WebGLShadowMap( _renderer, _objects, _capabilities ) { - let _frustum = new Frustum$1(); + let _frustum = new Frustum(); const _shadowMapSize = new Vector2(), _viewportSize = new Vector2(), @@ -21049,20 +21084,9 @@ function WebGLShadowMap( _renderer, _objects, _capabilities ) { } - if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { - - shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); - shadow.map.texture.name = light.name + '.shadowMap'; - - shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); - - shadow.camera.updateProjectionMatrix(); - - } - if ( shadow.map === null ) { - const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; + const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); shadow.map.texture.name = light.name + '.shadowMap'; @@ -21099,7 +21123,7 @@ function WebGLShadowMap( _renderer, _objects, _capabilities ) { // do blur pass for VSM - if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { VSMPass( shadow, camera ); @@ -21129,6 +21153,12 @@ function WebGLShadowMap( _renderer, _objects, _capabilities ) { } + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + + } + // vertical pass shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; @@ -21165,7 +21195,7 @@ function WebGLShadowMap( _renderer, _objects, _capabilities ) { } - if ( ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) || + if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || ( material.displacementMap && material.displacementScale !== 0 ) || ( material.alphaMap && material.alphaTest > 0 ) ) { @@ -22838,7 +22868,17 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); - if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer ); + + if ( renderTargetProperties.__webglColorRenderbuffer ) { + + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { + + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + } + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); } @@ -23192,7 +23232,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, const mipmaps = texture.mipmaps; const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); - const allocateMemory = ( textureProperties.__version === undefined ); + const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true ); const levels = getMipLevels( texture, image, supportsMips ); if ( texture.isDepthTexture ) { @@ -23242,7 +23282,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); - texture.type = UnsignedShortType; + texture.type = UnsignedIntType; glType = utils.convert( texture.type ); } @@ -23271,13 +23311,17 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, // - if ( useTexStorage && allocateMemory ) { + if ( allocateMemory ) { - state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height ); + if ( useTexStorage ) { - } else { + state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height ); + + } else { + + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + } } @@ -23419,13 +23463,26 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } else if ( texture.isFramebufferTexture ) { - if ( useTexStorage && allocateMemory ) { + if ( allocateMemory ) { - state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); + if ( useTexStorage ) { - } else { + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + } else { + + let width = image.width, height = image.height; + + for ( let i = 0; i < levels; i ++ ) { + + state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null ); + + width >>= 1; + height >>= 1; + + } + + } } @@ -23546,7 +23603,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); - const allocateMemory = ( textureProperties.__version === undefined ); + const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true ); let levels = getMipLevels( texture, image, supportsMips ); setTextureParameters( 34067, texture, supportsMips ); @@ -23816,25 +23873,30 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } else { - // Use the first texture for MRT so far - const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture; + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; - const glFormat = utils.convert( texture.format, texture.encoding ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); - const samples = getRenderTargetSamples( renderTarget ); + for ( let i = 0; i < textures.length; i ++ ) { - if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + const texture = textures[ i ]; - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); - } else if ( useMultisampledRTT( renderTarget ) ) { + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { - multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - } else { + } else if ( useMultisampledRTT( renderTarget ) ) { - _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + + } } @@ -24034,21 +24096,34 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } - } else if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + } - renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); - renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer(); + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer ); + const textures = isMultipleRenderTargets ? texture : [ texture ]; - const glFormat = utils.convert( texture.format, texture.encoding ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); - const samples = getRenderTargetSamples( renderTarget ); - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); - _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); + + _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + _gl.bindRenderbuffer( 36161, null ); if ( renderTarget.depthBuffer ) { @@ -24179,47 +24254,103 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; const width = renderTarget.width; const height = renderTarget.height; let mask = 16384; - const invalidationArray = [ 36064 ]; + const invalidationArray = []; const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); - if ( renderTarget.depthBuffer ) { - - invalidationArray.push( depthStyle ); + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { - } + for ( let i = 0; i < textures.length; i ++ ) { - const renderTargetProperties = properties.get( renderTarget ); - const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null ); - if ( ignoreDepthValues === false ) { + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 ); - if ( renderTarget.depthBuffer ) mask |= 256; - if ( renderTarget.stencilBuffer ) mask |= 1024; + } } state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); - if ( ignoreDepthValues === true ) { + for ( let i = 0; i < textures.length; i ++ ) { - _gl.invalidateFramebuffer( 36008, [ depthStyle ] ); - _gl.invalidateFramebuffer( 36009, [ depthStyle ] ); + invalidationArray.push( 36064 + i ); - } + if ( renderTarget.depthBuffer ) { + + invalidationArray.push( depthStyle ); + + } + + const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; + + if ( ignoreDepthValues === false ) { + + if ( renderTarget.depthBuffer ) mask |= 256; + if ( renderTarget.stencilBuffer ) mask |= 1024; + + } + + if ( isMultipleRenderTargets ) { + + _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + if ( ignoreDepthValues === true ) { + + _gl.invalidateFramebuffer( 36008, [ depthStyle ] ); + _gl.invalidateFramebuffer( 36009, [ depthStyle ] ); + + } + + if ( isMultipleRenderTargets ) { + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 ); - _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); + } + + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); + + if ( supportsInvalidateFramebuffer ) { - if ( supportsInvalidateFramebuffer ) { + _gl.invalidateFramebuffer( 36008, invalidationArray ); + + } - _gl.invalidateFramebuffer( 36008, invalidationArray ); } state.bindFramebuffer( 36008, null ); + state.bindFramebuffer( 36009, null ); + + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 ); + + } + + } + state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer ); } @@ -24583,6 +24714,10 @@ function WebGLUtils( gl, extensions, capabilities ) { } + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) + + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; + } return { convert: convert }; @@ -24595,28 +24730,28 @@ class ArrayCamera extends PerspectiveCamera { super(); + this.isArrayCamera = true; + this.cameras = array; } } -ArrayCamera.prototype.isArrayCamera = true; - class Group extends Object3D { constructor() { super(); + this.isGroup = true; + this.type = 'Group'; } } -Group.prototype.isGroup = true; - const _moveEvent = { type: 'move' }; class WebXRController { @@ -24744,43 +24879,6 @@ class WebXRController { if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { - if ( targetRay !== null ) { - - inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); - - if ( inputPose !== null ) { - - targetRay.matrix.fromArray( inputPose.transform.matrix ); - targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); - - if ( inputPose.linearVelocity ) { - - targetRay.hasLinearVelocity = true; - targetRay.linearVelocity.copy( inputPose.linearVelocity ); - - } else { - - targetRay.hasLinearVelocity = false; - - } - - if ( inputPose.angularVelocity ) { - - targetRay.hasAngularVelocity = true; - targetRay.angularVelocity.copy( inputPose.angularVelocity ); - - } else { - - targetRay.hasAngularVelocity = false; - - } - - this.dispatchEvent( _moveEvent ); - - } - - } - if ( hand && inputSource.hand ) { handPose = true; @@ -24885,6 +24983,51 @@ class WebXRController { } + if ( targetRay !== null ) { + + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + + // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it + if ( inputPose === null && gripPose !== null ) { + + inputPose = gripPose; + + } + + if ( inputPose !== null ) { + + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); + + if ( inputPose.linearVelocity ) { + + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy( inputPose.linearVelocity ); + + } else { + + targetRay.hasLinearVelocity = false; + + } + + if ( inputPose.angularVelocity ) { + + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy( inputPose.angularVelocity ); + + } else { + + targetRay.hasAngularVelocity = false; + + } + + this.dispatchEvent( _moveEvent ); + + } + + } + + } if ( targetRay !== null ) { @@ -24923,26 +25066,26 @@ class DepthTexture extends Texture { } - if ( type === undefined && format === DepthFormat ) type = UnsignedShortType; + if ( type === undefined && format === DepthFormat ) type = UnsignedIntType; if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.isDepthTexture = true; + this.image = { width: width, height: height }; this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; this.flipY = false; - this.generateMipmaps = false; + this.generateMipmaps = false; } } -DepthTexture.prototype.isDepthTexture = true; - class WebXRManager extends EventDispatcher { constructor( renderer, gl ) { @@ -24956,6 +25099,7 @@ class WebXRManager extends EventDispatcher { let referenceSpace = null; let referenceSpaceType = 'local-floor'; + let customReferenceSpace = null; let pose = null; let glBinding = null; @@ -24967,7 +25111,7 @@ class WebXRManager extends EventDispatcher { let newRenderTarget = null; const controllers = []; - const inputSourcesMap = new Map(); + const controllerInputSources = []; // @@ -25044,9 +25188,17 @@ class WebXRManager extends EventDispatcher { function onSessionEvent( event ) { - const controller = inputSourcesMap.get( event.inputSource ); + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); + + if ( controllerIndex === - 1 ) { + + return; + + } + + const controller = controllers[ controllerIndex ]; - if ( controller ) { + if ( controller !== undefined ) { controller.dispatchEvent( { type: event.type, data: event.inputSource } ); @@ -25056,13 +25208,26 @@ class WebXRManager extends EventDispatcher { function onSessionEnd() { - inputSourcesMap.forEach( function ( controller, inputSource ) { + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); - controller.disconnect( inputSource ); + for ( let i = 0; i < controllers.length; i ++ ) { - } ); + const inputSource = controllerInputSources[ i ]; + + if ( inputSource === null ) continue; + + controllerInputSources[ i ] = null; - inputSourcesMap.clear(); + controllers[ i ].disconnect( inputSource ); + + } _currentDepthNear = null; _currentDepthFar = null; @@ -25113,7 +25278,13 @@ class WebXRManager extends EventDispatcher { this.getReferenceSpace = function () { - return referenceSpace; + return customReferenceSpace || referenceSpace; + + }; + + this.setReferenceSpace = function ( space ) { + + customReferenceSpace = space; }; @@ -25198,12 +25369,12 @@ class WebXRManager extends EventDispatcher { glDepthFormat = attributes.stencil ? 35056 : 33190; depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; - depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; } const projectionlayerInit = { - colorFormat: ( renderer.outputEncoding === sRGBEncoding ) ? 35907 : 32856, + colorFormat: 32856, depthFormat: glDepthFormat, scaleFactor: framebufferScaleFactor }; @@ -25236,6 +25407,7 @@ class WebXRManager extends EventDispatcher { // Set foveation to maximum. this.setFoveation( 1.0 ); + customReferenceSpace = null; referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); animation.setContext( session ); @@ -25251,27 +25423,17 @@ class WebXRManager extends EventDispatcher { function onInputSourcesChange( event ) { - const inputSources = session.inputSources; - - // Assign inputSources to available controllers - - for ( let i = 0; i < controllers.length; i ++ ) { - - inputSourcesMap.set( inputSources[ i ], controllers[ i ] ); - - } - // Notify disconnected for ( let i = 0; i < event.removed.length; i ++ ) { const inputSource = event.removed[ i ]; - const controller = inputSourcesMap.get( inputSource ); + const index = controllerInputSources.indexOf( inputSource ); - if ( controller ) { + if ( index >= 0 ) { - controller.dispatchEvent( { type: 'disconnected', data: inputSource } ); - inputSourcesMap.delete( inputSource ); + controllerInputSources[ index ] = null; + controllers[ index ].dispatchEvent( { type: 'disconnected', data: inputSource } ); } @@ -25282,7 +25444,38 @@ class WebXRManager extends EventDispatcher { for ( let i = 0; i < event.added.length; i ++ ) { const inputSource = event.added[ i ]; - const controller = inputSourcesMap.get( inputSource ); + + let controllerIndex = controllerInputSources.indexOf( inputSource ); + + if ( controllerIndex === - 1 ) { + + // Assign input source a controller that currently has no input source + + for ( let i = 0; i < controllers.length; i ++ ) { + + if ( i >= controllerInputSources.length ) { + + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + + } else if ( controllerInputSources[ i ] === null ) { + + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; + + } + + } + + // If all controllers do currently receive input we ignore new ones + + if ( controllerIndex === - 1 ) break; + + } + + const controller = controllers[ controllerIndex ]; if ( controller ) { @@ -25485,7 +25678,7 @@ class WebXRManager extends EventDispatcher { function onAnimationFrame( time, frame ) { - pose = frame.getViewerPose( referenceSpace ); + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); xrFrame = frame; if ( pose !== null ) { @@ -25539,7 +25732,16 @@ class WebXRManager extends EventDispatcher { } - const camera = cameras[ i ]; + let camera = cameras[ i ]; + + if ( camera === undefined ) { + + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; + + } camera.matrix.fromArray( view.transform.matrix ); camera.projectionMatrix.fromArray( view.projectionMatrix ); @@ -25563,14 +25765,16 @@ class WebXRManager extends EventDispatcher { // - const inputSources = session.inputSources; - for ( let i = 0; i < controllers.length; i ++ ) { + const inputSource = controllerInputSources[ i ]; const controller = controllers[ i ]; - const inputSource = inputSources[ i ]; - controller.update( inputSource, frame, referenceSpace ); + if ( inputSource !== null && controller !== undefined ) { + + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); + + } } @@ -25810,10 +26014,12 @@ function WebGLMaterials( renderer, properties ) { // 10. clearcoat map // 11. clearcoat normal map // 12. clearcoat roughnessMap map - // 13. specular intensity map - // 14. specular tint map - // 15. transmission map - // 16. thickness map + // 13. iridescence map + // 14. iridescence thickness map + // 15. specular intensity map + // 16. specular tint map + // 17. transmission map + // 18. thickness map let uvScaleMap; @@ -25865,6 +26071,14 @@ function WebGLMaterials( renderer, properties ) { uvScaleMap = material.clearcoatRoughnessMap; + } else if ( material.iridescenceMap ) { + + uvScaleMap = material.iridescenceMap; + + } else if ( material.iridescenceThicknessMap ) { + + uvScaleMap = material.iridescenceThicknessMap; + } else if ( material.specularIntensityMap ) { uvScaleMap = material.specularIntensityMap; @@ -26172,6 +26386,27 @@ function WebGLMaterials( renderer, properties ) { } + if ( material.iridescence > 0 ) { + + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; + + if ( material.iridescenceMap ) { + + uniforms.iridescenceMap.value = material.iridescenceMap; + + } + + if ( material.iridescenceThicknessMap ) { + + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + + } + + } + if ( material.transmission > 0 ) { uniforms.transmission.value = material.transmission; @@ -26249,6 +26484,8 @@ function createCanvasElement() { function WebGLRenderer( parameters = {} ) { + this.isWebGLRenderer = true; + const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), _context = parameters.context !== undefined ? parameters.context : null, @@ -26262,7 +26499,7 @@ function WebGLRenderer( parameters = {} ) { let _alpha; - if ( parameters.context !== undefined ) { + if ( _context !== null ) { _alpha = _context.getContextAttributes().alpha; @@ -26324,6 +26561,28 @@ function WebGLRenderer( parameters = {} ) { this.toneMapping = NoToneMapping; this.toneMappingExposure = 1.0; + // + + Object.defineProperties( this, { + + // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d + + gammaFactor: { + get: function () { + + console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); + return 2; + + }, + set: function () { + + console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); + + } + } + + } ); + // internal properties const _this = this; @@ -26358,7 +26617,7 @@ function WebGLRenderer( parameters = {} ) { // frustum - const _frustum = new Frustum$1(); + const _frustum = new Frustum(); // clipping @@ -26421,6 +26680,7 @@ function WebGLRenderer( parameters = {} ) { // event listeners must be registered before WebGL context is created, see #12753 _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); if ( _gl === null ) { @@ -26762,6 +27022,7 @@ function WebGLRenderer( parameters = {} ) { _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); renderLists.dispose(); renderStates.dispose(); @@ -26822,6 +27083,12 @@ function WebGLRenderer( parameters = {} ) { } + function onContextCreationError( event ) { + + console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); + + } + function onMaterialDispose( event ) { const material = event.target; @@ -27394,7 +27661,7 @@ function WebGLRenderer( parameters = {} ) { _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, { generateMipmaps: true, - type: utils.convert( HalfFloatType ) !== null ? HalfFloatType : UnsignedByteType, + type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType, minFilter: LinearMipmapLinearFilter, samples: ( isWebGL2 && _antialias === true ) ? 4 : 0 } ); @@ -27696,7 +27963,7 @@ function WebGLRenderer( parameters = {} ) { needsProgramChange = true; - } else if ( material.fog && materialProperties.fog !== fog ) { + } else if ( material.fog === true && materialProperties.fog !== fog ) { needsProgramChange = true; @@ -27868,7 +28135,7 @@ function WebGLRenderer( parameters = {} ) { } else { - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' ); } @@ -27913,7 +28180,7 @@ function WebGLRenderer( parameters = {} ) { // refresh uniforms common to several materials - if ( fog && material.fog ) { + if ( fog && material.fog === true ) { materials.refreshFogUniforms( m_uniforms, fog ); @@ -28200,13 +28467,6 @@ function WebGLRenderer( parameters = {} ) { this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { - if ( texture.isFramebufferTexture !== true ) { - - console.error( 'THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.' ); - return; - - } - const levelScale = Math.pow( 2, - level ); const width = Math.floor( texture.image.width * levelScale ); const height = Math.floor( texture.image.height * levelScale ); @@ -28344,7 +28604,23 @@ function WebGLRenderer( parameters = {} ) { this.initTexture = function ( texture ) { - textures.setTexture2D( texture, 0 ); + if ( texture.isCubeTexture ) { + + textures.setTextureCube( texture, 0 ); + + } else if ( texture.isData3DTexture ) { + + textures.setTexture3D( texture, 0 ); + + } else if ( texture.isDataArrayTexture ) { + + textures.setTexture2DArray( texture, 0 ); + + } else { + + textures.setTexture2D( texture, 0 ); + + } state.unbindTexture(); @@ -28369,8 +28645,6 @@ function WebGLRenderer( parameters = {} ) { } -WebGLRenderer.prototype.isWebGLRenderer = true; - class WebGL1Renderer extends WebGLRenderer {} WebGL1Renderer.prototype.isWebGL1Renderer = true; @@ -28379,6 +28653,8 @@ class FogExp2 { constructor( color, density = 0.00025 ) { + this.isFogExp2 = true; + this.name = ''; this.color = new Color( color ); @@ -28404,12 +28680,12 @@ class FogExp2 { } -FogExp2.prototype.isFogExp2 = true; - class Fog { constructor( color, near = 1, far = 1000 ) { + this.isFog = true; + this.name = ''; this.color = new Color( color ); @@ -28438,14 +28714,14 @@ class Fog { } -Fog.prototype.isFog = true; - class Scene$1 extends Object3D { constructor() { super(); + this.isScene = true; + this.type = 'Scene'; this.background = null; @@ -28493,12 +28769,12 @@ class Scene$1 extends Object3D { } -Scene$1.prototype.isScene = true; - class InterleavedBuffer { constructor( array, stride ) { + this.isInterleavedBuffer = true; + this.array = array; this.stride = stride; this.count = array !== undefined ? array.length / stride : 0; @@ -28617,7 +28893,7 @@ class InterleavedBuffer { if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { - data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) ); + data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) ); } @@ -28634,14 +28910,14 @@ class InterleavedBuffer { } -InterleavedBuffer.prototype.isInterleavedBuffer = true; - const _vector$6 = /*@__PURE__*/ new Vector3(); class InterleavedBufferAttribute { constructor( interleavedBuffer, itemSize, offset, normalized = false ) { + this.isInterleavedBufferAttribute = true; + this.name = ''; this.data = interleavedBuffer; @@ -28814,7 +29090,7 @@ class InterleavedBufferAttribute { if ( data === undefined ) { - console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' ); + console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.' ); const array = []; @@ -28856,7 +29132,7 @@ class InterleavedBufferAttribute { if ( data === undefined ) { - console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' ); + console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.' ); const array = []; @@ -28883,7 +29159,7 @@ class InterleavedBufferAttribute { } else { - // save as true interlaved attribtue + // save as true interleaved attribtue if ( data.interleavedBuffers === undefined ) { @@ -28911,14 +29187,14 @@ class InterleavedBufferAttribute { } -InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true; - class SpriteMaterial extends Material { constructor( parameters ) { super(); + this.isSpriteMaterial = true; + this.type = 'SpriteMaterial'; this.color = new Color( 0xffffff ); @@ -28933,6 +29209,8 @@ class SpriteMaterial extends Material { this.transparent = true; + this.fog = true; + this.setValues( parameters ); } @@ -28951,14 +29229,14 @@ class SpriteMaterial extends Material { this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; } } -SpriteMaterial.prototype.isSpriteMaterial = true; - let _geometry; const _intersectPoint = /*@__PURE__*/ new Vector3(); @@ -28983,6 +29261,8 @@ class Sprite extends Object3D { super(); + this.isSprite = true; + this.type = 'Sprite'; if ( _geometry === undefined ) { @@ -29086,9 +29366,9 @@ class Sprite extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); if ( source.center !== undefined ) this.center.copy( source.center ); @@ -29100,8 +29380,6 @@ class Sprite extends Object3D { } -Sprite.prototype.isSprite = true; - function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { // compute position in camera space @@ -29333,6 +29611,8 @@ class SkinnedMesh extends Mesh { super( geometry, material ); + this.isSkinnedMesh = true; + this.type = 'SkinnedMesh'; this.bindMode = 'attached'; @@ -29341,9 +29621,9 @@ class SkinnedMesh extends Mesh { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.bindMode = source.bindMode; this.bindMatrix.copy( source.bindMatrix ); @@ -29462,28 +29742,28 @@ class SkinnedMesh extends Mesh { } -SkinnedMesh.prototype.isSkinnedMesh = true; - class Bone extends Object3D { constructor() { super(); + this.isBone = true; + this.type = 'Bone'; } } -Bone.prototype.isBone = true; - class DataTexture extends Texture { constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) { super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.isDataTexture = true; + this.image = { data: data, width: width, height: height }; this.generateMipmaps = false; @@ -29494,8 +29774,6 @@ class DataTexture extends Texture { } -DataTexture.prototype.isDataTexture = true; - const _offsetMatrix = /*@__PURE__*/ new Matrix4(); const _identityMatrix = /*@__PURE__*/ new Matrix4(); @@ -29783,6 +30061,8 @@ class InstancedBufferAttribute extends BufferAttribute { super( array, itemSize, normalized ); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; } @@ -29811,14 +30091,12 @@ class InstancedBufferAttribute extends BufferAttribute { } -InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true; - const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4(); const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4(); const _instanceIntersects = []; -const _mesh$1 = /*@__PURE__*/ new Mesh(); +const _mesh = /*@__PURE__*/ new Mesh(); class InstancedMesh extends Mesh { @@ -29826,6 +30104,8 @@ class InstancedMesh extends Mesh { super( geometry, material ); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); this.instanceColor = null; @@ -29835,9 +30115,9 @@ class InstancedMesh extends Mesh { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.instanceMatrix.copy( source.instanceMatrix ); @@ -29866,10 +30146,10 @@ class InstancedMesh extends Mesh { const matrixWorld = this.matrixWorld; const raycastTimes = this.count; - _mesh$1.geometry = this.geometry; - _mesh$1.material = this.material; + _mesh.geometry = this.geometry; + _mesh.material = this.material; - if ( _mesh$1.material === undefined ) return; + if ( _mesh.material === undefined ) return; for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { @@ -29881,9 +30161,9 @@ class InstancedMesh extends Mesh { // the mesh represents this single instance - _mesh$1.matrixWorld = _instanceWorldMatrix; + _mesh.matrixWorld = _instanceWorldMatrix; - _mesh$1.raycast( raycaster, _instanceIntersects ); + _mesh.raycast( raycaster, _instanceIntersects ); // process the result of raycast @@ -29932,14 +30212,14 @@ class InstancedMesh extends Mesh { } -InstancedMesh.prototype.isInstancedMesh = true; - class LineBasicMaterial extends Material { constructor( parameters ) { super(); + this.isLineBasicMaterial = true; + this.type = 'LineBasicMaterial'; this.color = new Color( 0xffffff ); @@ -29948,6 +30228,8 @@ class LineBasicMaterial extends Material { this.linecap = 'round'; this.linejoin = 'round'; + this.fog = true; + this.setValues( parameters ); } @@ -29963,14 +30245,14 @@ class LineBasicMaterial extends Material { this.linecap = source.linecap; this.linejoin = source.linejoin; + this.fog = source.fog; + return this; } } -LineBasicMaterial.prototype.isLineBasicMaterial = true; - const _start$1 = /*@__PURE__*/ new Vector3(); const _end$1 = /*@__PURE__*/ new Vector3(); const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4(); @@ -29983,6 +30265,8 @@ class Line$2 extends Object3D { super(); + this.isLine = true; + this.type = 'Line'; this.geometry = geometry; @@ -29992,9 +30276,9 @@ class Line$2 extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.material = source.material; this.geometry = source.geometry; @@ -30007,36 +30291,28 @@ class Line$2 extends Object3D { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - // we assume non-indexed geometry - - if ( geometry.index === null ) { + // we assume non-indexed geometry - const positionAttribute = geometry.attributes.position; - const lineDistances = [ 0 ]; + if ( geometry.index === null ) { - for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [ 0 ]; - _start$1.fromBufferAttribute( positionAttribute, i - 1 ); - _end$1.fromBufferAttribute( positionAttribute, i ); + for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { - lineDistances[ i ] = lineDistances[ i - 1 ]; - lineDistances[ i ] += _start$1.distanceTo( _end$1 ); + _start$1.fromBufferAttribute( positionAttribute, i - 1 ); + _end$1.fromBufferAttribute( positionAttribute, i ); - } - - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); - - } else { - - console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _start$1.distanceTo( _end$1 ); } - } else if ( geometry.isGeometry ) { + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { - console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); } @@ -30075,91 +30351,83 @@ class Line$2 extends Object3D { const interRay = new Vector3(); const step = this.isLineSegments ? 2 : 1; - if ( geometry.isBufferGeometry ) { - - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; - - if ( index !== null ) { + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; - const start = Math.max( 0, drawRange.start ); - const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + if ( index !== null ) { - for ( let i = start, l = end - 1; i < l; i += step ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const a = index.getX( i ); - const b = index.getX( i + 1 ); + for ( let i = start, l = end - 1; i < l; i += step ) { - vStart.fromBufferAttribute( positionAttribute, a ); - vEnd.fromBufferAttribute( positionAttribute, b ); + const a = index.getX( i ); + const b = index.getX( i + 1 ); - const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + vStart.fromBufferAttribute( positionAttribute, a ); + vEnd.fromBufferAttribute( positionAttribute, b ); - if ( distSq > localThresholdSq ) continue; + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + if ( distSq > localThresholdSq ) continue; - const distance = raycaster.ray.origin.distanceTo( interRay ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - if ( distance < raycaster.near || distance > raycaster.far ) continue; + const distance = raycaster.ray.origin.distanceTo( interRay ); - intersects.push( { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + intersects.push( { - } ); + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - } + } ); - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, l = end - 1; i < l; i += step ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); - vStart.fromBufferAttribute( positionAttribute, i ); - vEnd.fromBufferAttribute( positionAttribute, i + 1 ); + for ( let i = start, l = end - 1; i < l; i += step ) { - const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + vStart.fromBufferAttribute( positionAttribute, i ); + vEnd.fromBufferAttribute( positionAttribute, i + 1 ); - if ( distSq > localThresholdSq ) continue; + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + if ( distSq > localThresholdSq ) continue; - const distance = raycaster.ray.origin.distanceTo( interRay ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - if ( distance < raycaster.near || distance > raycaster.far ) continue; + const distance = raycaster.ray.origin.distanceTo( interRay ); - intersects.push( { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + intersects.push( { - } ); + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - } + } ); } - } else if ( geometry.isGeometry ) { - - console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - } } @@ -30168,51 +30436,35 @@ class Line$2 extends Object3D { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); - - if ( keys.length > 0 ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + if ( keys.length > 0 ) { - if ( morphAttribute !== undefined ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( morphAttribute !== undefined ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - const name = morphAttribute[ m ].name || String( m ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - } else { - - const morphTargets = geometry.morphTargets; - - if ( morphTargets !== undefined && morphTargets.length > 0 ) { - - console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); - - } - } } } -Line$2.prototype.isLine = true; - const _start = /*@__PURE__*/ new Vector3(); const _end = /*@__PURE__*/ new Vector3(); @@ -30222,6 +30474,8 @@ class LineSegments extends Line$2 { super( geometry, material ); + this.isLineSegments = true; + this.type = 'LineSegments'; } @@ -30230,36 +30484,28 @@ class LineSegments extends Line$2 { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { + // we assume non-indexed geometry - // we assume non-indexed geometry + if ( geometry.index === null ) { - if ( geometry.index === null ) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; - const positionAttribute = geometry.attributes.position; - const lineDistances = []; + for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { - for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { - - _start.fromBufferAttribute( positionAttribute, i ); - _end.fromBufferAttribute( positionAttribute, i + 1 ); - - lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; - lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); - - } + _start.fromBufferAttribute( positionAttribute, i ); + _end.fromBufferAttribute( positionAttribute, i + 1 ); - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); - - } else { - - console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); } - } else if ( geometry.isGeometry ) { + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { - console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); } @@ -30269,28 +30515,28 @@ class LineSegments extends Line$2 { } -LineSegments.prototype.isLineSegments = true; - class LineLoop extends Line$2 { constructor( geometry, material ) { super( geometry, material ); + this.isLineLoop = true; + this.type = 'LineLoop'; } } -LineLoop.prototype.isLineLoop = true; - class PointsMaterial extends Material { constructor( parameters ) { super(); + this.isPointsMaterial = true; + this.type = 'PointsMaterial'; this.color = new Color( 0xffffff ); @@ -30302,6 +30548,8 @@ class PointsMaterial extends Material { this.size = 1; this.sizeAttenuation = true; + this.fog = true; + this.setValues( parameters ); } @@ -30319,14 +30567,14 @@ class PointsMaterial extends Material { this.size = source.size; this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; } } -PointsMaterial.prototype.isPointsMaterial = true; - const _inverseMatrix = /*@__PURE__*/ new Matrix4(); const _ray = /*@__PURE__*/ new Ray(); const _sphere = /*@__PURE__*/ new Sphere(); @@ -30338,6 +30586,8 @@ class Points extends Object3D { super(); + this.isPoints = true; + this.type = 'Points'; this.geometry = geometry; @@ -30347,9 +30597,9 @@ class Points extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.material = source.material; this.geometry = source.geometry; @@ -30383,46 +30633,38 @@ class Points extends Object3D { const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); const localThresholdSq = localThreshold * localThreshold; - if ( geometry.isBufferGeometry ) { - - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; - - if ( index !== null ) { + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; - const start = Math.max( 0, drawRange.start ); - const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + if ( index !== null ) { - for ( let i = start, il = end; i < il; i ++ ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const a = index.getX( i ); + for ( let i = start, il = end; i < il; i ++ ) { - _position$2.fromBufferAttribute( positionAttribute, a ); + const a = index.getX( i ); - testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + _position$2.fromBufferAttribute( positionAttribute, a ); - } + testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, l = end; i < l; i ++ ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); - _position$2.fromBufferAttribute( positionAttribute, i ); + for ( let i = start, l = end; i < l; i ++ ) { - testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + _position$2.fromBufferAttribute( positionAttribute, i ); - } + testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); } - } else { - - console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - } } @@ -30431,51 +30673,35 @@ class Points extends Object3D { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); - - if ( keys.length > 0 ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + if ( keys.length > 0 ) { - if ( morphAttribute !== undefined ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( morphAttribute !== undefined ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - const name = morphAttribute[ m ].name || String( m ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - } else { - - const morphTargets = geometry.morphTargets; - - if ( morphTargets !== undefined && morphTargets.length > 0 ) { - - console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); - - } - } } } -Points.prototype.isPoints = true; - function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { const rayPointDistanceSq = _ray.distanceSqToPoint( point ); @@ -30512,6 +30738,8 @@ class VideoTexture extends Texture { super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.isVideoTexture = true; + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; @@ -30555,14 +30783,14 @@ class VideoTexture extends Texture { } -VideoTexture.prototype.isVideoTexture = true; - class FramebufferTexture extends Texture { constructor( width, height, format ) { super( { width, height } ); + this.isFramebufferTexture = true; + this.format = format; this.magFilter = NearestFilter; @@ -30576,14 +30804,14 @@ class FramebufferTexture extends Texture { } -FramebufferTexture.prototype.isFramebufferTexture = true; - class CompressedTexture extends Texture { constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.isCompressedTexture = true; + this.image = { width: width, height: height }; this.mipmaps = mipmaps; @@ -30601,22 +30829,20 @@ class CompressedTexture extends Texture { } -CompressedTexture.prototype.isCompressedTexture = true; - class CanvasTexture extends Texture { constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.isCanvasTexture = true; + this.needsUpdate = true; } } -CanvasTexture.prototype.isCanvasTexture = true; - /** * Extensible curve object. * @@ -31032,6 +31258,8 @@ class EllipseCurve extends Curve { super(); + this.isEllipseCurve = true; + this.type = 'EllipseCurve'; this.aX = aX; @@ -31176,22 +31404,20 @@ class EllipseCurve extends Curve { } -EllipseCurve.prototype.isEllipseCurve = true; - class ArcCurve extends EllipseCurve { constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + this.isArcCurve = true; + this.type = 'ArcCurve'; } } -ArcCurve.prototype.isArcCurve = true; - /** * Centripetal CatmullRom Curve - which is useful for avoiding * cusps and self-intersections in non-uniform catmull rom curves. @@ -31269,8 +31495,10 @@ function CubicPoly() { // -const tmp = new Vector3(); -const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly(); +const tmp = /*@__PURE__*/ new Vector3(); +const px = /*@__PURE__*/ new CubicPoly(); +const py = /*@__PURE__*/ new CubicPoly(); +const pz = /*@__PURE__*/ new CubicPoly(); class CatmullRomCurve3 extends Curve { @@ -31278,6 +31506,8 @@ class CatmullRomCurve3 extends Curve { super(); + this.isCatmullRomCurve3 = true; + this.type = 'CatmullRomCurve3'; this.points = points; @@ -31439,8 +31669,6 @@ class CatmullRomCurve3 extends Curve { } -CatmullRomCurve3.prototype.isCatmullRomCurve3 = true; - /** * Bezier Curves formulas obtained from * https://en.wikipedia.org/wiki/B%C3%A9zier_curve @@ -31525,6 +31753,8 @@ class CubicBezierCurve extends Curve { super(); + this.isCubicBezierCurve = true; + this.type = 'CubicBezierCurve'; this.v0 = v0; @@ -31590,14 +31820,14 @@ class CubicBezierCurve extends Curve { } -CubicBezierCurve.prototype.isCubicBezierCurve = true; - class CubicBezierCurve3 extends Curve { constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { super(); + this.isCubicBezierCurve3 = true; + this.type = 'CubicBezierCurve3'; this.v0 = v0; @@ -31664,14 +31894,14 @@ class CubicBezierCurve3 extends Curve { } -CubicBezierCurve3.prototype.isCubicBezierCurve3 = true; - class LineCurve extends Curve { constructor( v1 = new Vector2(), v2 = new Vector2() ) { super(); + this.isLineCurve = true; + this.type = 'LineCurve'; this.v1 = v1; @@ -31750,17 +31980,16 @@ class LineCurve extends Curve { } -LineCurve.prototype.isLineCurve = true; - class LineCurve3 extends Curve { constructor( v1 = new Vector3(), v2 = new Vector3() ) { super(); - this.type = 'LineCurve3'; this.isLineCurve3 = true; + this.type = 'LineCurve3'; + this.v1 = v1; this.v2 = v2; @@ -31828,6 +32057,8 @@ class QuadraticBezierCurve extends Curve { super(); + this.isQuadraticBezierCurve = true; + this.type = 'QuadraticBezierCurve'; this.v0 = v0; @@ -31889,14 +32120,14 @@ class QuadraticBezierCurve extends Curve { } -QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true; - class QuadraticBezierCurve3 extends Curve { constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { super(); + this.isQuadraticBezierCurve3 = true; + this.type = 'QuadraticBezierCurve3'; this.v0 = v0; @@ -31959,14 +32190,14 @@ class QuadraticBezierCurve3 extends Curve { } -QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true; - class SplineCurve extends Curve { constructor( points = [] ) { super(); + this.isSplineCurve = true; + this.type = 'SplineCurve'; this.points = points; @@ -32051,8 +32282,6 @@ class SplineCurve extends Curve { } -SplineCurve.prototype.isSplineCurve = true; - var Curves = /*#__PURE__*/Object.freeze({ __proto__: null, ArcCurve: ArcCurve, @@ -32314,11 +32543,12 @@ class CurvePath extends Curve { } -class Path$1 extends CurvePath { +class Path extends CurvePath { constructor( points ) { super(); + this.type = 'Path'; this.currentPoint = new Vector2(); @@ -32674,7 +32904,7 @@ class CapsuleGeometry extends LatheGeometry { constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) { - const path = new Path$1(); + const path = new Path(); path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 ); path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 ); @@ -33444,10 +33674,10 @@ class DodecahedronGeometry extends PolyhedronGeometry { } -const _v0 = new Vector3(); -const _v1$1 = new Vector3(); -const _normal = new Vector3(); -const _triangle = new Triangle(); +const _v0 = /*@__PURE__*/ new Vector3(); +const _v1$1 = /*@__PURE__*/ new Vector3(); +const _normal = /*@__PURE__*/ new Vector3(); +const _triangle = /*@__PURE__*/ new Triangle(); class EdgesGeometry extends BufferGeometry { @@ -33578,7 +33808,7 @@ class EdgesGeometry extends BufferGeometry { } -class Shape extends Path$1 { +class Shape extends Path { constructor( points ) { @@ -33665,7 +33895,7 @@ class Shape extends Path$1 { for ( let i = 0, l = json.holes.length; i < l; i ++ ) { const hole = json.holes[ i ]; - this.holes.push( new Path$1().fromJSON( hole ) ); + this.holes.push( new Path().fromJSON( hole ) ); } @@ -33740,7 +33970,7 @@ function linkedList( data, start, end, dim, clockwise ) { } - if ( last && equals$1( last, last.next ) ) { + if ( last && equals( last, last.next ) ) { removeNode( last ); last = last.next; @@ -33763,7 +33993,7 @@ function filterPoints( start, end ) { again = false; - if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { removeNode( p ); p = end = p.prev; @@ -33942,7 +34172,7 @@ function cureLocalIntersections( start, triangles, dim ) { const a = p.prev, b = p.next.next; - if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { triangles.push( a.i / dim ); triangles.push( p.i / dim ); @@ -34271,7 +34501,7 @@ function isValidDiagonal( a, b ) { return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors - equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case } @@ -34283,7 +34513,7 @@ function area( p, q, r ) { } // check if two points are equal -function equals$1( p1, p2 ) { +function equals( p1, p2 ) { return p1.x === p2.x && p1.y === p2.y; @@ -34292,10 +34522,10 @@ function equals$1( p1, p2 ) { // check if two segments intersect function intersects( p1, q1, p2, q2 ) { - const o1 = sign$1( area( p1, q1, p2 ) ); - const o2 = sign$1( area( p1, q1, q2 ) ); - const o3 = sign$1( area( p2, q2, p1 ) ); - const o4 = sign$1( area( p2, q2, q1 ) ); + const o1 = sign( area( p1, q1, p2 ) ); + const o2 = sign( area( p1, q1, q2 ) ); + const o3 = sign( area( p2, q2, p1 ) ); + const o4 = sign( area( p2, q2, q1 ) ); if ( o1 !== o2 && o3 !== o4 ) return true; // general case @@ -34315,7 +34545,7 @@ function onSegment( p, q, r ) { } -function sign$1( num ) { +function sign( num ) { return num > 0 ? 1 : num < 0 ? - 1 : 0; @@ -34370,8 +34600,8 @@ function middleInside( a, b ) { // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon( a, b ) { - const a2 = new Node$1( a.i, a.x, a.y ), - b2 = new Node$1( b.i, b.x, b.y ), + const a2 = new Node( a.i, a.x, a.y ), + b2 = new Node( b.i, b.x, b.y ), an = a.next, bp = b.prev; @@ -34394,7 +34624,7 @@ function splitPolygon( a, b ) { // create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode( i, x, y, last ) { - const p = new Node$1( i, x, y ); + const p = new Node( i, x, y ); if ( ! last ) { @@ -34424,7 +34654,7 @@ function removeNode( p ) { } -function Node$1( i, x, y ) { +function Node( i, x, y ) { // vertex index in coordinates array this.i = i; @@ -35347,6 +35577,8 @@ function toJSON$1( shapes, options, data ) { } + data.options = Object.assign( {}, options ); + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); return data; @@ -36484,11 +36716,15 @@ class ShadowMaterial extends Material { super(); + this.isShadowMaterial = true; + this.type = 'ShadowMaterial'; this.color = new Color( 0x000000 ); this.transparent = true; + this.fog = true; + this.setValues( parameters ); } @@ -36499,34 +36735,36 @@ class ShadowMaterial extends Material { this.color.copy( source.color ); + this.fog = source.fog; + return this; } } -ShadowMaterial.prototype.isShadowMaterial = true; - class RawShaderMaterial extends ShaderMaterial { constructor( parameters ) { super( parameters ); + this.isRawShaderMaterial = true; + this.type = 'RawShaderMaterial'; } } -RawShaderMaterial.prototype.isRawShaderMaterial = true; - class MeshStandardMaterial extends Material { constructor( parameters ) { super(); + this.isMeshStandardMaterial = true; + this.defines = { 'STANDARD': '' }; this.type = 'MeshStandardMaterial'; @@ -36574,6 +36812,8 @@ class MeshStandardMaterial extends Material { this.flatShading = false; + this.fog = true; + this.setValues( parameters ); } @@ -36627,20 +36867,22 @@ class MeshStandardMaterial extends Material { this.flatShading = source.flatShading; + this.fog = source.fog; + return this; } } -MeshStandardMaterial.prototype.isMeshStandardMaterial = true; - class MeshPhysicalMaterial extends MeshStandardMaterial { constructor( parameters ) { super(); + this.isMeshPhysicalMaterial = true; + this.defines = { 'STANDARD': '', @@ -36671,6 +36913,11 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { } } ); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [ 100, 400 ]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color( 0x000000 ); this.sheenColorMap = null; this.sheenRoughness = 1.0; @@ -36690,6 +36937,7 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { this._sheen = 0.0; this._clearcoat = 0; + this._iridescence = 0; this._transmission = 0; this.setValues( parameters ); @@ -36732,6 +36980,24 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { } + get iridescence() { + + return this._iridescence; + + } + + set iridescence( value ) { + + if ( this._iridescence > 0 !== value > 0 ) { + + this.version ++; + + } + + this._iridescence = value; + + } + get transmission() { return this._transmission; @@ -36770,6 +37036,12 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; this.sheenColor.copy( source.sheenColor ); this.sheenColorMap = source.sheenColorMap; @@ -36795,14 +37067,14 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { } -MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; - class MeshPhongMaterial extends Material { constructor( parameters ) { super(); + this.isMeshPhongMaterial = true; + this.type = 'MeshPhongMaterial'; this.color = new Color( 0xffffff ); // diffuse @@ -36848,6 +37120,8 @@ class MeshPhongMaterial extends Material { this.flatShading = false; + this.fog = true; + this.setValues( parameters ); } @@ -36899,20 +37173,22 @@ class MeshPhongMaterial extends Material { this.flatShading = source.flatShading; + this.fog = source.fog; + return this; } } -MeshPhongMaterial.prototype.isMeshPhongMaterial = true; - class MeshToonMaterial extends Material { constructor( parameters ) { super(); + this.isMeshToonMaterial = true; + this.defines = { 'TOON': '' }; this.type = 'MeshToonMaterial'; @@ -36950,6 +37226,8 @@ class MeshToonMaterial extends Material { this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; + this.fog = true; + this.setValues( parameters ); } @@ -36991,20 +37269,22 @@ class MeshToonMaterial extends Material { this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; } } -MeshToonMaterial.prototype.isMeshToonMaterial = true; - class MeshNormalMaterial extends Material { constructor( parameters ) { super(); + this.isMeshNormalMaterial = true; + this.type = 'MeshNormalMaterial'; this.bumpMap = null; @@ -37021,8 +37301,6 @@ class MeshNormalMaterial extends Material { this.wireframe = false; this.wireframeLinewidth = 1; - this.fog = false; - this.flatShading = false; this.setValues( parameters ); @@ -37055,14 +37333,14 @@ class MeshNormalMaterial extends Material { } -MeshNormalMaterial.prototype.isMeshNormalMaterial = true; - class MeshLambertMaterial extends Material { constructor( parameters ) { super(); + this.isMeshLambertMaterial = true; + this.type = 'MeshLambertMaterial'; this.color = new Color( 0xffffff ); // diffuse @@ -37093,6 +37371,8 @@ class MeshLambertMaterial extends Material { this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; + this.fog = true; + this.setValues( parameters ); } @@ -37129,20 +37409,22 @@ class MeshLambertMaterial extends Material { this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; } } -MeshLambertMaterial.prototype.isMeshLambertMaterial = true; - class MeshMatcapMaterial extends Material { constructor( parameters ) { super(); + this.isMeshMatcapMaterial = true; + this.defines = { 'MATCAP': '' }; this.type = 'MeshMatcapMaterial'; @@ -37168,6 +37450,8 @@ class MeshMatcapMaterial extends Material { this.flatShading = false; + this.fog = true; + this.setValues( parameters ); } @@ -37200,20 +37484,22 @@ class MeshMatcapMaterial extends Material { this.flatShading = source.flatShading; + this.fog = source.fog; + return this; } } -MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true; - class LineDashedMaterial extends LineBasicMaterial { constructor( parameters ) { super(); + this.isLineDashedMaterial = true; + this.type = 'LineDashedMaterial'; this.scale = 1; @@ -37238,35 +37524,6 @@ class LineDashedMaterial extends LineBasicMaterial { } -LineDashedMaterial.prototype.isLineDashedMaterial = true; - -const materialLib = { - ShadowMaterial, - SpriteMaterial, - RawShaderMaterial, - ShaderMaterial, - PointsMaterial, - MeshPhysicalMaterial, - MeshStandardMaterial, - MeshPhongMaterial, - MeshToonMaterial, - MeshNormalMaterial, - MeshLambertMaterial, - MeshDepthMaterial, - MeshDistanceMaterial, - MeshBasicMaterial, - MeshMatcapMaterial, - LineDashedMaterial, - LineBasicMaterial, - Material -}; - -Material.fromType = function ( type ) { - - return new materialLib[ type ](); - -}; - const AnimationUtils = { // same as Array.prototype.slice, but also works on typed arrays @@ -37688,7 +37945,7 @@ class Interpolant { i1 = pp.length; this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + return this.copySampleValue_( i1 - 1 ); } @@ -37736,7 +37993,7 @@ class Interpolant { // before start this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + return this.copySampleValue_( 0 ); } @@ -37793,7 +38050,7 @@ class Interpolant { if ( t0 === undefined ) { this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + return this.copySampleValue_( 0 ); } @@ -37801,7 +38058,7 @@ class Interpolant { i1 = pp.length; this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + return this.copySampleValue_( i1 - 1 ); } @@ -37859,11 +38116,6 @@ class Interpolant { } -// ALIAS DEFINITIONS - -Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_; -Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_; - /** * Fast and simple cubic spline interpolant. * @@ -40056,6 +40308,8 @@ class Light extends Object3D { super(); + this.isLight = true; + this.type = 'Light'; this.color = new Color( color ); @@ -40069,9 +40323,9 @@ class Light extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.color.copy( source.color ); this.intensity = source.intensity; @@ -40102,14 +40356,14 @@ class Light extends Object3D { } -Light.prototype.isLight = true; - class HemisphereLight extends Light { constructor( skyColor, groundColor, intensity ) { super( skyColor, intensity ); + this.isHemisphereLight = true; + this.type = 'HemisphereLight'; this.position.copy( Object3D.DefaultUp ); @@ -40119,9 +40373,9 @@ class HemisphereLight extends Light { } - copy( source ) { + copy( source, recursive ) { - Light.prototype.copy.call( this, source ); + super.copy( source, recursive ); this.groundColor.copy( source.groundColor ); @@ -40131,8 +40385,6 @@ class HemisphereLight extends Light { } -HemisphereLight.prototype.isHemisphereLight = true; - const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); const _lookTarget$1 = /*@__PURE__*/ new Vector3(); @@ -40157,7 +40409,7 @@ class LightShadow { this.autoUpdate = true; this.needsUpdate = false; - this._frustum = new Frustum$1(); + this._frustum = new Frustum(); this._frameExtents = new Vector2( 1, 1 ); this._viewportCount = 1; @@ -40280,6 +40532,8 @@ class SpotLightShadow extends LightShadow { super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + this.isSpotLightShadow = true; + this.focus = 1; } @@ -40317,14 +40571,14 @@ class SpotLightShadow extends LightShadow { } -SpotLightShadow.prototype.isSpotLightShadow = true; - class SpotLight extends Light { constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) { super( color, intensity ); + this.isSpotLight = true; + this.type = 'SpotLight'; this.position.copy( Object3D.DefaultUp ); @@ -40362,9 +40616,9 @@ class SpotLight extends Light { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.distance = source.distance; this.angle = source.angle; @@ -40381,8 +40635,6 @@ class SpotLight extends Light { } -SpotLight.prototype.isSpotLight = true; - const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); const _lightPositionWorld = /*@__PURE__*/ new Vector3(); const _lookTarget = /*@__PURE__*/ new Vector3(); @@ -40393,6 +40645,8 @@ class PointLightShadow extends LightShadow { super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + this.isPointLightShadow = true; + this._frameExtents = new Vector2( 4, 2 ); this._viewportCount = 6; @@ -40469,14 +40723,14 @@ class PointLightShadow extends LightShadow { } -PointLightShadow.prototype.isPointLightShadow = true; - class PointLight extends Light { constructor( color, intensity, distance = 0, decay = 1 ) { super( color, intensity ); + this.isPointLight = true; + this.type = 'PointLight'; this.distance = distance; @@ -40507,9 +40761,9 @@ class PointLight extends Light { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.distance = source.distance; this.decay = source.decay; @@ -40522,26 +40776,26 @@ class PointLight extends Light { } -PointLight.prototype.isPointLight = true; - class DirectionalLightShadow extends LightShadow { constructor() { super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + this.isDirectionalLightShadow = true; + } } -DirectionalLightShadow.prototype.isDirectionalLightShadow = true; - class DirectionalLight$1 extends Light { constructor( color, intensity ) { super( color, intensity ); + this.isDirectionalLight = true; + this.type = 'DirectionalLight'; this.position.copy( Object3D.DefaultUp ); @@ -40572,28 +40826,28 @@ class DirectionalLight$1 extends Light { } -DirectionalLight$1.prototype.isDirectionalLight = true; - class AmbientLight$1 extends Light { constructor( color, intensity ) { super( color, intensity ); + this.isAmbientLight = true; + this.type = 'AmbientLight'; } } -AmbientLight$1.prototype.isAmbientLight = true; - class RectAreaLight extends Light { constructor( color, intensity, width = 10, height = 10 ) { super( color, intensity ); + this.isRectAreaLight = true; + this.type = 'RectAreaLight'; this.width = width; @@ -40639,8 +40893,6 @@ class RectAreaLight extends Light { } -RectAreaLight.prototype.isRectAreaLight = true; - /** * Primary reference: * https://graphics.stanford.edu/papers/envmap/envmap.pdf @@ -40655,6 +40907,8 @@ class SphericalHarmonics3 { constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; for ( let i = 0; i < 9; i ++ ) { @@ -40879,14 +41133,14 @@ class SphericalHarmonics3 { } -SphericalHarmonics3.prototype.isSphericalHarmonics3 = true; - class LightProbe extends Light { constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { super( undefined, intensity ); + this.isLightProbe = true; + this.sh = sh; } @@ -40922,8 +41176,6 @@ class LightProbe extends Light { } -LightProbe.prototype.isLightProbe = true; - class MaterialLoader extends Loader { constructor( manager ) { @@ -40983,7 +41235,7 @@ class MaterialLoader extends Loader { } - const material = Material.fromType( json.type ); + const material = MaterialLoader.createMaterialFromType( json.type ); if ( json.uuid !== undefined ) material.uuid = json.uuid; if ( json.name !== undefined ) material.name = json.name; @@ -41000,6 +41252,9 @@ class MaterialLoader extends Loader { if ( json.shininess !== undefined ) material.shininess = json.shininess; if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; + if ( json.iridescence !== undefined ) material.iridescence = json.iridescence; + if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR; + if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange; if ( json.transmission !== undefined ) material.transmission = json.transmission; if ( json.thickness !== undefined ) material.thickness = json.thickness; if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance; @@ -41200,6 +41455,9 @@ class MaterialLoader extends Loader { if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); + if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap ); + if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap ); + if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap ); if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap ); @@ -41217,6 +41475,33 @@ class MaterialLoader extends Loader { } + static createMaterialFromType( type ) { + + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + + return new materialLib[ type ](); + + } + } class LoaderUtils { @@ -41299,6 +41584,8 @@ class InstancedBufferGeometry extends BufferGeometry { super(); + this.isInstancedBufferGeometry = true; + this.type = 'InstancedBufferGeometry'; this.instanceCount = Infinity; @@ -41334,8 +41621,6 @@ class InstancedBufferGeometry extends BufferGeometry { } -InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true; - class BufferGeometryLoader extends Loader { constructor( manager ) { @@ -41655,7 +41940,7 @@ class ObjectLoader extends Loader { for ( const uuid in images ) { - if ( images[ uuid ] instanceof HTMLImageElement ) { + if ( images[ uuid ].data instanceof HTMLImageElement ) { hasImages = true; break; @@ -42613,6 +42898,8 @@ class ImageBitmapLoader extends Loader { super( manager ); + this.isImageBitmapLoader = true; + if ( typeof createImageBitmap === 'undefined' ) { console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); @@ -42700,8 +42987,6 @@ class ImageBitmapLoader extends Loader { } -ImageBitmapLoader.prototype.isImageBitmapLoader = true; - let _context; const AudioContext = { @@ -42786,6 +43071,8 @@ class HemisphereLightProbe extends LightProbe { super( undefined, intensity ); + this.isHemisphereLightProbe = true; + const color1 = new Color().set( skyColor ); const color2 = new Color().set( groundColor ); @@ -42803,14 +43090,14 @@ class HemisphereLightProbe extends LightProbe { } -HemisphereLightProbe.prototype.isHemisphereLightProbe = true; - class AmbientLightProbe extends LightProbe { constructor( color, intensity = 1 ) { super( undefined, intensity ); + this.isAmbientLightProbe = true; + const color1 = new Color().set( color ); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); @@ -42820,8 +43107,6 @@ class AmbientLightProbe extends LightProbe { } -AmbientLightProbe.prototype.isAmbientLightProbe = true; - const _eyeRight = /*@__PURE__*/ new Matrix4(); const _eyeLeft = /*@__PURE__*/ new Matrix4(); const _projectionMatrix = /*@__PURE__*/ new Matrix4(); @@ -44006,18 +44291,18 @@ const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must // be matched to parse the rest of the track name. -const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); +const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. -const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); +const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); // Object on target node, and accessor. May not contain reserved // characters. Accessor may contain any character except closing bracket. -const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); +const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); // Property and accessor. May not contain reserved characters. Accessor may // contain any non-bracket characters. -const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); +const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); const _trackRe = new RegExp( '' + '^' @@ -44568,26 +44853,16 @@ class PropertyBinding { } - if ( targetObject.geometry.isBufferGeometry ) { + if ( ! targetObject.geometry.morphAttributes ) { - if ( ! targetObject.geometry.morphAttributes ) { - - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); - return; - - } - - if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { - - propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; - - } + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); + return; + } - } else { + if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this ); - return; + propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; } @@ -44728,6 +45003,8 @@ class AnimationObjectGroup { constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID$1(); // cached objects followed by the active ones @@ -45076,8 +45353,6 @@ class AnimationObjectGroup { } -AnimationObjectGroup.prototype.isAnimationObjectGroup = true; - class AnimationAction { constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { @@ -45772,6 +46047,9 @@ class AnimationAction { } +const _controlInterpolantsResultBuffer = /*@__PURE__*/ new Float32Array( 1 ); + + class AnimationMixer extends EventDispatcher { constructor( root ) { @@ -46244,7 +46522,7 @@ class AnimationMixer extends EventDispatcher { interpolant = new LinearInterpolant( new Float32Array( 2 ), new Float32Array( 2 ), - 1, this._controlInterpolantsResultBuffer ); + 1, _controlInterpolantsResultBuffer ); interpolant.__cacheIndex = lastActiveIndex; interpolants[ lastActiveIndex ] = interpolant; @@ -46529,8 +46807,6 @@ class AnimationMixer extends EventDispatcher { } -AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 ); - class Uniform { constructor( value ) { @@ -46560,6 +46836,8 @@ class InstancedInterleavedBuffer extends InterleavedBuffer { super( array, stride ); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; } @@ -46597,12 +46875,12 @@ class InstancedInterleavedBuffer extends InterleavedBuffer { } -InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true; - class GLBufferAttribute { constructor( buffer, type, itemSize, elementSize, count ) { + this.isGLBufferAttribute = true; + this.buffer = buffer; this.type = type; this.itemSize = itemSize; @@ -46654,8 +46932,6 @@ class GLBufferAttribute { } -GLBufferAttribute.prototype.isGLBufferAttribute = true; - class Raycaster { constructor( origin, direction, near = 0, far = Infinity ) { @@ -46911,6 +47187,8 @@ class Box2 { constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { + this.isBox2 = true; + this.min = min; this.max = max; @@ -47103,8 +47381,6 @@ class Box2 { } -Box2.prototype.isBox2 = true; - const _startP = /*@__PURE__*/ new Vector3(); const _startEnd = /*@__PURE__*/ new Vector3(); @@ -47339,9 +47615,10 @@ class SkeletonHelper extends LineSegments { super( geometry, material ); - this.type = 'SkeletonHelper'; this.isSkeletonHelper = true; + this.type = 'SkeletonHelper'; + this.root = object; this.bones = bones; @@ -47786,72 +48063,64 @@ class CameraHelper extends LineSegments { const pointMap = {}; - // colors - - const colorFrustum = new Color( 0xffaa00 ); - const colorCone = new Color( 0xff0000 ); - const colorUp = new Color( 0x00aaff ); - const colorTarget = new Color( 0xffffff ); - const colorCross = new Color( 0x333333 ); - // near - addLine( 'n1', 'n2', colorFrustum ); - addLine( 'n2', 'n4', colorFrustum ); - addLine( 'n4', 'n3', colorFrustum ); - addLine( 'n3', 'n1', colorFrustum ); + addLine( 'n1', 'n2' ); + addLine( 'n2', 'n4' ); + addLine( 'n4', 'n3' ); + addLine( 'n3', 'n1' ); // far - addLine( 'f1', 'f2', colorFrustum ); - addLine( 'f2', 'f4', colorFrustum ); - addLine( 'f4', 'f3', colorFrustum ); - addLine( 'f3', 'f1', colorFrustum ); + addLine( 'f1', 'f2' ); + addLine( 'f2', 'f4' ); + addLine( 'f4', 'f3' ); + addLine( 'f3', 'f1' ); // sides - addLine( 'n1', 'f1', colorFrustum ); - addLine( 'n2', 'f2', colorFrustum ); - addLine( 'n3', 'f3', colorFrustum ); - addLine( 'n4', 'f4', colorFrustum ); + addLine( 'n1', 'f1' ); + addLine( 'n2', 'f2' ); + addLine( 'n3', 'f3' ); + addLine( 'n4', 'f4' ); // cone - addLine( 'p', 'n1', colorCone ); - addLine( 'p', 'n2', colorCone ); - addLine( 'p', 'n3', colorCone ); - addLine( 'p', 'n4', colorCone ); + addLine( 'p', 'n1' ); + addLine( 'p', 'n2' ); + addLine( 'p', 'n3' ); + addLine( 'p', 'n4' ); // up - addLine( 'u1', 'u2', colorUp ); - addLine( 'u2', 'u3', colorUp ); - addLine( 'u3', 'u1', colorUp ); + addLine( 'u1', 'u2' ); + addLine( 'u2', 'u3' ); + addLine( 'u3', 'u1' ); // target - addLine( 'c', 't', colorTarget ); - addLine( 'p', 'c', colorCross ); + addLine( 'c', 't' ); + addLine( 'p', 'c' ); // cross - addLine( 'cn1', 'cn2', colorCross ); - addLine( 'cn3', 'cn4', colorCross ); + addLine( 'cn1', 'cn2' ); + addLine( 'cn3', 'cn4' ); - addLine( 'cf1', 'cf2', colorCross ); - addLine( 'cf3', 'cf4', colorCross ); + addLine( 'cf1', 'cf2' ); + addLine( 'cf3', 'cf4' ); - function addLine( a, b, color ) { + function addLine( a, b ) { - addPoint( a, color ); - addPoint( b, color ); + addPoint( a ); + addPoint( b ); } - function addPoint( id, color ) { + function addPoint( id ) { vertices.push( 0, 0, 0 ); - colors.push( color.r, color.g, color.b ); + colors.push( 0, 0, 0 ); if ( pointMap[ id ] === undefined ) { @@ -47880,6 +48149,73 @@ class CameraHelper extends LineSegments { this.update(); + // colors + + const colorFrustum = new Color( 0xffaa00 ); + const colorCone = new Color( 0xff0000 ); + const colorUp = new Color( 0x00aaff ); + const colorTarget = new Color( 0xffffff ); + const colorCross = new Color( 0x333333 ); + + this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross ); + + } + + setColors( frustum, cone, up, target, cross ) { + + const geometry = this.geometry; + + const colorAttribute = geometry.getAttribute( 'color' ); + + // near + + colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2 + colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4 + colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3 + colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1 + + // far + + colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2 + colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4 + colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3 + colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1 + + // sides + + colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1 + colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2 + colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3 + colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4 + + // cone + + colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1 + colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2 + colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3 + colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4 + + // up + + colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2 + colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3 + colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1 + + // target + + colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t + colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c + + // cross + + colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2 + colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4 + + colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2 + colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4 + + colorAttribute.needsUpdate = true; + } update() { @@ -48052,9 +48388,9 @@ class BoxHelper extends LineSegments { } - copy( source ) { + copy( source, recursive ) { - LineSegments.prototype.copy.call( this, source ); + super.copy( source, recursive ); this.object = source.object; @@ -48322,7 +48658,7 @@ class ShapePath { moveTo( x, y ) { - this.currentPath = new Path$1(); + this.currentPath = new Path(); this.subPaths.push( this.currentPath ); this.currentPath.moveTo( x, y ); @@ -48596,100277 +48932,28577 @@ class ShapePath { // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf -class DataUtils { - - // float32 to float16 - - static toHalfFloat( val ) { - - if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); - - val = clamp( val, - 65504, 65504 ); - - _floatView[ 0 ] = val; - const f = _uint32View[ 0 ]; - const e = ( f >> 23 ) & 0x1ff; - return _baseTable[ e ] + ( ( f & 0x007fffff ) >> _shiftTable[ e ] ); - - } - - // float16 to float32 - - static fromHalfFloat( val ) { - - const m = val >> 10; - _uint32View[ 0 ] = _mantissaTable[ _offsetTable[ m ] + ( val & 0x3ff ) ] + _exponentTable[ m ]; - return _floatView[ 0 ]; - - } - -} - -// float32 to float16 helpers - -const _buffer = new ArrayBuffer( 4 ); -const _floatView = new Float32Array( _buffer ); -const _uint32View = new Uint32Array( _buffer ); - -const _baseTable = new Uint32Array( 512 ); -const _shiftTable = new Uint32Array( 512 ); - -for ( let i = 0; i < 256; ++ i ) { - - const e = i - 127; - - // very small number (0, -0) - - if ( e < - 27 ) { - - _baseTable[ i ] = 0x0000; - _baseTable[ i | 0x100 ] = 0x8000; - _shiftTable[ i ] = 24; - _shiftTable[ i | 0x100 ] = 24; - - // small number (denorm) - - } else if ( e < - 14 ) { - - _baseTable[ i ] = 0x0400 >> ( - e - 14 ); - _baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; - _shiftTable[ i ] = - e - 1; - _shiftTable[ i | 0x100 ] = - e - 1; - - // normal number - - } else if ( e <= 15 ) { - - _baseTable[ i ] = ( e + 15 ) << 10; - _baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; - _shiftTable[ i ] = 13; - _shiftTable[ i | 0x100 ] = 13; - - // large number (Infinity, -Infinity) - - } else if ( e < 128 ) { - - _baseTable[ i ] = 0x7c00; - _baseTable[ i | 0x100 ] = 0xfc00; - _shiftTable[ i ] = 24; - _shiftTable[ i | 0x100 ] = 24; - - // stay (NaN, Infinity, -Infinity) - - } else { - - _baseTable[ i ] = 0x7c00; - _baseTable[ i | 0x100 ] = 0xfc00; - _shiftTable[ i ] = 13; - _shiftTable[ i | 0x100 ] = 13; - - } - -} - -// float16 to float32 helpers +const { + floatView: _floatView, + uint32View: _uint32View, + baseTable: _baseTable, + shiftTable: _shiftTable, + mantissaTable: _mantissaTable, + exponentTable: _exponentTable, + offsetTable: _offsetTable +} = /*@__PURE__*/ _generateTables(); -const _mantissaTable = new Uint32Array( 2048 ); -const _exponentTable = new Uint32Array( 64 ); -const _offsetTable = new Uint32Array( 64 ); +function _generateTables() { -for ( let i = 1; i < 1024; ++ i ) { + // float32 to float16 helpers - let m = i << 13; // zero pad mantissa bits - let e = 0; // zero exponent + const buffer = new ArrayBuffer( 4 ); + const floatView = new Float32Array( buffer ); + const uint32View = new Uint32Array( buffer ); - // normalized - while ( ( m & 0x00800000 ) === 0 ) { + const baseTable = new Uint32Array( 512 ); + const shiftTable = new Uint32Array( 512 ); - m <<= 1; - e -= 0x00800000; // decrement exponent + for ( let i = 0; i < 256; ++ i ) { - } + const e = i - 127; - m &= ~ 0x00800000; // clear leading 1 bit - e += 0x38800000; // adjust bias + // very small number (0, -0) - _mantissaTable[ i ] = m | e; + if ( e < - 27 ) { -} + baseTable[ i ] = 0x0000; + baseTable[ i | 0x100 ] = 0x8000; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; -for ( let i = 1024; i < 2048; ++ i ) { + // small number (denorm) - _mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); + } else if ( e < - 14 ) { -} + baseTable[ i ] = 0x0400 >> ( - e - 14 ); + baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; + shiftTable[ i ] = - e - 1; + shiftTable[ i | 0x100 ] = - e - 1; -for ( let i = 1; i < 31; ++ i ) { + // normal number - _exponentTable[ i ] = i << 23; + } else if ( e <= 15 ) { -} + baseTable[ i ] = ( e + 15 ) << 10; + baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; -_exponentTable[ 31 ] = 0x47800000; -_exponentTable[ 32 ] = 0x80000000; -for ( let i = 33; i < 63; ++ i ) { + // large number (Infinity, -Infinity) - _exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); + } else if ( e < 128 ) { -} + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; -_exponentTable[ 63 ] = 0xc7800000; + // stay (NaN, Infinity, -Infinity) -for ( let i = 1; i < 64; ++ i ) { + } else { - if ( i !== 32 ) { + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; - _offsetTable[ i ] = 1024; + } } -} - -const LineStrip = 0; -const LinePieces = 1; -const NoColors = 0; -const FaceColors = 1; -const VertexColors = 2; - -function MeshFaceMaterial( materials ) { - - console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' ); - return materials; + // float16 to float32 helpers -} - -function MultiMaterial( materials = [] ) { + const mantissaTable = new Uint32Array( 2048 ); + const exponentTable = new Uint32Array( 64 ); + const offsetTable = new Uint32Array( 64 ); - console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' ); - materials.isMultiMaterial = true; - materials.materials = materials; - materials.clone = function () { + for ( let i = 1; i < 1024; ++ i ) { - return materials.slice(); - - }; + let m = i << 13; // zero pad mantissa bits + let e = 0; // zero exponent - return materials; + // normalized + while ( ( m & 0x00800000 ) === 0 ) { -} + m <<= 1; + e -= 0x00800000; // decrement exponent -class PointCloud extends Points { + } - constructor( geometry, material ) { + m &= ~ 0x00800000; // clear leading 1 bit + e += 0x38800000; // adjust bias - console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); - super( geometry, material ); + mantissaTable[ i ] = m | e; } -} - -class Particle extends Sprite { - - constructor( material ) { + for ( let i = 1024; i < 2048; ++ i ) { - console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' ); - super( material ); + mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); } -} - -class ParticleSystem extends Points { - - constructor( geometry, material ) { + for ( let i = 1; i < 31; ++ i ) { - console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); - super( geometry, material ); + exponentTable[ i ] = i << 23; } -} - -class PointCloudMaterial extends PointsMaterial { + exponentTable[ 31 ] = 0x47800000; + exponentTable[ 32 ] = 0x80000000; - constructor( parameters ) { + for ( let i = 33; i < 63; ++ i ) { - console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); - super( parameters ); + exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); } -} - -class ParticleBasicMaterial extends PointsMaterial { - - constructor( parameters ) { - - console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); - super( parameters ); - - } + exponentTable[ 63 ] = 0xc7800000; -} + for ( let i = 1; i < 64; ++ i ) { -class ParticleSystemMaterial extends PointsMaterial { + if ( i !== 32 ) { - constructor( parameters ) { + offsetTable[ i ] = 1024; - console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); - super( parameters ); + } } -} - -class Vertex extends Vector3 { - - constructor( x, y, z ) { - - console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); - super( x, y, z ); - - } + return { + floatView: floatView, + uint32View: uint32View, + baseTable: baseTable, + shiftTable: shiftTable, + mantissaTable: mantissaTable, + exponentTable: exponentTable, + offsetTable: offsetTable, + }; } -// - -class DynamicBufferAttribute extends BufferAttribute { - - constructor( array, itemSize ) { - - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' ); - super( array, itemSize ); - this.setUsage( DynamicDrawUsage ); - - } - -} +// float32 to float16 -class Int8Attribute extends Int8BufferAttribute { +function toHalfFloat( val ) { - constructor( array, itemSize ) { + if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); - console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' ); - super( array, itemSize ); + val = clamp( val, - 65504, 65504 ); - } + _floatView[ 0 ] = val; + const f = _uint32View[ 0 ]; + const e = ( f >> 23 ) & 0x1ff; + return _baseTable[ e ] + ( ( f & 0x007fffff ) >> _shiftTable[ e ] ); } -class Uint8Attribute extends Uint8BufferAttribute { +// float16 to float32 - constructor( array, itemSize ) { +function fromHalfFloat( val ) { - console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' ); - super( array, itemSize ); - - } + const m = val >> 10; + _uint32View[ 0 ] = _mantissaTable[ _offsetTable[ m ] + ( val & 0x3ff ) ] + _exponentTable[ m ]; + return _floatView[ 0 ]; } -class Uint8ClampedAttribute extends Uint8ClampedBufferAttribute { - - constructor( array, itemSize ) { - - console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' ); - super( array, itemSize ); - - } +var DataUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + toHalfFloat: toHalfFloat, + fromHalfFloat: fromHalfFloat +}); -} +// r133, c5bb5434555a3c3ddd784944a0a124f996fc721b -class Int16Attribute extends Int16BufferAttribute { +class ParametricGeometry extends BufferGeometry { - constructor( array, itemSize ) { + constructor() { - console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' ); - super( array, itemSize ); + console.error( 'THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js' ); + super(); } } -class Uint16Attribute extends Uint16BufferAttribute { - - constructor( array, itemSize ) { +// r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92 - console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' ); - super( array, itemSize ); - - } - -} - -class Int32Attribute extends Int32BufferAttribute { +class TextGeometry extends BufferGeometry { - constructor( array, itemSize ) { + constructor() { - console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' ); - super( array, itemSize ); + console.error( 'THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js' ); + super(); } } -class Uint32Attribute extends Uint32BufferAttribute { - - constructor( array, itemSize ) { +// r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92 - console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' ); - super( array, itemSize ); +function FontLoader() { - } + console.error( 'THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js' ); } -class Float32Attribute extends Float32BufferAttribute { - - constructor( array, itemSize ) { +// r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92 - console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' ); - super( array, itemSize ); +function Font() { - } + console.error( 'THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js' ); } -class Float64Attribute extends Float64BufferAttribute { +// r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0 - constructor( array, itemSize ) { - - console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' ); - super( array, itemSize ); +function ImmediateRenderObject() { - } + console.error( 'THREE.ImmediateRenderObject has been removed.' ); } -// - -Curve.create = function ( construct, getPoint ) { - - console.log( 'THREE.Curve.create() has been deprecated' ); - - construct.prototype = Object.create( Curve.prototype ); - construct.prototype.constructor = construct; - construct.prototype.getPoint = getPoint; - - return construct; - -}; - -// - -Path$1.prototype.fromPoints = function ( points ) { - - console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' ); - return this.setFromPoints( points ); - -}; - -// +// r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17 -class AxisHelper extends AxesHelper { +class WebGLMultisampleRenderTarget extends WebGLRenderTarget { - constructor( size ) { + constructor( width, height, options ) { - console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' ); - super( size ); + console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' ); + super( width, height, options ); + this.samples = 4; } } -class BoundingBoxHelper extends BoxHelper { +// r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce - constructor( object, color ) { - - console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' ); - super( object, color ); - - } - -} - -class EdgesHelper extends LineSegments { +class DataTexture2DArray extends DataArrayTexture { - constructor( object, hex ) { + constructor( data, width, height, depth ) { - console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' ); - super( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' ); + super( data, width, height, depth ); } } -GridHelper.prototype.setColors = function () { - - console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); - -}; - -SkeletonHelper.prototype.update = function () { - - console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' ); - -}; +// r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce -class WireframeHelper extends LineSegments { +class DataTexture3D extends Data3DTexture { - constructor( object, hex ) { + constructor( data, width, height, depth ) { - console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' ); - super( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' ); + super( data, width, height, depth ); } } -// - -Loader.prototype.extractUrlBase = function ( url ) { - - console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' ); - return LoaderUtils.extractUrlBase( url ); - -}; - -Loader.Handlers = { - - add: function ( /* regex, loader */ ) { - - console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' ); - - }, - - get: function ( /* file */ ) { - - console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' ); - - } - -}; - -class XHRLoader extends FileLoader { +if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - constructor( manager ) { + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { + revision: REVISION, + } } ) ); - console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' ); - super( manager ); +} - } +if ( typeof window !== 'undefined' ) { -} + if ( window.__THREE__ ) { -class BinaryTextureLoader extends DataTextureLoader { + console.warn( 'WARNING: Multiple instances of Three.js being imported.' ); - constructor( manager ) { + } else { - console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' ); - super( manager ); + window.__THREE__ = REVISION; } } -// - -Box2.prototype.center = function ( optionalTarget ) { - - console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); - -}; - -Box2.prototype.empty = function () { - - console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - -}; - -Box2.prototype.isIntersectionBox = function ( box ) { - - console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - -}; - -Box2.prototype.size = function ( optionalTarget ) { - - console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); - -}; - -// - -Box3.prototype.center = function ( optionalTarget ) { - - console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); - -}; - -Box3.prototype.empty = function () { - - console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - -}; - -Box3.prototype.isIntersectionBox = function ( box ) { - - console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - -}; - -Box3.prototype.isIntersectionSphere = function ( sphere ) { - - console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); - -}; - -Box3.prototype.size = function ( optionalTarget ) { - - console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); - -}; - -// - -Euler.prototype.toVector3 = function () { - - console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' ); - -}; - - -// - -Sphere.prototype.empty = function () { - - console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - -}; - -// - -Frustum$1.prototype.setFromMatrix = function ( m ) { - - console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' ); - return this.setFromProjectionMatrix( m ); - -}; - -// - -Line3.prototype.center = function ( optionalTarget ) { - - console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); - -}; - -// - -Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) { - - console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' ); - return this.toArray( array, offset ); - -}; - -Matrix3.prototype.multiplyVector3 = function ( vector ) { - - console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); - -}; - -Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) { - - console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); - -}; - -Matrix3.prototype.applyToBufferAttribute = function ( attribute ) { - - console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' ); - return attribute.applyMatrix3( this ); - -}; - -Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) { - - console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' ); - -}; - -Matrix3.prototype.getInverse = function ( matrix ) { - - console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' ); - return this.copy( matrix ).invert(); - -}; - -// - -Matrix4.prototype.extractPosition = function ( m ) { - - console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); - -}; - -Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) { - - console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' ); - return this.toArray( array, offset ); - -}; - -Matrix4.prototype.getPosition = function () { - - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - return new Vector3().setFromMatrixColumn( this, 3 ); - -}; - -Matrix4.prototype.setRotationFromQuaternion = function ( q ) { - - console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); - return this.makeRotationFromQuaternion( q ); - -}; - -Matrix4.prototype.multiplyToArray = function () { - - console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' ); - -}; - -Matrix4.prototype.multiplyVector3 = function ( vector ) { - - console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - -}; - -Matrix4.prototype.multiplyVector4 = function ( vector ) { - - console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - -}; - -Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) { - - console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); - -}; - -Matrix4.prototype.rotateAxis = function ( v ) { - - console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); - v.transformDirection( this ); - -}; - -Matrix4.prototype.crossVector = function ( vector ) { - - console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - -}; - -Matrix4.prototype.translate = function () { - - console.error( 'THREE.Matrix4: .translate() has been removed.' ); - -}; - -Matrix4.prototype.rotateX = function () { - - console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); - -}; - -Matrix4.prototype.rotateY = function () { - - console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); - -}; - -Matrix4.prototype.rotateZ = function () { - - console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); - -}; - -Matrix4.prototype.rotateByAxis = function () { - - console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); - -}; - -Matrix4.prototype.applyToBufferAttribute = function ( attribute ) { - - console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' ); - return attribute.applyMatrix4( this ); - -}; - -Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) { - - console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' ); - -}; - -Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) { - - console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' ); - return this.makePerspective( left, right, top, bottom, near, far ); - -}; - -Matrix4.prototype.getInverse = function ( matrix ) { - - console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' ); - return this.copy( matrix ).invert(); - -}; - -// - -Plane.prototype.isIntersectionLine = function ( line ) { - - console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); - return this.intersectsLine( line ); - -}; - -// - -Quaternion.prototype.multiplyVector3 = function ( vector ) { - - console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); - -}; - -Quaternion.prototype.inverse = function ( ) { - - console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' ); - return this.invert(); - -}; - -// - -Ray.prototype.isIntersectionBox = function ( box ) { - - console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - -}; - -Ray.prototype.isIntersectionPlane = function ( plane ) { - - console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); - return this.intersectsPlane( plane ); - -}; - -Ray.prototype.isIntersectionSphere = function ( sphere ) { - - console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); - -}; - -// - -Triangle.prototype.area = function () { - - console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' ); - return this.getArea(); - -}; - -Triangle.prototype.barycoordFromPoint = function ( point, target ) { - - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return this.getBarycoord( point, target ); - -}; - -Triangle.prototype.midpoint = function ( target ) { - - console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' ); - return this.getMidpoint( target ); - -}; - -Triangle.prototypenormal = function ( target ) { - - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return this.getNormal( target ); - -}; - -Triangle.prototype.plane = function ( target ) { - - console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' ); - return this.getPlane( target ); - -}; - -Triangle.barycoordFromPoint = function ( point, a, b, c, target ) { - - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return Triangle.getBarycoord( point, a, b, c, target ); - -}; - -Triangle.normal = function ( a, b, c, target ) { - - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return Triangle.getNormal( a, b, c, target ); - -}; - -// - -Shape.prototype.extractAllPoints = function ( divisions ) { - - console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' ); - return this.extractPoints( divisions ); - -}; - -Shape.prototype.extrude = function ( options ) { - - console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' ); - return new ExtrudeGeometry( this, options ); - -}; - -Shape.prototype.makeGeometry = function ( options ) { - - console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' ); - return new ShapeGeometry( this, options ); - -}; - -// - -Vector2.prototype.fromAttribute = function ( attribute, index, offset ) { - - console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); - -}; - -Vector2.prototype.distanceToManhattan = function ( v ) { - - console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); - -}; - -Vector2.prototype.lengthManhattan = function () { - - console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); - -}; - -// - -Vector3.prototype.setEulerFromRotationMatrix = function () { - - console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); - -}; - -Vector3.prototype.setEulerFromQuaternion = function () { - - console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); - -}; - -Vector3.prototype.getPositionFromMatrix = function ( m ) { - - console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); - return this.setFromMatrixPosition( m ); - -}; - -Vector3.prototype.getScaleFromMatrix = function ( m ) { - - console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); - return this.setFromMatrixScale( m ); - -}; - -Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) { - - console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); - return this.setFromMatrixColumn( matrix, index ); - -}; - -Vector3.prototype.applyProjection = function ( m ) { - - console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' ); - return this.applyMatrix4( m ); - -}; - -Vector3.prototype.fromAttribute = function ( attribute, index, offset ) { - - console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); - -}; - -Vector3.prototype.distanceToManhattan = function ( v ) { - - console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); - -}; - -Vector3.prototype.lengthManhattan = function () { - - console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); - -}; - -// - -Vector4.prototype.fromAttribute = function ( attribute, index, offset ) { - - console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); - -}; - -Vector4.prototype.lengthManhattan = function () { - - console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); - -}; - -// - -Object3D.prototype.getChildByName = function ( name ) { - - console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name ); - -}; - -Object3D.prototype.renderDepth = function () { - - console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); - -}; - -Object3D.prototype.translate = function ( distance, axis ) { - - console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); - return this.translateOnAxis( axis, distance ); - -}; - -Object3D.prototype.getWorldRotation = function () { - - console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' ); - -}; - -Object3D.prototype.applyMatrix = function ( matrix ) { - - console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' ); - return this.applyMatrix4( matrix ); - -}; - -Object.defineProperties( Object3D.prototype, { - - eulerOrder: { - get: function () { - - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - return this.rotation.order; - - }, - set: function ( value ) { - - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - this.rotation.order = value; - - } - }, - useQuaternion: { - get: function () { - - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - - }, - set: function () { - - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - - } - } - -} ); - -Mesh.prototype.setDrawMode = function () { - - console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); - -}; - -Object.defineProperties( Mesh.prototype, { - - drawMode: { - get: function () { - - console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' ); - return TrianglesDrawMode; - - }, - set: function () { - - console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); - - } - } - -} ); - -SkinnedMesh.prototype.initBones = function () { - - console.error( 'THREE.SkinnedMesh: initBones() has been removed.' ); - -}; - -// - -PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { - - console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' + - 'Use .setFocalLength and .filmGauge for a photographic setup.' ); - - if ( filmGauge !== undefined ) this.filmGauge = filmGauge; - this.setFocalLength( focalLength ); - -}; - -// - -Object.defineProperties( Light.prototype, { - onlyShadow: { - set: function () { - - console.warn( 'THREE.Light: .onlyShadow has been removed.' ); - - } - }, - shadowCameraFov: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); - this.shadow.camera.fov = value; - - } - }, - shadowCameraLeft: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); - this.shadow.camera.left = value; - - } - }, - shadowCameraRight: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); - this.shadow.camera.right = value; - - } - }, - shadowCameraTop: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); - this.shadow.camera.top = value; - - } - }, - shadowCameraBottom: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); - this.shadow.camera.bottom = value; - - } - }, - shadowCameraNear: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); - this.shadow.camera.near = value; - - } - }, - shadowCameraFar: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); - this.shadow.camera.far = value; - - } - }, - shadowCameraVisible: { - set: function () { - - console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); - - } - }, - shadowBias: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); - this.shadow.bias = value; - - } - }, - shadowDarkness: { - set: function () { - - console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); - - } - }, - shadowMapWidth: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); - this.shadow.mapSize.width = value; - - } - }, - shadowMapHeight: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); - this.shadow.mapSize.height = value; - - } - } -} ); - -// - -Object.defineProperties( BufferAttribute.prototype, { - - length: { - get: function () { - - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' ); - return this.array.length; - - } - }, - dynamic: { - get: function () { - - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - return this.usage === DynamicDrawUsage; - - }, - set: function ( /* value */ ) { - - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - this.setUsage( DynamicDrawUsage ); - - } - } - -} ); - -BufferAttribute.prototype.setDynamic = function ( value ) { - - console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); - return this; - -}; - -BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) { - - console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' ); - -}, - -BufferAttribute.prototype.setArray = function ( /* array */ ) { - - console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); - -}; - -// - -BufferGeometry.prototype.addIndex = function ( index ) { - - console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); - this.setIndex( index ); - -}; - -BufferGeometry.prototype.addAttribute = function ( name, attribute ) { - - console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' ); - - if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) { - - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - - return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); - - } - - if ( name === 'index' ) { - - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); - - return this; - - } - - return this.setAttribute( name, attribute ); - -}; - -BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) { - - if ( indexOffset !== undefined ) { - - console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); - - } - - console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); - this.addGroup( start, count ); - -}; - -BufferGeometry.prototype.clearDrawCalls = function () { - - console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); - this.clearGroups(); - -}; - -BufferGeometry.prototype.computeOffsets = function () { - - console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); - -}; - -BufferGeometry.prototype.removeAttribute = function ( name ) { - - console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' ); - - return this.deleteAttribute( name ); - -}; - -BufferGeometry.prototype.applyMatrix = function ( matrix ) { - - console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' ); - return this.applyMatrix4( matrix ); - -}; - -Object.defineProperties( BufferGeometry.prototype, { - - drawcalls: { - get: function () { - - console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); - return this.groups; - - } - }, - offsets: { - get: function () { - - console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); - return this.groups; - - } - } - -} ); - -InterleavedBuffer.prototype.setDynamic = function ( value ) { - - console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); - return this; - -}; - -InterleavedBuffer.prototype.setArray = function ( /* array */ ) { - - console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); - -}; - -// - -ExtrudeGeometry.prototype.getArrays = function () { - - console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' ); - -}; - -ExtrudeGeometry.prototype.addShapeList = function () { - - console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' ); - -}; - -ExtrudeGeometry.prototype.addShape = function () { - - console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' ); - -}; - -// - -Scene$1.prototype.dispose = function () { - - console.error( 'THREE.Scene: .dispose() has been removed.' ); - -}; - -// - -Uniform.prototype.onUpdate = function () { - - console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' ); - return this; - -}; - -// - -Object.defineProperties( Material.prototype, { - - wrapAround: { - get: function () { - - console.warn( 'THREE.Material: .wrapAround has been removed.' ); - - }, - set: function () { - - console.warn( 'THREE.Material: .wrapAround has been removed.' ); - - } - }, - - overdraw: { - get: function () { - - console.warn( 'THREE.Material: .overdraw has been removed.' ); - - }, - set: function () { - - console.warn( 'THREE.Material: .overdraw has been removed.' ); - - } - }, - - wrapRGB: { - get: function () { - - console.warn( 'THREE.Material: .wrapRGB has been removed.' ); - return new Color(); - - } - }, - - shading: { - get: function () { - - console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - - }, - set: function ( value ) { - - console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - this.flatShading = ( value === FlatShading ); - - } - }, - - stencilMask: { - get: function () { - - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - return this.stencilFuncMask; - - }, - set: function ( value ) { - - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - this.stencilFuncMask = value; - - } - }, - - vertexTangents: { - get: function () { - - console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' ); - - }, - set: function () { - - console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' ); - - } - }, - -} ); - -Object.defineProperties( ShaderMaterial.prototype, { - - derivatives: { - get: function () { - - console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - return this.extensions.derivatives; - - }, - set: function ( value ) { - - console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - this.extensions.derivatives = value; - - } - } - -} ); - -// - -WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) { - - console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' ); - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); - -}; - -WebGLRenderer.prototype.animate = function ( callback ) { - - console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' ); - this.setAnimationLoop( callback ); - -}; - -WebGLRenderer.prototype.getCurrentRenderTarget = function () { - - console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' ); - return this.getRenderTarget(); - -}; - -WebGLRenderer.prototype.getMaxAnisotropy = function () { - - console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' ); - return this.capabilities.getMaxAnisotropy(); - -}; - -WebGLRenderer.prototype.getPrecision = function () { - - console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' ); - return this.capabilities.precision; - -}; - -WebGLRenderer.prototype.resetGLState = function () { - - console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' ); - return this.state.reset(); - -}; - -WebGLRenderer.prototype.supportsFloatTextures = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); - return this.extensions.get( 'OES_texture_float' ); - -}; - -WebGLRenderer.prototype.supportsHalfFloatTextures = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); - return this.extensions.get( 'OES_texture_half_float' ); - -}; - -WebGLRenderer.prototype.supportsStandardDerivatives = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); - return this.extensions.get( 'OES_standard_derivatives' ); - -}; - -WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); - -}; - -WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - -}; - -WebGLRenderer.prototype.supportsBlendMinMax = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); - return this.extensions.get( 'EXT_blend_minmax' ); - -}; - -WebGLRenderer.prototype.supportsVertexTextures = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' ); - return this.capabilities.vertexTextures; - -}; - -WebGLRenderer.prototype.supportsInstancedArrays = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); - return this.extensions.get( 'ANGLE_instanced_arrays' ); - -}; - -WebGLRenderer.prototype.enableScissorTest = function ( boolean ) { - - console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); - this.setScissorTest( boolean ); - -}; - -WebGLRenderer.prototype.initMaterial = function () { - - console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); - -}; - -WebGLRenderer.prototype.addPrePlugin = function () { - - console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); - -}; - -WebGLRenderer.prototype.addPostPlugin = function () { - - console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); - -}; - -WebGLRenderer.prototype.updateShadowMap = function () { - - console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); - -}; - -WebGLRenderer.prototype.setFaceCulling = function () { - - console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' ); - -}; - -WebGLRenderer.prototype.allocTextureUnit = function () { - - console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' ); - -}; - -WebGLRenderer.prototype.setTexture = function () { - - console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' ); - -}; - -WebGLRenderer.prototype.setTexture2D = function () { - - console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' ); - -}; - -WebGLRenderer.prototype.setTextureCube = function () { - - console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' ); - -}; - -WebGLRenderer.prototype.getActiveMipMapLevel = function () { - - console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' ); - return this.getActiveMipmapLevel(); - -}; - -Object.defineProperties( WebGLRenderer.prototype, { - - shadowMapEnabled: { - get: function () { - - return this.shadowMap.enabled; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); - this.shadowMap.enabled = value; - - } - }, - shadowMapType: { - get: function () { - - return this.shadowMap.type; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); - this.shadowMap.type = value; - - } - }, - shadowMapCullFace: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; - - }, - set: function ( /* value */ ) { - - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); - - } - }, - context: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' ); - return this.getContext(); - - } - }, - vr: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' ); - return this.xr; - - } - }, - gammaInput: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); - return false; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); - - } - }, - gammaOutput: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); - return false; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); - this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding; - - } - }, - toneMappingWhitePoint: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' ); - return 1.0; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' ); - - } - }, - gammaFactor: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); - return 2; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); - - } - } -} ); - -Object.defineProperties( WebGLShadowMap.prototype, { - - cullFace: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; - - }, - set: function ( /* cullFace */ ) { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); - - } - }, - renderReverseSided: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); - return undefined; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); - - } - }, - renderSingleSided: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); - return undefined; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); - - } - } - -} ); - -class WebGLRenderTargetCube extends WebGLCubeRenderTarget { - - constructor( width, height, options ) { - - console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' ); - super( width, options ); - - } - -} - -// - -Object.defineProperties( WebGLRenderTarget.prototype, { - - wrapS: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - return this.texture.wrapS; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - this.texture.wrapS = value; - - } - }, - wrapT: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - return this.texture.wrapT; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - this.texture.wrapT = value; - - } - }, - magFilter: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - return this.texture.magFilter; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - this.texture.magFilter = value; - - } - }, - minFilter: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - return this.texture.minFilter; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - this.texture.minFilter = value; - - } - }, - anisotropy: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - return this.texture.anisotropy; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - this.texture.anisotropy = value; - - } - }, - offset: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - return this.texture.offset; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - this.texture.offset = value; - - } - }, - repeat: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - return this.texture.repeat; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - this.texture.repeat = value; - - } - }, - format: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - return this.texture.format; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - this.texture.format = value; - - } - }, - type: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - return this.texture.type; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - this.texture.type = value; - - } - }, - generateMipmaps: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - return this.texture.generateMipmaps; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - this.texture.generateMipmaps = value; - - } - } - -} ); - -// - -Audio.prototype.load = function ( file ) { - - console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' ); - const scope = this; - const audioLoader = new AudioLoader(); - audioLoader.load( file, function ( buffer ) { - - scope.setBuffer( buffer ); - - } ); - return this; - -}; - - -AudioAnalyser.prototype.getData = function () { - - console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); - return this.getFrequencyData(); - -}; - -// - -CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) { - - console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' ); - return this.update( renderer, scene ); - -}; - -CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) { - - console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' ); - return this.renderTarget.clear( renderer, color, depth, stencil ); - -}; - -ImageUtils.crossOrigin = undefined; - -ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) { - - console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); - - const loader = new TextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); - - const texture = loader.load( url, onLoad, undefined, onError ); - - if ( mapping ) texture.mapping = mapping; - - return texture; - -}; - -ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) { - - console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); - - const loader = new CubeTextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); - - const texture = loader.load( urls, onLoad, undefined, onError ); - - if ( mapping ) texture.mapping = mapping; - - return texture; - -}; - -ImageUtils.loadCompressedTexture = function () { - - console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); - -}; - -ImageUtils.loadCompressedTextureCube = function () { - - console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); - -}; - -// - -function CanvasRenderer() { - - console.error( 'THREE.CanvasRenderer has been removed' ); - -} - -// - -function JSONLoader() { - - console.error( 'THREE.JSONLoader has been removed.' ); - -} - -// - -const SceneUtils = { - - createMultiMaterialObject: function ( /* geometry, materials */ ) { - - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); - - }, - - detach: function ( /* child, parent, scene */ ) { - - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); - - }, - - attach: function ( /* child, scene, parent */ ) { - - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); - - } - -}; - -// - -function LensFlare() { - - console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' ); - -} - -// - -class ParametricGeometry extends BufferGeometry { - - constructor() { - - console.error( 'THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js' ); - super(); - - } - -} - -class TextGeometry extends BufferGeometry { - - constructor() { - - console.error( 'THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js' ); - super(); - - } - -} - -function FontLoader() { - - console.error( 'THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js' ); - -} - -function Font$2() { - - console.error( 'THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js' ); - -} - -function ImmediateRenderObject() { - - console.error( 'THREE.ImmediateRenderObject has been removed.' ); - -} - -class WebGLMultisampleRenderTarget extends WebGLRenderTarget { - - constructor( width, height, options ) { - - console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' ); - super( width, height, options ); - this.samples = 4; - - } - -} - -class DataTexture2DArray extends DataArrayTexture { - - constructor( data, width, height, depth ) { - - console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' ); - super( data, width, height, depth ); - - } - -} - -class DataTexture3D extends Data3DTexture { - - constructor( data, width, height, depth ) { - - console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' ); - super( data, width, height, depth ); - - } - -} - -if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - - __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { - revision: REVISION, - } } ) ); - -} - -if ( typeof window !== 'undefined' ) { - - if ( window.__THREE__ ) { - - console.warn( 'WARNING: Multiple instances of Three.js being imported.' ); - - } else { - - window.__THREE__ = REVISION; - - } - -} - -var THREE = /*#__PURE__*/Object.freeze({ - __proto__: null, - ACESFilmicToneMapping: ACESFilmicToneMapping, - AddEquation: AddEquation, - AddOperation: AddOperation, - AdditiveAnimationBlendMode: AdditiveAnimationBlendMode, - AdditiveBlending: AdditiveBlending, - AlphaFormat: AlphaFormat, - AlwaysDepth: AlwaysDepth, - AlwaysStencilFunc: AlwaysStencilFunc, - AmbientLight: AmbientLight$1, - AmbientLightProbe: AmbientLightProbe, - AnimationClip: AnimationClip, - AnimationLoader: AnimationLoader, - AnimationMixer: AnimationMixer, - AnimationObjectGroup: AnimationObjectGroup, - AnimationUtils: AnimationUtils, - ArcCurve: ArcCurve, - ArrayCamera: ArrayCamera, - ArrowHelper: ArrowHelper, - Audio: Audio, - AudioAnalyser: AudioAnalyser, - AudioContext: AudioContext, - AudioListener: AudioListener, - AudioLoader: AudioLoader, - AxesHelper: AxesHelper, - AxisHelper: AxisHelper, - BackSide: BackSide, - BasicDepthPacking: BasicDepthPacking, - BasicShadowMap: BasicShadowMap, - BinaryTextureLoader: BinaryTextureLoader, - Bone: Bone, - BooleanKeyframeTrack: BooleanKeyframeTrack, - BoundingBoxHelper: BoundingBoxHelper, - Box2: Box2, - Box3: Box3, - Box3Helper: Box3Helper, - BoxBufferGeometry: BoxGeometry, - BoxGeometry: BoxGeometry, - BoxHelper: BoxHelper, - BufferAttribute: BufferAttribute, - BufferGeometry: BufferGeometry, - BufferGeometryLoader: BufferGeometryLoader, - ByteType: ByteType, - Cache: Cache, - Camera: Camera, - CameraHelper: CameraHelper, - CanvasRenderer: CanvasRenderer, - CanvasTexture: CanvasTexture, - CapsuleBufferGeometry: CapsuleGeometry, - CapsuleGeometry: CapsuleGeometry, - CatmullRomCurve3: CatmullRomCurve3, - CineonToneMapping: CineonToneMapping, - CircleBufferGeometry: CircleGeometry, - CircleGeometry: CircleGeometry, - ClampToEdgeWrapping: ClampToEdgeWrapping, - Clock: Clock, - Color: Color, - ColorKeyframeTrack: ColorKeyframeTrack, - ColorManagement: ColorManagement, - CompressedTexture: CompressedTexture, - CompressedTextureLoader: CompressedTextureLoader, - ConeBufferGeometry: ConeGeometry, - ConeGeometry: ConeGeometry, - CubeCamera: CubeCamera, - CubeReflectionMapping: CubeReflectionMapping, - CubeRefractionMapping: CubeRefractionMapping, - CubeTexture: CubeTexture, - CubeTextureLoader: CubeTextureLoader, - CubeUVReflectionMapping: CubeUVReflectionMapping, - CubicBezierCurve: CubicBezierCurve, - CubicBezierCurve3: CubicBezierCurve3, - CubicInterpolant: CubicInterpolant, - CullFaceBack: CullFaceBack, - CullFaceFront: CullFaceFront, - CullFaceFrontBack: CullFaceFrontBack, - CullFaceNone: CullFaceNone, - Curve: Curve, - CurvePath: CurvePath, - CustomBlending: CustomBlending, - CustomToneMapping: CustomToneMapping, - CylinderBufferGeometry: CylinderGeometry, - CylinderGeometry: CylinderGeometry, - Cylindrical: Cylindrical, - Data3DTexture: Data3DTexture, - DataArrayTexture: DataArrayTexture, - DataTexture: DataTexture, - DataTexture2DArray: DataTexture2DArray, - DataTexture3D: DataTexture3D, - DataTextureLoader: DataTextureLoader, - DataUtils: DataUtils, - DecrementStencilOp: DecrementStencilOp, - DecrementWrapStencilOp: DecrementWrapStencilOp, - DefaultLoadingManager: DefaultLoadingManager, - DepthFormat: DepthFormat, - DepthStencilFormat: DepthStencilFormat, - DepthTexture: DepthTexture, - DirectionalLight: DirectionalLight$1, - DirectionalLightHelper: DirectionalLightHelper, - DiscreteInterpolant: DiscreteInterpolant, - DodecahedronBufferGeometry: DodecahedronGeometry, - DodecahedronGeometry: DodecahedronGeometry, - DoubleSide: DoubleSide, - DstAlphaFactor: DstAlphaFactor, - DstColorFactor: DstColorFactor, - DynamicBufferAttribute: DynamicBufferAttribute, - DynamicCopyUsage: DynamicCopyUsage, - DynamicDrawUsage: DynamicDrawUsage, - DynamicReadUsage: DynamicReadUsage, - EdgesGeometry: EdgesGeometry, - EdgesHelper: EdgesHelper, - EllipseCurve: EllipseCurve, - EqualDepth: EqualDepth, - EqualStencilFunc: EqualStencilFunc, - EquirectangularReflectionMapping: EquirectangularReflectionMapping, - EquirectangularRefractionMapping: EquirectangularRefractionMapping, - Euler: Euler, - EventDispatcher: EventDispatcher, - ExtrudeBufferGeometry: ExtrudeGeometry, - ExtrudeGeometry: ExtrudeGeometry, - FaceColors: FaceColors, - FileLoader: FileLoader, - FlatShading: FlatShading, - Float16BufferAttribute: Float16BufferAttribute, - Float32Attribute: Float32Attribute, - Float32BufferAttribute: Float32BufferAttribute, - Float64Attribute: Float64Attribute, - Float64BufferAttribute: Float64BufferAttribute, - FloatType: FloatType, - Fog: Fog, - FogExp2: FogExp2, - Font: Font$2, - FontLoader: FontLoader, - FramebufferTexture: FramebufferTexture, - FrontSide: FrontSide, - Frustum: Frustum$1, - GLBufferAttribute: GLBufferAttribute, - GLSL1: GLSL1, - GLSL3: GLSL3, - GreaterDepth: GreaterDepth, - GreaterEqualDepth: GreaterEqualDepth, - GreaterEqualStencilFunc: GreaterEqualStencilFunc, - GreaterStencilFunc: GreaterStencilFunc, - GridHelper: GridHelper, - Group: Group, - HalfFloatType: HalfFloatType, - HemisphereLight: HemisphereLight, - HemisphereLightHelper: HemisphereLightHelper, - HemisphereLightProbe: HemisphereLightProbe, - IcosahedronBufferGeometry: IcosahedronGeometry, - IcosahedronGeometry: IcosahedronGeometry, - ImageBitmapLoader: ImageBitmapLoader, - ImageLoader: ImageLoader, - ImageUtils: ImageUtils, - ImmediateRenderObject: ImmediateRenderObject, - IncrementStencilOp: IncrementStencilOp, - IncrementWrapStencilOp: IncrementWrapStencilOp, - InstancedBufferAttribute: InstancedBufferAttribute, - InstancedBufferGeometry: InstancedBufferGeometry, - InstancedInterleavedBuffer: InstancedInterleavedBuffer, - InstancedMesh: InstancedMesh, - Int16Attribute: Int16Attribute, - Int16BufferAttribute: Int16BufferAttribute, - Int32Attribute: Int32Attribute, - Int32BufferAttribute: Int32BufferAttribute, - Int8Attribute: Int8Attribute, - Int8BufferAttribute: Int8BufferAttribute, - IntType: IntType, - InterleavedBuffer: InterleavedBuffer, - InterleavedBufferAttribute: InterleavedBufferAttribute, - Interpolant: Interpolant, - InterpolateDiscrete: InterpolateDiscrete, - InterpolateLinear: InterpolateLinear, - InterpolateSmooth: InterpolateSmooth, - InvertStencilOp: InvertStencilOp, - JSONLoader: JSONLoader, - KeepStencilOp: KeepStencilOp, - KeyframeTrack: KeyframeTrack, - LOD: LOD, - LatheBufferGeometry: LatheGeometry, - LatheGeometry: LatheGeometry, - Layers: Layers, - LensFlare: LensFlare, - LessDepth: LessDepth, - LessEqualDepth: LessEqualDepth, - LessEqualStencilFunc: LessEqualStencilFunc, - LessStencilFunc: LessStencilFunc, - Light: Light, - LightProbe: LightProbe, - Line: Line$2, - Line3: Line3, - LineBasicMaterial: LineBasicMaterial, - LineCurve: LineCurve, - LineCurve3: LineCurve3, - LineDashedMaterial: LineDashedMaterial, - LineLoop: LineLoop, - LinePieces: LinePieces, - LineSegments: LineSegments, - LineStrip: LineStrip, - LinearEncoding: LinearEncoding, - LinearFilter: LinearFilter, - LinearInterpolant: LinearInterpolant, - LinearMipMapLinearFilter: LinearMipMapLinearFilter, - LinearMipMapNearestFilter: LinearMipMapNearestFilter, - LinearMipmapLinearFilter: LinearMipmapLinearFilter, - LinearMipmapNearestFilter: LinearMipmapNearestFilter, - LinearSRGBColorSpace: LinearSRGBColorSpace, - LinearToneMapping: LinearToneMapping, - Loader: Loader, - LoaderUtils: LoaderUtils, - LoadingManager: LoadingManager, - LoopOnce: LoopOnce, - LoopPingPong: LoopPingPong, - LoopRepeat: LoopRepeat, - LuminanceAlphaFormat: LuminanceAlphaFormat, - LuminanceFormat: LuminanceFormat, - MOUSE: MOUSE, - Material: Material, - MaterialLoader: MaterialLoader, - Math: MathUtils, - MathUtils: MathUtils, - Matrix3: Matrix3, - Matrix4: Matrix4, - MaxEquation: MaxEquation, - Mesh: Mesh, - MeshBasicMaterial: MeshBasicMaterial, - MeshDepthMaterial: MeshDepthMaterial, - MeshDistanceMaterial: MeshDistanceMaterial, - MeshFaceMaterial: MeshFaceMaterial, - MeshLambertMaterial: MeshLambertMaterial, - MeshMatcapMaterial: MeshMatcapMaterial, - MeshNormalMaterial: MeshNormalMaterial, - MeshPhongMaterial: MeshPhongMaterial, - MeshPhysicalMaterial: MeshPhysicalMaterial, - MeshStandardMaterial: MeshStandardMaterial, - MeshToonMaterial: MeshToonMaterial, - MinEquation: MinEquation, - MirroredRepeatWrapping: MirroredRepeatWrapping, - MixOperation: MixOperation, - MultiMaterial: MultiMaterial, - MultiplyBlending: MultiplyBlending, - MultiplyOperation: MultiplyOperation, - NearestFilter: NearestFilter, - NearestMipMapLinearFilter: NearestMipMapLinearFilter, - NearestMipMapNearestFilter: NearestMipMapNearestFilter, - NearestMipmapLinearFilter: NearestMipmapLinearFilter, - NearestMipmapNearestFilter: NearestMipmapNearestFilter, - NeverDepth: NeverDepth, - NeverStencilFunc: NeverStencilFunc, - NoBlending: NoBlending, - NoColorSpace: NoColorSpace, - NoColors: NoColors, - NoToneMapping: NoToneMapping, - NormalAnimationBlendMode: NormalAnimationBlendMode, - NormalBlending: NormalBlending, - NotEqualDepth: NotEqualDepth, - NotEqualStencilFunc: NotEqualStencilFunc, - NumberKeyframeTrack: NumberKeyframeTrack, - Object3D: Object3D, - ObjectLoader: ObjectLoader, - ObjectSpaceNormalMap: ObjectSpaceNormalMap, - OctahedronBufferGeometry: OctahedronGeometry, - OctahedronGeometry: OctahedronGeometry, - OneFactor: OneFactor, - OneMinusDstAlphaFactor: OneMinusDstAlphaFactor, - OneMinusDstColorFactor: OneMinusDstColorFactor, - OneMinusSrcAlphaFactor: OneMinusSrcAlphaFactor, - OneMinusSrcColorFactor: OneMinusSrcColorFactor, - OrthographicCamera: OrthographicCamera, - PCFShadowMap: PCFShadowMap, - PCFSoftShadowMap: PCFSoftShadowMap, - PMREMGenerator: PMREMGenerator, - ParametricGeometry: ParametricGeometry, - Particle: Particle, - ParticleBasicMaterial: ParticleBasicMaterial, - ParticleSystem: ParticleSystem, - ParticleSystemMaterial: ParticleSystemMaterial, - Path: Path$1, - PerspectiveCamera: PerspectiveCamera, - Plane: Plane, - PlaneBufferGeometry: PlaneGeometry, - PlaneGeometry: PlaneGeometry, - PlaneHelper: PlaneHelper, - PointCloud: PointCloud, - PointCloudMaterial: PointCloudMaterial, - PointLight: PointLight, - PointLightHelper: PointLightHelper, - Points: Points, - PointsMaterial: PointsMaterial, - PolarGridHelper: PolarGridHelper, - PolyhedronBufferGeometry: PolyhedronGeometry, - PolyhedronGeometry: PolyhedronGeometry, - PositionalAudio: PositionalAudio, - PropertyBinding: PropertyBinding, - PropertyMixer: PropertyMixer, - QuadraticBezierCurve: QuadraticBezierCurve, - QuadraticBezierCurve3: QuadraticBezierCurve3, - Quaternion: Quaternion, - QuaternionKeyframeTrack: QuaternionKeyframeTrack, - QuaternionLinearInterpolant: QuaternionLinearInterpolant, - REVISION: REVISION, - RGBADepthPacking: RGBADepthPacking, - RGBAFormat: RGBAFormat, - RGBAIntegerFormat: RGBAIntegerFormat, - RGBA_ASTC_10x10_Format: RGBA_ASTC_10x10_Format, - RGBA_ASTC_10x5_Format: RGBA_ASTC_10x5_Format, - RGBA_ASTC_10x6_Format: RGBA_ASTC_10x6_Format, - RGBA_ASTC_10x8_Format: RGBA_ASTC_10x8_Format, - RGBA_ASTC_12x10_Format: RGBA_ASTC_12x10_Format, - RGBA_ASTC_12x12_Format: RGBA_ASTC_12x12_Format, - RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format, - RGBA_ASTC_5x4_Format: RGBA_ASTC_5x4_Format, - RGBA_ASTC_5x5_Format: RGBA_ASTC_5x5_Format, - RGBA_ASTC_6x5_Format: RGBA_ASTC_6x5_Format, - RGBA_ASTC_6x6_Format: RGBA_ASTC_6x6_Format, - RGBA_ASTC_8x5_Format: RGBA_ASTC_8x5_Format, - RGBA_ASTC_8x6_Format: RGBA_ASTC_8x6_Format, - RGBA_ASTC_8x8_Format: RGBA_ASTC_8x8_Format, - RGBA_BPTC_Format: RGBA_BPTC_Format, - RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format, - RGBA_PVRTC_2BPPV1_Format: RGBA_PVRTC_2BPPV1_Format, - RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format, - RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format, - RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format, - RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format, - RGBFormat: RGBFormat, - RGB_ETC1_Format: RGB_ETC1_Format, - RGB_ETC2_Format: RGB_ETC2_Format, - RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format, - RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format, - RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format, - RGFormat: RGFormat, - RGIntegerFormat: RGIntegerFormat, - RawShaderMaterial: RawShaderMaterial, - Ray: Ray, - Raycaster: Raycaster, - RectAreaLight: RectAreaLight, - RedFormat: RedFormat, - RedIntegerFormat: RedIntegerFormat, - ReinhardToneMapping: ReinhardToneMapping, - RepeatWrapping: RepeatWrapping, - ReplaceStencilOp: ReplaceStencilOp, - ReverseSubtractEquation: ReverseSubtractEquation, - RingBufferGeometry: RingGeometry, - RingGeometry: RingGeometry, - SRGBColorSpace: SRGBColorSpace, - Scene: Scene$1, - SceneUtils: SceneUtils, - ShaderChunk: ShaderChunk, - ShaderLib: ShaderLib, - ShaderMaterial: ShaderMaterial, - ShadowMaterial: ShadowMaterial, - Shape: Shape, - ShapeBufferGeometry: ShapeGeometry, - ShapeGeometry: ShapeGeometry, - ShapePath: ShapePath, - ShapeUtils: ShapeUtils, - ShortType: ShortType, - Skeleton: Skeleton, - SkeletonHelper: SkeletonHelper, - SkinnedMesh: SkinnedMesh, - SmoothShading: SmoothShading, - Source: Source, - Sphere: Sphere, - SphereBufferGeometry: SphereGeometry, - SphereGeometry: SphereGeometry, - Spherical: Spherical, - SphericalHarmonics3: SphericalHarmonics3, - SplineCurve: SplineCurve, - SpotLight: SpotLight, - SpotLightHelper: SpotLightHelper, - Sprite: Sprite, - SpriteMaterial: SpriteMaterial, - SrcAlphaFactor: SrcAlphaFactor, - SrcAlphaSaturateFactor: SrcAlphaSaturateFactor, - SrcColorFactor: SrcColorFactor, - StaticCopyUsage: StaticCopyUsage, - StaticDrawUsage: StaticDrawUsage, - StaticReadUsage: StaticReadUsage, - StereoCamera: StereoCamera, - StreamCopyUsage: StreamCopyUsage, - StreamDrawUsage: StreamDrawUsage, - StreamReadUsage: StreamReadUsage, - StringKeyframeTrack: StringKeyframeTrack, - SubtractEquation: SubtractEquation, - SubtractiveBlending: SubtractiveBlending, - TOUCH: TOUCH, - TangentSpaceNormalMap: TangentSpaceNormalMap, - TetrahedronBufferGeometry: TetrahedronGeometry, - TetrahedronGeometry: TetrahedronGeometry, - TextGeometry: TextGeometry, - Texture: Texture, - TextureLoader: TextureLoader, - TorusBufferGeometry: TorusGeometry, - TorusGeometry: TorusGeometry, - TorusKnotBufferGeometry: TorusKnotGeometry, - TorusKnotGeometry: TorusKnotGeometry, - Triangle: Triangle, - TriangleFanDrawMode: TriangleFanDrawMode, - TriangleStripDrawMode: TriangleStripDrawMode, - TrianglesDrawMode: TrianglesDrawMode, - TubeBufferGeometry: TubeGeometry, - TubeGeometry: TubeGeometry, - UVMapping: UVMapping, - Uint16Attribute: Uint16Attribute, - Uint16BufferAttribute: Uint16BufferAttribute, - Uint32Attribute: Uint32Attribute, - Uint32BufferAttribute: Uint32BufferAttribute, - Uint8Attribute: Uint8Attribute, - Uint8BufferAttribute: Uint8BufferAttribute, - Uint8ClampedAttribute: Uint8ClampedAttribute, - Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute, - Uniform: Uniform, - UniformsLib: UniformsLib, - UniformsUtils: UniformsUtils, - UnsignedByteType: UnsignedByteType, - UnsignedInt248Type: UnsignedInt248Type, - UnsignedIntType: UnsignedIntType, - UnsignedShort4444Type: UnsignedShort4444Type, - UnsignedShort5551Type: UnsignedShort5551Type, - UnsignedShortType: UnsignedShortType, - VSMShadowMap: VSMShadowMap, - Vector2: Vector2, - Vector3: Vector3, - Vector4: Vector4, - VectorKeyframeTrack: VectorKeyframeTrack, - Vertex: Vertex, - VertexColors: VertexColors, - VideoTexture: VideoTexture, - WebGL1Renderer: WebGL1Renderer, - WebGL3DRenderTarget: WebGL3DRenderTarget, - WebGLArrayRenderTarget: WebGLArrayRenderTarget, - WebGLCubeRenderTarget: WebGLCubeRenderTarget, - WebGLMultipleRenderTargets: WebGLMultipleRenderTargets, - WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget, - WebGLRenderTarget: WebGLRenderTarget, - WebGLRenderTargetCube: WebGLRenderTargetCube, - WebGLRenderer: WebGLRenderer, - WebGLUtils: WebGLUtils, - WireframeGeometry: WireframeGeometry, - WireframeHelper: WireframeHelper, - WrapAroundEnding: WrapAroundEnding, - XHRLoader: XHRLoader, - ZeroCurvatureEnding: ZeroCurvatureEnding, - ZeroFactor: ZeroFactor, - ZeroSlopeEnding: ZeroSlopeEnding, - ZeroStencilOp: ZeroStencilOp, - _SRGBAFormat: _SRGBAFormat, - sRGBEncoding: sRGBEncoding -}); - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -var constants$1 = {exports: {}}; - -var reactReconcilerConstants_production_min = {}; - -/** - * @license React - * react-reconciler-constants.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredReactReconcilerConstants_production_min; - -function requireReactReconcilerConstants_production_min () { - if (hasRequiredReactReconcilerConstants_production_min) return reactReconcilerConstants_production_min; - hasRequiredReactReconcilerConstants_production_min = 1; -reactReconcilerConstants_production_min.ConcurrentRoot=1;reactReconcilerConstants_production_min.ContinuousEventPriority=4;reactReconcilerConstants_production_min.DefaultEventPriority=16;reactReconcilerConstants_production_min.DiscreteEventPriority=1;reactReconcilerConstants_production_min.IdleEventPriority=536870912;reactReconcilerConstants_production_min.LegacyRoot=0; - return reactReconcilerConstants_production_min; -} - -var reactReconcilerConstants_development = {}; - -/** - * @license React - * react-reconciler-constants.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredReactReconcilerConstants_development; - -function requireReactReconcilerConstants_development () { - if (hasRequiredReactReconcilerConstants_development) return reactReconcilerConstants_development; - hasRequiredReactReconcilerConstants_development = 1; - - if (process.env.NODE_ENV !== "production") { - (function() { - - var SyncLane = - /* */ - 1; - var InputContinuousLane = - /* */ - 4; - var DefaultLane = - /* */ - 16; - var IdleLane = - /* */ - 536870912; - - var DiscreteEventPriority = SyncLane; - var ContinuousEventPriority = InputContinuousLane; - var DefaultEventPriority = DefaultLane; - var IdleEventPriority = IdleLane; - - var LegacyRoot = 0; - var ConcurrentRoot = 1; - - reactReconcilerConstants_development.ConcurrentRoot = ConcurrentRoot; - reactReconcilerConstants_development.ContinuousEventPriority = ContinuousEventPriority; - reactReconcilerConstants_development.DefaultEventPriority = DefaultEventPriority; - reactReconcilerConstants_development.DiscreteEventPriority = DiscreteEventPriority; - reactReconcilerConstants_development.IdleEventPriority = IdleEventPriority; - reactReconcilerConstants_development.LegacyRoot = LegacyRoot; - })(); - } - return reactReconcilerConstants_development; -} - -(function (module) { - - if (process.env.NODE_ENV === 'production') { - module.exports = requireReactReconcilerConstants_production_min(); - } else { - module.exports = requireReactReconcilerConstants_development(); - } -} (constants$1)); - -function createStore$3(createState) { - let state; - const listeners = /* @__PURE__ */ new Set(); - const setState = (partial, replace) => { - const nextState = typeof partial === "function" ? partial(state) : partial; - if (nextState !== state) { - const previousState = state; - state = replace ? nextState : Object.assign({}, state, nextState); - listeners.forEach((listener) => listener(state, previousState)); - } - }; - const getState = () => state; - const subscribeWithSelector = (listener, selector = getState, equalityFn = Object.is) => { - console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware"); - let currentSlice = selector(state); - function listenerToAdd() { - const nextSlice = selector(state); - if (!equalityFn(currentSlice, nextSlice)) { - const previousSlice = currentSlice; - listener(currentSlice = nextSlice, previousSlice); - } - } - listeners.add(listenerToAdd); - return () => listeners.delete(listenerToAdd); - }; - const subscribe = (listener, selector, equalityFn) => { - if (selector || equalityFn) { - return subscribeWithSelector(listener, selector, equalityFn); - } - listeners.add(listener); - return () => listeners.delete(listener); - }; - const destroy = () => listeners.clear(); - const api = { setState, getState, subscribe, destroy }; - state = createState(setState, getState, api); - return api; -} - -const isSSR$3 = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); -const useIsomorphicLayoutEffect$2 = isSSR$3 ? useEffect : useLayoutEffect$1; -function create$4(createState) { - const api = typeof createState === "function" ? createStore$3(createState) : createState; - const useStore = (selector = api.getState, equalityFn = Object.is) => { - const [, forceUpdate] = useReducer((c) => c + 1, 0); - const state = api.getState(); - const stateRef = useRef(state); - const selectorRef = useRef(selector); - const equalityFnRef = useRef(equalityFn); - const erroredRef = useRef(false); - const currentSliceRef = useRef(); - if (currentSliceRef.current === void 0) { - currentSliceRef.current = selector(state); - } - let newStateSlice; - let hasNewStateSlice = false; - if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) { - newStateSlice = selector(state); - hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice); - } - useIsomorphicLayoutEffect$2(() => { - if (hasNewStateSlice) { - currentSliceRef.current = newStateSlice; - } - stateRef.current = state; - selectorRef.current = selector; - equalityFnRef.current = equalityFn; - erroredRef.current = false; - }); - const stateBeforeSubscriptionRef = useRef(state); - useIsomorphicLayoutEffect$2(() => { - const listener = () => { - try { - const nextState = api.getState(); - const nextStateSlice = selectorRef.current(nextState); - if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) { - stateRef.current = nextState; - currentSliceRef.current = nextStateSlice; - forceUpdate(); - } - } catch (error) { - erroredRef.current = true; - forceUpdate(); - } - }; - const unsubscribe = api.subscribe(listener); - if (api.getState() !== stateBeforeSubscriptionRef.current) { - listener(); - } - return unsubscribe; - }, []); - const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current; - useDebugValue(sliceToReturn); - return sliceToReturn; - }; - Object.assign(useStore, api); - useStore[Symbol.iterator] = function() { - console.warn("[useStore, api] = create() is deprecated and will be removed in v4"); - const items = [useStore, api]; - return { - next() { - const done = items.length <= 0; - return { value: items.shift(), done }; - } - }; - }; - return useStore; -} - -var reactReconciler = {exports: {}}; - -var scheduler$1 = {exports: {}}; - -var scheduler_production_min = {}; - -/** - * @license React - * scheduler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredScheduler_production_min; - -function requireScheduler_production_min () { - if (hasRequiredScheduler_production_min) return scheduler_production_min; - hasRequiredScheduler_production_min = 1; - (function (exports) { -function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} - function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; - "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} - function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; - function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; - exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; -} (scheduler_production_min)); - return scheduler_production_min; -} - -var scheduler_development = {}; - -/** - * @license React - * scheduler.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredScheduler_development; - -function requireScheduler_development () { - if (hasRequiredScheduler_development) return scheduler_development; - hasRequiredScheduler_development = 1; - (function (exports) { - - if (process.env.NODE_ENV !== "production") { - (function() { - - /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ - if ( - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === - 'function' - ) { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); - } - var enableSchedulerDebugging = false; - var enableProfiling = false; - var frameYieldMs = 5; - - function push(heap, node) { - var index = heap.length; - heap.push(node); - siftUp(heap, node, index); - } - function peek(heap) { - return heap.length === 0 ? null : heap[0]; - } - function pop(heap) { - if (heap.length === 0) { - return null; - } - - var first = heap[0]; - var last = heap.pop(); - - if (last !== first) { - heap[0] = last; - siftDown(heap, last, 0); - } - - return first; - } - - function siftUp(heap, node, i) { - var index = i; - - while (index > 0) { - var parentIndex = index - 1 >>> 1; - var parent = heap[parentIndex]; - - if (compare(parent, node) > 0) { - // The parent is larger. Swap positions. - heap[parentIndex] = node; - heap[index] = parent; - index = parentIndex; - } else { - // The parent is smaller. Exit. - return; - } - } - } - - function siftDown(heap, node, i) { - var index = i; - var length = heap.length; - var halfLength = length >>> 1; - - while (index < halfLength) { - var leftIndex = (index + 1) * 2 - 1; - var left = heap[leftIndex]; - var rightIndex = leftIndex + 1; - var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. - - if (compare(left, node) < 0) { - if (rightIndex < length && compare(right, left) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - heap[index] = left; - heap[leftIndex] = node; - index = leftIndex; - } - } else if (rightIndex < length && compare(right, node) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - // Neither child is smaller. Exit. - return; - } - } - } - - function compare(a, b) { - // Compare sort index first, then task id. - var diff = a.sortIndex - b.sortIndex; - return diff !== 0 ? diff : a.id - b.id; - } - - // TODO: Use symbols? - var ImmediatePriority = 1; - var UserBlockingPriority = 2; - var NormalPriority = 3; - var LowPriority = 4; - var IdlePriority = 5; - - function markTaskErrored(task, ms) { - } - - /* eslint-disable no-var */ - - var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; - - if (hasPerformanceNow) { - var localPerformance = performance; - - exports.unstable_now = function () { - return localPerformance.now(); - }; - } else { - var localDate = Date; - var initialTime = localDate.now(); - - exports.unstable_now = function () { - return localDate.now() - initialTime; - }; - } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. - // Math.pow(2, 30) - 1 - // 0b111111111111111111111111111111 - - - var maxSigned31BitInt = 1073741823; // Times out immediately - - var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out - - var USER_BLOCKING_PRIORITY_TIMEOUT = 250; - var NORMAL_PRIORITY_TIMEOUT = 5000; - var LOW_PRIORITY_TIMEOUT = 10000; // Never times out - - var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap - - var taskQueue = []; - var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. - - var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. - var currentTask = null; - var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. - - var isPerformingWork = false; - var isHostCallbackScheduled = false; - var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. - - var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; - var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; - var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom - - typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; - - function advanceTimers(currentTime) { - // Check for tasks that are no longer delayed and add them to the queue. - var timer = peek(timerQueue); - - while (timer !== null) { - if (timer.callback === null) { - // Timer was cancelled. - pop(timerQueue); - } else if (timer.startTime <= currentTime) { - // Timer fired. Transfer to the task queue. - pop(timerQueue); - timer.sortIndex = timer.expirationTime; - push(taskQueue, timer); - } else { - // Remaining timers are pending. - return; - } - - timer = peek(timerQueue); - } - } - - function handleTimeout(currentTime) { - isHostTimeoutScheduled = false; - advanceTimers(currentTime); - - if (!isHostCallbackScheduled) { - if (peek(taskQueue) !== null) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } else { - var firstTimer = peek(timerQueue); - - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - } - } - } - - function flushWork(hasTimeRemaining, initialTime) { - - - isHostCallbackScheduled = false; - - if (isHostTimeoutScheduled) { - // We scheduled a timeout but it's no longer needed. Cancel it. - isHostTimeoutScheduled = false; - cancelHostTimeout(); - } - - isPerformingWork = true; - var previousPriorityLevel = currentPriorityLevel; - - try { - var currentTime; if (enableProfiling) ; else { - // No catch in prod code path. - return workLoop(hasTimeRemaining, initialTime); - } - } finally { - currentTask = null; - currentPriorityLevel = previousPriorityLevel; - isPerformingWork = false; - } - } - - function workLoop(hasTimeRemaining, initialTime) { - var currentTime = initialTime; - advanceTimers(currentTime); - currentTask = peek(taskQueue); - - while (currentTask !== null && !(enableSchedulerDebugging )) { - if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { - // This currentTask hasn't expired, and we've reached the deadline. - break; - } - - var callback = currentTask.callback; - - if (typeof callback === 'function') { - currentTask.callback = null; - currentPriorityLevel = currentTask.priorityLevel; - var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; - - var continuationCallback = callback(didUserCallbackTimeout); - currentTime = exports.unstable_now(); - - if (typeof continuationCallback === 'function') { - currentTask.callback = continuationCallback; - } else { - - if (currentTask === peek(taskQueue)) { - pop(taskQueue); - } - } - - advanceTimers(currentTime); - } else { - pop(taskQueue); - } - - currentTask = peek(taskQueue); - } // Return whether there's additional work - - - if (currentTask !== null) { - return true; - } else { - var firstTimer = peek(timerQueue); - - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - - return false; - } - } - - function unstable_runWithPriority(priorityLevel, eventHandler) { - switch (priorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - case LowPriority: - case IdlePriority: - break; - - default: - priorityLevel = NormalPriority; - } - - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - - function unstable_next(eventHandler) { - var priorityLevel; - - switch (currentPriorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - // Shift down to normal priority - priorityLevel = NormalPriority; - break; - - default: - // Anything lower than normal priority should remain at the current level. - priorityLevel = currentPriorityLevel; - break; - } - - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - - function unstable_wrapCallback(callback) { - var parentPriorityLevel = currentPriorityLevel; - return function () { - // This is a fork of runWithPriority, inlined for performance. - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = parentPriorityLevel; - - try { - return callback.apply(this, arguments); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - }; - } - - function unstable_scheduleCallback(priorityLevel, callback, options) { - var currentTime = exports.unstable_now(); - var startTime; - - if (typeof options === 'object' && options !== null) { - var delay = options.delay; - - if (typeof delay === 'number' && delay > 0) { - startTime = currentTime + delay; - } else { - startTime = currentTime; - } - } else { - startTime = currentTime; - } - - var timeout; - - switch (priorityLevel) { - case ImmediatePriority: - timeout = IMMEDIATE_PRIORITY_TIMEOUT; - break; - - case UserBlockingPriority: - timeout = USER_BLOCKING_PRIORITY_TIMEOUT; - break; - - case IdlePriority: - timeout = IDLE_PRIORITY_TIMEOUT; - break; - - case LowPriority: - timeout = LOW_PRIORITY_TIMEOUT; - break; - - case NormalPriority: - default: - timeout = NORMAL_PRIORITY_TIMEOUT; - break; - } - - var expirationTime = startTime + timeout; - var newTask = { - id: taskIdCounter++, - callback: callback, - priorityLevel: priorityLevel, - startTime: startTime, - expirationTime: expirationTime, - sortIndex: -1 - }; - - if (startTime > currentTime) { - // This is a delayed task. - newTask.sortIndex = startTime; - push(timerQueue, newTask); - - if (peek(taskQueue) === null && newTask === peek(timerQueue)) { - // All tasks are delayed, and this is the task with the earliest delay. - if (isHostTimeoutScheduled) { - // Cancel an existing timeout. - cancelHostTimeout(); - } else { - isHostTimeoutScheduled = true; - } // Schedule a timeout. - - - requestHostTimeout(handleTimeout, startTime - currentTime); - } - } else { - newTask.sortIndex = expirationTime; - push(taskQueue, newTask); - // wait until the next time we yield. - - - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - - return newTask; - } - - function unstable_pauseExecution() { - } - - function unstable_continueExecution() { - - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - - function unstable_getFirstCallbackNode() { - return peek(taskQueue); - } - - function unstable_cancelCallback(task) { - // remove from the queue because you can't remove arbitrary nodes from an - // array based heap, only the first one.) - - - task.callback = null; - } - - function unstable_getCurrentPriorityLevel() { - return currentPriorityLevel; - } - - var isMessageLoopRunning = false; - var scheduledHostCallback = null; - var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main - // thread, like user events. By default, it yields multiple times per frame. - // It does not attempt to align with frame boundaries, since most tasks don't - // need to be frame aligned; for those that do, use requestAnimationFrame. - - var frameInterval = frameYieldMs; - var startTime = -1; - - function shouldYieldToHost() { - var timeElapsed = exports.unstable_now() - startTime; - - if (timeElapsed < frameInterval) { - // The main thread has only been blocked for a really short amount of time; - // smaller than a single frame. Don't yield yet. - return false; - } // The main thread has been blocked for a non-negligible amount of time. We - - - return true; - } - - function requestPaint() { - - } - - function forceFrameRate(fps) { - if (fps < 0 || fps > 125) { - // Using console['error'] to evade Babel and ESLint - console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); - return; - } - - if (fps > 0) { - frameInterval = Math.floor(1000 / fps); - } else { - // reset the framerate - frameInterval = frameYieldMs; - } - } - - var performWorkUntilDeadline = function () { - if (scheduledHostCallback !== null) { - var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread - // has been blocked. - - startTime = currentTime; - var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the - // error can be observed. - // - // Intentionally not using a try-catch, since that makes some debugging - // techniques harder. Instead, if `scheduledHostCallback` errors, then - // `hasMoreWork` will remain true, and we'll continue the work loop. - - var hasMoreWork = true; - - try { - hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); - } finally { - if (hasMoreWork) { - // If there's more work, schedule the next message event at the end - // of the preceding one. - schedulePerformWorkUntilDeadline(); - } else { - isMessageLoopRunning = false; - scheduledHostCallback = null; - } - } - } else { - isMessageLoopRunning = false; - } // Yielding to the browser will give it a chance to paint, so we can - }; - - var schedulePerformWorkUntilDeadline; - - if (typeof localSetImmediate === 'function') { - // Node.js and old IE. - // There's a few reasons for why we prefer setImmediate. - // - // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. - // (Even though this is a DOM fork of the Scheduler, you could get here - // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) - // https://github.com/facebook/react/issues/20756 - // - // But also, it runs earlier which is the semantic we want. - // If other browsers ever implement it, it's better to use it. - // Although both of these would be inferior to native scheduling. - schedulePerformWorkUntilDeadline = function () { - localSetImmediate(performWorkUntilDeadline); - }; - } else if (typeof MessageChannel !== 'undefined') { - // DOM and Worker environments. - // We prefer MessageChannel because of the 4ms setTimeout clamping. - var channel = new MessageChannel(); - var port = channel.port2; - channel.port1.onmessage = performWorkUntilDeadline; - - schedulePerformWorkUntilDeadline = function () { - port.postMessage(null); - }; - } else { - // We should only fallback here in non-browser environments. - schedulePerformWorkUntilDeadline = function () { - localSetTimeout(performWorkUntilDeadline, 0); - }; - } - - function requestHostCallback(callback) { - scheduledHostCallback = callback; - - if (!isMessageLoopRunning) { - isMessageLoopRunning = true; - schedulePerformWorkUntilDeadline(); - } - } - - function requestHostTimeout(callback, ms) { - taskTimeoutID = localSetTimeout(function () { - callback(exports.unstable_now()); - }, ms); - } - - function cancelHostTimeout() { - localClearTimeout(taskTimeoutID); - taskTimeoutID = -1; - } - - var unstable_requestPaint = requestPaint; - var unstable_Profiling = null; - - exports.unstable_IdlePriority = IdlePriority; - exports.unstable_ImmediatePriority = ImmediatePriority; - exports.unstable_LowPriority = LowPriority; - exports.unstable_NormalPriority = NormalPriority; - exports.unstable_Profiling = unstable_Profiling; - exports.unstable_UserBlockingPriority = UserBlockingPriority; - exports.unstable_cancelCallback = unstable_cancelCallback; - exports.unstable_continueExecution = unstable_continueExecution; - exports.unstable_forceFrameRate = forceFrameRate; - exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; - exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; - exports.unstable_next = unstable_next; - exports.unstable_pauseExecution = unstable_pauseExecution; - exports.unstable_requestPaint = unstable_requestPaint; - exports.unstable_runWithPriority = unstable_runWithPriority; - exports.unstable_scheduleCallback = unstable_scheduleCallback; - exports.unstable_shouldYield = shouldYieldToHost; - exports.unstable_wrapCallback = unstable_wrapCallback; - /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ - if ( - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === - 'function' - ) { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); - } - - })(); - } -} (scheduler_development)); - return scheduler_development; -} - -(function (module) { - - if (process.env.NODE_ENV === 'production') { - module.exports = requireScheduler_production_min(); - } else { - module.exports = requireScheduler_development(); - } -} (scheduler$1)); - -/** - * @license React - * react-reconciler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var reactReconciler_production_min; -var hasRequiredReactReconciler_production_min; - -function requireReactReconciler_production_min () { - if (hasRequiredReactReconciler_production_min) return reactReconciler_production_min; - hasRequiredReactReconciler_production_min = 1; - reactReconciler_production_min = function $$$reconciler($$$hostConfig) { - var exports = {}; -var aa=React__default,ba=scheduler$1.exports,ca=Object.assign;function n(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;ch||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{bc=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?ac(a):""}var dc=Object.prototype.hasOwnProperty,ec=[],fc=-1;function gc(a){return {current:a}} - function x(a){0>fc||(a.current=ec[fc],ec[fc]=null,fc--);}function y(a,b){fc++;ec[fc]=a.current;a.current=b;}var hc={},A=gc(hc),B=gc(!1),ic=hc;function jc(a,b){var c=a.type.contextTypes;if(!c)return hc;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} - function C(a){a=a.childContextTypes;return null!==a&&void 0!==a}function kc(){x(B);x(A);}function lc(a,b,c){if(A.current!==hc)throw Error(n(168));y(A,b);y(B,c);}function mc(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(n(108,xa(a)||"Unknown",e));return ca({},c,d)} - function nc(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||hc;ic=A.current;y(A,a);y(B,B.current);return !0}function oc(a,b,c){var d=a.stateNode;if(!d)throw Error(n(169));c?(a=mc(a,b,ic),d.__reactInternalMemoizedMergedChildContext=a,x(B),x(A),y(A,a)):x(B);y(B,c);}var qc=Math.clz32?Math.clz32:pc,rc=Math.log,sc=Math.LN2;function pc(a){a>>>=0;return 0===a?32:31-(rc(a)/sc|0)|0}var tc=64,uc=4194304; - function vc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; - default:return a}}function wc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=vc(h):(f&=g,0!==f&&(d=vc(f)));}else g=c&~e,0!==g?d=vc(g):0!==f&&(d=vc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}function Bc(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-qc(b);a[b]=c;} - function Cc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0>=g;e-=g;Nd=1<<32-qc(b)+e|c<u?(t=w,w=null):t=w.sibling;var q=r(e,w,h[u],k);if(null===q){null===w&&(w=t);break}a&&w&&null===q.alternate&&b(e,w);g=f(q,g,u);null===m?l=q:m.sibling=q;m=q;w=t;}if(u===h.length)return c(e,w),I&&Pd(e,u),l;if(null===w){for(;uu?(q=m,m=null):q=m.sibling;var V=r(e,m,t.value,k);if(null===V){null===m&&(m=q);break}a&&m&&null===V.alternate&&b(e,m);g=f(V,g,u);null===w?l=V:w.sibling=V;w=V;m=q;}if(t.done)return c(e, - m),I&&Pd(e,u),l;if(null===m){for(;!t.done;u++,t=h.next())t=v(e,t.value,k),null!==t&&(g=f(t,g,u),null===w?l=t:w.sibling=t,w=t);I&&Pd(e,u);return l}for(m=d(e,m);!t.done;u++,t=h.next())t=z(m,e,u,t.value,k),null!==t&&(a&&null!==t.alternate&&m.delete(null===t.key?u:t.key),g=f(t,g,u),null===w?l=t:w.sibling=t,w=t);a&&m.forEach(function(a){return b(e,a)});I&&Pd(e,u);return l}function da(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ia&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!== - f){switch(f.$$typeof){case fa:a:{for(var k=f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ia){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===ra&&he(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=fe(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===ia?(d=ne(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=le(f.type,f.key,f.props,null,a.mode,h),h.ref=fe(a,d,f),h.return= - a,a=h);}return g(a);case ha:a:{for(l=f.key;null!==d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=me(f,a.mode,h);d.return=a;a=d;}return g(a);case ra:return l=f._init,da(a,d,l(f._payload),h)}if(Ea(f))return q(a,d,f,h);if(ua(f))return N(a,d,f,h);ge(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&& - 6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=ke(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return da}var oe=ie(!0),pe=ie(!1),qe={},re=gc(qe),se=gc(qe),te=gc(qe);function ue(a){if(a===qe)throw Error(n(174));return a}function ve(a,b){y(te,b);y(se,a);y(re,qe);a=Ga(b);x(re);y(re,a);}function we(){x(re);x(se);x(te);}function xe(a){var b=ue(te.current),c=ue(re.current);b=Ha(c,a.type,b);c!==b&&(y(se,a),y(re,b));}function ye(a){se.current===a&&(x(re),x(se));}var J=gc(0); - function ze(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||Ib(c)||Jb(c)))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Ae=[]; - function Be(){for(var a=0;ac?c:4;a(!0);var d=De.transition;De.transition={};try{a(!1),b();}finally{D=c,De.transition=d;}}function rf(){return Re().memoizedState}function sf(a,b,c){var d=zd(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};tf(a)?uf(b,c):(vf(a,b,c),c=H(),a=Ad(a,d,c),null!==a&&wf(a,b,d));} - function df(a,b,c){var d=zd(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(tf(a))uf(b,e);else {vf(a,b,e);var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(Rc(h,g))return}catch(k){}finally{}c=H();a=Ad(a,d,c);null!==a&&wf(a,b,d);}}function tf(a){var b=a.alternate;return a===K||null!==b&&b===K} - function uf(a,b){Ge=Fe=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function vf(a,b,c){null!==F&&0!==(a.mode&1)&&0===(G&2)?(a=b.interleaved,null===a?(c.next=c,null===md?md=[b]:md.push(b)):(c.next=a.next,a.next=c),b.interleaved=c):(a=b.pending,null===a?c.next=c:(c.next=a.next,a.next=c),b.pending=c);}function wf(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Dc(a,c);}} - var Oe={readContext:ld,useCallback:O,useContext:O,useEffect:O,useImperativeHandle:O,useInsertionEffect:O,useLayoutEffect:O,useMemo:O,useReducer:O,useRef:O,useState:O,useDebugValue:O,useDeferredValue:O,useTransition:O,useMutableSource:O,useSyncExternalStore:O,useId:O,unstable_isNewReconciler:!1},Le={readContext:ld,useCallback:function(a,b){Qe().memoizedState=[a,void 0===b?null:b];return a},useContext:ld,useEffect:hf,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ff(4194308, - 4,lf.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ff(4194308,4,a,b)},useInsertionEffect:function(a,b){return ff(4,2,a,b)},useMemo:function(a,b){var c=Qe();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Qe();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=sf.bind(null,K,a);return [d.memoizedState,a]},useRef:function(a){var b= - Qe();a={current:a};return b.memoizedState=a},useState:cf,useDebugValue:nf,useDeferredValue:function(a){var b=cf(a),c=b[0],d=b[1];hf(function(){var b=De.transition;De.transition={};try{d(a);}finally{De.transition=b;}},[a]);return c},useTransition:function(){var a=cf(!1),b=a[0];a=qf.bind(null,a[1]);Qe().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=K,e=Qe();if(I){if(void 0===c)throw Error(n(407));c=c();}else {c=b();if(null===F)throw Error(n(349)); - 0!==(Ee&30)||af(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;hf(Ye.bind(null,d,f,a),[a]);d.flags|=2048;Ze(9,$e.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Qe(),b=F.identifierPrefix;if(I){var c=Od;var d=Nd;c=(d&~(1<<32-qc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=He++;0Uf&&(b.flags|=128,d=!0,Qf(e,!1),b.lanes=4194304);}else {if(!d)if(a=ze(f),null!==a){if(b.flags|=128,d=!0,a=a.updateQueue,null!==a&&(b.updateQueue=a,b.flags|=4),Qf(e,!0),null===e.tail&&"hidden"===e.tailMode&&!f.alternate&&!I)return P(b),null}else 2*E()-e.renderingStartTime>Uf&&1073741824!==c&&(b.flags|=128,d=!0,Qf(e,!1),b.lanes=4194304);e.isBackwards?(f.sibling=b.child,b.child=f):(a=e.last,null!==a?a.sibling=f:b.child=f,e.last=f);}if(null!== - e.tail)return b=e.tail,e.rendering=b,e.tail=b.sibling,e.renderingStartTime=E(),b.sibling=null,a=J.current,y(J,d?a&1|2:a&1),b;P(b);return null;case 22:case 23:return Vf(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(Wf&1073741824)&&(P(b),Ua&&b.subtreeFlags&6&&(b.flags|=8192)):P(b),null;case 24:return null;case 25:return null}throw Error(n(156,b.tag));}var Xf=ea.ReactCurrentOwner,kd=!1; - function R(a,b,c,d){b.child=null===a?pe(b,null,c,d):oe(b,a.child,c,d);}function Yf(a,b,c,d,e){c=c.render;var f=b.ref;jd(b,e);d=Ke(a,b,c,d,f,e);c=Pe();if(null!==a&&!kd)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zf(a,b,e);I&&c&&Rd(b);b.flags|=1;R(a,b,d,e);return b.child} - function $f(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!ag(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,bg(a,b,f,d,e);a=le(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Zc;if(c(g,d)&&a.ref===b.ref)return Zf(a,b,e)}b.flags|=1;a=je(f,d);a.ref=b.ref;a.return=b;return b.child=a} - function bg(a,b,c,d,e){if(null!==a&&Zc(a.memoizedProps,d)&&a.ref===b.ref)if(kd=!1,0!==(a.lanes&e))0!==(a.flags&131072)&&(kd=!0);else return b.lanes=a.lanes,Zf(a,b,e);return cg(a,b,c,d,e)} - function dg(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null},y(eg,Wf),Wf|=c;else if(0!==(c&1073741824))b.memoizedState={baseLanes:0,cachePool:null},d=null!==f?f.baseLanes:c,y(eg,Wf),Wf|=d;else return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null},b.updateQueue=null,y(eg,Wf),Wf|=a,null;else null!==f?(d=f.baseLanes|c,b.memoizedState=null): - d=c,y(eg,Wf),Wf|=d;R(a,b,e,c);return b.child}function fg(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152;}function cg(a,b,c,d,e){var f=C(c)?ic:A.current;f=jc(b,f);jd(b,e);c=Ke(a,b,c,d,f,e);d=Pe();if(null!==a&&!kd)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zf(a,b,e);I&&d&&Rd(b);b.flags|=1;R(a,b,c,e);return b.child} - function gg(a,b,c,d,e){if(C(c)){var f=!0;nc(b);}else f=!1;jd(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),Dd(b,c,d),Fd(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=ld(l):(l=C(c)?ic:A.current,l=jc(b,l));var m=c.getDerivedStateFromProps,v="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;v||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!== - typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Ed(b,g,d,l);nd=!1;var r=b.memoizedState;g.state=r;ud(b,d,g,e);k=b.memoizedState;h!==d||r!==k||B.current||nd?("function"===typeof m&&(yd(b,c,m,d),k=b.memoizedState),(h=nd||Cd(b,c,h,d,r,k,l))?(v||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&& - (b.flags|=4194308)):("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1);}else {g=b.stateNode;pd(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:ad(b.type,h);g.props=l;v=b.pendingProps;r=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=ld(k):(k=C(c)?ic:A.current,k=jc(b,k));var z=c.getDerivedStateFromProps;(m="function"===typeof z||"function"=== - typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==v||r!==k)&&Ed(b,g,d,k);nd=!1;r=b.memoizedState;g.state=r;ud(b,d,g,e);var q=b.memoizedState;h!==v||r!==q||B.current||nd?("function"===typeof z&&(yd(b,c,z,d),q=b.memoizedState),(l=nd||Cd(b,c,l,d,r,q,k)||!1)?(m||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d, - q,k),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,q,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=q),g.props=d,g.state=q,g.context=k,d=l):("function"!== - typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1);}return hg(a,b,c,d,f,e)} - function hg(a,b,c,d,e,f){fg(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&oc(b,c,!1),Zf(a,b,f);d=b.stateNode;Xf.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=oe(b,a.child,null,f),b.child=oe(b,null,h,f)):R(a,b,h,f);b.memoizedState=d.state;e&&oc(b,c,!0);return b.child}function ig(a){var b=a.stateNode;b.pendingContext?lc(a,b.pendingContext,b.pendingContext!==b.context):b.context&&lc(a,b.context,!1);ve(a,b.containerInfo);} - function jg(a,b,c,d,e){de();ee(e);b.flags|=256;R(a,b,c,d);return b.child}var kg={dehydrated:null,treeContext:null,retryLane:0};function lg(a){return {baseLanes:a,cachePool:null}} - function mg(a,b,c){var d=b.pendingProps,e=J.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;y(J,e&1);if(null===a){ae(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:Jb(a)?b.lanes=8:b.lanes=1073741824,null;e=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,e={mode:"hidden",children:e},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=e): - f=ng(e,d,0,null),a=ne(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=lg(c),b.memoizedState=kg,a):og(b,e)}e=a.memoizedState;if(null!==e){h=e.dehydrated;if(null!==h){if(g){if(b.flags&256)return b.flags&=-257,pg(a,b,c,Error(n(422)));if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=ng({mode:"visible",children:d.children},e,0,null);f=ne(f,e,c,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&oe(b,a.child, - null,c);b.child.memoizedState=lg(c);b.memoizedState=kg;return f}if(0===(b.mode&1))b=pg(a,b,c,null);else if(Jb(h))b=pg(a,b,c,Error(n(419)));else if(d=0!==(c&a.childLanes),kd||d){d=F;if(null!==d){switch(c&-c){case 4:f=2;break;case 16:f=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:f=32;break;case 536870912:f= - 268435456;break;default:f=0;}d=0!==(f&(d.suspendedLanes|c))?0:f;0!==d&&d!==e.retryLane&&(e.retryLane=d,Ad(a,d,-1));}Tf();b=pg(a,b,c,Error(n(421)));}else Ib(h)?(b.flags|=128,b.child=a.child,b=qg.bind(null,a),Kb(h,b),b=null):(c=e.treeContext,p&&(Ud=Ob(h),Td=b,I=!0,Wd=null,Vd=!1,null!==c&&(Kd[Ld++]=Nd,Kd[Ld++]=Od,Kd[Ld++]=Md,Nd=c.id,Od=c.overflow,Md=b)),b=og(b,b.pendingProps.children),b.flags|=4096);return b}if(f)return d=rg(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState= - null===e?lg(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kg,d;c=sg(a,b,d.children,c);b.memoizedState=null;return c}if(f)return d=rg(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState=null===e?lg(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kg,d;c=sg(a,b,d.children,c);b.memoizedState=null;return c} - function og(a,b){b=ng({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function sg(a,b,c,d){var e=a.child;a=e.sibling;c=je(e,{mode:"visible",children:c});0===(b.mode&1)&&(c.lanes=d);c.return=b;c.sibling=null;null!==a&&(d=b.deletions,null===d?(b.deletions=[a],b.flags|=16):d.push(a));return b.child=c} - function rg(a,b,c,d,e){var f=b.mode;a=a.child;var g=a.sibling,h={mode:"hidden",children:c};0===(f&1)&&b.child!==a?(c=b.child,c.childLanes=0,c.pendingProps=h,b.deletions=null):(c=je(a,h),c.subtreeFlags=a.subtreeFlags&14680064);null!==g?d=je(g,d):(d=ne(d,f,e,null),d.flags|=2);d.return=b;c.return=b;c.sibling=d;b.child=c;return d}function pg(a,b,c,d){null!==d&&ee(d);oe(b,a.child,null,c);a=og(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a} - function tg(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);id(a.return,b,c);}function ug(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e);} - function vg(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;R(a,b,d.children,c);d=J.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else {if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&tg(a,c,b);else if(19===a.tag)tg(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return;}a.sibling.return=a.return;a=a.sibling;}d&=1;}y(J,d);if(0===(b.mode&1))b.memoizedState= - null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===ze(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);ug(b,!1,e,c,f);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===ze(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a;}ug(b,!0,c,null,f);break;case "together":ug(b,!1,null,null,void 0);break;default:b.memoizedState=null;}return b.child} - function Zf(a,b,c){null!==a&&(b.dependencies=a.dependencies);vd|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(n(153));if(null!==b.child){a=b.child;c=je(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=je(a,a.pendingProps),c.return=b;c.sibling=null;}return b.child} - function wg(a,b,c){switch(b.tag){case 3:ig(b);de();break;case 5:xe(b);break;case 1:C(b.type)&&nc(b);break;case 4:ve(b,b.stateNode.containerInfo);break;case 10:gd(b,b.type._context,b.memoizedProps.value);break;case 13:var d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return y(J,J.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return mg(a,b,c);y(J,J.current&1);a=Zf(a,b,c);return null!==a?a.sibling:null}y(J,J.current&1);break;case 19:d=0!==(c&b.childLanes);if(0!==(a.flags&128)){if(d)return vg(a, - b,c);b.flags|=128;}var e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);y(J,J.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,dg(a,b,c)}return Zf(a,b,c)} - function xg(a,b){Sd(b);switch(b.tag){case 1:return C(b.type)&&kc(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return we(),x(B),x(A),Be(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return ye(b),null;case 13:x(J);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(n(340));de();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return x(J),null;case 4:return we(),null;case 10:return hd(b.type._context),null;case 22:case 23:return Vf(), - null;case 24:return null;default:return null}}var yg=!1,zg=!1,Ag="function"===typeof WeakSet?WeakSet:Set,S=null;function Bg(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){T(a,b,d);}else c.current=null;}function Cg(a,b,c){try{c();}catch(d){T(a,b,d);}}var Dg=!1; - function Eg(a,b){Ia(a.containerInfo);for(S=b;null!==S;)if(a=S,b=a.child,0!==(a.subtreeFlags&1028)&&null!==b)b.return=a,S=b;else for(;null!==S;){a=S;try{var c=a.alternate;if(0!==(a.flags&1024))switch(a.tag){case 0:case 11:case 15:break;case 1:if(null!==c){var d=c.memoizedProps,e=c.memoizedState,f=a.stateNode,g=f.getSnapshotBeforeUpdate(a.elementType===a.type?d:ad(a.type,d),e);f.__reactInternalSnapshotBeforeUpdate=g;}break;case 3:Ua&&xb(a.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break; - default:throw Error(n(163));}}catch(h){T(a,a.return,h);}b=a.sibling;if(null!==b){b.return=a.return;S=b;break}S=a.return;}c=Dg;Dg=!1;return c}function Fg(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Cg(b,c,f);}e=e.next;}while(e!==d)}}function Gg(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}} - function Hg(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=Fa(c);break;default:a=c;}"function"===typeof b?b(a):b.current=a;}} - function Ig(a,b,c){if(Oc&&"function"===typeof Oc.onCommitFiberUnmount)try{Oc.onCommitFiberUnmount(Nc,b);}catch(g){}switch(b.tag){case 0:case 11:case 14:case 15:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var d=a=a.next;do{var e=d,f=e.destroy;e=e.tag;void 0!==f&&(0!==(e&2)?Cg(b,c,f):0!==(e&4)&&Cg(b,c,f));d=d.next;}while(d!==a)}break;case 1:Bg(b,c);a=b.stateNode;if("function"===typeof a.componentWillUnmount)try{a.props=b.memoizedProps,a.state=b.memoizedState,a.componentWillUnmount();}catch(g){T(b, - c,g);}break;case 5:Bg(b,c);break;case 4:Ua?Jg(a,b,c):Va&&Va&&(b=b.stateNode.containerInfo,c=zb(b),Cb(b,c));}}function Kg(a,b,c){for(var d=b;;)if(Ig(a,d,c),null===d.child||Ua&&4===d.tag){if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;}d.sibling.return=d.return;d=d.sibling;}else d.child.return=d,d=d.child;} - function Lg(a){var b=a.alternate;null!==b&&(a.alternate=null,Lg(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&Za(b));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Mg(a){return 5===a.tag||3===a.tag||4===a.tag} - function Ng(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Mg(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}} - function Og(a){if(Ua){a:{for(var b=a.return;null!==b;){if(Mg(b))break a;b=b.return;}throw Error(n(160));}var c=b;switch(c.tag){case 5:b=c.stateNode;c.flags&32&&(sb(b),c.flags&=-33);c=Ng(a);Pg(a,c,b);break;case 3:case 4:b=c.stateNode.containerInfo;c=Ng(a);Qg(a,c,b);break;default:throw Error(n(161));}}}function Qg(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?pb(c,a,b):kb(c,a);else if(4!==d&&(a=a.child,null!==a))for(Qg(a,b,c),a=a.sibling;null!==a;)Qg(a,b,c),a=a.sibling;} - function Pg(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?ob(c,a,b):jb(c,a);else if(4!==d&&(a=a.child,null!==a))for(Pg(a,b,c),a=a.sibling;null!==a;)Pg(a,b,c),a=a.sibling;} - function Jg(a,b,c){for(var d=b,e=!1,f,g;;){if(!e){e=d.return;a:for(;;){if(null===e)throw Error(n(160));f=e.stateNode;switch(e.tag){case 5:g=!1;break a;case 3:f=f.containerInfo;g=!0;break a;case 4:f=f.containerInfo;g=!0;break a}e=e.return;}e=!0;}if(5===d.tag||6===d.tag)Kg(a,d,c),g?rb(f,d.stateNode):qb(f,d.stateNode);else if(18===d.tag)g?Wb(f,d.stateNode):Vb(f,d.stateNode);else if(4===d.tag){if(null!==d.child){f=d.stateNode.containerInfo;g=!0;d.child.return=d;d=d.child;continue}}else if(Ig(a,d,c),null!== - d.child){d.child.return=d;d=d.child;continue}if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;4===d.tag&&(e=!1);}d.sibling.return=d.return;d=d.sibling;}} - function Rg(a,b){if(Ua){switch(b.tag){case 0:case 11:case 14:case 15:Fg(3,b,b.return);Gg(3,b);Fg(5,b,b.return);return;case 1:return;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps;a=null!==a?a.memoizedProps:d;var e=b.type,f=b.updateQueue;b.updateQueue=null;null!==f&&nb(c,f,e,a,d,b);}return;case 6:if(null===b.stateNode)throw Error(n(162));c=b.memoizedProps;lb(b.stateNode,null!==a?a.memoizedProps:c,c);return;case 3:p&&null!==a&&a.memoizedState.isDehydrated&&Tb(b.stateNode.containerInfo);return; - case 12:return;case 13:Sg(b);return;case 19:Sg(b);return;case 17:return}throw Error(n(163));}switch(b.tag){case 0:case 11:case 14:case 15:Fg(3,b,b.return);Gg(3,b);Fg(5,b,b.return);return;case 12:return;case 13:Sg(b);return;case 19:Sg(b);return;case 3:p&&null!==a&&a.memoizedState.isDehydrated&&Tb(b.stateNode.containerInfo);break;case 22:case 23:return}a:if(Va){switch(b.tag){case 1:case 5:case 6:break a;case 3:case 4:b=b.stateNode;Cb(b.containerInfo,b.pendingChildren);break a}throw Error(n(163));}} - function Sg(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Ag);b.forEach(function(b){var d=Tg.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}} - function Ug(a,b){for(S=b;null!==S;){b=S;var c=b.deletions;if(null!==c)for(var d=0;d";case bh:return ":has("+(ih(a)||"")+")";case ch:return '[role="'+a.value+'"]';case eh:return '"'+a.value+'"';case dh:return '[data-testname="'+a.value+'"]';default:throw Error(n(365));}} - function jh(a,b){var c=[];a=[a,0];for(var d=0;de&&(e=g);d&=~f;}d=e;d=E()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lh(d/1960))-d;if(10a?16:a;if(null===uh)var d=!1;else {a=uh;uh=null;vh=0;if(0!==(G&6))throw Error(n(331));var e=G;G|=4;for(S=a.current;null!==S;){var f=S,g=f.child;if(0!==(S.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kE()-Vg?Ih(a,0):qh|=c);Z(a,b);}function Vh(a,b){0===b&&(0===(a.mode&1)?b=1:(b=uc,uc<<=1,0===(uc&130023424)&&(uc=4194304)));var c=H();a=Ah(a,b);null!==a&&(Bc(a,b,c),Z(a,c));}function qg(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Vh(a,c);} - function Tg(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(n(314));}null!==d&&d.delete(b);Vh(a,c);}var Sh; - Sh=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||B.current)kd=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return kd=!1,wg(a,b,c);kd=0!==(a.flags&131072)?!0:!1;}else kd=!1,I&&0!==(b.flags&1048576)&&Qd(b,Jd,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;var e=jc(b,A.current);jd(b,c);e=Ke(null,b,d,a,e,c);var f=Pe();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof? - (b.tag=1,b.memoizedState=null,b.updateQueue=null,C(d)?(f=!0,nc(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,od(b),e.updater=Bd,b.stateNode=e,e._reactInternals=b,Fd(b,d,a,c),b=hg(null,b,d,!0,f,c)):(b.tag=0,I&&f&&Rd(b),R(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Wh(d);a=ad(d,a);switch(e){case 0:b=cg(null,b,d,a,c);break a;case 1:b=gg(null,b,d, - a,c);break a;case 11:b=Yf(null,b,d,a,c);break a;case 14:b=$f(null,b,d,ad(d.type,a),c);break a}throw Error(n(306,d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),cg(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),gg(a,b,d,e,c);case 3:a:{ig(b);if(null===a)throw Error(n(387));d=b.pendingProps;f=b.memoizedState;e=f.element;pd(a,b);ud(b,d,null,c);var g=b.memoizedState;d=g.element;if(p&&f.isDehydrated)if(f={element:d,isDehydrated:!1, - cache:g.cache,transitions:g.transitions},b.updateQueue.baseState=f,b.memoizedState=f,b.flags&256){e=Error(n(423));b=jg(a,b,d,c,e);break a}else if(d!==e){e=Error(n(424));b=jg(a,b,d,c,e);break a}else for(p&&(Ud=Nb(b.stateNode.containerInfo),Td=b,I=!0,Wd=null,Vd=!1),c=pe(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {de();if(d===e){b=Zf(a,b,c);break a}R(a,b,d,c);}b=b.child;}return b;case 5:return xe(b),null===a&&ae(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children, - Oa(d,e)?g=null:null!==f&&Oa(d,f)&&(b.flags|=32),fg(a,b),R(a,b,g,c),b.child;case 6:return null===a&&ae(b),null;case 13:return mg(a,b,c);case 4:return ve(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=oe(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),Yf(a,b,d,e,c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:return R(a,b,b.pendingProps.children,c),b.child;case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d= - b.type._context;e=b.pendingProps;f=b.memoizedProps;g=e.value;gd(b,d,g);if(null!==f)if(Rc(f.value,g)){if(f.children===e.children&&!B.current){b=Zf(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=qd(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|= - c);id(f.return,c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(n(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);id(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}R(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,jd(b,c),e=ld(e),d=d(e),b.flags|= - 1,R(a,b,d,c),b.child;case 14:return d=b.type,e=ad(d,b.pendingProps),e=ad(d.type,e),$f(a,b,d,e,c);case 15:return bg(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),b.tag=1,C(d)?(a=!0,nc(b)):a=!1,jd(b,c),Dd(b,d,e),Fd(b,d,e,c),hg(null,b,d,!0,a,c);case 19:return vg(a,b,c);case 22:return dg(a,b,c)}throw Error(n(156,b.tag));};function Dh(a,b){return Fc(a,b)} - function Xh(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Yd(a,b,c,d){return new Xh(a,b,c,d)}function ag(a){a=a.prototype;return !(!a||!a.isReactComponent)} - function Wh(a){if("function"===typeof a)return ag(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===na)return 11;if(a===qa)return 14}return 2} - function je(a,b){var c=a.alternate;null===c?(c=Yd(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; - c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} - function le(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)ag(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ia:return ne(c.children,e,f,b);case ja:g=8;e|=8;break;case ka:return a=Yd(12,c,b,e|2),a.elementType=ka,a.lanes=f,a;case oa:return a=Yd(13,c,b,e),a.elementType=oa,a.lanes=f,a;case pa:return a=Yd(19,c,b,e),a.elementType=pa,a.lanes=f,a;case sa:return ng(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case la:g=10;break a;case ma:g=9;break a;case na:g=11; - break a;case qa:g=14;break a;case ra:g=16;d=null;break a}throw Error(n(130,null==a?a:typeof a,""));}b=Yd(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function ne(a,b,c,d){a=Yd(7,a,d,b);a.lanes=c;return a}function ng(a,b,c,d){a=Yd(22,a,d,b);a.elementType=sa;a.lanes=c;a.stateNode={};return a}function ke(a,b,c){a=Yd(6,a,null,b);a.lanes=c;return a} - function me(a,b,c){b=Yd(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} - function Yh(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=Sa;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=Ac(0);this.expirationTimes=Ac(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=Ac(0);this.identifierPrefix=d;this.onRecoverableError=e;p&&(this.mutableSourceEagerHydrationData= - null);}function Zh(a,b,c,d,e,f,g,h,k){a=new Yh(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Yd(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null};od(f);return a} - function $h(a){if(!a)return hc;a=a._reactInternals;a:{if(ya(a)!==a||1!==a.tag)throw Error(n(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(C(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return;}while(null!==b);throw Error(n(171));}if(1===a.tag){var c=a.type;if(C(c))return mc(a,c,b)}return b} - function ai(a){var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(n(188));a=Object.keys(a).join(",");throw Error(n(268,a));}a=Ba(b);return null===a?null:a.stateNode}function bi(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c=l&&f>=v&&e<=m&&g<=r){a.splice(b,1);break}else if(!(d!==l||c.width!==k.width||rg)){v>f&&(k.height+=v-f,k.y=f);re)){l>d&&(k.width+= - l-d,k.x=d);mc&&(c=g)),g ")+"\n\nNo matching component was found for:\n ")+a.join(" > ")}return null}; - exports.getPublicRootInstance=function(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return Fa(a.child.stateNode);default:return a.child.stateNode}}; - exports.injectIntoDevTools=function(a){a={bundleType:a.bundleType,version:a.version,rendererPackageName:a.rendererPackageName,rendererConfig:a.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ea.ReactCurrentDispatcher,findHostInstanceByFiber:di,findFiberByHostInstance:a.findFiberByHostInstance|| - ei,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.0.0-fc46dba67-20220329"};if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)a=!1;else {var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)a=!0;else {try{Nc=b.inject(a),Oc=b;}catch(c){}a=b.checkDCE?!0:!1;}}return a};exports.isAlreadyRendering=function(){return !1}; - exports.observeVisibleRects=function(a,b,c,d){if(!bb)throw Error(n(363));a=kh(a,b);var e=ib(a,c,d).disconnect;return {disconnect:function(){e();}}};exports.registerMutableSourceForHydration=function(a,b){var c=b._getVersion;c=c(b._source);null==a.mutableSourceEagerHydrationData?a.mutableSourceEagerHydrationData=[b,c]:a.mutableSourceEagerHydrationData.push(b,c);};exports.runWithPriority=function(a,b){var c=D;try{return D=a,b()}finally{D=c;}};exports.shouldError=function(){return null}; - exports.shouldSuspend=function(){return !1};exports.updateContainer=function(a,b,c,d){var e=b.current,f=H(),g=zd(e);c=$h(c);null===b.context?b.context=c:b.pendingContext=c;b=qd(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);rd(e,b);a=Ad(e,g,f);null!==a&&sd(a,e,g);return g}; - - return exports; - }; - return reactReconciler_production_min; -} - -var reactReconciler_development = {exports: {}}; - -/** - * @license React - * react-reconciler.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredReactReconciler_development; - -function requireReactReconciler_development () { - if (hasRequiredReactReconciler_development) return reactReconciler_development.exports; - hasRequiredReactReconciler_development = 1; - - if (process.env.NODE_ENV !== "production") { - reactReconciler_development.exports = function $$$reconciler($$$hostConfig) { - var exports = {}; - - var React = React__default; - var Scheduler = scheduler$1.exports; - - var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - - var suppressWarning = false; - function setSuppressWarning(newSuppressWarning) { - { - suppressWarning = newSuppressWarning; - } - } // In DEV, calls to console.warn and console.error get replaced - // by calls to these methods by a Babel plugin. - // - // In PROD (or in packages without access to React internals), - // they are left as they are instead. - - function warn(format) { - { - if (!suppressWarning) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - printWarning('warn', format, args); - } - } - } - function error(format) { - { - if (!suppressWarning) { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - printWarning('error', format, args); - } - } - } - - function printWarning(level, format, args) { - // When changing this logic, you might want to also - // update consoleWithStackDev.www.js as well. - { - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - - if (stack !== '') { - format += '%s'; - args = args.concat([stack]); - } // eslint-disable-next-line react-internal/safe-string-coercion - - - var argsWithFormat = args.map(function (item) { - return String(item); - }); // Careful: RN currently depends on this prefix - - argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it - // breaks IE9: https://github.com/facebook/react/issues/13610 - // eslint-disable-next-line react-internal/no-production-logging - - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - - var assign = Object.assign; - - /** - * `ReactInstanceMap` maintains a mapping from a public facing stateful - * instance (key) and the internal representation (value). This allows public - * methods to accept the user facing instance as an argument and map them back - * to internal methods. - * - * Note that this module is currently shared and assumed to be stateless. - * If this becomes an actual Map, that will break. - */ - function get(key) { - return key._reactInternals; - } - function set(key, value) { - key._reactInternals = value; - } - - // ----------------------------------------------------------------------------- - var enablePersistentOffscreenHostContainer = false; // ----------------------------------------------------------------------------- - // the react-reconciler package. - - var enableNewReconciler = false; // Support legacy Primer support on internal FB www - - var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics. - - var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber - - var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz - var warnAboutStringRefs = false; // ----------------------------------------------------------------------------- - // Debugging and DevTools - // ----------------------------------------------------------------------------- - // Adds user timing marks for e.g. state updates, suspense, and work loop stuff, - // for an experimental timeline tool. - - var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState - - var enableProfilerTimer = true; // Record durations for commit and passive effects phases. - - var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update". - - var FunctionComponent = 0; - var ClassComponent = 1; - var IndeterminateComponent = 2; // Before we know whether it is function or class - - var HostRoot = 3; // Root of a host tree. Could be nested inside another node. - - var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. - - var HostComponent = 5; - var HostText = 6; - var Fragment = 7; - var Mode = 8; - var ContextConsumer = 9; - var ContextProvider = 10; - var ForwardRef = 11; - var Profiler = 12; - var SuspenseComponent = 13; - var MemoComponent = 14; - var SimpleMemoComponent = 15; - var LazyComponent = 16; - var IncompleteClassComponent = 17; - var DehydratedFragment = 18; - var SuspenseListComponent = 19; - var ScopeComponent = 21; - var OffscreenComponent = 22; - var LegacyHiddenComponent = 23; - var CacheComponent = 24; - var TracingMarkerComponent = 25; - - // ATTENTION - // When adding new symbols to this file, - // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' - // The Symbol used to tag the ReactElement-like types. - var REACT_ELEMENT_TYPE = Symbol.for('react.element'); - var REACT_PORTAL_TYPE = Symbol.for('react.portal'); - var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); - var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); - var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); - var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); - var REACT_CONTEXT_TYPE = Symbol.for('react.context'); - var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); - var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); - var REACT_MEMO_TYPE = Symbol.for('react.memo'); - var REACT_LAZY_TYPE = Symbol.for('react.lazy'); - var REACT_SCOPE_TYPE = Symbol.for('react.scope'); - var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); - var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); - var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); - var REACT_CACHE_TYPE = Symbol.for('react.cache'); - var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker'); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = '@@iterator'; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== 'object') { - return null; - } - - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - - if (typeof maybeIterator === 'function') { - return maybeIterator; - } - - return null; - } - - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - - if (displayName) { - return displayName; - } - - var functionName = innerType.displayName || innerType.name || ''; - return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; - } // Keep in sync with react-reconciler/getComponentNameFromFiber - - - function getContextName(type) { - return type.displayName || 'Context'; - } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. - - - function getComponentNameFromType(type) { - if (type == null) { - // Host root, text node or just invalid type. - return null; - } - - { - if (typeof type.tag === 'number') { - error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); - } - } - - if (typeof type === 'function') { - return type.displayName || type.name || null; - } - - if (typeof type === 'string') { - return type; - } - - switch (type) { - case REACT_FRAGMENT_TYPE: - return 'Fragment'; - - case REACT_PORTAL_TYPE: - return 'Portal'; - - case REACT_PROFILER_TYPE: - return 'Profiler'; - - case REACT_STRICT_MODE_TYPE: - return 'StrictMode'; - - case REACT_SUSPENSE_TYPE: - return 'Suspense'; - - case REACT_SUSPENSE_LIST_TYPE: - return 'SuspenseList'; - - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + '.Consumer'; - - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + '.Provider'; - - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, 'ForwardRef'); - - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - - if (outerName !== null) { - return outerName; - } - - return getComponentNameFromType(type.type) || 'Memo'; - - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - return getComponentNameFromType(init(payload)); - } catch (x) { - return null; - } - } - - // eslint-disable-next-line no-fallthrough - } - } - - return null; - } - - function getWrappedName$1(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ''; - return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); - } // Keep in sync with shared/getComponentNameFromType - - - function getContextName$1(type) { - return type.displayName || 'Context'; - } - - function getComponentNameFromFiber(fiber) { - var tag = fiber.tag, - type = fiber.type; - - switch (tag) { - case CacheComponent: - return 'Cache'; - - case ContextConsumer: - var context = type; - return getContextName$1(context) + '.Consumer'; - - case ContextProvider: - var provider = type; - return getContextName$1(provider._context) + '.Provider'; - - case DehydratedFragment: - return 'DehydratedFragment'; - - case ForwardRef: - return getWrappedName$1(type, type.render, 'ForwardRef'); - - case Fragment: - return 'Fragment'; - - case HostComponent: - // Host component type is the display name (e.g. "div", "View") - return type; - - case HostPortal: - return 'Portal'; - - case HostRoot: - return 'Root'; - - case HostText: - return 'Text'; - - case LazyComponent: - // Name comes from the type in this case; we don't have a tag. - return getComponentNameFromType(type); - - case Mode: - if (type === REACT_STRICT_MODE_TYPE) { - // Don't be less specific than shared/getComponentNameFromType - return 'StrictMode'; - } - - return 'Mode'; - - case OffscreenComponent: - return 'Offscreen'; - - case Profiler: - return 'Profiler'; - - case ScopeComponent: - return 'Scope'; - - case SuspenseComponent: - return 'Suspense'; - - case SuspenseListComponent: - return 'SuspenseList'; - - case TracingMarkerComponent: - return 'TracingMarker'; - // The display name for this tags come from the user-provided type: - - case ClassComponent: - case FunctionComponent: - case IncompleteClassComponent: - case IndeterminateComponent: - case MemoComponent: - case SimpleMemoComponent: - if (typeof type === 'function') { - return type.displayName || type.name || null; - } - - if (typeof type === 'string') { - return type; - } - - break; - - } - - return null; - } - - // Don't change these two values. They're used by React Dev Tools. - var NoFlags = - /* */ - 0; - var PerformedWork = - /* */ - 1; // You can change the rest (and add more). - - var Placement = - /* */ - 2; - var Update = - /* */ - 4; - var PlacementAndUpdate = - /* */ - Placement | Update; - var ChildDeletion = - /* */ - 16; - var ContentReset = - /* */ - 32; - var Callback = - /* */ - 64; - var DidCapture = - /* */ - 128; - var ForceClientRender = - /* */ - 256; - var Ref = - /* */ - 512; - var Snapshot = - /* */ - 1024; - var Passive = - /* */ - 2048; - var Hydrating = - /* */ - 4096; - var HydratingAndUpdate = - /* */ - Hydrating | Update; - var Visibility = - /* */ - 8192; - var StoreConsistency = - /* */ - 16384; - var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit) - - var HostEffectMask = - /* */ - 32767; // These are not really side effects, but we still reuse this field. - - var Incomplete = - /* */ - 32768; - var ShouldCapture = - /* */ - 65536; - var ForceUpdateForLegacySuspense = - /* */ - 131072; - var Forked = - /* */ - 1048576; // Static tags describe aspects of a fiber that are not specific to a render, - // e.g. a fiber uses a passive effect (even if there are no updates on this particular render). - // This enables us to defer more work in the unmount case, - // since we can defer traversing the tree during layout to look for Passive effects, - // and instead rely on the static flag as a signal that there may be cleanup work. - - var RefStatic = - /* */ - 2097152; - var LayoutStatic = - /* */ - 4194304; - var PassiveStatic = - /* */ - 8388608; // These flags allow us to traverse to fibers that have effects on mount - // without traversing the entire tree after every commit for - // double invoking - - var MountLayoutDev = - /* */ - 16777216; - var MountPassiveDev = - /* */ - 33554432; // Groups of flags that are used in the commit phase to skip over trees that - // don't contain effects, by checking subtreeFlags. - - var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility - // flag logic (see #20043) - Update | Snapshot | ( 0); - var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; - var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask - - var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones. - // This allows certain concepts to persist without recalculating them, - // e.g. whether a subtree contains passive effects or portals. - - var StaticMask = LayoutStatic | PassiveStatic | RefStatic; - - var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; - function getNearestMountedFiber(fiber) { - var node = fiber; - var nearestMounted = fiber; - - if (!fiber.alternate) { - // If there is no alternate, this might be a new tree that isn't inserted - // yet. If it is, then it will have a pending insertion effect on it. - var nextNode = node; - - do { - node = nextNode; - - if ((node.flags & (Placement | Hydrating)) !== NoFlags) { - // This is an insertion or in-progress hydration. The nearest possible - // mounted fiber is the parent but we need to continue to figure out - // if that one is still mounted. - nearestMounted = node.return; - } - - nextNode = node.return; - } while (nextNode); - } else { - while (node.return) { - node = node.return; - } - } - - if (node.tag === HostRoot) { - // TODO: Check if this was a nested HostRoot when used with - // renderContainerIntoSubtree. - return nearestMounted; - } // If we didn't hit the root, that means that we're in an disconnected tree - // that has been unmounted. - - - return null; - } - function isFiberMounted(fiber) { - return getNearestMountedFiber(fiber) === fiber; - } - function isMounted(component) { - { - var owner = ReactCurrentOwner.current; - - if (owner !== null && owner.tag === ClassComponent) { - var ownerFiber = owner; - var instance = ownerFiber.stateNode; - - if (!instance._warnedAboutRefsInRender) { - error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component'); - } - - instance._warnedAboutRefsInRender = true; - } - } - - var fiber = get(component); - - if (!fiber) { - return false; - } - - return getNearestMountedFiber(fiber) === fiber; - } - - function assertIsMounted(fiber) { - if (getNearestMountedFiber(fiber) !== fiber) { - throw new Error('Unable to find node on an unmounted component.'); - } - } - - function findCurrentFiberUsingSlowPath(fiber) { - var alternate = fiber.alternate; - - if (!alternate) { - // If there is no alternate, then we only need to check if it is mounted. - var nearestMounted = getNearestMountedFiber(fiber); - - if (nearestMounted === null) { - throw new Error('Unable to find node on an unmounted component.'); - } - - if (nearestMounted !== fiber) { - return null; - } - - return fiber; - } // If we have two possible branches, we'll walk backwards up to the root - // to see what path the root points to. On the way we may hit one of the - // special cases and we'll deal with them. - - - var a = fiber; - var b = alternate; - - while (true) { - var parentA = a.return; - - if (parentA === null) { - // We're at the root. - break; - } - - var parentB = parentA.alternate; - - if (parentB === null) { - // There is no alternate. This is an unusual case. Currently, it only - // happens when a Suspense component is hidden. An extra fragment fiber - // is inserted in between the Suspense fiber and its children. Skip - // over this extra fragment fiber and proceed to the next parent. - var nextParent = parentA.return; - - if (nextParent !== null) { - a = b = nextParent; - continue; - } // If there's no parent, we're at the root. - - - break; - } // If both copies of the parent fiber point to the same child, we can - // assume that the child is current. This happens when we bailout on low - // priority: the bailed out fiber's child reuses the current child. - - - if (parentA.child === parentB.child) { - var child = parentA.child; - - while (child) { - if (child === a) { - // We've determined that A is the current branch. - assertIsMounted(parentA); - return fiber; - } - - if (child === b) { - // We've determined that B is the current branch. - assertIsMounted(parentA); - return alternate; - } - - child = child.sibling; - } // We should never have an alternate for any mounting node. So the only - // way this could possibly happen is if this was unmounted, if at all. - - - throw new Error('Unable to find node on an unmounted component.'); - } - - if (a.return !== b.return) { - // The return pointer of A and the return pointer of B point to different - // fibers. We assume that return pointers never criss-cross, so A must - // belong to the child set of A.return, and B must belong to the child - // set of B.return. - a = parentA; - b = parentB; - } else { - // The return pointers point to the same fiber. We'll have to use the - // default, slow path: scan the child sets of each parent alternate to see - // which child belongs to which set. - // - // Search parent A's child set - var didFindChild = false; - var _child = parentA.child; - - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentA; - b = parentB; - break; - } - - if (_child === b) { - didFindChild = true; - b = parentA; - a = parentB; - break; - } - - _child = _child.sibling; - } - - if (!didFindChild) { - // Search parent B's child set - _child = parentB.child; - - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentB; - b = parentA; - break; - } - - if (_child === b) { - didFindChild = true; - b = parentB; - a = parentA; - break; - } - - _child = _child.sibling; - } - - if (!didFindChild) { - throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.'); - } - } - } - - if (a.alternate !== b) { - throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.'); - } - } // If the root is not a host container, we're in a disconnected tree. I.e. - // unmounted. - - - if (a.tag !== HostRoot) { - throw new Error('Unable to find node on an unmounted component.'); - } - - if (a.stateNode.current === a) { - // We've determined that A is the current branch. - return fiber; - } // Otherwise B has to be current branch. - - - return alternate; - } - function findCurrentHostFiber(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null; - } - - function findCurrentHostFiberImpl(node) { - // Next we'll drill down this component to find the first HostComponent/Text. - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } - - var child = node.child; - - while (child !== null) { - var match = findCurrentHostFiberImpl(child); - - if (match !== null) { - return match; - } - - child = child.sibling; - } - - return null; - } - - function findCurrentHostFiberWithNoPortals(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null; - } - - function findCurrentHostFiberWithNoPortalsImpl(node) { - // Next we'll drill down this component to find the first HostComponent/Text. - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } - - var child = node.child; - - while (child !== null) { - if (child.tag !== HostPortal) { - var match = findCurrentHostFiberWithNoPortalsImpl(child); - - if (match !== null) { - return match; - } - } - - child = child.sibling; - } - - return null; - } - - var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare - - function isArray(a) { - return isArrayImpl(a); - } - - // This is a host config that's used for the `react-reconciler` package on npm. - // It is only used by third-party renderers. - // - // Its API lets you pass the host config as an argument. - // However, inside the `react-reconciler` we treat host config as a module. - // This file is a shim between two worlds. - // - // It works because the `react-reconciler` bundle is wrapped in something like: - // - // module.exports = function ($$$config) { - // /* reconciler code */ - // } - // - // So `$$$config` looks like a global variable, but it's - // really an argument to a top-level wrapping function. - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - var getPublicInstance = $$$hostConfig.getPublicInstance; - var getRootHostContext = $$$hostConfig.getRootHostContext; - var getChildHostContext = $$$hostConfig.getChildHostContext; - var prepareForCommit = $$$hostConfig.prepareForCommit; - var resetAfterCommit = $$$hostConfig.resetAfterCommit; - var createInstance = $$$hostConfig.createInstance; - var appendInitialChild = $$$hostConfig.appendInitialChild; - var finalizeInitialChildren = $$$hostConfig.finalizeInitialChildren; - var prepareUpdate = $$$hostConfig.prepareUpdate; - var shouldSetTextContent = $$$hostConfig.shouldSetTextContent; - var createTextInstance = $$$hostConfig.createTextInstance; - var scheduleTimeout = $$$hostConfig.scheduleTimeout; - var cancelTimeout = $$$hostConfig.cancelTimeout; - var noTimeout = $$$hostConfig.noTimeout; - $$$hostConfig.now; - var isPrimaryRenderer = $$$hostConfig.isPrimaryRenderer; - var warnsIfNotActing = $$$hostConfig.warnsIfNotActing; - var supportsMutation = $$$hostConfig.supportsMutation; - var supportsPersistence = $$$hostConfig.supportsPersistence; - var supportsHydration = $$$hostConfig.supportsHydration; - var getInstanceFromNode = $$$hostConfig.getInstanceFromNode; - $$$hostConfig.beforeActiveInstanceBlur; - $$$hostConfig.afterActiveInstanceBlur; - var preparePortalMount = $$$hostConfig.preparePortalMount; - $$$hostConfig.preparePortalMount; - $$$hostConfig.getInstanceFromScope; - var getCurrentEventPriority = $$$hostConfig.getCurrentEventPriority; - var detachDeletedInstance = $$$hostConfig.detachDeletedInstance; // ------------------- - // Microtasks - // (optional) - // ------------------- - - var supportsMicrotasks = $$$hostConfig.supportsMicrotasks; - var scheduleMicrotask = $$$hostConfig.scheduleMicrotask; // ------------------- - // Test selectors - // (optional) - // ------------------- - - var supportsTestSelectors = $$$hostConfig.supportsTestSelectors; - var findFiberRoot = $$$hostConfig.findFiberRoot; - var getBoundingRect = $$$hostConfig.getBoundingRect; - var getTextContent = $$$hostConfig.getTextContent; - var isHiddenSubtree = $$$hostConfig.isHiddenSubtree; - var matchAccessibilityRole = $$$hostConfig.matchAccessibilityRole; - var setFocusIfFocusable = $$$hostConfig.setFocusIfFocusable; - var setupIntersectionObserver = $$$hostConfig.setupIntersectionObserver; // ------------------- - // Mutation - // (optional) - // ------------------- - - var appendChild = $$$hostConfig.appendChild; - var appendChildToContainer = $$$hostConfig.appendChildToContainer; - var commitTextUpdate = $$$hostConfig.commitTextUpdate; - var commitMount = $$$hostConfig.commitMount; - var commitUpdate = $$$hostConfig.commitUpdate; - var insertBefore = $$$hostConfig.insertBefore; - var insertInContainerBefore = $$$hostConfig.insertInContainerBefore; - var removeChild = $$$hostConfig.removeChild; - var removeChildFromContainer = $$$hostConfig.removeChildFromContainer; - var resetTextContent = $$$hostConfig.resetTextContent; - var hideInstance = $$$hostConfig.hideInstance; - var hideTextInstance = $$$hostConfig.hideTextInstance; - var unhideInstance = $$$hostConfig.unhideInstance; - var unhideTextInstance = $$$hostConfig.unhideTextInstance; - var clearContainer = $$$hostConfig.clearContainer; // ------------------- - // Persistence - // (optional) - // ------------------- - - var cloneInstance = $$$hostConfig.cloneInstance; - var createContainerChildSet = $$$hostConfig.createContainerChildSet; - var appendChildToContainerChildSet = $$$hostConfig.appendChildToContainerChildSet; - var finalizeContainerChildren = $$$hostConfig.finalizeContainerChildren; - var replaceContainerChildren = $$$hostConfig.replaceContainerChildren; - $$$hostConfig.getOffscreenContainerType; - var getOffscreenContainerProps = $$$hostConfig.getOffscreenContainerProps; - var cloneHiddenInstance = $$$hostConfig.cloneHiddenInstance; - var cloneHiddenTextInstance = $$$hostConfig.cloneHiddenTextInstance; // ------------------- - // Hydration - // (optional) - // ------------------- - - var canHydrateInstance = $$$hostConfig.canHydrateInstance; - var canHydrateTextInstance = $$$hostConfig.canHydrateTextInstance; - var canHydrateSuspenseInstance = $$$hostConfig.canHydrateSuspenseInstance; - var isSuspenseInstancePending = $$$hostConfig.isSuspenseInstancePending; - var isSuspenseInstanceFallback = $$$hostConfig.isSuspenseInstanceFallback; - var registerSuspenseInstanceRetry = $$$hostConfig.registerSuspenseInstanceRetry; - var getNextHydratableSibling = $$$hostConfig.getNextHydratableSibling; - var getFirstHydratableChild = $$$hostConfig.getFirstHydratableChild; - var getFirstHydratableChildWithinContainer = $$$hostConfig.getFirstHydratableChildWithinContainer; - var getFirstHydratableChildWithinSuspenseInstance = $$$hostConfig.getFirstHydratableChildWithinSuspenseInstance; - var hydrateInstance = $$$hostConfig.hydrateInstance; - var hydrateTextInstance = $$$hostConfig.hydrateTextInstance; - var hydrateSuspenseInstance = $$$hostConfig.hydrateSuspenseInstance; - var getNextHydratableInstanceAfterSuspenseInstance = $$$hostConfig.getNextHydratableInstanceAfterSuspenseInstance; - var commitHydratedContainer = $$$hostConfig.commitHydratedContainer; - var commitHydratedSuspenseInstance = $$$hostConfig.commitHydratedSuspenseInstance; - var clearSuspenseBoundary = $$$hostConfig.clearSuspenseBoundary; - var clearSuspenseBoundaryFromContainer = $$$hostConfig.clearSuspenseBoundaryFromContainer; - var shouldDeleteUnhydratedTailInstances = $$$hostConfig.shouldDeleteUnhydratedTailInstances; - var didNotMatchHydratedContainerTextInstance = $$$hostConfig.didNotMatchHydratedContainerTextInstance; - var didNotMatchHydratedTextInstance = $$$hostConfig.didNotMatchHydratedTextInstance; - var didNotHydrateInstanceWithinContainer = $$$hostConfig.didNotHydrateInstanceWithinContainer; - var didNotHydrateInstanceWithinSuspenseInstance = $$$hostConfig.didNotHydrateInstanceWithinSuspenseInstance; - var didNotHydrateInstance = $$$hostConfig.didNotHydrateInstance; - var didNotFindHydratableInstanceWithinContainer = $$$hostConfig.didNotFindHydratableInstanceWithinContainer; - var didNotFindHydratableTextInstanceWithinContainer = $$$hostConfig.didNotFindHydratableTextInstanceWithinContainer; - var didNotFindHydratableSuspenseInstanceWithinContainer = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinContainer; - var didNotFindHydratableInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableInstanceWithinSuspenseInstance; - var didNotFindHydratableTextInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableTextInstanceWithinSuspenseInstance; - var didNotFindHydratableSuspenseInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinSuspenseInstance; - var didNotFindHydratableInstance = $$$hostConfig.didNotFindHydratableInstance; - var didNotFindHydratableTextInstance = $$$hostConfig.didNotFindHydratableTextInstance; - var didNotFindHydratableSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstance; - var errorHydratingContainer = $$$hostConfig.errorHydratingContainer; - - // Helpers to patch console.logs to avoid logging during side-effect free - // replaying on render function. This currently only patches the object - // lazily which won't cover if the log function was extracted eagerly. - // We could also eagerly patch the method. - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - - function disabledLog() {} - - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 - - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - /* eslint-enable react-internal/no-production-logging */ - } - - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - /* eslint-enable react-internal/no-production-logging */ - } - - if (disabledDepth < 0) { - error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); - } - } - } - - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ''; - } - } // We use the prefix to ensure our stacks line up with native stack frames. - - - return '\n' + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - - { - var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - - function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if ( !fn || reentry) { - return ''; - } - - { - var frame = componentFrameCache.get(fn); - - if (frame !== undefined) { - return frame; - } - } - - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. - - Error.prepareStackTrace = undefined; - var previousDispatcher; - - { - previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function - // for warnings. - - ReactCurrentDispatcher.current = null; - disableLogs(); - } - - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error(); - }; // $FlowFixMe - - - Object.defineProperty(Fake.prototype, 'props', { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error(); - } - }); - - if (typeof Reflect === 'object' && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - - fn(); - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === 'string') { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sample.stack.split('\n'); - var controlLines = control.stack.split('\n'); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c--; - } - - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s--; - c--; // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. - - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" - // but we have a user-provided "displayName" - // splice it in to make the stack more readable. - - - if (fn.displayName && _frame.includes('')) { - _frame = _frame.replace('', fn.displayName); - } - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, _frame); - } - } // Return the line we found. - - - return _frame; - } - } while (s >= 1 && c >= 0); - } - - break; - } - } - } - } finally { - reentry = false; - - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - - Error.prepareStackTrace = previousPrepareStackTrace; - } // Fallback to just using the name if we couldn't make it throw. - - - var name = fn ? fn.displayName || fn.name : ''; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, syntheticFrame); - } - } - - return syntheticFrame; - } - - function describeClassComponentFrame(ctor, source, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - - function shouldConstruct(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - - if (type == null) { - return ''; - } - - if (typeof type === 'function') { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - - if (typeof type === 'string') { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame('Suspense'); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame('SuspenseList'); - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) {} - } - } - } - - return ''; - } - - var hasOwnProperty = Object.prototype.hasOwnProperty; - - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } - } - - function checkPropTypes(typeSpecs, values, location, componentName, element) { - { - // $FlowFixMe This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== 'function') { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); - err.name = 'Invariant Violation'; - throw err; - } - - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); - - setCurrentlyValidatingElement(null); - } - - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error('Failed %s type: %s', location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - - var valueStack = []; - var fiberStack; - - { - fiberStack = []; - } - - var index = -1; - - function createCursor(defaultValue) { - return { - current: defaultValue - }; - } - - function pop(cursor, fiber) { - if (index < 0) { - { - error('Unexpected pop.'); - } - - return; - } - - { - if (fiber !== fiberStack[index]) { - error('Unexpected Fiber popped.'); - } - } - - cursor.current = valueStack[index]; - valueStack[index] = null; - - { - fiberStack[index] = null; - } - - index--; - } - - function push(cursor, value, fiber) { - index++; - valueStack[index] = cursor.current; - - { - fiberStack[index] = fiber; - } - - cursor.current = value; - } - - var warnedAboutMissingGetChildContext; - - { - warnedAboutMissingGetChildContext = {}; - } - - var emptyContextObject = {}; - - { - Object.freeze(emptyContextObject); - } // A cursor to the current merged context object on the stack. - - - var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. - - var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. - // We use this to get access to the parent context after we have already - // pushed the next context provider, and now need to merge their contexts. - - var previousContext = emptyContextObject; - - function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) { - { - if (didPushOwnContextIfProvider && isContextProvider(Component)) { - // If the fiber is a context provider itself, when we read its context - // we may have already pushed its own child context on the stack. A context - // provider should not "see" its own child context. Therefore we read the - // previous (parent) context instead for a context provider. - return previousContext; - } - - return contextStackCursor.current; - } - } - - function cacheContext(workInProgress, unmaskedContext, maskedContext) { - { - var instance = workInProgress.stateNode; - instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; - instance.__reactInternalMemoizedMaskedChildContext = maskedContext; - } - } - - function getMaskedContext(workInProgress, unmaskedContext) { - { - var type = workInProgress.type; - var contextTypes = type.contextTypes; - - if (!contextTypes) { - return emptyContextObject; - } // Avoid recreating masked context unless unmasked context has changed. - // Failing to do this will result in unnecessary calls to componentWillReceiveProps. - // This may trigger infinite loops if componentWillReceiveProps calls setState. - - - var instance = workInProgress.stateNode; - - if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { - return instance.__reactInternalMemoizedMaskedChildContext; - } - - var context = {}; - - for (var key in contextTypes) { - context[key] = unmaskedContext[key]; - } - - { - var name = getComponentNameFromFiber(workInProgress) || 'Unknown'; - checkPropTypes(contextTypes, context, 'context', name); - } // Cache unmasked context so we can avoid recreating masked context unless necessary. - // Context is created before the class component is instantiated so check for instance. - - - if (instance) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return context; - } - } - - function hasContextChanged() { - { - return didPerformWorkStackCursor.current; - } - } - - function isContextProvider(type) { - { - var childContextTypes = type.childContextTypes; - return childContextTypes !== null && childContextTypes !== undefined; - } - } - - function popContext(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } - } - - function popTopLevelContextObject(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } - } - - function pushTopLevelContextObject(fiber, context, didChange) { - { - if (contextStackCursor.current !== emptyContextObject) { - throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - push(contextStackCursor, context, fiber); - push(didPerformWorkStackCursor, didChange, fiber); - } - } - - function processChildContext(fiber, type, parentContext) { - { - var instance = fiber.stateNode; - var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. - // It has only been added in Fiber to match the (unintentional) behavior in Stack. - - if (typeof instance.getChildContext !== 'function') { - { - var componentName = getComponentNameFromFiber(fiber) || 'Unknown'; - - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; - - error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); - } - } - - return parentContext; - } - - var childContext = instance.getChildContext(); - - for (var contextKey in childContext) { - if (!(contextKey in childContextTypes)) { - throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); - } - } - - { - var name = getComponentNameFromFiber(fiber) || 'Unknown'; - checkPropTypes(childContextTypes, childContext, 'child context', name); - } - - return assign({}, parentContext, childContext); - } - } - - function pushContextProvider(workInProgress) { - { - var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. - // If the instance does not exist yet, we will push null at first, - // and replace it on the stack later when invalidating the context. - - var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later. - // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. - - previousContext = contextStackCursor.current; - push(contextStackCursor, memoizedMergedChildContext, workInProgress); - push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress); - return true; - } - } - - function invalidateContextProvider(workInProgress, type, didChange) { - { - var instance = workInProgress.stateNode; - - if (!instance) { - throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - if (didChange) { - // Merge parent and own context. - // Skip this if we're not updating due to sCU. - // This avoids unnecessarily recomputing memoized values. - var mergedContext = processChildContext(workInProgress, type, previousContext); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. - // It is important to unwind the context in the reverse order. - - pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. - - push(contextStackCursor, mergedContext, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } else { - pop(didPerformWorkStackCursor, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } - } - } - - function findCurrentUnmaskedContext(fiber) { - { - // Currently this is only used with renderSubtreeIntoContainer; not sure if it - // makes sense elsewhere - if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { - throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var node = fiber; - - do { - switch (node.tag) { - case HostRoot: - return node.stateNode.context; - - case ClassComponent: - { - var Component = node.type; - - if (isContextProvider(Component)) { - return node.stateNode.__reactInternalMemoizedMergedChildContext; - } - - break; - } - } - - node = node.return; - } while (node !== null); - - throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - } - - var LegacyRoot = 0; - var ConcurrentRoot = 1; - - var NoMode = - /* */ - 0; // TODO: Remove ConcurrentMode by reading from the root tag instead - - var ConcurrentMode = - /* */ - 1; - var ProfileMode = - /* */ - 2; - var StrictLegacyMode = - /* */ - 8; - var StrictEffectsMode = - /* */ - 16; - - // TODO: This is pretty well supported by browsers. Maybe we can drop it. - var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. - // Based on: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 - - var log = Math.log; - var LN2 = Math.LN2; - - function clz32Fallback(x) { - var asUint = x >>> 0; - - if (asUint === 0) { - return 32; - } - - return 31 - (log(asUint) / LN2 | 0) | 0; - } - - // If those values are changed that package should be rebuilt and redeployed. - - var TotalLanes = 31; - var NoLanes = - /* */ - 0; - var NoLane = - /* */ - 0; - var SyncLane = - /* */ - 1; - var InputContinuousHydrationLane = - /* */ - 2; - var InputContinuousLane = - /* */ - 4; - var DefaultHydrationLane = - /* */ - 8; - var DefaultLane = - /* */ - 16; - var TransitionHydrationLane = - /* */ - 32; - var TransitionLanes = - /* */ - 4194240; - var TransitionLane1 = - /* */ - 64; - var TransitionLane2 = - /* */ - 128; - var TransitionLane3 = - /* */ - 256; - var TransitionLane4 = - /* */ - 512; - var TransitionLane5 = - /* */ - 1024; - var TransitionLane6 = - /* */ - 2048; - var TransitionLane7 = - /* */ - 4096; - var TransitionLane8 = - /* */ - 8192; - var TransitionLane9 = - /* */ - 16384; - var TransitionLane10 = - /* */ - 32768; - var TransitionLane11 = - /* */ - 65536; - var TransitionLane12 = - /* */ - 131072; - var TransitionLane13 = - /* */ - 262144; - var TransitionLane14 = - /* */ - 524288; - var TransitionLane15 = - /* */ - 1048576; - var TransitionLane16 = - /* */ - 2097152; - var RetryLanes = - /* */ - 130023424; - var RetryLane1 = - /* */ - 4194304; - var RetryLane2 = - /* */ - 8388608; - var RetryLane3 = - /* */ - 16777216; - var RetryLane4 = - /* */ - 33554432; - var RetryLane5 = - /* */ - 67108864; - var SomeRetryLane = RetryLane1; - var SelectiveHydrationLane = - /* */ - 134217728; - var NonIdleLanes = - /* */ - 268435455; - var IdleHydrationLane = - /* */ - 268435456; - var IdleLane = - /* */ - 536870912; - var OffscreenLane = - /* */ - 1073741824; // This function is used for the experimental timeline (react-devtools-timeline) - // It should be kept in sync with the Lanes values above. - - function getLabelForLane(lane) { - { - if (lane & SyncLane) { - return 'Sync'; - } - - if (lane & InputContinuousHydrationLane) { - return 'InputContinuousHydration'; - } - - if (lane & InputContinuousLane) { - return 'InputContinuous'; - } - - if (lane & DefaultHydrationLane) { - return 'DefaultHydration'; - } - - if (lane & DefaultLane) { - return 'Default'; - } - - if (lane & TransitionHydrationLane) { - return 'TransitionHydration'; - } - - if (lane & TransitionLanes) { - return 'Transition'; - } - - if (lane & RetryLanes) { - return 'Retry'; - } - - if (lane & SelectiveHydrationLane) { - return 'SelectiveHydration'; - } - - if (lane & IdleHydrationLane) { - return 'IdleHydration'; - } - - if (lane & IdleLane) { - return 'Idle'; - } - - if (lane & OffscreenLane) { - return 'Offscreen'; - } - } - } - var NoTimestamp = -1; - var nextTransitionLane = TransitionLane1; - var nextRetryLane = RetryLane1; - - function getHighestPriorityLanes(lanes) { - switch (getHighestPriorityLane(lanes)) { - case SyncLane: - return SyncLane; - - case InputContinuousHydrationLane: - return InputContinuousHydrationLane; - - case InputContinuousLane: - return InputContinuousLane; - - case DefaultHydrationLane: - return DefaultHydrationLane; - - case DefaultLane: - return DefaultLane; - - case TransitionHydrationLane: - return TransitionHydrationLane; - - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - return lanes & TransitionLanes; - - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - case RetryLane5: - return lanes & RetryLanes; - - case SelectiveHydrationLane: - return SelectiveHydrationLane; - - case IdleHydrationLane: - return IdleHydrationLane; - - case IdleLane: - return IdleLane; - - case OffscreenLane: - return OffscreenLane; - - default: - { - error('Should have found matching lanes. This is a bug in React.'); - } // This shouldn't be reachable, but as a fallback, return the entire bitmask. - - - return lanes; - } - } - - function getNextLanes(root, wipLanes) { - // Early bailout if there's no pending work left. - var pendingLanes = root.pendingLanes; - - if (pendingLanes === NoLanes) { - return NoLanes; - } - - var nextLanes = NoLanes; - var suspendedLanes = root.suspendedLanes; - var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished, - // even if the work is suspended. - - var nonIdlePendingLanes = pendingLanes & NonIdleLanes; - - if (nonIdlePendingLanes !== NoLanes) { - var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; - - if (nonIdleUnblockedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); - } else { - var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; - - if (nonIdlePingedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); - } - } - } else { - // The only remaining work is Idle. - var unblockedLanes = pendingLanes & ~suspendedLanes; - - if (unblockedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(unblockedLanes); - } else { - if (pingedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(pingedLanes); - } - } - } - - if (nextLanes === NoLanes) { - // This should only be reachable if we're suspended - // TODO: Consider warning in this path if a fallback timer is not scheduled. - return NoLanes; - } // If we're already in the middle of a render, switching lanes will interrupt - // it and we'll lose our progress. We should only do this if the new lanes are - // higher priority. - - - if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't - // bother waiting until the root is complete. - (wipLanes & suspendedLanes) === NoLanes) { - var nextLane = getHighestPriorityLane(nextLanes); - var wipLane = getHighestPriorityLane(wipLanes); - - if ( // Tests whether the next lane is equal or lower priority than the wip - // one. This works because the bits decrease in priority as you go left. - nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The - // only difference between default updates and transition updates is that - // default updates do not support refresh transitions. - nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) { - // Keep working on the existing in-progress tree. Do not interrupt. - return wipLanes; - } - } - - if ((nextLanes & InputContinuousLane) !== NoLanes) { - // When updates are sync by default, we entangle continuous priority updates - // and default updates, so they render in the same batch. The only reason - // they use separate lanes is because continuous updates should interrupt - // transitions, but default updates should not. - nextLanes |= pendingLanes & DefaultLane; - } // Check for entangled lanes and add them to the batch. - // - // A lane is said to be entangled with another when it's not allowed to render - // in a batch that does not also include the other lane. Typically we do this - // when multiple updates have the same source, and we only want to respond to - // the most recent event from that source. - // - // Note that we apply entanglements *after* checking for partial work above. - // This means that if a lane is entangled during an interleaved event while - // it's already rendering, we won't interrupt it. This is intentional, since - // entanglement is usually "best effort": we'll try our best to render the - // lanes in the same batch, but it's not worth throwing out partially - // completed work in order to do it. - // TODO: Reconsider this. The counter-argument is that the partial work - // represents an intermediate state, which we don't want to show to the user. - // And by spending extra time finishing it, we're increasing the amount of - // time it takes to show the final state, which is what they are actually - // waiting for. - // - // For those exceptions where entanglement is semantically important, like - // useMutableSource, we should ensure that there is no partial work at the - // time we apply the entanglement. - - - var entangledLanes = root.entangledLanes; - - if (entangledLanes !== NoLanes) { - var entanglements = root.entanglements; - var lanes = nextLanes & entangledLanes; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - nextLanes |= entanglements[index]; - lanes &= ~lane; - } - } - - return nextLanes; - } - function getMostRecentEventTime(root, lanes) { - var eventTimes = root.eventTimes; - var mostRecentEventTime = NoTimestamp; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - var eventTime = eventTimes[index]; - - if (eventTime > mostRecentEventTime) { - mostRecentEventTime = eventTime; - } - - lanes &= ~lane; - } - - return mostRecentEventTime; - } - - function computeExpirationTime(lane, currentTime) { - switch (lane) { - case SyncLane: - case InputContinuousHydrationLane: - case InputContinuousLane: - // User interactions should expire slightly more quickly. - // - // NOTE: This is set to the corresponding constant as in Scheduler.js. - // When we made it larger, a product metric in www regressed, suggesting - // there's a user interaction that's being starved by a series of - // synchronous updates. If that theory is correct, the proper solution is - // to fix the starvation. However, this scenario supports the idea that - // expiration times are an important safeguard when starvation - // does happen. - return currentTime + 250; - - case DefaultHydrationLane: - case DefaultLane: - case TransitionHydrationLane: - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - return currentTime + 5000; - - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - case RetryLane5: - // TODO: Retries should be allowed to expire if they are CPU bound for - // too long, but when I made this change it caused a spike in browser - // crashes. There must be some other underlying bug; not super urgent but - // ideally should figure out why and fix it. Unfortunately we don't have - // a repro for the crashes, only detected via production metrics. - return NoTimestamp; - - case SelectiveHydrationLane: - case IdleHydrationLane: - case IdleLane: - case OffscreenLane: - // Anything idle priority or lower should never expire. - return NoTimestamp; - - default: - { - error('Should have found matching lanes. This is a bug in React.'); - } - - return NoTimestamp; - } - } - - function markStarvedLanesAsExpired(root, currentTime) { - // TODO: This gets called every time we yield. We can optimize by storing - // the earliest expiration time on the root. Then use that to quickly bail out - // of this function. - var pendingLanes = root.pendingLanes; - var suspendedLanes = root.suspendedLanes; - var pingedLanes = root.pingedLanes; - var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their - // expiration time. If so, we'll assume the update is being starved and mark - // it as expired to force it to finish. - - var lanes = pendingLanes; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - var expirationTime = expirationTimes[index]; - - if (expirationTime === NoTimestamp) { - // Found a pending lane with no expiration time. If it's not suspended, or - // if it's pinged, assume it's CPU-bound. Compute a new expiration time - // using the current time. - if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) { - // Assumes timestamps are monotonically increasing. - expirationTimes[index] = computeExpirationTime(lane, currentTime); - } - } else if (expirationTime <= currentTime) { - // This lane expired - root.expiredLanes |= lane; - } - - lanes &= ~lane; - } - } // This returns the highest priority pending lanes regardless of whether they - // are suspended. - - function getHighestPriorityPendingLanes(root) { - return getHighestPriorityLanes(root.pendingLanes); - } - function getLanesToRetrySynchronouslyOnError(root) { - var everythingButOffscreen = root.pendingLanes & ~OffscreenLane; - - if (everythingButOffscreen !== NoLanes) { - return everythingButOffscreen; - } - - if (everythingButOffscreen & OffscreenLane) { - return OffscreenLane; - } - - return NoLanes; - } - function includesSyncLane(lanes) { - return (lanes & SyncLane) !== NoLanes; - } - function includesNonIdleWork(lanes) { - return (lanes & NonIdleLanes) !== NoLanes; - } - function includesOnlyRetries(lanes) { - return (lanes & RetryLanes) === lanes; - } - function includesOnlyTransitions(lanes) { - return (lanes & TransitionLanes) === lanes; - } - function includesBlockingLane(root, lanes) { - - var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane; - return (lanes & SyncDefaultLanes) !== NoLanes; - } - function includesExpiredLane(root, lanes) { - // This is a separate check from includesBlockingLane because a lane can - // expire after a render has already started. - return (lanes & root.expiredLanes) !== NoLanes; - } - function isTransitionLane(lane) { - return (lane & TransitionLanes) !== 0; - } - function claimNextTransitionLane() { - // Cycle through the lanes, assigning each new transition to the next lane. - // In most cases, this means every transition gets its own lane, until we - // run out of lanes and cycle back to the beginning. - var lane = nextTransitionLane; - nextTransitionLane <<= 1; - - if ((nextTransitionLane & TransitionLanes) === 0) { - nextTransitionLane = TransitionLane1; - } - - return lane; - } - function claimNextRetryLane() { - var lane = nextRetryLane; - nextRetryLane <<= 1; - - if ((nextRetryLane & RetryLanes) === 0) { - nextRetryLane = RetryLane1; - } - - return lane; - } - function getHighestPriorityLane(lanes) { - return lanes & -lanes; - } - function pickArbitraryLane(lanes) { - // This wrapper function gets inlined. Only exists so to communicate that it - // doesn't matter which bit is selected; you can pick any bit without - // affecting the algorithms where its used. Here I'm using - // getHighestPriorityLane because it requires the fewest operations. - return getHighestPriorityLane(lanes); - } - - function pickArbitraryLaneIndex(lanes) { - return 31 - clz32(lanes); - } - - function laneToIndex(lane) { - return pickArbitraryLaneIndex(lane); - } - - function includesSomeLane(a, b) { - return (a & b) !== NoLanes; - } - function isSubsetOfLanes(set, subset) { - return (set & subset) === subset; - } - function mergeLanes(a, b) { - return a | b; - } - function removeLanes(set, subset) { - return set & ~subset; - } - function intersectLanes(a, b) { - return a & b; - } // Seems redundant, but it changes the type from a single lane (used for - // updates) to a group of lanes (used for flushing work). - - function laneToLanes(lane) { - return lane; - } - function higherPriorityLane(a, b) { - // This works because the bit ranges decrease in priority as you go left. - return a !== NoLane && a < b ? a : b; - } - function createLaneMap(initial) { - // Intentionally pushing one by one. - // https://v8.dev/blog/elements-kinds#avoid-creating-holes - var laneMap = []; - - for (var i = 0; i < TotalLanes; i++) { - laneMap.push(initial); - } - - return laneMap; - } - function markRootUpdated(root, updateLane, eventTime) { - root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update - // could unblock them. Clear the suspended lanes so that we can try rendering - // them again. - // - // TODO: We really only need to unsuspend only lanes that are in the - // `subtreeLanes` of the updated fiber, or the update lanes of the return - // path. This would exclude suspended updates in an unrelated sibling tree, - // since there's no way for this update to unblock it. - // - // We don't do this if the incoming update is idle, because we never process - // idle updates until after all the regular updates have finished; there's no - // way it could unblock a transition. - - if (updateLane !== IdleLane) { - root.suspendedLanes = NoLanes; - root.pingedLanes = NoLanes; - } - - var eventTimes = root.eventTimes; - var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most - // recent event, and we assume time is monotonically increasing. - - eventTimes[index] = eventTime; - } - function markRootSuspended(root, suspendedLanes) { - root.suspendedLanes |= suspendedLanes; - root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times. - - var expirationTimes = root.expirationTimes; - var lanes = suspendedLanes; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - expirationTimes[index] = NoTimestamp; - lanes &= ~lane; - } - } - function markRootPinged(root, pingedLanes, eventTime) { - root.pingedLanes |= root.suspendedLanes & pingedLanes; - } - function markRootFinished(root, remainingLanes) { - var noLongerPendingLanes = root.pendingLanes & ~remainingLanes; - root.pendingLanes = remainingLanes; // Let's try everything again - - root.suspendedLanes = 0; - root.pingedLanes = 0; - root.expiredLanes &= remainingLanes; - root.mutableReadLanes &= remainingLanes; - root.entangledLanes &= remainingLanes; - var entanglements = root.entanglements; - var eventTimes = root.eventTimes; - var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work - - var lanes = noLongerPendingLanes; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - entanglements[index] = NoLanes; - eventTimes[index] = NoTimestamp; - expirationTimes[index] = NoTimestamp; - lanes &= ~lane; - } - } - function markRootEntangled(root, entangledLanes) { - // In addition to entangling each of the given lanes with each other, we also - // have to consider _transitive_ entanglements. For each lane that is already - // entangled with *any* of the given lanes, that lane is now transitively - // entangled with *all* the given lanes. - // - // Translated: If C is entangled with A, then entangling A with B also - // entangles C with B. - // - // If this is hard to grasp, it might help to intentionally break this - // function and look at the tests that fail in ReactTransition-test.js. Try - // commenting out one of the conditions below. - var rootEntangledLanes = root.entangledLanes |= entangledLanes; - var entanglements = root.entanglements; - var lanes = rootEntangledLanes; - - while (lanes) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - - if ( // Is this one of the newly entangled lanes? - lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes? - entanglements[index] & entangledLanes) { - entanglements[index] |= entangledLanes; - } - - lanes &= ~lane; - } - } - function getBumpedLaneForHydration(root, renderLanes) { - var renderLane = getHighestPriorityLane(renderLanes); - var lane; - - switch (renderLane) { - case InputContinuousLane: - lane = InputContinuousHydrationLane; - break; - - case DefaultLane: - lane = DefaultHydrationLane; - break; - - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - case RetryLane5: - lane = TransitionHydrationLane; - break; - - case IdleLane: - lane = IdleHydrationLane; - break; - - default: - // Everything else is already either a hydration lane, or shouldn't - // be retried at a hydration lane. - lane = NoLane; - break; - } // Check if the lane we chose is suspended. If so, that indicates that we - // already attempted and failed to hydrate at that level. Also check if we're - // already rendering that lane, which is rare but could happen. - - - if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) { - // Give up trying to hydrate and fall back to client render. - return NoLane; - } - - return lane; - } - function addFiberToLanesMap(root, fiber, lanes) { - - if (!isDevToolsPresent) { - return; - } - - var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - - while (lanes > 0) { - var index = laneToIndex(lanes); - var lane = 1 << index; - var updaters = pendingUpdatersLaneMap[index]; - updaters.add(fiber); - lanes &= ~lane; - } - } - function movePendingFibersToMemoized(root, lanes) { - - if (!isDevToolsPresent) { - return; - } - - var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - var memoizedUpdaters = root.memoizedUpdaters; - - while (lanes > 0) { - var index = laneToIndex(lanes); - var lane = 1 << index; - var updaters = pendingUpdatersLaneMap[index]; - - if (updaters.size > 0) { - updaters.forEach(function (fiber) { - var alternate = fiber.alternate; - - if (alternate === null || !memoizedUpdaters.has(alternate)) { - memoizedUpdaters.add(fiber); - } - }); - updaters.clear(); - } - - lanes &= ~lane; - } - } - - var DiscreteEventPriority = SyncLane; - var ContinuousEventPriority = InputContinuousLane; - var DefaultEventPriority = DefaultLane; - var IdleEventPriority = IdleLane; - var currentUpdatePriority = NoLane; - function getCurrentUpdatePriority() { - return currentUpdatePriority; - } - function setCurrentUpdatePriority(newPriority) { - currentUpdatePriority = newPriority; - } - function runWithPriority(priority, fn) { - var previousPriority = currentUpdatePriority; - - try { - currentUpdatePriority = priority; - return fn(); - } finally { - currentUpdatePriority = previousPriority; - } - } - function higherEventPriority(a, b) { - return a !== 0 && a < b ? a : b; - } - function lowerEventPriority(a, b) { - return a === 0 || a > b ? a : b; - } - function isHigherEventPriority(a, b) { - return a !== 0 && a < b; - } - function lanesToEventPriority(lanes) { - var lane = getHighestPriorityLane(lanes); - - if (!isHigherEventPriority(DiscreteEventPriority, lane)) { - return DiscreteEventPriority; - } - - if (!isHigherEventPriority(ContinuousEventPriority, lane)) { - return ContinuousEventPriority; - } - - if (includesNonIdleWork(lane)) { - return DefaultEventPriority; - } - - return IdleEventPriority; - } - - // This module only exists as an ESM wrapper around the external CommonJS - var scheduleCallback = Scheduler.unstable_scheduleCallback; - var cancelCallback = Scheduler.unstable_cancelCallback; - var shouldYield = Scheduler.unstable_shouldYield; - var requestPaint = Scheduler.unstable_requestPaint; - var now$1 = Scheduler.unstable_now; - var ImmediatePriority = Scheduler.unstable_ImmediatePriority; - var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; - var NormalPriority = Scheduler.unstable_NormalPriority; - var IdlePriority = Scheduler.unstable_IdlePriority; - // this doesn't actually exist on the scheduler, but it *does* - // on scheduler/unstable_mock, which we'll need for internal testing - var unstable_yieldValue = Scheduler.unstable_yieldValue; - var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue; - - var rendererID = null; - var injectedHook = null; - var injectedProfilingHooks = null; - var hasLoggedError = false; - var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined'; - function injectInternals(internals) { - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { - // No DevTools - return false; - } - - var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; - - if (hook.isDisabled) { - // This isn't a real property on the hook, but it can be set to opt out - // of DevTools integration and associated warnings and logs. - // https://github.com/facebook/react/issues/3877 - return true; - } - - if (!hook.supportsFiber) { - { - error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools'); - } // DevTools exists, even though it doesn't support Fiber. - - - return true; - } - - try { - if (enableSchedulingProfiler) { - // Conditionally inject these hooks only if Timeline profiler is supported by this build. - // This gives DevTools a way to feature detect that isn't tied to version number - // (since profiling and timeline are controlled by different feature flags). - internals = assign({}, internals, { - getLaneLabelMap: getLaneLabelMap, - injectProfilingHooks: injectProfilingHooks - }); - } - - rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. - - injectedHook = hook; - } catch (err) { - // Catch all errors because it is unsafe to throw during initialization. - { - error('React instrumentation encountered an error: %s.', err); - } - } - - if (hook.checkDCE) { - // This is the real DevTools. - return true; - } else { - // This is likely a hook installed by Fast Refresh runtime. - return false; - } - } - function onScheduleRoot(root, children) { - { - if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') { - try { - injectedHook.onScheduleFiberRoot(rendererID, root, children); - } catch (err) { - if ( !hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - function onCommitRoot(root, eventPriority) { - if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { - try { - var didError = (root.current.flags & DidCapture) === DidCapture; - - if (enableProfilerTimer) { - var schedulerPriority; - - switch (eventPriority) { - case DiscreteEventPriority: - schedulerPriority = ImmediatePriority; - break; - - case ContinuousEventPriority: - schedulerPriority = UserBlockingPriority; - break; - - case DefaultEventPriority: - schedulerPriority = NormalPriority; - break; - - case IdleEventPriority: - schedulerPriority = IdlePriority; - break; - - default: - schedulerPriority = NormalPriority; - break; - } - - injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError); - } - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - function onPostCommitRoot(root) { - if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') { - try { - injectedHook.onPostCommitFiberRoot(rendererID, root); - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - function onCommitUnmount(fiber) { - if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') { - try { - injectedHook.onCommitFiberUnmount(rendererID, fiber); - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - function setIsStrictModeForDevtools(newIsStrictMode) { - { - if (typeof unstable_yieldValue === 'function') { - // We're in a test because Scheduler.unstable_yieldValue only exists - // in SchedulerMock. To reduce the noise in strict mode tests, - // suppress warnings and disable scheduler yielding during the double render - unstable_setDisableYieldValue(newIsStrictMode); - setSuppressWarning(newIsStrictMode); - } - - if (injectedHook && typeof injectedHook.setStrictMode === 'function') { - try { - injectedHook.setStrictMode(rendererID, newIsStrictMode); - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - } // Profiler API hooks - - function injectProfilingHooks(profilingHooks) { - injectedProfilingHooks = profilingHooks; - } - - function getLaneLabelMap() { - { - var map = new Map(); - var lane = 1; - - for (var index = 0; index < TotalLanes; index++) { - var label = getLabelForLane(lane); - map.set(lane, label); - lane *= 2; - } - - return map; - } - } - - function markCommitStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') { - injectedProfilingHooks.markCommitStarted(lanes); - } - } - } - function markCommitStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') { - injectedProfilingHooks.markCommitStopped(); - } - } - } - function markComponentRenderStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') { - injectedProfilingHooks.markComponentRenderStarted(fiber); - } - } - } - function markComponentRenderStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') { - injectedProfilingHooks.markComponentRenderStopped(); - } - } - } - function markComponentPassiveEffectMountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') { - injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); - } - } - } - function markComponentPassiveEffectMountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') { - injectedProfilingHooks.markComponentPassiveEffectMountStopped(); - } - } - } - function markComponentPassiveEffectUnmountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') { - injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); - } - } - } - function markComponentPassiveEffectUnmountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') { - injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); - } - } - } - function markComponentLayoutEffectMountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') { - injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); - } - } - } - function markComponentLayoutEffectMountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') { - injectedProfilingHooks.markComponentLayoutEffectMountStopped(); - } - } - } - function markComponentLayoutEffectUnmountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') { - injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); - } - } - } - function markComponentLayoutEffectUnmountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') { - injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); - } - } - } - function markComponentErrored(fiber, thrownValue, lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') { - injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); - } - } - } - function markComponentSuspended(fiber, wakeable, lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') { - injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); - } - } - } - function markLayoutEffectsStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') { - injectedProfilingHooks.markLayoutEffectsStarted(lanes); - } - } - } - function markLayoutEffectsStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') { - injectedProfilingHooks.markLayoutEffectsStopped(); - } - } - } - function markPassiveEffectsStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') { - injectedProfilingHooks.markPassiveEffectsStarted(lanes); - } - } - } - function markPassiveEffectsStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') { - injectedProfilingHooks.markPassiveEffectsStopped(); - } - } - } - function markRenderStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') { - injectedProfilingHooks.markRenderStarted(lanes); - } - } - } - function markRenderYielded() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') { - injectedProfilingHooks.markRenderYielded(); - } - } - } - function markRenderStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') { - injectedProfilingHooks.markRenderStopped(); - } - } - } - function markRenderScheduled(lane) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') { - injectedProfilingHooks.markRenderScheduled(lane); - } - } - } - function markForceUpdateScheduled(fiber, lane) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') { - injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); - } - } - } - function markStateUpdateScheduled(fiber, lane) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') { - injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); - } - } - } - - /** - * inlined Object.is polyfill to avoid requiring consumers ship their own - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - */ - function is(x, y) { - return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare - ; - } - - var objectIs = typeof Object.is === 'function' ? Object.is : is; - - var syncQueue = null; - var includesLegacySyncCallbacks = false; - var isFlushingSyncQueue = false; - function scheduleSyncCallback(callback) { - // Push this callback into an internal queue. We'll flush these either in - // the next tick, or earlier if something calls `flushSyncCallbackQueue`. - if (syncQueue === null) { - syncQueue = [callback]; - } else { - // Push onto existing queue. Don't need to schedule a callback because - // we already scheduled one when we created the queue. - syncQueue.push(callback); - } - } - function scheduleLegacySyncCallback(callback) { - includesLegacySyncCallbacks = true; - scheduleSyncCallback(callback); - } - function flushSyncCallbacksOnlyInLegacyMode() { - // Only flushes the queue if there's a legacy sync callback scheduled. - // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So - // it might make more sense for the queue to be a list of roots instead of a - // list of generic callbacks. Then we can have two: one for legacy roots, one - // for concurrent roots. And this method would only flush the legacy ones. - if (includesLegacySyncCallbacks) { - flushSyncCallbacks(); - } - } - function flushSyncCallbacks() { - if (!isFlushingSyncQueue && syncQueue !== null) { - // Prevent re-entrance. - isFlushingSyncQueue = true; - var i = 0; - var previousUpdatePriority = getCurrentUpdatePriority(); - - try { - var isSync = true; - var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this - // queue is in the render or commit phases. - - setCurrentUpdatePriority(DiscreteEventPriority); - - for (; i < queue.length; i++) { - var callback = queue[i]; - - do { - callback = callback(isSync); - } while (callback !== null); - } - - syncQueue = null; - includesLegacySyncCallbacks = false; - } catch (error) { - // If something throws, leave the remaining callbacks on the queue. - if (syncQueue !== null) { - syncQueue = syncQueue.slice(i + 1); - } // Resume flushing in the next tick - - - scheduleCallback(ImmediatePriority, flushSyncCallbacks); - throw error; - } finally { - setCurrentUpdatePriority(previousUpdatePriority); - isFlushingSyncQueue = false; - } - } - - return null; - } - - // This is imported by the event replaying implementation in React DOM. It's - // in a separate file to break a circular dependency between the renderer and - // the reconciler. - function isRootDehydrated(root) { - var currentState = root.current.memoizedState; - return currentState.isDehydrated; - } - - var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; - var NoTransition = null; - function requestCurrentTransition() { - return ReactCurrentBatchConfig.transition; - } - - /** - * Performs equality by iterating through keys on an object and returning false - * when any key has values which are not strictly equal between the arguments. - * Returns true when the values of all keys are strictly equal. - */ - - function shallowEqual(objA, objB) { - if (objectIs(objA, objB)) { - return true; - } - - if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { - return false; - } - - var keysA = Object.keys(objA); - var keysB = Object.keys(objB); - - if (keysA.length !== keysB.length) { - return false; - } // Test for A's keys different from B. - - - for (var i = 0; i < keysA.length; i++) { - var currentKey = keysA[i]; - - if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) { - return false; - } - } - - return true; - } - - function describeFiber(fiber) { - fiber._debugOwner ? fiber._debugOwner.type : null ; - fiber._debugSource ; - - switch (fiber.tag) { - case HostComponent: - return describeBuiltInComponentFrame(fiber.type); - - case LazyComponent: - return describeBuiltInComponentFrame('Lazy'); - - case SuspenseComponent: - return describeBuiltInComponentFrame('Suspense'); - - case SuspenseListComponent: - return describeBuiltInComponentFrame('SuspenseList'); - - case FunctionComponent: - case IndeterminateComponent: - case SimpleMemoComponent: - return describeFunctionComponentFrame(fiber.type); - - case ForwardRef: - return describeFunctionComponentFrame(fiber.type.render); - - case ClassComponent: - return describeClassComponentFrame(fiber.type); - - default: - return ''; - } - } - - function getStackByFiberInDevAndProd(workInProgress) { - try { - var info = ''; - var node = workInProgress; - - do { - info += describeFiber(node); - node = node.return; - } while (node); - - return info; - } catch (x) { - return '\nError generating stack: ' + x.message + '\n' + x.stack; - } - } - - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - var current = null; - var isRendering = false; - function getCurrentFiberOwnerNameInDevOrNull() { - { - if (current === null) { - return null; - } - - var owner = current._debugOwner; - - if (owner !== null && typeof owner !== 'undefined') { - return getComponentNameFromFiber(owner); - } - } - - return null; - } - - function getCurrentFiberStackInDev() { - { - if (current === null) { - return ''; - } // Safe because if current fiber exists, we are reconciling, - // and it is guaranteed to be the work-in-progress version. - - - return getStackByFiberInDevAndProd(current); - } - } - - function resetCurrentFiber() { - { - ReactDebugCurrentFrame$1.getCurrentStack = null; - current = null; - isRendering = false; - } - } - function setCurrentFiber(fiber) { - { - ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev; - current = fiber; - isRendering = false; - } - } - function setIsRendering(rendering) { - { - isRendering = rendering; - } - } - - var ReactStrictModeWarnings = { - recordUnsafeLifecycleWarnings: function (fiber, instance) {}, - flushPendingUnsafeLifecycleWarnings: function () {}, - recordLegacyContextWarning: function (fiber, instance) {}, - flushLegacyContextWarning: function () {}, - discardPendingWarnings: function () {} - }; - - { - var findStrictRoot = function (fiber) { - var maybeStrictRoot = null; - var node = fiber; - - while (node !== null) { - if (node.mode & StrictLegacyMode) { - maybeStrictRoot = node; - } - - node = node.return; - } - - return maybeStrictRoot; - }; - - var setToSortedString = function (set) { - var array = []; - set.forEach(function (value) { - array.push(value); - }); - return array.sort().join(', '); - }; - - var pendingComponentWillMountWarnings = []; - var pendingUNSAFE_ComponentWillMountWarnings = []; - var pendingComponentWillReceivePropsWarnings = []; - var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - var pendingComponentWillUpdateWarnings = []; - var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. - - var didWarnAboutUnsafeLifecycles = new Set(); - - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) { - // Dedupe strategy: Warn once per component. - if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { - return; - } - - if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components. - instance.componentWillMount.__suppressDeprecationWarning !== true) { - pendingComponentWillMountWarnings.push(fiber); - } - - if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') { - pendingUNSAFE_ComponentWillMountWarnings.push(fiber); - } - - if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { - pendingComponentWillReceivePropsWarnings.push(fiber); - } - - if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); - } - - if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { - pendingComponentWillUpdateWarnings.push(fiber); - } - - if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') { - pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); - } - }; - - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () { - // We do an initial pass to gather component names - var componentWillMountUniqueNames = new Set(); - - if (pendingComponentWillMountWarnings.length > 0) { - pendingComponentWillMountWarnings.forEach(function (fiber) { - componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillMountWarnings = []; - } - - var UNSAFE_componentWillMountUniqueNames = new Set(); - - if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { - pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) { - UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillMountWarnings = []; - } - - var componentWillReceivePropsUniqueNames = new Set(); - - if (pendingComponentWillReceivePropsWarnings.length > 0) { - pendingComponentWillReceivePropsWarnings.forEach(function (fiber) { - componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillReceivePropsWarnings = []; - } - - var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); - - if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { - pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) { - UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - } - - var componentWillUpdateUniqueNames = new Set(); - - if (pendingComponentWillUpdateWarnings.length > 0) { - pendingComponentWillUpdateWarnings.forEach(function (fiber) { - componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillUpdateWarnings = []; - } - - var UNSAFE_componentWillUpdateUniqueNames = new Set(); - - if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { - pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) { - UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillUpdateWarnings = []; - } // Finally, we flush all the warnings - // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' - - - if (UNSAFE_componentWillMountUniqueNames.size > 0) { - var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); - - error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames); - } - - if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { - var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames); - - error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames); - } - - if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { - var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames); - - error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2); - } - - if (componentWillMountUniqueNames.size > 0) { - var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); - - warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3); - } - - if (componentWillReceivePropsUniqueNames.size > 0) { - var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames); - - warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4); - } - - if (componentWillUpdateUniqueNames.size > 0) { - var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); - - warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5); - } - }; - - var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. - - var didWarnAboutLegacyContext = new Set(); - - ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) { - var strictRoot = findStrictRoot(fiber); - - if (strictRoot === null) { - error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - - return; - } // Dedup strategy: Warn once per component. - - - if (didWarnAboutLegacyContext.has(fiber.type)) { - return; - } - - var warningsForRoot = pendingLegacyContextWarning.get(strictRoot); - - if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') { - if (warningsForRoot === undefined) { - warningsForRoot = []; - pendingLegacyContextWarning.set(strictRoot, warningsForRoot); - } - - warningsForRoot.push(fiber); - } - }; - - ReactStrictModeWarnings.flushLegacyContextWarning = function () { - pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) { - if (fiberArray.length === 0) { - return; - } - - var firstFiber = fiberArray[0]; - var uniqueNames = new Set(); - fiberArray.forEach(function (fiber) { - uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutLegacyContext.add(fiber.type); - }); - var sortedNames = setToSortedString(uniqueNames); - - try { - setCurrentFiber(firstFiber); - - error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames); - } finally { - resetCurrentFiber(); - } - }); - }; - - ReactStrictModeWarnings.discardPendingWarnings = function () { - pendingComponentWillMountWarnings = []; - pendingUNSAFE_ComponentWillMountWarnings = []; - pendingComponentWillReceivePropsWarnings = []; - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - pendingComponentWillUpdateWarnings = []; - pendingUNSAFE_ComponentWillUpdateWarnings = []; - pendingLegacyContextWarning = new Map(); - }; - } - - /* - * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol - * and Temporal.* types. See https://github.com/facebook/react/pull/22064. - * - * The functions in this module will throw an easier-to-understand, - * easier-to-debug exception with a clear errors message message explaining the - * problem. (Instead of a confusing exception thrown inside the implementation - * of the `value` object). - */ - // $FlowFixMe only called in DEV, so void return is not possible. - function typeName(value) { - { - // toStringTag is needed for namespaced types like Temporal.Instant - var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; - return type; - } - } // $FlowFixMe only called in DEV, so void return is not possible. - - - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e) { - return true; - } - } - } - - function testStringCoercion(value) { - // If you ended up here by following an exception call stack, here's what's - // happened: you supplied an object or symbol value to React (as a prop, key, - // DOM attribute, CSS property, string ref, etc.) and when React tried to - // coerce it to a string using `'' + value`, an exception was thrown. - // - // The most common types that will cause this exception are `Symbol` instances - // and Temporal objects like `Temporal.Instant`. But any object that has a - // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this - // exception. (Library authors do this to prevent users from using built-in - // numeric operators like `+` or comparison operators like `>=` because custom - // methods are needed to perform accurate arithmetic or comparison.) - // - // To fix the problem, coerce this object or symbol value to a string before - // passing it to React. The most reliable way is usually `String(value)`. - // - // To find which value is throwing, check the browser or debugger console. - // Before this exception was thrown, there should be `console.error` output - // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the - // problem and how that type was used: key, atrribute, input value prop, etc. - // In most cases, this console output also shows the component and its - // ancestor components where the exception happened. - // - // eslint-disable-next-line react-internal/safe-string-coercion - return '' + value; - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); - - return testStringCoercion(value); // throw (to help callers find troubleshooting comments) - } - } - } - function checkPropStringCoercion(value, propName) { - { - if (willCoercionThrow(value)) { - error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); - - return testStringCoercion(value); // throw (to help callers find troubleshooting comments) - } - } - } - - function resolveDefaultProps(Component, baseProps) { - if (Component && Component.defaultProps) { - // Resolve default props. Taken from ReactElement - var props = assign({}, baseProps); - var defaultProps = Component.defaultProps; - - for (var propName in defaultProps) { - if (props[propName] === undefined) { - props[propName] = defaultProps[propName]; - } - } - - return props; - } - - return baseProps; - } - - var valueCursor = createCursor(null); - var rendererSigil; - - { - // Use this to detect multiple renderers using the same context - rendererSigil = {}; - } - - var currentlyRenderingFiber = null; - var lastContextDependency = null; - var lastFullyObservedContext = null; - var isDisallowedContextReadInDEV = false; - function resetContextDependencies() { - // This is called right before React yields execution, to ensure `readContext` - // cannot be called outside the render phase. - currentlyRenderingFiber = null; - lastContextDependency = null; - lastFullyObservedContext = null; - - { - isDisallowedContextReadInDEV = false; - } - } - function enterDisallowedContextReadInDEV() { - { - isDisallowedContextReadInDEV = true; - } - } - function exitDisallowedContextReadInDEV() { - { - isDisallowedContextReadInDEV = false; - } - } - function pushProvider(providerFiber, context, nextValue) { - if (isPrimaryRenderer) { - push(valueCursor, context._currentValue, providerFiber); - context._currentValue = nextValue; - - { - if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { - error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); - } - - context._currentRenderer = rendererSigil; - } - } else { - push(valueCursor, context._currentValue2, providerFiber); - context._currentValue2 = nextValue; - - { - if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { - error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); - } - - context._currentRenderer2 = rendererSigil; - } - } - } - function popProvider(context, providerFiber) { - var currentValue = valueCursor.current; - pop(valueCursor, providerFiber); - - if (isPrimaryRenderer) { - { - context._currentValue = currentValue; - } - } else { - { - context._currentValue2 = currentValue; - } - } - } - function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { - // Update the child lanes of all the ancestors, including the alternates. - var node = parent; - - while (node !== null) { - var alternate = node.alternate; - - if (!isSubsetOfLanes(node.childLanes, renderLanes)) { - node.childLanes = mergeLanes(node.childLanes, renderLanes); - - if (alternate !== null) { - alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); - } - } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) { - alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); - } - - if (node === propagationRoot) { - break; - } - - node = node.return; - } - - { - if (node !== propagationRoot) { - error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - } - } - function propagateContextChange(workInProgress, context, renderLanes) { - { - propagateContextChange_eager(workInProgress, context, renderLanes); - } - } - - function propagateContextChange_eager(workInProgress, context, renderLanes) { - - var fiber = workInProgress.child; - - if (fiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - fiber.return = workInProgress; - } - - while (fiber !== null) { - var nextFiber = void 0; // Visit this fiber. - - var list = fiber.dependencies; - - if (list !== null) { - nextFiber = fiber.child; - var dependency = list.firstContext; - - while (dependency !== null) { - // Check if the context matches. - if (dependency.context === context) { - // Match! Schedule an update on this fiber. - if (fiber.tag === ClassComponent) { - // Schedule a force update on the work-in-progress. - var lane = pickArbitraryLane(renderLanes); - var update = createUpdate(NoTimestamp, lane); - update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the - // update to the current fiber, too, which means it will persist even if - // this render is thrown away. Since it's a race condition, not sure it's - // worth fixing. - // Inlined `enqueueUpdate` to remove interleaved update check - - var updateQueue = fiber.updateQueue; - - if (updateQueue === null) ; else { - var sharedQueue = updateQueue.shared; - var pending = sharedQueue.pending; - - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - - sharedQueue.pending = update; - } - } - - fiber.lanes = mergeLanes(fiber.lanes, renderLanes); - var alternate = fiber.alternate; - - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes); - } - - scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too. - - list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the - // dependency list. - - break; - } - - dependency = dependency.next; - } - } else if (fiber.tag === ContextProvider) { - // Don't scan deeper if this is a matching provider - nextFiber = fiber.type === workInProgress.type ? null : fiber.child; - } else if ( fiber.tag === DehydratedFragment) { - // If a dehydrated suspense boundary is in this subtree, we don't know - // if it will have any context consumers in it. The best we can do is - // mark it as having updates. - var parentSuspense = fiber.return; - - if (parentSuspense === null) { - throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.'); - } - - parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); - var _alternate = parentSuspense.alternate; - - if (_alternate !== null) { - _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes); - } // This is intentionally passing this fiber as the parent - // because we want to schedule this fiber as having work - // on its children. We'll use the childLanes on - // this fiber to indicate that a context has changed. - - - scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress); - nextFiber = fiber.sibling; - } else { - // Traverse down. - nextFiber = fiber.child; - } - - if (nextFiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - nextFiber.return = fiber; - } else { - // No child. Traverse to next sibling. - nextFiber = fiber; - - while (nextFiber !== null) { - if (nextFiber === workInProgress) { - // We're back to the root of this subtree. Exit. - nextFiber = null; - break; - } - - var sibling = nextFiber.sibling; - - if (sibling !== null) { - // Set the return pointer of the sibling to the work-in-progress fiber. - sibling.return = nextFiber.return; - nextFiber = sibling; - break; - } // No more siblings. Traverse up. - - - nextFiber = nextFiber.return; - } - } - - fiber = nextFiber; - } - } - function prepareToReadContext(workInProgress, renderLanes) { - currentlyRenderingFiber = workInProgress; - lastContextDependency = null; - lastFullyObservedContext = null; - var dependencies = workInProgress.dependencies; - - if (dependencies !== null) { - { - var firstContext = dependencies.firstContext; - - if (firstContext !== null) { - if (includesSomeLane(dependencies.lanes, renderLanes)) { - // Context list has a pending update. Mark that this fiber performed work. - markWorkInProgressReceivedUpdate(); - } // Reset the work-in-progress list - - - dependencies.firstContext = null; - } - } - } - } - function readContext(context) { - { - // This warning would fire if you read context inside a Hook like useMemo. - // Unlike the class check below, it's not enforced in production for perf. - if (isDisallowedContextReadInDEV) { - error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); - } - } - - var value = isPrimaryRenderer ? context._currentValue : context._currentValue2; - - if (lastFullyObservedContext === context) ; else { - var contextItem = { - context: context, - memoizedValue: value, - next: null - }; - - if (lastContextDependency === null) { - if (currentlyRenderingFiber === null) { - throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); - } // This is the first dependency for this component. Create a new list. - - - lastContextDependency = contextItem; - currentlyRenderingFiber.dependencies = { - lanes: NoLanes, - firstContext: contextItem - }; - } else { - // Append a new context item. - lastContextDependency = lastContextDependency.next = contextItem; - } - } - - return value; - } - - // An array of all update queues that received updates during the current - // render. When this render exits, either because it finishes or because it is - // interrupted, the interleaved updates will be transferred onto the main part - // of the queue. - var interleavedQueues = null; - function pushInterleavedQueue(queue) { - if (interleavedQueues === null) { - interleavedQueues = [queue]; - } else { - interleavedQueues.push(queue); - } - } - function enqueueInterleavedUpdates() { - // Transfer the interleaved updates onto the main queue. Each queue has a - // `pending` field and an `interleaved` field. When they are not null, they - // point to the last node in a circular linked list. We need to append the - // interleaved list to the end of the pending list by joining them into a - // single, circular list. - if (interleavedQueues !== null) { - for (var i = 0; i < interleavedQueues.length; i++) { - var queue = interleavedQueues[i]; - var lastInterleavedUpdate = queue.interleaved; - - if (lastInterleavedUpdate !== null) { - queue.interleaved = null; - var firstInterleavedUpdate = lastInterleavedUpdate.next; - var lastPendingUpdate = queue.pending; - - if (lastPendingUpdate !== null) { - var firstPendingUpdate = lastPendingUpdate.next; - lastPendingUpdate.next = firstInterleavedUpdate; - lastInterleavedUpdate.next = firstPendingUpdate; - } - - queue.pending = lastInterleavedUpdate; - } - } - - interleavedQueues = null; - } - } - - var UpdateState = 0; - var ReplaceState = 1; - var ForceUpdate = 2; - var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. - // It should only be read right after calling `processUpdateQueue`, via - // `checkHasForceUpdateAfterProcessing`. - - var hasForceUpdate = false; - var didWarnUpdateInsideUpdate; - var currentlyProcessingQueue; - - { - didWarnUpdateInsideUpdate = false; - currentlyProcessingQueue = null; - } - - function initializeUpdateQueue(fiber) { - var queue = { - baseState: fiber.memoizedState, - firstBaseUpdate: null, - lastBaseUpdate: null, - shared: { - pending: null, - interleaved: null, - lanes: NoLanes - }, - effects: null - }; - fiber.updateQueue = queue; - } - function cloneUpdateQueue(current, workInProgress) { - // Clone the update queue from current. Unless it's already a clone. - var queue = workInProgress.updateQueue; - var currentQueue = current.updateQueue; - - if (queue === currentQueue) { - var clone = { - baseState: currentQueue.baseState, - firstBaseUpdate: currentQueue.firstBaseUpdate, - lastBaseUpdate: currentQueue.lastBaseUpdate, - shared: currentQueue.shared, - effects: currentQueue.effects - }; - workInProgress.updateQueue = clone; - } - } - function createUpdate(eventTime, lane) { - var update = { - eventTime: eventTime, - lane: lane, - tag: UpdateState, - payload: null, - callback: null, - next: null - }; - return update; - } - function enqueueUpdate(fiber, update, lane) { - var updateQueue = fiber.updateQueue; - - if (updateQueue === null) { - // Only occurs if the fiber has been unmounted. - return; - } - - var sharedQueue = updateQueue.shared; - - if (isInterleavedUpdate(fiber)) { - var interleaved = sharedQueue.interleaved; - - if (interleaved === null) { - // This is the first update. Create a circular list. - update.next = update; // At the end of the current render, this queue's interleaved updates will - // be transferred to the pending queue. - - pushInterleavedQueue(sharedQueue); - } else { - update.next = interleaved.next; - interleaved.next = update; - } - - sharedQueue.interleaved = update; - } else { - var pending = sharedQueue.pending; - - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - - sharedQueue.pending = update; - } - - { - if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) { - error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); - - didWarnUpdateInsideUpdate = true; - } - } - } - function entangleTransitions(root, fiber, lane) { - var updateQueue = fiber.updateQueue; - - if (updateQueue === null) { - // Only occurs if the fiber has been unmounted. - return; - } - - var sharedQueue = updateQueue.shared; - - if (isTransitionLane(lane)) { - var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must - // have finished. We can remove them from the shared queue, which represents - // a superset of the actually pending lanes. In some cases we may entangle - // more than we need to, but that's OK. In fact it's worse if we *don't* - // entangle when we should. - - queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. - - var newQueueLanes = mergeLanes(queueLanes, lane); - sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if - // the lane finished since the last time we entangled it. So we need to - // entangle it again, just to be sure. - - markRootEntangled(root, newQueueLanes); - } - } - function enqueueCapturedUpdate(workInProgress, capturedUpdate) { - // Captured updates are updates that are thrown by a child during the render - // phase. They should be discarded if the render is aborted. Therefore, - // we should only put them on the work-in-progress queue, not the current one. - var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone. - - var current = workInProgress.alternate; - - if (current !== null) { - var currentQueue = current.updateQueue; - - if (queue === currentQueue) { - // The work-in-progress queue is the same as current. This happens when - // we bail out on a parent fiber that then captures an error thrown by - // a child. Since we want to append the update only to the work-in - // -progress queue, we need to clone the updates. We usually clone during - // processUpdateQueue, but that didn't happen in this case because we - // skipped over the parent when we bailed out. - var newFirst = null; - var newLast = null; - var firstBaseUpdate = queue.firstBaseUpdate; - - if (firstBaseUpdate !== null) { - // Loop through the updates and clone them. - var update = firstBaseUpdate; - - do { - var clone = { - eventTime: update.eventTime, - lane: update.lane, - tag: update.tag, - payload: update.payload, - callback: update.callback, - next: null - }; - - if (newLast === null) { - newFirst = newLast = clone; - } else { - newLast.next = clone; - newLast = clone; - } - - update = update.next; - } while (update !== null); // Append the captured update the end of the cloned list. - - - if (newLast === null) { - newFirst = newLast = capturedUpdate; - } else { - newLast.next = capturedUpdate; - newLast = capturedUpdate; - } - } else { - // There are no base updates. - newFirst = newLast = capturedUpdate; - } - - queue = { - baseState: currentQueue.baseState, - firstBaseUpdate: newFirst, - lastBaseUpdate: newLast, - shared: currentQueue.shared, - effects: currentQueue.effects - }; - workInProgress.updateQueue = queue; - return; - } - } // Append the update to the end of the list. - - - var lastBaseUpdate = queue.lastBaseUpdate; - - if (lastBaseUpdate === null) { - queue.firstBaseUpdate = capturedUpdate; - } else { - lastBaseUpdate.next = capturedUpdate; - } - - queue.lastBaseUpdate = capturedUpdate; - } - - function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) { - switch (update.tag) { - case ReplaceState: - { - var payload = update.payload; - - if (typeof payload === 'function') { - // Updater function - { - enterDisallowedContextReadInDEV(); - } - - var nextState = payload.call(instance, prevState, nextProps); - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - payload.call(instance, prevState, nextProps); - } finally { - setIsStrictModeForDevtools(false); - } - } - - exitDisallowedContextReadInDEV(); - } - - return nextState; - } // State object - - - return payload; - } - - case CaptureUpdate: - { - workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture; - } - // Intentional fallthrough - - case UpdateState: - { - var _payload = update.payload; - var partialState; - - if (typeof _payload === 'function') { - // Updater function - { - enterDisallowedContextReadInDEV(); - } - - partialState = _payload.call(instance, prevState, nextProps); - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - _payload.call(instance, prevState, nextProps); - } finally { - setIsStrictModeForDevtools(false); - } - } - - exitDisallowedContextReadInDEV(); - } - } else { - // Partial state object - partialState = _payload; - } - - if (partialState === null || partialState === undefined) { - // Null and undefined are treated as no-ops. - return prevState; - } // Merge the partial state and the previous state. - - - return assign({}, prevState, partialState); - } - - case ForceUpdate: - { - hasForceUpdate = true; - return prevState; - } - } - - return prevState; - } - - function processUpdateQueue(workInProgress, props, instance, renderLanes) { - // This is always non-null on a ClassComponent or HostRoot - var queue = workInProgress.updateQueue; - hasForceUpdate = false; - - { - currentlyProcessingQueue = queue.shared; - } - - var firstBaseUpdate = queue.firstBaseUpdate; - var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue. - - var pendingQueue = queue.shared.pending; - - if (pendingQueue !== null) { - queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first - // and last so that it's non-circular. - - var lastPendingUpdate = pendingQueue; - var firstPendingUpdate = lastPendingUpdate.next; - lastPendingUpdate.next = null; // Append pending updates to base queue - - if (lastBaseUpdate === null) { - firstBaseUpdate = firstPendingUpdate; - } else { - lastBaseUpdate.next = firstPendingUpdate; - } - - lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then - // we need to transfer the updates to that queue, too. Because the base - // queue is a singly-linked list with no cycles, we can append to both - // lists and take advantage of structural sharing. - // TODO: Pass `current` as argument - - var current = workInProgress.alternate; - - if (current !== null) { - // This is always non-null on a ClassComponent or HostRoot - var currentQueue = current.updateQueue; - var currentLastBaseUpdate = currentQueue.lastBaseUpdate; - - if (currentLastBaseUpdate !== lastBaseUpdate) { - if (currentLastBaseUpdate === null) { - currentQueue.firstBaseUpdate = firstPendingUpdate; - } else { - currentLastBaseUpdate.next = firstPendingUpdate; - } - - currentQueue.lastBaseUpdate = lastPendingUpdate; - } - } - } // These values may change as we process the queue. - - - if (firstBaseUpdate !== null) { - // Iterate through the list of updates to compute the result. - var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes - // from the original lanes. - - var newLanes = NoLanes; - var newBaseState = null; - var newFirstBaseUpdate = null; - var newLastBaseUpdate = null; - var update = firstBaseUpdate; - - do { - var updateLane = update.lane; - var updateEventTime = update.eventTime; - - if (!isSubsetOfLanes(renderLanes, updateLane)) { - // Priority is insufficient. Skip this update. If this is the first - // skipped update, the previous update/state is the new base - // update/state. - var clone = { - eventTime: updateEventTime, - lane: updateLane, - tag: update.tag, - payload: update.payload, - callback: update.callback, - next: null - }; - - if (newLastBaseUpdate === null) { - newFirstBaseUpdate = newLastBaseUpdate = clone; - newBaseState = newState; - } else { - newLastBaseUpdate = newLastBaseUpdate.next = clone; - } // Update the remaining priority in the queue. - - - newLanes = mergeLanes(newLanes, updateLane); - } else { - // This update does have sufficient priority. - if (newLastBaseUpdate !== null) { - var _clone = { - eventTime: updateEventTime, - // This update is going to be committed so we never want uncommit - // it. Using NoLane works because 0 is a subset of all bitmasks, so - // this will never be skipped by the check above. - lane: NoLane, - tag: update.tag, - payload: update.payload, - callback: update.callback, - next: null - }; - newLastBaseUpdate = newLastBaseUpdate.next = _clone; - } // Process this update. - - - newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance); - var callback = update.callback; - - if (callback !== null && // If the update was already committed, we should not queue its - // callback again. - update.lane !== NoLane) { - workInProgress.flags |= Callback; - var effects = queue.effects; - - if (effects === null) { - queue.effects = [update]; - } else { - effects.push(update); - } - } - } - - update = update.next; - - if (update === null) { - pendingQueue = queue.shared.pending; - - if (pendingQueue === null) { - break; - } else { - // An update was scheduled from inside a reducer. Add the new - // pending updates to the end of the list and keep processing. - var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we - // unravel them when transferring them to the base queue. - - var _firstPendingUpdate = _lastPendingUpdate.next; - _lastPendingUpdate.next = null; - update = _firstPendingUpdate; - queue.lastBaseUpdate = _lastPendingUpdate; - queue.shared.pending = null; - } - } - } while (true); - - if (newLastBaseUpdate === null) { - newBaseState = newState; - } - - queue.baseState = newBaseState; - queue.firstBaseUpdate = newFirstBaseUpdate; - queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to - // process them during this render, but we do need to track which lanes - // are remaining. - - var lastInterleaved = queue.shared.interleaved; - - if (lastInterleaved !== null) { - var interleaved = lastInterleaved; - - do { - newLanes = mergeLanes(newLanes, interleaved.lane); - interleaved = interleaved.next; - } while (interleaved !== lastInterleaved); - } else if (firstBaseUpdate === null) { - // `queue.lanes` is used for entangling transitions. We can set it back to - // zero once the queue is empty. - queue.shared.lanes = NoLanes; - } // Set the remaining expiration time to be whatever is remaining in the queue. - // This should be fine because the only two other things that contribute to - // expiration time are props and context. We're already in the middle of the - // begin phase by the time we start processing the queue, so we've already - // dealt with the props. Context in components that specify - // shouldComponentUpdate is tricky; but we'll have to account for - // that regardless. - - - markSkippedUpdateLanes(newLanes); - workInProgress.lanes = newLanes; - workInProgress.memoizedState = newState; - } - - { - currentlyProcessingQueue = null; - } - } - - function callCallback(callback, context) { - if (typeof callback !== 'function') { - throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback)); - } - - callback.call(context); - } - - function resetHasForceUpdateBeforeProcessing() { - hasForceUpdate = false; - } - function checkHasForceUpdateAfterProcessing() { - return hasForceUpdate; - } - function commitUpdateQueue(finishedWork, finishedQueue, instance) { - // Commit the effects - var effects = finishedQueue.effects; - finishedQueue.effects = null; - - if (effects !== null) { - for (var i = 0; i < effects.length; i++) { - var effect = effects[i]; - var callback = effect.callback; - - if (callback !== null) { - effect.callback = null; - callCallback(callback, instance); - } - } - } - } - - var fakeInternalInstance = {}; // React.Component uses a shared frozen object by default. - // We'll use it to determine whether we need to initialize legacy refs. - - var emptyRefsObject = new React.Component().refs; - var didWarnAboutStateAssignmentForComponent; - var didWarnAboutUninitializedState; - var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; - var didWarnAboutLegacyLifecyclesAndDerivedState; - var didWarnAboutUndefinedDerivedState; - var warnOnUndefinedDerivedState; - var warnOnInvalidCallback; - var didWarnAboutDirectlyAssigningPropsToState; - var didWarnAboutContextTypeAndContextTypes; - var didWarnAboutInvalidateContextType; - - { - didWarnAboutStateAssignmentForComponent = new Set(); - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - didWarnAboutDirectlyAssigningPropsToState = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutContextTypeAndContextTypes = new Set(); - didWarnAboutInvalidateContextType = new Set(); - var didWarnOnInvalidCallback = new Set(); - - warnOnInvalidCallback = function (callback, callerName) { - if (callback === null || typeof callback === 'function') { - return; - } - - var key = callerName + '_' + callback; - - if (!didWarnOnInvalidCallback.has(key)) { - didWarnOnInvalidCallback.add(key); - - error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); - } - }; - - warnOnUndefinedDerivedState = function (type, partialState) { - if (partialState === undefined) { - var componentName = getComponentNameFromType(type) || 'Component'; - - if (!didWarnAboutUndefinedDerivedState.has(componentName)) { - didWarnAboutUndefinedDerivedState.add(componentName); - - error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); - } - } - }; // This is so gross but it's at least non-critical and can be removed if - // it causes problems. This is meant to give a nicer error message for - // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, - // ...)) which otherwise throws a "_processChildContext is not a function" - // exception. - - - Object.defineProperty(fakeInternalInstance, '_processChildContext', { - enumerable: false, - value: function () { - throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).'); - } - }); - Object.freeze(fakeInternalInstance); - } - - function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) { - var prevState = workInProgress.memoizedState; - var partialState = getDerivedStateFromProps(nextProps, prevState); - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - // Invoke the function an extra time to help detect side-effects. - partialState = getDerivedStateFromProps(nextProps, prevState); - } finally { - setIsStrictModeForDevtools(false); - } - } - - warnOnUndefinedDerivedState(ctor, partialState); - } // Merge the partial state and the previous state. - - - var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); - workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the - // base state. - - if (workInProgress.lanes === NoLanes) { - // Queue is always non-null for classes - var updateQueue = workInProgress.updateQueue; - updateQueue.baseState = memoizedState; - } - } - - var classComponentUpdater = { - isMounted: isMounted, - enqueueSetState: function (inst, payload, callback) { - var fiber = get(inst); - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - var update = createUpdate(eventTime, lane); - update.payload = payload; - - if (callback !== undefined && callback !== null) { - { - warnOnInvalidCallback(callback, 'setState'); - } - - update.callback = callback; - } - - enqueueUpdate(fiber, update); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitions(root, fiber, lane); - } - - { - markStateUpdateScheduled(fiber, lane); - } - }, - enqueueReplaceState: function (inst, payload, callback) { - var fiber = get(inst); - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - var update = createUpdate(eventTime, lane); - update.tag = ReplaceState; - update.payload = payload; - - if (callback !== undefined && callback !== null) { - { - warnOnInvalidCallback(callback, 'replaceState'); - } - - update.callback = callback; - } - - enqueueUpdate(fiber, update); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitions(root, fiber, lane); - } - - { - markStateUpdateScheduled(fiber, lane); - } - }, - enqueueForceUpdate: function (inst, callback) { - var fiber = get(inst); - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - var update = createUpdate(eventTime, lane); - update.tag = ForceUpdate; - - if (callback !== undefined && callback !== null) { - { - warnOnInvalidCallback(callback, 'forceUpdate'); - } - - update.callback = callback; - } - - enqueueUpdate(fiber, update); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitions(root, fiber, lane); - } - - { - markForceUpdateScheduled(fiber, lane); - } - } - }; - - function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) { - var instance = workInProgress.stateNode; - - if (typeof instance.shouldComponentUpdate === 'function') { - var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - // Invoke the function an extra time to help detect side-effects. - shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); - } finally { - setIsStrictModeForDevtools(false); - } - } - - if (shouldUpdate === undefined) { - error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component'); - } - } - - return shouldUpdate; - } - - if (ctor.prototype && ctor.prototype.isPureReactComponent) { - return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); - } - - return true; - } - - function checkClassInstance(workInProgress, ctor, newProps) { - var instance = workInProgress.stateNode; - - { - var name = getComponentNameFromType(ctor) || 'Component'; - var renderPresent = instance.render; - - if (!renderPresent) { - if (ctor.prototype && typeof ctor.prototype.render === 'function') { - error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); - } else { - error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); - } - } - - if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { - error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); - } - - if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { - error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); - } - - if (instance.propTypes) { - error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); - } - - if (instance.contextType) { - error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); - } - - { - if (instance.contextTypes) { - error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); - } - - if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { - didWarnAboutContextTypeAndContextTypes.add(ctor); - - error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); - } - } - - if (typeof instance.componentShouldUpdate === 'function') { - error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); - } - - if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { - error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); - } - - if (typeof instance.componentDidUnmount === 'function') { - error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); - } - - if (typeof instance.componentDidReceiveProps === 'function') { - error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); - } - - if (typeof instance.componentWillRecieveProps === 'function') { - error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); - } - - if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { - error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); - } - - var hasMutatedProps = instance.props !== newProps; - - if (instance.props !== undefined && hasMutatedProps) { - error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); - } - - if (instance.defaultProps) { - error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); - } - - if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - - error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); - } - - if (typeof instance.getDerivedStateFromProps === 'function') { - error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); - } - - if (typeof instance.getDerivedStateFromError === 'function') { - error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); - } - - if (typeof ctor.getSnapshotBeforeUpdate === 'function') { - error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); - } - - var _state = instance.state; - - if (_state && (typeof _state !== 'object' || isArray(_state))) { - error('%s.state: must be set to an object or null', name); - } - - if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { - error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); - } - } - } - - function adoptClassInstance(workInProgress, instance) { - instance.updater = classComponentUpdater; - workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates - - set(instance, workInProgress); - - { - instance._reactInternalInstance = fakeInternalInstance; - } - } - - function constructClassInstance(workInProgress, ctor, props) { - var isLegacyContextConsumer = false; - var unmaskedContext = emptyContextObject; - var context = emptyContextObject; - var contextType = ctor.contextType; - - { - if ('contextType' in ctor) { - var isValid = // Allow null for conditional declaration - contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a - - if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { - didWarnAboutInvalidateContextType.add(ctor); - var addendum = ''; - - if (contextType === undefined) { - addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; - } else if (typeof contextType !== 'object') { - addendum = ' However, it is set to a ' + typeof contextType + '.'; - } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { - addendum = ' Did you accidentally pass the Context.Provider instead?'; - } else if (contextType._context !== undefined) { - // - addendum = ' Did you accidentally pass the Context.Consumer instead?'; - } else { - addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; - } - - error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); - } - } - } - - if (typeof contextType === 'object' && contextType !== null) { - context = readContext(contextType); - } else { - unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - var contextTypes = ctor.contextTypes; - isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined; - context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; - } - - var instance = new ctor(props, context); // Instantiate twice to help detect side-effects. - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - instance = new ctor(props, context); // eslint-disable-line no-new - } finally { - setIsStrictModeForDevtools(false); - } - } - } - - var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null; - adoptClassInstance(workInProgress, instance); - - { - if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { - var componentName = getComponentNameFromType(ctor) || 'Component'; - - if (!didWarnAboutUninitializedState.has(componentName)) { - didWarnAboutUninitializedState.add(componentName); - - error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); - } - } // If new component APIs are defined, "unsafe" lifecycles won't be called. - // Warn about these lifecycles if they are present. - // Don't warn about react-lifecycles-compat polyfilled methods though. - - - if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { - var foundWillMountName = null; - var foundWillReceivePropsName = null; - var foundWillUpdateName = null; - - if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { - foundWillMountName = 'componentWillMount'; - } else if (typeof instance.UNSAFE_componentWillMount === 'function') { - foundWillMountName = 'UNSAFE_componentWillMount'; - } - - if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { - foundWillReceivePropsName = 'componentWillReceiveProps'; - } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; - } - - if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { - foundWillUpdateName = 'componentWillUpdate'; - } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { - foundWillUpdateName = 'UNSAFE_componentWillUpdate'; - } - - if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { - var _componentName = getComponentNameFromType(ctor) || 'Component'; - - var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; - - if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { - didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); - - error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); - } - } - } - } // Cache unmasked context so we can avoid recreating masked context unless necessary. - // ReactFiberContext usually updates this cache but can't for newly-created instances. - - - if (isLegacyContextConsumer) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return instance; - } - - function callComponentWillMount(workInProgress, instance) { - var oldState = instance.state; - - if (typeof instance.componentWillMount === 'function') { - instance.componentWillMount(); - } - - if (typeof instance.UNSAFE_componentWillMount === 'function') { - instance.UNSAFE_componentWillMount(); - } - - if (oldState !== instance.state) { - { - error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component'); - } - - classComponentUpdater.enqueueReplaceState(instance, instance.state, null); - } - } - - function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) { - var oldState = instance.state; - - if (typeof instance.componentWillReceiveProps === 'function') { - instance.componentWillReceiveProps(newProps, nextContext); - } - - if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); - } - - if (instance.state !== oldState) { - { - var componentName = getComponentNameFromFiber(workInProgress) || 'Component'; - - if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { - didWarnAboutStateAssignmentForComponent.add(componentName); - - error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName); - } - } - - classComponentUpdater.enqueueReplaceState(instance, instance.state, null); - } - } // Invokes the mount life-cycles on a previously never rendered instance. - - - function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { - { - checkClassInstance(workInProgress, ctor, newProps); - } - - var instance = workInProgress.stateNode; - instance.props = newProps; - instance.state = workInProgress.memoizedState; - instance.refs = emptyRefsObject; - initializeUpdateQueue(workInProgress); - var contextType = ctor.contextType; - - if (typeof contextType === 'object' && contextType !== null) { - instance.context = readContext(contextType); - } else { - var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - instance.context = getMaskedContext(workInProgress, unmaskedContext); - } - - { - if (instance.state === newProps) { - var componentName = getComponentNameFromType(ctor) || 'Component'; - - if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { - didWarnAboutDirectlyAssigningPropsToState.add(componentName); - - error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); - } - } - - if (workInProgress.mode & StrictLegacyMode) { - ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance); - } - - { - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance); - } - } - - instance.state = workInProgress.memoizedState; - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - - if (typeof getDerivedStateFromProps === 'function') { - applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); - instance.state = workInProgress.memoizedState; - } // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - - - if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { - callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's - // process them now. - - processUpdateQueue(workInProgress, newProps, instance, renderLanes); - instance.state = workInProgress.memoizedState; - } - - if (typeof instance.componentDidMount === 'function') { - var fiberFlags = Update; - - { - fiberFlags |= LayoutStatic; - } - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - - workInProgress.flags |= fiberFlags; - } - } - - function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) { - var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; - instance.props = oldProps; - var oldContext = instance.context; - var contextType = ctor.contextType; - var nextContext = emptyContextObject; - - if (typeof contextType === 'object' && contextType !== null) { - nextContext = readContext(contextType); - } else { - var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext); - } - - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what - // ever the previously attempted to render - not the "current". However, - // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { - if (oldProps !== newProps || oldContext !== nextContext) { - callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); - } - } - - resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; - var newState = instance.state = oldState; - processUpdateQueue(workInProgress, newProps, instance, renderLanes); - newState = workInProgress.memoizedState; - - if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidMount === 'function') { - var fiberFlags = Update; - - { - fiberFlags |= LayoutStatic; - } - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - - workInProgress.flags |= fiberFlags; - } - - return false; - } - - if (typeof getDerivedStateFromProps === 'function') { - applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); - newState = workInProgress.memoizedState; - } - - var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext); - - if (shouldUpdate) { - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { - if (typeof instance.componentWillMount === 'function') { - instance.componentWillMount(); - } - - if (typeof instance.UNSAFE_componentWillMount === 'function') { - instance.UNSAFE_componentWillMount(); - } - } - - if (typeof instance.componentDidMount === 'function') { - var _fiberFlags = Update; - - { - _fiberFlags |= LayoutStatic; - } - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - _fiberFlags |= MountLayoutDev; - } - - workInProgress.flags |= _fiberFlags; - } - } else { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidMount === 'function') { - var _fiberFlags2 = Update; - - { - _fiberFlags2 |= LayoutStatic; - } - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - _fiberFlags2 |= MountLayoutDev; - } - - workInProgress.flags |= _fiberFlags2; - } // If shouldComponentUpdate returned false, we should still update the - // memoized state to indicate that this work can be reused. - - - workInProgress.memoizedProps = newProps; - workInProgress.memoizedState = newState; - } // Update the existing instance's state, props, and context pointers even - // if shouldComponentUpdate returns false. - - - instance.props = newProps; - instance.state = newState; - instance.context = nextContext; - return shouldUpdate; - } // Invokes the update life-cycles and returns false if it shouldn't rerender. - - - function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) { - var instance = workInProgress.stateNode; - cloneUpdateQueue(current, workInProgress); - var unresolvedOldProps = workInProgress.memoizedProps; - var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps); - instance.props = oldProps; - var unresolvedNewProps = workInProgress.pendingProps; - var oldContext = instance.context; - var contextType = ctor.contextType; - var nextContext = emptyContextObject; - - if (typeof contextType === 'object' && contextType !== null) { - nextContext = readContext(contextType); - } else { - var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); - } - - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what - // ever the previously attempted to render - not the "current". However, - // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { - if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { - callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); - } - } - - resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; - var newState = instance.state = oldState; - processUpdateQueue(workInProgress, newProps, instance, renderLanes); - newState = workInProgress.memoizedState; - - if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation )) { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.flags |= Update; - } - } - - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.flags |= Snapshot; - } - } - - return false; - } - - if (typeof getDerivedStateFromProps === 'function') { - applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); - newState = workInProgress.memoizedState; - } - - var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice, - // both before and after `shouldComponentUpdate` has been called. Not ideal, - // but I'm loath to refactor this function. This only happens for memoized - // components so it's not that common. - enableLazyContextPropagation ; - - if (shouldUpdate) { - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) { - if (typeof instance.componentWillUpdate === 'function') { - instance.componentWillUpdate(newProps, newState, nextContext); - } - - if (typeof instance.UNSAFE_componentWillUpdate === 'function') { - instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); - } - } - - if (typeof instance.componentDidUpdate === 'function') { - workInProgress.flags |= Update; - } - - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - workInProgress.flags |= Snapshot; - } - } else { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.flags |= Update; - } - } - - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.flags |= Snapshot; - } - } // If shouldComponentUpdate returned false, we should still update the - // memoized props/state to indicate that this work can be reused. - - - workInProgress.memoizedProps = newProps; - workInProgress.memoizedState = newState; - } // Update the existing instance's state, props, and context pointers even - // if shouldComponentUpdate returns false. - - - instance.props = newProps; - instance.state = newState; - instance.context = nextContext; - return shouldUpdate; - } - - // TODO: Use the unified fiber stack module instead of this local one? - // Intentionally not using it yet to derisk the initial implementation, because - // the way we push/pop these values is a bit unusual. If there's a mistake, I'd - // rather the ids be wrong than crash the whole reconciler. - var forkStack = []; - var forkStackIndex = 0; - var treeForkProvider = null; - var treeForkCount = 0; - var idStack = []; - var idStackIndex = 0; - var treeContextProvider = null; - var treeContextId = 1; - var treeContextOverflow = ''; - function isForkedChild(workInProgress) { - warnIfNotHydrating(); - return (workInProgress.flags & Forked) !== NoFlags; - } - function getForksAtLevel(workInProgress) { - warnIfNotHydrating(); - return treeForkCount; - } - function getTreeId() { - var overflow = treeContextOverflow; - var idWithLeadingBit = treeContextId; - var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); - return id.toString(32) + overflow; - } - function pushTreeFork(workInProgress, totalChildren) { - // This is called right after we reconcile an array (or iterator) of child - // fibers, because that's the only place where we know how many children in - // the whole set without doing extra work later, or storing addtional - // information on the fiber. - // - // That's why this function is separate from pushTreeId — it's called during - // the render phase of the fork parent, not the child, which is where we push - // the other context values. - // - // In the Fizz implementation this is much simpler because the child is - // rendered in the same callstack as the parent. - // - // It might be better to just add a `forks` field to the Fiber type. It would - // make this module simpler. - warnIfNotHydrating(); - forkStack[forkStackIndex++] = treeForkCount; - forkStack[forkStackIndex++] = treeForkProvider; - treeForkProvider = workInProgress; - treeForkCount = totalChildren; - } - function pushTreeId(workInProgress, totalChildren, index) { - warnIfNotHydrating(); - idStack[idStackIndex++] = treeContextId; - idStack[idStackIndex++] = treeContextOverflow; - idStack[idStackIndex++] = treeContextProvider; - treeContextProvider = workInProgress; - var baseIdWithLeadingBit = treeContextId; - var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part - // of the id; we use it to account for leading 0s. - - var baseLength = getBitLength(baseIdWithLeadingBit) - 1; - var baseId = baseIdWithLeadingBit & ~(1 << baseLength); - var slot = index + 1; - var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into - // consideration the leading 1 we use to mark the end of the sequence. - - if (length > 30) { - // We overflowed the bitwise-safe range. Fall back to slower algorithm. - // This branch assumes the length of the base id is greater than 5; it won't - // work for smaller ids, because you need 5 bits per character. - // - // We encode the id in multiple steps: first the base id, then the - // remaining digits. - // - // Each 5 bit sequence corresponds to a single base 32 character. So for - // example, if the current id is 23 bits long, we can convert 20 of those - // bits into a string of 4 characters, with 3 bits left over. - // - // First calculate how many bits in the base id represent a complete - // sequence of characters. - var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. - - var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. - - var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. - - var restOfBaseId = baseId >> numberOfOverflowBits; - var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because - // we made more room, this time it won't overflow. - - var restOfLength = getBitLength(totalChildren) + restOfBaseLength; - var restOfNewBits = slot << restOfBaseLength; - var id = restOfNewBits | restOfBaseId; - var overflow = newOverflow + baseOverflow; - treeContextId = 1 << restOfLength | id; - treeContextOverflow = overflow; - } else { - // Normal path - var newBits = slot << baseLength; - - var _id = newBits | baseId; - - var _overflow = baseOverflow; - treeContextId = 1 << length | _id; - treeContextOverflow = _overflow; - } - } - function pushMaterializedTreeId(workInProgress) { - warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear - // in its children. - - var returnFiber = workInProgress.return; - - if (returnFiber !== null) { - var numberOfForks = 1; - var slotIndex = 0; - pushTreeFork(workInProgress, numberOfForks); - pushTreeId(workInProgress, numberOfForks, slotIndex); - } - } - - function getBitLength(number) { - return 32 - clz32(number); - } - - function getLeadingBit(id) { - return 1 << getBitLength(id) - 1; - } - - function popTreeContext(workInProgress) { - // Restore the previous values. - // This is a bit more complicated than other context-like modules in Fiber - // because the same Fiber may appear on the stack multiple times and for - // different reasons. We have to keep popping until the work-in-progress is - // no longer at the top of the stack. - while (workInProgress === treeForkProvider) { - treeForkProvider = forkStack[--forkStackIndex]; - forkStack[forkStackIndex] = null; - treeForkCount = forkStack[--forkStackIndex]; - forkStack[forkStackIndex] = null; - } - - while (workInProgress === treeContextProvider) { - treeContextProvider = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - treeContextOverflow = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - treeContextId = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - } - } - function getSuspendedTreeContext() { - warnIfNotHydrating(); - - if (treeContextProvider !== null) { - return { - id: treeContextId, - overflow: treeContextOverflow - }; - } else { - return null; - } - } - function restoreSuspendedTreeContext(workInProgress, suspendedContext) { - warnIfNotHydrating(); - idStack[idStackIndex++] = treeContextId; - idStack[idStackIndex++] = treeContextOverflow; - idStack[idStackIndex++] = treeContextProvider; - treeContextId = suspendedContext.id; - treeContextOverflow = suspendedContext.overflow; - treeContextProvider = workInProgress; - } - - function warnIfNotHydrating() { - { - if (!getIsHydrating()) { - error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.'); - } - } - } - - // This may have been an insertion or a hydration. - - var hydrationParentFiber = null; - var nextHydratableInstance = null; - var isHydrating = false; - var didSuspend = false; // Hydration errors that were thrown inside this boundary - - var hydrationErrors = null; - - function warnIfHydrating() { - { - if (isHydrating) { - error('We should not be hydrating here. This is a bug in React. Please file a bug.'); - } - } - } - - function markDidSuspendWhileHydratingDEV() { - { - didSuspend = true; - } - } - - function enterHydrationState(fiber) { - if (!supportsHydration) { - return false; - } - - var parentInstance = fiber.stateNode.containerInfo; - nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); - hydrationParentFiber = fiber; - isHydrating = true; - hydrationErrors = null; - didSuspend = false; - return true; - } - - function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) { - if (!supportsHydration) { - return false; - } - - nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); - hydrationParentFiber = fiber; - isHydrating = true; - hydrationErrors = null; - didSuspend = false; - - if (treeContext !== null) { - restoreSuspendedTreeContext(fiber, treeContext); - } - - return true; - } - - function warnUnhydratedInstance(returnFiber, instance) { - { - switch (returnFiber.tag) { - case HostRoot: - didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance); - break; - - case HostComponent: - didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance); - break; - - case SuspenseComponent: - var suspenseState = returnFiber.memoizedState; - if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance); - break; - } - } - } - - function deleteHydratableInstance(returnFiber, instance) { - warnUnhydratedInstance(returnFiber, instance); - var childToDelete = createFiberFromHostInstanceForDeletion(); - childToDelete.stateNode = instance; - childToDelete.return = returnFiber; - var deletions = returnFiber.deletions; - - if (deletions === null) { - returnFiber.deletions = [childToDelete]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(childToDelete); - } - } - - function warnNonhydratedInstance(returnFiber, fiber) { - { - if (didSuspend) { - // Inside a boundary that already suspended. We're currently rendering the - // siblings of a suspended node. The mismatch may be due to the missing - // data, so it's probably a false positive. - return; - } - - switch (returnFiber.tag) { - case HostRoot: - { - var parentContainer = returnFiber.stateNode.containerInfo; - - switch (fiber.tag) { - case HostComponent: - var type = fiber.type; - var props = fiber.pendingProps; - didNotFindHydratableInstanceWithinContainer(parentContainer, type, props); - break; - - case HostText: - var text = fiber.pendingProps; - didNotFindHydratableTextInstanceWithinContainer(parentContainer, text); - break; - - case SuspenseComponent: - didNotFindHydratableSuspenseInstanceWithinContainer(parentContainer); - break; - } - - break; - } - - case HostComponent: - { - var parentType = returnFiber.type; - var parentProps = returnFiber.memoizedProps; - var parentInstance = returnFiber.stateNode; - - switch (fiber.tag) { - case HostComponent: - var _type = fiber.type; - var _props = fiber.pendingProps; - didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props); - break; - - case HostText: - var _text = fiber.pendingProps; - didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text); - break; - - case SuspenseComponent: - didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance); - break; - } - - break; - } - - case SuspenseComponent: - { - var suspenseState = returnFiber.memoizedState; - var _parentInstance = suspenseState.dehydrated; - if (_parentInstance !== null) switch (fiber.tag) { - case HostComponent: - var _type2 = fiber.type; - var _props2 = fiber.pendingProps; - didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2, _props2); - break; - - case HostText: - var _text2 = fiber.pendingProps; - didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2); - break; - - case SuspenseComponent: - didNotFindHydratableSuspenseInstanceWithinSuspenseInstance(_parentInstance); - break; - } - break; - } - - default: - return; - } - } - } - - function insertNonHydratedInstance(returnFiber, fiber) { - fiber.flags = fiber.flags & ~Hydrating | Placement; - warnNonhydratedInstance(returnFiber, fiber); - } - - function tryHydrate(fiber, nextInstance) { - switch (fiber.tag) { - case HostComponent: - { - var type = fiber.type; - var props = fiber.pendingProps; - var instance = canHydrateInstance(nextInstance, type, props); - - if (instance !== null) { - fiber.stateNode = instance; - hydrationParentFiber = fiber; - nextHydratableInstance = getFirstHydratableChild(instance); - return true; - } - - return false; - } - - case HostText: - { - var text = fiber.pendingProps; - var textInstance = canHydrateTextInstance(nextInstance, text); - - if (textInstance !== null) { - fiber.stateNode = textInstance; - hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate. - - nextHydratableInstance = null; - return true; - } - - return false; - } - - case SuspenseComponent: - { - { - var suspenseInstance = canHydrateSuspenseInstance(nextInstance); - - if (suspenseInstance !== null) { - var suspenseState = { - dehydrated: suspenseInstance, - treeContext: getSuspendedTreeContext(), - retryLane: OffscreenLane - }; - fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. - // This simplifies the code for getHostSibling and deleting nodes, - // since it doesn't have to consider all Suspense boundaries and - // check if they're dehydrated ones or not. - - var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); - dehydratedFragment.return = fiber; - fiber.child = dehydratedFragment; - hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into - // it during the first pass. Instead, we'll reenter it later. - - nextHydratableInstance = null; - return true; - } - } - - return false; - } - - default: - return false; - } - } - - function shouldClientRenderOnMismatch(fiber) { - return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags; - } - - function throwOnHydrationMismatch(fiber) { - throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.'); - } - - function tryToClaimNextHydratableInstance(fiber) { - if (!isHydrating) { - return; - } - - var nextInstance = nextHydratableInstance; - - if (!nextInstance) { - if (shouldClientRenderOnMismatch(fiber)) { - warnNonhydratedInstance(hydrationParentFiber, fiber); - throwOnHydrationMismatch(); - } // Nothing to hydrate. Make it an insertion. - - - insertNonHydratedInstance(hydrationParentFiber, fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } - - var firstAttemptedInstance = nextInstance; - - if (!tryHydrate(fiber, nextInstance)) { - if (shouldClientRenderOnMismatch(fiber)) { - warnNonhydratedInstance(hydrationParentFiber, fiber); - throwOnHydrationMismatch(); - } // If we can't hydrate this instance let's try the next one. - // We use this as a heuristic. It's based on intuition and not data so it - // might be flawed or unnecessary. - - - nextInstance = getNextHydratableSibling(firstAttemptedInstance); - var prevHydrationParentFiber = hydrationParentFiber; - - if (!nextInstance || !tryHydrate(fiber, nextInstance)) { - // Nothing to hydrate. Make it an insertion. - insertNonHydratedInstance(hydrationParentFiber, fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } // We matched the next one, we'll now assume that the first one was - // superfluous and we'll delete it. Since we can't eagerly delete it - // we'll have to schedule a deletion. To do that, this node needs a dummy - // fiber associated with it. - - - deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); - } - } - - function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { - if (!supportsHydration) { - throw new Error('Expected prepareToHydrateHostInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var instance = fiber.stateNode; - var shouldWarnIfMismatchDev = !didSuspend; - var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component. - - fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there - // is a new ref we mark this as an update. - - if (updatePayload !== null) { - return true; - } - - return false; - } - - function prepareToHydrateHostTextInstance(fiber) { - if (!supportsHydration) { - throw new Error('Expected prepareToHydrateHostTextInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var textInstance = fiber.stateNode; - var textContent = fiber.memoizedProps; - var shouldWarnIfMismatchDev = !didSuspend; - var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber, shouldWarnIfMismatchDev); - - if (shouldUpdate) { - // We assume that prepareToHydrateHostTextInstance is called in a context where the - // hydration parent is the parent host component of this host text. - var returnFiber = hydrationParentFiber; - - if (returnFiber !== null) { - var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; - - switch (returnFiber.tag) { - case HostRoot: - { - var parentContainer = returnFiber.stateNode.containerInfo; - didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode); - break; - } - - case HostComponent: - { - var parentType = returnFiber.type; - var parentProps = returnFiber.memoizedProps; - var parentInstance = returnFiber.stateNode; - didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode); - break; - } - } - } - } - - return shouldUpdate; - } - - function prepareToHydrateHostSuspenseInstance(fiber) { - if (!supportsHydration) { - throw new Error('Expected prepareToHydrateHostSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var suspenseState = fiber.memoizedState; - var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; - - if (!suspenseInstance) { - throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - hydrateSuspenseInstance(suspenseInstance, fiber); - } - - function skipPastDehydratedSuspenseInstance(fiber) { - if (!supportsHydration) { - throw new Error('Expected skipPastDehydratedSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var suspenseState = fiber.memoizedState; - var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; - - if (!suspenseInstance) { - throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); - } - - function popToNextHostParent(fiber) { - var parent = fiber.return; - - while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) { - parent = parent.return; - } - - hydrationParentFiber = parent; - } - - function popHydrationState(fiber) { - if (!supportsHydration) { - return false; - } - - if (fiber !== hydrationParentFiber) { - // We're deeper than the current hydration context, inside an inserted - // tree. - return false; - } - - if (!isHydrating) { - // If we're not currently hydrating but we're in a hydration context, then - // we were an insertion and now need to pop up reenter hydration of our - // siblings. - popToNextHostParent(fiber); - isHydrating = true; - return false; - } // If we have any remaining hydratable nodes, we need to delete them now. - // We only do this deeper than head and body since they tend to have random - // other nodes in them. We also ignore components with pure text content in - // side of them. We also don't delete anything inside the root container. - - - if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) { - var nextInstance = nextHydratableInstance; - - if (nextInstance) { - if (shouldClientRenderOnMismatch(fiber)) { - warnIfUnhydratedTailNodes(fiber); - throwOnHydrationMismatch(); - } else { - while (nextInstance) { - deleteHydratableInstance(fiber, nextInstance); - nextInstance = getNextHydratableSibling(nextInstance); - } - } - } - } - - popToNextHostParent(fiber); - - if (fiber.tag === SuspenseComponent) { - nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); - } else { - nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; - } - - return true; - } - - function hasUnhydratedTailNodes() { - return isHydrating && nextHydratableInstance !== null; - } - - function warnIfUnhydratedTailNodes(fiber) { - var nextInstance = nextHydratableInstance; - - while (nextInstance) { - warnUnhydratedInstance(fiber, nextInstance); - nextInstance = getNextHydratableSibling(nextInstance); - } - } - - function resetHydrationState() { - if (!supportsHydration) { - return; - } - - hydrationParentFiber = null; - nextHydratableInstance = null; - isHydrating = false; - didSuspend = false; - } - - function upgradeHydrationErrorsToRecoverable() { - if (hydrationErrors !== null) { - // Successfully completed a forced client render. The errors that occurred - // during the hydration attempt are now recovered. We will log them in - // commit phase, once the entire tree has finished. - queueRecoverableErrors(hydrationErrors); - hydrationErrors = null; - } - } - - function getIsHydrating() { - return isHydrating; - } - - function queueHydrationError(error) { - if (hydrationErrors === null) { - hydrationErrors = [error]; - } else { - hydrationErrors.push(error); - } - } - - var didWarnAboutMaps; - var didWarnAboutGenerators; - var didWarnAboutStringRefs; - var ownerHasKeyUseWarning; - var ownerHasFunctionTypeWarning; - - var warnForMissingKey = function (child, returnFiber) {}; - - { - didWarnAboutMaps = false; - didWarnAboutGenerators = false; - didWarnAboutStringRefs = {}; - /** - * Warn if there's no key explicitly set on dynamic arrays of children or - * object keys are not valid. This allows us to keep track of children between - * updates. - */ - - ownerHasKeyUseWarning = {}; - ownerHasFunctionTypeWarning = {}; - - warnForMissingKey = function (child, returnFiber) { - if (child === null || typeof child !== 'object') { - return; - } - - if (!child._store || child._store.validated || child.key != null) { - return; - } - - if (typeof child._store !== 'object') { - throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - child._store.validated = true; - var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; - - if (ownerHasKeyUseWarning[componentName]) { - return; - } - - ownerHasKeyUseWarning[componentName] = true; - - error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.'); - }; - } - - function coerceRef(returnFiber, current, element) { - var mixedRef = element.ref; - - if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') { - { - // TODO: Clean this up once we turn on the string ref warning for - // everyone, because the strict mode case will no longer be relevant - if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs - // because these cannot be automatically converted to an arrow function - // using a codemod. Therefore, we don't have to warn about string refs again. - !(element._owner && element._self && element._owner.stateNode !== element._self)) { - var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; - - if (!didWarnAboutStringRefs[componentName]) { - { - error('A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', mixedRef); - } - - didWarnAboutStringRefs[componentName] = true; - } - } - } - - if (element._owner) { - var owner = element._owner; - var inst; - - if (owner) { - var ownerFiber = owner; - - if (ownerFiber.tag !== ClassComponent) { - throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref'); - } - - inst = ownerFiber.stateNode; - } - - if (!inst) { - throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.'); - } // Assigning this to a const so Flow knows it won't change in the closure - - - var resolvedInst = inst; - - { - checkPropStringCoercion(mixedRef, 'ref'); - } - - var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref - - if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) { - return current.ref; - } - - var ref = function (value) { - var refs = resolvedInst.refs; - - if (refs === emptyRefsObject) { - // This is a lazy pooled frozen object, so we need to initialize. - refs = resolvedInst.refs = {}; - } - - if (value === null) { - delete refs[stringRef]; - } else { - refs[stringRef] = value; - } - }; - - ref._stringRef = stringRef; - return ref; - } else { - if (typeof mixedRef !== 'string') { - throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.'); - } - - if (!element._owner) { - throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.'); - } - } - } - - return mixedRef; - } - - function throwOnInvalidObjectType(returnFiber, newChild) { - var childString = Object.prototype.toString.call(newChild); - throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); - } - - function warnOnFunctionType(returnFiber) { - { - var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; - - if (ownerHasFunctionTypeWarning[componentName]) { - return; - } - - ownerHasFunctionTypeWarning[componentName] = true; - - error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.'); - } - } - - function resolveLazy(lazyType) { - var payload = lazyType._payload; - var init = lazyType._init; - return init(payload); - } // This wrapper function exists because I expect to clone the code in each path - // to be able to optimize each path individually by branching early. This needs - // a compiler or we can do it manually. Helpers that don't need this branching - // live outside of this function. - - - function ChildReconciler(shouldTrackSideEffects) { - function deleteChild(returnFiber, childToDelete) { - if (!shouldTrackSideEffects) { - // Noop. - return; - } - - var deletions = returnFiber.deletions; - - if (deletions === null) { - returnFiber.deletions = [childToDelete]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(childToDelete); - } - } - - function deleteRemainingChildren(returnFiber, currentFirstChild) { - if (!shouldTrackSideEffects) { - // Noop. - return null; - } // TODO: For the shouldClone case, this could be micro-optimized a bit by - // assuming that after the first child we've already added everything. - - - var childToDelete = currentFirstChild; - - while (childToDelete !== null) { - deleteChild(returnFiber, childToDelete); - childToDelete = childToDelete.sibling; - } - - return null; - } - - function mapRemainingChildren(returnFiber, currentFirstChild) { - // Add the remaining children to a temporary map so that we can find them by - // keys quickly. Implicit (null) keys get added to this set with their index - // instead. - var existingChildren = new Map(); - var existingChild = currentFirstChild; - - while (existingChild !== null) { - if (existingChild.key !== null) { - existingChildren.set(existingChild.key, existingChild); - } else { - existingChildren.set(existingChild.index, existingChild); - } - - existingChild = existingChild.sibling; - } - - return existingChildren; - } - - function useFiber(fiber, pendingProps) { - // We currently set sibling to null and index to 0 here because it is easy - // to forget to do before returning it. E.g. for the single child case. - var clone = createWorkInProgress(fiber, pendingProps); - clone.index = 0; - clone.sibling = null; - return clone; - } - - function placeChild(newFiber, lastPlacedIndex, newIndex) { - newFiber.index = newIndex; - - if (!shouldTrackSideEffects) { - // During hydration, the useId algorithm needs to know which fibers are - // part of a list of children (arrays, iterators). - newFiber.flags |= Forked; - return lastPlacedIndex; - } - - var current = newFiber.alternate; - - if (current !== null) { - var oldIndex = current.index; - - if (oldIndex < lastPlacedIndex) { - // This is a move. - newFiber.flags |= Placement; - return lastPlacedIndex; - } else { - // This item can stay in place. - return oldIndex; - } - } else { - // This is an insertion. - newFiber.flags |= Placement; - return lastPlacedIndex; - } - } - - function placeSingleChild(newFiber) { - // This is simpler for the single child case. We only need to do a - // placement for inserting new children. - if (shouldTrackSideEffects && newFiber.alternate === null) { - newFiber.flags |= Placement; - } - - return newFiber; - } - - function updateTextNode(returnFiber, current, textContent, lanes) { - if (current === null || current.tag !== HostText) { - // Insert - var created = createFiberFromText(textContent, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } else { - // Update - var existing = useFiber(current, textContent); - existing.return = returnFiber; - return existing; - } - } - - function updateElement(returnFiber, current, element, lanes) { - var elementType = element.type; - - if (elementType === REACT_FRAGMENT_TYPE) { - return updateFragment(returnFiber, current, element.props.children, lanes, element.key); - } - - if (current !== null) { - if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path: - isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type. - // We need to do this after the Hot Reloading check above, - // because hot reloading has different semantics than prod because - // it doesn't resuspend. So we can't let the call below suspend. - typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) { - // Move based on index - var existing = useFiber(current, element.props); - existing.ref = coerceRef(returnFiber, current, element); - existing.return = returnFiber; - - { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - - return existing; - } - } // Insert - - - var created = createFiberFromElement(element, returnFiber.mode, lanes); - created.ref = coerceRef(returnFiber, current, element); - created.return = returnFiber; - return created; - } - - function updatePortal(returnFiber, current, portal, lanes) { - if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) { - // Insert - var created = createFiberFromPortal(portal, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } else { - // Update - var existing = useFiber(current, portal.children || []); - existing.return = returnFiber; - return existing; - } - } - - function updateFragment(returnFiber, current, fragment, lanes, key) { - if (current === null || current.tag !== Fragment) { - // Insert - var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key); - created.return = returnFiber; - return created; - } else { - // Update - var existing = useFiber(current, fragment); - existing.return = returnFiber; - return existing; - } - } - - function createChild(returnFiber, newChild, lanes) { - if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { - // Text nodes don't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - var created = createFiberFromText('' + newChild, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - { - var _created = createFiberFromElement(newChild, returnFiber.mode, lanes); - - _created.ref = coerceRef(returnFiber, null, newChild); - _created.return = returnFiber; - return _created; - } - - case REACT_PORTAL_TYPE: - { - var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes); - - _created2.return = returnFiber; - return _created2; - } - - case REACT_LAZY_TYPE: - { - { - var payload = newChild._payload; - var init = newChild._init; - return createChild(returnFiber, init(payload), lanes); - } - } - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null); - - _created3.return = returnFiber; - return _created3; - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - return null; - } - - function updateSlot(returnFiber, oldFiber, newChild, lanes) { - // Update the fiber if the keys match, otherwise return null. - var key = oldFiber !== null ? oldFiber.key : null; - - if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { - // Text nodes don't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - if (key !== null) { - return null; - } - - return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - { - if (newChild.key === key) { - return updateElement(returnFiber, oldFiber, newChild, lanes); - } else { - return null; - } - } - - case REACT_PORTAL_TYPE: - { - if (newChild.key === key) { - return updatePortal(returnFiber, oldFiber, newChild, lanes); - } else { - return null; - } - } - - case REACT_LAZY_TYPE: - { - { - var payload = newChild._payload; - var init = newChild._init; - return updateSlot(returnFiber, oldFiber, init(payload), lanes); - } - } - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - if (key !== null) { - return null; - } - - return updateFragment(returnFiber, oldFiber, newChild, lanes, null); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - return null; - } - - function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) { - if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { - // Text nodes don't have keys, so we neither have to check the old nor - // new node for the key. If both are text nodes, they match. - var matchedFiber = existingChildren.get(newIdx) || null; - return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - { - var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; - - return updateElement(returnFiber, _matchedFiber, newChild, lanes); - } - - case REACT_PORTAL_TYPE: - { - var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; - - return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); - } - - case REACT_LAZY_TYPE: - { - var payload = newChild._payload; - var init = newChild._init; - return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes); - } - - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - var _matchedFiber3 = existingChildren.get(newIdx) || null; - - return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - return null; - } - /** - * Warns if there is a duplicate or missing key - */ - - - function warnOnInvalidKey(child, knownKeys, returnFiber) { - { - if (typeof child !== 'object' || child === null) { - return knownKeys; - } - - switch (child.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - warnForMissingKey(child, returnFiber); - var key = child.key; - - if (typeof key !== 'string') { - break; - } - - if (knownKeys === null) { - knownKeys = new Set(); - knownKeys.add(key); - break; - } - - if (!knownKeys.has(key)) { - knownKeys.add(key); - break; - } - - error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key); - - break; - - case REACT_LAZY_TYPE: - { - var payload = child._payload; - var init = child._init; - warnOnInvalidKey(init(payload), knownKeys, returnFiber); - break; - } - } - } - - return knownKeys; - } - - function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) { - // This algorithm can't optimize by searching from both ends since we - // don't have backpointers on fibers. I'm trying to see how far we can get - // with that model. If it ends up not being worth the tradeoffs, we can - // add it later. - // Even with a two ended optimization, we'd want to optimize for the case - // where there are few changes and brute force the comparison instead of - // going for the Map. It'd like to explore hitting that path first in - // forward-only mode and only go for the Map once we notice that we need - // lots of look ahead. This doesn't handle reversal as well as two ended - // search but that's unusual. Besides, for the two ended optimization to - // work on Iterables, we'd need to copy the whole set. - // In this first iteration, we'll just live with hitting the bad case - // (adding everything to a Map) in for every insert/move. - // If you change this code, also update reconcileChildrenIterator() which - // uses the same algorithm. - { - // First, validate keys. - var knownKeys = null; - - for (var i = 0; i < newChildren.length; i++) { - var child = newChildren[i]; - knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); - } - } - - var resultingFirstChild = null; - var previousNewFiber = null; - var oldFiber = currentFirstChild; - var lastPlacedIndex = 0; - var newIdx = 0; - var nextOldFiber = null; - - for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - - var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes); - - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - - break; - } - - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (newIdx === newChildren.length) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - - if (getIsHydrating()) { - var numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; newIdx < newChildren.length; newIdx++) { - var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes); - - if (_newFiber === null) { - continue; - } - - lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = _newFiber; - } else { - previousNewFiber.sibling = _newFiber; - } - - previousNewFiber = _newFiber; - } - - if (getIsHydrating()) { - var _numberOfForks = newIdx; - pushTreeFork(returnFiber, _numberOfForks); - } - - return resultingFirstChild; - } // Add all children to a key map for quick lookups. - - - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - - for (; newIdx < newChildren.length; newIdx++) { - var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes); - - if (_newFiber2 !== null) { - if (shouldTrackSideEffects) { - if (_newFiber2.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key); - } - } - - lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - resultingFirstChild = _newFiber2; - } else { - previousNewFiber.sibling = _newFiber2; - } - - previousNewFiber = _newFiber2; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(function (child) { - return deleteChild(returnFiber, child); - }); - } - - if (getIsHydrating()) { - var _numberOfForks2 = newIdx; - pushTreeFork(returnFiber, _numberOfForks2); - } - - return resultingFirstChild; - } - - function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) { - // This is the same implementation as reconcileChildrenArray(), - // but using the iterator instead. - var iteratorFn = getIteratorFn(newChildrenIterable); - - if (typeof iteratorFn !== 'function') { - throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.'); - } - - { - // We don't support rendering Generators because it's a mutation. - // See https://github.com/facebook/react/issues/12995 - if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag - newChildrenIterable[Symbol.toStringTag] === 'Generator') { - if (!didWarnAboutGenerators) { - error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); - } - - didWarnAboutGenerators = true; - } // Warn about using Maps as children - - - if (newChildrenIterable.entries === iteratorFn) { - if (!didWarnAboutMaps) { - error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); - } - - didWarnAboutMaps = true; - } // First, validate keys. - // We'll get a different iterator later for the main pass. - - - var _newChildren = iteratorFn.call(newChildrenIterable); - - if (_newChildren) { - var knownKeys = null; - - var _step = _newChildren.next(); - - for (; !_step.done; _step = _newChildren.next()) { - var child = _step.value; - knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); - } - } - } - - var newChildren = iteratorFn.call(newChildrenIterable); - - if (newChildren == null) { - throw new Error('An iterable object provided no iterator.'); - } - - var resultingFirstChild = null; - var previousNewFiber = null; - var oldFiber = currentFirstChild; - var lastPlacedIndex = 0; - var newIdx = 0; - var nextOldFiber = null; - var step = newChildren.next(); - - for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - - var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); - - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - - break; - } - - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (step.done) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - - if (getIsHydrating()) { - var numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber3 = createChild(returnFiber, step.value, lanes); - - if (_newFiber3 === null) { - continue; - } - - lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = _newFiber3; - } else { - previousNewFiber.sibling = _newFiber3; - } - - previousNewFiber = _newFiber3; - } - - if (getIsHydrating()) { - var _numberOfForks3 = newIdx; - pushTreeFork(returnFiber, _numberOfForks3); - } - - return resultingFirstChild; - } // Add all children to a key map for quick lookups. - - - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - - for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes); - - if (_newFiber4 !== null) { - if (shouldTrackSideEffects) { - if (_newFiber4.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key); - } - } - - lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - resultingFirstChild = _newFiber4; - } else { - previousNewFiber.sibling = _newFiber4; - } - - previousNewFiber = _newFiber4; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(function (child) { - return deleteChild(returnFiber, child); - }); - } - - if (getIsHydrating()) { - var _numberOfForks4 = newIdx; - pushTreeFork(returnFiber, _numberOfForks4); - } - - return resultingFirstChild; - } - - function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) { - // There's no need to check for keys on text nodes since we don't have a - // way to define them. - if (currentFirstChild !== null && currentFirstChild.tag === HostText) { - // We already have an existing node so let's just update it and delete - // the rest. - deleteRemainingChildren(returnFiber, currentFirstChild.sibling); - var existing = useFiber(currentFirstChild, textContent); - existing.return = returnFiber; - return existing; - } // The existing first child is not a text node so we need to create one - // and delete the existing ones. - - - deleteRemainingChildren(returnFiber, currentFirstChild); - var created = createFiberFromText(textContent, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } - - function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) { - var key = element.key; - var child = currentFirstChild; - - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - var elementType = element.type; - - if (elementType === REACT_FRAGMENT_TYPE) { - if (child.tag === Fragment) { - deleteRemainingChildren(returnFiber, child.sibling); - var existing = useFiber(child, element.props.children); - existing.return = returnFiber; - - { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - - return existing; - } - } else { - if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path: - isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type. - // We need to do this after the Hot Reloading check above, - // because hot reloading has different semantics than prod because - // it doesn't resuspend. So we can't let the call below suspend. - typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) { - deleteRemainingChildren(returnFiber, child.sibling); - - var _existing = useFiber(child, element.props); - - _existing.ref = coerceRef(returnFiber, child, element); - _existing.return = returnFiber; - - { - _existing._debugSource = element._source; - _existing._debugOwner = element._owner; - } - - return _existing; - } - } // Didn't match. - - - deleteRemainingChildren(returnFiber, child); - break; - } else { - deleteChild(returnFiber, child); - } - - child = child.sibling; - } - - if (element.type === REACT_FRAGMENT_TYPE) { - var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key); - created.return = returnFiber; - return created; - } else { - var _created4 = createFiberFromElement(element, returnFiber.mode, lanes); - - _created4.ref = coerceRef(returnFiber, currentFirstChild, element); - _created4.return = returnFiber; - return _created4; - } - } - - function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) { - var key = portal.key; - var child = currentFirstChild; - - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { - deleteRemainingChildren(returnFiber, child.sibling); - var existing = useFiber(child, portal.children || []); - existing.return = returnFiber; - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - break; - } - } else { - deleteChild(returnFiber, child); - } - - child = child.sibling; - } - - var created = createFiberFromPortal(portal, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } // This API will tag the children with the side-effect of the reconciliation - // itself. They will be added to the side-effect list as we pass through the - // children and the parent. - - - function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) { - // This function is not recursive. - // If the top level item is an array, we treat it as a set of children, - // not as a fragment. Nested arrays on the other hand will be treated as - // fragment nodes. Recursion happens at the normal flow. - // Handle top level unkeyed fragments as if they were arrays. - // This leads to an ambiguity between <>{[...]} and <>.... - // We treat the ambiguous cases above the same. - var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; - - if (isUnkeyedTopLevelFragment) { - newChild = newChild.props.children; - } // Handle object types - - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes)); - - case REACT_PORTAL_TYPE: - return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes)); - - case REACT_LAZY_TYPE: - { - var payload = newChild._payload; - var init = newChild._init; // TODO: This function is supposed to be non-recursive. - - return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes); - } - - } - - if (isArray(newChild)) { - return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes); - } - - if (getIteratorFn(newChild)) { - return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { - return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes)); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } // Remaining cases are all treated as empty. - - - return deleteRemainingChildren(returnFiber, currentFirstChild); - } - - return reconcileChildFibers; - } - - var reconcileChildFibers = ChildReconciler(true); - var mountChildFibers = ChildReconciler(false); - function cloneChildFibers(current, workInProgress) { - if (current !== null && workInProgress.child !== current.child) { - throw new Error('Resuming work not yet implemented.'); - } - - if (workInProgress.child === null) { - return; - } - - var currentChild = workInProgress.child; - var newChild = createWorkInProgress(currentChild, currentChild.pendingProps); - workInProgress.child = newChild; - newChild.return = workInProgress; - - while (currentChild.sibling !== null) { - currentChild = currentChild.sibling; - newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps); - newChild.return = workInProgress; - } - - newChild.sibling = null; - } // Reset a workInProgress child set to prepare it for a second pass. - - function resetChildFibers(workInProgress, lanes) { - var child = workInProgress.child; - - while (child !== null) { - resetWorkInProgress(child, lanes); - child = child.sibling; - } - } - - var NO_CONTEXT = {}; - var contextStackCursor$1 = createCursor(NO_CONTEXT); - var contextFiberStackCursor = createCursor(NO_CONTEXT); - var rootInstanceStackCursor = createCursor(NO_CONTEXT); - - function requiredContext(c) { - if (c === NO_CONTEXT) { - throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.'); - } - - return c; - } - - function getRootHostContainer() { - var rootInstance = requiredContext(rootInstanceStackCursor.current); - return rootInstance; - } - - function pushHostContainer(fiber, nextRootInstance) { - // Push current root instance onto the stack; - // This allows us to reset root when portals are popped. - push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - - push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. - // However, we can't just call getRootHostContext() and push it because - // we'd have a different number of entries on the stack depending on - // whether getRootHostContext() throws somewhere in renderer code or not. - // So we push an empty value first. This lets us safely unwind on errors. - - push(contextStackCursor$1, NO_CONTEXT, fiber); - var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. - - pop(contextStackCursor$1, fiber); - push(contextStackCursor$1, nextRootContext, fiber); - } - - function popHostContainer(fiber) { - pop(contextStackCursor$1, fiber); - pop(contextFiberStackCursor, fiber); - pop(rootInstanceStackCursor, fiber); - } - - function getHostContext() { - var context = requiredContext(contextStackCursor$1.current); - return context; - } - - function pushHostContext(fiber) { - var rootInstance = requiredContext(rootInstanceStackCursor.current); - var context = requiredContext(contextStackCursor$1.current); - var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique. - - if (context === nextContext) { - return; - } // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - - - push(contextFiberStackCursor, fiber, fiber); - push(contextStackCursor$1, nextContext, fiber); - } - - function popHostContext(fiber) { - // Do not pop unless this Fiber provided the current context. - // pushHostContext() only pushes Fibers that provide unique contexts. - if (contextFiberStackCursor.current !== fiber) { - return; - } - - pop(contextStackCursor$1, fiber); - pop(contextFiberStackCursor, fiber); - } - - var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is - // inherited deeply down the subtree. The upper bits only affect - // this immediate suspense boundary and gets reset each new - // boundary or suspense list. - - var SubtreeSuspenseContextMask = 1; // Subtree Flags: - // InvisibleParentSuspenseContext indicates that one of our parent Suspense - // boundaries is not currently showing visible main content. - // Either because it is already showing a fallback or is not mounted at all. - // We can use this to determine if it is desirable to trigger a fallback at - // the parent. If not, then we might need to trigger undesirable boundaries - // and/or suspend the commit to avoid hiding the parent content. - - var InvisibleParentSuspenseContext = 1; // Shallow Flags: - // ForceSuspenseFallback can be used by SuspenseList to force newly added - // items into their fallback state during one of the render passes. - - var ForceSuspenseFallback = 2; - var suspenseStackCursor = createCursor(DefaultSuspenseContext); - function hasSuspenseContext(parentContext, flag) { - return (parentContext & flag) !== 0; - } - function setDefaultShallowSuspenseContext(parentContext) { - return parentContext & SubtreeSuspenseContextMask; - } - function setShallowSuspenseContext(parentContext, shallowContext) { - return parentContext & SubtreeSuspenseContextMask | shallowContext; - } - function addSubtreeSuspenseContext(parentContext, subtreeContext) { - return parentContext | subtreeContext; - } - function pushSuspenseContext(fiber, newContext) { - push(suspenseStackCursor, newContext, fiber); - } - function popSuspenseContext(fiber) { - pop(suspenseStackCursor, fiber); - } - - function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { - // If it was the primary children that just suspended, capture and render the - // fallback. Otherwise, don't capture and bubble to the next boundary. - var nextState = workInProgress.memoizedState; - - if (nextState !== null) { - if (nextState.dehydrated !== null) { - // A dehydrated boundary always captures. - return true; - } - - return false; - } - - workInProgress.memoizedProps; // Regular boundaries always capture. - - { - return true; - } // If it's a boundary we should avoid, then we prefer to bubble up to the - } - function findFirstSuspended(row) { - var node = row; - - while (node !== null) { - if (node.tag === SuspenseComponent) { - var state = node.memoizedState; - - if (state !== null) { - var dehydrated = state.dehydrated; - - if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) { - return node; - } - } - } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't - // keep track of whether it suspended or not. - node.memoizedProps.revealOrder !== undefined) { - var didSuspend = (node.flags & DidCapture) !== NoFlags; - - if (didSuspend) { - return node; - } - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === row) { - return null; - } - - while (node.sibling === null) { - if (node.return === null || node.return === row) { - return null; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - - return null; - } - - var NoFlags$1 = - /* */ - 0; // Represents whether effect should fire. - - var HasEffect = - /* */ - 1; // Represents the phase in which the effect (not the clean-up) fires. - - var Insertion = - /* */ - 2; - var Layout = - /* */ - 4; - var Passive$1 = - /* */ - 8; - - // and should be reset before starting a new render. - // This tracks which mutable sources need to be reset after a render. - - var workInProgressSources = []; - function resetWorkInProgressVersions() { - for (var i = 0; i < workInProgressSources.length; i++) { - var mutableSource = workInProgressSources[i]; - - if (isPrimaryRenderer) { - mutableSource._workInProgressVersionPrimary = null; - } else { - mutableSource._workInProgressVersionSecondary = null; - } - } - - workInProgressSources.length = 0; - } - // This ensures that the version used for server rendering matches the one - // that is eventually read during hydration. - // If they don't match there's a potential tear and a full deopt render is required. - - function registerMutableSourceForHydration(root, mutableSource) { - var getVersion = mutableSource._getVersion; - var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished. - // Retaining it forever may interfere with GC. - - if (root.mutableSourceEagerHydrationData == null) { - root.mutableSourceEagerHydrationData = [mutableSource, version]; - } else { - root.mutableSourceEagerHydrationData.push(mutableSource, version); - } - } - - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, - ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; - var didWarnAboutMismatchedHooksForComponent; - var didWarnUncachedGetSnapshot; - - { - didWarnAboutMismatchedHooksForComponent = new Set(); - } - - // These are set right before calling the component. - var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from - // the work-in-progress hook. - - var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The - // current hook list is the list that belongs to the current fiber. The - // work-in-progress hook list is a new list that will be added to the - // work-in-progress fiber. - - var currentHook = null; - var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This - // does not get reset if we do another render pass; only when we're completely - // finished evaluating this component. This is an optimization so we know - // whether we need to clear render phase updates after a throw. - - var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This - // gets reset after each attempt. - // TODO: Maybe there's some way to consolidate this with - // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`. - - var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component. - - var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during - // hydration). This counter is global, so client ids are not stable across - // render attempts. - - var globalClientIdCounter = 0; - var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook - - var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. - // The list stores the order of hooks used during the initial render (mount). - // Subsequent renders (updates) reference this list. - - var hookTypesDev = null; - var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore - // the dependencies for Hooks that need them (e.g. useEffect or useMemo). - // When true, such Hooks will always be "remounted". Only used during hot reload. - - var ignorePreviousDependencies = false; - - function mountHookTypesDev() { - { - var hookName = currentHookNameInDev; - - if (hookTypesDev === null) { - hookTypesDev = [hookName]; - } else { - hookTypesDev.push(hookName); - } - } - } - - function updateHookTypesDev() { - { - var hookName = currentHookNameInDev; - - if (hookTypesDev !== null) { - hookTypesUpdateIndexDev++; - - if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { - warnOnHookMismatchInDev(hookName); - } - } - } - } - - function checkDepsAreArrayDev(deps) { - { - if (deps !== undefined && deps !== null && !isArray(deps)) { - // Verify deps, but only on mount to avoid extra checks. - // It's unlikely their type would change as usually you define them inline. - error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps); - } - } - } - - function warnOnHookMismatchInDev(currentHookName) { - { - var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1); - - if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { - didWarnAboutMismatchedHooksForComponent.add(componentName); - - if (hookTypesDev !== null) { - var table = ''; - var secondColumnStart = 30; - - for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { - var oldHookName = hookTypesDev[i]; - var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; - var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up - // lol @ IE not supporting String#repeat - - while (row.length < secondColumnStart) { - row += ' '; - } - - row += newHookName + '\n'; - table += row; - } - - error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table); - } - } - } - } - - function throwInvalidHookError() { - throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); - } - - function areHookInputsEqual(nextDeps, prevDeps) { - { - if (ignorePreviousDependencies) { - // Only true when this component is being hot reloaded. - return false; - } - } - - if (prevDeps === null) { - { - error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); - } - - return false; - } - - { - // Don't bother comparing lengths in prod because these arrays should be - // passed inline. - if (nextDeps.length !== prevDeps.length) { - error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]"); - } - } - - for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - if (objectIs(nextDeps[i], prevDeps[i])) { - continue; - } - - return false; - } - - return true; - } - - function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) { - renderLanes = nextRenderLanes; - currentlyRenderingFiber$1 = workInProgress; - - { - hookTypesDev = current !== null ? current._debugHookTypes : null; - hookTypesUpdateIndexDev = -1; // Used for hot reloading: - - ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; - } - - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - workInProgress.lanes = NoLanes; // The following should have already been reset - // currentHook = null; - // workInProgressHook = null; - // didScheduleRenderPhaseUpdate = false; - // localIdCounter = 0; - // TODO Warn if no hooks are used at all during mount, then some are used during update. - // Currently we will identify the update render as a mount because memoizedState === null. - // This is tricky because it's valid for certain types of components (e.g. React.lazy) - // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used. - // Non-stateful hooks (e.g. context) don't get added to memoizedState, - // so memoizedState would be null during updates and mounts. - - { - if (current !== null && current.memoizedState !== null) { - ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; - } else if (hookTypesDev !== null) { - // This dispatcher handles an edge case where a component is updating, - // but no stateful hooks have been used. - // We want to match the production code behavior (which will use HooksDispatcherOnMount), - // but with the extra DEV validation to ensure hooks ordering hasn't changed. - // This dispatcher does that. - ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; - } else { - ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; - } - } - - var children = Component(props, secondArg); // Check if there was a render phase update - - if (didScheduleRenderPhaseUpdateDuringThisPass) { - // Keep rendering in a loop for as long as render phase updates continue to - // be scheduled. Use a counter to prevent infinite loops. - var numberOfReRenders = 0; - - do { - didScheduleRenderPhaseUpdateDuringThisPass = false; - localIdCounter = 0; - - if (numberOfReRenders >= RE_RENDER_LIMIT) { - throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); - } - - numberOfReRenders += 1; - - { - // Even when hot reloading, allow dependencies to stabilize - // after first render to prevent infinite render phase updates. - ignorePreviousDependencies = false; - } // Start over from the beginning of the list - - - currentHook = null; - workInProgressHook = null; - workInProgress.updateQueue = null; - - { - // Also validate hook order for cascading updates. - hookTypesUpdateIndexDev = -1; - } - - ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ; - children = Component(props, secondArg); - } while (didScheduleRenderPhaseUpdateDuringThisPass); - } // We can assume the previous dispatcher is always this one, since we set it - // at the beginning of the render phase and there's no re-entrance. - - - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - - { - workInProgress._debugHookTypes = hookTypesDev; - } // This check uses currentHook so that it works the same in DEV and prod bundles. - // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. - - - var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; - renderLanes = NoLanes; - currentlyRenderingFiber$1 = null; - currentHook = null; - workInProgressHook = null; - - { - currentHookNameInDev = null; - hookTypesDev = null; - hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last - // render. If this fires, it suggests that we incorrectly reset the static - // flags in some other part of the codebase. This has happened before, for - // example, in the SuspenseList implementation. - - if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird - // and creates false positives. To make this work in legacy mode, we'd - // need to mark fibers that commit in an incomplete state, somehow. For - // now I'll disable the warning that most of the bugs that would trigger - // it are either exclusive to concurrent mode or exist in both. - (current.mode & ConcurrentMode) !== NoMode) { - error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.'); - } - } - - didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook - // localIdCounter = 0; - - if (didRenderTooFewHooks) { - throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.'); - } - - return children; - } - function checkDidRenderIdHook() { - // This should be called immediately after every renderWithHooks call. - // Conceptually, it's part of the return value of renderWithHooks; it's only a - // separate function to avoid using an array tuple. - var didRenderIdHook = localIdCounter !== 0; - localIdCounter = 0; - return didRenderIdHook; - } - function bailoutHooks(current, workInProgress, lanes) { - workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the - // complete phase (bubbleProperties). - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update); - } else { - workInProgress.flags &= ~(Passive | Update); - } - - current.lanes = removeLanes(current.lanes, lanes); - } - function resetHooksAfterThrow() { - // We can assume the previous dispatcher is always this one, since we set it - // at the beginning of the render phase and there's no re-entrance. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - - if (didScheduleRenderPhaseUpdate) { - // There were render phase updates. These are only valid for this render - // phase, which we are now aborting. Remove the updates from the queues so - // they do not persist to the next render. Do not remove updates from hooks - // that weren't processed. - // - // Only reset the updates from the queue if it has a clone. If it does - // not have a clone, that means it wasn't processed, and the updates were - // scheduled before we entered the render phase. - var hook = currentlyRenderingFiber$1.memoizedState; - - while (hook !== null) { - var queue = hook.queue; - - if (queue !== null) { - queue.pending = null; - } - - hook = hook.next; - } - - didScheduleRenderPhaseUpdate = false; - } - - renderLanes = NoLanes; - currentlyRenderingFiber$1 = null; - currentHook = null; - workInProgressHook = null; - - { - hookTypesDev = null; - hookTypesUpdateIndexDev = -1; - currentHookNameInDev = null; - isUpdatingOpaqueValueInRenderPhase = false; - } - - didScheduleRenderPhaseUpdateDuringThisPass = false; - localIdCounter = 0; - } - - function mountWorkInProgressHook() { - var hook = { - memoizedState: null, - baseState: null, - baseQueue: null, - queue: null, - next: null - }; - - if (workInProgressHook === null) { - // This is the first hook in the list - currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook; - } else { - // Append to the end of the list - workInProgressHook = workInProgressHook.next = hook; - } - - return workInProgressHook; - } - - function updateWorkInProgressHook() { - // This function is used both for updates and for re-renders triggered by a - // render phase update. It assumes there is either a current hook we can - // clone, or a work-in-progress hook from a previous render pass that we can - // use as a base. When we reach the end of the base list, we must switch to - // the dispatcher used for mounts. - var nextCurrentHook; - - if (currentHook === null) { - var current = currentlyRenderingFiber$1.alternate; - - if (current !== null) { - nextCurrentHook = current.memoizedState; - } else { - nextCurrentHook = null; - } - } else { - nextCurrentHook = currentHook.next; - } - - var nextWorkInProgressHook; - - if (workInProgressHook === null) { - nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState; - } else { - nextWorkInProgressHook = workInProgressHook.next; - } - - if (nextWorkInProgressHook !== null) { - // There's already a work-in-progress. Reuse it. - workInProgressHook = nextWorkInProgressHook; - nextWorkInProgressHook = workInProgressHook.next; - currentHook = nextCurrentHook; - } else { - // Clone from the current hook. - if (nextCurrentHook === null) { - throw new Error('Rendered more hooks than during the previous render.'); - } - - currentHook = nextCurrentHook; - var newHook = { - memoizedState: currentHook.memoizedState, - baseState: currentHook.baseState, - baseQueue: currentHook.baseQueue, - queue: currentHook.queue, - next: null - }; - - if (workInProgressHook === null) { - // This is the first hook in the list. - currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook; - } else { - // Append to the end of the list. - workInProgressHook = workInProgressHook.next = newHook; - } - } - - return workInProgressHook; - } - - function createFunctionComponentUpdateQueue() { - return { - lastEffect: null, - stores: null - }; - } - - function basicStateReducer(state, action) { - // $FlowFixMe: Flow doesn't like mixed types - return typeof action === 'function' ? action(state) : action; - } - - function mountReducer(reducer, initialArg, init) { - var hook = mountWorkInProgressHook(); - var initialState; - - if (init !== undefined) { - initialState = init(initialArg); - } else { - initialState = initialArg; - } - - hook.memoizedState = hook.baseState = initialState; - var queue = { - pending: null, - interleaved: null, - lanes: NoLanes, - dispatch: null, - lastRenderedReducer: reducer, - lastRenderedState: initialState - }; - hook.queue = queue; - var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue); - return [hook.memoizedState, dispatch]; - } - - function updateReducer(reducer, initialArg, init) { - var hook = updateWorkInProgressHook(); - var queue = hook.queue; - - if (queue === null) { - throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); - } - - queue.lastRenderedReducer = reducer; - var current = currentHook; // The last rebase update that is NOT part of the base state. - - var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet. - - var pendingQueue = queue.pending; - - if (pendingQueue !== null) { - // We have new updates that haven't been processed yet. - // We'll add them to the base queue. - if (baseQueue !== null) { - // Merge the pending queue and the base queue. - var baseFirst = baseQueue.next; - var pendingFirst = pendingQueue.next; - baseQueue.next = pendingFirst; - pendingQueue.next = baseFirst; - } - - { - if (current.baseQueue !== baseQueue) { - // Internal invariant that should never happen, but feasibly could in - // the future if we implement resuming, or some form of that. - error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.'); - } - } - - current.baseQueue = baseQueue = pendingQueue; - queue.pending = null; - } - - if (baseQueue !== null) { - // We have a queue to process. - var first = baseQueue.next; - var newState = current.baseState; - var newBaseState = null; - var newBaseQueueFirst = null; - var newBaseQueueLast = null; - var update = first; - - do { - var updateLane = update.lane; - - if (!isSubsetOfLanes(renderLanes, updateLane)) { - // Priority is insufficient. Skip this update. If this is the first - // skipped update, the previous update/state is the new base - // update/state. - var clone = { - lane: updateLane, - action: update.action, - hasEagerState: update.hasEagerState, - eagerState: update.eagerState, - next: null - }; - - if (newBaseQueueLast === null) { - newBaseQueueFirst = newBaseQueueLast = clone; - newBaseState = newState; - } else { - newBaseQueueLast = newBaseQueueLast.next = clone; - } // Update the remaining priority in the queue. - // TODO: Don't need to accumulate this. Instead, we can remove - // renderLanes from the original lanes. - - - currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane); - markSkippedUpdateLanes(updateLane); - } else { - // This update does have sufficient priority. - if (newBaseQueueLast !== null) { - var _clone = { - // This update is going to be committed so we never want uncommit - // it. Using NoLane works because 0 is a subset of all bitmasks, so - // this will never be skipped by the check above. - lane: NoLane, - action: update.action, - hasEagerState: update.hasEagerState, - eagerState: update.eagerState, - next: null - }; - newBaseQueueLast = newBaseQueueLast.next = _clone; - } // Process this update. - - - if (update.hasEagerState) { - // If this update is a state update (not a reducer) and was processed eagerly, - // we can use the eagerly computed state - newState = update.eagerState; - } else { - var action = update.action; - newState = reducer(newState, action); - } - } - - update = update.next; - } while (update !== null && update !== first); - - if (newBaseQueueLast === null) { - newBaseState = newState; - } else { - newBaseQueueLast.next = newBaseQueueFirst; - } // Mark that the fiber performed work, but only if the new state is - // different from the current state. - - - if (!objectIs(newState, hook.memoizedState)) { - markWorkInProgressReceivedUpdate(); - } - - hook.memoizedState = newState; - hook.baseState = newBaseState; - hook.baseQueue = newBaseQueueLast; - queue.lastRenderedState = newState; - } // Interleaved updates are stored on a separate queue. We aren't going to - // process them during this render, but we do need to track which lanes - // are remaining. - - - var lastInterleaved = queue.interleaved; - - if (lastInterleaved !== null) { - var interleaved = lastInterleaved; - - do { - var interleavedLane = interleaved.lane; - currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane); - markSkippedUpdateLanes(interleavedLane); - interleaved = interleaved.next; - } while (interleaved !== lastInterleaved); - } else if (baseQueue === null) { - // `queue.lanes` is used for entangling transitions. We can set it back to - // zero once the queue is empty. - queue.lanes = NoLanes; - } - - var dispatch = queue.dispatch; - return [hook.memoizedState, dispatch]; - } - - function rerenderReducer(reducer, initialArg, init) { - var hook = updateWorkInProgressHook(); - var queue = hook.queue; - - if (queue === null) { - throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); - } - - queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous - // work-in-progress hook. - - var dispatch = queue.dispatch; - var lastRenderPhaseUpdate = queue.pending; - var newState = hook.memoizedState; - - if (lastRenderPhaseUpdate !== null) { - // The queue doesn't persist past this render pass. - queue.pending = null; - var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; - var update = firstRenderPhaseUpdate; - - do { - // Process this render phase update. We don't have to check the - // priority because it will always be the same as the current - // render's. - var action = update.action; - newState = reducer(newState, action); - update = update.next; - } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is - // different from the current state. - - - if (!objectIs(newState, hook.memoizedState)) { - markWorkInProgressReceivedUpdate(); - } - - hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to - // the base state unless the queue is empty. - // TODO: Not sure if this is the desired semantics, but it's what we - // do for gDSFP. I can't remember why. - - if (hook.baseQueue === null) { - hook.baseState = newState; - } - - queue.lastRenderedState = newState; - } - - return [newState, dispatch]; - } - - function mountMutableSource(source, getSnapshot, subscribe) { - { - return undefined; - } - } - - function updateMutableSource(source, getSnapshot, subscribe) { - { - return undefined; - } - } - - function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - var fiber = currentlyRenderingFiber$1; - var hook = mountWorkInProgressHook(); - var nextSnapshot; - var isHydrating = getIsHydrating(); - - if (isHydrating) { - if (getServerSnapshot === undefined) { - throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); - } - - nextSnapshot = getServerSnapshot(); - - { - if (!didWarnUncachedGetSnapshot) { - if (nextSnapshot !== getServerSnapshot()) { - error('The result of getServerSnapshot should be cached to avoid an infinite loop'); - - didWarnUncachedGetSnapshot = true; - } - } - } - } else { - nextSnapshot = getSnapshot(); - - { - if (!didWarnUncachedGetSnapshot) { - var cachedSnapshot = getSnapshot(); - - if (!objectIs(nextSnapshot, cachedSnapshot)) { - error('The result of getSnapshot should be cached to avoid an infinite loop'); - - didWarnUncachedGetSnapshot = true; - } - } - } // Unless we're rendering a blocking lane, schedule a consistency check. - // Right before committing, we will walk the tree and check if any of the - // stores were mutated. - // - // We won't do this if we're hydrating server-rendered content, because if - // the content is stale, it's already visible anyway. Instead we'll patch - // it up in a passive effect. - - - var root = getWorkInProgressRoot(); - - if (root === null) { - throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); - } - - if (!includesBlockingLane(root, renderLanes)) { - pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); - } - } // Read the current snapshot from the store on every render. This breaks the - // normal rules of React, and only works because store updates are - // always synchronous. - - - hook.memoizedState = nextSnapshot; - var inst = { - value: nextSnapshot, - getSnapshot: getSnapshot - }; - hook.queue = inst; // Schedule an effect to subscribe to the store. - - mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update - // this whenever subscribe, getSnapshot, or value changes. Because there's no - // clean-up function, and we track the deps correctly, we can call pushEffect - // directly, without storing any additional state. For the same reason, we - // don't need to set a static flag, either. - // TODO: We can move this to the passive phase once we add a pre-commit - // consistency check. See the next comment. - - fiber.flags |= Passive; - pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); - return nextSnapshot; - } - - function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - var fiber = currentlyRenderingFiber$1; - var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the - // normal rules of React, and only works because store updates are - // always synchronous. - - var nextSnapshot = getSnapshot(); - - { - if (!didWarnUncachedGetSnapshot) { - var cachedSnapshot = getSnapshot(); - - if (!objectIs(nextSnapshot, cachedSnapshot)) { - error('The result of getSnapshot should be cached to avoid an infinite loop'); - - didWarnUncachedGetSnapshot = true; - } - } - } - - var prevSnapshot = hook.memoizedState; - var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot); - - if (snapshotChanged) { - hook.memoizedState = nextSnapshot; - markWorkInProgressReceivedUpdate(); - } - - var inst = hook.queue; - updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the - // commit phase if there was an interleaved mutation. In concurrent mode - // this can happen all the time, but even in synchronous mode, an earlier - // effect may have mutated the store. - - if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by - // checking whether we scheduled a subscription effect above. - workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) { - fiber.flags |= Passive; - pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check. - // Right before committing, we will walk the tree and check if any of the - // stores were mutated. - - var root = getWorkInProgressRoot(); - - if (root === null) { - throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); - } - - if (!includesBlockingLane(root, renderLanes)) { - pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); - } - } - - return nextSnapshot; - } - - function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) { - fiber.flags |= StoreConsistency; - var check = { - getSnapshot: getSnapshot, - value: renderedSnapshot - }; - var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; - - if (componentUpdateQueue === null) { - componentUpdateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; - componentUpdateQueue.stores = [check]; - } else { - var stores = componentUpdateQueue.stores; - - if (stores === null) { - componentUpdateQueue.stores = [check]; - } else { - stores.push(check); - } - } - } - - function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) { - // These are updated in the passive phase - inst.value = nextSnapshot; - inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could - // have been in an event that fired before the passive effects, or it could - // have been in a layout effect. In that case, we would have used the old - // snapsho and getSnapshot values to bail out. We need to check one more time. - - if (checkIfSnapshotChanged(inst)) { - // Force a re-render. - forceStoreRerender(fiber); - } - } - - function subscribeToStore(fiber, inst, subscribe) { - var handleStoreChange = function () { - // The store changed. Check if the snapshot changed since the last time we - // read from the store. - if (checkIfSnapshotChanged(inst)) { - // Force a re-render. - forceStoreRerender(fiber); - } - }; // Subscribe to the store and return a clean-up function. - - - return subscribe(handleStoreChange); - } - - function checkIfSnapshotChanged(inst) { - var latestGetSnapshot = inst.getSnapshot; - var prevValue = inst.value; - - try { - var nextValue = latestGetSnapshot(); - return !objectIs(prevValue, nextValue); - } catch (error) { - return true; - } - } - - function forceStoreRerender(fiber) { - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - - function mountState(initialState) { - var hook = mountWorkInProgressHook(); - - if (typeof initialState === 'function') { - // $FlowFixMe: Flow doesn't like mixed types - initialState = initialState(); - } - - hook.memoizedState = hook.baseState = initialState; - var queue = { - pending: null, - interleaved: null, - lanes: NoLanes, - dispatch: null, - lastRenderedReducer: basicStateReducer, - lastRenderedState: initialState - }; - hook.queue = queue; - var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue); - return [hook.memoizedState, dispatch]; - } - - function updateState(initialState) { - return updateReducer(basicStateReducer); - } - - function rerenderState(initialState) { - return rerenderReducer(basicStateReducer); - } - - function pushEffect(tag, create, destroy, deps) { - var effect = { - tag: tag, - create: create, - destroy: destroy, - deps: deps, - // Circular - next: null - }; - var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; - - if (componentUpdateQueue === null) { - componentUpdateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; - componentUpdateQueue.lastEffect = effect.next = effect; - } else { - var lastEffect = componentUpdateQueue.lastEffect; - - if (lastEffect === null) { - componentUpdateQueue.lastEffect = effect.next = effect; - } else { - var firstEffect = lastEffect.next; - lastEffect.next = effect; - effect.next = firstEffect; - componentUpdateQueue.lastEffect = effect; - } - } - - return effect; - } - - function mountRef(initialValue) { - var hook = mountWorkInProgressHook(); - - { - var _ref2 = { - current: initialValue - }; - hook.memoizedState = _ref2; - return _ref2; - } - } - - function updateRef(initialValue) { - var hook = updateWorkInProgressHook(); - return hook.memoizedState; - } - - function mountEffectImpl(fiberFlags, hookFlags, create, deps) { - var hook = mountWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - currentlyRenderingFiber$1.flags |= fiberFlags; - hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps); - } - - function updateEffectImpl(fiberFlags, hookFlags, create, deps) { - var hook = updateWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - var destroy = undefined; - - if (currentHook !== null) { - var prevEffect = currentHook.memoizedState; - destroy = prevEffect.destroy; - - if (nextDeps !== null) { - var prevDeps = prevEffect.deps; - - if (areHookInputsEqual(nextDeps, prevDeps)) { - hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps); - return; - } - } - } - - currentlyRenderingFiber$1.flags |= fiberFlags; - hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps); - } - - function mountEffect(create, deps) { - if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { - return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps); - } else { - return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps); - } - } - - function updateEffect(create, deps) { - return updateEffectImpl(Passive, Passive$1, create, deps); - } - - function mountInsertionEffect(create, deps) { - return mountEffectImpl(Update, Insertion, create, deps); - } - - function updateInsertionEffect(create, deps) { - return updateEffectImpl(Update, Insertion, create, deps); - } - - function mountLayoutEffect(create, deps) { - var fiberFlags = Update; - - { - fiberFlags |= LayoutStatic; - } - - if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - - return mountEffectImpl(fiberFlags, Layout, create, deps); - } - - function updateLayoutEffect(create, deps) { - return updateEffectImpl(Update, Layout, create, deps); - } - - function imperativeHandleEffect(create, ref) { - if (typeof ref === 'function') { - var refCallback = ref; - - var _inst = create(); - - refCallback(_inst); - return function () { - refCallback(null); - }; - } else if (ref !== null && ref !== undefined) { - var refObject = ref; - - { - if (!refObject.hasOwnProperty('current')) { - error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}'); - } - } - - var _inst2 = create(); - - refObject.current = _inst2; - return function () { - refObject.current = null; - }; - } - } - - function mountImperativeHandle(ref, create, deps) { - { - if (typeof create !== 'function') { - error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); - } - } // TODO: If deps are provided, should we skip comparing the ref itself? - - - var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - var fiberFlags = Update; - - { - fiberFlags |= LayoutStatic; - } - - if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - - return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); - } - - function updateImperativeHandle(ref, create, deps) { - { - if (typeof create !== 'function') { - error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); - } - } // TODO: If deps are provided, should we skip comparing the ref itself? - - - var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); - } - - function mountDebugValue(value, formatterFn) {// This hook is normally a no-op. - // The react-debug-hooks package injects its own implementation - // so that e.g. DevTools can display custom hook values. - } - - var updateDebugValue = mountDebugValue; - - function mountCallback(callback, deps) { - var hook = mountWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - hook.memoizedState = [callback, nextDeps]; - return callback; - } - - function updateCallback(callback, deps) { - var hook = updateWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - var prevState = hook.memoizedState; - - if (prevState !== null) { - if (nextDeps !== null) { - var prevDeps = prevState[1]; - - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } - } - - hook.memoizedState = [callback, nextDeps]; - return callback; - } - - function mountMemo(nextCreate, deps) { - var hook = mountWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - var nextValue = nextCreate(); - hook.memoizedState = [nextValue, nextDeps]; - return nextValue; - } - - function updateMemo(nextCreate, deps) { - var hook = updateWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - var prevState = hook.memoizedState; - - if (prevState !== null) { - // Assume these are defined. If they're not, areHookInputsEqual will warn. - if (nextDeps !== null) { - var prevDeps = prevState[1]; - - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } - } - - var nextValue = nextCreate(); - hook.memoizedState = [nextValue, nextDeps]; - return nextValue; - } - - function mountDeferredValue(value) { - var _mountState = mountState(value), - prevValue = _mountState[0], - setValue = _mountState[1]; - - mountEffect(function () { - var prevTransition = ReactCurrentBatchConfig$1.transition; - ReactCurrentBatchConfig$1.transition = {}; - - try { - setValue(value); - } finally { - ReactCurrentBatchConfig$1.transition = prevTransition; - } - }, [value]); - return prevValue; - } - - function updateDeferredValue(value) { - var _updateState = updateState(), - prevValue = _updateState[0], - setValue = _updateState[1]; - - updateEffect(function () { - var prevTransition = ReactCurrentBatchConfig$1.transition; - ReactCurrentBatchConfig$1.transition = {}; - - try { - setValue(value); - } finally { - ReactCurrentBatchConfig$1.transition = prevTransition; - } - }, [value]); - return prevValue; - } - - function rerenderDeferredValue(value) { - var _rerenderState = rerenderState(), - prevValue = _rerenderState[0], - setValue = _rerenderState[1]; - - updateEffect(function () { - var prevTransition = ReactCurrentBatchConfig$1.transition; - ReactCurrentBatchConfig$1.transition = {}; - - try { - setValue(value); - } finally { - ReactCurrentBatchConfig$1.transition = prevTransition; - } - }, [value]); - return prevValue; - } - - function startTransition(setPending, callback, options) { - var previousPriority = getCurrentUpdatePriority(); - setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); - setPending(true); - var prevTransition = ReactCurrentBatchConfig$1.transition; - ReactCurrentBatchConfig$1.transition = {}; - var currentTransition = ReactCurrentBatchConfig$1.transition; - - { - ReactCurrentBatchConfig$1.transition._updatedFibers = new Set(); - } - - try { - setPending(false); - callback(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$1.transition = prevTransition; - - { - if (prevTransition === null && currentTransition._updatedFibers) { - var updatedFibersCount = currentTransition._updatedFibers.size; - - if (updatedFibersCount > 10) { - warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); - } - - currentTransition._updatedFibers.clear(); - } - } - } - } - - function mountTransition() { - var _mountState2 = mountState(false), - isPending = _mountState2[0], - setPending = _mountState2[1]; // The `start` method never changes. - - - var start = startTransition.bind(null, setPending); - var hook = mountWorkInProgressHook(); - hook.memoizedState = start; - return [isPending, start]; - } - - function updateTransition() { - var _updateState2 = updateState(), - isPending = _updateState2[0]; - - var hook = updateWorkInProgressHook(); - var start = hook.memoizedState; - return [isPending, start]; - } - - function rerenderTransition() { - var _rerenderState2 = rerenderState(), - isPending = _rerenderState2[0]; - - var hook = updateWorkInProgressHook(); - var start = hook.memoizedState; - return [isPending, start]; - } - - var isUpdatingOpaqueValueInRenderPhase = false; - function getIsUpdatingOpaqueValueInRenderPhaseInDEV() { - { - return isUpdatingOpaqueValueInRenderPhase; - } - } - - function mountId() { - var hook = mountWorkInProgressHook(); - var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we - // should do this in Fiber, too? Deferring this decision for now because - // there's no other place to store the prefix except for an internal field on - // the public createRoot object, which the fiber tree does not currently have - // a reference to. - - var identifierPrefix = root.identifierPrefix; - var id; - - if (getIsHydrating()) { - var treeId = getTreeId(); // Use a captial R prefix for server-generated ids. - - id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end - // that represents the position of this useId hook among all the useId - // hooks for this fiber. - - var localId = localIdCounter++; - - if (localId > 0) { - id += 'H' + localId.toString(32); - } - - id += ':'; - } else { - // Use a lowercase r prefix for client-generated ids. - var globalClientId = globalClientIdCounter++; - id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':'; - } - - hook.memoizedState = id; - return id; - } - - function updateId() { - var hook = updateWorkInProgressHook(); - var id = hook.memoizedState; - return id; - } - - function dispatchReducerAction(fiber, queue, action) { - { - if (typeof arguments[3] === 'function') { - error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); - } - } - - var lane = requestUpdateLane(fiber); - var update = { - lane: lane, - action: action, - hasEagerState: false, - eagerState: null, - next: null - }; - - if (isRenderPhaseUpdate(fiber)) { - enqueueRenderPhaseUpdate(queue, update); - } else { - enqueueUpdate$1(fiber, queue, update); - var eventTime = requestEventTime(); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitionUpdate(root, queue, lane); - } - } - - markUpdateInDevTools(fiber, lane); - } - - function dispatchSetState(fiber, queue, action) { - { - if (typeof arguments[3] === 'function') { - error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); - } - } - - var lane = requestUpdateLane(fiber); - var update = { - lane: lane, - action: action, - hasEagerState: false, - eagerState: null, - next: null - }; - - if (isRenderPhaseUpdate(fiber)) { - enqueueRenderPhaseUpdate(queue, update); - } else { - enqueueUpdate$1(fiber, queue, update); - var alternate = fiber.alternate; - - if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) { - // The queue is currently empty, which means we can eagerly compute the - // next state before entering the render phase. If the new state is the - // same as the current state, we may be able to bail out entirely. - var lastRenderedReducer = queue.lastRenderedReducer; - - if (lastRenderedReducer !== null) { - var prevDispatcher; - - { - prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - } - - try { - var currentState = queue.lastRenderedState; - var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute - // it, on the update object. If the reducer hasn't changed by the - // time we enter the render phase, then the eager state can be used - // without calling the reducer again. - - update.hasEagerState = true; - update.eagerState = eagerState; - - if (objectIs(eagerState, currentState)) { - // Fast path. We can bail out without scheduling React to re-render. - // It's still possible that we'll need to rebase this update later, - // if the component re-renders for a different reason and by that - // time the reducer has changed. - return; - } - } catch (error) {// Suppress the error. It will throw again in the render phase. - } finally { - { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - } - } - } - - var eventTime = requestEventTime(); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitionUpdate(root, queue, lane); - } - } - - markUpdateInDevTools(fiber, lane); - } - - function isRenderPhaseUpdate(fiber) { - var alternate = fiber.alternate; - return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1; - } - - function enqueueRenderPhaseUpdate(queue, update) { - // This is a render phase update. Stash it in a lazily-created map of - // queue -> linked list of updates. After this render pass, we'll restart - // and apply the stashed updates on top of the work-in-progress hook. - didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; - var pending = queue.pending; - - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - - queue.pending = update; - } - - function enqueueUpdate$1(fiber, queue, update, lane) { - if (isInterleavedUpdate(fiber)) { - var interleaved = queue.interleaved; - - if (interleaved === null) { - // This is the first update. Create a circular list. - update.next = update; // At the end of the current render, this queue's interleaved updates will - // be transferred to the pending queue. - - pushInterleavedQueue(queue); - } else { - update.next = interleaved.next; - interleaved.next = update; - } - - queue.interleaved = update; - } else { - var pending = queue.pending; - - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - - queue.pending = update; - } - } - - function entangleTransitionUpdate(root, queue, lane) { - if (isTransitionLane(lane)) { - var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they - // must have finished. We can remove them from the shared queue, which - // represents a superset of the actually pending lanes. In some cases we - // may entangle more than we need to, but that's OK. In fact it's worse if - // we *don't* entangle when we should. - - queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. - - var newQueueLanes = mergeLanes(queueLanes, lane); - queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if - // the lane finished since the last time we entangled it. So we need to - // entangle it again, just to be sure. - - markRootEntangled(root, newQueueLanes); - } - } - - function markUpdateInDevTools(fiber, lane, action) { - - { - markStateUpdateScheduled(fiber, lane); - } - } - - var ContextOnlyDispatcher = { - readContext: readContext, - useCallback: throwInvalidHookError, - useContext: throwInvalidHookError, - useEffect: throwInvalidHookError, - useImperativeHandle: throwInvalidHookError, - useInsertionEffect: throwInvalidHookError, - useLayoutEffect: throwInvalidHookError, - useMemo: throwInvalidHookError, - useReducer: throwInvalidHookError, - useRef: throwInvalidHookError, - useState: throwInvalidHookError, - useDebugValue: throwInvalidHookError, - useDeferredValue: throwInvalidHookError, - useTransition: throwInvalidHookError, - useMutableSource: throwInvalidHookError, - useSyncExternalStore: throwInvalidHookError, - useId: throwInvalidHookError, - unstable_isNewReconciler: enableNewReconciler - }; - - var HooksDispatcherOnMountInDEV = null; - var HooksDispatcherOnMountWithHookTypesInDEV = null; - var HooksDispatcherOnUpdateInDEV = null; - var HooksDispatcherOnRerenderInDEV = null; - var InvalidNestedHooksDispatcherOnMountInDEV = null; - var InvalidNestedHooksDispatcherOnUpdateInDEV = null; - var InvalidNestedHooksDispatcherOnRerenderInDEV = null; - - { - var warnInvalidContextAccess = function () { - error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); - }; - - var warnInvalidHookAccess = function () { - error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); - }; - - HooksDispatcherOnMountInDEV = { - readContext: function (context) { - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - mountHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - mountHookTypesDev(); - return mountRef(initialValue); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - mountHookTypesDev(); - return mountDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - mountHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - mountHookTypesDev(); - return mountTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - mountHookTypesDev(); - return mountMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - mountHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - mountHookTypesDev(); - return mountId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - HooksDispatcherOnMountWithHookTypesInDEV = { - readContext: function (context) { - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - updateHookTypesDev(); - return mountCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - updateHookTypesDev(); - return mountEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - updateHookTypesDev(); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - updateHookTypesDev(); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - updateHookTypesDev(); - return mountLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - updateHookTypesDev(); - return mountRef(initialValue); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - updateHookTypesDev(); - return mountDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - updateHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - updateHookTypesDev(); - return mountTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - updateHookTypesDev(); - return mountMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - updateHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - updateHookTypesDev(); - return mountId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - HooksDispatcherOnUpdateInDEV = { - readContext: function (context) { - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - updateHookTypesDev(); - return updateRef(); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - updateHookTypesDev(); - return updateDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - updateHookTypesDev(); - return updateTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - HooksDispatcherOnRerenderInDEV = { - readContext: function (context) { - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - - try { - return rerenderReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - updateHookTypesDev(); - return updateRef(); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - - try { - return rerenderState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - updateHookTypesDev(); - return rerenderDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - updateHookTypesDev(); - return rerenderTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - InvalidNestedHooksDispatcherOnMountInDEV = { - readContext: function (context) { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - warnInvalidHookAccess(); - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - warnInvalidHookAccess(); - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountRef(initialValue); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - warnInvalidHookAccess(); - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - InvalidNestedHooksDispatcherOnUpdateInDEV = { - readContext: function (context) { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateRef(); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - InvalidNestedHooksDispatcherOnRerenderInDEV = { - readContext: function (context) { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return rerenderReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateRef(); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return rerenderState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return rerenderDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return rerenderTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - } - - var now$2 = Scheduler.unstable_now; - var commitTime = 0; - var layoutEffectStartTime = -1; - var profilerStartTime = -1; - var passiveEffectStartTime = -1; - /** - * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect). - * - * The overall sequence is: - * 1. render - * 2. commit (and call `onRender`, `onCommit`) - * 3. check for nested updates - * 4. flush passive effects (and call `onPostCommit`) - * - * Nested updates are identified in step 3 above, - * but step 4 still applies to the work that was just committed. - * We use two flags to track nested updates then: - * one tracks whether the upcoming update is a nested update, - * and the other tracks whether the current update was a nested update. - * The first value gets synced to the second at the start of the render phase. - */ - - var currentUpdateIsNested = false; - var nestedUpdateScheduled = false; - - function isCurrentUpdateNested() { - return currentUpdateIsNested; - } - - function markNestedUpdateScheduled() { - { - nestedUpdateScheduled = true; - } - } - - function resetNestedUpdateFlag() { - { - currentUpdateIsNested = false; - nestedUpdateScheduled = false; - } - } - - function syncNestedUpdateFlag() { - { - currentUpdateIsNested = nestedUpdateScheduled; - nestedUpdateScheduled = false; - } - } - - function getCommitTime() { - return commitTime; - } - - function recordCommitTime() { - - commitTime = now$2(); - } - - function startProfilerTimer(fiber) { - - profilerStartTime = now$2(); - - if (fiber.actualStartTime < 0) { - fiber.actualStartTime = now$2(); - } - } - - function stopProfilerTimerIfRunning(fiber) { - - profilerStartTime = -1; - } - - function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { - - if (profilerStartTime >= 0) { - var elapsedTime = now$2() - profilerStartTime; - fiber.actualDuration += elapsedTime; - - if (overrideBaseTime) { - fiber.selfBaseDuration = elapsedTime; - } - - profilerStartTime = -1; - } - } - - function recordLayoutEffectDuration(fiber) { - - if (layoutEffectStartTime >= 0) { - var elapsedTime = now$2() - layoutEffectStartTime; - layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor - // Or the root (for the DevTools Profiler to read) - - var parentFiber = fiber.return; - - while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - root.effectDuration += elapsedTime; - return; - - case Profiler: - var parentStateNode = parentFiber.stateNode; - parentStateNode.effectDuration += elapsedTime; - return; - } - - parentFiber = parentFiber.return; - } - } - } - - function recordPassiveEffectDuration(fiber) { - - if (passiveEffectStartTime >= 0) { - var elapsedTime = now$2() - passiveEffectStartTime; - passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor - // Or the root (for the DevTools Profiler to read) - - var parentFiber = fiber.return; - - while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - - if (root !== null) { - root.passiveEffectDuration += elapsedTime; - } - - return; - - case Profiler: - var parentStateNode = parentFiber.stateNode; - - if (parentStateNode !== null) { - // Detached fibers have their state node cleared out. - // In this case, the return pointer is also cleared out, - // so we won't be able to report the time spent in this Profiler's subtree. - parentStateNode.passiveEffectDuration += elapsedTime; - } - - return; - } - - parentFiber = parentFiber.return; - } - } - } - - function startLayoutEffectTimer() { - - layoutEffectStartTime = now$2(); - } - - function startPassiveEffectTimer() { - - passiveEffectStartTime = now$2(); - } - - function transferActualDuration(fiber) { - // Transfer time spent rendering these children so we don't lose it - // after we rerender. This is used as a helper in special cases - // where we should count the work of multiple passes. - var child = fiber.child; - - while (child) { - fiber.actualDuration += child.actualDuration; - child = child.sibling; - } - } - - function createCapturedValue(value, source) { - // If the value is an error, call this function immediately after it is thrown - // so the stack is accurate. - return { - value: value, - source: source, - stack: getStackByFiberInDevAndProd(source) - }; - } - - // This module is forked in different environments. - // By default, return `true` to log errors to the console. - // Forks can return `false` if this isn't desirable. - function showErrorDialog(boundary, errorInfo) { - return true; - } - - function logCapturedError(boundary, errorInfo) { - try { - var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging. - // This enables renderers like ReactNative to better manage redbox behavior. - - if (logError === false) { - return; - } - - var error = errorInfo.value; - - if (true) { - var source = errorInfo.source; - var stack = errorInfo.stack; - var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling - // `preventDefault()` in window `error` handler. - // We record this information as an expando on the error. - - if (error != null && error._suppressLogging) { - if (boundary.tag === ClassComponent) { - // The error is recoverable and was silenced. - // Ignore it and don't print the stack addendum. - // This is handy for testing error boundaries without noise. - return; - } // The error is fatal. Since the silencing might have - // been accidental, we'll surface it anyway. - // However, the browser would have silenced the original error - // so we'll print it first, and then print the stack addendum. - - - console['error'](error); // Don't transform to our wrapper - // For a more detailed description of this block, see: - // https://github.com/facebook/react/pull/13384 - } - - var componentName = source ? getComponentNameFromFiber(source) : null; - var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:'; - var errorBoundaryMessage; - - if (boundary.tag === HostRoot) { - errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.'; - } else { - var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous'; - errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + "."); - } - - var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. - // We don't include the original error message and JS stack because the browser - // has already printed it. Even if the application swallows the error, it is still - // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. - - console['error'](combinedMessage); // Don't transform to our wrapper - } - } catch (e) { - // This method must not throw, or React internal state will get messed up. - // If console.error is overridden, or logCapturedError() shows a dialog that throws, - // we want to report this error outside of the normal stack as a last resort. - // https://github.com/facebook/react/issues/13188 - setTimeout(function () { - throw e; - }); - } - } - - var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map; - - function createRootErrorUpdate(fiber, errorInfo, lane) { - var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null. - - update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property - // being called "element". - - update.payload = { - element: null - }; - var error = errorInfo.value; - - update.callback = function () { - onUncaughtError(error); - logCapturedError(fiber, errorInfo); - }; - - return update; - } - - function createClassErrorUpdate(fiber, errorInfo, lane) { - var update = createUpdate(NoTimestamp, lane); - update.tag = CaptureUpdate; - var getDerivedStateFromError = fiber.type.getDerivedStateFromError; - - if (typeof getDerivedStateFromError === 'function') { - var error$1 = errorInfo.value; - - update.payload = function () { - return getDerivedStateFromError(error$1); - }; - - update.callback = function () { - { - markFailedErrorBoundaryForHotReloading(fiber); - } - - logCapturedError(fiber, errorInfo); - }; - } - - var inst = fiber.stateNode; - - if (inst !== null && typeof inst.componentDidCatch === 'function') { - update.callback = function callback() { - { - markFailedErrorBoundaryForHotReloading(fiber); - } - - logCapturedError(fiber, errorInfo); - - if (typeof getDerivedStateFromError !== 'function') { - // To preserve the preexisting retry behavior of error boundaries, - // we keep track of which ones already failed during this batch. - // This gets reset before we yield back to the browser. - // TODO: Warn in strict mode if getDerivedStateFromError is - // not defined. - markLegacyErrorBoundaryAsFailed(this); - } - - var error$1 = errorInfo.value; - var stack = errorInfo.stack; - this.componentDidCatch(error$1, { - componentStack: stack !== null ? stack : '' - }); - - { - if (typeof getDerivedStateFromError !== 'function') { - // If componentDidCatch is the only error boundary method defined, - // then it needs to call setState to recover from errors. - // If no state update is scheduled then the boundary will swallow the error. - if (!includesSomeLane(fiber.lanes, SyncLane)) { - error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown'); - } - } - } - }; - } - - return update; - } - - function attachPingListener(root, wakeable, lanes) { - // Attach a ping listener - // - // The data might resolve before we have a chance to commit the fallback. Or, - // in the case of a refresh, we'll never commit a fallback. So we need to - // attach a listener now. When it resolves ("pings"), we can decide whether to - // try rendering the tree again. - // - // Only attach a listener if one does not already exist for the lanes - // we're currently rendering (which acts like a "thread ID" here). - // - // We only need to do this in concurrent mode. Legacy Suspense always - // commits fallbacks synchronously, so there are no pings. - var pingCache = root.pingCache; - var threadIDs; - - if (pingCache === null) { - pingCache = root.pingCache = new PossiblyWeakMap$1(); - threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } else { - threadIDs = pingCache.get(wakeable); - - if (threadIDs === undefined) { - threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } - } - - if (!threadIDs.has(lanes)) { - // Memoize using the thread ID to prevent redundant listeners. - threadIDs.add(lanes); - var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes); - - { - if (isDevToolsPresent) { - // If we have pending work still, restore the original updaters - restorePendingUpdaters(root, lanes); - } - } - - wakeable.then(ping, ping); - } - } - - function attachRetryListener(suspenseBoundary, root, wakeable, lanes) { - // Retry listener - // - // If the fallback does commit, we need to attach a different type of - // listener. This one schedules an update on the Suspense boundary to turn - // the fallback state off. - // - // Stash the wakeable on the boundary fiber so we can access it in the - // commit phase. - // - // When the wakeable resolves, we'll attempt to render the boundary - // again ("retry"). - var wakeables = suspenseBoundary.updateQueue; - - if (wakeables === null) { - var updateQueue = new Set(); - updateQueue.add(wakeable); - suspenseBoundary.updateQueue = updateQueue; - } else { - wakeables.add(wakeable); - } - } - - function resetSuspendedComponent(sourceFiber, rootRenderLanes) { - // A legacy mode Suspense quirk, only relevant to hook components. - - - var tag = sourceFiber.tag; - - if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) { - var currentSource = sourceFiber.alternate; - - if (currentSource) { - sourceFiber.updateQueue = currentSource.updateQueue; - sourceFiber.memoizedState = currentSource.memoizedState; - sourceFiber.lanes = currentSource.lanes; - } else { - sourceFiber.updateQueue = null; - sourceFiber.memoizedState = null; - } - } - } - - function getNearestSuspenseBoundaryToCapture(returnFiber) { - var node = returnFiber; - - do { - if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) { - return node; - } // This boundary already captured during this render. Continue to the next - // boundary. - - - node = node.return; - } while (node !== null); - - return null; - } - - function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) { - // This marks a Suspense boundary so that when we're unwinding the stack, - // it captures the suspended "exception" and does a second (fallback) pass. - if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { - // Legacy Mode Suspense - // - // If the boundary is in legacy mode, we should *not* - // suspend the commit. Pretend as if the suspended component rendered - // null and keep rendering. When the Suspense boundary completes, - // we'll do a second pass to render the fallback. - if (suspenseBoundary === returnFiber) { - // Special case where we suspended while reconciling the children of - // a Suspense boundary's inner Offscreen wrapper fiber. This happens - // when a React.lazy component is a direct child of a - // Suspense boundary. - // - // Suspense boundaries are implemented as multiple fibers, but they - // are a single conceptual unit. The legacy mode behavior where we - // pretend the suspended fiber committed as `null` won't work, - // because in this case the "suspended" fiber is the inner - // Offscreen wrapper. - // - // Because the contents of the boundary haven't started rendering - // yet (i.e. nothing in the tree has partially rendered) we can - // switch to the regular, concurrent mode behavior: mark the - // boundary with ShouldCapture and enter the unwind phase. - suspenseBoundary.flags |= ShouldCapture; - } else { - suspenseBoundary.flags |= DidCapture; - sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete. - // But we shouldn't call any lifecycle methods or callbacks. Remove - // all lifecycle effect tags. - - sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); - - if (supportsPersistence && enablePersistentOffscreenHostContainer) { - // Another legacy Suspense quirk. In persistent mode, if this is the - // initial mount, override the props of the host container to hide - // its contents. - var currentSuspenseBoundary = suspenseBoundary.alternate; - - if (currentSuspenseBoundary === null) { - var offscreenFiber = suspenseBoundary.child; - var offscreenContainer = offscreenFiber.child; - - if (offscreenContainer !== null) { - var children = offscreenContainer.memoizedProps.children; - var containerProps = getOffscreenContainerProps('hidden', children); - offscreenContainer.pendingProps = containerProps; - offscreenContainer.memoizedProps = containerProps; - } - } - } - - if (sourceFiber.tag === ClassComponent) { - var currentSourceFiber = sourceFiber.alternate; - - if (currentSourceFiber === null) { - // This is a new mount. Change the tag so it's not mistaken for a - // completed class component. For example, we should not call - // componentWillUnmount if it is deleted. - sourceFiber.tag = IncompleteClassComponent; - } else { - // When we try rendering again, we should not reuse the current fiber, - // since it's known to be in an inconsistent state. Use a force update to - // prevent a bail out. - var update = createUpdate(NoTimestamp, SyncLane); - update.tag = ForceUpdate; - enqueueUpdate(sourceFiber, update); - } - } // The source fiber did not complete. Mark it with Sync priority to - // indicate that it still has pending work. - - - sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); - } - - return suspenseBoundary; - } // Confirmed that the boundary is in a concurrent mode tree. Continue - // with the normal suspend path. - // - // After this we'll use a set of heuristics to determine whether this - // render pass will run to completion or restart or "suspend" the commit. - // The actual logic for this is spread out in different places. - // - // This first principle is that if we're going to suspend when we complete - // a root, then we should also restart if we get an update or ping that - // might unsuspend it, and vice versa. The only reason to suspend is - // because you think you might want to restart before committing. However, - // it doesn't make sense to restart only while in the period we're suspended. - // - // Restarting too aggressively is also not good because it starves out any - // intermediate loading state. So we use heuristics to determine when. - // Suspense Heuristics - // - // If nothing threw a Promise or all the same fallbacks are already showing, - // then don't suspend/restart. - // - // If this is an initial render of a new tree of Suspense boundaries and - // those trigger a fallback, then don't suspend/restart. We want to ensure - // that we can show the initial loading state as quickly as possible. - // - // If we hit a "Delayed" case, such as when we'd switch from content back into - // a fallback, then we should always suspend/restart. Transitions apply - // to this case. If none is defined, JND is used instead. - // - // If we're already showing a fallback and it gets "retried", allowing us to show - // another level, but there's still an inner boundary that would show a fallback, - // then we suspend/restart for 500ms since the last time we showed a fallback - // anywhere in the tree. This effectively throttles progressive loading into a - // consistent train of commits. This also gives us an opportunity to restart to - // get to the completed state slightly earlier. - // - // If there's ambiguity due to batching it's resolved in preference of: - // 1) "delayed", 2) "initial render", 3) "retry". - // - // We want to ensure that a "busy" state doesn't get force committed. We want to - // ensure that new initial loading states can commit as soon as possible. - - - suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in - // the begin phase to prevent an early bailout. - - suspenseBoundary.lanes = rootRenderLanes; - return suspenseBoundary; - } - - function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) { - // The source fiber did not complete. - sourceFiber.flags |= Incomplete; - - { - if (isDevToolsPresent) { - // If we have pending work still, restore the original updaters - restorePendingUpdaters(root, rootRenderLanes); - } - } - - if (value !== null && typeof value === 'object' && typeof value.then === 'function') { - // This is a wakeable. The component suspended. - var wakeable = value; - resetSuspendedComponent(sourceFiber); - - - var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); - - if (suspenseBoundary !== null) { - suspenseBoundary.flags &= ~ForceClientRender; - markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always - // commits fallbacks synchronously, so there are no pings. - - if (suspenseBoundary.mode & ConcurrentMode) { - attachPingListener(root, wakeable, rootRenderLanes); - } - - attachRetryListener(suspenseBoundary, root, wakeable); - return; - } else { - // No boundary was found. Unless this is a sync update, this is OK. - // We can suspend and wait for more data to arrive. - if (!includesSyncLane(rootRenderLanes)) { - // This is not a sync update. Suspend. Since we're not activating a - // Suspense boundary, this will unwind all the way to the root without - // performing a second pass to render a fallback. (This is arguably how - // refresh transitions should work, too, since we're not going to commit - // the fallbacks anyway.) - // - // This case also applies to initial hydration. - attachPingListener(root, wakeable, rootRenderLanes); - renderDidSuspendDelayIfPossible(); - return; - } // This is a sync/discrete update. We treat this case like an error - // because discrete renders are expected to produce a complete tree - // synchronously to maintain consistency with external state. - - - var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path. - // The error will be caught by the nearest suspense boundary. - - value = uncaughtSuspenseError; - } - } else { - // This is a regular error, not a Suspense wakeable. - if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { - markDidSuspendWhileHydratingDEV(); - - var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by - // discarding the dehydrated content and switching to a client render. - // Instead of surfacing the error, find the nearest Suspense boundary - // and render it again without hydration. - - - if (_suspenseBoundary !== null) { - if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) { - // Set a flag to indicate that we should try rendering the normal - // children again, not the fallback. - _suspenseBoundary.flags |= ForceClientRender; - } - - markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should - // still log it so it can be fixed. - - queueHydrationError(value); - return; - } - } - } // We didn't find a boundary that could handle this type of exception. Start - // over and traverse parent path again, this time treating the exception - // as an error. - - - renderDidError(value); - value = createCapturedValue(value, sourceFiber); - var workInProgress = returnFiber; - - do { - switch (workInProgress.tag) { - case HostRoot: - { - var _errorInfo = value; - workInProgress.flags |= ShouldCapture; - var lane = pickArbitraryLane(rootRenderLanes); - workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); - var update = createRootErrorUpdate(workInProgress, _errorInfo, lane); - enqueueCapturedUpdate(workInProgress, update); - return; - } - - case ClassComponent: - // Capture and retry - var errorInfo = value; - var ctor = workInProgress.type; - var instance = workInProgress.stateNode; - - if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) { - workInProgress.flags |= ShouldCapture; - - var _lane = pickArbitraryLane(rootRenderLanes); - - workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state - - var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane); - - enqueueCapturedUpdate(workInProgress, _update); - return; - } - - break; - } - - workInProgress = workInProgress.return; - } while (workInProgress !== null); - } - - function getSuspendedCache() { - { - return null; - } // This function is called when a Suspense boundary suspends. It returns the - } - - function markUpdate(workInProgress) { - // Tag the fiber with an update effect. This turns a Placement into - // a PlacementAndUpdate. - workInProgress.flags |= Update; - } - - function markRef(workInProgress) { - workInProgress.flags |= Ref; - - { - workInProgress.flags |= RefStatic; - } - } - - function hadNoMutationsEffects(current, completedWork) { - var didBailout = current !== null && current.child === completedWork.child; - - if (didBailout) { - return true; - } - - if ((completedWork.flags & ChildDeletion) !== NoFlags) { - return false; - } // TODO: If we move the `hadNoMutationsEffects` call after `bubbleProperties` - // then we only have to check the `completedWork.subtreeFlags`. - - - var child = completedWork.child; - - while (child !== null) { - if ((child.flags & MutationMask) !== NoFlags || (child.subtreeFlags & MutationMask) !== NoFlags) { - return false; - } - - child = child.sibling; - } - - return true; - } - - var appendAllChildren; - var updateHostContainer; - var updateHostComponent; - var updateHostText; - - if (supportsMutation) { - // Mutation mode - appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - var node = workInProgress.child; - - while (node !== null) { - if (node.tag === HostComponent || node.tag === HostText) { - appendInitialChild(parent, node.stateNode); - } else if (node.tag === HostPortal) ; else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === workInProgress) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - }; - - updateHostContainer = function (current, workInProgress) {// Noop - }; - - updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) { - // If we have an alternate, that means this is an update and we need to - // schedule a side-effect to do the updates. - var oldProps = current.memoizedProps; - - if (oldProps === newProps) { - // In mutation mode, this is sufficient for a bailout because - // we won't touch this node even if children changed. - return; - } // If we get updated because one of our children updated, we don't - // have newProps so we'll have to reuse them. - // TODO: Split the update API as separate for the props vs. children. - // Even better would be if children weren't special cased at all tho. - - - var instance = workInProgress.stateNode; - var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host - // component is hitting the resume path. Figure out why. Possibly - // related to `hidden`. - - var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component. - - workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there - // is a new ref we mark this as an update. All the work is done in commitWork. - - if (updatePayload) { - markUpdate(workInProgress); - } - }; - - updateHostText = function (current, workInProgress, oldText, newText) { - // If the text differs, mark it as an update. All the work in done in commitWork. - if (oldText !== newText) { - markUpdate(workInProgress); - } - }; - } else if (supportsPersistence) { - // Persistent host tree mode - appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - var node = workInProgress.child; - - while (node !== null) { - // eslint-disable-next-line no-labels - if (node.tag === HostComponent) { - var instance = node.stateNode; - - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - var props = node.memoizedProps; - var type = node.type; - instance = cloneHiddenInstance(instance, type, props, node); - } - - appendInitialChild(parent, instance); - } else if (node.tag === HostText) { - var _instance = node.stateNode; - - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - var text = node.memoizedProps; - _instance = cloneHiddenTextInstance(_instance, text, node); - } - - appendInitialChild(parent, _instance); - } else if (node.tag === HostPortal) ; else if (node.tag === OffscreenComponent && node.memoizedState !== null) { - // The children in this boundary are hidden. Toggle their visibility - // before appending. - var child = node.child; - - if (child !== null) { - child.return = node; - } - - { - appendAllChildren(parent, node, true, true); - } - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } // $FlowFixMe This is correct but Flow is confused by the labeled break. - - - node = node; - - if (node === workInProgress) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - }; // An unfortunate fork of appendAllChildren because we have two different parent types. - - - var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - var node = workInProgress.child; - - while (node !== null) { - // eslint-disable-next-line no-labels - if (node.tag === HostComponent) { - var instance = node.stateNode; - - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - var props = node.memoizedProps; - var type = node.type; - instance = cloneHiddenInstance(instance, type, props, node); - } - - appendChildToContainerChildSet(containerChildSet, instance); - } else if (node.tag === HostText) { - var _instance2 = node.stateNode; - - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - var text = node.memoizedProps; - _instance2 = cloneHiddenTextInstance(_instance2, text, node); - } - - appendChildToContainerChildSet(containerChildSet, _instance2); - } else if (node.tag === HostPortal) ; else if (node.tag === OffscreenComponent && node.memoizedState !== null) { - // The children in this boundary are hidden. Toggle their visibility - // before appending. - var child = node.child; - - if (child !== null) { - child.return = node; - } - - { - appendAllChildrenToContainer(containerChildSet, node, true, true); - } - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } // $FlowFixMe This is correct but Flow is confused by the labeled break. - - - node = node; - - if (node === workInProgress) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - }; - - updateHostContainer = function (current, workInProgress) { - var portalOrRoot = workInProgress.stateNode; - var childrenUnchanged = hadNoMutationsEffects(current, workInProgress); - - if (childrenUnchanged) ; else { - var container = portalOrRoot.containerInfo; - var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set. - - appendAllChildrenToContainer(newChildSet, workInProgress, false, false); - portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container. - - markUpdate(workInProgress); - finalizeContainerChildren(container, newChildSet); - } - }; - - updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) { - var currentInstance = current.stateNode; - var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates. - // This guarantees that we can reuse all of them. - - var childrenUnchanged = hadNoMutationsEffects(current, workInProgress); - - if (childrenUnchanged && oldProps === newProps) { - // No changes, just reuse the existing instance. - // Note that this might release a previous clone. - workInProgress.stateNode = currentInstance; - return; - } - - var recyclableInstance = workInProgress.stateNode; - var currentHostContext = getHostContext(); - var updatePayload = null; - - if (oldProps !== newProps) { - updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext); - } - - if (childrenUnchanged && updatePayload === null) { - // No changes, just reuse the existing instance. - // Note that this might release a previous clone. - workInProgress.stateNode = currentInstance; - return; - } - - var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance); - - if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) { - markUpdate(workInProgress); - } - - workInProgress.stateNode = newInstance; - - if (childrenUnchanged) { - // If there are no other effects in this tree, we need to flag this node as having one. - // Even though we're not going to use it for anything. - // Otherwise parents won't know that there are new children to propagate upwards. - markUpdate(workInProgress); - } else { - // If children might have changed, we have to add them all to the set. - appendAllChildren(newInstance, workInProgress, false, false); - } - }; - - updateHostText = function (current, workInProgress, oldText, newText) { - if (oldText !== newText) { - // If the text content differs, we'll create a new text instance for it. - var rootContainerInstance = getRootHostContainer(); - var currentHostContext = getHostContext(); - workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress); // We'll have to mark it as having an effect, even though we won't use the effect for anything. - // This lets the parents know that at least one of their children has changed. - - markUpdate(workInProgress); - } else { - workInProgress.stateNode = current.stateNode; - } - }; - } else { - // No host operations - updateHostContainer = function (current, workInProgress) {// Noop - }; - - updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) {// Noop - }; - - updateHostText = function (current, workInProgress, oldText, newText) {// Noop - }; - } - - function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { - if (getIsHydrating()) { - // If we're hydrating, we should consume as many items as we can - // so we don't leave any behind. - return; - } - - switch (renderState.tailMode) { - case 'hidden': - { - // Any insertions at the end of the tail list after this point - // should be invisible. If there are already mounted boundaries - // anything before them are not considered for collapsing. - // Therefore we need to go through the whole tail to find if - // there are any. - var tailNode = renderState.tail; - var lastTailNode = null; - - while (tailNode !== null) { - if (tailNode.alternate !== null) { - lastTailNode = tailNode; - } - - tailNode = tailNode.sibling; - } // Next we're simply going to delete all insertions after the - // last rendered item. - - - if (lastTailNode === null) { - // All remaining items in the tail are insertions. - renderState.tail = null; - } else { - // Detach the insertion after the last node that was already - // inserted. - lastTailNode.sibling = null; - } - - break; - } - - case 'collapsed': - { - // Any insertions at the end of the tail list after this point - // should be invisible. If there are already mounted boundaries - // anything before them are not considered for collapsing. - // Therefore we need to go through the whole tail to find if - // there are any. - var _tailNode = renderState.tail; - var _lastTailNode = null; - - while (_tailNode !== null) { - if (_tailNode.alternate !== null) { - _lastTailNode = _tailNode; - } - - _tailNode = _tailNode.sibling; - } // Next we're simply going to delete all insertions after the - // last rendered item. - - - if (_lastTailNode === null) { - // All remaining items in the tail are insertions. - if (!hasRenderedATailFallback && renderState.tail !== null) { - // We suspended during the head. We want to show at least one - // row at the tail. So we'll keep on and cut off the rest. - renderState.tail.sibling = null; - } else { - renderState.tail = null; - } - } else { - // Detach the insertion after the last node that was already - // inserted. - _lastTailNode.sibling = null; - } - - break; - } - } - } - - function bubbleProperties(completedWork) { - var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child; - var newChildLanes = NoLanes; - var subtreeFlags = NoFlags; - - if (!didBailout) { - // Bubble up the earliest expiration time. - if ( (completedWork.mode & ProfileMode) !== NoMode) { - // In profiling mode, resetChildExpirationTime is also used to reset - // profiler durations. - var actualDuration = completedWork.actualDuration; - var treeBaseDuration = completedWork.selfBaseDuration; - var child = completedWork.child; - - while (child !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes)); - subtreeFlags |= child.subtreeFlags; - subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will - // only be updated if work is done on the fiber (i.e. it doesn't bailout). - // When work is done, it should bubble to the parent's actualDuration. If - // the fiber has not been cloned though, (meaning no work was done), then - // this value will reflect the amount of time spent working on a previous - // render. In that case it should not bubble. We determine whether it was - // cloned by comparing the child pointer. - - actualDuration += child.actualDuration; - treeBaseDuration += child.treeBaseDuration; - child = child.sibling; - } - - completedWork.actualDuration = actualDuration; - completedWork.treeBaseDuration = treeBaseDuration; - } else { - var _child = completedWork.child; - - while (_child !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes)); - subtreeFlags |= _child.subtreeFlags; - subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code - // smell because it assumes the commit phase is never concurrent with - // the render phase. Will address during refactor to alternate model. - - _child.return = completedWork; - _child = _child.sibling; - } - } - - completedWork.subtreeFlags |= subtreeFlags; - } else { - // Bubble up the earliest expiration time. - if ( (completedWork.mode & ProfileMode) !== NoMode) { - // In profiling mode, resetChildExpirationTime is also used to reset - // profiler durations. - var _treeBaseDuration = completedWork.selfBaseDuration; - var _child2 = completedWork.child; - - while (_child2 !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, - // so we should bubble those up even during a bailout. All the other - // flags have a lifetime only of a single render + commit, so we should - // ignore them. - - subtreeFlags |= _child2.subtreeFlags & StaticMask; - subtreeFlags |= _child2.flags & StaticMask; - _treeBaseDuration += _child2.treeBaseDuration; - _child2 = _child2.sibling; - } - - completedWork.treeBaseDuration = _treeBaseDuration; - } else { - var _child3 = completedWork.child; - - while (_child3 !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, - // so we should bubble those up even during a bailout. All the other - // flags have a lifetime only of a single render + commit, so we should - // ignore them. - - subtreeFlags |= _child3.subtreeFlags & StaticMask; - subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code - // smell because it assumes the commit phase is never concurrent with - // the render phase. Will address during refactor to alternate model. - - _child3.return = completedWork; - _child3 = _child3.sibling; - } - } - - completedWork.subtreeFlags |= subtreeFlags; - } - - completedWork.childLanes = newChildLanes; - return didBailout; - } - - function completeWork(current, workInProgress, renderLanes) { - var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing - // to the current tree provider fiber is just as fast and less error-prone. - // Ideally we would have a special version of the work loop only - // for hydration. - - popTreeContext(workInProgress); - - switch (workInProgress.tag) { - case IndeterminateComponent: - case LazyComponent: - case SimpleMemoComponent: - case FunctionComponent: - case ForwardRef: - case Fragment: - case Mode: - case Profiler: - case ContextConsumer: - case MemoComponent: - bubbleProperties(workInProgress); - return null; - - case ClassComponent: - { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - popContext(workInProgress); - } - - bubbleProperties(workInProgress); - return null; - } - - case HostRoot: - { - var fiberRoot = workInProgress.stateNode; - - popHostContainer(workInProgress); - popTopLevelContextObject(workInProgress); - resetWorkInProgressVersions(); - - if (fiberRoot.pendingContext) { - fiberRoot.context = fiberRoot.pendingContext; - fiberRoot.pendingContext = null; - } - - if (current === null || current.child === null) { - // If we hydrated, pop so that we can delete any remaining children - // that weren't hydrated. - var wasHydrated = popHydrationState(workInProgress); - - if (wasHydrated) { - // If we hydrated, then we'll need to schedule an update for - // the commit side-effects on the root. - markUpdate(workInProgress); - } else { - if (current !== null) { - var prevState = current.memoizedState; - - if ( // Check if this is a client root - !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error) - (workInProgress.flags & ForceClientRender) !== NoFlags) { - // Schedule an effect to clear this container at the start of the - // next commit. This handles the case of React rendering into a - // container with previous children. It's also safe to do for - // updates too, because current.child would only be null if the - // previous render was null (so the container would already - // be empty). - workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been - // recoverable errors during first hydration attempt. If so, add - // them to a queue so we can log them in the commit phase. - - upgradeHydrationErrorsToRecoverable(); - } - } - } - } - - updateHostContainer(current, workInProgress); - bubbleProperties(workInProgress); - return null; - } - - case HostComponent: - { - popHostContext(workInProgress); - var rootContainerInstance = getRootHostContainer(); - var type = workInProgress.type; - - if (current !== null && workInProgress.stateNode != null) { - updateHostComponent(current, workInProgress, type, newProps, rootContainerInstance); - - if (current.ref !== workInProgress.ref) { - markRef(workInProgress); - } - } else { - if (!newProps) { - if (workInProgress.stateNode === null) { - throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); - } // This can happen when we abort work. - - - bubbleProperties(workInProgress); - return null; - } - - var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context - // "stack" as the parent. Then append children as we go in beginWork - // or completeWork depending on whether we want to add them top->down or - // bottom->up. Top->down is faster in IE11. - - var _wasHydrated = popHydrationState(workInProgress); - - if (_wasHydrated) { - // TODO: Move this and createInstance step into the beginPhase - // to consolidate. - if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) { - // If changes to the hydrated node need to be applied at the - // commit-phase we mark this as such. - markUpdate(workInProgress); - } - } else { - var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress); - appendAllChildren(instance, workInProgress, false, false); - workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount. - // (eg DOM renderer supports auto-focus for certain elements). - // Make sure such renderers get scheduled for later work. - - if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) { - markUpdate(workInProgress); - } - } - - if (workInProgress.ref !== null) { - // If there is a ref on a host node we need to schedule a callback - markRef(workInProgress); - } - } - - bubbleProperties(workInProgress); - return null; - } - - case HostText: - { - var newText = newProps; - - if (current && workInProgress.stateNode != null) { - var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need - // to schedule a side-effect to do the updates. - - updateHostText(current, workInProgress, oldText, newText); - } else { - if (typeof newText !== 'string') { - if (workInProgress.stateNode === null) { - throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); - } // This can happen when we abort work. - - } - - var _rootContainerInstance = getRootHostContainer(); - - var _currentHostContext = getHostContext(); - - var _wasHydrated2 = popHydrationState(workInProgress); - - if (_wasHydrated2) { - if (prepareToHydrateHostTextInstance(workInProgress)) { - markUpdate(workInProgress); - } - } else { - workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress); - } - } - - bubbleProperties(workInProgress); - return null; - } - - case SuspenseComponent: - { - popSuspenseContext(workInProgress); - var nextState = workInProgress.memoizedState; - - { - if ( hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) { - warnIfUnhydratedTailNodes(workInProgress); - resetHydrationState(); - workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture; - return workInProgress; - } - - if (nextState !== null && nextState.dehydrated !== null) { - // We might be inside a hydration state the first time we're picking up this - // Suspense boundary, and also after we've reentered it for further hydration. - var _wasHydrated3 = popHydrationState(workInProgress); - - if (current === null) { - if (!_wasHydrated3) { - throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.'); - } - - prepareToHydrateHostSuspenseInstance(workInProgress); - bubbleProperties(workInProgress); - - { - if ((workInProgress.mode & ProfileMode) !== NoMode) { - var isTimedOutSuspense = nextState !== null; - - if (isTimedOutSuspense) { - // Don't count time spent in a timed out Suspense subtree as part of the base duration. - var primaryChildFragment = workInProgress.child; - - if (primaryChildFragment !== null) { - // $FlowFixMe Flow doesn't support type casting in combination with the -= operator - workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration; - } - } - } - } - - return null; - } else { - // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration - // state since we're now exiting out of it. popHydrationState doesn't do that for us. - resetHydrationState(); - - if ((workInProgress.flags & DidCapture) === NoFlags) { - // This boundary did not suspend so it's now hydrated and unsuspended. - workInProgress.memoizedState = null; - } // If nothing suspended, we need to schedule an effect to mark this boundary - // as having hydrated so events know that they're free to be invoked. - // It's also a signal to replay events and the suspense callback. - // If something suspended, schedule an effect to attach retry listeners. - // So we might as well always mark this. - - - workInProgress.flags |= Update; - bubbleProperties(workInProgress); - - { - if ((workInProgress.mode & ProfileMode) !== NoMode) { - var _isTimedOutSuspense = nextState !== null; - - if (_isTimedOutSuspense) { - // Don't count time spent in a timed out Suspense subtree as part of the base duration. - var _primaryChildFragment = workInProgress.child; - - if (_primaryChildFragment !== null) { - // $FlowFixMe Flow doesn't support type casting in combination with the -= operator - workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration; - } - } - } - } - - return null; - } - } // Successfully completed this tree. If this was a forced client render, - // there may have been recoverable errors during first hydration - // attempt. If so, add them to a queue so we can log them in the - // commit phase. - - - upgradeHydrationErrorsToRecoverable(); - } - - if ((workInProgress.flags & DidCapture) !== NoFlags) { - // Something suspended. Re-render with the fallback children. - workInProgress.lanes = renderLanes; // Do not reset the effect list. - - if ( (workInProgress.mode & ProfileMode) !== NoMode) { - transferActualDuration(workInProgress); - } // Don't bubble properties in this case. - - - return workInProgress; - } - - var nextDidTimeout = nextState !== null; - var prevDidTimeout = false; - - if (current === null) { - popHydrationState(workInProgress); - } else { - var _prevState = current.memoizedState; - prevDidTimeout = _prevState !== null; - } - // an effect to toggle the subtree's visibility. When we switch from - // fallback -> primary, the inner Offscreen fiber schedules this effect - // as part of its normal complete phase. But when we switch from - // primary -> fallback, the inner Offscreen fiber does not have a complete - // phase. So we need to schedule its effect here. - // - // We also use this flag to connect/disconnect the effects, but the same - // logic applies: when re-connecting, the Offscreen fiber's complete - // phase will handle scheduling the effect. It's only when the fallback - // is active that we have to do anything special. - - - if (nextDidTimeout && !prevDidTimeout) { - var _offscreenFiber = workInProgress.child; - _offscreenFiber.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything - // in the concurrent tree already suspended during this render. - // This is a known bug. - - if ((workInProgress.mode & ConcurrentMode) !== NoMode) { - // TODO: Move this back to throwException because this is too late - // if this is a large tree which is common for initial loads. We - // don't know if we should restart a render or not until we get - // this marker, and this is too late. - // If this render already had a ping or lower pri updates, - // and this is the first time we know we're going to suspend we - // should be able to immediately restart from within throwException. - var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback); - - if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) { - // If this was in an invisible tree or a new render, then showing - // this boundary is ok. - renderDidSuspend(); - } else { - // Otherwise, we're going to have to hide content so we should - // suspend for longer if possible. - renderDidSuspendDelayIfPossible(); - } - } - } - - var wakeables = workInProgress.updateQueue; - - if (wakeables !== null) { - // Schedule an effect to attach a retry listener to the promise. - // TODO: Move to passive phase - workInProgress.flags |= Update; - } - - bubbleProperties(workInProgress); - - { - if ((workInProgress.mode & ProfileMode) !== NoMode) { - if (nextDidTimeout) { - // Don't count time spent in a timed out Suspense subtree as part of the base duration. - var _primaryChildFragment2 = workInProgress.child; - - if (_primaryChildFragment2 !== null) { - // $FlowFixMe Flow doesn't support type casting in combination with the -= operator - workInProgress.treeBaseDuration -= _primaryChildFragment2.treeBaseDuration; - } - } - } - } - - return null; - } - - case HostPortal: - popHostContainer(workInProgress); - updateHostContainer(current, workInProgress); - - if (current === null) { - preparePortalMount(workInProgress.stateNode.containerInfo); - } - - bubbleProperties(workInProgress); - return null; - - case ContextProvider: - // Pop provider fiber - var context = workInProgress.type._context; - popProvider(context, workInProgress); - bubbleProperties(workInProgress); - return null; - - case IncompleteClassComponent: - { - // Same as class component case. I put it down here so that the tags are - // sequential to ensure this switch is compiled to a jump table. - var _Component = workInProgress.type; - - if (isContextProvider(_Component)) { - popContext(workInProgress); - } - - bubbleProperties(workInProgress); - return null; - } - - case SuspenseListComponent: - { - popSuspenseContext(workInProgress); - var renderState = workInProgress.memoizedState; - - if (renderState === null) { - // We're running in the default, "independent" mode. - // We don't do anything in this mode. - bubbleProperties(workInProgress); - return null; - } - - var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags; - var renderedTail = renderState.rendering; - - if (renderedTail === null) { - // We just rendered the head. - if (!didSuspendAlready) { - // This is the first pass. We need to figure out if anything is still - // suspended in the rendered set. - // If new content unsuspended, but there's still some content that - // didn't. Then we need to do a second pass that forces everything - // to keep showing their fallbacks. - // We might be suspended if something in this render pass suspended, or - // something in the previous committed pass suspended. Otherwise, - // there's no chance so we can skip the expensive call to - // findFirstSuspended. - var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags); - - if (!cannotBeSuspended) { - var row = workInProgress.child; - - while (row !== null) { - var suspended = findFirstSuspended(row); - - if (suspended !== null) { - didSuspendAlready = true; - workInProgress.flags |= DidCapture; - cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as - // part of the second pass. In that case nothing will subscribe to - // its thenables. Instead, we'll transfer its thenables to the - // SuspenseList so that it can retry if they resolve. - // There might be multiple of these in the list but since we're - // going to wait for all of them anyway, it doesn't really matter - // which ones gets to ping. In theory we could get clever and keep - // track of how many dependencies remain but it gets tricky because - // in the meantime, we can add/remove/change items and dependencies. - // We might bail out of the loop before finding any but that - // doesn't matter since that means that the other boundaries that - // we did find already has their listeners attached. - - var newThenables = suspended.updateQueue; - - if (newThenables !== null) { - workInProgress.updateQueue = newThenables; - workInProgress.flags |= Update; - } // Rerender the whole list, but this time, we'll force fallbacks - // to stay in place. - // Reset the effect flags before doing the second pass since that's now invalid. - // Reset the child fibers to their original state. - - - workInProgress.subtreeFlags = NoFlags; - resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately - // rerender the children. - - pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case. - - return workInProgress.child; - } - - row = row.sibling; - } - } - - if (renderState.tail !== null && now$1() > getRenderTargetTime()) { - // We have already passed our CPU deadline but we still have rows - // left in the tail. We'll just give up further attempts to render - // the main content and only render fallbacks. - workInProgress.flags |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this - // to get it started back up to attempt the next item. While in terms - // of priority this work has the same priority as this current render, - // it's not part of the same transition once the transition has - // committed. If it's sync, we still want to yield so that it can be - // painted. Conceptually, this is really the same as pinging. - // We can use any RetryLane even if it's the one currently rendering - // since we're leaving it behind on this node. - - workInProgress.lanes = SomeRetryLane; - } - } else { - cutOffTailIfNeeded(renderState, false); - } // Next we're going to render the tail. - - } else { - // Append the rendered row to the child list. - if (!didSuspendAlready) { - var _suspended = findFirstSuspended(renderedTail); - - if (_suspended !== null) { - workInProgress.flags |= DidCapture; - didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't - // get lost if this row ends up dropped during a second pass. - - var _newThenables = _suspended.updateQueue; - - if (_newThenables !== null) { - workInProgress.updateQueue = _newThenables; - workInProgress.flags |= Update; - } - - cutOffTailIfNeeded(renderState, true); // This might have been modified. - - if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating. - ) { - // We're done. - bubbleProperties(workInProgress); - return null; - } - } else if ( // The time it took to render last row is greater than the remaining - // time we have to render. So rendering one more row would likely - // exceed it. - now$1() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) { - // We have now passed our CPU deadline and we'll just give up further - // attempts to render the main content and only render fallbacks. - // The assumption is that this is usually faster. - workInProgress.flags |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this - // to get it started back up to attempt the next item. While in terms - // of priority this work has the same priority as this current render, - // it's not part of the same transition once the transition has - // committed. If it's sync, we still want to yield so that it can be - // painted. Conceptually, this is really the same as pinging. - // We can use any RetryLane even if it's the one currently rendering - // since we're leaving it behind on this node. - - workInProgress.lanes = SomeRetryLane; - } - } - - if (renderState.isBackwards) { - // The effect list of the backwards tail will have been added - // to the end. This breaks the guarantee that life-cycles fire in - // sibling order but that isn't a strong guarantee promised by React. - // Especially since these might also just pop in during future commits. - // Append to the beginning of the list. - renderedTail.sibling = workInProgress.child; - workInProgress.child = renderedTail; - } else { - var previousSibling = renderState.last; - - if (previousSibling !== null) { - previousSibling.sibling = renderedTail; - } else { - workInProgress.child = renderedTail; - } - - renderState.last = renderedTail; - } - } - - if (renderState.tail !== null) { - // We still have tail rows to render. - // Pop a row. - var next = renderState.tail; - renderState.rendering = next; - renderState.tail = next.sibling; - renderState.renderingStartTime = now$1(); - next.sibling = null; // Restore the context. - // TODO: We can probably just avoid popping it instead and only - // setting it the first time we go from not suspended to suspended. - - var suspenseContext = suspenseStackCursor.current; - - if (didSuspendAlready) { - suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); - } else { - suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - } - - pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. - // Don't bubble properties in this case. - - return next; - } - - bubbleProperties(workInProgress); - return null; - } - - case ScopeComponent: - { - - break; - } - - case OffscreenComponent: - case LegacyHiddenComponent: - { - popRenderLanes(workInProgress); - var _nextState = workInProgress.memoizedState; - var nextIsHidden = _nextState !== null; - - if (current !== null) { - var _prevState2 = current.memoizedState; - var prevIsHidden = _prevState2 !== null; - - if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding — it only pre-renders. - !enableLegacyHidden )) { - workInProgress.flags |= Visibility; - } - } - - if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) { - bubbleProperties(workInProgress); - } else { - // Don't bubble properties for hidden children unless we're rendering - // at offscreen priority. - if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) { - bubbleProperties(workInProgress); - - if (supportsMutation) { - // Check if there was an insertion or update in the hidden subtree. - // If so, we need to hide those nodes in the commit phase, so - // schedule a visibility effect. - if ( workInProgress.subtreeFlags & (Placement | Update)) { - workInProgress.flags |= Visibility; - } - } - } - } - - return null; - } - - case CacheComponent: - { - - return null; - } - - case TracingMarkerComponent: - { - - return null; - } - } - - throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); - } - - var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; - var didReceiveUpdate = false; - var didWarnAboutBadClass; - var didWarnAboutModulePatternComponent; - var didWarnAboutContextTypeOnFunctionComponent; - var didWarnAboutGetDerivedStateOnFunctionComponent; - var didWarnAboutFunctionRefs; - var didWarnAboutReassigningProps; - var didWarnAboutRevealOrder; - var didWarnAboutTailOptions; - - { - didWarnAboutBadClass = {}; - didWarnAboutModulePatternComponent = {}; - didWarnAboutContextTypeOnFunctionComponent = {}; - didWarnAboutGetDerivedStateOnFunctionComponent = {}; - didWarnAboutFunctionRefs = {}; - didWarnAboutReassigningProps = false; - didWarnAboutRevealOrder = {}; - didWarnAboutTailOptions = {}; - } - - function reconcileChildren(current, workInProgress, nextChildren, renderLanes) { - if (current === null) { - // If this is a fresh new component that hasn't been rendered yet, we - // won't update its child set by applying minimal side-effects. Instead, - // we will add them all to the child before it gets rendered. That means - // we can optimize this reconciliation pass by not tracking side-effects. - workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); - } else { - // If the current child is the same as the work in progress, it means that - // we haven't yet started any work on these children. Therefore, we use - // the clone algorithm to create a copy of all the current children. - // If we had any progressed work already, that is invalid at this point so - // let's throw it out. - workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes); - } - } - - function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) { - // This function is fork of reconcileChildren. It's used in cases where we - // want to reconcile without matching against the existing set. This has the - // effect of all current children being unmounted; even if the type and key - // are the same, the old child is unmounted and a new child is created. - // - // To do this, we're going to go through the reconcile algorithm twice. In - // the first pass, we schedule a deletion for all the current children by - // passing null. - workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we - // pass null in place of where we usually pass the current child set. This has - // the effect of remounting all children regardless of whether their - // identities match. - - workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); - } - - function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) { - // TODO: current can be non-null here even if the component - // hasn't yet mounted. This happens after the first render suspends. - // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes(innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(Component)); - } - } - } - - var render = Component.render; - var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent - - var nextChildren; - var hasId; - prepareToReadContext(workInProgress, renderLanes); - - { - markComponentRenderStarted(workInProgress); - } - - { - ReactCurrentOwner$1.current = workInProgress; - setIsRendering(true); - nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); - hasId = checkDidRenderIdHook(); - - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); - hasId = checkDidRenderIdHook(); - } finally { - setIsStrictModeForDevtools(false); - } - } - - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } - - if (current !== null && !didReceiveUpdate) { - bailoutHooks(current, workInProgress, renderLanes); - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { - if (current === null) { - var type = Component.type; - - if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. - Component.defaultProps === undefined) { - var resolvedType = type; - - { - resolvedType = resolveFunctionForHotReloading(type); - } // If this is a plain function component without default props, - // and with only the default shallow comparison, we upgrade it - // to a SimpleMemoComponent to allow fast path updates. - - - workInProgress.tag = SimpleMemoComponent; - workInProgress.type = resolvedType; - - { - validateFunctionComponentInDev(workInProgress, type); - } - - return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes); - } - - { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes(innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(type)); - } - } - - var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes); - child.ref = workInProgress.ref; - child.return = workInProgress; - workInProgress.child = child; - return child; - } - - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes(_innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(_type)); - } - } - - var currentChild = current.child; // This is always exactly one child - - var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); - - if (!hasScheduledUpdateOrContext) { - // This will be the props with resolved defaultProps, - // unlike current.memoizedProps which will be the unresolved ones. - var prevProps = currentChild.memoizedProps; // Default to shallow comparison - - var compare = Component.compare; - compare = compare !== null ? compare : shallowEqual; - - if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) { - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - var newChild = createWorkInProgress(currentChild, nextProps); - newChild.ref = workInProgress.ref; - newChild.return = workInProgress; - workInProgress.child = newChild; - return newChild; - } - - function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { - // TODO: current can be non-null here even if the component - // hasn't yet mounted. This happens when the inner render suspends. - // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - 'prop', getComponentNameFromType(outerMemoType)); - } - } - } - } - - if (current !== null) { - var prevProps = current.memoizedProps; - - if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload. - workInProgress.type === current.type )) { - didReceiveUpdate = false; - - if (!checkScheduledUpdateOrContext(current, renderLanes)) { - // The pending lanes were cleared at the beginning of beginWork. We're - // about to bail out, but there might be other lanes that weren't - // included in the current render. Usually, the priority level of the - // remaining updates is accumulated during the evaluation of the - // component (i.e. when processing the update queue). But since since - // we're bailing out early *without* evaluating the component, we need - // to account for it here, too. Reset to the value of the current fiber. - // NOTE: This only applies to SimpleMemoComponent, not MemoComponent, - // because a MemoComponent fiber does not have hooks or an update queue; - // rather, it wraps around an inner component, which may or may not - // contains hooks. - // TODO: Move the reset at in beginWork out of the common path so that - // this is no longer necessary. - workInProgress.lanes = current.lanes; - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { - // This is a special case that only exists for legacy mode. - // See https://github.com/facebook/react/pull/19216. - didReceiveUpdate = true; - } - } - } - - return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes); - } - - function updateOffscreenComponent(current, workInProgress, renderLanes) { - var nextProps = workInProgress.pendingProps; - var nextChildren = nextProps.children; - var prevState = current !== null ? current.memoizedState : null; - - if (nextProps.mode === 'hidden' || enableLegacyHidden ) { - // Rendering a hidden tree. - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - // In legacy sync mode, don't defer the subtree. Render it now. - var nextState = { - baseLanes: NoLanes, - cachePool: null - }; - workInProgress.memoizedState = nextState; - - pushRenderLanes(workInProgress, renderLanes); - } else if (!includesSomeLane(renderLanes, OffscreenLane)) { - var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out - // and resume this tree later. - - var nextBaseLanes; - - if (prevState !== null) { - var prevBaseLanes = prevState.baseLanes; - nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes); - } else { - nextBaseLanes = renderLanes; - } // Schedule this fiber to re-render at offscreen priority. Then bailout. - - - workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane); - var _nextState = { - baseLanes: nextBaseLanes, - cachePool: spawnedCachePool - }; - workInProgress.memoizedState = _nextState; - workInProgress.updateQueue = null; - // to avoid a push/pop misalignment. - - - pushRenderLanes(workInProgress, nextBaseLanes); - - return null; - } else { - // This is the second render. The surrounding visible content has already - // committed. Now we resume rendering the hidden tree. - // Rendering at offscreen, so we can clear the base lanes. - var _nextState2 = { - baseLanes: NoLanes, - cachePool: null - }; - workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out. - - var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes; - - pushRenderLanes(workInProgress, subtreeRenderLanes); - } - } else { - // Rendering a visible tree. - var _subtreeRenderLanes; - - if (prevState !== null) { - // We're going from hidden -> visible. - _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes); - - - workInProgress.memoizedState = null; - } else { - // We weren't previously hidden, and we still aren't, so there's nothing - // special to do. Need to push to the stack regardless, though, to avoid - // a push/pop misalignment. - _subtreeRenderLanes = renderLanes; - } - - pushRenderLanes(workInProgress, _subtreeRenderLanes); - } - - { - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - } - - function updateFragment(current, workInProgress, renderLanes) { - var nextChildren = workInProgress.pendingProps; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateMode(current, workInProgress, renderLanes) { - var nextChildren = workInProgress.pendingProps.children; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateProfiler(current, workInProgress, renderLanes) { - { - workInProgress.flags |= Update; - - { - // Reset effect durations for the next eventual effect phase. - // These are reset during render to allow the DevTools commit hook a chance to read them, - var stateNode = workInProgress.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - } - - var nextProps = workInProgress.pendingProps; - var nextChildren = nextProps.children; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function markRef$1(current, workInProgress) { - var ref = workInProgress.ref; - - if (current === null && ref !== null || current !== null && current.ref !== ref) { - // Schedule a Ref effect - workInProgress.flags |= Ref; - - { - workInProgress.flags |= RefStatic; - } - } - } - - function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes(innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(Component)); - } - } - } - - var context; - - { - var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); - context = getMaskedContext(workInProgress, unmaskedContext); - } - - var nextChildren; - var hasId; - prepareToReadContext(workInProgress, renderLanes); - - { - markComponentRenderStarted(workInProgress); - } - - { - ReactCurrentOwner$1.current = workInProgress; - setIsRendering(true); - nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); - hasId = checkDidRenderIdHook(); - - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); - hasId = checkDidRenderIdHook(); - } finally { - setIsStrictModeForDevtools(false); - } - } - - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } - - if (current !== null && !didReceiveUpdate) { - bailoutHooks(current, workInProgress, renderLanes); - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) { - { - // This is used by DevTools to force a boundary to error. - switch (shouldError(workInProgress)) { - case false: - { - var _instance = workInProgress.stateNode; - var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack. - // Is there a better way to do this? - - var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context); - var state = tempInstance.state; - - _instance.updater.enqueueSetState(_instance, state, null); - - break; - } - - case true: - { - workInProgress.flags |= DidCapture; - workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes - - var error$1 = new Error('Simulated error coming from DevTools'); - var lane = pickArbitraryLane(renderLanes); - workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state - - var update = createClassErrorUpdate(workInProgress, createCapturedValue(error$1, workInProgress), lane); - enqueueCapturedUpdate(workInProgress, update); - break; - } - } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes(innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(Component)); - } - } - } // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - - - var hasContext; - - if (isContextProvider(Component)) { - hasContext = true; - pushContextProvider(workInProgress); - } else { - hasContext = false; - } - - prepareToReadContext(workInProgress, renderLanes); - var instance = workInProgress.stateNode; - var shouldUpdate; - - if (instance === null) { - if (current !== null) { - // A class component without an instance only mounts if it suspended - // inside a non-concurrent tree, in an inconsistent state. We want to - // treat it like a new mount, even though an empty version of it already - // committed. Disconnect the alternate pointers. - current.alternate = null; - workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - - workInProgress.flags |= Placement; - } // In the initial pass we might need to construct the instance. - - - constructClassInstance(workInProgress, Component, nextProps); - mountClassInstance(workInProgress, Component, nextProps, renderLanes); - shouldUpdate = true; - } else if (current === null) { - // In a resume, we'll already have an instance we can reuse. - shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes); - } else { - shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes); - } - - var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes); - - { - var inst = workInProgress.stateNode; - - if (shouldUpdate && inst.props !== nextProps) { - if (!didWarnAboutReassigningProps) { - error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component'); - } - - didWarnAboutReassigningProps = true; - } - } - - return nextUnitOfWork; - } - - function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) { - // Refs should update even if shouldComponentUpdate returns false - markRef$1(current, workInProgress); - var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags; - - if (!shouldUpdate && !didCaptureError) { - // Context providers should defer to sCU for rendering - if (hasContext) { - invalidateContextProvider(workInProgress, Component, false); - } - - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - var instance = workInProgress.stateNode; // Rerender - - ReactCurrentOwner$1.current = workInProgress; - var nextChildren; - - if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') { - // If we captured an error, but getDerivedStateFromError is not defined, - // unmount all the children. componentDidCatch will schedule an update to - // re-render a fallback. This is temporary until we migrate everyone to - // the new API. - // TODO: Warn in a future release. - nextChildren = null; - - { - stopProfilerTimerIfRunning(); - } - } else { - { - markComponentRenderStarted(workInProgress); - } - - { - setIsRendering(true); - nextChildren = instance.render(); - - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - instance.render(); - } finally { - setIsStrictModeForDevtools(false); - } - } - - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - - if (current !== null && didCaptureError) { - // If we're recovering from an error, reconcile without reusing any of - // the existing children. Conceptually, the normal children and the children - // that are shown on error are two different sets, so we shouldn't reuse - // normal children even if their identities match. - forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes); - } else { - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } // Memoize state using the values we just used to render. - // TODO: Restructure so we never read values from the instance. - - - workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. - - if (hasContext) { - invalidateContextProvider(workInProgress, Component, true); - } - - return workInProgress.child; - } - - function pushHostRootContext(workInProgress) { - var root = workInProgress.stateNode; - - if (root.pendingContext) { - pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context); - } else if (root.context) { - // Should always be set - pushTopLevelContextObject(workInProgress, root.context, false); - } - - pushHostContainer(workInProgress, root.containerInfo); - } - - function updateHostRoot(current, workInProgress, renderLanes) { - pushHostRootContext(workInProgress); - - if (current === null) { - throw new Error('Should have a current fiber. This is a bug in React.'); - } - - var nextProps = workInProgress.pendingProps; - var prevState = workInProgress.memoizedState; - var prevChildren = prevState.element; - cloneUpdateQueue(current, workInProgress); - processUpdateQueue(workInProgress, nextProps, null, renderLanes); - var nextState = workInProgress.memoizedState; - workInProgress.stateNode; - // being called "element". - - - var nextChildren = nextState.element; - - if (supportsHydration && prevState.isDehydrated) { - // This is a hydration root whose shell has not yet hydrated. We should - // attempt to hydrate. - // Flip isDehydrated to false to indicate that when this render - // finishes, the root will no longer be dehydrated. - var overrideState = { - element: nextChildren, - isDehydrated: false, - cache: nextState.cache, - transitions: nextState.transitions - }; - var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't - // have reducer functions so it doesn't need rebasing. - - updateQueue.baseState = overrideState; - workInProgress.memoizedState = overrideState; - - if (workInProgress.flags & ForceClientRender) { - // Something errored during a previous attempt to hydrate the shell, so we - // forced a client render. - var recoverableError = new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'); - return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError); - } else if (nextChildren !== prevChildren) { - var _recoverableError = new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'); - - return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError); - } else { - // The outermost shell has not hydrated yet. Start hydrating. - enterHydrationState(workInProgress); - - var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); - workInProgress.child = child; - var node = child; - - while (node) { - // Mark each child as hydrating. This is a fast path to know whether this - // tree is part of a hydrating tree. This is used to determine if a child - // node has fully mounted yet, and for scheduling event replaying. - // Conceptually this is similar to Placement in that a new subtree is - // inserted into the React tree here. It just happens to not need DOM - // mutations because it already exists. - node.flags = node.flags & ~Placement | Hydrating; - node = node.sibling; - } - } - } else { - // Root is not dehydrated. Either this is a client-only root, or it - // already hydrated. - resetHydrationState(); - - if (nextChildren === prevChildren) { - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } - - return workInProgress.child; - } - - function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) { - // Revert to client rendering. - resetHydrationState(); - queueHydrationError(recoverableError); - workInProgress.flags |= ForceClientRender; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateHostComponent$1(current, workInProgress, renderLanes) { - pushHostContext(workInProgress); - - if (current === null) { - tryToClaimNextHydratableInstance(workInProgress); - } - - var type = workInProgress.type; - var nextProps = workInProgress.pendingProps; - var prevProps = current !== null ? current.memoizedProps : null; - var nextChildren = nextProps.children; - var isDirectTextChild = shouldSetTextContent(type, nextProps); - - if (isDirectTextChild) { - // We special case a direct text child of a host node. This is a common - // case. We won't handle it as a reified child. We will instead handle - // this in the host environment that also has access to this prop. That - // avoids allocating another HostText fiber and traversing it. - nextChildren = null; - } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { - // If we're switching from a direct text child to a normal child, or to - // empty, we need to schedule the text content to be reset. - workInProgress.flags |= ContentReset; - } - - markRef$1(current, workInProgress); - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateHostText$1(current, workInProgress) { - if (current === null) { - tryToClaimNextHydratableInstance(workInProgress); - } // Nothing to do here. This is terminal. We'll do the completion step - // immediately after. - - - return null; - } - - function mountLazyComponent(_current, workInProgress, elementType, renderLanes) { - if (_current !== null) { - // A lazy component only mounts if it suspended inside a non- - // concurrent tree, in an inconsistent state. We want to treat it like - // a new mount, even though an empty version of it already committed. - // Disconnect the alternate pointers. - _current.alternate = null; - workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - - workInProgress.flags |= Placement; - } - - var props = workInProgress.pendingProps; - var lazyComponent = elementType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - var Component = init(payload); // Store the unwrapped component in the type. - - workInProgress.type = Component; - var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component); - var resolvedProps = resolveDefaultProps(Component, props); - var child; - - switch (resolvedTag) { - case FunctionComponent: - { - { - validateFunctionComponentInDev(workInProgress, Component); - workInProgress.type = Component = resolveFunctionForHotReloading(Component); - } - - child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes); - return child; - } - - case ClassComponent: - { - { - workInProgress.type = Component = resolveClassForHotReloading(Component); - } - - child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes); - return child; - } - - case ForwardRef: - { - { - workInProgress.type = Component = resolveForwardRefForHotReloading(Component); - } - - child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes); - return child; - } - - case MemoComponent: - { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only - 'prop', getComponentNameFromType(Component)); - } - } - } - - child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too - renderLanes); - return child; - } - } - - var hint = ''; - - { - if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) { - hint = ' Did you wrap a component in React.lazy() more than once?'; - } - } // This message intentionally doesn't mention ForwardRef or MemoComponent - // because the fact that it's a separate type of work is an - // implementation detail. - - - throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint)); - } - - function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) { - if (_current !== null) { - // An incomplete component only mounts if it suspended inside a non- - // concurrent tree, in an inconsistent state. We want to treat it like - // a new mount, even though an empty version of it already committed. - // Disconnect the alternate pointers. - _current.alternate = null; - workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - - workInProgress.flags |= Placement; - } // Promote the fiber to a class and try rendering again. - - - workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` - // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - - var hasContext; - - if (isContextProvider(Component)) { - hasContext = true; - pushContextProvider(workInProgress); - } else { - hasContext = false; - } - - prepareToReadContext(workInProgress, renderLanes); - constructClassInstance(workInProgress, Component, nextProps); - mountClassInstance(workInProgress, Component, nextProps, renderLanes); - return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); - } - - function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) { - if (_current !== null) { - // An indeterminate component only mounts if it suspended inside a non- - // concurrent tree, in an inconsistent state. We want to treat it like - // a new mount, even though an empty version of it already committed. - // Disconnect the alternate pointers. - _current.alternate = null; - workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - - workInProgress.flags |= Placement; - } - - var props = workInProgress.pendingProps; - var context; - - { - var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); - context = getMaskedContext(workInProgress, unmaskedContext); - } - - prepareToReadContext(workInProgress, renderLanes); - var value; - var hasId; - - { - markComponentRenderStarted(workInProgress); - } - - { - if (Component.prototype && typeof Component.prototype.render === 'function') { - var componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutBadClass[componentName]) { - error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); - - didWarnAboutBadClass[componentName] = true; - } - } - - if (workInProgress.mode & StrictLegacyMode) { - ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null); - } - - setIsRendering(true); - ReactCurrentOwner$1.current = workInProgress; - value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); - hasId = checkDidRenderIdHook(); - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - - { - // Support for module components is deprecated and is removed behind a flag. - // Whether or not it would crash later, we want to show a good message in DEV first. - if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { - var _componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutModulePatternComponent[_componentName]) { - error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); - - didWarnAboutModulePatternComponent[_componentName] = true; - } - } - } - - if ( // Run these checks in production only if the flag is off. - // Eventually we'll delete this branch altogether. - typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { - { - var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutModulePatternComponent[_componentName2]) { - error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); - - didWarnAboutModulePatternComponent[_componentName2] = true; - } - } // Proceed under the assumption that this is a class instance - - - workInProgress.tag = ClassComponent; // Throw out any hooks that were used. - - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - - var hasContext = false; - - if (isContextProvider(Component)) { - hasContext = true; - pushContextProvider(workInProgress); - } else { - hasContext = false; - } - - workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; - initializeUpdateQueue(workInProgress); - adoptClassInstance(workInProgress, value); - mountClassInstance(workInProgress, Component, props, renderLanes); - return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); - } else { - // Proceed under the assumption that this is a function component - workInProgress.tag = FunctionComponent; - - { - - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); - hasId = checkDidRenderIdHook(); - } finally { - setIsStrictModeForDevtools(false); - } - } - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } - - reconcileChildren(null, workInProgress, value, renderLanes); - - { - validateFunctionComponentInDev(workInProgress, Component); - } - - return workInProgress.child; - } - } - - function validateFunctionComponentInDev(workInProgress, Component) { - { - if (Component) { - if (Component.childContextTypes) { - error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); - } - } - - if (workInProgress.ref !== null) { - var info = ''; - var ownerName = getCurrentFiberOwnerNameInDevOrNull(); - - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - - var warningKey = ownerName || ''; - var debugSource = workInProgress._debugSource; - - if (debugSource) { - warningKey = debugSource.fileName + ':' + debugSource.lineNumber; - } - - if (!didWarnAboutFunctionRefs[warningKey]) { - didWarnAboutFunctionRefs[warningKey] = true; - - error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info); - } - } - - if (typeof Component.getDerivedStateFromProps === 'function') { - var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { - error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); - - didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; - } - } - - if (typeof Component.contextType === 'object' && Component.contextType !== null) { - var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { - error('%s: Function components do not support contextType.', _componentName4); - - didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; - } - } - } - } - - var SUSPENDED_MARKER = { - dehydrated: null, - treeContext: null, - retryLane: NoLane - }; - - function mountSuspenseOffscreenState(renderLanes) { - return { - baseLanes: renderLanes, - cachePool: getSuspendedCache() - }; - } - - function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) { - var cachePool = null; - - return { - baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes), - cachePool: cachePool - }; - } // TODO: Probably should inline this back - - - function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) { - // If we're already showing a fallback, there are cases where we need to - // remain on that fallback regardless of whether the content has resolved. - // For example, SuspenseList coordinates when nested content appears. - if (current !== null) { - var suspenseState = current.memoizedState; - - if (suspenseState === null) { - // Currently showing content. Don't hide it, even if ForceSuspenseFallback - // is true. More precise name might be "ForceRemainSuspenseFallback". - // Note: This is a factoring smell. Can't remain on a fallback if there's - // no fallback to remain on. - return false; - } - } // Not currently showing content. Consult the Suspense context. - - - return hasSuspenseContext(suspenseContext, ForceSuspenseFallback); - } - - function getRemainingWorkInPrimaryTree(current, renderLanes) { - // TODO: Should not remove render lanes that were pinged during this render - return removeLanes(current.childLanes, renderLanes); - } - - function updateSuspenseComponent(current, workInProgress, renderLanes) { - var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. - - { - if (shouldSuspend(workInProgress)) { - workInProgress.flags |= DidCapture; - } - } - - var suspenseContext = suspenseStackCursor.current; - var showFallback = false; - var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags; - - if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) { - // Something in this boundary's subtree already suspended. Switch to - // rendering the fallback children. - showFallback = true; - workInProgress.flags &= ~DidCapture; - } else { - // Attempting the main content - if (current === null || current.memoizedState !== null) { - // This is a new mount or this boundary is already showing a fallback state. - // Mark this subtree context as having at least one invisible parent that could - // handle the fallback state. - // Avoided boundaries are not considered since they cannot handle preferred fallback states. - { - suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext); - } - } - } - - suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense - // boundary's children. This involves some custom reconciliation logic. Two - // main reasons this is so complicated. - // - // First, Legacy Mode has different semantics for backwards compatibility. The - // primary tree will commit in an inconsistent state, so when we do the - // second pass to render the fallback, we do some exceedingly, uh, clever - // hacks to make that not totally break. Like transferring effects and - // deletions from hidden tree. In Concurrent Mode, it's much simpler, - // because we bailout on the primary tree completely and leave it in its old - // state, no effects. Same as what we do for Offscreen (except that - // Offscreen doesn't have the first render pass). - // - // Second is hydration. During hydration, the Suspense fiber has a slightly - // different layout, where the child points to a dehydrated fragment, which - // contains the DOM rendered by the server. - // - // Third, even if you set all that aside, Suspense is like error boundaries in - // that we first we try to render one tree, and if that fails, we render again - // and switch to a different tree. Like a try/catch block. So we have to track - // which branch we're currently rendering. Ideally we would model this using - // a stack. - - if (current === null) { - // Initial mount - // If we're currently hydrating, try to hydrate this boundary. - tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. - - { - var suspenseState = workInProgress.memoizedState; - - if (suspenseState !== null) { - var dehydrated = suspenseState.dehydrated; - - if (dehydrated !== null) { - return mountDehydratedSuspenseComponent(workInProgress, dehydrated); - } - } - } - - var nextPrimaryChildren = nextProps.children; - var nextFallbackChildren = nextProps.fallback; - - if (showFallback) { - var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes); - var primaryChildFragment = workInProgress.child; - primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes); - workInProgress.memoizedState = SUSPENDED_MARKER; - return fallbackFragment; - } else { - return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren); - } - } else { - // This is an update. - // If the current fiber has a SuspenseState, that means it's already showing - // a fallback. - var prevState = current.memoizedState; - - if (prevState !== null) { - // The current tree is already showing a fallback - // Special path for hydration - { - var _dehydrated = prevState.dehydrated; - - if (_dehydrated !== null) { - if (!didSuspend) { - return updateDehydratedSuspenseComponent(current, workInProgress, _dehydrated, prevState, renderLanes); - } else if (workInProgress.flags & ForceClientRender) { - // Something errored during hydration. Try again without hydrating. - workInProgress.flags &= ~ForceClientRender; - return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.')); - } else if (workInProgress.memoizedState !== null) { - // Something suspended and we should still be in dehydrated mode. - // Leave the existing child in place. - workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there - // but the normal suspense pass doesn't. - - workInProgress.flags |= DidCapture; - return null; - } else { - // Suspended but we should no longer be in dehydrated mode. - // Therefore we now have to render the fallback. - var _nextPrimaryChildren = nextProps.children; - var _nextFallbackChildren = nextProps.fallback; - var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes); - var _primaryChildFragment2 = workInProgress.child; - _primaryChildFragment2.memoizedState = mountSuspenseOffscreenState(renderLanes); - workInProgress.memoizedState = SUSPENDED_MARKER; - return fallbackChildFragment; - } - } - } - - if (showFallback) { - var _nextFallbackChildren2 = nextProps.fallback; - var _nextPrimaryChildren2 = nextProps.children; - - var _fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren2, _nextFallbackChildren2, renderLanes); - - var _primaryChildFragment3 = workInProgress.child; - var prevOffscreenState = current.child.memoizedState; - _primaryChildFragment3.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes); - _primaryChildFragment3.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); - workInProgress.memoizedState = SUSPENDED_MARKER; - return _fallbackChildFragment; - } else { - var _nextPrimaryChildren3 = nextProps.children; - - var _primaryChildFragment4 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren3, renderLanes); - - workInProgress.memoizedState = null; - return _primaryChildFragment4; - } - } else { - // The current tree is not already showing a fallback. - if (showFallback) { - // Timed out. - var _nextFallbackChildren3 = nextProps.fallback; - var _nextPrimaryChildren4 = nextProps.children; - - var _fallbackChildFragment2 = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren4, _nextFallbackChildren3, renderLanes); - - var _primaryChildFragment5 = workInProgress.child; - var _prevOffscreenState = current.child.memoizedState; - _primaryChildFragment5.memoizedState = _prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(_prevOffscreenState, renderLanes); - _primaryChildFragment5.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); // Skip the primary children, and continue working on the - // fallback children. - - workInProgress.memoizedState = SUSPENDED_MARKER; - return _fallbackChildFragment2; - } else { - // Still haven't timed out. Continue rendering the children, like we - // normally do. - var _nextPrimaryChildren5 = nextProps.children; - - var _primaryChildFragment6 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren5, renderLanes); - - workInProgress.memoizedState = null; - return _primaryChildFragment6; - } - } - } - } - - function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) { - var mode = workInProgress.mode; - var primaryChildProps = { - mode: 'visible', - children: primaryChildren - }; - var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); - primaryChildFragment.return = workInProgress; - workInProgress.child = primaryChildFragment; - return primaryChildFragment; - } - - function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) { - var mode = workInProgress.mode; - var progressedPrimaryFragment = workInProgress.child; - var primaryChildProps = { - mode: 'hidden', - children: primaryChildren - }; - var primaryChildFragment; - var fallbackChildFragment; - - if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) { - // In legacy mode, we commit the primary tree as if it successfully - // completed, even though it's in an inconsistent state. - primaryChildFragment = progressedPrimaryFragment; - primaryChildFragment.childLanes = NoLanes; - primaryChildFragment.pendingProps = primaryChildProps; - - if ( workInProgress.mode & ProfileMode) { - // Reset the durations from the first pass so they aren't included in the - // final amounts. This seems counterintuitive, since we're intentionally - // not measuring part of the render phase, but this makes it match what we - // do in Concurrent Mode. - primaryChildFragment.actualDuration = 0; - primaryChildFragment.actualStartTime = -1; - primaryChildFragment.selfBaseDuration = 0; - primaryChildFragment.treeBaseDuration = 0; - } - - fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); - } else { - primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); - fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); - } - - primaryChildFragment.return = workInProgress; - fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress.child = primaryChildFragment; - return fallbackChildFragment; - } - - function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) { - // The props argument to `createFiberFromOffscreen` is `any` typed, so we use - // this wrapper function to constrain it. - return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); - } - - function updateWorkInProgressOffscreenFiber(current, offscreenProps) { - // The props argument to `createWorkInProgress` is `any` typed, so we use this - // wrapper function to constrain it. - return createWorkInProgress(current, offscreenProps); - } - - function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) { - var currentPrimaryChildFragment = current.child; - var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; - var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, { - mode: 'visible', - children: primaryChildren - }); - - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - primaryChildFragment.lanes = renderLanes; - } - - primaryChildFragment.return = workInProgress; - primaryChildFragment.sibling = null; - - if (currentFallbackChildFragment !== null) { - // Delete the fallback child fragment - var deletions = workInProgress.deletions; - - if (deletions === null) { - workInProgress.deletions = [currentFallbackChildFragment]; - workInProgress.flags |= ChildDeletion; - } else { - deletions.push(currentFallbackChildFragment); - } - } - - workInProgress.child = primaryChildFragment; - return primaryChildFragment; - } - - function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { - var mode = workInProgress.mode; - var currentPrimaryChildFragment = current.child; - var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; - var primaryChildProps = { - mode: 'hidden', - children: primaryChildren - }; - var primaryChildFragment; - - if ( // In legacy mode, we commit the primary tree as if it successfully - // completed, even though it's in an inconsistent state. - (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was - // already cloned. In legacy mode, the only case where this isn't true is - // when DevTools forces us to display a fallback; we skip the first render - // pass entirely and go straight to rendering the fallback. (In Concurrent - // Mode, SuspenseList can also trigger this scenario, but this is a legacy- - // only codepath.) - workInProgress.child !== currentPrimaryChildFragment) { - var progressedPrimaryFragment = workInProgress.child; - primaryChildFragment = progressedPrimaryFragment; - primaryChildFragment.childLanes = NoLanes; - primaryChildFragment.pendingProps = primaryChildProps; - - if ( workInProgress.mode & ProfileMode) { - // Reset the durations from the first pass so they aren't included in the - // final amounts. This seems counterintuitive, since we're intentionally - // not measuring part of the render phase, but this makes it match what we - // do in Concurrent Mode. - primaryChildFragment.actualDuration = 0; - primaryChildFragment.actualStartTime = -1; - primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; - primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; - } - // However, since we're going to remain on the fallback, we no longer want - // to delete it. - - - workInProgress.deletions = null; - } else { - primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); - // (We don't do this in legacy mode, because in legacy mode we don't re-use - // the current tree; see previous branch.) - - - primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; - } - - var fallbackChildFragment; - - if (currentFallbackChildFragment !== null) { - fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren); - } else { - fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already - // mounted but this is a new fiber. - - fallbackChildFragment.flags |= Placement; - } - - fallbackChildFragment.return = workInProgress; - primaryChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress.child = primaryChildFragment; - return fallbackChildFragment; - } - - function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) { - // Falling back to client rendering. Because this has performance - // implications, it's considered a recoverable error, even though the user - // likely won't observe anything wrong with the UI. - // - // The error is passed in as an argument to enforce that every caller provide - // a custom message, or explicitly opt out (currently the only path that opts - // out is legacy mode; every concurrent path provides an error). - if (recoverableError !== null) { - queueHydrationError(recoverableError); - } // This will add the old fiber to the deletion list - - - reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated. - - var nextProps = workInProgress.pendingProps; - var primaryChildren = nextProps.children; - var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already - // mounted but this is a new fiber. - - primaryChildFragment.flags |= Placement; - workInProgress.memoizedState = null; - return primaryChildFragment; - } - - function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { - var fiberMode = workInProgress.mode; - var primaryChildProps = { - mode: 'visible', - children: primaryChildren - }; - var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode); - var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense - // boundary) already mounted but this is a new fiber. - - fallbackChildFragment.flags |= Placement; - primaryChildFragment.return = workInProgress; - fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress.child = primaryChildFragment; - - if ((workInProgress.mode & ConcurrentMode) !== NoMode) { - // We will have dropped the effect list which contains the - // deletion. We need to reconcile to delete the current child. - reconcileChildFibers(workInProgress, current.child, null, renderLanes); - } - - return fallbackChildFragment; - } - - function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) { - // During the first pass, we'll bail out and not drill into the children. - // Instead, we'll leave the content in place and try to hydrate it later. - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - { - error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, )' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.'); - } - - workInProgress.lanes = laneToLanes(SyncLane); - } else if (isSuspenseInstanceFallback(suspenseInstance)) { - // This is a client-only boundary. Since we won't get any content from the server - // for this, we need to schedule that at a higher priority based on when it would - // have timed out. In theory we could render it in this pass but it would have the - // wrong priority associated with it and will prevent hydration of parent path. - // Instead, we'll leave work left on it to render it in a separate commit. - // TODO This time should be the time at which the server rendered response that is - // a parent to this boundary was displayed. However, since we currently don't have - // a protocol to transfer that time, we'll just estimate it by using the current - // time. This will mean that Suspense timeouts are slightly shifted to later than - // they should be. - // Schedule a normal pri update to render this content. - workInProgress.lanes = laneToLanes(DefaultHydrationLane); - } else { - // We'll continue hydrating the rest at offscreen priority since we'll already - // be showing the right content coming from the server, it is no rush. - workInProgress.lanes = laneToLanes(OffscreenLane); - } - - return null; - } - - function updateDehydratedSuspenseComponent(current, workInProgress, suspenseInstance, suspenseState, renderLanes) { - // We should never be hydrating at this point because it is the first pass, - // but after we've already committed once. - warnIfHydrating(); - - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument - // required — every concurrent mode path that causes hydration to - // de-opt to client rendering should have an error message. - null); - } - - if (isSuspenseInstanceFallback(suspenseInstance)) { - // This boundary is in a permanent fallback state. In this case, we'll never - // get an update and we'll never be able to hydrate the final content. Let's just try the - // client side render instead. - return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: The server should serialize the error message so we can log it - // here on the client. Or, in production, a hash/id that corresponds to - // the error. - new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.')); - } - // any context has changed, we need to treat is as if the input might have changed. - - - var hasContextChanged = includesSomeLane(renderLanes, current.childLanes); - - if (didReceiveUpdate || hasContextChanged) { - // This boundary has changed since the first render. This means that we are now unable to - // hydrate it. We might still be able to hydrate it using a higher priority lane. - var root = getWorkInProgressRoot(); - - if (root !== null) { - var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes); - - if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) { - // Intentionally mutating since this render will get interrupted. This - // is one of the very rare times where we mutate the current tree - // during the render phase. - suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render - - var eventTime = NoTimestamp; - scheduleUpdateOnFiber(current, attemptHydrationAtLane, eventTime); - } - } // If we have scheduled higher pri work above, this will probably just abort the render - // since we now have higher priority work, but in case it doesn't, we need to prepare to - // render something, if we time out. Even if that requires us to delete everything and - // skip hydration. - // Delay having to do this as long as the suspense timeout allows us. - - - renderDidSuspendDelayIfPossible(); - return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.')); - } else if (isSuspenseInstancePending(suspenseInstance)) { - // This component is still pending more data from the server, so we can't hydrate its - // content. We treat it as if this component suspended itself. It might seem as if - // we could just try to render it client-side instead. However, this will perform a - // lot of unnecessary work and is unlikely to complete since it often will suspend - // on missing data anyway. Additionally, the server might be able to render more - // than we can on the client yet. In that case we'd end up with more fallback states - // on the client than if we just leave it alone. If the server times out or errors - // these should update this boundary to the permanent Fallback state instead. - // Mark it as having captured (i.e. suspended). - workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. - - workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result. - - var retry = retryDehydratedSuspenseBoundary.bind(null, current); - registerSuspenseInstanceRetry(suspenseInstance, retry); - return null; - } else { - // This is the first attempt. - reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext); - var nextProps = workInProgress.pendingProps; - var primaryChildren = nextProps.children; - var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this - // tree is part of a hydrating tree. This is used to determine if a child - // node has fully mounted yet, and for scheduling event replaying. - // Conceptually this is similar to Placement in that a new subtree is - // inserted into the React tree here. It just happens to not need DOM - // mutations because it already exists. - - primaryChildFragment.flags |= Hydrating; - return primaryChildFragment; - } - } - - function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) { - fiber.lanes = mergeLanes(fiber.lanes, renderLanes); - var alternate = fiber.alternate; - - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes); - } - - scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot); - } - - function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) { - // Mark any Suspense boundaries with fallbacks as having work to do. - // If they were previously forced into fallbacks, they may now be able - // to unblock. - var node = firstChild; - - while (node !== null) { - if (node.tag === SuspenseComponent) { - var state = node.memoizedState; - - if (state !== null) { - scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); - } - } else if (node.tag === SuspenseListComponent) { - // If the tail is hidden there might not be an Suspense boundaries - // to schedule work on. In this case we have to schedule it on the - // list itself. - // We don't have to traverse to the children of the list since - // the list will propagate the change when it rerenders. - scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === workInProgress) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - - function findLastContentRow(firstChild) { - // This is going to find the last row among these children that is already - // showing content on the screen, as opposed to being in fallback state or - // new. If a row has multiple Suspense boundaries, any of them being in the - // fallback state, counts as the whole row being in a fallback state. - // Note that the "rows" will be workInProgress, but any nested children - // will still be current since we haven't rendered them yet. The mounted - // order may not be the same as the new order. We use the new order. - var row = firstChild; - var lastContentRow = null; - - while (row !== null) { - var currentRow = row.alternate; // New rows can't be content rows. - - if (currentRow !== null && findFirstSuspended(currentRow) === null) { - lastContentRow = row; - } - - row = row.sibling; - } - - return lastContentRow; - } - - function validateRevealOrder(revealOrder) { - { - if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) { - didWarnAboutRevealOrder[revealOrder] = true; - - if (typeof revealOrder === 'string') { - switch (revealOrder.toLowerCase()) { - case 'together': - case 'forwards': - case 'backwards': - { - error('"%s" is not a valid value for revealOrder on . ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase()); - - break; - } - - case 'forward': - case 'backward': - { - error('"%s" is not a valid value for revealOrder on . ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase()); - - break; - } - - default: - error('"%s" is not a supported revealOrder on . ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); - - break; - } - } else { - error('%s is not a supported value for revealOrder on . ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); - } - } - } - } - - function validateTailOptions(tailMode, revealOrder) { - { - if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) { - if (tailMode !== 'collapsed' && tailMode !== 'hidden') { - didWarnAboutTailOptions[tailMode] = true; - - error('"%s" is not a supported value for tail on . ' + 'Did you mean "collapsed" or "hidden"?', tailMode); - } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') { - didWarnAboutTailOptions[tailMode] = true; - - error(' is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode); - } - } - } - } - - function validateSuspenseListNestedChild(childSlot, index) { - { - var isAnArray = isArray(childSlot); - var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function'; - - if (isAnArray || isIterable) { - var type = isAnArray ? 'array' : 'iterable'; - - error('A nested %s was passed to row #%s in . Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + ' ... ' + '{%s} ... ' + '', type, index, type); - - return false; - } - } - - return true; - } - - function validateSuspenseListChildren(children, revealOrder) { - { - if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) { - if (isArray(children)) { - for (var i = 0; i < children.length; i++) { - if (!validateSuspenseListNestedChild(children[i], i)) { - return; - } - } - } else { - var iteratorFn = getIteratorFn(children); - - if (typeof iteratorFn === 'function') { - var childrenIterator = iteratorFn.call(children); - - if (childrenIterator) { - var step = childrenIterator.next(); - var _i = 0; - - for (; !step.done; step = childrenIterator.next()) { - if (!validateSuspenseListNestedChild(step.value, _i)) { - return; - } - - _i++; - } - } - } else { - error('A single row was passed to a . ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder); - } - } - } - } - } - - function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) { - var renderState = workInProgress.memoizedState; - - if (renderState === null) { - workInProgress.memoizedState = { - isBackwards: isBackwards, - rendering: null, - renderingStartTime: 0, - last: lastContentRow, - tail: tail, - tailMode: tailMode - }; - } else { - // We can reuse the existing object from previous renders. - renderState.isBackwards = isBackwards; - renderState.rendering = null; - renderState.renderingStartTime = 0; - renderState.last = lastContentRow; - renderState.tail = tail; - renderState.tailMode = tailMode; - } - } // This can end up rendering this component multiple passes. - // The first pass splits the children fibers into two sets. A head and tail. - // We first render the head. If anything is in fallback state, we do another - // pass through beginWork to rerender all children (including the tail) with - // the force suspend context. If the first render didn't have anything in - // in fallback state. Then we render each row in the tail one-by-one. - // That happens in the completeWork phase without going back to beginWork. - - - function updateSuspenseListComponent(current, workInProgress, renderLanes) { - var nextProps = workInProgress.pendingProps; - var revealOrder = nextProps.revealOrder; - var tailMode = nextProps.tail; - var newChildren = nextProps.children; - validateRevealOrder(revealOrder); - validateTailOptions(tailMode, revealOrder); - validateSuspenseListChildren(newChildren, revealOrder); - reconcileChildren(current, workInProgress, newChildren, renderLanes); - var suspenseContext = suspenseStackCursor.current; - var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback); - - if (shouldForceFallback) { - suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); - workInProgress.flags |= DidCapture; - } else { - var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags; - - if (didSuspendBefore) { - // If we previously forced a fallback, we need to schedule work - // on any nested boundaries to let them know to try to render - // again. This is the same as context updating. - propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes); - } - - suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - } - - pushSuspenseContext(workInProgress, suspenseContext); - - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - // In legacy mode, SuspenseList doesn't work so we just - // use make it a noop by treating it as the default revealOrder. - workInProgress.memoizedState = null; - } else { - switch (revealOrder) { - case 'forwards': - { - var lastContentRow = findLastContentRow(workInProgress.child); - var tail; - - if (lastContentRow === null) { - // The whole list is part of the tail. - // TODO: We could fast path by just rendering the tail now. - tail = workInProgress.child; - workInProgress.child = null; - } else { - // Disconnect the tail rows after the content row. - // We're going to render them separately later. - tail = lastContentRow.sibling; - lastContentRow.sibling = null; - } - - initSuspenseListRenderState(workInProgress, false, // isBackwards - tail, lastContentRow, tailMode); - break; - } - - case 'backwards': - { - // We're going to find the first row that has existing content. - // At the same time we're going to reverse the list of everything - // we pass in the meantime. That's going to be our tail in reverse - // order. - var _tail = null; - var row = workInProgress.child; - workInProgress.child = null; - - while (row !== null) { - var currentRow = row.alternate; // New rows can't be content rows. - - if (currentRow !== null && findFirstSuspended(currentRow) === null) { - // This is the beginning of the main content. - workInProgress.child = row; - break; - } - - var nextRow = row.sibling; - row.sibling = _tail; - _tail = row; - row = nextRow; - } // TODO: If workInProgress.child is null, we can continue on the tail immediately. - - - initSuspenseListRenderState(workInProgress, true, // isBackwards - _tail, null, // last - tailMode); - break; - } - - case 'together': - { - initSuspenseListRenderState(workInProgress, false, // isBackwards - null, // tail - null, // last - undefined); - break; - } - - default: - { - // The default reveal order is the same as not having - // a boundary. - workInProgress.memoizedState = null; - } - } - } - - return workInProgress.child; - } - - function updatePortalComponent(current, workInProgress, renderLanes) { - pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); - var nextChildren = workInProgress.pendingProps; - - if (current === null) { - // Portals are special because we don't append the children during mount - // but at commit. Therefore we need to track insertions which the normal - // flow doesn't do during mount. This doesn't happen at the root because - // the root always starts with a "current" with a null child. - // TODO: Consider unifying this with how the root works. - workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); - } else { - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } - - return workInProgress.child; - } - - var hasWarnedAboutUsingNoValuePropOnContextProvider = false; - - function updateContextProvider(current, workInProgress, renderLanes) { - var providerType = workInProgress.type; - var context = providerType._context; - var newProps = workInProgress.pendingProps; - var oldProps = workInProgress.memoizedProps; - var newValue = newProps.value; - - { - if (!('value' in newProps)) { - if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { - hasWarnedAboutUsingNoValuePropOnContextProvider = true; - - error('The `value` prop is required for the ``. Did you misspell it or forget to pass it?'); - } - } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider'); - } - } - - pushProvider(workInProgress, context, newValue); - - { - if (oldProps !== null) { - var oldValue = oldProps.value; - - if (objectIs(oldValue, newValue)) { - // No change. Bailout early if children are the same. - if (oldProps.children === newProps.children && !hasContextChanged()) { - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - } else { - // The context value changed. Search for matching consumers and schedule - // them to update. - propagateContextChange(workInProgress, context, renderLanes); - } - } - } - - var newChildren = newProps.children; - reconcileChildren(current, workInProgress, newChildren, renderLanes); - return workInProgress.child; - } - - var hasWarnedAboutUsingContextAsConsumer = false; - - function updateContextConsumer(current, workInProgress, renderLanes) { - var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In - // DEV mode, we create a separate object for Context.Consumer that acts - // like a proxy to Context. This proxy object adds unnecessary code in PROD - // so we use the old behaviour (Context.Consumer references Context) to - // reduce size and overhead. The separate object references context via - // a property called "_context", which also gives us the ability to check - // in DEV mode if this property exists or not and warn if it does not. - - { - if (context._context === undefined) { - // This may be because it's a Context (rather than a Consumer). - // Or it may be because it's older React where they're the same thing. - // We only want to warn if we're sure it's a new React. - if (context !== context.Consumer) { - if (!hasWarnedAboutUsingContextAsConsumer) { - hasWarnedAboutUsingContextAsConsumer = true; - - error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); - } - } - } else { - context = context._context; - } - } - - var newProps = workInProgress.pendingProps; - var render = newProps.children; - - { - if (typeof render !== 'function') { - error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); - } - } - - prepareToReadContext(workInProgress, renderLanes); - var newValue = readContext(context); - - { - markComponentRenderStarted(workInProgress); - } - - var newChildren; - - { - ReactCurrentOwner$1.current = workInProgress; - setIsRendering(true); - newChildren = render(newValue); - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, newChildren, renderLanes); - return workInProgress.child; - } - - function markWorkInProgressReceivedUpdate() { - didReceiveUpdate = true; - } - - function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) { - if (current !== null) { - // Reuse previous dependencies - workInProgress.dependencies = current.dependencies; - } - - { - // Don't update "base" render times for bailouts. - stopProfilerTimerIfRunning(); - } - - markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work. - - if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { - // The children don't have any work either. We can skip them. - // TODO: Once we add back resuming, we should check if the children are - // a work-in-progress set. If so, we need to transfer their effects. - { - return null; - } - } // This fiber doesn't have work, but its subtree does. Clone the child - // fibers and continue. - - - cloneChildFibers(current, workInProgress); - return workInProgress.child; - } - - function remountFiber(current, oldWorkInProgress, newWorkInProgress) { - { - var returnFiber = oldWorkInProgress.return; - - if (returnFiber === null) { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('Cannot swap the root fiber.'); - } // Disconnect from the old current. - // It will get deleted. - - - current.alternate = null; - oldWorkInProgress.alternate = null; // Connect to the new tree. - - newWorkInProgress.index = oldWorkInProgress.index; - newWorkInProgress.sibling = oldWorkInProgress.sibling; - newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. - - if (oldWorkInProgress === returnFiber.child) { - returnFiber.child = newWorkInProgress; - } else { - var prevSibling = returnFiber.child; - - if (prevSibling === null) { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('Expected parent to have a child.'); - } - - while (prevSibling.sibling !== oldWorkInProgress) { - prevSibling = prevSibling.sibling; - - if (prevSibling === null) { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('Expected to find the previous sibling.'); - } - } - - prevSibling.sibling = newWorkInProgress; - } // Delete the old fiber and place the new one. - // Since the old fiber is disconnected, we have to schedule it manually. - - - var deletions = returnFiber.deletions; - - if (deletions === null) { - returnFiber.deletions = [current]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(current); - } - - newWorkInProgress.flags |= Placement; // Restart work from the new fiber. - - return newWorkInProgress; - } - } - - function checkScheduledUpdateOrContext(current, renderLanes) { - // Before performing an early bailout, we must check if there are pending - // updates or context. - var updateLanes = current.lanes; - - if (includesSomeLane(updateLanes, renderLanes)) { - return true; - } // No pending update, but because context is propagated lazily, we need - - return false; - } - - function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) { - // This fiber does not have any pending work. Bailout without entering - // the begin phase. There's still some bookkeeping we that needs to be done - // in this optimized path, mostly pushing stuff onto the stack. - switch (workInProgress.tag) { - case HostRoot: - pushHostRootContext(workInProgress); - workInProgress.stateNode; - - resetHydrationState(); - break; - - case HostComponent: - pushHostContext(workInProgress); - break; - - case ClassComponent: - { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - pushContextProvider(workInProgress); - } - - break; - } - - case HostPortal: - pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); - break; - - case ContextProvider: - { - var newValue = workInProgress.memoizedProps.value; - var context = workInProgress.type._context; - pushProvider(workInProgress, context, newValue); - break; - } - - case Profiler: - { - // Profiler should only call onRender when one of its descendants actually rendered. - var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); - - if (hasChildWork) { - workInProgress.flags |= Update; - } - - { - // Reset effect durations for the next eventual effect phase. - // These are reset during render to allow the DevTools commit hook a chance to read them, - var stateNode = workInProgress.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - } - - break; - - case SuspenseComponent: - { - var state = workInProgress.memoizedState; - - if (state !== null) { - { - if (state.dehydrated !== null) { - pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has - // been unsuspended it has committed as a resolved Suspense component. - // If it needs to be retried, it should have work scheduled on it. - - workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we - // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork. - - return null; - } - } // If this boundary is currently timed out, we need to decide - // whether to retry the primary children, or to skip over it and - // go straight to the fallback. Check the priority of the primary - // child fragment. - - - var primaryChildFragment = workInProgress.child; - var primaryChildLanes = primaryChildFragment.childLanes; - - if (includesSomeLane(renderLanes, primaryChildLanes)) { - // The primary children have pending work. Use the normal path - // to attempt to render the primary children again. - return updateSuspenseComponent(current, workInProgress, renderLanes); - } else { - // The primary child fragment does not have pending work marked - // on it - pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient - // priority. Bailout. - - var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - - if (child !== null) { - // The fallback children have pending work. Skip over the - // primary children and work on the fallback. - return child.sibling; - } else { - // Note: We can return `null` here because we already checked - // whether there were nested context consumers, via the call to - // `bailoutOnAlreadyFinishedWork` above. - return null; - } - } - } else { - pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); - } - - break; - } - - case SuspenseListComponent: - { - var didSuspendBefore = (current.flags & DidCapture) !== NoFlags; - - var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); - - if (didSuspendBefore) { - if (_hasChildWork) { - // If something was in fallback state last time, and we have all the - // same children then we're still in progressive loading state. - // Something might get unblocked by state updates or retries in the - // tree which will affect the tail. So we need to use the normal - // path to compute the correct tail. - return updateSuspenseListComponent(current, workInProgress, renderLanes); - } // If none of the children had any work, that means that none of - // them got retried so they'll still be blocked in the same way - // as before. We can fast bail out. - - - workInProgress.flags |= DidCapture; - } // If nothing suspended before and we're rendering the same children, - // then the tail doesn't matter. Anything new that suspends will work - // in the "together" mode, so we can continue from the state we had. - - - var renderState = workInProgress.memoizedState; - - if (renderState !== null) { - // Reset to the "together" mode in case we've started a different - // update in the past but didn't complete it. - renderState.rendering = null; - renderState.tail = null; - renderState.lastEffect = null; - } - - pushSuspenseContext(workInProgress, suspenseStackCursor.current); - - if (_hasChildWork) { - break; - } else { - // If none of the children had any work, that means that none of - // them got retried so they'll still be blocked in the same way - // as before. We can fast bail out. - return null; - } - } - - case OffscreenComponent: - case LegacyHiddenComponent: - { - // Need to check if the tree still needs to be deferred. This is - // almost identical to the logic used in the normal update path, - // so we'll just enter that. The only difference is we'll bail out - // at the next level instead of this one, because the child props - // have not changed. Which is fine. - // TODO: Probably should refactor `beginWork` to split the bailout - // path from the normal path. I'm tempted to do a labeled break here - // but I won't :) - workInProgress.lanes = NoLanes; - return updateOffscreenComponent(current, workInProgress, renderLanes); - } - } - - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - function beginWork(current, workInProgress, renderLanes) { - { - if (workInProgress._debugNeedsRemount && current !== null) { - // This will restart the begin phase with a new fiber. - return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes)); - } - } - - if (current !== null) { - var oldProps = current.memoizedProps; - var newProps = workInProgress.pendingProps; - - if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload: - workInProgress.type !== current.type )) { - // If props or context changed, mark the fiber as having performed work. - // This may be unset if the props are determined to be equal later (memo). - didReceiveUpdate = true; - } else { - // Neither props nor legacy context changes. Check if there's a pending - // update or context change. - var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); - - if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there - // may not be work scheduled on `current`, so we check for this flag. - (workInProgress.flags & DidCapture) === NoFlags) { - // No pending updates or context. Bail out now. - didReceiveUpdate = false; - return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes); - } - - if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { - // This is a special case that only exists for legacy mode. - // See https://github.com/facebook/react/pull/19216. - didReceiveUpdate = true; - } else { - // An update was scheduled on this fiber, but there are no new props - // nor legacy context. Set this to false. If an update queue or context - // consumer produces a changed value, it will set this to true. Otherwise, - // the component will assume the children have not changed and bail out. - didReceiveUpdate = false; - } - } - } else { - didReceiveUpdate = false; - - if (getIsHydrating() && isForkedChild(workInProgress)) { - // Check if this child belongs to a list of muliple children in - // its parent. - // - // In a true multi-threaded implementation, we would render children on - // parallel threads. This would represent the beginning of a new render - // thread for this subtree. - // - // We only use this for id generation during hydration, which is why the - // logic is located in this special branch. - var slotIndex = workInProgress.index; - var numberOfForks = getForksAtLevel(); - pushTreeId(workInProgress, numberOfForks, slotIndex); - } - } // Before entering the begin phase, clear pending update priority. - // TODO: This assumes that we're about to evaluate the component and process - // the update queue. However, there's an exception: SimpleMemoComponent - // sometimes bails out later in the begin phase. This indicates that we should - // move this assignment out of the common path and into each branch. - - - workInProgress.lanes = NoLanes; - - switch (workInProgress.tag) { - case IndeterminateComponent: - { - return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes); - } - - case LazyComponent: - { - var elementType = workInProgress.elementType; - return mountLazyComponent(current, workInProgress, elementType, renderLanes); - } - - case FunctionComponent: - { - var Component = workInProgress.type; - var unresolvedProps = workInProgress.pendingProps; - var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); - return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes); - } - - case ClassComponent: - { - var _Component = workInProgress.type; - var _unresolvedProps = workInProgress.pendingProps; - - var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps); - - return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes); - } - - case HostRoot: - return updateHostRoot(current, workInProgress, renderLanes); - - case HostComponent: - return updateHostComponent$1(current, workInProgress, renderLanes); - - case HostText: - return updateHostText$1(current, workInProgress); - - case SuspenseComponent: - return updateSuspenseComponent(current, workInProgress, renderLanes); - - case HostPortal: - return updatePortalComponent(current, workInProgress, renderLanes); - - case ForwardRef: - { - var type = workInProgress.type; - var _unresolvedProps2 = workInProgress.pendingProps; - - var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); - - return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes); - } - - case Fragment: - return updateFragment(current, workInProgress, renderLanes); - - case Mode: - return updateMode(current, workInProgress, renderLanes); - - case Profiler: - return updateProfiler(current, workInProgress, renderLanes); - - case ContextProvider: - return updateContextProvider(current, workInProgress, renderLanes); - - case ContextConsumer: - return updateContextConsumer(current, workInProgress, renderLanes); - - case MemoComponent: - { - var _type2 = workInProgress.type; - var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only - 'prop', getComponentNameFromType(_type2)); - } - } - } - - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); - return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes); - } - - case SimpleMemoComponent: - { - return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes); - } - - case IncompleteClassComponent: - { - var _Component2 = workInProgress.type; - var _unresolvedProps4 = workInProgress.pendingProps; - - var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4); - - return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes); - } - - case SuspenseListComponent: - { - return updateSuspenseListComponent(current, workInProgress, renderLanes); - } - - case ScopeComponent: - { - - break; - } - - case OffscreenComponent: - { - return updateOffscreenComponent(current, workInProgress, renderLanes); - } - } - - throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); - } - - function unwindWork(current, workInProgress, renderLanes) { - // Note: This intentionally doesn't check if we're hydrating because comparing - // to the current tree provider fiber is just as fast and less error-prone. - // Ideally we would have a special version of the work loop only - // for hydration. - popTreeContext(workInProgress); - - switch (workInProgress.tag) { - case ClassComponent: - { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - popContext(workInProgress); - } - - var flags = workInProgress.flags; - - if (flags & ShouldCapture) { - workInProgress.flags = flags & ~ShouldCapture | DidCapture; - - if ( (workInProgress.mode & ProfileMode) !== NoMode) { - transferActualDuration(workInProgress); - } - - return workInProgress; - } - - return null; - } - - case HostRoot: - { - - popHostContainer(workInProgress); - popTopLevelContextObject(workInProgress); - resetWorkInProgressVersions(); - var _flags = workInProgress.flags; - - if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) { - // There was an error during render that wasn't captured by a suspense - // boundary. Do a second pass on the root to unmount the children. - workInProgress.flags = _flags & ~ShouldCapture | DidCapture; - return workInProgress; - } // We unwound to the root without completing it. Exit. - - - return null; - } - - case HostComponent: - { - // TODO: popHydrationState - popHostContext(workInProgress); - return null; - } - - case SuspenseComponent: - { - popSuspenseContext(workInProgress); - - { - var suspenseState = workInProgress.memoizedState; - - if (suspenseState !== null && suspenseState.dehydrated !== null) { - if (workInProgress.alternate === null) { - throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.'); - } - - resetHydrationState(); - } - } - - var _flags2 = workInProgress.flags; - - if (_flags2 & ShouldCapture) { - workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary. - - if ( (workInProgress.mode & ProfileMode) !== NoMode) { - transferActualDuration(workInProgress); - } - - return workInProgress; - } - - return null; - } - - case SuspenseListComponent: - { - popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been - // caught by a nested boundary. If not, it should bubble through. - - return null; - } - - case HostPortal: - popHostContainer(workInProgress); - return null; - - case ContextProvider: - var context = workInProgress.type._context; - popProvider(context, workInProgress); - return null; - - case OffscreenComponent: - case LegacyHiddenComponent: - popRenderLanes(workInProgress); - - return null; - - case CacheComponent: - - return null; - - default: - return null; - } - } - - function unwindInterruptedWork(current, interruptedWork, renderLanes) { - // Note: This intentionally doesn't check if we're hydrating because comparing - // to the current tree provider fiber is just as fast and less error-prone. - // Ideally we would have a special version of the work loop only - // for hydration. - popTreeContext(interruptedWork); - - switch (interruptedWork.tag) { - case ClassComponent: - { - var childContextTypes = interruptedWork.type.childContextTypes; - - if (childContextTypes !== null && childContextTypes !== undefined) { - popContext(interruptedWork); - } - - break; - } - - case HostRoot: - { - - popHostContainer(interruptedWork); - popTopLevelContextObject(interruptedWork); - resetWorkInProgressVersions(); - break; - } - - case HostComponent: - { - popHostContext(interruptedWork); - break; - } - - case HostPortal: - popHostContainer(interruptedWork); - break; - - case SuspenseComponent: - popSuspenseContext(interruptedWork); - break; - - case SuspenseListComponent: - popSuspenseContext(interruptedWork); - break; - - case ContextProvider: - var context = interruptedWork.type._context; - popProvider(context, interruptedWork); - break; - - case OffscreenComponent: - case LegacyHiddenComponent: - popRenderLanes(interruptedWork); - - break; - } - } - - function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) { - var funcArgs = Array.prototype.slice.call(arguments, 3); - - try { - func.apply(context, funcArgs); - } catch (error) { - this.onError(error); - } - } - - var invokeGuardedCallbackImpl = invokeGuardedCallbackProd; - - { - // In DEV mode, we swap out invokeGuardedCallback for a special version - // that plays more nicely with the browser's DevTools. The idea is to preserve - // "Pause on exceptions" behavior. Because React wraps all user-provided - // functions in invokeGuardedCallback, and the production version of - // invokeGuardedCallback uses a try-catch, all user exceptions are treated - // like caught exceptions, and the DevTools won't pause unless the developer - // takes the extra step of enabling pause on caught exceptions. This is - // unintuitive, though, because even though React has caught the error, from - // the developer's perspective, the error is uncaught. - // - // To preserve the expected "Pause on exceptions" behavior, we don't use a - // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake - // DOM node, and call the user-provided callback from inside an event handler - // for that fake event. If the callback throws, the error is "captured" using - // a global event handler. But because the error happens in a different - // event loop context, it does not interrupt the normal program flow. - // Effectively, this gives us try-catch behavior without actually using - // try-catch. Neat! - // Check that the browser supports the APIs we need to implement our special - // DEV version of invokeGuardedCallback - if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { - var fakeNode = document.createElement('react'); - - invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) { - // If document doesn't exist we know for sure we will crash in this method - // when we call document.createEvent(). However this can cause confusing - // errors: https://github.com/facebook/create-react-app/issues/3482 - // So we preemptively throw with a better message instead. - if (typeof document === 'undefined' || document === null) { - throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.'); - } - - var evt = document.createEvent('Event'); - var didCall = false; // Keeps track of whether the user-provided callback threw an error. We - // set this to true at the beginning, then set it to false right after - // calling the function. If the function errors, `didError` will never be - // set to false. This strategy works even if the browser is flaky and - // fails to call our global error handler, because it doesn't rely on - // the error event at all. - - var didError = true; // Keeps track of the value of window.event so that we can reset it - // during the callback to let user code access window.event in the - // browsers that support it. - - var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event - // dispatching: https://github.com/facebook/react/issues/13688 - - var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); - - function restoreAfterDispatch() { - // We immediately remove the callback from event listeners so that - // nested `invokeGuardedCallback` calls do not clash. Otherwise, a - // nested call would trigger the fake event handlers of any call higher - // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the - // window.event assignment in both IE <= 10 as they throw an error - // "Member not found" in strict mode, and in Firefox which does not - // support window.event. - - if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) { - window.event = windowEvent; - } - } // Create an event handler for our fake event. We will synchronously - // dispatch our fake event using `dispatchEvent`. Inside the handler, we - // call the user-provided callback. - - - var funcArgs = Array.prototype.slice.call(arguments, 3); - - function callCallback() { - didCall = true; - restoreAfterDispatch(); - func.apply(context, funcArgs); - didError = false; - } // Create a global error event handler. We use this to capture the value - // that was thrown. It's possible that this error handler will fire more - // than once; for example, if non-React code also calls `dispatchEvent` - // and a handler for that event throws. We should be resilient to most of - // those cases. Even if our error event handler fires more than once, the - // last error event is always used. If the callback actually does error, - // we know that the last error event is the correct one, because it's not - // possible for anything else to have happened in between our callback - // erroring and the code that follows the `dispatchEvent` call below. If - // the callback doesn't error, but the error event was fired, we know to - // ignore it because `didError` will be false, as described above. - - - var error; // Use this to track whether the error event is ever called. - - var didSetError = false; - var isCrossOriginError = false; - - function handleWindowError(event) { - error = event.error; - didSetError = true; - - if (error === null && event.colno === 0 && event.lineno === 0) { - isCrossOriginError = true; - } - - if (event.defaultPrevented) { - // Some other error handler has prevented default. - // Browsers silence the error report if this happens. - // We'll remember this to later decide whether to log it or not. - if (error != null && typeof error === 'object') { - try { - error._suppressLogging = true; - } catch (inner) {// Ignore. - } - } - } - } // Create a fake event type. - - - var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers - - window.addEventListener('error', handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function - // errors, it will trigger our global error handler. - - evt.initEvent(evtType, false, false); - fakeNode.dispatchEvent(evt); - - if (windowEventDescriptor) { - Object.defineProperty(window, 'event', windowEventDescriptor); - } - - if (didCall && didError) { - if (!didSetError) { - // The callback errored, but the error event never fired. - // eslint-disable-next-line react-internal/prod-error-codes - error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); - } else if (isCrossOriginError) { - // eslint-disable-next-line react-internal/prod-error-codes - error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.'); - } - - this.onError(error); - } // Remove our event listeners - - - window.removeEventListener('error', handleWindowError); - - if (!didCall) { - // Something went really wrong, and our event was not dispatched. - // https://github.com/facebook/react/issues/16734 - // https://github.com/facebook/react/issues/16585 - // Fall back to the production implementation. - restoreAfterDispatch(); - return invokeGuardedCallbackProd.apply(this, arguments); - } - }; - } - } - - var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; - - var hasError = false; - var caughtError = null; // Used by event system to capture/rethrow the first error. - var reporter = { - onError: function (error) { - hasError = true; - caughtError = error; - } - }; - /** - * Call a function while guarding against errors that happens within it. - * Returns an error if it throws, otherwise null. - * - * In production, this is implemented using a try-catch. The reason we don't - * use a try-catch directly is so that we can swap out a different - * implementation in DEV mode. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - - function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = false; - caughtError = null; - invokeGuardedCallbackImpl$1.apply(reporter, arguments); - } - function hasCaughtError() { - return hasError; - } - function clearCaughtError() { - if (hasError) { - var error = caughtError; - hasError = false; - caughtError = null; - return error; - } else { - throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.'); - } - } - - var didWarnAboutUndefinedSnapshotBeforeUpdate = null; - - { - didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); - } // Used during the commit phase to track the state of the Offscreen component stack. - // Allows us to avoid traversing the return path to find the nearest Offscreen ancestor. - // Only used when enableSuspenseLayoutEffectSemantics is enabled. - - - var offscreenSubtreeIsHidden = false; - var offscreenSubtreeWasHidden = false; - var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; - var nextEffect = null; // Used for Profiling builds to track updaters. - - var inProgressLanes = null; - var inProgressRoot = null; - - function reportUncaughtErrorInDEV(error) { - // Wrapping each small part of the commit phase into a guarded - // callback is a bit too slow (https://github.com/facebook/react/pull/21666). - // But we rely on it to surface errors to DEV tools like overlays - // (https://github.com/facebook/react/issues/21712). - // As a compromise, rethrow only caught errors in a guard. - { - invokeGuardedCallback(null, function () { - throw error; - }); - clearCaughtError(); - } - } - - var callComponentWillUnmountWithTimer = function (current, instance) { - instance.props = current.memoizedProps; - instance.state = current.memoizedState; - - if ( current.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - instance.componentWillUnmount(); - } finally { - recordLayoutEffectDuration(current); - } - } else { - instance.componentWillUnmount(); - } - }; // Capture errors so they don't interrupt mounting. - - - function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) { - try { - commitHookEffectListMount(Layout, current); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } // Capture errors so they don't interrupt unmounting. - - - function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) { - try { - callComponentWillUnmountWithTimer(current, instance); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } // Capture errors so they don't interrupt mounting. - - - function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) { - try { - instance.componentDidMount(); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } // Capture errors so they don't interrupt mounting. - - - function safelyAttachRef(current, nearestMountedAncestor) { - try { - commitAttachRef(current); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } - - function safelyDetachRef(current, nearestMountedAncestor) { - var ref = current.ref; - - if (ref !== null) { - if (typeof ref === 'function') { - var retVal; - - try { - if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - retVal = ref(null); - } finally { - recordLayoutEffectDuration(current); - } - } else { - retVal = ref(null); - } - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - - { - if (typeof retVal === 'function') { - error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current)); - } - } - } else { - ref.current = null; - } - } - } - - function safelyCallDestroy(current, nearestMountedAncestor, destroy) { - try { - destroy(); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } - var shouldFireAfterActiveInstanceBlur = false; - function commitBeforeMutationEffects(root, firstChild) { - prepareForCommit(root.containerInfo); - nextEffect = firstChild; - commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber - - var shouldFire = shouldFireAfterActiveInstanceBlur; - shouldFireAfterActiveInstanceBlur = false; - return shouldFire; - } - - function commitBeforeMutationEffects_begin() { - while (nextEffect !== null) { - var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur. - - var child = fiber.child; - - if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) { - ensureCorrectReturnPointer(child, fiber); - nextEffect = child; - } else { - commitBeforeMutationEffects_complete(); - } - } - } - - function commitBeforeMutationEffects_complete() { - while (nextEffect !== null) { - var fiber = nextEffect; - setCurrentFiber(fiber); - - try { - commitBeforeMutationEffectsOnFiber(fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitBeforeMutationEffectsOnFiber(finishedWork) { - var current = finishedWork.alternate; - var flags = finishedWork.flags; - - if ((flags & Snapshot) !== NoFlags) { - setCurrentFiber(finishedWork); - - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - break; - } - - case ClassComponent: - { - if (current !== null) { - var prevProps = current.memoizedProps; - var prevState = current.memoizedState; - var instance = finishedWork.stateNode; // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - - if (instance.state !== finishedWork.memoizedState) { - error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - } - } - - var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState); - - { - var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; - - if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { - didWarnSet.add(finishedWork.type); - - error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork)); - } - } - - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - - break; - } - - case HostRoot: - { - if (supportsMutation) { - var root = finishedWork.stateNode; - clearContainer(root.containerInfo); - } - - break; - } - - case HostComponent: - case HostText: - case HostPortal: - case IncompleteClassComponent: - // Nothing to do for these component types - break; - - default: - { - throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); - } - } - - resetCurrentFiber(); - } - } - - function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) { - var updateQueue = finishedWork.updateQueue; - var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - var effect = firstEffect; - - do { - if ((effect.tag & flags) === flags) { - // Unmount - var destroy = effect.destroy; - effect.destroy = undefined; - - if (destroy !== undefined) { - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectUnmountStarted(finishedWork); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectUnmountStarted(finishedWork); - } - } - - safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); - - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectUnmountStopped(); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectUnmountStopped(); - } - } - } - } - - effect = effect.next; - } while (effect !== firstEffect); - } - } - - function commitHookEffectListMount(flags, finishedWork) { - var updateQueue = finishedWork.updateQueue; - var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - var effect = firstEffect; - - do { - if ((effect.tag & flags) === flags) { - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectMountStarted(finishedWork); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectMountStarted(finishedWork); - } - } // Mount - - - var create = effect.create; - effect.destroy = create(); - - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectMountStopped(); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectMountStopped(); - } - } - - { - var destroy = effect.destroy; - - if (destroy !== undefined && typeof destroy !== 'function') { - var hookName = void 0; - - if ((effect.tag & Layout) !== NoFlags) { - hookName = 'useLayoutEffect'; - } else if ((effect.tag & Insertion) !== NoFlags) { - hookName = 'useInsertionEffect'; - } else { - hookName = 'useEffect'; - } - - var addendum = void 0; - - if (destroy === null) { - addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).'; - } else if (typeof destroy.then === 'function') { - addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching'; - } else { - addendum = ' You returned: ' + destroy; - } - - error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum); - } - } - } - - effect = effect.next; - } while (effect !== firstEffect); - } - } - - function commitPassiveEffectDurations(finishedRoot, finishedWork) { - { - // Only Profilers with work in their subtree will have an Update effect scheduled. - if ((finishedWork.flags & Update) !== NoFlags) { - switch (finishedWork.tag) { - case Profiler: - { - var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration; - var _finishedWork$memoize = finishedWork.memoizedProps, - id = _finishedWork$memoize.id, - onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase. - // It does not get reset until the start of the next commit phase. - - var commitTime = getCommitTime(); - var phase = finishedWork.alternate === null ? 'mount' : 'update'; - - { - if (isCurrentUpdateNested()) { - phase = 'nested-update'; - } - } - - if (typeof onPostCommit === 'function') { - onPostCommit(id, phase, passiveEffectDuration, commitTime); - } // Bubble times to the next nearest ancestor Profiler. - // After we process that Profiler, we'll bubble further up. - - - var parentFiber = finishedWork.return; - - outer: while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - root.passiveEffectDuration += passiveEffectDuration; - break outer; - - case Profiler: - var parentStateNode = parentFiber.stateNode; - parentStateNode.passiveEffectDuration += passiveEffectDuration; - break outer; - } - - parentFiber = parentFiber.return; - } - - break; - } - } - } - } - } - - function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) { - if ((finishedWork.flags & LayoutMask) !== NoFlags) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( !offscreenSubtreeWasHidden) { - // At this point layout effects have already been destroyed (during mutation phase). - // This is done to prevent sibling component effects from interfering with each other, - // e.g. a destroy function in one component should never override a ref set - // by a create function in another component during the same commit. - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListMount(Layout | HasEffect, finishedWork); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - commitHookEffectListMount(Layout | HasEffect, finishedWork); - } - } - - break; - } - - case ClassComponent: - { - var instance = finishedWork.stateNode; - - if (finishedWork.flags & Update) { - if (!offscreenSubtreeWasHidden) { - if (current === null) { - // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - - if (instance.state !== finishedWork.memoizedState) { - error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - } - } - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - instance.componentDidMount(); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - instance.componentDidMount(); - } - } else { - var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps); - var prevState = current.memoizedState; // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - - if (instance.state !== finishedWork.memoizedState) { - error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - } - } - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); - } - } - } - } // TODO: I think this is now always non-null by the time it reaches the - // commit phase. Consider removing the type check. - - - var updateQueue = finishedWork.updateQueue; - - if (updateQueue !== null) { - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - - if (instance.state !== finishedWork.memoizedState) { - error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - } - } // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - - - commitUpdateQueue(finishedWork, updateQueue, instance); - } - - break; - } - - case HostRoot: - { - // TODO: I think this is now always non-null by the time it reaches the - // commit phase. Consider removing the type check. - var _updateQueue = finishedWork.updateQueue; - - if (_updateQueue !== null) { - var _instance = null; - - if (finishedWork.child !== null) { - switch (finishedWork.child.tag) { - case HostComponent: - _instance = getPublicInstance(finishedWork.child.stateNode); - break; - - case ClassComponent: - _instance = finishedWork.child.stateNode; - break; - } - } - - commitUpdateQueue(finishedWork, _updateQueue, _instance); - } - - break; - } - - case HostComponent: - { - var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted - // (eg DOM renderer may schedule auto-focus for inputs and form controls). - // These effects should only be committed when components are first mounted, - // aka when there is no current/alternate. - - if (current === null && finishedWork.flags & Update) { - var type = finishedWork.type; - var props = finishedWork.memoizedProps; - commitMount(_instance2, type, props, finishedWork); - } - - break; - } - - case HostText: - { - // We have no life-cycles associated with text. - break; - } - - case HostPortal: - { - // We have no life-cycles associated with portals. - break; - } - - case Profiler: - { - { - var _finishedWork$memoize2 = finishedWork.memoizedProps, - onCommit = _finishedWork$memoize2.onCommit, - onRender = _finishedWork$memoize2.onRender; - var effectDuration = finishedWork.stateNode.effectDuration; - var commitTime = getCommitTime(); - var phase = current === null ? 'mount' : 'update'; - - { - if (isCurrentUpdateNested()) { - phase = 'nested-update'; - } - } - - if (typeof onRender === 'function') { - onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime); - } - - { - if (typeof onCommit === 'function') { - onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime); - } // Schedule a passive effect for this Profiler to call onPostCommit hooks. - // This effect should be scheduled even if there is no onPostCommit callback for this Profiler, - // because the effect is also where times bubble to parent Profilers. - - - enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor. - // Do not reset these values until the next render so DevTools has a chance to read them first. - - var parentFiber = finishedWork.return; - - outer: while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - root.effectDuration += effectDuration; - break outer; - - case Profiler: - var parentStateNode = parentFiber.stateNode; - parentStateNode.effectDuration += effectDuration; - break outer; - } - - parentFiber = parentFiber.return; - } - } - } - - break; - } - - case SuspenseComponent: - { - commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); - break; - } - - case SuspenseListComponent: - case IncompleteClassComponent: - case ScopeComponent: - case OffscreenComponent: - case LegacyHiddenComponent: - { - break; - } - - default: - throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); - } - } - - if ( !offscreenSubtreeWasHidden) { - { - if (finishedWork.flags & Ref) { - commitAttachRef(finishedWork); - } - } - } - } - - function reappearLayoutEffectsOnFiber(node) { - // Turn on layout effects in a tree that previously disappeared. - // TODO (Offscreen) Check: flags & LayoutStatic - switch (node.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( node.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - safelyCallCommitHookLayoutEffectListMount(node, node.return); - } finally { - recordLayoutEffectDuration(node); - } - } else { - safelyCallCommitHookLayoutEffectListMount(node, node.return); - } - - break; - } - - case ClassComponent: - { - var instance = node.stateNode; - - if (typeof instance.componentDidMount === 'function') { - safelyCallComponentDidMount(node, node.return, instance); - } - - safelyAttachRef(node, node.return); - break; - } - - case HostComponent: - { - safelyAttachRef(node, node.return); - break; - } - } - } - - function hideOrUnhideAllChildren(finishedWork, isHidden) { - // Only hide or unhide the top-most host nodes. - var hostSubtreeRoot = null; - - if (supportsMutation) { - // We only have the top Fiber that was inserted but we need to recurse down its - // children to find all the terminal nodes. - var node = finishedWork; - - while (true) { - if (node.tag === HostComponent) { - if (hostSubtreeRoot === null) { - hostSubtreeRoot = node; - var instance = node.stateNode; - - if (isHidden) { - hideInstance(instance); - } else { - unhideInstance(node.stateNode, node.memoizedProps); - } - } - } else if (node.tag === HostText) { - if (hostSubtreeRoot === null) { - var _instance3 = node.stateNode; - - if (isHidden) { - hideTextInstance(_instance3); - } else { - unhideTextInstance(_instance3, node.memoizedProps); - } - } - } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === finishedWork) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === finishedWork) { - return; - } - - if (hostSubtreeRoot === node) { - hostSubtreeRoot = null; - } - - node = node.return; - } - - if (hostSubtreeRoot === node) { - hostSubtreeRoot = null; - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - } - - function commitAttachRef(finishedWork) { - var ref = finishedWork.ref; - - if (ref !== null) { - var instance = finishedWork.stateNode; - var instanceToUse; - - switch (finishedWork.tag) { - case HostComponent: - instanceToUse = getPublicInstance(instance); - break; - - default: - instanceToUse = instance; - } // Moved outside to ensure DCE works with this flag - - if (typeof ref === 'function') { - var retVal; - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - retVal = ref(instanceToUse); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - retVal = ref(instanceToUse); - } - - { - if (typeof retVal === 'function') { - error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork)); - } - } - } else { - { - if (!ref.hasOwnProperty('current')) { - error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork)); - } - } - - ref.current = instanceToUse; - } - } - } - - function commitDetachRef(current) { - var currentRef = current.ref; - - if (currentRef !== null) { - if (typeof currentRef === 'function') { - if ( current.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - currentRef(null); - } finally { - recordLayoutEffectDuration(current); - } - } else { - currentRef(null); - } - } else { - currentRef.current = null; - } - } - } // User-originating errors (lifecycles and refs) should not interrupt - // deletion, so don't let them throw. Host-originating errors should - // interrupt deletion, so it's okay - - - function commitUnmount(finishedRoot, current, nearestMountedAncestor) { - onCommitUnmount(current); - - switch (current.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: - { - var updateQueue = current.updateQueue; - - if (updateQueue !== null) { - var lastEffect = updateQueue.lastEffect; - - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - var effect = firstEffect; - - do { - var _effect = effect, - destroy = _effect.destroy, - tag = _effect.tag; - - if (destroy !== undefined) { - if ((tag & Insertion) !== NoFlags$1) { - safelyCallDestroy(current, nearestMountedAncestor, destroy); - } else if ((tag & Layout) !== NoFlags$1) { - { - markComponentLayoutEffectUnmountStarted(current); - } - - if ( current.mode & ProfileMode) { - startLayoutEffectTimer(); - safelyCallDestroy(current, nearestMountedAncestor, destroy); - recordLayoutEffectDuration(current); - } else { - safelyCallDestroy(current, nearestMountedAncestor, destroy); - } - - { - markComponentLayoutEffectUnmountStopped(); - } - } - } - - effect = effect.next; - } while (effect !== firstEffect); - } - } - - return; - } - - case ClassComponent: - { - safelyDetachRef(current, nearestMountedAncestor); - var instance = current.stateNode; - - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance); - } - - return; - } - - case HostComponent: - { - safelyDetachRef(current, nearestMountedAncestor); - return; - } - - case HostPortal: - { - // TODO: this is recursive. - // We are also not using this parent because - // the portal will get pushed immediately. - if (supportsMutation) { - unmountHostComponents(finishedRoot, current, nearestMountedAncestor); - } else if (supportsPersistence) { - emptyPortalContainer(current); - } - - return; - } - - case DehydratedFragment: - { - - return; - } - - case ScopeComponent: - { - - return; - } - } - } - - function commitNestedUnmounts(finishedRoot, root, nearestMountedAncestor) { - // While we're inside a removed host node we don't want to call - // removeChild on the inner nodes because they're removed by the top - // call anyway. We also want to call componentWillUnmount on all - // composites before this host node is removed from the tree. Therefore - // we do an inner loop while we're still inside the host node. - var node = root; - - while (true) { - commitUnmount(finishedRoot, node, nearestMountedAncestor); // Visit children because they may contain more composite or host nodes. - // Skip portals because commitUnmount() currently visits them recursively. - - if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above. - // If we don't use mutation we drill down into portals here instead. - !supportsMutation || node.tag !== HostPortal)) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === root) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === root) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - - function detachFiberMutation(fiber) { - // Cut off the return pointer to disconnect it from the tree. - // This enables us to detect and warn against state updates on an unmounted component. - // It also prevents events from bubbling from within disconnected components. - // - // Ideally, we should also clear the child pointer of the parent alternate to let this - // get GC:ed but we don't know which for sure which parent is the current - // one so we'll settle for GC:ing the subtree of this child. - // This child itself will be GC:ed when the parent updates the next time. - // - // Note that we can't clear child or sibling pointers yet. - // They're needed for passive effects and for findDOMNode. - // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects). - // - // Don't reset the alternate yet, either. We need that so we can detach the - // alternate's fields in the passive phase. Clearing the return pointer is - // sufficient for findDOMNode semantics. - var alternate = fiber.alternate; - - if (alternate !== null) { - alternate.return = null; - } - - fiber.return = null; - } - - function detachFiberAfterEffects(fiber) { - var alternate = fiber.alternate; - - if (alternate !== null) { - fiber.alternate = null; - detachFiberAfterEffects(alternate); - } // Note: Defensively using negation instead of < in case - // `deletedTreeCleanUpLevel` is undefined. - - - { - // Clear cyclical Fiber fields. This level alone is designed to roughly - // approximate the planned Fiber refactor. In that world, `setState` will be - // bound to a special "instance" object instead of a Fiber. The Instance - // object will not have any of these fields. It will only be connected to - // the fiber tree via a single link at the root. So if this level alone is - // sufficient to fix memory issues, that bodes well for our plans. - fiber.child = null; - fiber.deletions = null; - fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host - // tree, which has its own pointers to children, parents, and siblings. - // The other host nodes also point back to fibers, so we should detach that - // one, too. - - if (fiber.tag === HostComponent) { - var hostInstance = fiber.stateNode; - - if (hostInstance !== null) { - detachDeletedInstance(hostInstance); - } - } - - fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We - // already disconnect the `return` pointer at the root of the deleted - // subtree (in `detachFiberMutation`). Besides, `return` by itself is not - // cyclical — it's only cyclical when combined with `child`, `sibling`, and - // `alternate`. But we'll clear it in the next level anyway, just in case. - - { - fiber._debugOwner = null; - } - - { - // Theoretically, nothing in here should be necessary, because we already - // disconnected the fiber from the tree. So even if something leaks this - // particular fiber, it won't leak anything else - // - // The purpose of this branch is to be super aggressive so we can measure - // if there's any difference in memory impact. If there is, that could - // indicate a React leak we don't know about. - fiber.return = null; - fiber.dependencies = null; - fiber.memoizedProps = null; - fiber.memoizedState = null; - fiber.pendingProps = null; - fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead. - - fiber.updateQueue = null; - } - } - } - - function emptyPortalContainer(current) { - if (!supportsPersistence) { - return; - } - - var portal = current.stateNode; - var containerInfo = portal.containerInfo; - var emptyChildSet = createContainerChildSet(containerInfo); - replaceContainerChildren(containerInfo, emptyChildSet); - } - - function commitContainer(finishedWork) { - if (!supportsPersistence) { - return; - } - - switch (finishedWork.tag) { - case ClassComponent: - case HostComponent: - case HostText: - { - return; - } - - case HostRoot: - case HostPortal: - { - var portalOrRoot = finishedWork.stateNode; - var containerInfo = portalOrRoot.containerInfo, - pendingChildren = portalOrRoot.pendingChildren; - replaceContainerChildren(containerInfo, pendingChildren); - return; - } - } - - throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); - } - - function getHostParentFiber(fiber) { - var parent = fiber.return; - - while (parent !== null) { - if (isHostParent(parent)) { - return parent; - } - - parent = parent.return; - } - - throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.'); - } - - function isHostParent(fiber) { - return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; - } - - function getHostSibling(fiber) { - // We're going to search forward into the tree until we find a sibling host - // node. Unfortunately, if multiple insertions are done in a row we have to - // search past them. This leads to exponential search for the next sibling. - // TODO: Find a more efficient way to do this. - var node = fiber; - - siblings: while (true) { - // If we didn't find anything, let's try the next sibling. - while (node.sibling === null) { - if (node.return === null || isHostParent(node.return)) { - // If we pop out of the root or hit the parent the fiber we are the - // last sibling. - return null; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - - while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) { - // If it is not host node and, we might have a host node inside it. - // Try to search down until we find one. - if (node.flags & Placement) { - // If we don't have a child, try the siblings instead. - continue siblings; - } // If we don't have a child, try the siblings instead. - // We also skip portals because they are not part of this host tree. - - - if (node.child === null || node.tag === HostPortal) { - continue siblings; - } else { - node.child.return = node; - node = node.child; - } - } // Check if this host node is stable or about to be placed. - - - if (!(node.flags & Placement)) { - // Found it! - return node.stateNode; - } - } - } - - function commitPlacement(finishedWork) { - if (!supportsMutation) { - return; - } // Recursively insert all host nodes into the parent. - - - var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. - - switch (parentFiber.tag) { - case HostComponent: - { - var parent = parentFiber.stateNode; - - if (parentFiber.flags & ContentReset) { - // Reset the text content of the parent before doing any insertions - resetTextContent(parent); // Clear ContentReset from the effect tag - - parentFiber.flags &= ~ContentReset; - } - - var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its - // children to find all the terminal nodes. - - insertOrAppendPlacementNode(finishedWork, before, parent); - break; - } - - case HostRoot: - case HostPortal: - { - var _parent = parentFiber.stateNode.containerInfo; - - var _before = getHostSibling(finishedWork); - - insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent); - break; - } - // eslint-disable-next-line-no-fallthrough - - default: - throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.'); - } - } - - function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { - var tag = node.tag; - var isHost = tag === HostComponent || tag === HostText; - - if (isHost) { - var stateNode = node.stateNode; - - if (before) { - insertInContainerBefore(parent, stateNode, before); - } else { - appendChildToContainer(parent, stateNode); - } - } else if (tag === HostPortal) ; else { - var child = node.child; - - if (child !== null) { - insertOrAppendPlacementNodeIntoContainer(child, before, parent); - var sibling = child.sibling; - - while (sibling !== null) { - insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); - sibling = sibling.sibling; - } - } - } - } - - function insertOrAppendPlacementNode(node, before, parent) { - var tag = node.tag; - var isHost = tag === HostComponent || tag === HostText; - - if (isHost) { - var stateNode = node.stateNode; - - if (before) { - insertBefore(parent, stateNode, before); - } else { - appendChild(parent, stateNode); - } - } else if (tag === HostPortal) ; else { - var child = node.child; - - if (child !== null) { - insertOrAppendPlacementNode(child, before, parent); - var sibling = child.sibling; - - while (sibling !== null) { - insertOrAppendPlacementNode(sibling, before, parent); - sibling = sibling.sibling; - } - } - } - } - - function unmountHostComponents(finishedRoot, current, nearestMountedAncestor) { - // We only have the top Fiber that was deleted but we need to recurse down its - // children to find all the terminal nodes. - var node = current; // Each iteration, currentParent is populated with node's host parent if not - // currentParentIsValid. - - var currentParentIsValid = false; // Note: these two variables *must* always be updated together. - - var currentParent; - var currentParentIsContainer; - - while (true) { - if (!currentParentIsValid) { - var parent = node.return; - - findParent: while (true) { - if (parent === null) { - throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.'); - } - - var parentStateNode = parent.stateNode; - - switch (parent.tag) { - case HostComponent: - currentParent = parentStateNode; - currentParentIsContainer = false; - break findParent; - - case HostRoot: - currentParent = parentStateNode.containerInfo; - currentParentIsContainer = true; - break findParent; - - case HostPortal: - currentParent = parentStateNode.containerInfo; - currentParentIsContainer = true; - break findParent; - } - - parent = parent.return; - } - - currentParentIsValid = true; - } - - if (node.tag === HostComponent || node.tag === HostText) { - commitNestedUnmounts(finishedRoot, node, nearestMountedAncestor); // After all the children have unmounted, it is now safe to remove the - // node from the tree. - - if (currentParentIsContainer) { - removeChildFromContainer(currentParent, node.stateNode); - } else { - removeChild(currentParent, node.stateNode); - } // Don't visit children because we already visited them. - - } else if ( node.tag === DehydratedFragment) { - - - if (currentParentIsContainer) { - clearSuspenseBoundaryFromContainer(currentParent, node.stateNode); - } else { - clearSuspenseBoundary(currentParent, node.stateNode); - } - } else if (node.tag === HostPortal) { - if (node.child !== null) { - // When we go into a portal, it becomes the parent to remove from. - // We will reassign it back when we pop the portal on the way up. - currentParent = node.stateNode.containerInfo; - currentParentIsContainer = true; // Visit children because portals might contain host components. - - node.child.return = node; - node = node.child; - continue; - } - } else { - commitUnmount(finishedRoot, node, nearestMountedAncestor); // Visit children because we may find more host components below. - - if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - } - - if (node === current) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === current) { - return; - } - - node = node.return; - - if (node.tag === HostPortal) { - // When we go out of the portal, we need to restore the parent. - // Since we don't keep a stack of them, we will search for it. - currentParentIsValid = false; - } - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - - function commitDeletion(finishedRoot, current, nearestMountedAncestor) { - if (supportsMutation) { - // Recursively delete all host nodes from the parent. - // Detach refs and call componentWillUnmount() on the whole subtree. - unmountHostComponents(finishedRoot, current, nearestMountedAncestor); - } else { - // Detach refs and call componentWillUnmount() on the whole subtree. - commitNestedUnmounts(finishedRoot, current, nearestMountedAncestor); - } - - detachFiberMutation(current); - } - - function commitWork(current, finishedWork) { - if (!supportsMutation) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: - { - commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); - commitHookEffectListMount(Insertion | HasEffect, finishedWork); // Layout effects are destroyed during the mutation phase so that all - // destroy functions for all fibers are called before any create functions. - // This prevents sibling component effects from interfering with each other, - // e.g. a destroy function in one component should never override a ref set - // by a create function in another component during the same commit. - // TODO: Check if we're inside an Offscreen subtree that disappeared - // during this commit. If so, we would have already unmounted its - // layout hooks. (However, since we null out the `destroy` function - // right before calling it, the behavior is already correct, so this - // would mostly be for modeling purposes.) - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } - - return; - } - - case Profiler: - { - return; - } - - case SuspenseComponent: - { - commitSuspenseCallback(finishedWork); - attachSuspenseRetryListeners(finishedWork); - return; - } - - case SuspenseListComponent: - { - attachSuspenseRetryListeners(finishedWork); - return; - } - - case HostRoot: - { - if (supportsHydration) { - if (current !== null) { - var prevRootState = current.memoizedState; - - if (prevRootState.isDehydrated) { - var root = finishedWork.stateNode; - commitHydratedContainer(root.containerInfo); - } - } - } - - break; - } - - case OffscreenComponent: - case LegacyHiddenComponent: - { - return; - } - } - - commitContainer(finishedWork); - return; - } - - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: - { - commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); - commitHookEffectListMount(Insertion | HasEffect, finishedWork); // Layout effects are destroyed during the mutation phase so that all - // destroy functions for all fibers are called before any create functions. - // This prevents sibling component effects from interfering with each other, - // e.g. a destroy function in one component should never override a ref set - // by a create function in another component during the same commit. - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } - - return; - } - - case ClassComponent: - { - return; - } - - case HostComponent: - { - var instance = finishedWork.stateNode; - - if (instance != null) { - // Commit the work prepared earlier. - var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps - // as the newProps. The updatePayload will contain the real change in - // this case. - - var oldProps = current !== null ? current.memoizedProps : newProps; - var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. - - var updatePayload = finishedWork.updateQueue; - finishedWork.updateQueue = null; - - if (updatePayload !== null) { - commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork); - } - } - - return; - } - - case HostText: - { - if (finishedWork.stateNode === null) { - throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.'); - } - - var textInstance = finishedWork.stateNode; - var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps - // as the newProps. The updatePayload will contain the real change in - // this case. - - var oldText = current !== null ? current.memoizedProps : newText; - commitTextUpdate(textInstance, oldText, newText); - return; - } - - case HostRoot: - { - if (supportsHydration) { - if (current !== null) { - var _prevRootState = current.memoizedState; - - if (_prevRootState.isDehydrated) { - var _root = finishedWork.stateNode; - commitHydratedContainer(_root.containerInfo); - } - } - } - - return; - } - - case Profiler: - { - return; - } - - case SuspenseComponent: - { - commitSuspenseCallback(finishedWork); - attachSuspenseRetryListeners(finishedWork); - return; - } - - case SuspenseListComponent: - { - attachSuspenseRetryListeners(finishedWork); - return; - } - - case IncompleteClassComponent: - { - return; - } - } - - throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); - } - - function commitSuspenseCallback(finishedWork) { - // TODO: Move this to passive phase - finishedWork.memoizedState; - } - - function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { - if (!supportsHydration) { - return; - } - - var newState = finishedWork.memoizedState; - - if (newState === null) { - var current = finishedWork.alternate; - - if (current !== null) { - var prevState = current.memoizedState; - - if (prevState !== null) { - var suspenseInstance = prevState.dehydrated; - - if (suspenseInstance !== null) { - commitHydratedSuspenseInstance(suspenseInstance); - } - } - } - } - } - - function attachSuspenseRetryListeners(finishedWork) { - // If this boundary just timed out, then it will have a set of wakeables. - // For each wakeable, attach a listener so that when it resolves, React - // attempts to re-render the boundary in the primary (pre-timeout) state. - var wakeables = finishedWork.updateQueue; - - if (wakeables !== null) { - finishedWork.updateQueue = null; - var retryCache = finishedWork.stateNode; - - if (retryCache === null) { - retryCache = finishedWork.stateNode = new PossiblyWeakSet(); - } - - wakeables.forEach(function (wakeable) { - // Memoize using the boundary fiber to prevent redundant listeners. - var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - - if (!retryCache.has(wakeable)) { - retryCache.add(wakeable); - - { - if (isDevToolsPresent) { - if (inProgressLanes !== null && inProgressRoot !== null) { - // If we have pending work still, associate the original updaters with it. - restorePendingUpdaters(inProgressRoot, inProgressLanes); - } else { - throw Error('Expected finished root and lanes to be set. This is a bug in React.'); - } - } - } - - wakeable.then(retry, retry); - } - }); - } - } // This function detects when a Suspense boundary goes from visible to hidden. - - function commitResetTextContent(current) { - if (!supportsMutation) { - return; - } - - resetTextContent(current.stateNode); - } - - function commitMutationEffects(root, firstChild, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - nextEffect = firstChild; - commitMutationEffects_begin(root, committedLanes); - inProgressLanes = null; - inProgressRoot = null; - } - - function commitMutationEffects_begin(root, lanes) { - while (nextEffect !== null) { - var fiber = nextEffect; // TODO: Should wrap this in flags check, too, as optimization - - var deletions = fiber.deletions; - - if (deletions !== null) { - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - - try { - commitDeletion(root, childToDelete, fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(childToDelete, fiber, error); - } - } - } - - var child = fiber.child; - - if ((fiber.subtreeFlags & MutationMask) !== NoFlags && child !== null) { - ensureCorrectReturnPointer(child, fiber); - nextEffect = child; - } else { - commitMutationEffects_complete(root, lanes); - } - } - } - - function commitMutationEffects_complete(root, lanes) { - while (nextEffect !== null) { - var fiber = nextEffect; - setCurrentFiber(fiber); - - try { - commitMutationEffectsOnFiber(fiber, root, lanes); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitMutationEffectsOnFiber(finishedWork, root, lanes) { - // TODO: The factoring of this phase could probably be improved. Consider - // switching on the type of work before checking the flags. That's what - // we do in all the other phases. I think this one is only different - // because of the shared reconciliation logic below. - var flags = finishedWork.flags; - - if (flags & ContentReset) { - commitResetTextContent(finishedWork); - } - - if (flags & Ref) { - var current = finishedWork.alternate; - - if (current !== null) { - commitDetachRef(current); - } - } - - if (flags & Visibility) { - switch (finishedWork.tag) { - case SuspenseComponent: - { - var newState = finishedWork.memoizedState; - var isHidden = newState !== null; - - if (isHidden) { - var _current = finishedWork.alternate; - var wasHidden = _current !== null && _current.memoizedState !== null; - - if (!wasHidden) { - // TODO: Move to passive phase - markCommitTimeOfFallback(); - } - } - - break; - } - - case OffscreenComponent: - { - var _newState = finishedWork.memoizedState; - - var _isHidden = _newState !== null; - - var _current2 = finishedWork.alternate; - - var _wasHidden = _current2 !== null && _current2.memoizedState !== null; - - var offscreenBoundary = finishedWork; - - if (supportsMutation) { - // TODO: This needs to run whenever there's an insertion or update - // inside a hidden Offscreen tree. - hideOrUnhideAllChildren(offscreenBoundary, _isHidden); - } - - { - if (_isHidden) { - if (!_wasHidden) { - if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) { - nextEffect = offscreenBoundary; - var offscreenChild = offscreenBoundary.child; - - while (offscreenChild !== null) { - nextEffect = offscreenChild; - disappearLayoutEffects_begin(offscreenChild); - offscreenChild = offscreenChild.sibling; - } - } - } - } - - break; - } - } - } - } // The following switch statement is only concerned about placement, - // updates, and deletions. To avoid needing to add a case for every possible - // bitmap value, we remove the secondary effects from the effect tag and - // switch on that value. - - - var primaryFlags = flags & (Placement | Update | Hydrating); - - switch (primaryFlags) { - case Placement: - { - commitPlacement(finishedWork); // Clear the "placement" from effect tag so that we know that this is - // inserted, before any life-cycles like componentDidMount gets called. - // TODO: findDOMNode doesn't rely on this any more but isMounted does - // and isMounted is deprecated anyway so we should be able to kill this. - - finishedWork.flags &= ~Placement; - break; - } - - case PlacementAndUpdate: - { - // Placement - commitPlacement(finishedWork); // Clear the "placement" from effect tag so that we know that this is - // inserted, before any life-cycles like componentDidMount gets called. - - finishedWork.flags &= ~Placement; // Update - - var _current3 = finishedWork.alternate; - commitWork(_current3, finishedWork); - break; - } - - case Hydrating: - { - finishedWork.flags &= ~Hydrating; - break; - } - - case HydratingAndUpdate: - { - finishedWork.flags &= ~Hydrating; // Update - - var _current4 = finishedWork.alternate; - commitWork(_current4, finishedWork); - break; - } - - case Update: - { - var _current5 = finishedWork.alternate; - commitWork(_current5, finishedWork); - break; - } - } - } - - function commitLayoutEffects(finishedWork, root, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - nextEffect = finishedWork; - commitLayoutEffects_begin(finishedWork, root, committedLanes); - inProgressLanes = null; - inProgressRoot = null; - } - - function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) { - // Suspense layout effects semantics don't change for legacy roots. - var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode; - - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - - if ( fiber.tag === OffscreenComponent && isModernRoot) { - // Keep track of the current Offscreen stack's state. - var isHidden = fiber.memoizedState !== null; - var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; - - if (newOffscreenSubtreeIsHidden) { - // The Offscreen tree is hidden. Skip over its layout effects. - commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); - continue; - } else { - // TODO (Offscreen) Also check: subtreeFlags & LayoutMask - var current = fiber.alternate; - var wasHidden = current !== null && current.memoizedState !== null; - var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; - var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root. - - offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; - - if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { - // This is the root of a reappearing boundary. Turn its layout effects - // back on. - nextEffect = fiber; - reappearLayoutEffects_begin(fiber); - } - - var child = firstChild; - - while (child !== null) { - nextEffect = child; - commitLayoutEffects_begin(child, // New root; bubble back up to here and stop. - root, committedLanes); - child = child.sibling; - } // Restore Offscreen state and resume in our-progress traversal. - - - nextEffect = fiber; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); - continue; - } - } - - if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) { - ensureCorrectReturnPointer(firstChild, fiber); - nextEffect = firstChild; - } else { - commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); - } - } - } - - function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) { - while (nextEffect !== null) { - var fiber = nextEffect; - - if ((fiber.flags & LayoutMask) !== NoFlags) { - var current = fiber.alternate; - setCurrentFiber(fiber); - - try { - commitLayoutEffectOnFiber(root, current, fiber, committedLanes); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - } - - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function disappearLayoutEffects_begin(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) - - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: - { - if ( fiber.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount(Layout, fiber, fiber.return); - } finally { - recordLayoutEffectDuration(fiber); - } - } else { - commitHookEffectListUnmount(Layout, fiber, fiber.return); - } - - break; - } - - case ClassComponent: - { - // TODO (Offscreen) Check: flags & RefStatic - safelyDetachRef(fiber, fiber.return); - var instance = fiber.stateNode; - - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount(fiber, fiber.return, instance); - } - - break; - } - - case HostComponent: - { - safelyDetachRef(fiber, fiber.return); - break; - } - - case OffscreenComponent: - { - // Check if this is a - var isHidden = fiber.memoizedState !== null; - - if (isHidden) { - // Nested Offscreen tree is already hidden. Don't disappear - // its effects. - disappearLayoutEffects_complete(subtreeRoot); - continue; - } - - break; - } - } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic - - - if (firstChild !== null) { - firstChild.return = fiber; - nextEffect = firstChild; - } else { - disappearLayoutEffects_complete(subtreeRoot); - } - } - } - - function disappearLayoutEffects_complete(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function reappearLayoutEffects_begin(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - - if (fiber.tag === OffscreenComponent) { - var isHidden = fiber.memoizedState !== null; - - if (isHidden) { - // Nested Offscreen tree is still hidden. Don't re-appear its effects. - reappearLayoutEffects_complete(subtreeRoot); - continue; - } - } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic - - - if (firstChild !== null) { - // This node may have been reused from a previous render, so we can't - // assume its return pointer is correct. - firstChild.return = fiber; - nextEffect = firstChild; - } else { - reappearLayoutEffects_complete(subtreeRoot); - } - } - } - - function reappearLayoutEffects_complete(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic - - setCurrentFiber(fiber); - - try { - reappearLayoutEffectsOnFiber(fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - // This node may have been reused from a previous render, so we can't - // assume its return pointer is correct. - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitPassiveMountEffects(root, finishedWork) { - nextEffect = finishedWork; - commitPassiveMountEffects_begin(finishedWork, root); - } - - function commitPassiveMountEffects_begin(subtreeRoot, root) { - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - - if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { - ensureCorrectReturnPointer(firstChild, fiber); - nextEffect = firstChild; - } else { - commitPassiveMountEffects_complete(subtreeRoot, root); - } - } - } - - function commitPassiveMountEffects_complete(subtreeRoot, root) { - while (nextEffect !== null) { - var fiber = nextEffect; - - if ((fiber.flags & Passive) !== NoFlags) { - setCurrentFiber(fiber); - - try { - commitPassiveMountOnFiber(root, fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - } - - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitPassiveMountOnFiber(finishedRoot, finishedWork) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( finishedWork.mode & ProfileMode) { - startPassiveEffectTimer(); - - try { - commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); - } finally { - recordPassiveEffectDuration(finishedWork); - } - } else { - commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); - } - - break; - } - } - } - - function commitPassiveUnmountEffects(firstChild) { - nextEffect = firstChild; - commitPassiveUnmountEffects_begin(); - } - - function commitPassiveUnmountEffects_begin() { - while (nextEffect !== null) { - var fiber = nextEffect; - var child = fiber.child; - - if ((nextEffect.flags & ChildDeletion) !== NoFlags) { - var deletions = fiber.deletions; - - if (deletions !== null) { - for (var i = 0; i < deletions.length; i++) { - var fiberToDelete = deletions[i]; - nextEffect = fiberToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber); - } - - { - // A fiber was deleted from this parent fiber, but it's still part of - // the previous (alternate) parent fiber's list of children. Because - // children are a linked list, an earlier sibling that's still alive - // will be connected to the deleted fiber via its `alternate`: - // - // live fiber - // --alternate--> previous live fiber - // --sibling--> deleted fiber - // - // We can't disconnect `alternate` on nodes that haven't been deleted - // yet, but we can disconnect the `sibling` and `child` pointers. - var previousFiber = fiber.alternate; - - if (previousFiber !== null) { - var detachedChild = previousFiber.child; - - if (detachedChild !== null) { - previousFiber.child = null; - - do { - var detachedSibling = detachedChild.sibling; - detachedChild.sibling = null; - detachedChild = detachedSibling; - } while (detachedChild !== null); - } - } - } - - nextEffect = fiber; - } - } - - if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { - ensureCorrectReturnPointer(child, fiber); - nextEffect = child; - } else { - commitPassiveUnmountEffects_complete(); - } - } - } - - function commitPassiveUnmountEffects_complete() { - while (nextEffect !== null) { - var fiber = nextEffect; - - if ((fiber.flags & Passive) !== NoFlags) { - setCurrentFiber(fiber); - commitPassiveUnmountOnFiber(fiber); - resetCurrentFiber(); - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitPassiveUnmountOnFiber(finishedWork) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( finishedWork.mode & ProfileMode) { - startPassiveEffectTimer(); - commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); - recordPassiveEffectDuration(finishedWork); - } else { - commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); - } - - break; - } - } - } - - function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) { - while (nextEffect !== null) { - var fiber = nextEffect; // Deletion effects fire in parent -> child order - // TODO: Check if fiber has a PassiveStatic flag - - setCurrentFiber(fiber); - commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); - resetCurrentFiber(); - var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we - // do this, still need to handle `deletedTreeCleanUpLevel` correctly.) - - if (child !== null) { - ensureCorrectReturnPointer(child, fiber); - nextEffect = child; - } else { - commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot); - } - } - } - - function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - var sibling = fiber.sibling; - var returnFiber = fiber.return; - - { - // Recursively traverse the entire deleted tree and clean up fiber fields. - // This is more aggressive than ideal, and the long term goal is to only - // have to detach the deleted tree at the root. - detachFiberAfterEffects(fiber); - - if (fiber === deletedSubtreeRoot) { - nextEffect = null; - return; - } - } - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, returnFiber); - nextEffect = sibling; - return; - } - - nextEffect = returnFiber; - } - } - - function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) { - switch (current.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( current.mode & ProfileMode) { - startPassiveEffectTimer(); - commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); - recordPassiveEffectDuration(current); - } else { - commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); - } - - break; - } - } - } - - var didWarnWrongReturnPointer = false; - - function ensureCorrectReturnPointer(fiber, expectedReturnFiber) { - { - if (!didWarnWrongReturnPointer && fiber.return !== expectedReturnFiber) { - didWarnWrongReturnPointer = true; - - error('Internal React error: Return pointer is inconsistent ' + 'with parent.'); - } - } // TODO: Remove this assignment once we're confident that it won't break - // anything, by checking the warning logs for the above invariant - - - fiber.return = expectedReturnFiber; - } // TODO: Reuse reappearLayoutEffects traversal here? - - - function invokeLayoutEffectMountInDEV(fiber) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - try { - commitHookEffectListMount(Layout | HasEffect, fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - break; - } - - case ClassComponent: - { - var instance = fiber.stateNode; - - try { - instance.componentDidMount(); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - break; - } - } - } - } - - function invokePassiveEffectMountInDEV(fiber) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - try { - commitHookEffectListMount(Passive$1 | HasEffect, fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - break; - } - } - } - } - - function invokeLayoutEffectUnmountInDEV(fiber) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - try { - commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - break; - } - - case ClassComponent: - { - var instance = fiber.stateNode; - - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount(fiber, fiber.return, instance); - } - - break; - } - } - } - } - - function invokePassiveEffectUnmountInDEV(fiber) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - try { - commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - } - } - } - } - - var COMPONENT_TYPE = 0; - var HAS_PSEUDO_CLASS_TYPE = 1; - var ROLE_TYPE = 2; - var TEST_NAME_TYPE = 3; - var TEXT_TYPE = 4; - - if (typeof Symbol === 'function' && Symbol.for) { - var symbolFor = Symbol.for; - COMPONENT_TYPE = symbolFor('selector.component'); - HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class'); - ROLE_TYPE = symbolFor('selector.role'); - TEST_NAME_TYPE = symbolFor('selector.test_id'); - TEXT_TYPE = symbolFor('selector.text'); - } - - function createComponentSelector(component) { - return { - $$typeof: COMPONENT_TYPE, - value: component - }; - } - function createHasPseudoClassSelector(selectors) { - return { - $$typeof: HAS_PSEUDO_CLASS_TYPE, - value: selectors - }; - } - function createRoleSelector(role) { - return { - $$typeof: ROLE_TYPE, - value: role - }; - } - function createTextSelector(text) { - return { - $$typeof: TEXT_TYPE, - value: text - }; - } - function createTestNameSelector(id) { - return { - $$typeof: TEST_NAME_TYPE, - value: id - }; - } - - function findFiberRootForHostRoot(hostRoot) { - var maybeFiber = getInstanceFromNode(hostRoot); - - if (maybeFiber != null) { - if (typeof maybeFiber.memoizedProps['data-testname'] !== 'string') { - throw new Error('Invalid host root specified. Should be either a React container or a node with a testname attribute.'); - } - - return maybeFiber; - } else { - var fiberRoot = findFiberRoot(hostRoot); - - if (fiberRoot === null) { - throw new Error('Could not find React container within specified host subtree.'); - } // The Flow type for FiberRoot is a little funky. - // createFiberRoot() cheats this by treating the root as :any and adding stateNode lazily. - - - return fiberRoot.stateNode.current; - } - } - - function matchSelector(fiber, selector) { - switch (selector.$$typeof) { - case COMPONENT_TYPE: - if (fiber.type === selector.value) { - return true; - } - - break; - - case HAS_PSEUDO_CLASS_TYPE: - return hasMatchingPaths(fiber, selector.value); - - case ROLE_TYPE: - if (fiber.tag === HostComponent) { - var node = fiber.stateNode; - - if (matchAccessibilityRole(node, selector.value)) { - return true; - } - } - - break; - - case TEXT_TYPE: - if (fiber.tag === HostComponent || fiber.tag === HostText) { - var textContent = getTextContent(fiber); - - if (textContent !== null && textContent.indexOf(selector.value) >= 0) { - return true; - } - } - - break; - - case TEST_NAME_TYPE: - if (fiber.tag === HostComponent) { - var dataTestID = fiber.memoizedProps['data-testname']; - - if (typeof dataTestID === 'string' && dataTestID.toLowerCase() === selector.value.toLowerCase()) { - return true; - } - } - - break; - - default: - throw new Error('Invalid selector type specified.'); - } - - return false; - } - - function selectorToString(selector) { - switch (selector.$$typeof) { - case COMPONENT_TYPE: - var displayName = getComponentNameFromType(selector.value) || 'Unknown'; - return "<" + displayName + ">"; - - case HAS_PSEUDO_CLASS_TYPE: - return ":has(" + (selectorToString(selector) || '') + ")"; - - case ROLE_TYPE: - return "[role=\"" + selector.value + "\"]"; - - case TEXT_TYPE: - return "\"" + selector.value + "\""; - - case TEST_NAME_TYPE: - return "[data-testname=\"" + selector.value + "\"]"; - - default: - throw new Error('Invalid selector type specified.'); - } - } - - function findPaths(root, selectors) { - var matchingFibers = []; - var stack = [root, 0]; - var index = 0; - - while (index < stack.length) { - var fiber = stack[index++]; - var selectorIndex = stack[index++]; - var selector = selectors[selectorIndex]; - - if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { - continue; - } else { - while (selector != null && matchSelector(fiber, selector)) { - selectorIndex++; - selector = selectors[selectorIndex]; - } - } - - if (selectorIndex === selectors.length) { - matchingFibers.push(fiber); - } else { - var child = fiber.child; - - while (child !== null) { - stack.push(child, selectorIndex); - child = child.sibling; - } - } - } - - return matchingFibers; - } // Same as findPaths but with eager bailout on first match - - - function hasMatchingPaths(root, selectors) { - var stack = [root, 0]; - var index = 0; - - while (index < stack.length) { - var fiber = stack[index++]; - var selectorIndex = stack[index++]; - var selector = selectors[selectorIndex]; - - if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { - continue; - } else { - while (selector != null && matchSelector(fiber, selector)) { - selectorIndex++; - selector = selectors[selectorIndex]; - } - } - - if (selectorIndex === selectors.length) { - return true; - } else { - var child = fiber.child; - - while (child !== null) { - stack.push(child, selectorIndex); - child = child.sibling; - } - } - } - - return false; - } - - function findAllNodes(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var root = findFiberRootForHostRoot(hostRoot); - var matchingFibers = findPaths(root, selectors); - var instanceRoots = []; - var stack = Array.from(matchingFibers); - var index = 0; - - while (index < stack.length) { - var node = stack[index++]; - - if (node.tag === HostComponent) { - if (isHiddenSubtree(node)) { - continue; - } - - instanceRoots.push(node.stateNode); - } else { - var child = node.child; - - while (child !== null) { - stack.push(child); - child = child.sibling; - } - } - } - - return instanceRoots; - } - function getFindAllNodesFailureDescription(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var root = findFiberRootForHostRoot(hostRoot); - var maxSelectorIndex = 0; - var matchedNames = []; // The logic of this loop should be kept in sync with findPaths() - - var stack = [root, 0]; - var index = 0; - - while (index < stack.length) { - var fiber = stack[index++]; - var selectorIndex = stack[index++]; - var selector = selectors[selectorIndex]; - - if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { - continue; - } else if (matchSelector(fiber, selector)) { - matchedNames.push(selectorToString(selector)); - selectorIndex++; - - if (selectorIndex > maxSelectorIndex) { - maxSelectorIndex = selectorIndex; - } - } - - if (selectorIndex < selectors.length) { - var child = fiber.child; - - while (child !== null) { - stack.push(child, selectorIndex); - child = child.sibling; - } - } - } - - if (maxSelectorIndex < selectors.length) { - var unmatchedNames = []; - - for (var i = maxSelectorIndex; i < selectors.length; i++) { - unmatchedNames.push(selectorToString(selectors[i])); - } - - return 'findAllNodes was able to match part of the selector:\n' + (" " + matchedNames.join(' > ') + "\n\n") + 'No matching component was found for:\n' + (" " + unmatchedNames.join(' > ')); - } - - return null; - } - function findBoundingRects(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var instanceRoots = findAllNodes(hostRoot, selectors); - var boundingRects = []; - - for (var i = 0; i < instanceRoots.length; i++) { - boundingRects.push(getBoundingRect(instanceRoots[i])); - } - - for (var _i = boundingRects.length - 1; _i > 0; _i--) { - var targetRect = boundingRects[_i]; - var targetLeft = targetRect.x; - var targetRight = targetLeft + targetRect.width; - var targetTop = targetRect.y; - var targetBottom = targetTop + targetRect.height; - - for (var j = _i - 1; j >= 0; j--) { - if (_i !== j) { - var otherRect = boundingRects[j]; - var otherLeft = otherRect.x; - var otherRight = otherLeft + otherRect.width; - var otherTop = otherRect.y; - var otherBottom = otherTop + otherRect.height; // Merging all rects to the minimums set would be complicated, - // but we can handle the most common cases: - // 1. completely overlapping rects - // 2. adjacent rects that are the same width or height (e.g. items in a list) - // - // Even given the above constraints, - // we still won't end up with the fewest possible rects without doing multiple passes, - // but it's good enough for this purpose. - - if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) { - // Complete overlapping rects; remove the inner one. - boundingRects.splice(_i, 1); - break; - } else if (targetLeft === otherLeft && targetRect.width === otherRect.width && !(otherBottom < targetTop) && !(otherTop > targetBottom)) { - // Adjacent vertical rects; merge them. - if (otherTop > targetTop) { - otherRect.height += otherTop - targetTop; - otherRect.y = targetTop; - } - - if (otherBottom < targetBottom) { - otherRect.height = targetBottom - otherTop; - } - - boundingRects.splice(_i, 1); - break; - } else if (targetTop === otherTop && targetRect.height === otherRect.height && !(otherRight < targetLeft) && !(otherLeft > targetRight)) { - // Adjacent horizontal rects; merge them. - if (otherLeft > targetLeft) { - otherRect.width += otherLeft - targetLeft; - otherRect.x = targetLeft; - } - - if (otherRight < targetRight) { - otherRect.width = targetRight - otherLeft; - } - - boundingRects.splice(_i, 1); - break; - } - } - } - } - - return boundingRects; - } - function focusWithin(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var root = findFiberRootForHostRoot(hostRoot); - var matchingFibers = findPaths(root, selectors); - var stack = Array.from(matchingFibers); - var index = 0; - - while (index < stack.length) { - var fiber = stack[index++]; - - if (isHiddenSubtree(fiber)) { - continue; - } - - if (fiber.tag === HostComponent) { - var node = fiber.stateNode; - - if (setFocusIfFocusable(node)) { - return true; - } - } - - var child = fiber.child; - - while (child !== null) { - stack.push(child); - child = child.sibling; - } - } - - return false; - } - var commitHooks = []; - function onCommitRoot$1() { - if (supportsTestSelectors) { - commitHooks.forEach(function (commitHook) { - return commitHook(); - }); - } - } - function observeVisibleRects(hostRoot, selectors, callback, options) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var instanceRoots = findAllNodes(hostRoot, selectors); - - var _setupIntersectionObs = setupIntersectionObserver(instanceRoots, callback, options), - disconnect = _setupIntersectionObs.disconnect, - observe = _setupIntersectionObs.observe, - unobserve = _setupIntersectionObs.unobserve; // When React mutates the host environment, we may need to change what we're listening to. - - - var commitHook = function () { - var nextInstanceRoots = findAllNodes(hostRoot, selectors); - instanceRoots.forEach(function (target) { - if (nextInstanceRoots.indexOf(target) < 0) { - unobserve(target); - } - }); - nextInstanceRoots.forEach(function (target) { - if (instanceRoots.indexOf(target) < 0) { - observe(target); - } - }); - }; - - commitHooks.push(commitHook); - return { - disconnect: function () { - // Stop listening for React mutations: - var index = commitHooks.indexOf(commitHook); - - if (index >= 0) { - commitHooks.splice(index, 1); - } // Disconnect the host observer: - - - disconnect(); - } - }; - } - - var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; - function isLegacyActEnvironment(fiber) { - { - // Legacy mode. We preserve the behavior of React 17's act. It assumes an - // act environment whenever `jest` is defined, but you can still turn off - // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly - // to false. - var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global - typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest - - var jestIsDefined = typeof jest !== 'undefined'; - return warnsIfNotActing && jestIsDefined && isReactActEnvironmentGlobal !== false; - } - } - function isConcurrentActEnvironment() { - { - var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global - typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; - - if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { - // TODO: Include link to relevant documentation page. - error('The current testing environment is not configured to support ' + 'act(...)'); - } - - return isReactActEnvironmentGlobal; - } - } - - var ceil = Math.ceil; - var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, - ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, - ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig, - ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue; - var NoContext = - /* */ - 0; - var BatchedContext = - /* */ - 1; - var RenderContext = - /* */ - 2; - var CommitContext = - /* */ - 4; - var RootInProgress = 0; - var RootFatalErrored = 1; - var RootErrored = 2; - var RootSuspended = 3; - var RootSuspendedWithDelay = 4; - var RootCompleted = 5; - var RootDidNotComplete = 6; // Describes where we are in the React execution stack - - var executionContext = NoContext; // The root we're working on - - var workInProgressRoot = null; // The fiber we're working on - - var workInProgress = null; // The lanes we're rendering - - var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree - // This is a superset of the lanes we started working on at the root. The only - // case where it's different from `workInProgressRootRenderLanes` is when we - // enter a subtree that is hidden and needs to be unhidden: Suspense and - // Offscreen component. - // - // Most things in the work loop should deal with workInProgressRootRenderLanes. - // Most things in begin/complete phases should deal with subtreeRenderLanes. - - var subtreeRenderLanes = NoLanes; - var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc. - - var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown - - var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's - // includes unprocessed updates, not work in bailed out children. - - var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render. - - var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event). - - var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase. - - var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI. - // We will log them once the tree commits. - - var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train - // model where we don't commit new loading states in too quick succession. - - var globalMostRecentFallbackTime = 0; - var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering - // more and prefer CPU suspense heuristics instead. - - var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU - // suspense heuristics and opt out of rendering more content. - - var RENDER_TIMEOUT_MS = 500; - - function resetRenderTimer() { - workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS; - } - - function getRenderTargetTime() { - return workInProgressRootRenderTargetTime; - } - var hasUncaughtError = false; - var firstUncaughtError = null; - var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true; - var rootDoesHavePassiveEffects = false; - var rootWithPendingPassiveEffects = null; - var pendingPassiveEffectsLanes = NoLanes; - var pendingPassiveProfilerEffects = []; - - var NESTED_UPDATE_LIMIT = 50; - var nestedUpdateCount = 0; - var rootWithNestedUpdates = null; - var NESTED_PASSIVE_UPDATE_LIMIT = 50; - var nestedPassiveUpdateCount = 0; // If two updates are scheduled within the same event, we should treat their - // event times as simultaneous, even if the actual clock time has advanced - // between the first and second call. - - var currentEventTime = NoTimestamp; - var currentEventTransitionLane = NoLanes; - function getWorkInProgressRoot() { - return workInProgressRoot; - } - function requestEventTime() { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - // We're inside React, so it's fine to read the actual time. - return now$1(); - } // We're not inside React, so we may be in the middle of a browser event. - - - if (currentEventTime !== NoTimestamp) { - // Use the same start time for all updates until we enter React again. - return currentEventTime; - } // This is the first update since React yielded. Compute a new start time. - - - currentEventTime = now$1(); - return currentEventTime; - } - function requestUpdateLane(fiber) { - // Special cases - var mode = fiber.mode; - - if ((mode & ConcurrentMode) === NoMode) { - return SyncLane; - } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { - // This is a render phase update. These are not officially supported. The - // old behavior is to give this the same "thread" (lanes) as - // whatever is currently rendering. So if you call `setState` on a component - // that happens later in the same render, it will flush. Ideally, we want to - // remove the special case and treat them as if they came from an - // interleaved event. Regardless, this pattern is not officially supported. - // This behavior is only a fallback. The flag only exists until we can roll - // out the setState warning, since existing code might accidentally rely on - // the current behavior. - return pickArbitraryLane(workInProgressRootRenderLanes); - } - - var isTransition = requestCurrentTransition() !== NoTransition; - - if (isTransition) { - if ( ReactCurrentBatchConfig$2.transition !== null) { - var transition = ReactCurrentBatchConfig$2.transition; - - if (!transition._updatedFibers) { - transition._updatedFibers = new Set(); - } - - transition._updatedFibers.add(fiber); - } // The algorithm for assigning an update to a lane should be stable for all - // updates at the same priority within the same event. To do this, the - // inputs to the algorithm must be the same. - // - // The trick we use is to cache the first of each of these inputs within an - // event. Then reset the cached values once we can be sure the event is - // over. Our heuristic for that is whenever we enter a concurrent work loop. - - - if (currentEventTransitionLane === NoLane) { - // All transitions within the same event are assigned the same lane. - currentEventTransitionLane = claimNextTransitionLane(); - } - - return currentEventTransitionLane; - } // Updates originating inside certain React methods, like flushSync, have - // their priority set by tracking it with a context variable. - // - // The opaque type returned by the host config is internally a lane, so we can - // use that directly. - // TODO: Move this type conversion to the event priority module. - - - var updateLane = getCurrentUpdatePriority(); - - if (updateLane !== NoLane) { - return updateLane; - } // This update originated outside React. Ask the host environment for an - // appropriate priority, based on the type of event. - // - // The opaque type returned by the host config is internally a lane, so we can - // use that directly. - // TODO: Move this type conversion to the event priority module. - - - var eventLane = getCurrentEventPriority(); - return eventLane; - } - - function requestRetryLane(fiber) { - // This is a fork of `requestUpdateLane` designed specifically for Suspense - // "retries" — a special update that attempts to flip a Suspense boundary - // from its placeholder state to its primary/resolved state. - // Special cases - var mode = fiber.mode; - - if ((mode & ConcurrentMode) === NoMode) { - return SyncLane; - } - - return claimNextRetryLane(); - } - - function scheduleUpdateOnFiber(fiber, lane, eventTime) { - checkForNestedUpdates(); - var root = markUpdateLaneFromFiberToRoot(fiber, lane); - - if (root === null) { - return null; - } // Mark that the root has a pending update. - - - markRootUpdated(root, lane, eventTime); - - if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) { - // This update was dispatched during the render phase. This is a mistake - // if the update originates from user space (with the exception of local - // hook updates, which are handled differently and don't reach this - // function), but there are some internal React features that use this as - // an implementation detail, like selective hydration. - warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase - } else { - // This is a normal update, scheduled from outside the render phase. For - // example, during an input event. - { - if (isDevToolsPresent) { - addFiberToLanesMap(root, fiber, lane); - } - } - - warnIfUpdatesNotWrappedWithActDEV(fiber); - - if (root === workInProgressRoot) { - // TODO: Consolidate with `isInterleavedUpdate` check - // Received an update to a tree that's in the middle of rendering. Mark - // that there was an interleaved update work on this root. Unless the - // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render - // phase update. In that case, we don't treat render phase updates as if - // they were interleaved, for backwards compat reasons. - if ( (executionContext & RenderContext) === NoContext) { - workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); - } - - if (workInProgressRootExitStatus === RootSuspendedWithDelay) { - // The root already suspended with a delay, which means this render - // definitely won't finish. Since we have a new update, let's mark it as - // suspended now, right before marking the incoming update. This has the - // effect of interrupting the current render and switching to the update. - // TODO: Make sure this doesn't override pings that happen while we've - // already started rendering. - markRootSuspended$1(root, workInProgressRootRenderLanes); - } - } - - ensureRootIsScheduled(root, eventTime); - - if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. - !( ReactCurrentActQueue$1.isBatchingLegacy)) { - // Flush the synchronous work now, unless we're already working or inside - // a batch. This is intentionally inside scheduleUpdateOnFiber instead of - // scheduleCallbackForFiber to preserve the ability to schedule a callback - // without immediately flushing it. We only do this for user-initiated - // updates, to preserve historical behavior of legacy mode. - resetRenderTimer(); - flushSyncCallbacksOnlyInLegacyMode(); - } - } - - return root; - } - function scheduleInitialHydrationOnRoot(root, lane, eventTime) { - // This is a special fork of scheduleUpdateOnFiber that is only used to - // schedule the initial hydration of a root that has just been created. Most - // of the stuff in scheduleUpdateOnFiber can be skipped. - // - // The main reason for this separate path, though, is to distinguish the - // initial children from subsequent updates. In fully client-rendered roots - // (createRoot instead of hydrateRoot), all top-level renders are modeled as - // updates, but hydration roots are special because the initial render must - // match what was rendered on the server. - var current = root.current; - current.lanes = lane; - markRootUpdated(root, lane, eventTime); - ensureRootIsScheduled(root, eventTime); - } // This is split into a separate function so we can mark a fiber with pending - // work without treating it as a typical update that originates from an event; - // e.g. retrying a Suspense boundary isn't an update, but it does schedule work - // on a fiber. - - function markUpdateLaneFromFiberToRoot(sourceFiber, lane) { - // Update the source fiber's lanes - sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); - var alternate = sourceFiber.alternate; - - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, lane); - } - - { - if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) { - warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); - } - } // Walk the parent path to the root and update the child lanes. - - - var node = sourceFiber; - var parent = sourceFiber.return; - - while (parent !== null) { - parent.childLanes = mergeLanes(parent.childLanes, lane); - alternate = parent.alternate; - - if (alternate !== null) { - alternate.childLanes = mergeLanes(alternate.childLanes, lane); - } else { - { - if ((parent.flags & (Placement | Hydrating)) !== NoFlags) { - warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); - } - } - } - - node = parent; - parent = parent.return; - } - - if (node.tag === HostRoot) { - var root = node.stateNode; - return root; - } else { - return null; - } - } - - function isInterleavedUpdate(fiber, lane) { - return (// TODO: Optimize slightly by comparing to root that fiber belongs to. - // Requires some refactoring. Not a big deal though since it's rare for - // concurrent apps to have more than a single root. - workInProgressRoot !== null && (fiber.mode & ConcurrentMode) !== NoMode && ( // If this is a render phase update (i.e. UNSAFE_componentWillReceiveProps), - // then don't treat this as an interleaved update. This pattern is - // accompanied by a warning but we haven't fully deprecated it yet. We can - // remove once the deferRenderPhaseUpdateToNextBatch flag is enabled. - (executionContext & RenderContext) === NoContext) - ); - } // Use this function to schedule a task for a root. There's only one task per - // root; if a task was already scheduled, we'll check to make sure the priority - // of the existing task is the same as the priority of the next level that the - // root has work on. This function is called on every update, and right before - // exiting a task. - - function ensureRootIsScheduled(root, currentTime) { - var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as - // expired so we know to work on those next. - - markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority. - - var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); - - if (nextLanes === NoLanes) { - // Special case: There's nothing to work on. - if (existingCallbackNode !== null) { - cancelCallback$1(existingCallbackNode); - } - - root.callbackNode = null; - root.callbackPriority = NoLane; - return; - } // We use the highest priority lane to represent the priority of the callback. - - - var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it. - - var existingCallbackPriority = root.callbackPriority; - - if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a - // Scheduler task, rather than an `act` task, cancel it and re-scheduled - // on the `act` queue. - !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { - { - // If we're going to re-use an existing task, it needs to exist. - // Assume that discrete update microtasks are non-cancellable and null. - // TODO: Temporary until we confirm this warning is not fired. - if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) { - error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.'); - } - } // The priority hasn't changed. We can reuse the existing task. Exit. - - - return; - } - - if (existingCallbackNode != null) { - // Cancel the existing callback. We'll schedule a new one below. - cancelCallback$1(existingCallbackNode); - } // Schedule a new callback. - - - var newCallbackNode; - - if (newCallbackPriority === SyncLane) { - // Special case: Sync React callbacks are scheduled on a special - // internal queue - if (root.tag === LegacyRoot) { - if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) { - ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; - } - - scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); - } else { - scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); - } - - if (supportsMicrotasks) { - // Flush the queue in a microtask. - if ( ReactCurrentActQueue$1.current !== null) { - // Inside `act`, use our internal `act` queue so that these get flushed - // at the end of the current scope even when using the sync version - // of `act`. - ReactCurrentActQueue$1.current.push(flushSyncCallbacks); - } else { - scheduleMicrotask(function () { - // In Safari, appending an iframe forces microtasks to run. - // https://github.com/facebook/react/issues/22459 - // We don't support running callbacks in the middle of render - // or commit so we need to check against that. - if (executionContext === NoContext) { - // It's only safe to do this conditionally because we always - // check for pending work before we exit the task. - flushSyncCallbacks(); - } - }); - } - } else { - // Flush the queue in an Immediate task. - scheduleCallback$1(ImmediatePriority, flushSyncCallbacks); - } - - newCallbackNode = null; - } else { - var schedulerPriorityLevel; - - switch (lanesToEventPriority(nextLanes)) { - case DiscreteEventPriority: - schedulerPriorityLevel = ImmediatePriority; - break; - - case ContinuousEventPriority: - schedulerPriorityLevel = UserBlockingPriority; - break; - - case DefaultEventPriority: - schedulerPriorityLevel = NormalPriority; - break; - - case IdleEventPriority: - schedulerPriorityLevel = IdlePriority; - break; - - default: - schedulerPriorityLevel = NormalPriority; - break; - } - - newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root)); - } - - root.callbackPriority = newCallbackPriority; - root.callbackNode = newCallbackNode; - } // This is the entry point for every concurrent task, i.e. anything that - // goes through Scheduler. - - - function performConcurrentWorkOnRoot(root, didTimeout) { - { - resetNestedUpdateFlag(); - } // Since we know we're in a React event, we can clear the current - // event time. The next update will compute a new event time. - - - currentEventTime = NoTimestamp; - currentEventTransitionLane = NoLanes; - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Should not already be working.'); - } // Flush any pending passive effects before deciding which lanes to work on, - // in case they schedule additional work. - - - var originalCallbackNode = root.callbackNode; - var didFlushPassiveEffects = flushPassiveEffects(); - - if (didFlushPassiveEffects) { - // Something in the passive effect phase may have canceled the current task. - // Check if the task node for this root was changed. - if (root.callbackNode !== originalCallbackNode) { - // The current task was canceled. Exit. We don't need to call - // `ensureRootIsScheduled` because the check above implies either that - // there's a new task, or that there's no remaining work on this root. - return null; - } - } // Determine the next lanes to work on, using the fields stored - // on the root. - - - var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); - - if (lanes === NoLanes) { - // Defensive coding. This is never expected to happen. - return null; - } // We disable time-slicing in some cases: if the work has been CPU-bound - // for too long ("expired" work, to prevent starvation), or we're in - // sync-updates-by-default mode. - // TODO: We only check `didTimeout` defensively, to account for a Scheduler - // bug we're still investigating. Once the bug in Scheduler is fixed, - // we can remove this, since we track expiration ourselves. - - - var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout); - var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes); - - if (exitStatus !== RootInProgress) { - if (exitStatus === RootErrored) { - // If something threw an error, try rendering one more time. We'll - // render synchronously to block concurrent data mutations, and we'll - // includes all pending updates are included. If it still fails after - // the second attempt, we'll give up and commit the resulting tree. - var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - - if (errorRetryLanes !== NoLanes) { - lanes = errorRetryLanes; - exitStatus = recoverFromConcurrentError(root, errorRetryLanes); - } - } - - if (exitStatus === RootFatalErrored) { - var fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended$1(root, lanes); - ensureRootIsScheduled(root, now$1()); - throw fatalError; - } - - if (exitStatus === RootDidNotComplete) { - // The render unwound without completing the tree. This happens in special - // cases where need to exit the current render without producing a - // consistent tree or committing. - // - // This should only happen during a concurrent render, not a discrete or - // synchronous update. We should have already checked for this when we - // unwound the stack. - markRootSuspended$1(root, lanes); - } else { - // The render completed. - // Check if this render may have yielded to a concurrent event, and if so, - // confirm that any newly rendered stores are consistent. - // TODO: It's possible that even a concurrent render may never have yielded - // to the main thread, if it was fast enough, or if it expired. We could - // skip the consistency check in that case, too. - var renderWasConcurrent = !includesBlockingLane(root, lanes); - var finishedWork = root.current.alternate; - - if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { - // A store was mutated in an interleaved event. Render again, - // synchronously, to block further mutations. - exitStatus = renderRootSync(root, lanes); // We need to check again if something threw - - if (exitStatus === RootErrored) { - var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - - if (_errorRetryLanes !== NoLanes) { - lanes = _errorRetryLanes; - exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any - // concurrent events. - } - } - - if (exitStatus === RootFatalErrored) { - var _fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended$1(root, lanes); - ensureRootIsScheduled(root, now$1()); - throw _fatalError; - } - } // We now have a consistent tree. The next step is either to commit it, - // or, if something suspended, wait to commit it after a timeout. - - - root.finishedWork = finishedWork; - root.finishedLanes = lanes; - finishConcurrentRender(root, exitStatus, lanes); - } - } - - ensureRootIsScheduled(root, now$1()); - - if (root.callbackNode === originalCallbackNode) { - // The task node scheduled for this root is the same one that's - // currently executed. Need to return a continuation. - return performConcurrentWorkOnRoot.bind(null, root); - } - - return null; - } - - function recoverFromConcurrentError(root, errorRetryLanes) { - // If an error occurred during hydration, discard server response and fall - // back to client side render. - // Before rendering again, save the errors from the previous attempt. - var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; - - if (isRootDehydrated(root)) { - // The shell failed to hydrate. Set a flag to force a client rendering - // during the next attempt. To do this, we call prepareFreshStack now - // to create the root work-in-progress fiber. This is a bit weird in terms - // of factoring, because it relies on renderRootSync not calling - // prepareFreshStack again in the call below, which happens because the - // root and lanes haven't changed. - // - // TODO: I think what we should do is set ForceClientRender inside - // throwException, like we do for nested Suspense boundaries. The reason - // it's here instead is so we can switch to the synchronous work loop, too. - // Something to consider for a future refactor. - var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); - rootWorkInProgress.flags |= ForceClientRender; - - { - errorHydratingContainer(root.containerInfo); - } - } - - var exitStatus = renderRootSync(root, errorRetryLanes); - - if (exitStatus !== RootErrored) { - // Successfully finished rendering on retry - // The errors from the failed first attempt have been recovered. Add - // them to the collection of recoverable errors. We'll log them in the - // commit phase. - var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; - workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors - // from the first attempt, to preserve the causal sequence. - - if (errorsFromSecondAttempt !== null) { - queueRecoverableErrors(errorsFromSecondAttempt); - } - } - - return exitStatus; - } - - function queueRecoverableErrors(errors) { - if (workInProgressRootRecoverableErrors === null) { - workInProgressRootRecoverableErrors = errors; - } else { - workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); - } - } - - function finishConcurrentRender(root, exitStatus, lanes) { - switch (exitStatus) { - case RootInProgress: - case RootFatalErrored: - { - throw new Error('Root did not complete. This is a bug in React.'); - } - // Flow knows about invariant, so it complains if I add a break - // statement, but eslint doesn't know about invariant, so it complains - // if I do. eslint-disable-next-line no-fallthrough - - case RootErrored: - { - // We should have already attempted to retry this tree. If we reached - // this point, it errored again. Commit it. - commitRoot(root, workInProgressRootRecoverableErrors); - break; - } - - case RootSuspended: - { - markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we - // should immediately commit it or wait a bit. - - if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope - !shouldForceFlushFallbacksInDEV()) { - // This render only included retries, no updates. Throttle committing - // retries so that we don't show too many loading states too quickly. - var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now$1(); // Don't bother with a very short suspense time. - - if (msUntilTimeout > 10) { - var nextLanes = getNextLanes(root, NoLanes); - - if (nextLanes !== NoLanes) { - // There's additional work on this root. - break; - } - - var suspendedLanes = root.suspendedLanes; - - if (!isSubsetOfLanes(suspendedLanes, lanes)) { - // We should prefer to render the fallback of at the last - // suspended level. Ping the last suspended level to try - // rendering it again. - // FIXME: What if the suspended lanes are Idle? Should not restart. - requestEventTime(); - markRootPinged(root, suspendedLanes); - break; - } // The render is suspended, it hasn't timed out, and there's no - // lower priority work to do. Instead of committing the fallback - // immediately, wait for more data to arrive. - - - root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors), msUntilTimeout); - break; - } - } // The work expired. Commit immediately. - - - commitRoot(root, workInProgressRootRecoverableErrors); - break; - } - - case RootSuspendedWithDelay: - { - markRootSuspended$1(root, lanes); - - if (includesOnlyTransitions(lanes)) { - // This is a transition, so we should exit without committing a - // placeholder and without scheduling a timeout. Delay indefinitely - // until we receive more data. - break; - } - - if (!shouldForceFlushFallbacksInDEV()) { - // This is not a transition, but we did trigger an avoided state. - // Schedule a placeholder to display after a short delay, using the Just - // Noticeable Difference. - // TODO: Is the JND optimization worth the added complexity? If this is - // the only reason we track the event time, then probably not. - // Consider removing. - var mostRecentEventTime = getMostRecentEventTime(root, lanes); - var eventTimeMs = mostRecentEventTime; - var timeElapsedMs = now$1() - eventTimeMs; - - var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time. - - - if (_msUntilTimeout > 10) { - // Instead of committing the fallback immediately, wait for more data - // to arrive. - root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors), _msUntilTimeout); - break; - } - } // Commit the placeholder. - - - commitRoot(root, workInProgressRootRecoverableErrors); - break; - } - - case RootCompleted: - { - // The work completed. Ready to commit. - commitRoot(root, workInProgressRootRecoverableErrors); - break; - } - - default: - { - throw new Error('Unknown root exit status.'); - } - } - } - - function isRenderConsistentWithExternalStores(finishedWork) { - // Search the rendered tree for external store reads, and check whether the - // stores were mutated in a concurrent event. Intentionally using an iterative - // loop instead of recursion so we can exit early. - var node = finishedWork; - - while (true) { - if (node.flags & StoreConsistency) { - var updateQueue = node.updateQueue; - - if (updateQueue !== null) { - var checks = updateQueue.stores; - - if (checks !== null) { - for (var i = 0; i < checks.length; i++) { - var check = checks[i]; - var getSnapshot = check.getSnapshot; - var renderedValue = check.value; - - try { - if (!objectIs(getSnapshot(), renderedValue)) { - // Found an inconsistent store. - return false; - } - } catch (error) { - // If `getSnapshot` throws, return `false`. This will schedule - // a re-render, and the error will be rethrown during render. - return false; - } - } - } - } - } - - var child = node.child; - - if (node.subtreeFlags & StoreConsistency && child !== null) { - child.return = node; - node = child; - continue; - } - - if (node === finishedWork) { - return true; - } - - while (node.sibling === null) { - if (node.return === null || node.return === finishedWork) { - return true; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } // Flow doesn't know this is unreachable, but eslint does - // eslint-disable-next-line no-unreachable - - - return true; - } - - function markRootSuspended$1(root, suspendedLanes) { - // When suspending, we should always exclude lanes that were pinged or (more - // rarely, since we try to avoid it) updated during the render phase. - // TODO: Lol maybe there's a better way to factor this besides this - // obnoxiously named function :) - suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); - suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); - markRootSuspended(root, suspendedLanes); - } // This is the entry point for synchronous tasks that don't go - // through Scheduler - - - function performSyncWorkOnRoot(root) { - { - syncNestedUpdateFlag(); - } - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Should not already be working.'); - } - - flushPassiveEffects(); - var lanes = getNextLanes(root, NoLanes); - - if (!includesSomeLane(lanes, SyncLane)) { - // There's no remaining sync work left. - ensureRootIsScheduled(root, now$1()); - return null; - } - - var exitStatus = renderRootSync(root, lanes); - - if (root.tag !== LegacyRoot && exitStatus === RootErrored) { - // If something threw an error, try rendering one more time. We'll render - // synchronously to block concurrent data mutations, and we'll includes - // all pending updates are included. If it still fails after the second - // attempt, we'll give up and commit the resulting tree. - var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - - if (errorRetryLanes !== NoLanes) { - lanes = errorRetryLanes; - exitStatus = recoverFromConcurrentError(root, errorRetryLanes); - } - } - - if (exitStatus === RootFatalErrored) { - var fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended$1(root, lanes); - ensureRootIsScheduled(root, now$1()); - throw fatalError; - } - - if (exitStatus === RootDidNotComplete) { - throw new Error('Root did not complete. This is a bug in React.'); - } // We now have a consistent tree. Because this is a sync render, we - // will commit it even if something suspended. - - - var finishedWork = root.current.alternate; - root.finishedWork = finishedWork; - root.finishedLanes = lanes; - commitRoot(root, workInProgressRootRecoverableErrors); // Before exiting, make sure there's a callback scheduled for the next - // pending level. - - ensureRootIsScheduled(root, now$1()); - return null; - } - - function flushRoot(root, lanes) { - if (lanes !== NoLanes) { - markRootEntangled(root, mergeLanes(lanes, SyncLane)); - ensureRootIsScheduled(root, now$1()); - - if ((executionContext & (RenderContext | CommitContext)) === NoContext) { - resetRenderTimer(); - flushSyncCallbacks(); - } - } - } - function deferredUpdates(fn) { - var previousPriority = getCurrentUpdatePriority(); - var prevTransition = ReactCurrentBatchConfig$2.transition; - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DefaultEventPriority); - return fn(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - } - } - function batchedUpdates(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer - // most batchedUpdates-like method. - - if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. - !( ReactCurrentActQueue$1.isBatchingLegacy)) { - resetRenderTimer(); - flushSyncCallbacksOnlyInLegacyMode(); - } - } - } - function discreteUpdates(fn, a, b, c, d) { - var previousPriority = getCurrentUpdatePriority(); - var prevTransition = ReactCurrentBatchConfig$2.transition; - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - return fn(a, b, c, d); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - - if (executionContext === NoContext) { - resetRenderTimer(); - } - } - } // Overload the definition to the two valid signatures. - // Warning, this opts-out of checking the function body. - - // eslint-disable-next-line no-redeclare - function flushSync(fn) { - // In legacy mode, we flush pending passive effects at the beginning of the - // next event, not at the end of the previous one. - if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { - flushPassiveEffects(); - } - - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - var prevTransition = ReactCurrentBatchConfig$2.transition; - var previousPriority = getCurrentUpdatePriority(); - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - - if (fn) { - return fn(); - } else { - return undefined; - } - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. - // Note that this will happen even if batchedUpdates is higher up - // the stack. - - if ((executionContext & (RenderContext | CommitContext)) === NoContext) { - flushSyncCallbacks(); - } - } - } - function isAlreadyRendering() { - // Used by the renderer to print a warning if certain APIs are called from - // the wrong context. - return (executionContext & (RenderContext | CommitContext)) !== NoContext; - } - function flushControlled(fn) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - var prevTransition = ReactCurrentBatchConfig$2.transition; - var previousPriority = getCurrentUpdatePriority(); - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - fn(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - executionContext = prevExecutionContext; - - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - resetRenderTimer(); - flushSyncCallbacks(); - } - } - } - function pushRenderLanes(fiber, lanes) { - push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); - subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); - } - function popRenderLanes(fiber) { - subtreeRenderLanes = subtreeRenderLanesCursor.current; - pop(subtreeRenderLanesCursor, fiber); - } - - function prepareFreshStack(root, lanes) { - root.finishedWork = null; - root.finishedLanes = NoLanes; - var timeoutHandle = root.timeoutHandle; - - if (timeoutHandle !== noTimeout) { - // The root previous suspended and scheduled a timeout to commit a fallback - // state. Now that we have additional work, cancel the timeout. - root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above - - cancelTimeout(timeoutHandle); - } - - if (workInProgress !== null) { - var interruptedWork = workInProgress.return; - - while (interruptedWork !== null) { - var current = interruptedWork.alternate; - unwindInterruptedWork(current, interruptedWork); - interruptedWork = interruptedWork.return; - } - } - - workInProgressRoot = root; - var rootWorkInProgress = createWorkInProgress(root.current, null); - workInProgress = rootWorkInProgress; - workInProgressRootRenderLanes = subtreeRenderLanes = lanes; - workInProgressRootExitStatus = RootInProgress; - workInProgressRootFatalError = null; - workInProgressRootSkippedLanes = NoLanes; - workInProgressRootInterleavedUpdatedLanes = NoLanes; - workInProgressRootPingedLanes = NoLanes; - workInProgressRootConcurrentErrors = null; - workInProgressRootRecoverableErrors = null; - enqueueInterleavedUpdates(); - - { - ReactStrictModeWarnings.discardPendingWarnings(); - } - - return rootWorkInProgress; - } - - function handleError(root, thrownValue) { - do { - var erroredWork = workInProgress; - - try { - // Reset module-level state that was set during the render phase. - resetContextDependencies(); - resetHooksAfterThrow(); - resetCurrentFiber(); // TODO: I found and added this missing line while investigating a - // separate issue. Write a regression test using string refs. - - ReactCurrentOwner$2.current = null; - - if (erroredWork === null || erroredWork.return === null) { - // Expected to be working on a non-root fiber. This is a fatal error - // because there's no ancestor that can handle it; the root is - // supposed to capture all errors that weren't caught by an error - // boundary. - workInProgressRootExitStatus = RootFatalErrored; - workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next - // sibling, or the parent if there are no siblings. But since the root - // has no siblings nor a parent, we set it to null. Usually this is - // handled by `completeUnitOfWork` or `unwindWork`, but since we're - // intentionally not calling those, we need set it here. - // TODO: Consider calling `unwindWork` to pop the contexts. - - workInProgress = null; - return; - } - - if (enableProfilerTimer && erroredWork.mode & ProfileMode) { - // Record the time spent rendering before an error was thrown. This - // avoids inaccurate Profiler durations in the case of a - // suspended render. - stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); - } - - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - - if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') { - var wakeable = thrownValue; - markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes); - } else { - markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes); - } - } - - throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); - completeUnitOfWork(erroredWork); - } catch (yetAnotherThrownValue) { - // Something in the return path also threw. - thrownValue = yetAnotherThrownValue; - - if (workInProgress === erroredWork && erroredWork !== null) { - // If this boundary has already errored, then we had trouble processing - // the error. Bubble it to the next boundary. - erroredWork = erroredWork.return; - workInProgress = erroredWork; - } else { - erroredWork = workInProgress; - } - - continue; - } // Return to the normal work loop. - - - return; - } while (true); - } - - function pushDispatcher() { - var prevDispatcher = ReactCurrentDispatcher$2.current; - ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; - - if (prevDispatcher === null) { - // The React isomorphic package does not include a default dispatcher. - // Instead the first renderer will lazily attach one, in order to give - // nicer error messages. - return ContextOnlyDispatcher; - } else { - return prevDispatcher; - } - } - - function popDispatcher(prevDispatcher) { - ReactCurrentDispatcher$2.current = prevDispatcher; - } - - function markCommitTimeOfFallback() { - globalMostRecentFallbackTime = now$1(); - } - function markSkippedUpdateLanes(lane) { - workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes); - } - function renderDidSuspend() { - if (workInProgressRootExitStatus === RootInProgress) { - workInProgressRootExitStatus = RootSuspended; - } - } - function renderDidSuspendDelayIfPossible() { - if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) { - workInProgressRootExitStatus = RootSuspendedWithDelay; - } // Check if there are updates that we skipped tree that might have unblocked - // this render. - - - if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { - // Mark the current render as suspended so that we switch to working on - // the updates that were skipped. Usually we only suspend at the end of - // the render phase. - // TODO: We should probably always mark the root as suspended immediately - // (inside this function), since by suspending at the end of the render - // phase introduces a potential mistake where we suspend lanes that were - // pinged or updated while we were rendering. - markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); - } - } - function renderDidError(error) { - if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { - workInProgressRootExitStatus = RootErrored; - } - - if (workInProgressRootConcurrentErrors === null) { - workInProgressRootConcurrentErrors = [error]; - } else { - workInProgressRootConcurrentErrors.push(error); - } - } // Called during render to determine if anything has suspended. - // Returns false if we're not sure. - - function renderHasNotSuspendedYet() { - // If something errored or completed, we can't really be sure, - // so those are false. - return workInProgressRootExitStatus === RootInProgress; - } - - function renderRootSync(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - - if (memoizedUpdaters.size > 0) { - restorePendingUpdaters(root, workInProgressRootRenderLanes); - memoizedUpdaters.clear(); - } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. - // If we bailout on this work, we'll move them back (like above). - // It's important to move them now in case the work spawns more work at the same priority with different updaters. - // That way we can keep the current update and future updates separate. - - - movePendingFibersToMemoized(root, lanes); - } - } - prepareFreshStack(root, lanes); - } - - { - markRenderStarted(lanes); - } - - do { - try { - workLoopSync(); - break; - } catch (thrownValue) { - handleError(root, thrownValue); - } - } while (true); - - resetContextDependencies(); - executionContext = prevExecutionContext; - popDispatcher(prevDispatcher); - - if (workInProgress !== null) { - // This is a sync render, so we should have finished the whole tree. - throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.'); - } - - { - markRenderStopped(); - } // Set this to null to indicate there's no in-progress render. - - - workInProgressRoot = null; - workInProgressRootRenderLanes = NoLanes; - return workInProgressRootExitStatus; - } // The work loop is an extremely hot path. Tell Closure not to inline it. - - /** @noinline */ - - - function workLoopSync() { - // Already timed out, so perform work without checking if we need to yield. - while (workInProgress !== null) { - performUnitOfWork(workInProgress); - } - } - - function renderRootConcurrent(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - - if (memoizedUpdaters.size > 0) { - restorePendingUpdaters(root, workInProgressRootRenderLanes); - memoizedUpdaters.clear(); - } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. - // If we bailout on this work, we'll move them back (like above). - // It's important to move them now in case the work spawns more work at the same priority with different updaters. - // That way we can keep the current update and future updates separate. - - - movePendingFibersToMemoized(root, lanes); - } - } - resetRenderTimer(); - prepareFreshStack(root, lanes); - } - - { - markRenderStarted(lanes); - } - - do { - try { - workLoopConcurrent(); - break; - } catch (thrownValue) { - handleError(root, thrownValue); - } - } while (true); - - resetContextDependencies(); - popDispatcher(prevDispatcher); - executionContext = prevExecutionContext; - - - if (workInProgress !== null) { - // Still work remaining. - { - markRenderYielded(); - } - - return RootInProgress; - } else { - // Completed the tree. - { - markRenderStopped(); - } // Set this to null to indicate there's no in-progress render. - - - workInProgressRoot = null; - workInProgressRootRenderLanes = NoLanes; // Return the final exit status. - - return workInProgressRootExitStatus; - } - } - /** @noinline */ - - - function workLoopConcurrent() { - // Perform work until Scheduler asks us to yield - while (workInProgress !== null && !shouldYield()) { - performUnitOfWork(workInProgress); - } - } - - function performUnitOfWork(unitOfWork) { - // The current, flushed, state of this fiber is the alternate. Ideally - // nothing should rely on this, but relying on it here means that we don't - // need an additional field on the work in progress. - var current = unitOfWork.alternate; - setCurrentFiber(unitOfWork); - var next; - - if ( (unitOfWork.mode & ProfileMode) !== NoMode) { - startProfilerTimer(unitOfWork); - next = beginWork$1(current, unitOfWork, subtreeRenderLanes); - stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); - } else { - next = beginWork$1(current, unitOfWork, subtreeRenderLanes); - } - - resetCurrentFiber(); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - - if (next === null) { - // If this doesn't spawn new work, complete the current work. - completeUnitOfWork(unitOfWork); - } else { - workInProgress = next; - } - - ReactCurrentOwner$2.current = null; - } - - function completeUnitOfWork(unitOfWork) { - // Attempt to complete the current unit of work, then move to the next - // sibling. If there are no more siblings, return to the parent fiber. - var completedWork = unitOfWork; - - do { - // The current, flushed, state of this fiber is the alternate. Ideally - // nothing should rely on this, but relying on it here means that we don't - // need an additional field on the work in progress. - var current = completedWork.alternate; - var returnFiber = completedWork.return; // Check if the work completed or if something threw. - - if ((completedWork.flags & Incomplete) === NoFlags) { - setCurrentFiber(completedWork); - var next = void 0; - - if ( (completedWork.mode & ProfileMode) === NoMode) { - next = completeWork(current, completedWork, subtreeRenderLanes); - } else { - startProfilerTimer(completedWork); - next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error. - - stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); - } - - resetCurrentFiber(); - - if (next !== null) { - // Completing this fiber spawned new work. Work on that next. - workInProgress = next; - return; - } - } else { - // This fiber did not complete because something threw. Pop values off - // the stack without entering the complete phase. If this is a boundary, - // capture values if possible. - var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes. - - - if (_next !== null) { - // If completing this work spawned new work, do that next. We'll come - // back here again. - // Since we're restarting, remove anything that is not a host effect - // from the effect tag. - _next.flags &= HostEffectMask; - workInProgress = _next; - return; - } - - if ( (completedWork.mode & ProfileMode) !== NoMode) { - // Record the render duration for the fiber that errored. - stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing. - - var actualDuration = completedWork.actualDuration; - var child = completedWork.child; - - while (child !== null) { - actualDuration += child.actualDuration; - child = child.sibling; - } - - completedWork.actualDuration = actualDuration; - } - - if (returnFiber !== null) { - // Mark the parent fiber as incomplete and clear its subtree flags. - returnFiber.flags |= Incomplete; - returnFiber.subtreeFlags = NoFlags; - returnFiber.deletions = null; - } else { - // We've unwound all the way to the root. - workInProgressRootExitStatus = RootDidNotComplete; - workInProgress = null; - return; - } - } - - var siblingFiber = completedWork.sibling; - - if (siblingFiber !== null) { - // If there is more work to do in this returnFiber, do that next. - workInProgress = siblingFiber; - return; - } // Otherwise, return to the parent - - - completedWork = returnFiber; // Update the next thing we're working on in case something throws. - - workInProgress = completedWork; - } while (completedWork !== null); // We've reached the root. - - - if (workInProgressRootExitStatus === RootInProgress) { - workInProgressRootExitStatus = RootCompleted; - } - } - - function commitRoot(root, recoverableErrors) { - // TODO: This no longer makes any sense. We already wrap the mutation and - // layout phases. Should be able to remove. - var previousUpdateLanePriority = getCurrentUpdatePriority(); - var prevTransition = ReactCurrentBatchConfig$2.transition; - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - commitRootImpl(root, recoverableErrors, previousUpdateLanePriority); - } finally { - ReactCurrentBatchConfig$2.transition = prevTransition; - setCurrentUpdatePriority(previousUpdateLanePriority); - } - - return null; - } - - function commitRootImpl(root, recoverableErrors, renderPriorityLevel) { - do { - // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which - // means `flushPassiveEffects` will sometimes result in additional - // passive effects. So we need to keep flushing in a loop until there are - // no more pending effects. - // TODO: Might be better if `flushPassiveEffects` did not automatically - // flush synchronous work at the end, to avoid factoring hazards like this. - flushPassiveEffects(); - } while (rootWithPendingPassiveEffects !== null); - - flushRenderPhaseStrictModeWarningsInDEV(); - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Should not already be working.'); - } - - var finishedWork = root.finishedWork; - var lanes = root.finishedLanes; - - { - markCommitStarted(lanes); - } - - if (finishedWork === null) { - - { - markCommitStopped(); - } - - return null; - } else { - { - if (lanes === NoLanes) { - error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.'); - } - } - } - - root.finishedWork = null; - root.finishedLanes = NoLanes; - - if (finishedWork === root.current) { - throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.'); - } // commitRoot never returns a continuation; it always finishes synchronously. - // So we can clear these now to allow a new callback to be scheduled. - - - root.callbackNode = null; - root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first - // pending time is whatever is left on the root fiber. - - var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); - markRootFinished(root, remainingLanes); - - if (root === workInProgressRoot) { - // We can reset these now that they are finished. - workInProgressRoot = null; - workInProgress = null; - workInProgressRootRenderLanes = NoLanes; - } // If there are pending passive effects, schedule a callback to process them. - // Do this as early as possible, so it is queued before anything else that - // might get scheduled in the commit phase. (See #16714.) - // TODO: Delete all other places that schedule the passive effect callback - // They're redundant. - - - if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { - if (!rootDoesHavePassiveEffects) { - rootDoesHavePassiveEffects = true; - scheduleCallback$1(NormalPriority, function () { - flushPassiveEffects(); // This render triggered passive effects: release the root cache pool - // *after* passive effects fire to avoid freeing a cache pool that may - // be referenced by a node in the tree (HostRoot, Cache boundary etc) - - return null; - }); - } - } // Check if there are any effects in the whole tree. - // TODO: This is left over from the effect list implementation, where we had - // to check for the existence of `firstEffect` to satisfy Flow. I think the - // only other reason this optimization exists is because it affects profiling. - // Reconsider whether this is necessary. - - - var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; - var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; - - if (subtreeHasEffects || rootHasEffect) { - var prevTransition = ReactCurrentBatchConfig$2.transition; - ReactCurrentBatchConfig$2.transition = null; - var previousPriority = getCurrentUpdatePriority(); - setCurrentUpdatePriority(DiscreteEventPriority); - var prevExecutionContext = executionContext; - executionContext |= CommitContext; // Reset this to null before calling lifecycles - - ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass - // of the effect list for each phase: all mutation effects come before all - // layout effects, and so on. - // The first phase a "before mutation" phase. We use this phase to read the - // state of the host tree right before we mutate it. This is where - // getSnapshotBeforeUpdate is called. - - commitBeforeMutationEffects(root, finishedWork); - - { - // Mark the current commit time to be shared by all Profilers in this - // batch. This enables them to be grouped later. - recordCommitTime(); - } - - - commitMutationEffects(root, finishedWork, lanes); - - resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after - // the mutation phase, so that the previous tree is still current during - // componentWillUnmount, but before the layout phase, so that the finished - // work is current during componentDidMount/Update. - - root.current = finishedWork; // The next phase is the layout phase, where we call effects that read - - { - markLayoutEffectsStarted(lanes); - } - - commitLayoutEffects(finishedWork, root, lanes); - - { - markLayoutEffectsStopped(); - } - // opportunity to paint. - - - requestPaint(); - executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value. - - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - } else { - // No effects. - root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were - // no effects. - // TODO: Maybe there's a better way to report this. - - { - recordCommitTime(); - } - } - - var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; - - if (rootDoesHavePassiveEffects) { - // This commit has passive effects. Stash a reference to them. But don't - // schedule a callback until after flushing layout work. - rootDoesHavePassiveEffects = false; - rootWithPendingPassiveEffects = root; - pendingPassiveEffectsLanes = lanes; - } // Read this again, since an effect might have updated it - - - remainingLanes = root.pendingLanes; // Check if there's remaining work on this root - // TODO: This is part of the `componentDidCatch` implementation. Its purpose - // is to detect whether something might have called setState inside - // `componentDidCatch`. The mechanism is known to be flawed because `setState` - // inside `componentDidCatch` is itself flawed — that's why we recommend - // `getDerivedStateFromError` instead. However, it could be improved by - // checking if remainingLanes includes Sync work, instead of whether there's - // any work remaining at all (which would also include stuff like Suspense - // retries or transitions). It's been like this for a while, though, so fixing - // it probably isn't that urgent. - - if (remainingLanes === NoLanes) { - // If there's no remaining work, we can clear the set of already failed - // error boundaries. - legacyErrorBoundariesThatAlreadyFailed = null; - } - - { - if (!rootDidHavePassiveEffects) { - commitDoubleInvokeEffectsInDEV(root.current, false); - } - } - - onCommitRoot(finishedWork.stateNode, renderPriorityLevel); - - { - if (isDevToolsPresent) { - root.memoizedUpdaters.clear(); - } - } - - { - onCommitRoot$1(); - } // Always call this before exiting `commitRoot`, to ensure that any - // additional work on this root is scheduled. - - - ensureRootIsScheduled(root, now$1()); - - if (recoverableErrors !== null) { - // There were errors during this render, but recovered from them without - // needing to surface it to the UI. We log them here. - var onRecoverableError = root.onRecoverableError; - - for (var i = 0; i < recoverableErrors.length; i++) { - var recoverableError = recoverableErrors[i]; - onRecoverableError(recoverableError); - } - } - - if (hasUncaughtError) { - hasUncaughtError = false; - var error$1 = firstUncaughtError; - firstUncaughtError = null; - throw error$1; - } // If the passive effects are the result of a discrete render, flush them - // synchronously at the end of the current task so that the result is - // immediately observable. Otherwise, we assume that they are not - // order-dependent and do not need to be observed by external systems, so we - // can wait until after paint. - // TODO: We can optimize this by not scheduling the callback earlier. Since we - // currently schedule the callback in multiple places, will wait until those - // are consolidated. - - - if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) { - flushPassiveEffects(); - } // Read this again, since a passive effect might have updated it - - - remainingLanes = root.pendingLanes; - - if (includesSomeLane(remainingLanes, SyncLane)) { - { - markNestedUpdateScheduled(); - } // Count the number of times the root synchronously re-renders without - // finishing. If there are too many, it indicates an infinite update loop. - - - if (root === rootWithNestedUpdates) { - nestedUpdateCount++; - } else { - nestedUpdateCount = 0; - rootWithNestedUpdates = root; - } - } else { - nestedUpdateCount = 0; - } // If layout work was scheduled, flush it now. - - - flushSyncCallbacks(); - - { - markCommitStopped(); - } - - return null; - } - - function flushPassiveEffects() { - // Returns whether passive effects were flushed. - // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should - // probably just combine the two functions. I believe they were only separate - // in the first place because we used to wrap it with - // `Scheduler.runWithPriority`, which accepts a function. But now we track the - // priority within React itself, so we can mutate the variable directly. - if (rootWithPendingPassiveEffects !== null) { - var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); - var priority = lowerEventPriority(DefaultEventPriority, renderPriority); - var prevTransition = ReactCurrentBatchConfig$2.transition; - var previousPriority = getCurrentUpdatePriority(); - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(priority); - return flushPassiveEffectsImpl(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; // Once passive effects have run for the tree - giving components a - } - } - - return false; - } - function enqueuePendingPassiveProfilerEffect(fiber) { - { - pendingPassiveProfilerEffects.push(fiber); - - if (!rootDoesHavePassiveEffects) { - rootDoesHavePassiveEffects = true; - scheduleCallback$1(NormalPriority, function () { - flushPassiveEffects(); - return null; - }); - } - } - } - - function flushPassiveEffectsImpl() { - if (rootWithPendingPassiveEffects === null) { - return false; - } - - var root = rootWithPendingPassiveEffects; - var lanes = pendingPassiveEffectsLanes; - rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects. - // Figure out why and fix it. It's not causing any known issues (probably - // because it's only used for profiling), but it's a refactor hazard. - - pendingPassiveEffectsLanes = NoLanes; - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Cannot flush passive effects while already rendering.'); - } - - { - markPassiveEffectsStarted(lanes); - } - - var prevExecutionContext = executionContext; - executionContext |= CommitContext; - commitPassiveUnmountEffects(root.current); - commitPassiveMountEffects(root, root.current); // TODO: Move to commitPassiveMountEffects - - { - var profilerEffects = pendingPassiveProfilerEffects; - pendingPassiveProfilerEffects = []; - - for (var i = 0; i < profilerEffects.length; i++) { - var _fiber = profilerEffects[i]; - commitPassiveEffectDurations(root, _fiber); - } - } - - { - markPassiveEffectsStopped(); - } - - { - commitDoubleInvokeEffectsInDEV(root.current, true); - } - - executionContext = prevExecutionContext; - flushSyncCallbacks(); // If additional passive effects were scheduled, increment a counter. If this - // exceeds the limit, we'll fire a warning. - - nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1; // TODO: Move to commitPassiveMountEffects - - onPostCommitRoot(root); - - { - var stateNode = root.current.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - - return true; - } - - function isAlreadyFailedLegacyErrorBoundary(instance) { - return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); - } - function markLegacyErrorBoundaryAsFailed(instance) { - if (legacyErrorBoundariesThatAlreadyFailed === null) { - legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); - } else { - legacyErrorBoundariesThatAlreadyFailed.add(instance); - } - } - - function prepareToThrowUncaughtError(error) { - if (!hasUncaughtError) { - hasUncaughtError = true; - firstUncaughtError = error; - } - } - - var onUncaughtError = prepareToThrowUncaughtError; - - function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { - var errorInfo = createCapturedValue(error, sourceFiber); - var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); - enqueueUpdate(rootFiber, update); - var eventTime = requestEventTime(); - var root = markUpdateLaneFromFiberToRoot(rootFiber, SyncLane); - - if (root !== null) { - markRootUpdated(root, SyncLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - } - - function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { - if (sourceFiber.tag === HostRoot) { - // Error was thrown at the root. There is no parent, so the root - // itself should capture it. - captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1); - return; - } - - var fiber = null; - - { - fiber = nearestMountedAncestor; - } - - while (fiber !== null) { - if (fiber.tag === HostRoot) { - captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1); - return; - } else if (fiber.tag === ClassComponent) { - var ctor = fiber.type; - var instance = fiber.stateNode; - - if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) { - var errorInfo = createCapturedValue(error$1, sourceFiber); - var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); - enqueueUpdate(fiber, update); - var eventTime = requestEventTime(); - var root = markUpdateLaneFromFiberToRoot(fiber, SyncLane); - - if (root !== null) { - markRootUpdated(root, SyncLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - - return; - } - } - - fiber = fiber.return; - } - - { - // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning - // will fire for errors that are thrown by destroy functions inside deleted - // trees. What it should instead do is propagate the error to the parent of - // the deleted tree. In the meantime, do not add this warning to the - // allowlist; this is only for our internal use. - error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1); - } - } - function pingSuspendedRoot(root, wakeable, pingedLanes) { - var pingCache = root.pingCache; - - if (pingCache !== null) { - // The wakeable resolved, so we no longer need to memoize, because it will - // never be thrown again. - pingCache.delete(wakeable); - } - - var eventTime = requestEventTime(); - markRootPinged(root, pingedLanes); - warnIfSuspenseResolutionNotWrappedWithActDEV(root); - - if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { - // Received a ping at the same priority level at which we're currently - // rendering. We might want to restart this render. This should mirror - // the logic of whether or not a root suspends once it completes. - // TODO: If we're rendering sync either due to Sync, Batched or expired, - // we should probably never restart. - // If we're suspended with delay, or if it's a retry, we'll always suspend - // so we can always restart. - if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now$1() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { - // Restart from the root. - prepareFreshStack(root, NoLanes); - } else { - // Even though we can't restart right now, we might get an - // opportunity later. So we mark this render as having a ping. - workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); - } - } - - ensureRootIsScheduled(root, eventTime); - } - - function retryTimedOutBoundary(boundaryFiber, retryLane) { - // The boundary fiber (a Suspense component or SuspenseList component) - // previously was rendered in its fallback state. One of the promises that - // suspended it has resolved, which means at least part of the tree was - // likely unblocked. Try rendering again, at a new lanes. - if (retryLane === NoLane) { - // TODO: Assign this to `suspenseState.retryLane`? to avoid - // unnecessary entanglement? - retryLane = requestRetryLane(boundaryFiber); - } // TODO: Special case idle priority? - - - var eventTime = requestEventTime(); - var root = markUpdateLaneFromFiberToRoot(boundaryFiber, retryLane); - - if (root !== null) { - markRootUpdated(root, retryLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - } - - function retryDehydratedSuspenseBoundary(boundaryFiber) { - var suspenseState = boundaryFiber.memoizedState; - var retryLane = NoLane; - - if (suspenseState !== null) { - retryLane = suspenseState.retryLane; - } - - retryTimedOutBoundary(boundaryFiber, retryLane); - } - function resolveRetryWakeable(boundaryFiber, wakeable) { - var retryLane = NoLane; // Default - - var retryCache; - - { - switch (boundaryFiber.tag) { - case SuspenseComponent: - retryCache = boundaryFiber.stateNode; - var suspenseState = boundaryFiber.memoizedState; - - if (suspenseState !== null) { - retryLane = suspenseState.retryLane; - } - - break; - - case SuspenseListComponent: - retryCache = boundaryFiber.stateNode; - break; - - default: - throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.'); - } - } - - if (retryCache !== null) { - // The wakeable resolved, so we no longer need to memoize, because it will - // never be thrown again. - retryCache.delete(wakeable); - } - - retryTimedOutBoundary(boundaryFiber, retryLane); - } // Computes the next Just Noticeable Difference (JND) boundary. - // The theory is that a person can't tell the difference between small differences in time. - // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable - // difference in the experience. However, waiting for longer might mean that we can avoid - // showing an intermediate loading state. The longer we have already waited, the harder it - // is to tell small differences in time. Therefore, the longer we've already waited, - // the longer we can wait additionally. At some point we have to give up though. - // We pick a train model where the next boundary commits at a consistent schedule. - // These particular numbers are vague estimates. We expect to adjust them based on research. - - function jnd(timeElapsed) { - return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960; - } - - function checkForNestedUpdates() { - if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { - nestedUpdateCount = 0; - rootWithNestedUpdates = null; - throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.'); - } - - { - if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { - nestedPassiveUpdateCount = 0; - - error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.'); - } - } - } - - function flushRenderPhaseStrictModeWarningsInDEV() { - { - ReactStrictModeWarnings.flushLegacyContextWarning(); - - { - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); - } - } - } - - function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) { - { - // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects - // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level. - // Maybe not a big deal since this is DEV only behavior. - setCurrentFiber(fiber); - invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); - - if (hasPassiveEffects) { - invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); - } - - invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); - - if (hasPassiveEffects) { - invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); - } - - resetCurrentFiber(); - } - } - - function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - var current = firstChild; - var subtreeRoot = null; - - while (current !== null) { - var primarySubtreeFlag = current.subtreeFlags & fiberFlags; - - if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) { - current = current.child; - } else { - if ((current.flags & fiberFlags) !== NoFlags) { - invokeEffectFn(current); - } - - if (current.sibling !== null) { - current = current.sibling; - } else { - current = subtreeRoot = current.return; - } - } - } - } - } - - var didWarnStateUpdateForNotYetMountedComponent = null; - - function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { - { - if ((executionContext & RenderContext) !== NoContext) { - // We let the other warning about render phase updates deal with this one. - return; - } - - if (!(fiber.mode & ConcurrentMode)) { - return; - } - - var tag = fiber.tag; - - if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) { - // Only warn for user-defined components, not internal ones like Suspense. - return; - } // We show the whole stack but dedupe on the top component's name because - // the problematic code almost always lies inside that component. - - - var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent'; - - if (didWarnStateUpdateForNotYetMountedComponent !== null) { - if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { - return; - } - - didWarnStateUpdateForNotYetMountedComponent.add(componentName); - } else { - didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]); - } - - var previousFiber = current; - - try { - setCurrentFiber(fiber); - - error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.'); - } finally { - if (previousFiber) { - setCurrentFiber(fiber); - } else { - resetCurrentFiber(); - } - } - } - } - - var beginWork$1; - - { - var dummyFiber = null; - - beginWork$1 = function (current, unitOfWork, lanes) { - // If a component throws an error, we replay it again in a synchronously - // dispatched event, so that the debugger will treat it as an uncaught - // error See ReactErrorUtils for more information. - // Before entering the begin phase, copy the work-in-progress onto a dummy - // fiber. If beginWork throws, we'll use this to reset the state. - var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); - - try { - return beginWork(current, unitOfWork, lanes); - } catch (originalError) { - if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') { - // Don't replay promises. Treat everything else like an error. - throw originalError; - } // Keep this code in sync with handleError; any changes here must have - // corresponding changes there. - - - resetContextDependencies(); - resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the - // same fiber again. - // Unwind the failed stack frame - - unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber. - - assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); - - if ( unitOfWork.mode & ProfileMode) { - // Reset the profiler timer. - startProfilerTimer(unitOfWork); - } // Run beginWork again. - - - invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes); - - if (hasCaughtError()) { - var replayError = clearCaughtError(); - - if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) { - // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. - originalError._suppressLogging = true; - } - } // We always throw the original error in case the second render pass is not idempotent. - // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. - - - throw originalError; - } - }; - } - - var didWarnAboutUpdateInRender = false; - var didWarnAboutUpdateInRenderForAnotherComponent; - - { - didWarnAboutUpdateInRenderForAnotherComponent = new Set(); - } - - function warnAboutRenderPhaseUpdatesInDEV(fiber) { - { - if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) { - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed. - - var dedupeKey = renderingComponentName; - - if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { - didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); - var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown'; - - error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName); - } - - break; - } - - case ClassComponent: - { - if (!didWarnAboutUpdateInRender) { - error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.'); - - didWarnAboutUpdateInRender = true; - } - - break; - } - } - } - } - } - - function restorePendingUpdaters(root, lanes) { - { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - memoizedUpdaters.forEach(function (schedulingFiber) { - addFiberToLanesMap(root, schedulingFiber, lanes); - }); // This function intentionally does not clear memoized updaters. - // Those may still be relevant to the current commit - // and a future one (e.g. Suspense). - } - } - } - var fakeActCallbackNode = {}; - - function scheduleCallback$1(priorityLevel, callback) { - { - // If we're currently inside an `act` scope, bypass Scheduler and push to - // the `act` queue instead. - var actQueue = ReactCurrentActQueue$1.current; - - if (actQueue !== null) { - actQueue.push(callback); - return fakeActCallbackNode; - } else { - return scheduleCallback(priorityLevel, callback); - } - } - } - - function cancelCallback$1(callbackNode) { - if ( callbackNode === fakeActCallbackNode) { - return; - } // In production, always call Scheduler. This function will be stripped out. - - - return cancelCallback(callbackNode); - } - - function shouldForceFlushFallbacksInDEV() { - // Never force flush in production. This function should get stripped out. - return ReactCurrentActQueue$1.current !== null; - } - - function warnIfUpdatesNotWrappedWithActDEV(fiber) { - { - if (fiber.mode & ConcurrentMode) { - if (!isConcurrentActEnvironment()) { - // Not in an act environment. No need to warn. - return; - } - } else { - // Legacy mode has additional cases where we suppress a warning. - if (!isLegacyActEnvironment()) { - // Not in an act environment. No need to warn. - return; - } - - if (executionContext !== NoContext) { - // Legacy mode doesn't warn if the update is batched, i.e. - // batchedUpdates or flushSync. - return; - } - - if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { - // For backwards compatibility with pre-hooks code, legacy mode only - // warns for updates that originate from a hook. - return; - } - } - - if (ReactCurrentActQueue$1.current === null) { - var previousFiber = current; - - try { - setCurrentFiber(fiber); - - error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber)); - } finally { - if (previousFiber) { - setCurrentFiber(fiber); - } else { - resetCurrentFiber(); - } - } - } - } - } - - function warnIfSuspenseResolutionNotWrappedWithActDEV(root) { - { - if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) { - error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + ' /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act'); - } - } - } - - /* eslint-disable react-internal/prod-error-codes */ - var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. - - var failedBoundaries = null; - var setRefreshHandler = function (handler) { - { - resolveFamily = handler; - } - }; - function resolveFunctionForHotReloading(type) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return type; - } - - var family = resolveFamily(type); - - if (family === undefined) { - return type; - } // Use the latest known implementation. - - - return family.current; - } - } - function resolveClassForHotReloading(type) { - // No implementation differences. - return resolveFunctionForHotReloading(type); - } - function resolveForwardRefForHotReloading(type) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return type; - } - - var family = resolveFamily(type); - - if (family === undefined) { - // Check if we're dealing with a real forwardRef. Don't want to crash early. - if (type !== null && type !== undefined && typeof type.render === 'function') { - // ForwardRef is special because its resolved .type is an object, - // but it's possible that we only have its inner render function in the map. - // If that inner render function is different, we'll build a new forwardRef type. - var currentRender = resolveFunctionForHotReloading(type.render); - - if (type.render !== currentRender) { - var syntheticType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render: currentRender - }; - - if (type.displayName !== undefined) { - syntheticType.displayName = type.displayName; - } - - return syntheticType; - } - } - - return type; - } // Use the latest known implementation. - - - return family.current; - } - } - function isCompatibleFamilyForHotReloading(fiber, element) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return false; - } - - var prevType = fiber.elementType; - var nextType = element.type; // If we got here, we know types aren't === equal. - - var needsCompareFamilies = false; - var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null; - - switch (fiber.tag) { - case ClassComponent: - { - if (typeof nextType === 'function') { - needsCompareFamilies = true; - } - - break; - } - - case FunctionComponent: - { - if (typeof nextType === 'function') { - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - // We don't know the inner type yet. - // We're going to assume that the lazy inner type is stable, - // and so it is sufficient to avoid reconciling it away. - // We're not going to unwrap or actually use the new lazy type. - needsCompareFamilies = true; - } - - break; - } - - case ForwardRef: - { - if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - needsCompareFamilies = true; - } - - break; - } - - case MemoComponent: - case SimpleMemoComponent: - { - if ($$typeofNextType === REACT_MEMO_TYPE) { - // TODO: if it was but can no longer be simple, - // we shouldn't set this. - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - needsCompareFamilies = true; - } - - break; - } - - default: - return false; - } // Check if both types have a family and it's the same one. - - - if (needsCompareFamilies) { - // Note: memo() and forwardRef() we'll compare outer rather than inner type. - // This means both of them need to be registered to preserve state. - // If we unwrapped and compared the inner types for wrappers instead, - // then we would risk falsely saying two separate memo(Foo) - // calls are equivalent because they wrap the same Foo function. - var prevFamily = resolveFamily(prevType); - - if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { - return true; - } - } - - return false; - } - } - function markFailedErrorBoundaryForHotReloading(fiber) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return; - } - - if (typeof WeakSet !== 'function') { - return; - } - - if (failedBoundaries === null) { - failedBoundaries = new WeakSet(); - } - - failedBoundaries.add(fiber); - } - } - var scheduleRefresh = function (root, update) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return; - } - - var staleFamilies = update.staleFamilies, - updatedFamilies = update.updatedFamilies; - flushPassiveEffects(); - flushSync(function () { - scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies); - }); - } - }; - var scheduleRoot = function (root, element) { - { - if (root.context !== emptyContextObject) { - // Super edge case: root has a legacy _renderSubtree context - // but we don't know the parentComponent so we can't pass it. - // Just ignore. We'll delete this with _renderSubtree code path later. - return; - } - - flushPassiveEffects(); - flushSync(function () { - updateContainer(element, root, null, null); - }); - } - }; - - function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { - { - var alternate = fiber.alternate, - child = fiber.child, - sibling = fiber.sibling, - tag = fiber.tag, - type = fiber.type; - var candidateType = null; - - switch (tag) { - case FunctionComponent: - case SimpleMemoComponent: - case ClassComponent: - candidateType = type; - break; - - case ForwardRef: - candidateType = type.render; - break; - } - - if (resolveFamily === null) { - throw new Error('Expected resolveFamily to be set during hot reload.'); - } - - var needsRender = false; - var needsRemount = false; - - if (candidateType !== null) { - var family = resolveFamily(candidateType); - - if (family !== undefined) { - if (staleFamilies.has(family)) { - needsRemount = true; - } else if (updatedFamilies.has(family)) { - if (tag === ClassComponent) { - needsRemount = true; - } else { - needsRender = true; - } - } - } - } - - if (failedBoundaries !== null) { - if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) { - needsRemount = true; - } - } - - if (needsRemount) { - fiber._debugNeedsRemount = true; - } - - if (needsRemount || needsRender) { - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - - if (child !== null && !needsRemount) { - scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); - } - - if (sibling !== null) { - scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); - } - } - } - - var findHostInstancesForRefresh = function (root, families) { - { - var hostInstances = new Set(); - var types = new Set(families.map(function (family) { - return family.current; - })); - findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances); - return hostInstances; - } - }; - - function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { - { - var child = fiber.child, - sibling = fiber.sibling, - tag = fiber.tag, - type = fiber.type; - var candidateType = null; - - switch (tag) { - case FunctionComponent: - case SimpleMemoComponent: - case ClassComponent: - candidateType = type; - break; - - case ForwardRef: - candidateType = type.render; - break; - } - - var didMatch = false; - - if (candidateType !== null) { - if (types.has(candidateType)) { - didMatch = true; - } - } - - if (didMatch) { - // We have a match. This only drills down to the closest host components. - // There's no need to search deeper because for the purpose of giving - // visual feedback, "flashing" outermost parent rectangles is sufficient. - findHostInstancesForFiberShallowly(fiber, hostInstances); - } else { - // If there's no match, maybe there will be one further down in the child tree. - if (child !== null) { - findHostInstancesForMatchingFibersRecursively(child, types, hostInstances); - } - } - - if (sibling !== null) { - findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); - } - } - } - - function findHostInstancesForFiberShallowly(fiber, hostInstances) { - { - var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances); - - if (foundHostInstances) { - return; - } // If we didn't find any host children, fallback to closest host parent. - - - var node = fiber; - - while (true) { - switch (node.tag) { - case HostComponent: - hostInstances.add(node.stateNode); - return; - - case HostPortal: - hostInstances.add(node.stateNode.containerInfo); - return; - - case HostRoot: - hostInstances.add(node.stateNode.containerInfo); - return; - } - - if (node.return === null) { - throw new Error('Expected to reach root first.'); - } - - node = node.return; - } - } - } - - function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { - { - var node = fiber; - var foundHostInstances = false; - - while (true) { - if (node.tag === HostComponent) { - // We got a match. - foundHostInstances = true; - hostInstances.add(node.stateNode); // There may still be more, so keep searching. - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === fiber) { - return foundHostInstances; - } - - while (node.sibling === null) { - if (node.return === null || node.return === fiber) { - return foundHostInstances; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - - return false; - } - - var hasBadMapPolyfill; - - { - hasBadMapPolyfill = false; - - try { - var nonExtensibleObject = Object.preventExtensions({}); - /* eslint-disable no-new */ - - new Map([[nonExtensibleObject, null]]); - new Set([nonExtensibleObject]); - /* eslint-enable no-new */ - } catch (e) { - // TODO: Consider warning about bad polyfills - hasBadMapPolyfill = true; - } - } - - function FiberNode(tag, pendingProps, key, mode) { - // Instance - this.tag = tag; - this.key = key; - this.elementType = null; - this.type = null; - this.stateNode = null; // Fiber - - this.return = null; - this.child = null; - this.sibling = null; - this.index = 0; - this.ref = null; - this.pendingProps = pendingProps; - this.memoizedProps = null; - this.updateQueue = null; - this.memoizedState = null; - this.dependencies = null; - this.mode = mode; // Effects - - this.flags = NoFlags; - this.subtreeFlags = NoFlags; - this.deletions = null; - this.lanes = NoLanes; - this.childLanes = NoLanes; - this.alternate = null; - - { - // Note: The following is done to avoid a v8 performance cliff. - // - // Initializing the fields below to smis and later updating them with - // double values will cause Fibers to end up having separate shapes. - // This behavior/bug has something to do with Object.preventExtension(). - // Fortunately this only impacts DEV builds. - // Unfortunately it makes React unusably slow for some applications. - // To work around this, initialize the fields below with doubles. - // - // Learn more about this here: - // https://github.com/facebook/react/issues/14365 - // https://bugs.chromium.org/p/v8/issues/detail?id=8538 - this.actualDuration = Number.NaN; - this.actualStartTime = Number.NaN; - this.selfBaseDuration = Number.NaN; - this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. - // This won't trigger the performance cliff mentioned above, - // and it simplifies other profiler code (including DevTools). - - this.actualDuration = 0; - this.actualStartTime = -1; - this.selfBaseDuration = 0; - this.treeBaseDuration = 0; - } - - { - // This isn't directly used but is handy for debugging internals: - this._debugSource = null; - this._debugOwner = null; - this._debugNeedsRemount = false; - this._debugHookTypes = null; - - if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { - Object.preventExtensions(this); - } - } - } // This is a constructor function, rather than a POJO constructor, still - // please ensure we do the following: - // 1) Nobody should add any instance methods on this. Instance methods can be - // more difficult to predict when they get optimized and they are almost - // never inlined properly in static compilers. - // 2) Nobody should rely on `instanceof Fiber` for type testing. We should - // always know when it is a fiber. - // 3) We might want to experiment with using numeric keys since they are easier - // to optimize in a non-JIT environment. - // 4) We can easily go from a constructor to a createFiber object literal if that - // is faster. - // 5) It should be easy to port this to a C struct and keep a C implementation - // compatible. - - - var createFiber = function (tag, pendingProps, key, mode) { - // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors - return new FiberNode(tag, pendingProps, key, mode); - }; - - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function isSimpleFunctionComponent(type) { - return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined; - } - function resolveLazyComponentTag(Component) { - if (typeof Component === 'function') { - return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent; - } else if (Component !== undefined && Component !== null) { - var $$typeof = Component.$$typeof; - - if ($$typeof === REACT_FORWARD_REF_TYPE) { - return ForwardRef; - } - - if ($$typeof === REACT_MEMO_TYPE) { - return MemoComponent; - } - } - - return IndeterminateComponent; - } // This is used to create an alternate fiber to do work on. - - function createWorkInProgress(current, pendingProps) { - var workInProgress = current.alternate; - - if (workInProgress === null) { - // We use a double buffering pooling technique because we know that we'll - // only ever need at most two versions of a tree. We pool the "other" unused - // node that we're free to reuse. This is lazily created to avoid allocating - // extra objects for things that are never updated. It also allow us to - // reclaim the extra memory if needed. - workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode); - workInProgress.elementType = current.elementType; - workInProgress.type = current.type; - workInProgress.stateNode = current.stateNode; - - { - // DEV-only fields - workInProgress._debugSource = current._debugSource; - workInProgress._debugOwner = current._debugOwner; - workInProgress._debugHookTypes = current._debugHookTypes; - } - - workInProgress.alternate = current; - current.alternate = workInProgress; - } else { - workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type. - - workInProgress.type = current.type; // We already have an alternate. - // Reset the effect tag. - - workInProgress.flags = NoFlags; // The effects are no longer valid. - - workInProgress.subtreeFlags = NoFlags; - workInProgress.deletions = null; - - { - // We intentionally reset, rather than copy, actualDuration & actualStartTime. - // This prevents time from endlessly accumulating in new commits. - // This has the downside of resetting values for different priority renders, - // But works for yielding (the common case) and should support resuming. - workInProgress.actualDuration = 0; - workInProgress.actualStartTime = -1; - } - } // Reset all effects except static ones. - // Static effects are not specific to a render. - - - workInProgress.flags = current.flags & StaticMask; - workInProgress.childLanes = current.childLanes; - workInProgress.lanes = current.lanes; - workInProgress.child = current.child; - workInProgress.memoizedProps = current.memoizedProps; - workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so - // it cannot be shared with the current fiber. - - var currentDependencies = current.dependencies; - workInProgress.dependencies = currentDependencies === null ? null : { - lanes: currentDependencies.lanes, - firstContext: currentDependencies.firstContext - }; // These will be overridden during the parent's reconciliation - - workInProgress.sibling = current.sibling; - workInProgress.index = current.index; - workInProgress.ref = current.ref; - - { - workInProgress.selfBaseDuration = current.selfBaseDuration; - workInProgress.treeBaseDuration = current.treeBaseDuration; - } - - { - workInProgress._debugNeedsRemount = current._debugNeedsRemount; - - switch (workInProgress.tag) { - case IndeterminateComponent: - case FunctionComponent: - case SimpleMemoComponent: - workInProgress.type = resolveFunctionForHotReloading(current.type); - break; - - case ClassComponent: - workInProgress.type = resolveClassForHotReloading(current.type); - break; - - case ForwardRef: - workInProgress.type = resolveForwardRefForHotReloading(current.type); - break; - } - } - - return workInProgress; - } // Used to reuse a Fiber for a second pass. - - function resetWorkInProgress(workInProgress, renderLanes) { - // This resets the Fiber to what createFiber or createWorkInProgress would - // have set the values to before during the first pass. Ideally this wouldn't - // be necessary but unfortunately many code paths reads from the workInProgress - // when they should be reading from current and writing to workInProgress. - // We assume pendingProps, index, key, ref, return are still untouched to - // avoid doing another reconciliation. - // Reset the effect flags but keep any Placement tags, since that's something - // that child fiber is setting, not the reconciliation. - workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid. - - var current = workInProgress.alternate; - - if (current === null) { - // Reset to createFiber's initial values. - workInProgress.childLanes = NoLanes; - workInProgress.lanes = renderLanes; - workInProgress.child = null; - workInProgress.subtreeFlags = NoFlags; - workInProgress.memoizedProps = null; - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - workInProgress.dependencies = null; - workInProgress.stateNode = null; - - { - // Note: We don't reset the actualTime counts. It's useful to accumulate - // actual time across multiple render passes. - workInProgress.selfBaseDuration = 0; - workInProgress.treeBaseDuration = 0; - } - } else { - // Reset to the cloned values that createWorkInProgress would've. - workInProgress.childLanes = current.childLanes; - workInProgress.lanes = current.lanes; - workInProgress.child = current.child; - workInProgress.subtreeFlags = NoFlags; - workInProgress.deletions = null; - workInProgress.memoizedProps = current.memoizedProps; - workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type. - - workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so - // it cannot be shared with the current fiber. - - var currentDependencies = current.dependencies; - workInProgress.dependencies = currentDependencies === null ? null : { - lanes: currentDependencies.lanes, - firstContext: currentDependencies.firstContext - }; - - { - // Note: We don't reset the actualTime counts. It's useful to accumulate - // actual time across multiple render passes. - workInProgress.selfBaseDuration = current.selfBaseDuration; - workInProgress.treeBaseDuration = current.treeBaseDuration; - } - } - - return workInProgress; - } - function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { - var mode; - - if (tag === ConcurrentRoot) { - mode = ConcurrentMode; - - if (isStrictMode === true) { - mode |= StrictLegacyMode; - - { - mode |= StrictEffectsMode; - } - } - } else { - mode = NoMode; - } - - if ( isDevToolsPresent) { - // Always collect profile timings when DevTools are present. - // This enables DevTools to start capturing timing at any point– - // Without some nodes in the tree having empty base times. - mode |= ProfileMode; - } - - return createFiber(HostRoot, null, null, mode); - } - function createFiberFromTypeAndProps(type, // React$ElementType - key, pendingProps, owner, mode, lanes) { - var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. - - var resolvedType = type; - - if (typeof type === 'function') { - if (shouldConstruct$1(type)) { - fiberTag = ClassComponent; - - { - resolvedType = resolveClassForHotReloading(resolvedType); - } - } else { - { - resolvedType = resolveFunctionForHotReloading(resolvedType); - } - } - } else if (typeof type === 'string') { - fiberTag = HostComponent; - } else { - getTag: switch (type) { - case REACT_FRAGMENT_TYPE: - return createFiberFromFragment(pendingProps.children, mode, lanes, key); - - case REACT_STRICT_MODE_TYPE: - fiberTag = Mode; - mode |= StrictLegacyMode; - - if ( (mode & ConcurrentMode) !== NoMode) { - // Strict effects should never run on legacy roots - mode |= StrictEffectsMode; - } - - break; - - case REACT_PROFILER_TYPE: - return createFiberFromProfiler(pendingProps, mode, lanes, key); - - case REACT_SUSPENSE_TYPE: - return createFiberFromSuspense(pendingProps, mode, lanes, key); - - case REACT_SUSPENSE_LIST_TYPE: - return createFiberFromSuspenseList(pendingProps, mode, lanes, key); - - case REACT_OFFSCREEN_TYPE: - return createFiberFromOffscreen(pendingProps, mode, lanes, key); - - case REACT_LEGACY_HIDDEN_TYPE: - - // eslint-disable-next-line no-fallthrough - - case REACT_SCOPE_TYPE: - - // eslint-disable-next-line no-fallthrough - - case REACT_CACHE_TYPE: - - // eslint-disable-next-line no-fallthrough - - case REACT_TRACING_MARKER_TYPE: - - // eslint-disable-next-line no-fallthrough - - case REACT_DEBUG_TRACING_MODE_TYPE: - - // eslint-disable-next-line no-fallthrough - - default: - { - if (typeof type === 'object' && type !== null) { - switch (type.$$typeof) { - case REACT_PROVIDER_TYPE: - fiberTag = ContextProvider; - break getTag; - - case REACT_CONTEXT_TYPE: - // This is a consumer - fiberTag = ContextConsumer; - break getTag; - - case REACT_FORWARD_REF_TYPE: - fiberTag = ForwardRef; - - { - resolvedType = resolveForwardRefForHotReloading(resolvedType); - } - - break getTag; - - case REACT_MEMO_TYPE: - fiberTag = MemoComponent; - break getTag; - - case REACT_LAZY_TYPE: - fiberTag = LazyComponent; - resolvedType = null; - break getTag; - } - } - - var info = ''; - - { - if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { - info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; - } - - var ownerName = owner ? getComponentNameFromFiber(owner) : null; - - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - } - - throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); - } - } - } - - var fiber = createFiber(fiberTag, pendingProps, key, mode); - fiber.elementType = type; - fiber.type = resolvedType; - fiber.lanes = lanes; - - { - fiber._debugOwner = owner; - } - - return fiber; - } - function createFiberFromElement(element, mode, lanes) { - var owner = null; - - { - owner = element._owner; - } - - var type = element.type; - var key = element.key; - var pendingProps = element.props; - var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes); - - { - fiber._debugSource = element._source; - fiber._debugOwner = element._owner; - } - - return fiber; - } - function createFiberFromFragment(elements, mode, lanes, key) { - var fiber = createFiber(Fragment, elements, key, mode); - fiber.lanes = lanes; - return fiber; - } - - function createFiberFromProfiler(pendingProps, mode, lanes, key) { - { - if (typeof pendingProps.id !== 'string') { - error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id); - } - } - - var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); - fiber.elementType = REACT_PROFILER_TYPE; - fiber.lanes = lanes; - - { - fiber.stateNode = { - effectDuration: 0, - passiveEffectDuration: 0 - }; - } - - return fiber; - } - - function createFiberFromSuspense(pendingProps, mode, lanes, key) { - var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); - fiber.elementType = REACT_SUSPENSE_TYPE; - fiber.lanes = lanes; - return fiber; - } - function createFiberFromSuspenseList(pendingProps, mode, lanes, key) { - var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); - fiber.elementType = REACT_SUSPENSE_LIST_TYPE; - fiber.lanes = lanes; - return fiber; - } - function createFiberFromOffscreen(pendingProps, mode, lanes, key) { - var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); - fiber.elementType = REACT_OFFSCREEN_TYPE; - fiber.lanes = lanes; - var primaryChildInstance = {}; - fiber.stateNode = primaryChildInstance; - return fiber; - } - function createFiberFromText(content, mode, lanes) { - var fiber = createFiber(HostText, content, null, mode); - fiber.lanes = lanes; - return fiber; - } - function createFiberFromHostInstanceForDeletion() { - var fiber = createFiber(HostComponent, null, null, NoMode); - fiber.elementType = 'DELETED'; - return fiber; - } - function createFiberFromDehydratedFragment(dehydratedNode) { - var fiber = createFiber(DehydratedFragment, null, null, NoMode); - fiber.stateNode = dehydratedNode; - return fiber; - } - function createFiberFromPortal(portal, mode, lanes) { - var pendingProps = portal.children !== null ? portal.children : []; - var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); - fiber.lanes = lanes; - fiber.stateNode = { - containerInfo: portal.containerInfo, - pendingChildren: null, - // Used by persistent updates - implementation: portal.implementation - }; - return fiber; - } // Used for stashing WIP properties to replay failed work in DEV. - - function assignFiberPropertiesInDEV(target, source) { - if (target === null) { - // This Fiber's initial properties will always be overwritten. - // We only use a Fiber to ensure the same hidden class so DEV isn't slow. - target = createFiber(IndeterminateComponent, null, null, NoMode); - } // This is intentionally written as a list of all properties. - // We tried to use Object.assign() instead but this is called in - // the hottest path, and Object.assign() was too slow: - // https://github.com/facebook/react/issues/12502 - // This code is DEV-only so size is not a concern. - - - target.tag = source.tag; - target.key = source.key; - target.elementType = source.elementType; - target.type = source.type; - target.stateNode = source.stateNode; - target.return = source.return; - target.child = source.child; - target.sibling = source.sibling; - target.index = source.index; - target.ref = source.ref; - target.pendingProps = source.pendingProps; - target.memoizedProps = source.memoizedProps; - target.updateQueue = source.updateQueue; - target.memoizedState = source.memoizedState; - target.dependencies = source.dependencies; - target.mode = source.mode; - target.flags = source.flags; - target.subtreeFlags = source.subtreeFlags; - target.deletions = source.deletions; - target.lanes = source.lanes; - target.childLanes = source.childLanes; - target.alternate = source.alternate; - - { - target.actualDuration = source.actualDuration; - target.actualStartTime = source.actualStartTime; - target.selfBaseDuration = source.selfBaseDuration; - target.treeBaseDuration = source.treeBaseDuration; - } - - target._debugSource = source._debugSource; - target._debugOwner = source._debugOwner; - target._debugNeedsRemount = source._debugNeedsRemount; - target._debugHookTypes = source._debugHookTypes; - return target; - } - - function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) { - this.tag = tag; - this.containerInfo = containerInfo; - this.pendingChildren = null; - this.current = null; - this.pingCache = null; - this.finishedWork = null; - this.timeoutHandle = noTimeout; - this.context = null; - this.pendingContext = null; - this.callbackNode = null; - this.callbackPriority = NoLane; - this.eventTimes = createLaneMap(NoLanes); - this.expirationTimes = createLaneMap(NoTimestamp); - this.pendingLanes = NoLanes; - this.suspendedLanes = NoLanes; - this.pingedLanes = NoLanes; - this.expiredLanes = NoLanes; - this.mutableReadLanes = NoLanes; - this.finishedLanes = NoLanes; - this.entangledLanes = NoLanes; - this.entanglements = createLaneMap(NoLanes); - this.identifierPrefix = identifierPrefix; - this.onRecoverableError = onRecoverableError; - - if (supportsHydration) { - this.mutableSourceEagerHydrationData = null; - } - - { - this.effectDuration = 0; - this.passiveEffectDuration = 0; - } - - { - this.memoizedUpdaters = new Set(); - var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = []; - - for (var _i = 0; _i < TotalLanes; _i++) { - pendingUpdatersLaneMap.push(new Set()); - } - } - - { - switch (tag) { - case ConcurrentRoot: - this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()'; - break; - - case LegacyRoot: - this._debugRootType = hydrate ? 'hydrate()' : 'render()'; - break; - } - } - } - - function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the - // host config, but because they are passed in at runtime, we have to thread - // them through the root constructor. Perhaps we should put them all into a - // single type, like a DynamicHostConfig that is defined by the renderer. - identifierPrefix, onRecoverableError, transitionCallbacks) { - var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); - // stateNode is any. - - - var uninitializedFiber = createHostRootFiber(tag, isStrictMode); - root.current = uninitializedFiber; - uninitializedFiber.stateNode = root; - - { - var _initialState = { - element: initialChildren, - isDehydrated: hydrate, - cache: null, - // not enabled yet - transitions: null - }; - uninitializedFiber.memoizedState = _initialState; - } - - initializeUpdateQueue(uninitializedFiber); - return root; - } - - var ReactVersion = '18.0.0-fc46dba67-20220329'; - - function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation. - implementation) { - var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - - { - checkKeyStringCoercion(key); - } - - return { - // This tag allow us to uniquely identify this as a React Portal - $$typeof: REACT_PORTAL_TYPE, - key: key == null ? null : '' + key, - children: children, - containerInfo: containerInfo, - implementation: implementation - }; - } - - var didWarnAboutNestedUpdates; - var didWarnAboutFindNodeInStrictMode; - - { - didWarnAboutNestedUpdates = false; - didWarnAboutFindNodeInStrictMode = {}; - } - - function getContextForSubtree(parentComponent) { - if (!parentComponent) { - return emptyContextObject; - } - - var fiber = get(parentComponent); - var parentContext = findCurrentUnmaskedContext(fiber); - - if (fiber.tag === ClassComponent) { - var Component = fiber.type; - - if (isContextProvider(Component)) { - return processChildContext(fiber, Component, parentContext); - } - } - - return parentContext; - } - - function findHostInstance(component) { - var fiber = get(component); - - if (fiber === undefined) { - if (typeof component.render === 'function') { - throw new Error('Unable to find node on an unmounted component.'); - } else { - var keys = Object.keys(component).join(','); - throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); - } - } - - var hostFiber = findCurrentHostFiber(fiber); - - if (hostFiber === null) { - return null; - } - - return hostFiber.stateNode; - } - - function findHostInstanceWithWarning(component, methodName) { - { - var fiber = get(component); - - if (fiber === undefined) { - if (typeof component.render === 'function') { - throw new Error('Unable to find node on an unmounted component.'); - } else { - var keys = Object.keys(component).join(','); - throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); - } - } - - var hostFiber = findCurrentHostFiber(fiber); - - if (hostFiber === null) { - return null; - } - - if (hostFiber.mode & StrictLegacyMode) { - var componentName = getComponentNameFromFiber(fiber) || 'Component'; - - if (!didWarnAboutFindNodeInStrictMode[componentName]) { - didWarnAboutFindNodeInStrictMode[componentName] = true; - var previousFiber = current; - - try { - setCurrentFiber(hostFiber); - - if (fiber.mode & StrictLegacyMode) { - error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); - } else { - error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); - } - } finally { - // Ideally this should reset to previous but this shouldn't be called in - // render and there's another warning for that anyway. - if (previousFiber) { - setCurrentFiber(previousFiber); - } else { - resetCurrentFiber(); - } - } - } - } - - return hostFiber.stateNode; - } - } - - function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { - var hydrate = false; - var initialChildren = null; - return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); - } - function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode. - callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { - var hydrate = true; - var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor - - root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from - // a regular update because the initial render must match was was rendered - // on the server. - // NOTE: This update intentionally doesn't have a payload. We're only using - // the update to schedule work on the root fiber (and, for legacy roots, to - // enqueue the callback if one is provided). - - var current = root.current; - var eventTime = requestEventTime(); - var lane = requestUpdateLane(current); - var update = createUpdate(eventTime, lane); - update.callback = callback !== undefined && callback !== null ? callback : null; - enqueueUpdate(current, update); - scheduleInitialHydrationOnRoot(root, lane, eventTime); - return root; - } - function updateContainer(element, container, parentComponent, callback) { - { - onScheduleRoot(container, element); - } - - var current$1 = container.current; - var eventTime = requestEventTime(); - var lane = requestUpdateLane(current$1); - - { - markRenderScheduled(lane); - } - - var context = getContextForSubtree(parentComponent); - - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - - { - if (isRendering && current !== null && !didWarnAboutNestedUpdates) { - didWarnAboutNestedUpdates = true; - - error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown'); - } - } - - var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property - // being called "element". - - update.payload = { - element: element - }; - callback = callback === undefined ? null : callback; - - if (callback !== null) { - { - if (typeof callback !== 'function') { - error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback); - } - } - - update.callback = callback; - } - - enqueueUpdate(current$1, update); - var root = scheduleUpdateOnFiber(current$1, lane, eventTime); - - if (root !== null) { - entangleTransitions(root, current$1, lane); - } - - return lane; - } - function getPublicRootInstance(container) { - var containerFiber = container.current; - - if (!containerFiber.child) { - return null; - } - - switch (containerFiber.child.tag) { - case HostComponent: - return getPublicInstance(containerFiber.child.stateNode); - - default: - return containerFiber.child.stateNode; - } - } - function attemptSynchronousHydration(fiber) { - switch (fiber.tag) { - case HostRoot: - var root = fiber.stateNode; - - if (isRootDehydrated(root)) { - // Flush the first scheduled "update". - var lanes = getHighestPriorityPendingLanes(root); - flushRoot(root, lanes); - } - - break; - - case SuspenseComponent: - var eventTime = requestEventTime(); - flushSync(function () { - return scheduleUpdateOnFiber(fiber, SyncLane, eventTime); - }); // If we're still blocked after this, we need to increase - // the priority of any promises resolving within this - // boundary so that they next attempt also has higher pri. - - var retryLane = SyncLane; - markRetryLaneIfNotHydrated(fiber, retryLane); - break; - } - } - - function markRetryLaneImpl(fiber, retryLane) { - var suspenseState = fiber.memoizedState; - - if (suspenseState !== null && suspenseState.dehydrated !== null) { - suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane); - } - } // Increases the priority of thenables when they resolve within this boundary. - - - function markRetryLaneIfNotHydrated(fiber, retryLane) { - markRetryLaneImpl(fiber, retryLane); - var alternate = fiber.alternate; - - if (alternate) { - markRetryLaneImpl(alternate, retryLane); - } - } - - function attemptContinuousHydration(fiber) { - if (fiber.tag !== SuspenseComponent) { - // We ignore HostRoots here because we can't increase - // their priority and they should not suspend on I/O, - // since you have to wrap anything that might suspend in - // Suspense. - return; - } - - var eventTime = requestEventTime(); - var lane = SelectiveHydrationLane; - scheduleUpdateOnFiber(fiber, lane, eventTime); - markRetryLaneIfNotHydrated(fiber, lane); - } - function attemptHydrationAtCurrentPriority(fiber) { - if (fiber.tag !== SuspenseComponent) { - // We ignore HostRoots here because we can't increase - // their priority other than synchronously flush it. - return; - } - - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - scheduleUpdateOnFiber(fiber, lane, eventTime); - markRetryLaneIfNotHydrated(fiber, lane); - } - function findHostInstanceWithNoPortals(fiber) { - var hostFiber = findCurrentHostFiberWithNoPortals(fiber); - - if (hostFiber === null) { - return null; - } - - return hostFiber.stateNode; - } - - var shouldErrorImpl = function (fiber) { - return null; - }; - - function shouldError(fiber) { - return shouldErrorImpl(fiber); - } - - var shouldSuspendImpl = function (fiber) { - return false; - }; - - function shouldSuspend(fiber) { - return shouldSuspendImpl(fiber); - } - var overrideHookState = null; - var overrideHookStateDeletePath = null; - var overrideHookStateRenamePath = null; - var overrideProps = null; - var overridePropsDeletePath = null; - var overridePropsRenamePath = null; - var scheduleUpdate = null; - var setErrorHandler = null; - var setSuspenseHandler = null; - - { - var copyWithDeleteImpl = function (obj, path, index) { - var key = path[index]; - var updated = isArray(obj) ? obj.slice() : assign({}, obj); - - if (index + 1 === path.length) { - if (isArray(updated)) { - updated.splice(key, 1); - } else { - delete updated[key]; - } - - return updated; - } // $FlowFixMe number or string is fine here - - - updated[key] = copyWithDeleteImpl(obj[key], path, index + 1); - return updated; - }; - - var copyWithDelete = function (obj, path) { - return copyWithDeleteImpl(obj, path, 0); - }; - - var copyWithRenameImpl = function (obj, oldPath, newPath, index) { - var oldKey = oldPath[index]; - var updated = isArray(obj) ? obj.slice() : assign({}, obj); - - if (index + 1 === oldPath.length) { - var newKey = newPath[index]; // $FlowFixMe number or string is fine here - - updated[newKey] = updated[oldKey]; - - if (isArray(updated)) { - updated.splice(oldKey, 1); - } else { - delete updated[oldKey]; - } - } else { - // $FlowFixMe number or string is fine here - updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here - obj[oldKey], oldPath, newPath, index + 1); - } - - return updated; - }; - - var copyWithRename = function (obj, oldPath, newPath) { - if (oldPath.length !== newPath.length) { - warn('copyWithRename() expects paths of the same length'); - - return; - } else { - for (var i = 0; i < newPath.length - 1; i++) { - if (oldPath[i] !== newPath[i]) { - warn('copyWithRename() expects paths to be the same except for the deepest key'); - - return; - } - } - } - - return copyWithRenameImpl(obj, oldPath, newPath, 0); - }; - - var copyWithSetImpl = function (obj, path, index, value) { - if (index >= path.length) { - return value; - } - - var key = path[index]; - var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here - - updated[key] = copyWithSetImpl(obj[key], path, index + 1, value); - return updated; - }; - - var copyWithSet = function (obj, path, value) { - return copyWithSetImpl(obj, path, 0, value); - }; - - var findHook = function (fiber, id) { - // For now, the "id" of stateful hooks is just the stateful hook index. - // This may change in the future with e.g. nested hooks. - var currentHook = fiber.memoizedState; - - while (currentHook !== null && id > 0) { - currentHook = currentHook.next; - id--; - } - - return currentHook; - }; // Support DevTools editable values for useState and useReducer. - - - overrideHookState = function (fiber, id, path, value) { - var hook = findHook(fiber, id); - - if (hook !== null) { - var newState = copyWithSet(hook.memoizedState, path, value); - hook.memoizedState = newState; - hook.baseState = newState; // We aren't actually adding an update to the queue, - // because there is no update we can add for useReducer hooks that won't trigger an error. - // (There's no appropriate action type for DevTools overrides.) - // As a result though, React will see the scheduled update as a noop and bailout. - // Shallow cloning props works as a workaround for now to bypass the bailout check. - - fiber.memoizedProps = assign({}, fiber.memoizedProps); - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - }; - - overrideHookStateDeletePath = function (fiber, id, path) { - var hook = findHook(fiber, id); - - if (hook !== null) { - var newState = copyWithDelete(hook.memoizedState, path); - hook.memoizedState = newState; - hook.baseState = newState; // We aren't actually adding an update to the queue, - // because there is no update we can add for useReducer hooks that won't trigger an error. - // (There's no appropriate action type for DevTools overrides.) - // As a result though, React will see the scheduled update as a noop and bailout. - // Shallow cloning props works as a workaround for now to bypass the bailout check. - - fiber.memoizedProps = assign({}, fiber.memoizedProps); - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - }; - - overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) { - var hook = findHook(fiber, id); - - if (hook !== null) { - var newState = copyWithRename(hook.memoizedState, oldPath, newPath); - hook.memoizedState = newState; - hook.baseState = newState; // We aren't actually adding an update to the queue, - // because there is no update we can add for useReducer hooks that won't trigger an error. - // (There's no appropriate action type for DevTools overrides.) - // As a result though, React will see the scheduled update as a noop and bailout. - // Shallow cloning props works as a workaround for now to bypass the bailout check. - - fiber.memoizedProps = assign({}, fiber.memoizedProps); - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - }; // Support DevTools props for function components, forwardRef, memo, host components, etc. - - - overrideProps = function (fiber, path, value) { - fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); - - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - }; - - overridePropsDeletePath = function (fiber, path) { - fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); - - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - }; - - overridePropsRenamePath = function (fiber, oldPath, newPath) { - fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); - - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - }; - - scheduleUpdate = function (fiber) { - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - }; - - setErrorHandler = function (newShouldErrorImpl) { - shouldErrorImpl = newShouldErrorImpl; - }; - - setSuspenseHandler = function (newShouldSuspendImpl) { - shouldSuspendImpl = newShouldSuspendImpl; - }; - } - - function findHostInstanceByFiber(fiber) { - var hostFiber = findCurrentHostFiber(fiber); - - if (hostFiber === null) { - return null; - } - - return hostFiber.stateNode; - } - - function emptyFindFiberByHostInstance(instance) { - return null; - } - - function getCurrentFiberForDevTools() { - return current; - } - - function injectIntoDevTools(devToolsConfig) { - var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - return injectInternals({ - bundleType: devToolsConfig.bundleType, - version: devToolsConfig.version, - rendererPackageName: devToolsConfig.rendererPackageName, - rendererConfig: devToolsConfig.rendererConfig, - overrideHookState: overrideHookState, - overrideHookStateDeletePath: overrideHookStateDeletePath, - overrideHookStateRenamePath: overrideHookStateRenamePath, - overrideProps: overrideProps, - overridePropsDeletePath: overridePropsDeletePath, - overridePropsRenamePath: overridePropsRenamePath, - setErrorHandler: setErrorHandler, - setSuspenseHandler: setSuspenseHandler, - scheduleUpdate: scheduleUpdate, - currentDispatcherRef: ReactCurrentDispatcher, - findHostInstanceByFiber: findHostInstanceByFiber, - findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, - // React Refresh - findHostInstancesForRefresh: findHostInstancesForRefresh , - scheduleRefresh: scheduleRefresh , - scheduleRoot: scheduleRoot , - setRefreshHandler: setRefreshHandler , - // Enables DevTools to append owner stacks to error messages in DEV mode. - getCurrentFiber: getCurrentFiberForDevTools , - // Enables DevTools to detect reconciler version rather than renderer version - // which may not match for third party renderers. - reconcilerVersion: ReactVersion - }); - } - - exports.attemptContinuousHydration = attemptContinuousHydration; - exports.attemptHydrationAtCurrentPriority = attemptHydrationAtCurrentPriority; - exports.attemptSynchronousHydration = attemptSynchronousHydration; - exports.batchedUpdates = batchedUpdates; - exports.createComponentSelector = createComponentSelector; - exports.createContainer = createContainer; - exports.createHasPseudoClassSelector = createHasPseudoClassSelector; - exports.createHydrationContainer = createHydrationContainer; - exports.createPortal = createPortal; - exports.createRoleSelector = createRoleSelector; - exports.createTestNameSelector = createTestNameSelector; - exports.createTextSelector = createTextSelector; - exports.deferredUpdates = deferredUpdates; - exports.discreteUpdates = discreteUpdates; - exports.findAllNodes = findAllNodes; - exports.findBoundingRects = findBoundingRects; - exports.findHostInstance = findHostInstance; - exports.findHostInstanceWithNoPortals = findHostInstanceWithNoPortals; - exports.findHostInstanceWithWarning = findHostInstanceWithWarning; - exports.flushControlled = flushControlled; - exports.flushPassiveEffects = flushPassiveEffects; - exports.flushSync = flushSync; - exports.focusWithin = focusWithin; - exports.getCurrentUpdatePriority = getCurrentUpdatePriority; - exports.getFindAllNodesFailureDescription = getFindAllNodesFailureDescription; - exports.getPublicRootInstance = getPublicRootInstance; - exports.injectIntoDevTools = injectIntoDevTools; - exports.isAlreadyRendering = isAlreadyRendering; - exports.observeVisibleRects = observeVisibleRects; - exports.registerMutableSourceForHydration = registerMutableSourceForHydration; - exports.runWithPriority = runWithPriority; - exports.shouldError = shouldError; - exports.shouldSuspend = shouldSuspend; - exports.updateContainer = updateContainer; - return exports; - }; - } - return reactReconciler_development.exports; -} - -(function (module) { - - if (process.env.NODE_ENV === 'production') { - module.exports = requireReactReconciler_production_min(); - } else { - module.exports = requireReactReconciler_development(); - } -} (reactReconciler)); - -var Reconciler = /*@__PURE__*/getDefaultExportFromCjs(reactReconciler.exports); - -function shallowEqualArrays(arrA, arrB, equal = (a, b) => a === b) { - if (arrA === arrB) return true; - if (!arrA || !arrB) return false; - const len = arrA.length; - if (arrB.length !== len) return false; - - for (let i = 0; i < len; i++) if (!equal(arrA[i], arrB[i])) return false; - - return true; -} - -const globalCache = []; - -function query(fn, keys, preload = false, config = {}) { - for (const entry of globalCache) { - // Find a match - if (shallowEqualArrays(keys, entry.keys, entry.equal)) { - // If we're pre-loading and the element is present, just return - if (preload) return undefined; // If an error occurred, throw - - if (Object.prototype.hasOwnProperty.call(entry, 'error')) throw entry.error; // If a response was successful, return - - if (Object.prototype.hasOwnProperty.call(entry, 'response')) return entry.response; // If the promise is still unresolved, throw - - if (!preload) throw entry.promise; - } - } // The request is new or has changed. - - - const entry = { - keys, - equal: config.equal, - promise: // Execute the promise - fn(...keys) // When it resolves, store its value - .then(response => entry.response = response) // Remove the entry if a lifespan was given - .then(() => { - if (config.lifespan && config.lifespan > 0) { - setTimeout(() => { - const index = globalCache.indexOf(entry); - if (index !== -1) globalCache.splice(index, 1); - }, config.lifespan); - } - }) // Store caught errors, they will be thrown in the render-phase to bubble into an error-bound - .catch(error => entry.error = error) - }; // Register the entry - - globalCache.push(entry); // And throw the promise, this yields control back to React - - if (!preload) throw entry.promise; - return undefined; -} - -const suspend = (fn, keys, config) => query(fn, keys, false, config); - -const isOrthographicCamera = def => def && def.isOrthographicCamera; // React currently throws a warning when using useLayoutEffect on the server. -// To get around it, we can conditionally useEffect on the server (no-op) and -// useLayoutEffect on the client. - -const isSSR$2 = typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); -const useIsomorphicLayoutEffect$1 = isSSR$2 ? React.useEffect : React.useLayoutEffect; -function useMutableCallback(fn) { - const ref = React.useRef(fn); - useIsomorphicLayoutEffect$1(() => void (ref.current = fn), [fn]); - return ref; -} -function Block({ - set -}) { - useIsomorphicLayoutEffect$1(() => { - set(new Promise(() => null)); - return () => set(false); - }, [set]); - return null; -} -class ErrorBoundary extends React.Component { - constructor(...args) { - super(...args); - this.state = { - error: false - }; - } - - componentDidCatch(error) { - this.props.set(error); - } - - render() { - return this.state.error ? null : this.props.children; - } - -} - -ErrorBoundary.getDerivedStateFromError = () => ({ - error: true -}); - -const DEFAULT = '__default'; -const isDiffSet = def => def && !!def.memoized && !!def.changes; -function calculateDpr(dpr) { - return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], window.devicePixelRatio), dpr[1]) : dpr; -} -/** - * Returns instance root state - */ - -const getRootState = obj => { - var _r3f; - - return (_r3f = obj.__r3f) == null ? void 0 : _r3f.root.getState(); -}; -// A collection of compare functions -const is$1 = { - obj: a => a === Object(a) && !is$1.arr(a) && typeof a !== 'function', - fun: a => typeof a === 'function', - str: a => typeof a === 'string', - num: a => typeof a === 'number', - boo: a => typeof a === 'boolean', - und: a => a === void 0, - arr: a => Array.isArray(a), - - equ(a, b, { - arrays = 'shallow', - objects = 'reference', - strict = true - } = {}) { - // Wrong type or one of the two undefined, doesn't match - if (typeof a !== typeof b || !!a !== !!b) return false; // Atomic, just compare a against b - - if (is$1.str(a) || is$1.num(a)) return a === b; - const isObj = is$1.obj(a); - if (isObj && objects === 'reference') return a === b; - const isArr = is$1.arr(a); - if (isArr && arrays === 'reference') return a === b; // Array or Object, shallow compare first to see if it's a match - - if ((isArr || isObj) && a === b) return true; // Last resort, go through keys - - let i; - - for (i in a) if (!(i in b)) return false; - - for (i in strict ? b : a) if (a[i] !== b[i]) return false; - - if (is$1.und(i)) { - if (isArr && a.length === 0 && b.length === 0) return true; - if (isObj && Object.keys(a).length === 0 && Object.keys(b).length === 0) return true; - if (a !== b) return false; - } - - return true; - } - -}; // Collects nodes and materials from a THREE.Object3D - -function dispose(obj) { - if (obj.dispose && obj.type !== 'Scene') obj.dispose(); - - for (const p in obj) { - p.dispose == null ? void 0 : p.dispose(); - delete obj[p]; - } -} // Each object in the scene carries a small LocalState descriptor - -function prepare(object, state) { - const instance = object; - - if (state != null && state.primitive || !instance.__r3f) { - instance.__r3f = { - type: '', - root: null, - previousAttach: null, - memoizedProps: {}, - eventCount: 0, - handlers: {}, - objects: [], - parent: null, - ...state - }; - } - - return object; -} - -function resolve(instance, key) { - let target = instance; - - if (key.includes('-')) { - const entries = key.split('-'); - const last = entries.pop(); - target = entries.reduce((acc, key) => acc[key], instance); - return { - target, - key: last - }; - } else return { - target, - key - }; -} // Checks if a dash-cased string ends with an integer - - -const INDEX_REGEX = /-\d+$/; -function attach(parent, child, type) { - if (is$1.str(type)) { - // If attaching into an array (foo-0), create one - if (INDEX_REGEX.test(type)) { - const root = type.replace(INDEX_REGEX, ''); - const { - target, - key - } = resolve(parent, root); - if (!Array.isArray(target[key])) target[key] = []; - } - - const { - target, - key - } = resolve(parent, type); - child.__r3f.previousAttach = target[key]; - target[key] = child; - } else child.__r3f.previousAttach = type(parent, child); -} -function detach(parent, child, type) { - var _child$__r3f, _child$__r3f2; - - if (is$1.str(type)) { - const { - target, - key - } = resolve(parent, type); - const previous = child.__r3f.previousAttach; // When the previous value was undefined, it means the value was never set to begin with - - if (previous === undefined) delete target[key]; // Otherwise set the previous value - else target[key] = previous; - } else (_child$__r3f = child.__r3f) == null ? void 0 : _child$__r3f.previousAttach == null ? void 0 : _child$__r3f.previousAttach(parent, child); - - (_child$__r3f2 = child.__r3f) == null ? true : delete _child$__r3f2.previousAttach; -} // This function prepares a set of changes to be applied to the instance - -function diffProps(instance, { - children: cN, - key: kN, - ref: rN, - ...props -}, { - children: cP, - key: kP, - ref: rP, - ...previous -} = {}, remove = false) { - var _instance$__r3f; - - const localState = (_instance$__r3f = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f : {}; - const entries = Object.entries(props); - const changes = []; // Catch removed props, prepend them so they can be reset or removed - - if (remove) { - const previousKeys = Object.keys(previous); - - for (let i = 0; i < previousKeys.length; i++) { - if (!props.hasOwnProperty(previousKeys[i])) entries.unshift([previousKeys[i], DEFAULT + 'remove']); - } - } - - entries.forEach(([key, value]) => { - var _instance$__r3f2; - - // Bail out on primitive object - if ((_instance$__r3f2 = instance.__r3f) != null && _instance$__r3f2.primitive && key === 'object') return; // When props match bail out - - if (is$1.equ(value, previous[key])) return; // Collect handlers and bail out - - if (/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key)) return changes.push([key, value, true, []]); // Split dashed props - - let entries = []; - if (key.includes('-')) entries = key.split('-'); - changes.push([key, value, false, entries]); - }); - const memoized = { ...props - }; - if (localState.memoizedProps && localState.memoizedProps.args) memoized.args = localState.memoizedProps.args; - if (localState.memoizedProps && localState.memoizedProps.attach) memoized.attach = localState.memoizedProps.attach; - return { - memoized, - changes - }; -} // This function applies a set of changes to the instance - -function applyProps$1(instance, data) { - var _instance$__r3f3, _root$getState; - - // Filter equals, events and reserved props - const localState = (_instance$__r3f3 = instance.__r3f) != null ? _instance$__r3f3 : {}; - const root = localState.root; - const rootState = (_root$getState = root == null ? void 0 : root.getState == null ? void 0 : root.getState()) != null ? _root$getState : {}; - const { - memoized, - changes - } = isDiffSet(data) ? data : diffProps(instance, data); - const prevHandlers = localState.eventCount; // Prepare memoized props - - if (instance.__r3f) instance.__r3f.memoizedProps = memoized; - changes.forEach(([key, value, isEvent, keys]) => { - let currentInstance = instance; - let targetProp = currentInstance[key]; // Revolve dashed props - - if (keys.length) { - targetProp = keys.reduce((acc, key) => acc[key], instance); // If the target is atomic, it forces us to switch the root - - if (!(targetProp && targetProp.set)) { - const [name, ...reverseEntries] = keys.reverse(); - currentInstance = reverseEntries.reverse().reduce((acc, key) => acc[key], instance); - key = name; - } - } // https://github.com/mrdoob/three.js/issues/21209 - // HMR/fast-refresh relies on the ability to cancel out props, but threejs - // has no means to do this. Hence we curate a small collection of value-classes - // with their respective constructor/set arguments - // For removed props, try to set default values, if possible - - - if (value === DEFAULT + 'remove') { - if (targetProp && targetProp.constructor) { - var _memoized$args; - - // use the prop constructor to find the default it should be - value = new targetProp.constructor(...((_memoized$args = memoized.args) != null ? _memoized$args : [])); - } else if (currentInstance.constructor) { - var _currentInstance$__r; - - // create a blank slate of the instance and copy the particular parameter. - // @ts-ignore - const defaultClassCall = new currentInstance.constructor(...((_currentInstance$__r = currentInstance.__r3f.memoizedProps.args) != null ? _currentInstance$__r : [])); - value = defaultClassCall[targetProp]; // destory the instance - - if (defaultClassCall.dispose) defaultClassCall.dispose(); // instance does not have constructor, just set it to 0 - } else { - value = 0; - } - } // Deal with pointer events ... - - - if (isEvent) { - if (value) localState.handlers[key] = value;else delete localState.handlers[key]; - localState.eventCount = Object.keys(localState.handlers).length; - } // Special treatment for objects with support for set/copy, and layers - else if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof Layers)) { - // If value is an array - if (Array.isArray(value)) { - if (targetProp.fromArray) targetProp.fromArray(value);else targetProp.set(...value); - } // Test again target.copy(class) next ... - else if (targetProp.copy && value && value.constructor && targetProp.constructor.name === value.constructor.name) { - targetProp.copy(value); - } // If nothing else fits, just set the single value, ignore undefined - // https://github.com/pmndrs/react-three-fiber/issues/274 - else if (value !== undefined) { - const isColor = targetProp instanceof Color; // Allow setting array scalars - - if (!isColor && targetProp.setScalar) targetProp.setScalar(value); // Layers have no copy function, we must therefore copy the mask property - else if (targetProp instanceof Layers && value instanceof Layers) targetProp.mask = value.mask; // Otherwise just set ... - else targetProp.set(value); // For versions of three which don't support THREE.ColorManagement, - // Auto-convert sRGB colors - // https://github.com/pmndrs/react-three-fiber/issues/344 - - const supportsColorManagement = ('ColorManagement' in THREE); - if (!supportsColorManagement && !rootState.linear && isColor) targetProp.convertSRGBToLinear(); - } // Else, just overwrite the value - - } else { - currentInstance[key] = value; // Auto-convert sRGB textures, for now ... - // https://github.com/pmndrs/react-three-fiber/issues/344 - - if (!rootState.linear && currentInstance[key] instanceof Texture) { - currentInstance[key].encoding = sRGBEncoding; - } - } - - invalidateInstance(instance); - }); - - if (localState.parent && rootState.internal && instance.raycast && prevHandlers !== localState.eventCount) { - // Pre-emptively remove the instance from the interaction manager - const index = rootState.internal.interaction.indexOf(instance); - if (index > -1) rootState.internal.interaction.splice(index, 1); // Add the instance to the interaction manager only when it has handlers - - if (localState.eventCount) rootState.internal.interaction.push(instance); - } // Call the update lifecycle when it is being updated, but only when it is part of the scene - - - if (changes.length && instance.parent) updateInstance(instance); - return instance; -} -function invalidateInstance(instance) { - var _instance$__r3f4, _instance$__r3f4$root; - - const state = (_instance$__r3f4 = instance.__r3f) == null ? void 0 : (_instance$__r3f4$root = _instance$__r3f4.root) == null ? void 0 : _instance$__r3f4$root.getState == null ? void 0 : _instance$__r3f4$root.getState(); - if (state && state.internal.frames === 0) state.invalidate(); -} -function updateInstance(instance) { - instance.onUpdate == null ? void 0 : instance.onUpdate(instance); -} -function updateCamera(camera, size) { - // https://github.com/pmndrs/react-three-fiber/issues/92 - // Do not mess with the camera if it belongs to the user - if (!camera.manual) { - if (isOrthographicCamera(camera)) { - camera.left = size.width / -2; - camera.right = size.width / 2; - camera.top = size.height / 2; - camera.bottom = size.height / -2; - } else { - camera.aspect = size.width / size.height; - } - - camera.updateProjectionMatrix(); // https://github.com/pmndrs/react-three-fiber/issues/178 - // Update matrix world since the renderer is a frame late - - camera.updateMatrixWorld(); - } -} -/** - * Safely sets a deeply-nested value on an object. - */ - -function setDeep(obj, value, keys) { - const key = keys.pop(); - const target = keys.reduce((acc, key) => acc[key], obj); - return target[key] = value; -} - -function makeId(event) { - return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId; -} // https://github.com/facebook/react/tree/main/packages/react-reconciler#getcurrenteventpriority -// Gives React a clue as to how import the current interaction is - - -function getEventPriority() { - var _window, _window$event; - - let name = (_window = window) == null ? void 0 : (_window$event = _window.event) == null ? void 0 : _window$event.type; - - switch (name) { - case 'click': - case 'contextmenu': - case 'dblclick': - case 'pointercancel': - case 'pointerdown': - case 'pointerup': - return constants$1.exports.DiscreteEventPriority; - - case 'pointermove': - case 'pointerout': - case 'pointerover': - case 'pointerenter': - case 'pointerleave': - case 'wheel': - return constants$1.exports.ContinuousEventPriority; - - default: - return constants$1.exports.DefaultEventPriority; - } -} -/** - * Release pointer captures. - * This is called by releasePointerCapture in the API, and when an object is removed. - */ - -function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) { - const captureData = captures.get(obj); - - if (captureData) { - captures.delete(obj); // If this was the last capturing object for this pointer - - if (captures.size === 0) { - capturedMap.delete(pointerId); - captureData.target.releasePointerCapture(pointerId); - } - } -} - -function removeInteractivity(store, object) { - const { - internal - } = store.getState(); // Removes every trace of an object from the data store - - internal.interaction = internal.interaction.filter(o => o !== object); - internal.initialHits = internal.initialHits.filter(o => o !== object); - internal.hovered.forEach((value, key) => { - if (value.eventObject === object || value.object === object) { - // Clear out intersects, they are outdated by now - internal.hovered.delete(key); - } - }); - internal.capturedMap.forEach((captures, pointerId) => { - releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId); - }); -} -function createEvents(store) { - const temp = new Vector3(); - /** Calculates delta */ - - function calculateDistance(event) { - const { - internal - } = store.getState(); - const dx = event.offsetX - internal.initialClick[0]; - const dy = event.offsetY - internal.initialClick[1]; - return Math.round(Math.sqrt(dx * dx + dy * dy)); - } - /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */ - - - function filterPointerEvents(objects) { - return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => { - var _r3f; - - return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers['onPointer' + name]; - })); - } - - function intersect(event, filter) { - const state = store.getState(); - const duplicates = new Set(); - const intersections = []; // Allow callers to eliminate event objects - - const eventsObjects = filter ? filter(state.internal.interaction) : state.internal.interaction; // Reset all raycaster cameras to undefined - - eventsObjects.forEach(obj => { - const state = getRootState(obj); - - if (state) { - state.raycaster.camera = undefined; - } - }); - - if (!state.previousRoot) { - // Make sure root-level pointer and ray are set up - state.events.compute == null ? void 0 : state.events.compute(event, state); - } // Collect events - - - let hits = eventsObjects // Intersect objects - .flatMap(obj => { - const state = getRootState(obj); // Skip event handling when noEvents is set, or when the raycasters camera is null - - if (!state || !state.events.enabled || state.raycaster.camera === null) return []; // When the camera is undefined we have to call the event layers update function - - if (state.raycaster.camera === undefined) { - var _state$previousRoot; - - state.events.compute == null ? void 0 : state.events.compute(event, state, (_state$previousRoot = state.previousRoot) == null ? void 0 : _state$previousRoot.getState()); // If the camera is still undefined we have to skip this layer entirely - - if (state.raycaster.camera === undefined) state.raycaster.camera = null; - } // Intersect object by object - - - return state.raycaster.camera ? state.raycaster.intersectObject(obj, true) : []; - }) // Sort by event priority and distance - .sort((a, b) => { - const aState = getRootState(a.object); - const bState = getRootState(b.object); - if (!aState || !bState) return 0; - return bState.events.priority - aState.events.priority || a.distance - b.distance; - }) // Filter out duplicates - .filter(item => { - const id = makeId(item); - if (duplicates.has(id)) return false; - duplicates.add(id); - return true; - }); // https://github.com/mrdoob/three.js/issues/16031 - // Allow custom userland intersect sort order, this likely only makes sense on the root filter - - if (state.events.filter) hits = state.events.filter(hits, state); // Bubble up the events, find the event source (eventObject) - - for (const hit of hits) { - let eventObject = hit.object; // Bubble event up - - while (eventObject) { - var _r3f2; - - if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({ ...hit, - eventObject - }); - eventObject = eventObject.parent; - } - } // If the interaction is captured, make all capturing targets part of the intersect. - - - if ('pointerId' in event && state.internal.capturedMap.has(event.pointerId)) { - for (let captureData of state.internal.capturedMap.get(event.pointerId).values()) { - intersections.push(captureData.intersection); - } - } - - return intersections; - } - /** Handles intersections by forwarding them to handlers */ - - - function handleIntersects(intersections, event, delta, callback) { - const { - raycaster, - pointer, - camera, - internal - } = store.getState(); // If anything has been found, forward it to the event listeners - - if (intersections.length) { - const unprojectedPoint = temp.set(pointer.x, pointer.y, 0).unproject(camera); - const localState = { - stopped: false - }; - - for (const hit of intersections) { - const hasPointerCapture = id => { - var _internal$capturedMap, _internal$capturedMap2; - - return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false; - }; - - const setPointerCapture = id => { - const captureData = { - intersection: hit, - target: event.target - }; - - if (internal.capturedMap.has(id)) { - // if the pointerId was previously captured, we add the hit to the - // event capturedMap. - internal.capturedMap.get(id).set(hit.eventObject, captureData); - } else { - // if the pointerId was not previously captured, we create a map - // containing the hitObject, and the hit. hitObject is used for - // faster access. - internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]])); - } // Call the original event now - event.target.setPointerCapture(id); - }; - - const releasePointerCapture = id => { - const captures = internal.capturedMap.get(id); - - if (captures) { - releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id); - } - }; // Add native event props - - - let extractEventProps = {}; // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones. - - for (let prop in event) { - let property = event[prop]; // Only copy over atomics, leave functions alone as these should be - // called as event.nativeEvent.fn() - - if (typeof property !== 'function') extractEventProps[prop] = property; - } - - let raycastEvent = { ...hit, - ...extractEventProps, - pointer, - intersections, - stopped: localState.stopped, - delta, - unprojectedPoint, - ray: raycaster.ray, - camera: camera, - // Hijack stopPropagation, which just sets a flag - stopPropagation: () => { - // https://github.com/pmndrs/react-three-fiber/issues/596 - // Events are not allowed to stop propagation if the pointer has been captured - const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId); // We only authorize stopPropagation... - - if ( // ...if this pointer hasn't been captured - !capturesForPointer || // ... or if the hit object is capturing the pointer - capturesForPointer.has(hit.eventObject)) { - raycastEvent.stopped = localState.stopped = true; // Propagation is stopped, remove all other hover records - // An event handler is only allowed to flush other handlers if it is hovered itself - - if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) { - // Objects cannot flush out higher up objects that have already caught the event - const higher = intersections.slice(0, intersections.indexOf(hit)); - cancelPointer([...higher, hit]); - } - } - }, - // there should be a distinction between target and currentTarget - target: { - hasPointerCapture, - setPointerCapture, - releasePointerCapture - }, - currentTarget: { - hasPointerCapture, - setPointerCapture, - releasePointerCapture - }, - nativeEvent: event - }; // Call subscribers - - callback(raycastEvent); // Event bubbling may be interrupted by stopPropagation - - if (localState.stopped === true) break; - } - } - - return intersections; - } - - function cancelPointer(intersections) { - const { - internal - } = store.getState(); - Array.from(internal.hovered.values()).forEach(hoveredObj => { - // When no objects were hit or the the hovered object wasn't found underneath the cursor - // we call onPointerOut and delete the object from the hovered-elements map - if (!intersections.length || !intersections.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) { - const eventObject = hoveredObj.eventObject; - const instance = eventObject.__r3f; - const handlers = instance == null ? void 0 : instance.handlers; - internal.hovered.delete(makeId(hoveredObj)); - - if (instance != null && instance.eventCount) { - // Clear out intersects, they are outdated by now - const data = { ...hoveredObj, - intersections - }; - handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data); - handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data); - } - } - }); - } - - const handlePointer = name => { - // Deal with cancelation - switch (name) { - case 'onPointerLeave': - case 'onPointerCancel': - return () => cancelPointer([]); - - case 'onLostPointerCapture': - return event => { - const { - internal - } = store.getState(); - - if ('pointerId' in event && !internal.capturedMap.has(event.pointerId)) { - // If the object event interface had onLostPointerCapture, we'd call it here on every - // object that's getting removed. - internal.capturedMap.delete(event.pointerId); - cancelPointer([]); - } - }; - } // Any other pointer goes here ... - - - return event => { - const { - onPointerMissed, - internal - } = store.getState(); //prepareRay(event) - - internal.lastEvent.current = event; // Get fresh intersects - - const isPointerMove = name === 'onPointerMove'; - const isClickEvent = name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick'; - const filter = isPointerMove ? filterPointerEvents : undefined; //const hits = patchIntersects(intersect(filter), event) - - const hits = intersect(event, filter); - const delta = isClickEvent ? calculateDistance(event) : 0; // Save initial coordinates on pointer-down - - if (name === 'onPointerDown') { - internal.initialClick = [event.offsetX, event.offsetY]; - internal.initialHits = hits.map(hit => hit.eventObject); - } // If a click yields no results, pass it back to the user as a miss - // Missed events have to come first in order to establish user-land side-effect clean up - - - if (isClickEvent && !hits.length) { - if (delta <= 2) { - pointerMissed(event, internal.interaction); - if (onPointerMissed) onPointerMissed(event); - } - } // Take care of unhover - - - if (isPointerMove) cancelPointer(hits); - handleIntersects(hits, event, delta, data => { - const eventObject = data.eventObject; - const instance = eventObject.__r3f; - const handlers = instance == null ? void 0 : instance.handlers; // Check presence of handlers - - if (!(instance != null && instance.eventCount)) return; - - if (isPointerMove) { - // Move event ... - if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) { - // When enter or out is present take care of hover-state - const id = makeId(data); - const hoveredItem = internal.hovered.get(id); - - if (!hoveredItem) { - // If the object wasn't previously hovered, book it and call its handler - internal.hovered.set(id, data); - handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data); - handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data); - } else if (hoveredItem.stopped) { - // If the object was previously hovered and stopped, we shouldn't allow other items to proceed - data.stopPropagation(); - } - } // Call mouse move - - - handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data); - } else { - // All other events ... - const handler = handlers[name]; - - if (handler) { - // Forward all events back to their respective handlers with the exception of click events, - // which must use the initial target - if (!isClickEvent || internal.initialHits.includes(eventObject)) { - // Missed events have to come first - pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); // Now call the handler - - handler(data); - } - } else { - // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit - if (isClickEvent && internal.initialHits.includes(eventObject)) { - pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); - } - } - } - }); - }; - }; - - function pointerMissed(event, objects) { - objects.forEach(object => { - var _r3f3; - - return (_r3f3 = object.__r3f) == null ? void 0 : _r3f3.handlers.onPointerMissed == null ? void 0 : _r3f3.handlers.onPointerMissed(event); - }); - } - - return { - handlePointer - }; -} - -let catalogue = {}; - -let extend = objects => void (catalogue = { ...catalogue, - ...objects -}); - -function createRenderer(roots, getEventPriority) { - function createInstance(type, { - args = [], - attach, - ...props - }, root) { - let name = `${type[0].toUpperCase()}${type.slice(1)}`; - let instance; // Auto-attach geometries and materials - - if (attach === undefined) { - if (name.endsWith('Geometry')) attach = 'geometry';else if (name.endsWith('Material')) attach = 'material'; - } - - if (type === 'primitive') { - if (props.object === undefined) throw `Primitives without 'object' are invalid!`; - const object = props.object; - instance = prepare(object, { - type, - root, - attach, - primitive: true - }); - } else { - const target = catalogue[name]; - - if (!target) { - throw `${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`; - } // Throw if an object or literal was passed for args - - - if (!Array.isArray(args)) throw 'The args prop must be an array!'; // Instanciate new object, link it to the root - // Append memoized props with args so it's not forgotten - - instance = prepare(new target(...args), { - type, - root, - attach, - // Save args in case we need to reconstruct later for HMR - memoizedProps: { - args - } - }); - } // It should NOT call onUpdate on object instanciation, because it hasn't been added to the - // view yet. If the callback relies on references for instance, they won't be ready yet, this is - // why it passes "true" here - // There is no reason to apply props to injects - - - if (name !== 'inject') applyProps$1(instance, props); - return instance; - } - - function appendChild(parentInstance, child) { - let added = false; - - if (child) { - var _child$__r3f, _parentInstance$__r3f; - - // The attach attribute implies that the object attaches itself on the parent - if ((_child$__r3f = child.__r3f) != null && _child$__r3f.attach) { - attach(parentInstance, child, child.__r3f.attach); - } else if (child.isObject3D && parentInstance.isObject3D) { - // add in the usual parent-child way - parentInstance.add(child); - added = true; - } // This is for anything that used attach, and for non-Object3Ds that don't get attached to props; - // that is, anything that's a child in React but not a child in the scenegraph. - - - if (!added) (_parentInstance$__r3f = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f.objects.push(child); - if (!child.__r3f) prepare(child, {}); - child.__r3f.parent = parentInstance; - updateInstance(child); - invalidateInstance(child); - } - } - - function insertBefore(parentInstance, child, beforeChild) { - let added = false; - - if (child) { - var _child$__r3f2, _parentInstance$__r3f2; - - if ((_child$__r3f2 = child.__r3f) != null && _child$__r3f2.attach) { - attach(parentInstance, child, child.__r3f.attach); - } else if (child.isObject3D && parentInstance.isObject3D) { - child.parent = parentInstance; - child.dispatchEvent({ - type: 'added' - }); - const restSiblings = parentInstance.children.filter(sibling => sibling !== child); - const index = restSiblings.indexOf(beforeChild); - parentInstance.children = [...restSiblings.slice(0, index), child, ...restSiblings.slice(index)]; - added = true; - } - - if (!added) (_parentInstance$__r3f2 = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f2.objects.push(child); - if (!child.__r3f) prepare(child, {}); - child.__r3f.parent = parentInstance; - updateInstance(child); - invalidateInstance(child); - } - } - - function removeRecursive(array, parent, dispose = false) { - if (array) [...array].forEach(child => removeChild(parent, child, dispose)); - } - - function removeChild(parentInstance, child, dispose) { - if (child) { - var _parentInstance$__r3f3, _child$__r3f3, _child$__r3f5; - - // Clear the parent reference - if (child.__r3f) child.__r3f.parent = null; // Remove child from the parents objects - - if ((_parentInstance$__r3f3 = parentInstance.__r3f) != null && _parentInstance$__r3f3.objects) parentInstance.__r3f.objects = parentInstance.__r3f.objects.filter(x => x !== child); // Remove attachment - - if ((_child$__r3f3 = child.__r3f) != null && _child$__r3f3.attach) { - detach(parentInstance, child, child.__r3f.attach); - } else if (child.isObject3D && parentInstance.isObject3D) { - var _child$__r3f4; - - parentInstance.remove(child); // Remove interactivity - - if ((_child$__r3f4 = child.__r3f) != null && _child$__r3f4.root) { - removeInteractivity(child.__r3f.root, child); - } - } // Allow objects to bail out of recursive dispose altogether by passing dispose={null} - // Never dispose of primitives because their state may be kept outside of React! - // In order for an object to be able to dispose it has to have - // - a dispose method, - // - it cannot be a - // - it cannot be a THREE.Scene, because three has broken it's own api - // - // Since disposal is recursive, we can check the optional dispose arg, which will be undefined - // when the reconciler calls it, but then carry our own check recursively - - - const isPrimitive = (_child$__r3f5 = child.__r3f) == null ? void 0 : _child$__r3f5.primitive; - const shouldDispose = dispose === undefined ? child.dispose !== null && !isPrimitive : dispose; // Remove nested child objects. Primitives should not have objects and children that are - // attached to them declaratively ... - - if (!isPrimitive) { - var _child$__r3f6; - - removeRecursive((_child$__r3f6 = child.__r3f) == null ? void 0 : _child$__r3f6.objects, child, shouldDispose); - removeRecursive(child.children, child, shouldDispose); - } // Remove references - - - if (child.__r3f) { - delete child.__r3f.root; - delete child.__r3f.objects; - delete child.__r3f.handlers; - delete child.__r3f.memoizedProps; - if (!isPrimitive) delete child.__r3f; - } // Dispose item whenever the reconciler feels like it - - - if (shouldDispose && child.dispose && child.type !== 'Scene') { - scheduler$1.exports.unstable_scheduleCallback(scheduler$1.exports.unstable_IdlePriority, () => { - try { - child.dispose(); - } catch (e) { - /* ... */ - } - }); - } - - invalidateInstance(parentInstance); - } - } - - function switchInstance(instance, type, newProps, fiber) { - var _instance$__r3f; - - const parent = (_instance$__r3f = instance.__r3f) == null ? void 0 : _instance$__r3f.parent; - if (!parent) return; - const newInstance = createInstance(type, newProps, instance.__r3f.root); // https://github.com/pmndrs/react-three-fiber/issues/1348 - // When args change the instance has to be re-constructed, which then - // forces r3f to re-parent the children and non-scene objects - // This can not include primitives, which should not have declarative children - - if (type !== 'primitive' && instance.children) { - instance.children.forEach(child => appendChild(newInstance, child)); - instance.children = []; - } - - instance.__r3f.objects.forEach(child => appendChild(newInstance, child)); - - instance.__r3f.objects = []; - removeChild(parent, instance); - appendChild(parent, newInstance); // Re-bind event handlers - - if (newInstance.raycast && newInstance.__r3f.eventCount) { - const rootState = newInstance.__r3f.root.getState(); - - rootState.internal.interaction.push(newInstance); - } // This evil hack switches the react-internal fiber node - [fiber, fiber.alternate].forEach(fiber => { - if (fiber !== null) { - fiber.stateNode = newInstance; - - if (fiber.ref) { - if (typeof fiber.ref === 'function') fiber.ref(newInstance);else fiber.ref.current = newInstance; - } - } - }); - } - - const reconciler = Reconciler({ - createInstance, - removeChild, - appendChild, - appendInitialChild: appendChild, - insertBefore, - supportsMicrotask: true, - warnsIfNotActing: true, - supportsMutation: true, - isPrimaryRenderer: false, - noTimeout: -1, - appendChildToContainer: (container, child) => { - const scene = container.getState().scene; // Link current root to the default scene - - scene.__r3f.root = container; - appendChild(scene, child); - }, - removeChildFromContainer: (container, child) => removeChild(container.getState().scene, child), - insertInContainerBefore: (container, child, beforeChild) => insertBefore(container.getState().scene, child, beforeChild), - getRootHostContext: () => null, - getChildHostContext: parentHostContext => parentHostContext, - - finalizeInitialChildren(instance) { - var _instance$__r3f2; - - const localState = (_instance$__r3f2 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f2 : {}; // https://github.com/facebook/react/issues/20271 - // Returning true will trigger commitMount - - return !!localState.handlers; - }, - - prepareUpdate(instance, type, oldProps, newProps) { - // Create diff-sets - if (instance.__r3f.primitive && newProps.object && newProps.object !== instance) { - return [true]; - } else { - // This is a data object, let's extract critical information about it - const { - args: argsNew = [], - children: cN, - ...restNew - } = newProps; - const { - args: argsOld = [], - children: cO, - ...restOld - } = oldProps; // Throw if an object or literal was passed for args - - if (!Array.isArray(argsNew)) throw 'The args prop must be an array!'; // If it has new props or arguments, then it needs to be re-instanciated - - if (argsNew.some((value, index) => value !== argsOld[index])) return [true]; // Create a diff-set, flag if there are any changes - - const diff = diffProps(instance, restNew, restOld, true); - if (diff.changes.length) return [false, diff]; // Otherwise do not touch the instance - - return null; - } - }, - - commitUpdate(instance, [reconstruct, diff], type, oldProps, newProps, fiber) { - // Reconstruct when args or instance, - shouldDeprioritizeSubtree: () => false, - prepareForCommit: () => null, - preparePortalMount: container => prepare(container.getState().scene), - resetAfterCommit: () => {}, - shouldSetTextContent: () => false, - clearContainer: () => false, - detachDeletedInstance: () => {}, - - hideInstance(instance) { - var _instance$__r3f4; - - // Deatch while the instance is hidden - const { - attach: type, - parent - } = (_instance$__r3f4 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f4 : {}; - if (type && parent) detach(parent, instance, type); - if (instance.isObject3D) instance.visible = false; - invalidateInstance(instance); - }, - - unhideInstance(instance, props) { - var _instance$__r3f5; - - // Re-attach when the instance is unhidden - const { - attach: type, - parent - } = (_instance$__r3f5 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f5 : {}; - if (type && parent) attach(parent, instance, type); - if (instance.isObject3D && props.visible == null || props.visible) instance.visible = true; - invalidateInstance(instance); - }, - - createTextInstance: () => {}, - hideTextInstance: () => { - throw new Error('Text is not allowed in the R3F tree.'); - }, - unhideTextInstance: () => {}, - getCurrentEventPriority: () => getEventPriority ? getEventPriority() : constants$1.exports.DefaultEventPriority, - // @ts-ignore - now: typeof performance !== 'undefined' && is$1.fun(performance.now) ? performance.now : is$1.fun(Date.now) ? Date.now : undefined, - // @ts-ignore - scheduleTimeout: is$1.fun(setTimeout) ? setTimeout : undefined, - // @ts-ignore - cancelTimeout: is$1.fun(clearTimeout) ? clearTimeout : undefined, - setTimeout: is$1.fun(setTimeout) ? setTimeout : undefined, - clearTimeout: is$1.fun(clearTimeout) ? clearTimeout : undefined - }); - return { - reconciler, - applyProps: applyProps$1 - }; -} -const isRenderer = def => !!(def != null && def.render); -const context = /*#__PURE__*/React.createContext(null); - -const createStore$2 = (invalidate, advance) => { - const rootState = create$4((set, get) => { - const position = new Vector3(); - const defaultTarget = new Vector3(); - const tempTarget = new Vector3(); - - function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) { - const { - width, - height - } = size; - const aspect = width / height; - if (target instanceof Vector3) tempTarget.copy(target);else tempTarget.set(...target); - const distance = camera.getWorldPosition(position).distanceTo(tempTarget); - - if (isOrthographicCamera(camera)) { - return { - width: width / camera.zoom, - height: height / camera.zoom, - factor: 1, - distance, - aspect - }; - } else { - const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians - - const h = 2 * Math.tan(fov / 2) * distance; // visible height - - const w = h * (width / height); - return { - width: w, - height: h, - factor: width / w, - distance, - aspect - }; - } - } - - let performanceTimeout = undefined; - - const setPerformanceCurrent = current => set(state => ({ - performance: { ...state.performance, - current - } - })); - - const pointer = new Vector2(); - return { - set, - get, - // Mock objects that have to be configured - gl: null, - camera: null, - raycaster: null, - events: { - priority: 1, - enabled: true, - connected: false - }, - xr: null, - invalidate: (frames = 1) => invalidate(get(), frames), - advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()), - legacy: false, - linear: false, - flat: false, - scene: prepare(new Scene$1()), - controls: null, - clock: new Clock(), - pointer, - mouse: pointer, - frameloop: 'always', - onPointerMissed: undefined, - performance: { - current: 1, - min: 0.5, - max: 1, - debounce: 200, - regress: () => { - const state = get(); // Clear timeout - - if (performanceTimeout) clearTimeout(performanceTimeout); // Set lower bound performance - - if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min); // Go back to upper bound performance after a while unless something regresses meanwhile - - performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce); - } - }, - size: { - width: 0, - height: 0, - updateStyle: false - }, - viewport: { - initialDpr: 0, - dpr: 0, - width: 0, - height: 0, - aspect: 0, - distance: 0, - factor: 0, - getCurrentViewport - }, - setEvents: events => set(state => ({ ...state, - events: { ...state.events, - ...events - } - })), - setSize: (width, height, updateStyle) => { - const camera = get().camera; - const size = { - width, - height, - updateStyle - }; - set(state => ({ - size, - viewport: { ...state.viewport, - ...getCurrentViewport(camera, defaultTarget, size) - } - })); - }, - setDpr: dpr => set(state => { - const resolved = calculateDpr(dpr); - return { - viewport: { ...state.viewport, - dpr: resolved, - initialDpr: state.viewport.initialDpr || resolved - } - }; - }), - setFrameloop: (frameloop = 'always') => { - const clock = get().clock; // if frameloop === "never" clock.elapsedTime is updated using advance(timestamp) - - clock.stop(); - clock.elapsedTime = 0; - - if (frameloop !== 'never') { - clock.start(); - clock.elapsedTime = 0; - } - - set(() => ({ - frameloop - })); - }, - previousRoot: undefined, - internal: { - active: false, - priority: 0, - frames: 0, - lastEvent: /*#__PURE__*/React.createRef(), - interaction: [], - hovered: new Map(), - subscribers: [], - initialClick: [0, 0], - initialHits: [], - capturedMap: new Map(), - subscribe: (ref, priority, store) => { - const internal = get().internal; // If this subscription was given a priority, it takes rendering into its own hands - // For that reason we switch off automatic rendering and increase the manual flag - // As long as this flag is positive there can be no internal rendering at all - // because there could be multiple render subscriptions - - internal.priority = internal.priority + (priority > 0 ? 1 : 0); - internal.subscribers.push({ - ref, - priority, - store - }); // Register subscriber and sort layers from lowest to highest, meaning, - // highest priority renders last (on top of the other frames) - - internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority); - return () => { - const internal = get().internal; - - if (internal != null && internal.subscribers) { - // Decrease manual flag if this subscription had a priority - internal.priority = internal.priority - (priority > 0 ? 1 : 0); // Remove subscriber from list - - internal.subscribers = internal.subscribers.filter(s => s.ref !== ref); - } - }; - } - } - }; - }); - const state = rootState.getState(); - let oldSize = state.size; - let oldDpr = state.viewport.dpr; - let oldCamera = state.camera; - rootState.subscribe(() => { - const { - camera, - size, - viewport, - gl, - set - } = rootState.getState(); // Resize camera and renderer on changes to size and pixelratio - - if (size !== oldSize || viewport.dpr !== oldDpr) { - oldSize = size; - oldDpr = viewport.dpr; // Update camera & renderer - - updateCamera(camera, size); - gl.setPixelRatio(viewport.dpr); - gl.setSize(size.width, size.height, size.updateStyle); - } // Update viewport once the camera changes - - - if (camera !== oldCamera) { - oldCamera = camera; // Update viewport - - set(state => ({ - viewport: { ...state.viewport, - ...state.viewport.getCurrentViewport(camera) - } - })); - } - }); // Invalidate on any change - - rootState.subscribe(state => invalidate(state)); // Return root state - - return rootState; -}; - -function createSubs(callback, subs) { - const index = subs.length; - subs.push(callback); - return () => void subs.splice(index, 1); -} - -let i$4; -let globalEffects = []; -let globalAfterEffects = []; -let globalTailEffects = []; -/** - * Adds a global render callback which is called each frame. - * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect - */ - -const addEffect = callback => createSubs(callback, globalEffects); - -function run(effects, timestamp) { - for (i$4 = 0; i$4 < effects.length; i$4++) effects[i$4](timestamp); -} - -let subscribers; -let subscription; - -function render$1(timestamp, state, frame) { - // Run local effects - let delta = state.clock.getDelta(); // In frameloop='never' mode, clock times are updated using the provided timestamp - - if (state.frameloop === 'never' && typeof timestamp === 'number') { - delta = timestamp - state.clock.elapsedTime; - state.clock.oldTime = state.clock.elapsedTime; - state.clock.elapsedTime = timestamp; - } // Call subscribers (useFrame) - - - subscribers = state.internal.subscribers; - - for (i$4 = 0; i$4 < subscribers.length; i$4++) { - subscription = subscribers[i$4]; - subscription.ref.current(subscription.store.getState(), delta, frame); - } // Render content - - - if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera); // Decrease frame count - - state.internal.frames = Math.max(0, state.internal.frames - 1); - return state.frameloop === 'always' ? 1 : state.internal.frames; -} - -function createLoop(roots) { - let running = false; - let repeat; - let frame; - let state; - - function loop(timestamp) { - frame = requestAnimationFrame(loop); - running = true; - repeat = 0; // Run effects - - if (globalEffects.length) run(globalEffects, timestamp); // Render all roots - - roots.forEach(root => { - var _state$gl$xr; - - state = root.store.getState(); // If the frameloop is invalidated, do not run another frame - - if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) { - repeat += render$1(timestamp, state); - } - }); // Run after-effects - - if (globalAfterEffects.length) run(globalAfterEffects, timestamp); // Stop the loop if nothing invalidates it - - if (repeat === 0) { - // Tail call effects, they are called when rendering stops - if (globalTailEffects.length) run(globalTailEffects, timestamp); // Flag end of operation - - running = false; - return cancelAnimationFrame(frame); - } - } - - function invalidate(state, frames = 1) { - var _state$gl$xr2; - - if (!state) return roots.forEach(root => invalidate(root.store.getState()), frames); - if ((_state$gl$xr2 = state.gl.xr) != null && _state$gl$xr2.isPresenting || !state.internal.active || state.frameloop === 'never') return; // Increase frames, do not go higher than 60 - - state.internal.frames = Math.min(60, state.internal.frames + frames); // If the render-loop isn't active, start it - - if (!running) { - running = true; - requestAnimationFrame(loop); - } - } - - function advance(timestamp, runGlobalEffects = true, state, frame) { - if (runGlobalEffects) run(globalEffects, timestamp); - if (!state) roots.forEach(root => render$1(timestamp, root.store.getState()));else render$1(timestamp, state, frame); - if (runGlobalEffects) run(globalAfterEffects, timestamp); - } - - return { - loop, - - /** - * Invalidates the view, requesting a frame to be rendered. Will globally invalidate unless passed a root's state. - * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate - */ - invalidate, - - /** - * Advances the frameloop and runs render effects, useful for when manually rendering via `frameloop="never"`. - * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance - */ - advance - }; -} - -function useStore$1() { - const store = React.useContext(context); - if (!store) throw `R3F hooks can only be used within the Canvas component!`; - return store; -} -/** - * Accesses R3F's internal state, containing renderer, canvas, scene, etc. - * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usethree - */ - -function useThree(selector = state => state, equalityFn) { - return useStore$1()(selector, equalityFn); -} -/** - * Executes a callback before render in a shared frame loop. - * Can order effects with render priority or manually render with a positive priority. - * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe - */ - -function useFrame(callback, renderPriority = 0) { - const store = useStore$1(); - const subscribe = store.getState().internal.subscribe; // Memoize ref - - const ref = useMutableCallback(callback); // Subscribe on mount, unsubscribe on unmount - - useIsomorphicLayoutEffect$1(() => subscribe(ref, renderPriority, store), [renderPriority, subscribe, store]); - return null; -} - -const roots = new Map(); -const { - invalidate, - advance: advance$1 -} = createLoop(roots); -const { - reconciler, - applyProps -} = createRenderer(roots, getEventPriority); -const shallowLoose = { - objects: 'shallow', - strict: false -}; - -const createRendererInstance = (gl, canvas) => { - const customRenderer = typeof gl === 'function' ? gl(canvas) : gl; - if (isRenderer(customRenderer)) return customRenderer;else return new WebGLRenderer({ - powerPreference: 'high-performance', - canvas: canvas, - antialias: true, - alpha: true, - ...gl - }); -}; - -function createRoot(canvas) { - // Check against mistaken use of createRoot - let prevRoot = roots.get(canvas); - let prevFiber = prevRoot == null ? void 0 : prevRoot.fiber; - let prevStore = prevRoot == null ? void 0 : prevRoot.store; - if (prevRoot) console.warn('R3F.createRoot should only be called once!'); // Report when an error was detected in a previous render - // https://github.com/pmndrs/react-three-fiber/pull/2261 - - const logRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event, - // emulating an uncaught JavaScript error. - reportError : // In older browsers and test environments, fallback to console.error. - console.error; // Create store - - const store = prevStore || createStore$2(invalidate, advance$1); // Create renderer - - const fiber = prevFiber || reconciler.createContainer(store, constants$1.exports.ConcurrentRoot, null, false, null, '', logRecoverableError, null); // Map it - - if (!prevRoot) roots.set(canvas, { - fiber, - store - }); // Locals - - let onCreated; - let configured = false; - return { - configure(props = {}) { - var _canvas$parentElement, _canvas$parentElement2, _canvas$parentElement3, _canvas$parentElement4; - - let { - gl: glConfig, - size, - events, - onCreated: onCreatedCallback, - shadows = false, - linear = false, - flat = false, - legacy = false, - orthographic = false, - frameloop = 'always', - dpr = [1, 2], - performance, - raycaster: raycastOptions, - camera: cameraOptions, - onPointerMissed - } = props; - let state = store.getState(); // Set up renderer (one time only!) - - let gl = state.gl; - if (!state.gl) state.set({ - gl: gl = createRendererInstance(glConfig, canvas) - }); // Set up raycaster (one time only!) - - let raycaster = state.raycaster; - if (!raycaster) state.set({ - raycaster: raycaster = new Raycaster() - }); // Set raycaster options - - const { - params, - ...options - } = raycastOptions || {}; - if (!is$1.equ(options, raycaster, shallowLoose)) applyProps(raycaster, { ...options - }); - if (!is$1.equ(params, raycaster.params, shallowLoose)) applyProps(raycaster, { - params: { ...raycaster.params, - ...params - } - }); // Create default camera (one time only!) - - if (!state.camera) { - const isCamera = cameraOptions instanceof Camera; - const camera = isCamera ? cameraOptions : orthographic ? new OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new PerspectiveCamera(75, 0, 0.1, 1000); - - if (!isCamera) { - camera.position.z = 5; - if (cameraOptions) applyProps(camera, cameraOptions); // Always look at center by default - - if (!(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0); - } - - state.set({ - camera - }); - } // Set up XR (one time only!) - - - if (!state.xr) { - // Handle frame behavior in WebXR - const handleXRFrame = (timestamp, frame) => { - const state = store.getState(); - if (state.frameloop === 'never') return; - advance$1(timestamp, true, state, frame); - }; // Toggle render switching on session - - - const handleSessionChange = () => { - const state = store.getState(); - state.gl.xr.enabled = state.gl.xr.isPresenting; - state.gl.xr.setAnimationLoop(state.gl.xr.isPresenting ? handleXRFrame : null); - if (!state.gl.xr.isPresenting) invalidate(state); - }; // WebXR session manager - - - const xr = { - connect() { - const gl = store.getState().gl; - gl.xr.addEventListener('sessionstart', handleSessionChange); - gl.xr.addEventListener('sessionend', handleSessionChange); - }, - - disconnect() { - const gl = store.getState().gl; - gl.xr.removeEventListener('sessionstart', handleSessionChange); - gl.xr.removeEventListener('sessionend', handleSessionChange); - } - - }; // Subscribe to WebXR session events - - if (gl.xr) xr.connect(); - state.set({ - xr - }); - } // Set shadowmap - - - if (gl.shadowMap) { - const isBoolean = is$1.boo(shadows); - - if (isBoolean && gl.shadowMap.enabled !== shadows || !is$1.equ(shadows, gl.shadowMap, shallowLoose)) { - const old = gl.shadowMap.enabled; - gl.shadowMap.enabled = !!shadows; - if (!isBoolean) Object.assign(gl.shadowMap, shadows);else gl.shadowMap.type = PCFSoftShadowMap; - if (old !== gl.shadowMap.enabled) gl.shadowMap.needsUpdate = true; - } - } // Safely set color management if available. - // Avoid accessing THREE.ColorManagement to play nice with older versions - - - if ('ColorManagement' in THREE) { - setDeep(THREE, legacy, ['ColorManagement', 'legacyMode']); - } - - const outputEncoding = linear ? LinearEncoding : sRGBEncoding; - const toneMapping = flat ? NoToneMapping : ACESFilmicToneMapping; - if (gl.outputEncoding !== outputEncoding) gl.outputEncoding = outputEncoding; - if (gl.toneMapping !== toneMapping) gl.toneMapping = toneMapping; // Update color management state - - if (state.legacy !== legacy) state.set(() => ({ - legacy - })); - if (state.linear !== linear) state.set(() => ({ - linear - })); - if (state.flat !== flat) state.set(() => ({ - flat - })); // Set gl props - - if (glConfig && !is$1.fun(glConfig) && !isRenderer(glConfig) && !is$1.equ(glConfig, gl, shallowLoose)) applyProps(gl, glConfig); // Store events internally - - if (events && !state.events.handlers) state.set({ - events: events(store) - }); // Check pixelratio - - if (dpr && state.viewport.dpr !== calculateDpr(dpr)) state.setDpr(dpr); // Check size, allow it to take on container bounds initially - - size = size || { - width: (_canvas$parentElement = (_canvas$parentElement2 = canvas.parentElement) == null ? void 0 : _canvas$parentElement2.clientWidth) != null ? _canvas$parentElement : 0, - height: (_canvas$parentElement3 = (_canvas$parentElement4 = canvas.parentElement) == null ? void 0 : _canvas$parentElement4.clientHeight) != null ? _canvas$parentElement3 : 0 - }; - if (!is$1.equ(size, state.size, shallowLoose)) state.setSize(size.width, size.height, size.updateStyle); // Check frameloop - - if (state.frameloop !== frameloop) state.setFrameloop(frameloop); // Check pointer missed - - if (!state.onPointerMissed) state.set({ - onPointerMissed - }); // Check performance - - if (performance && !is$1.equ(performance, state.performance, shallowLoose)) state.set(state => ({ - performance: { ...state.performance, - ...performance - } - })); // Set locals - - onCreated = onCreatedCallback; - configured = true; - return this; - }, - - render(children) { - // The root has to be configured before it can be rendered - if (!configured) this.configure(); - reconciler.updateContainer( /*#__PURE__*/React.createElement(Provider, { - store: store, - children: children, - onCreated: onCreated, - rootElement: canvas - }), fiber, null, () => undefined); - return store; - }, - - unmount() { - unmountComponentAtNode(canvas); - } - - }; -} - -function Provider({ - store, - children, - onCreated, - rootElement -}) { - useIsomorphicLayoutEffect$1(() => { - const state = store.getState(); // Flag the canvas active, rendering will now begin - - state.set(state => ({ - internal: { ...state.internal, - active: true - } - })); // Notifiy that init is completed, the scene graph exists, but nothing has yet rendered - - if (onCreated) onCreated(state); // Connect events to the targets parent, this is done to ensure events are registered on - // a shared target, and not on the canvas itself - - if (!store.getState().events.connected) state.events.connect == null ? void 0 : state.events.connect(rootElement); // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - return /*#__PURE__*/React.createElement(context.Provider, { - value: store - }, children); -} - -function unmountComponentAtNode(canvas, callback) { - const root = roots.get(canvas); - const fiber = root == null ? void 0 : root.fiber; - - if (fiber) { - const state = root == null ? void 0 : root.store.getState(); - if (state) state.internal.active = false; - reconciler.updateContainer(null, fiber, null, () => { - if (state) { - setTimeout(() => { - try { - var _state$gl, _state$gl$renderLists, _state$gl2, _state$gl3; - - state.events.disconnect == null ? void 0 : state.events.disconnect(); - (_state$gl = state.gl) == null ? void 0 : (_state$gl$renderLists = _state$gl.renderLists) == null ? void 0 : _state$gl$renderLists.dispose == null ? void 0 : _state$gl$renderLists.dispose(); - (_state$gl2 = state.gl) == null ? void 0 : _state$gl2.forceContextLoss == null ? void 0 : _state$gl2.forceContextLoss(); - if ((_state$gl3 = state.gl) != null && _state$gl3.xr) state.xr.disconnect(); - dispose(state); - roots.delete(canvas); - if (callback) callback(canvas); - } catch (e) { - /* ... */ - } - }, 500); - } - }); - } -} - -reconciler.injectIntoDevTools({ - bundleType: process.env.NODE_ENV === 'production' ? 0 : 1, - rendererPackageName: '@react-three/fiber', - version: React.version -}); - -function _extends$3() { - _extends$3 = Object.assign ? Object.assign.bind() : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - return _extends$3.apply(this, arguments); -} - -/** - * Returns a function, that, as long as it continues to be invoked, will not - * be triggered. The function will be called after it stops being called for - * N milliseconds. If `immediate` is passed, trigger the function on the - * leading edge, instead of the trailing. The function also has a property 'clear' - * that is a function which will clear the timer to prevent previously scheduled executions. - * - * @source underscore.js - * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ - * @param {Function} function to wrap - * @param {Number} timeout in ms (`100`) - * @param {Boolean} whether to execute at the beginning (`false`) - * @api public - */ - -function debounce(func, wait, immediate){ - var timeout, args, context, timestamp, result; - if (null == wait) wait = 100; - - function later() { - var last = Date.now() - timestamp; - - if (last < wait && last >= 0) { - timeout = setTimeout(later, wait - last); - } else { - timeout = null; - if (!immediate) { - result = func.apply(context, args); - context = args = null; - } - } - } - var debounced = function(){ - context = this; - args = arguments; - timestamp = Date.now(); - var callNow = immediate && !timeout; - if (!timeout) timeout = setTimeout(later, wait); - if (callNow) { - result = func.apply(context, args); - context = args = null; - } - - return result; - }; - - debounced.clear = function() { - if (timeout) { - clearTimeout(timeout); - timeout = null; - } - }; - - debounced.flush = function() { - if (timeout) { - result = func.apply(context, args); - context = args = null; - - clearTimeout(timeout); - timeout = null; - } - }; - - return debounced; -} -// Adds compatibility for ES modules -debounce.debounce = debounce; - -var debounce_1 = debounce; - -function useMeasure(_temp) { - let { - debounce, - scroll, - polyfill, - offsetSize - } = _temp === void 0 ? { - debounce: 0, - scroll: false, - offsetSize: false - } : _temp; - const ResizeObserver = polyfill || (typeof window === 'undefined' ? class ResizeObserver {} : window.ResizeObserver); - - if (!ResizeObserver) { - throw new Error('This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills'); - } - - const [bounds, set] = useState({ - left: 0, - top: 0, - width: 0, - height: 0, - bottom: 0, - right: 0, - x: 0, - y: 0 - }); // keep all state in a ref - - const state = useRef({ - element: null, - scrollContainers: null, - resizeObserver: null, - lastBounds: bounds - }); // set actual debounce values early, so effects know if they should react accordingly - - const scrollDebounce = debounce ? typeof debounce === 'number' ? debounce : debounce.scroll : null; - const resizeDebounce = debounce ? typeof debounce === 'number' ? debounce : debounce.resize : null; // make sure to update state only as long as the component is truly mounted - - const mounted = useRef(false); - useEffect(() => { - mounted.current = true; - return () => void (mounted.current = false); - }); // memoize handlers, so event-listeners know when they should update - - const [forceRefresh, resizeChange, scrollChange] = useMemo(() => { - const callback = () => { - if (!state.current.element) return; - const { - left, - top, - width, - height, - bottom, - right, - x, - y - } = state.current.element.getBoundingClientRect(); - const size = { - left, - top, - width, - height, - bottom, - right, - x, - y - }; - - if (state.current.element instanceof HTMLElement && offsetSize) { - size.height = state.current.element.offsetHeight; - size.width = state.current.element.offsetWidth; - } - - Object.freeze(size); - if (mounted.current && !areBoundsEqual(state.current.lastBounds, size)) set(state.current.lastBounds = size); - }; - - return [callback, resizeDebounce ? debounce_1(callback, resizeDebounce) : callback, scrollDebounce ? debounce_1(callback, scrollDebounce) : callback]; - }, [set, offsetSize, scrollDebounce, resizeDebounce]); // cleanup current scroll-listeners / observers - - function removeListeners() { - if (state.current.scrollContainers) { - state.current.scrollContainers.forEach(element => element.removeEventListener('scroll', scrollChange, true)); - state.current.scrollContainers = null; - } - - if (state.current.resizeObserver) { - state.current.resizeObserver.disconnect(); - state.current.resizeObserver = null; - } - } // add scroll-listeners / observers - - - function addListeners() { - if (!state.current.element) return; - state.current.resizeObserver = new ResizeObserver(scrollChange); - state.current.resizeObserver.observe(state.current.element); - - if (scroll && state.current.scrollContainers) { - state.current.scrollContainers.forEach(scrollContainer => scrollContainer.addEventListener('scroll', scrollChange, { - capture: true, - passive: true - })); - } - } // the ref we expose to the user - - - const ref = node => { - if (!node || node === state.current.element) return; - removeListeners(); - state.current.element = node; - state.current.scrollContainers = findScrollContainers(node); - addListeners(); - }; // add general event listeners - - - useOnWindowScroll(scrollChange, Boolean(scroll)); - useOnWindowResize(resizeChange); // respond to changes that are relevant for the listeners - - useEffect(() => { - removeListeners(); - addListeners(); - }, [scroll, scrollChange, resizeChange]); // remove all listeners when the components unmounts - - useEffect(() => removeListeners, []); - return [ref, bounds, forceRefresh]; -} // Adds native resize listener to window - - -function useOnWindowResize(onWindowResize) { - useEffect(() => { - const cb = onWindowResize; - window.addEventListener('resize', cb); - return () => void window.removeEventListener('resize', cb); - }, [onWindowResize]); -} - -function useOnWindowScroll(onScroll, enabled) { - useEffect(() => { - if (enabled) { - const cb = onScroll; - window.addEventListener('scroll', cb, { - capture: true, - passive: true - }); - return () => void window.removeEventListener('scroll', cb, true); - } - }, [onScroll, enabled]); -} // Returns a list of scroll offsets - - -function findScrollContainers(element) { - const result = []; - if (!element || element === document.body) return result; - const { - overflow, - overflowX, - overflowY - } = window.getComputedStyle(element); - if ([overflow, overflowX, overflowY].some(prop => prop === 'auto' || prop === 'scroll')) result.push(element); - return [...result, ...findScrollContainers(element.parentElement)]; -} // Checks if element boundaries are equal - - -const keys$a = ['x', 'y', 'top', 'bottom', 'left', 'right', 'width', 'height']; - -const areBoundsEqual = (a, b) => keys$a.every(key => a[key] === b[key]); - -const DOM_EVENTS = { - onClick: ['click', false], - onContextMenu: ['contextmenu', false], - onDoubleClick: ['dblclick', false], - onWheel: ['wheel', true], - onPointerDown: ['pointerdown', true], - onPointerUp: ['pointerup', true], - onPointerLeave: ['pointerleave', true], - onPointerMove: ['pointermove', true], - onPointerCancel: ['pointercancel', true], - onLostPointerCapture: ['lostpointercapture', true] -}; -/** Default R3F event manager for web */ - -function createPointerEvents(store) { - const { - handlePointer - } = createEvents(store); - return { - priority: 1, - enabled: true, - - compute(event, state, previous) { - // https://github.com/pmndrs/react-three-fiber/pull/782 - // Events trigger outside of canvas when moved, use offsetX/Y by default and allow overrides - state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1); - state.raycaster.setFromCamera(state.pointer, state.camera); - }, - - connected: undefined, - handlers: Object.keys(DOM_EVENTS).reduce((acc, key) => ({ ...acc, - [key]: handlePointer(key) - }), {}), - connect: target => { - var _events$handlers; - - const { - set, - events - } = store.getState(); - events.disconnect == null ? void 0 : events.disconnect(); - set(state => ({ - events: { ...state.events, - connected: target - } - })); - Object.entries((_events$handlers = events.handlers) != null ? _events$handlers : []).forEach(([name, event]) => { - const [eventName, passive] = DOM_EVENTS[name]; - target.addEventListener(eventName, event, { - passive - }); - }); - }, - disconnect: () => { - const { - set, - events - } = store.getState(); - - if (events.connected) { - var _events$handlers2; - - Object.entries((_events$handlers2 = events.handlers) != null ? _events$handlers2 : []).forEach(([name, event]) => { - if (events && events.connected instanceof HTMLElement) { - const [eventName] = DOM_EVENTS[name]; - events.connected.removeEventListener(eventName, event); - } - }); - set(state => ({ - events: { ...state.events, - connected: undefined - } - })); - } - } - }; -} - -/** - * A DOM canvas which accepts threejs elements as children. - * @see https://docs.pmnd.rs/react-three-fiber/api/canvas - */ -const Canvas = /*#__PURE__*/React.forwardRef(function Canvas({ - children, - fallback, - resize, - style, - gl, - events = createPointerEvents, - shadows, - linear, - flat, - legacy, - orthographic, - frameloop, - dpr, - performance, - raycaster, - camera, - onPointerMissed, - onCreated, - ...props -}, forwardedRef) { - // Create a known catalogue of Threejs-native elements - // This will include the entire THREE namespace by default, users can extend - // their own elements by using the createRoot API instead - React.useMemo(() => extend(THREE), []); - const [containerRef, { - width, - height - }] = useMeasure({ - scroll: true, - debounce: { - scroll: 50, - resize: 0 - }, - ...resize - }); - const canvasRef = React.useRef(null); - const divRef = React.useRef(null); - const [canvas, setCanvas] = React.useState(null); - React.useImperativeHandle(forwardedRef, () => canvasRef.current); - const handlePointerMissed = useMutableCallback(onPointerMissed); - const [block, setBlock] = React.useState(false); - const [error, setError] = React.useState(false); // Suspend this component if block is a promise (2nd run) - - if (block) throw block; // Throw exception outwards if anything within canvas throws - - if (error) throw error; - const root = React.useRef(null); - - if (width > 0 && height > 0 && canvas) { - if (!root.current) root.current = createRoot(canvas); - root.current.configure({ - gl, - events, - shadows, - linear, - flat, - legacy, - orthographic, - frameloop, - dpr, - performance, - raycaster, - camera, - size: { - width, - height - }, - // Pass mutable reference to onPointerMissed so it's free to update - onPointerMissed: (...args) => handlePointerMissed.current == null ? void 0 : handlePointerMissed.current(...args), - onCreated: state => { - state.events.connect == null ? void 0 : state.events.connect(divRef.current); - onCreated == null ? void 0 : onCreated(state); - } - }); - root.current.render( /*#__PURE__*/React.createElement(ErrorBoundary, { - set: setError - }, /*#__PURE__*/React.createElement(React.Suspense, { - fallback: /*#__PURE__*/React.createElement(Block, { - set: setBlock - }) - }, children))); - } - - useIsomorphicLayoutEffect$1(() => { - setCanvas(canvasRef.current); - }, []); - React.useEffect(() => { - if (canvas) return () => unmountComponentAtNode(canvas); - }, [canvas]); - return /*#__PURE__*/React.createElement("div", _extends$3({ - ref: divRef, - style: { - position: 'relative', - width: '100%', - height: '100%', - overflow: 'hidden', - ...style - } - }, props), /*#__PURE__*/React.createElement("div", { - ref: containerRef, - style: { - width: '100%', - height: '100%' - } - }, /*#__PURE__*/React.createElement("canvas", { - ref: canvasRef, - style: { - display: 'block' - } - }, fallback))); -}); - -var resizeObservers = []; - -var hasActiveObservations = function () { - return resizeObservers.some(function (ro) { return ro.activeTargets.length > 0; }); -}; - -var hasSkippedObservations = function () { - return resizeObservers.some(function (ro) { return ro.skippedTargets.length > 0; }); -}; - -var msg = 'ResizeObserver loop completed with undelivered notifications.'; -var deliverResizeLoopError = function () { - var event; - if (typeof ErrorEvent === 'function') { - event = new ErrorEvent('error', { - message: msg - }); - } - else { - event = document.createEvent('Event'); - event.initEvent('error', false, false); - event.message = msg; - } - window.dispatchEvent(event); -}; - -var ResizeObserverBoxOptions; -(function (ResizeObserverBoxOptions) { - ResizeObserverBoxOptions["BORDER_BOX"] = "border-box"; - ResizeObserverBoxOptions["CONTENT_BOX"] = "content-box"; - ResizeObserverBoxOptions["DEVICE_PIXEL_CONTENT_BOX"] = "device-pixel-content-box"; -})(ResizeObserverBoxOptions || (ResizeObserverBoxOptions = {})); - -var freeze = function (obj) { return Object.freeze(obj); }; - -var ResizeObserverSize = (function () { - function ResizeObserverSize(inlineSize, blockSize) { - this.inlineSize = inlineSize; - this.blockSize = blockSize; - freeze(this); - } - return ResizeObserverSize; -}()); - -var DOMRectReadOnly = (function () { - function DOMRectReadOnly(x, y, width, height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.top = this.y; - this.left = this.x; - this.bottom = this.top + this.height; - this.right = this.left + this.width; - return freeze(this); - } - DOMRectReadOnly.prototype.toJSON = function () { - var _a = this, x = _a.x, y = _a.y, top = _a.top, right = _a.right, bottom = _a.bottom, left = _a.left, width = _a.width, height = _a.height; - return { x: x, y: y, top: top, right: right, bottom: bottom, left: left, width: width, height: height }; - }; - DOMRectReadOnly.fromRect = function (rectangle) { - return new DOMRectReadOnly(rectangle.x, rectangle.y, rectangle.width, rectangle.height); - }; - return DOMRectReadOnly; -}()); - -var isSVG = function (target) { return target instanceof SVGElement && 'getBBox' in target; }; -var isHidden = function (target) { - if (isSVG(target)) { - var _a = target.getBBox(), width = _a.width, height = _a.height; - return !width && !height; - } - var _b = target, offsetWidth = _b.offsetWidth, offsetHeight = _b.offsetHeight; - return !(offsetWidth || offsetHeight || target.getClientRects().length); -}; -var isElement = function (obj) { - var _a, _b; - if (obj instanceof Element) { - return true; - } - var scope = (_b = (_a = obj) === null || _a === void 0 ? void 0 : _a.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView; - return !!(scope && obj instanceof scope.Element); -}; -var isReplacedElement = function (target) { - switch (target.tagName) { - case 'INPUT': - if (target.type !== 'image') { - break; - } - case 'VIDEO': - case 'AUDIO': - case 'EMBED': - case 'OBJECT': - case 'CANVAS': - case 'IFRAME': - case 'IMG': - return true; - } - return false; -}; - -var global$1 = typeof window !== 'undefined' ? window : {}; - -var cache = new WeakMap(); -var scrollRegexp = /auto|scroll/; -var verticalRegexp = /^tb|vertical/; -var IE = (/msie|trident/i).test(global$1.navigator && global$1.navigator.userAgent); -var parseDimension = function (pixel) { return parseFloat(pixel || '0'); }; -var size$1 = function (inlineSize, blockSize, switchSizes) { - if (inlineSize === void 0) { inlineSize = 0; } - if (blockSize === void 0) { blockSize = 0; } - if (switchSizes === void 0) { switchSizes = false; } - return new ResizeObserverSize((switchSizes ? blockSize : inlineSize) || 0, (switchSizes ? inlineSize : blockSize) || 0); -}; -var zeroBoxes = freeze({ - devicePixelContentBoxSize: size$1(), - borderBoxSize: size$1(), - contentBoxSize: size$1(), - contentRect: new DOMRectReadOnly(0, 0, 0, 0) -}); -var calculateBoxSizes = function (target, forceRecalculation) { - if (forceRecalculation === void 0) { forceRecalculation = false; } - if (cache.has(target) && !forceRecalculation) { - return cache.get(target); - } - if (isHidden(target)) { - cache.set(target, zeroBoxes); - return zeroBoxes; - } - var cs = getComputedStyle(target); - var svg = isSVG(target) && target.ownerSVGElement && target.getBBox(); - var removePadding = !IE && cs.boxSizing === 'border-box'; - var switchSizes = verticalRegexp.test(cs.writingMode || ''); - var canScrollVertically = !svg && scrollRegexp.test(cs.overflowY || ''); - var canScrollHorizontally = !svg && scrollRegexp.test(cs.overflowX || ''); - var paddingTop = svg ? 0 : parseDimension(cs.paddingTop); - var paddingRight = svg ? 0 : parseDimension(cs.paddingRight); - var paddingBottom = svg ? 0 : parseDimension(cs.paddingBottom); - var paddingLeft = svg ? 0 : parseDimension(cs.paddingLeft); - var borderTop = svg ? 0 : parseDimension(cs.borderTopWidth); - var borderRight = svg ? 0 : parseDimension(cs.borderRightWidth); - var borderBottom = svg ? 0 : parseDimension(cs.borderBottomWidth); - var borderLeft = svg ? 0 : parseDimension(cs.borderLeftWidth); - var horizontalPadding = paddingLeft + paddingRight; - var verticalPadding = paddingTop + paddingBottom; - var horizontalBorderArea = borderLeft + borderRight; - var verticalBorderArea = borderTop + borderBottom; - var horizontalScrollbarThickness = !canScrollHorizontally ? 0 : target.offsetHeight - verticalBorderArea - target.clientHeight; - var verticalScrollbarThickness = !canScrollVertically ? 0 : target.offsetWidth - horizontalBorderArea - target.clientWidth; - var widthReduction = removePadding ? horizontalPadding + horizontalBorderArea : 0; - var heightReduction = removePadding ? verticalPadding + verticalBorderArea : 0; - var contentWidth = svg ? svg.width : parseDimension(cs.width) - widthReduction - verticalScrollbarThickness; - var contentHeight = svg ? svg.height : parseDimension(cs.height) - heightReduction - horizontalScrollbarThickness; - var borderBoxWidth = contentWidth + horizontalPadding + verticalScrollbarThickness + horizontalBorderArea; - var borderBoxHeight = contentHeight + verticalPadding + horizontalScrollbarThickness + verticalBorderArea; - var boxes = freeze({ - devicePixelContentBoxSize: size$1(Math.round(contentWidth * devicePixelRatio), Math.round(contentHeight * devicePixelRatio), switchSizes), - borderBoxSize: size$1(borderBoxWidth, borderBoxHeight, switchSizes), - contentBoxSize: size$1(contentWidth, contentHeight, switchSizes), - contentRect: new DOMRectReadOnly(paddingLeft, paddingTop, contentWidth, contentHeight) - }); - cache.set(target, boxes); - return boxes; -}; -var calculateBoxSize = function (target, observedBox, forceRecalculation) { - var _a = calculateBoxSizes(target, forceRecalculation), borderBoxSize = _a.borderBoxSize, contentBoxSize = _a.contentBoxSize, devicePixelContentBoxSize = _a.devicePixelContentBoxSize; - switch (observedBox) { - case ResizeObserverBoxOptions.DEVICE_PIXEL_CONTENT_BOX: - return devicePixelContentBoxSize; - case ResizeObserverBoxOptions.BORDER_BOX: - return borderBoxSize; - default: - return contentBoxSize; - } -}; - -var ResizeObserverEntry = (function () { - function ResizeObserverEntry(target) { - var boxes = calculateBoxSizes(target); - this.target = target; - this.contentRect = boxes.contentRect; - this.borderBoxSize = freeze([boxes.borderBoxSize]); - this.contentBoxSize = freeze([boxes.contentBoxSize]); - this.devicePixelContentBoxSize = freeze([boxes.devicePixelContentBoxSize]); - } - return ResizeObserverEntry; -}()); - -var calculateDepthForNode = function (node) { - if (isHidden(node)) { - return Infinity; - } - var depth = 0; - var parent = node.parentNode; - while (parent) { - depth += 1; - parent = parent.parentNode; - } - return depth; -}; - -var broadcastActiveObservations = function () { - var shallowestDepth = Infinity; - var callbacks = []; - resizeObservers.forEach(function processObserver(ro) { - if (ro.activeTargets.length === 0) { - return; - } - var entries = []; - ro.activeTargets.forEach(function processTarget(ot) { - var entry = new ResizeObserverEntry(ot.target); - var targetDepth = calculateDepthForNode(ot.target); - entries.push(entry); - ot.lastReportedSize = calculateBoxSize(ot.target, ot.observedBox); - if (targetDepth < shallowestDepth) { - shallowestDepth = targetDepth; - } - }); - callbacks.push(function resizeObserverCallback() { - ro.callback.call(ro.observer, entries, ro.observer); - }); - ro.activeTargets.splice(0, ro.activeTargets.length); - }); - for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { - var callback = callbacks_1[_i]; - callback(); - } - return shallowestDepth; -}; - -var gatherActiveObservationsAtDepth = function (depth) { - resizeObservers.forEach(function processObserver(ro) { - ro.activeTargets.splice(0, ro.activeTargets.length); - ro.skippedTargets.splice(0, ro.skippedTargets.length); - ro.observationTargets.forEach(function processTarget(ot) { - if (ot.isActive()) { - if (calculateDepthForNode(ot.target) > depth) { - ro.activeTargets.push(ot); - } - else { - ro.skippedTargets.push(ot); - } - } - }); - }); -}; - -var process$1 = function () { - var depth = 0; - gatherActiveObservationsAtDepth(depth); - while (hasActiveObservations()) { - depth = broadcastActiveObservations(); - gatherActiveObservationsAtDepth(depth); - } - if (hasSkippedObservations()) { - deliverResizeLoopError(); - } - return depth > 0; -}; - -var trigger; -var callbacks = []; -var notify = function () { return callbacks.splice(0).forEach(function (cb) { return cb(); }); }; -var queueMicroTask = function (callback) { - if (!trigger) { - var toggle_1 = 0; - var el_1 = document.createTextNode(''); - var config = { characterData: true }; - new MutationObserver(function () { return notify(); }).observe(el_1, config); - trigger = function () { el_1.textContent = "" + (toggle_1 ? toggle_1-- : toggle_1++); }; - } - callbacks.push(callback); - trigger(); -}; - -var queueResizeObserver = function (cb) { - queueMicroTask(function ResizeObserver() { - requestAnimationFrame(cb); - }); -}; - -var watching = 0; -var isWatching = function () { return !!watching; }; -var CATCH_PERIOD = 250; -var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true }; -var events = [ - 'resize', - 'load', - 'transitionend', - 'animationend', - 'animationstart', - 'animationiteration', - 'keyup', - 'keydown', - 'mouseup', - 'mousedown', - 'mouseover', - 'mouseout', - 'blur', - 'focus' -]; -var time = function (timeout) { - if (timeout === void 0) { timeout = 0; } - return Date.now() + timeout; -}; -var scheduled = false; -var Scheduler = (function () { - function Scheduler() { - var _this = this; - this.stopped = true; - this.listener = function () { return _this.schedule(); }; - } - Scheduler.prototype.run = function (timeout) { - var _this = this; - if (timeout === void 0) { timeout = CATCH_PERIOD; } - if (scheduled) { - return; - } - scheduled = true; - var until = time(timeout); - queueResizeObserver(function () { - var elementsHaveResized = false; - try { - elementsHaveResized = process$1(); - } - finally { - scheduled = false; - timeout = until - time(); - if (!isWatching()) { - return; - } - if (elementsHaveResized) { - _this.run(1000); - } - else if (timeout > 0) { - _this.run(timeout); - } - else { - _this.start(); - } - } - }); - }; - Scheduler.prototype.schedule = function () { - this.stop(); - this.run(); - }; - Scheduler.prototype.observe = function () { - var _this = this; - var cb = function () { return _this.observer && _this.observer.observe(document.body, observerConfig); }; - document.body ? cb() : global$1.addEventListener('DOMContentLoaded', cb); - }; - Scheduler.prototype.start = function () { - var _this = this; - if (this.stopped) { - this.stopped = false; - this.observer = new MutationObserver(this.listener); - this.observe(); - events.forEach(function (name) { return global$1.addEventListener(name, _this.listener, true); }); - } - }; - Scheduler.prototype.stop = function () { - var _this = this; - if (!this.stopped) { - this.observer && this.observer.disconnect(); - events.forEach(function (name) { return global$1.removeEventListener(name, _this.listener, true); }); - this.stopped = true; - } - }; - return Scheduler; -}()); -var scheduler = new Scheduler(); -var updateCount = function (n) { - !watching && n > 0 && scheduler.start(); - watching += n; - !watching && scheduler.stop(); -}; - -var skipNotifyOnElement = function (target) { - return !isSVG(target) - && !isReplacedElement(target) - && getComputedStyle(target).display === 'inline'; -}; -var ResizeObservation = (function () { - function ResizeObservation(target, observedBox) { - this.target = target; - this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX; - this.lastReportedSize = { - inlineSize: 0, - blockSize: 0 - }; - } - ResizeObservation.prototype.isActive = function () { - var size = calculateBoxSize(this.target, this.observedBox, true); - if (skipNotifyOnElement(this.target)) { - this.lastReportedSize = size; - } - if (this.lastReportedSize.inlineSize !== size.inlineSize - || this.lastReportedSize.blockSize !== size.blockSize) { - return true; - } - return false; - }; - return ResizeObservation; -}()); - -var ResizeObserverDetail = (function () { - function ResizeObserverDetail(resizeObserver, callback) { - this.activeTargets = []; - this.skippedTargets = []; - this.observationTargets = []; - this.observer = resizeObserver; - this.callback = callback; - } - return ResizeObserverDetail; -}()); - -var observerMap = new WeakMap(); -var getObservationIndex = function (observationTargets, target) { - for (var i = 0; i < observationTargets.length; i += 1) { - if (observationTargets[i].target === target) { - return i; - } - } - return -1; -}; -var ResizeObserverController = (function () { - function ResizeObserverController() { - } - ResizeObserverController.connect = function (resizeObserver, callback) { - var detail = new ResizeObserverDetail(resizeObserver, callback); - observerMap.set(resizeObserver, detail); - }; - ResizeObserverController.observe = function (resizeObserver, target, options) { - var detail = observerMap.get(resizeObserver); - var firstObservation = detail.observationTargets.length === 0; - if (getObservationIndex(detail.observationTargets, target) < 0) { - firstObservation && resizeObservers.push(detail); - detail.observationTargets.push(new ResizeObservation(target, options && options.box)); - updateCount(1); - scheduler.schedule(); - } - }; - ResizeObserverController.unobserve = function (resizeObserver, target) { - var detail = observerMap.get(resizeObserver); - var index = getObservationIndex(detail.observationTargets, target); - var lastObservation = detail.observationTargets.length === 1; - if (index >= 0) { - lastObservation && resizeObservers.splice(resizeObservers.indexOf(detail), 1); - detail.observationTargets.splice(index, 1); - updateCount(-1); - } - }; - ResizeObserverController.disconnect = function (resizeObserver) { - var _this = this; - var detail = observerMap.get(resizeObserver); - detail.observationTargets.slice().forEach(function (ot) { return _this.unobserve(resizeObserver, ot.target); }); - detail.activeTargets.splice(0, detail.activeTargets.length); - }; - return ResizeObserverController; -}()); - -var ResizeObserver = (function () { - function ResizeObserver(callback) { - if (arguments.length === 0) { - throw new TypeError("Failed to construct 'ResizeObserver': 1 argument required, but only 0 present."); - } - if (typeof callback !== 'function') { - throw new TypeError("Failed to construct 'ResizeObserver': The callback provided as parameter 1 is not a function."); - } - ResizeObserverController.connect(this, callback); - } - ResizeObserver.prototype.observe = function (target, options) { - if (arguments.length === 0) { - throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': 1 argument required, but only 0 present."); - } - if (!isElement(target)) { - throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element"); - } - ResizeObserverController.observe(this, target, options); - }; - ResizeObserver.prototype.unobserve = function (target) { - if (arguments.length === 0) { - throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': 1 argument required, but only 0 present."); - } - if (!isElement(target)) { - throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': parameter 1 is not of type 'Element"); - } - ResizeObserverController.unobserve(this, target); - }; - ResizeObserver.prototype.disconnect = function () { - ResizeObserverController.disconnect(this); - }; - ResizeObserver.toString = function () { - return 'function ResizeObserver () { [polyfill code] }'; - }; - return ResizeObserver; -}()); - -const v1$1 = new Vector3(); -const v2 = new Vector3(); -const v3 = new Vector3(); - -function defaultCalculatePosition(el, camera, size) { - const objectPos = v1$1.setFromMatrixPosition(el.matrixWorld); - objectPos.project(camera); - const widthHalf = size.width / 2; - const heightHalf = size.height / 2; - return [objectPos.x * widthHalf + widthHalf, -(objectPos.y * heightHalf) + heightHalf]; -} - -function isObjectBehindCamera(el, camera) { - const objectPos = v1$1.setFromMatrixPosition(el.matrixWorld); - const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); - const deltaCamObj = objectPos.sub(cameraPos); - const camDir = camera.getWorldDirection(v3); - return deltaCamObj.angleTo(camDir) > Math.PI / 2; -} - -function isObjectVisible(el, camera, raycaster, occlude) { - const elPos = v1$1.setFromMatrixPosition(el.matrixWorld); - const screenPos = elPos.clone(); - screenPos.project(camera); - raycaster.setFromCamera(screenPos, camera); - const intersects = raycaster.intersectObjects(occlude, true); - - if (intersects.length) { - const intersectionDistance = intersects[0].distance; - const pointDistance = elPos.distanceTo(raycaster.ray.origin); - return pointDistance < intersectionDistance; - } - - return true; -} - -function objectScale(el, camera) { - if (camera instanceof OrthographicCamera) { - return camera.zoom; - } else if (camera instanceof PerspectiveCamera) { - const objectPos = v1$1.setFromMatrixPosition(el.matrixWorld); - const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); - const vFOV = camera.fov * Math.PI / 180; - const dist = objectPos.distanceTo(cameraPos); - const scaleFOV = 2 * Math.tan(vFOV / 2) * dist; - return 1 / scaleFOV; - } else { - return 1; - } -} - -function objectZIndex(el, camera, zIndexRange) { - if (camera instanceof PerspectiveCamera || camera instanceof OrthographicCamera) { - const objectPos = v1$1.setFromMatrixPosition(el.matrixWorld); - const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); - const dist = objectPos.distanceTo(cameraPos); - const A = (zIndexRange[1] - zIndexRange[0]) / (camera.far - camera.near); - const B = zIndexRange[1] - A * camera.far; - return Math.round(A * dist + B); - } - - return undefined; -} - -const epsilon = value => Math.abs(value) < 1e-10 ? 0 : value; - -function getCSSMatrix(matrix, multipliers, prepend = '') { - let matrix3d = 'matrix3d('; - - for (let i = 0; i !== 16; i++) { - matrix3d += epsilon(multipliers[i] * matrix.elements[i]) + (i !== 15 ? ',' : ')'); - } - - return prepend + matrix3d; -} - -const getCameraCSSMatrix = (multipliers => { - return matrix => getCSSMatrix(matrix, multipliers); -})([1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1]); - -const getObjectCSSMatrix = (scaleMultipliers => { - return (matrix, factor) => getCSSMatrix(matrix, scaleMultipliers(factor), 'translate(-50%,-50%)'); -})(f => [1 / f, 1 / f, 1 / f, 1, -1 / f, -1 / f, -1 / f, -1, 1 / f, 1 / f, 1 / f, 1, 1, 1, 1, 1]); - -const Html = /*#__PURE__*/React.forwardRef(({ - children, - eps = 0.001, - style, - className, - prepend, - center, - fullscreen, - portal, - distanceFactor, - sprite = false, - transform = false, - occlude, - onOcclude, - zIndexRange = [16777271, 0], - calculatePosition = defaultCalculatePosition, - as = 'div', - wrapperClass, - pointerEvents = 'auto', - ...props -}, ref) => { - var _portal$current; - - const gl = useThree(({ - gl - }) => gl); - const camera = useThree(({ - camera - }) => camera); - const scene = useThree(({ - scene - }) => scene); - const size = useThree(({ - size - }) => size); - const raycaster = useThree(({ - raycaster - }) => raycaster); - const [el] = React.useState(() => document.createElement(as)); - const root = React.useRef(); - const group = React.useRef(null); - const oldZoom = React.useRef(0); - const oldPosition = React.useRef([0, 0]); - const transformOuterRef = React.useRef(null); - const transformInnerRef = React.useRef(null); - const target = (_portal$current = portal == null ? void 0 : portal.current) !== null && _portal$current !== void 0 ? _portal$current : gl.domElement.parentNode; - React.useLayoutEffect(() => { - if (group.current) { - const currentRoot = root.current = ReactDOM.createRoot(el); - scene.updateMatrixWorld(); - - if (transform) { - el.style.cssText = `position:absolute;top:0;left:0;pointer-events:none;overflow:hidden;`; - } else { - const vec = calculatePosition(group.current, camera, size); - el.style.cssText = `position:absolute;top:0;left:0;transform:translate3d(${vec[0]}px,${vec[1]}px,0);transform-origin:0 0;`; - } - - if (target) { - if (prepend) target.prepend(el);else target.appendChild(el); - } - - return () => { - if (target) target.removeChild(el); - currentRoot.unmount(); - }; - } - }, [target, transform]); - React.useLayoutEffect(() => { - if (wrapperClass) el.className = wrapperClass; - }, [wrapperClass]); - const styles = React.useMemo(() => { - if (transform) { - return { - position: 'absolute', - top: 0, - left: 0, - width: size.width, - height: size.height, - transformStyle: 'preserve-3d', - pointerEvents: 'none' - }; - } else { - return { - position: 'absolute', - transform: center ? 'translate3d(-50%,-50%,0)' : 'none', - ...(fullscreen && { - top: -size.height / 2, - left: -size.width / 2, - width: size.width, - height: size.height - }), - ...style - }; - } - }, [style, center, fullscreen, size, transform]); - const transformInnerStyles = React.useMemo(() => ({ - position: 'absolute', - pointerEvents - }), [pointerEvents]); - React.useLayoutEffect(() => { - if (transform) { - var _root$current; - - (_root$current = root.current) == null ? void 0 : _root$current.render( /*#__PURE__*/React.createElement("div", { - ref: transformOuterRef, - style: styles - }, /*#__PURE__*/React.createElement("div", { - ref: transformInnerRef, - style: transformInnerStyles - }, /*#__PURE__*/React.createElement("div", { - ref: ref, - className: className, - style: style, - children: children - })))); - } else { - var _root$current2; - - (_root$current2 = root.current) == null ? void 0 : _root$current2.render( /*#__PURE__*/React.createElement("div", { - ref: ref, - style: styles, - className: className, - children: children - })); - } - }); - const visible = React.useRef(true); - useFrame(() => { - if (group.current) { - camera.updateMatrixWorld(); - group.current.updateWorldMatrix(true, false); - const vec = transform ? oldPosition.current : calculatePosition(group.current, camera, size); - - if (transform || Math.abs(oldZoom.current - camera.zoom) > eps || Math.abs(oldPosition.current[0] - vec[0]) > eps || Math.abs(oldPosition.current[1] - vec[1]) > eps) { - const isBehindCamera = isObjectBehindCamera(group.current, camera); - let raytraceTarget = false; - - if (typeof occlude === 'boolean') { - if (occlude === true) { - raytraceTarget = [scene]; - } - } else if (Array.isArray(occlude)) { - raytraceTarget = occlude.map(item => item.current); - } - - const previouslyVisible = visible.current; - - if (raytraceTarget) { - const isvisible = isObjectVisible(group.current, camera, raycaster, raytraceTarget); - visible.current = isvisible && !isBehindCamera; - } else { - visible.current = !isBehindCamera; - } - - if (previouslyVisible !== visible.current) { - if (onOcclude) onOcclude(!visible.current);else el.style.display = visible.current ? 'block' : 'none'; - } - - el.style.zIndex = `${objectZIndex(group.current, camera, zIndexRange)}`; - - if (transform) { - const [widthHalf, heightHalf] = [size.width / 2, size.height / 2]; - const fov = camera.projectionMatrix.elements[5] * heightHalf; - const { - isOrthographicCamera, - top, - left, - bottom, - right - } = camera; - const cameraMatrix = getCameraCSSMatrix(camera.matrixWorldInverse); - const cameraTransform = isOrthographicCamera ? `scale(${fov})translate(${epsilon(-(right + left) / 2)}px,${epsilon((top + bottom) / 2)}px)` : `translateZ(${fov}px)`; - let matrix = group.current.matrixWorld; - - if (sprite) { - matrix = camera.matrixWorldInverse.clone().transpose().copyPosition(matrix).scale(group.current.scale); - matrix.elements[3] = matrix.elements[7] = matrix.elements[11] = 0; - matrix.elements[15] = 1; - } - - el.style.width = size.width + 'px'; - el.style.height = size.height + 'px'; - el.style.perspective = isOrthographicCamera ? '' : `${fov}px`; - - if (transformOuterRef.current && transformInnerRef.current) { - transformOuterRef.current.style.transform = `${cameraTransform}${cameraMatrix}translate(${widthHalf}px,${heightHalf}px)`; - transformInnerRef.current.style.transform = getObjectCSSMatrix(matrix, 1 / ((distanceFactor || 10) / 400)); - } - } else { - const scale = distanceFactor === undefined ? 1 : objectScale(group.current, camera) * distanceFactor; - el.style.transform = `translate3d(${vec[0]}px,${vec[1]}px,0) scale(${scale})`; - } - - oldPosition.current = vec; - oldZoom.current = camera.zoom; - } - } - }); - return /*#__PURE__*/React.createElement("group", _extends$3({}, props, { - ref: group - })); -}); - -function createStore$1(createState) { - let state; - const listeners = /* @__PURE__ */ new Set(); - const setState = (partial, replace) => { - const nextState = typeof partial === "function" ? partial(state) : partial; - if (nextState !== state) { - const previousState = state; - state = replace ? nextState : Object.assign({}, state, nextState); - listeners.forEach((listener) => listener(state, previousState)); - } - }; - const getState = () => state; - const subscribeWithSelector = (listener, selector = getState, equalityFn = Object.is) => { - console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware"); - let currentSlice = selector(state); - function listenerToAdd() { - const nextSlice = selector(state); - if (!equalityFn(currentSlice, nextSlice)) { - const previousSlice = currentSlice; - listener(currentSlice = nextSlice, previousSlice); - } - } - listeners.add(listenerToAdd); - return () => listeners.delete(listenerToAdd); - }; - const subscribe = (listener, selector, equalityFn) => { - if (selector || equalityFn) { - return subscribeWithSelector(listener, selector, equalityFn); - } - listeners.add(listener); - return () => listeners.delete(listener); - }; - const destroy = () => listeners.clear(); - const api = { setState, getState, subscribe, destroy }; - state = createState(setState, getState, api); - return api; -} - -const isSSR$1 = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); -const useIsomorphicLayoutEffect = isSSR$1 ? useEffect : useLayoutEffect$1; -function create$3(createState) { - const api = typeof createState === "function" ? createStore$1(createState) : createState; - const useStore = (selector = api.getState, equalityFn = Object.is) => { - const [, forceUpdate] = useReducer((c) => c + 1, 0); - const state = api.getState(); - const stateRef = useRef(state); - const selectorRef = useRef(selector); - const equalityFnRef = useRef(equalityFn); - const erroredRef = useRef(false); - const currentSliceRef = useRef(); - if (currentSliceRef.current === void 0) { - currentSliceRef.current = selector(state); - } - let newStateSlice; - let hasNewStateSlice = false; - if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) { - newStateSlice = selector(state); - hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice); - } - useIsomorphicLayoutEffect(() => { - if (hasNewStateSlice) { - currentSliceRef.current = newStateSlice; - } - stateRef.current = state; - selectorRef.current = selector; - equalityFnRef.current = equalityFn; - erroredRef.current = false; - }); - const stateBeforeSubscriptionRef = useRef(state); - useIsomorphicLayoutEffect(() => { - const listener = () => { - try { - const nextState = api.getState(); - const nextStateSlice = selectorRef.current(nextState); - if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) { - stateRef.current = nextState; - currentSliceRef.current = nextStateSlice; - forceUpdate(); - } - } catch (error) { - erroredRef.current = true; - forceUpdate(); - } - }; - const unsubscribe = api.subscribe(listener); - if (api.getState() !== stateBeforeSubscriptionRef.current) { - listener(); - } - return unsubscribe; - }, []); - const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current; - useDebugValue(sliceToReturn); - return sliceToReturn; - }; - Object.assign(useStore, api); - useStore[Symbol.iterator] = function() { - console.warn("[useStore, api] = create() is deprecated and will be removed in v4"); - const items = [useStore, api]; - return { - next() { - const done = items.length <= 0; - return { value: items.shift(), done }; - } - }; - }; - return useStore; -} - -let saveLastTotalLoaded = 0; -create$3(set => { - DefaultLoadingManager.onStart = (item, loaded, total) => { - set({ - active: true, - item, - loaded, - total, - progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 - }); - }; - - DefaultLoadingManager.onLoad = () => { - set({ - active: false - }); - }; - - DefaultLoadingManager.onError = item => set(state => ({ - errors: [...state.errors, item] - })); - - DefaultLoadingManager.onProgress = (item, loaded, total) => { - if (loaded === total) { - saveLastTotalLoaded = total; - } - - set({ - active: true, - item, - loaded, - total, - progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 || 100 - }); - }; - - return { - errors: [], - active: false, - progress: 0, - item: '', - loaded: 0, - total: 0 - }; -}); - -function mergeRefs(refs) { - return function (value) { - refs.forEach(function (ref) { - if (typeof ref === "function") { - ref(value); - } else if (ref != null) { - ref.current = value; - } - }); - }; -} - -let updateQueue = makeQueue(); -const raf = fn => schedule(fn, updateQueue); -let writeQueue = makeQueue(); - -raf.write = fn => schedule(fn, writeQueue); - -let onStartQueue = makeQueue(); - -raf.onStart = fn => schedule(fn, onStartQueue); - -let onFrameQueue = makeQueue(); - -raf.onFrame = fn => schedule(fn, onFrameQueue); - -let onFinishQueue = makeQueue(); - -raf.onFinish = fn => schedule(fn, onFinishQueue); - -let timeouts = []; - -raf.setTimeout = (handler, ms) => { - let time = raf.now() + ms; - - let cancel = () => { - let i = timeouts.findIndex(t => t.cancel == cancel); - if (~i) timeouts.splice(i, 1); - pendingCount -= ~i ? 1 : 0; - }; - - let timeout = { - time, - handler, - cancel - }; - timeouts.splice(findTimeout(time), 0, timeout); - pendingCount += 1; - start(); - return timeout; -}; - -let findTimeout = time => ~(~timeouts.findIndex(t => t.time > time) || ~timeouts.length); - -raf.cancel = fn => { - onStartQueue.delete(fn); - onFrameQueue.delete(fn); - updateQueue.delete(fn); - writeQueue.delete(fn); - onFinishQueue.delete(fn); -}; - -raf.sync = fn => { - sync = true; - raf.batchedUpdates(fn); - sync = false; -}; - -raf.throttle = fn => { - let lastArgs; - - function queuedFn() { - try { - fn(...lastArgs); - } finally { - lastArgs = null; - } - } - - function throttled(...args) { - lastArgs = args; - raf.onStart(queuedFn); - } - - throttled.handler = fn; - - throttled.cancel = () => { - onStartQueue.delete(queuedFn); - lastArgs = null; - }; - - return throttled; -}; - -let nativeRaf = typeof window != 'undefined' ? window.requestAnimationFrame : () => {}; - -raf.use = impl => nativeRaf = impl; - -raf.now = typeof performance != 'undefined' ? () => performance.now() : Date.now; - -raf.batchedUpdates = fn => fn(); - -raf.catch = console.error; -raf.frameLoop = 'always'; - -raf.advance = () => { - if (raf.frameLoop !== 'demand') { - console.warn('Cannot call the manual advancement of rafz whilst frameLoop is not set as demand'); - } else { - update(); - } -}; - -let ts = -1; -let pendingCount = 0; -let sync = false; - -function schedule(fn, queue) { - if (sync) { - queue.delete(fn); - fn(0); - } else { - queue.add(fn); - start(); - } -} - -function start() { - if (ts < 0) { - ts = 0; - - if (raf.frameLoop !== 'demand') { - nativeRaf(loop); - } - } -} - -function stop() { - ts = -1; -} - -function loop() { - if (~ts) { - nativeRaf(loop); - raf.batchedUpdates(update); - } -} - -function update() { - let prevTs = ts; - ts = raf.now(); - let count = findTimeout(ts); - - if (count) { - eachSafely(timeouts.splice(0, count), t => t.handler()); - pendingCount -= count; - } - - onStartQueue.flush(); - updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667); - onFrameQueue.flush(); - writeQueue.flush(); - onFinishQueue.flush(); - - if (!pendingCount) { - stop(); - } -} - -function makeQueue() { - let next = new Set(); - let current = next; - return { - add(fn) { - pendingCount += current == next && !next.has(fn) ? 1 : 0; - next.add(fn); - }, - - delete(fn) { - pendingCount -= current == next && next.has(fn) ? 1 : 0; - return next.delete(fn); - }, - - flush(arg) { - if (current.size) { - next = new Set(); - pendingCount -= current.size; - eachSafely(current, fn => fn(arg) && next.add(fn)); - pendingCount += next.size; - current = next; - } - } - - }; -} - -function eachSafely(values, each) { - values.forEach(value => { - try { - each(value); - } catch (e) { - raf.catch(e); - } - }); -} - -function noop$2() {} -const defineHidden = (obj, key, value) => Object.defineProperty(obj, key, { - value, - writable: true, - configurable: true -}); -const is = { - arr: Array.isArray, - obj: a => !!a && a.constructor.name === 'Object', - fun: a => typeof a === 'function', - str: a => typeof a === 'string', - num: a => typeof a === 'number', - und: a => a === undefined -}; -function isEqual(a, b) { - if (is.arr(a)) { - if (!is.arr(b) || a.length !== b.length) return false; - - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return false; - } - - return true; - } - - return a === b; -} -const each = (obj, fn) => obj.forEach(fn); -function eachProp(obj, fn, ctx) { - if (is.arr(obj)) { - for (let i = 0; i < obj.length; i++) { - fn.call(ctx, obj[i], `${i}`); - } - - return; - } - - for (const key in obj) { - if (obj.hasOwnProperty(key)) { - fn.call(ctx, obj[key], key); - } - } -} -const toArray = a => is.und(a) ? [] : is.arr(a) ? a : [a]; -const isSSR = () => typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); - -let createStringInterpolator$1; -let to; -let colors$1 = null; -let skipAnimation = false; -let willAdvance = noop$2; -const assign$4 = globals => { - if (globals.to) to = globals.to; - if (globals.now) raf.now = globals.now; - if (globals.colors !== undefined) colors$1 = globals.colors; - if (globals.skipAnimation != null) skipAnimation = globals.skipAnimation; - if (globals.createStringInterpolator) createStringInterpolator$1 = globals.createStringInterpolator; - if (globals.requestAnimationFrame) raf.use(globals.requestAnimationFrame); - if (globals.batchedUpdates) raf.batchedUpdates = globals.batchedUpdates; - if (globals.willAdvance) willAdvance = globals.willAdvance; - if (globals.frameLoop) raf.frameLoop = globals.frameLoop; -}; - -var globals = /*#__PURE__*/Object.freeze({ - __proto__: null, - get createStringInterpolator () { return createStringInterpolator$1; }, - get to () { return to; }, - get colors () { return colors$1; }, - get skipAnimation () { return skipAnimation; }, - get willAdvance () { return willAdvance; }, - assign: assign$4 -}); - -const startQueue = new Set(); -let currentFrame = []; -let prevFrame = []; -let priority = 0; -const frameLoop = { - get idle() { - return !startQueue.size && !currentFrame.length; - }, - - start(animation) { - if (priority > animation.priority) { - startQueue.add(animation); - raf.onStart(flushStartQueue); - } else { - startSafely(animation); - raf(advance); - } - }, - - advance, - - sort(animation) { - if (priority) { - raf.onFrame(() => frameLoop.sort(animation)); - } else { - const prevIndex = currentFrame.indexOf(animation); - - if (~prevIndex) { - currentFrame.splice(prevIndex, 1); - startUnsafely(animation); - } - } - }, - - clear() { - currentFrame = []; - startQueue.clear(); - } - -}; - -function flushStartQueue() { - startQueue.forEach(startSafely); - startQueue.clear(); - raf(advance); -} - -function startSafely(animation) { - if (!currentFrame.includes(animation)) startUnsafely(animation); -} - -function startUnsafely(animation) { - currentFrame.splice(findIndex$2(currentFrame, other => other.priority > animation.priority), 0, animation); -} - -function advance(dt) { - const nextFrame = prevFrame; - - for (let i = 0; i < currentFrame.length; i++) { - const animation = currentFrame[i]; - priority = animation.priority; - - if (!animation.idle) { - willAdvance(animation); - animation.advance(dt); - - if (!animation.idle) { - nextFrame.push(animation); - } - } - } - - priority = 0; - prevFrame = currentFrame; - prevFrame.length = 0; - currentFrame = nextFrame; - return currentFrame.length > 0; -} - -function findIndex$2(arr, test) { - const index = arr.findIndex(test); - return index < 0 ? arr.length : index; -} - -const colors = { - transparent: 0x00000000, - aliceblue: 0xf0f8ffff, - antiquewhite: 0xfaebd7ff, - aqua: 0x00ffffff, - aquamarine: 0x7fffd4ff, - azure: 0xf0ffffff, - beige: 0xf5f5dcff, - bisque: 0xffe4c4ff, - black: 0x000000ff, - blanchedalmond: 0xffebcdff, - blue: 0x0000ffff, - blueviolet: 0x8a2be2ff, - brown: 0xa52a2aff, - burlywood: 0xdeb887ff, - burntsienna: 0xea7e5dff, - cadetblue: 0x5f9ea0ff, - chartreuse: 0x7fff00ff, - chocolate: 0xd2691eff, - coral: 0xff7f50ff, - cornflowerblue: 0x6495edff, - cornsilk: 0xfff8dcff, - crimson: 0xdc143cff, - cyan: 0x00ffffff, - darkblue: 0x00008bff, - darkcyan: 0x008b8bff, - darkgoldenrod: 0xb8860bff, - darkgray: 0xa9a9a9ff, - darkgreen: 0x006400ff, - darkgrey: 0xa9a9a9ff, - darkkhaki: 0xbdb76bff, - darkmagenta: 0x8b008bff, - darkolivegreen: 0x556b2fff, - darkorange: 0xff8c00ff, - darkorchid: 0x9932ccff, - darkred: 0x8b0000ff, - darksalmon: 0xe9967aff, - darkseagreen: 0x8fbc8fff, - darkslateblue: 0x483d8bff, - darkslategray: 0x2f4f4fff, - darkslategrey: 0x2f4f4fff, - darkturquoise: 0x00ced1ff, - darkviolet: 0x9400d3ff, - deeppink: 0xff1493ff, - deepskyblue: 0x00bfffff, - dimgray: 0x696969ff, - dimgrey: 0x696969ff, - dodgerblue: 0x1e90ffff, - firebrick: 0xb22222ff, - floralwhite: 0xfffaf0ff, - forestgreen: 0x228b22ff, - fuchsia: 0xff00ffff, - gainsboro: 0xdcdcdcff, - ghostwhite: 0xf8f8ffff, - gold: 0xffd700ff, - goldenrod: 0xdaa520ff, - gray: 0x808080ff, - green: 0x008000ff, - greenyellow: 0xadff2fff, - grey: 0x808080ff, - honeydew: 0xf0fff0ff, - hotpink: 0xff69b4ff, - indianred: 0xcd5c5cff, - indigo: 0x4b0082ff, - ivory: 0xfffff0ff, - khaki: 0xf0e68cff, - lavender: 0xe6e6faff, - lavenderblush: 0xfff0f5ff, - lawngreen: 0x7cfc00ff, - lemonchiffon: 0xfffacdff, - lightblue: 0xadd8e6ff, - lightcoral: 0xf08080ff, - lightcyan: 0xe0ffffff, - lightgoldenrodyellow: 0xfafad2ff, - lightgray: 0xd3d3d3ff, - lightgreen: 0x90ee90ff, - lightgrey: 0xd3d3d3ff, - lightpink: 0xffb6c1ff, - lightsalmon: 0xffa07aff, - lightseagreen: 0x20b2aaff, - lightskyblue: 0x87cefaff, - lightslategray: 0x778899ff, - lightslategrey: 0x778899ff, - lightsteelblue: 0xb0c4deff, - lightyellow: 0xffffe0ff, - lime: 0x00ff00ff, - limegreen: 0x32cd32ff, - linen: 0xfaf0e6ff, - magenta: 0xff00ffff, - maroon: 0x800000ff, - mediumaquamarine: 0x66cdaaff, - mediumblue: 0x0000cdff, - mediumorchid: 0xba55d3ff, - mediumpurple: 0x9370dbff, - mediumseagreen: 0x3cb371ff, - mediumslateblue: 0x7b68eeff, - mediumspringgreen: 0x00fa9aff, - mediumturquoise: 0x48d1ccff, - mediumvioletred: 0xc71585ff, - midnightblue: 0x191970ff, - mintcream: 0xf5fffaff, - mistyrose: 0xffe4e1ff, - moccasin: 0xffe4b5ff, - navajowhite: 0xffdeadff, - navy: 0x000080ff, - oldlace: 0xfdf5e6ff, - olive: 0x808000ff, - olivedrab: 0x6b8e23ff, - orange: 0xffa500ff, - orangered: 0xff4500ff, - orchid: 0xda70d6ff, - palegoldenrod: 0xeee8aaff, - palegreen: 0x98fb98ff, - paleturquoise: 0xafeeeeff, - palevioletred: 0xdb7093ff, - papayawhip: 0xffefd5ff, - peachpuff: 0xffdab9ff, - peru: 0xcd853fff, - pink: 0xffc0cbff, - plum: 0xdda0ddff, - powderblue: 0xb0e0e6ff, - purple: 0x800080ff, - rebeccapurple: 0x663399ff, - red: 0xff0000ff, - rosybrown: 0xbc8f8fff, - royalblue: 0x4169e1ff, - saddlebrown: 0x8b4513ff, - salmon: 0xfa8072ff, - sandybrown: 0xf4a460ff, - seagreen: 0x2e8b57ff, - seashell: 0xfff5eeff, - sienna: 0xa0522dff, - silver: 0xc0c0c0ff, - skyblue: 0x87ceebff, - slateblue: 0x6a5acdff, - slategray: 0x708090ff, - slategrey: 0x708090ff, - snow: 0xfffafaff, - springgreen: 0x00ff7fff, - steelblue: 0x4682b4ff, - tan: 0xd2b48cff, - teal: 0x008080ff, - thistle: 0xd8bfd8ff, - tomato: 0xff6347ff, - turquoise: 0x40e0d0ff, - violet: 0xee82eeff, - wheat: 0xf5deb3ff, - white: 0xffffffff, - whitesmoke: 0xf5f5f5ff, - yellow: 0xffff00ff, - yellowgreen: 0x9acd32ff -}; - -const NUMBER = '[-+]?\\d*\\.?\\d+'; -const PERCENTAGE = NUMBER + '%'; - -function call$1(...parts) { - return '\\(\\s*(' + parts.join(')\\s*,\\s*(') + ')\\s*\\)'; -} - -const rgb = new RegExp('rgb' + call$1(NUMBER, NUMBER, NUMBER)); -const rgba = new RegExp('rgba' + call$1(NUMBER, NUMBER, NUMBER, NUMBER)); -const hsl = new RegExp('hsl' + call$1(NUMBER, PERCENTAGE, PERCENTAGE)); -const hsla = new RegExp('hsla' + call$1(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)); -const hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; -const hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; -const hex6 = /^#([0-9a-fA-F]{6})$/; -const hex8 = /^#([0-9a-fA-F]{8})$/; - -function normalizeColor(color) { - let match; - - if (typeof color === 'number') { - return color >>> 0 === color && color >= 0 && color <= 0xffffffff ? color : null; - } - - if (match = hex6.exec(color)) return parseInt(match[1] + 'ff', 16) >>> 0; - - if (colors$1 && colors$1[color] !== undefined) { - return colors$1[color]; - } - - if (match = rgb.exec(color)) { - return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | 0x000000ff) >>> 0; - } - - if (match = rgba.exec(color)) { - return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | parse1(match[4])) >>> 0; - } - - if (match = hex3.exec(color)) { - return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + 'ff', 16) >>> 0; - } - - if (match = hex8.exec(color)) return parseInt(match[1], 16) >>> 0; - - if (match = hex4.exec(color)) { - return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + match[4] + match[4], 16) >>> 0; - } - - if (match = hsl.exec(color)) { - return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | 0x000000ff) >>> 0; - } - - if (match = hsla.exec(color)) { - return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | parse1(match[4])) >>> 0; - } - - return null; -} - -function hue2rgb(p, q, t) { - if (t < 0) t += 1; - if (t > 1) t -= 1; - if (t < 1 / 6) return p + (q - p) * 6 * t; - if (t < 1 / 2) return q; - if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; - return p; -} - -function hslToRgb(h, s, l) { - const q = l < 0.5 ? l * (1 + s) : l + s - l * s; - const p = 2 * l - q; - const r = hue2rgb(p, q, h + 1 / 3); - const g = hue2rgb(p, q, h); - const b = hue2rgb(p, q, h - 1 / 3); - return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8; -} - -function parse255(str) { - const int = parseInt(str, 10); - if (int < 0) return 0; - if (int > 255) return 255; - return int; -} - -function parse360(str) { - const int = parseFloat(str); - return (int % 360 + 360) % 360 / 360; -} - -function parse1(str) { - const num = parseFloat(str); - if (num < 0) return 0; - if (num > 1) return 255; - return Math.round(num * 255); -} - -function parsePercentage(str) { - const int = parseFloat(str); - if (int < 0) return 0; - if (int > 100) return 1; - return int / 100; -} - -function colorToRgba(input) { - let int32Color = normalizeColor(input); - if (int32Color === null) return input; - int32Color = int32Color || 0; - let r = (int32Color & 0xff000000) >>> 24; - let g = (int32Color & 0x00ff0000) >>> 16; - let b = (int32Color & 0x0000ff00) >>> 8; - let a = (int32Color & 0x000000ff) / 255; - return `rgba(${r}, ${g}, ${b}, ${a})`; -} - -const createInterpolator = (range, output, extrapolate) => { - if (is.fun(range)) { - return range; - } - - if (is.arr(range)) { - return createInterpolator({ - range, - output: output, - extrapolate - }); - } - - if (is.str(range.output[0])) { - return createStringInterpolator$1(range); - } - - const config = range; - const outputRange = config.output; - const inputRange = config.range || [0, 1]; - const extrapolateLeft = config.extrapolateLeft || config.extrapolate || 'extend'; - const extrapolateRight = config.extrapolateRight || config.extrapolate || 'extend'; - - const easing = config.easing || (t => t); - - return input => { - const range = findRange(input, inputRange); - return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight, config.map); - }; -}; - -function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) { - let result = map ? map(input) : input; - - if (result < inputMin) { - if (extrapolateLeft === 'identity') return result;else if (extrapolateLeft === 'clamp') result = inputMin; - } - - if (result > inputMax) { - if (extrapolateRight === 'identity') return result;else if (extrapolateRight === 'clamp') result = inputMax; - } - - if (outputMin === outputMax) return outputMin; - if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax; - if (inputMin === -Infinity) result = -result;else if (inputMax === Infinity) result = result - inputMin;else result = (result - inputMin) / (inputMax - inputMin); - result = easing(result); - if (outputMin === -Infinity) result = -result;else if (outputMax === Infinity) result = result + outputMin;else result = result * (outputMax - outputMin) + outputMin; - return result; -} - -function findRange(input, inputRange) { - for (var i = 1; i < inputRange.length - 1; ++i) if (inputRange[i] >= input) break; - - return i - 1; -} - -function _extends$2() { - _extends$2 = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends$2.apply(this, arguments); -} - -const $get = Symbol.for('FluidValue.get'); -const $observers = Symbol.for('FluidValue.observers'); - -const hasFluidValue = arg => Boolean(arg && arg[$get]); - -const getFluidValue = arg => arg && arg[$get] ? arg[$get]() : arg; - -function callFluidObserver(observer, event) { - if (observer.eventObserved) { - observer.eventObserved(event); - } else { - observer(event); - } -} - -function callFluidObservers(target, event) { - let observers = target[$observers]; - - if (observers) { - observers.forEach(observer => { - callFluidObserver(observer, event); - }); - } -} - -class FluidValue { - constructor(get) { - this[$get] = void 0; - this[$observers] = void 0; - - if (!get && !(get = this.get)) { - throw Error('Unknown getter'); - } - - setFluidGetter(this, get); - } - -} - -const setFluidGetter = (target, get) => setHidden(target, $get, get); - -function addFluidObserver(target, observer) { - if (target[$get]) { - let observers = target[$observers]; - - if (!observers) { - setHidden(target, $observers, observers = new Set()); - } - - if (!observers.has(observer)) { - observers.add(observer); - - if (target.observerAdded) { - target.observerAdded(observers.size, observer); - } - } - } - - return observer; -} - -function removeFluidObserver(target, observer) { - let observers = target[$observers]; - - if (observers && observers.has(observer)) { - const count = observers.size - 1; - - if (count) { - observers.delete(observer); - } else { - target[$observers] = null; - } - - if (target.observerRemoved) { - target.observerRemoved(count, observer); - } - } -} - -const setHidden = (target, key, value) => Object.defineProperty(target, key, { - value, - writable: true, - configurable: true -}); - -const numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; -const colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi; -const unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, 'i'); -const rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi; -const cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/; - -const variableToRgba = input => { - const [token, fallback] = parseCSSVariable(input); - - if (!token || isSSR()) { - return input; - } - - const value = window.getComputedStyle(document.documentElement).getPropertyValue(token); - - if (value) { - return value.trim(); - } else if (fallback && fallback.startsWith('--')) { - const _value = window.getComputedStyle(document.documentElement).getPropertyValue(fallback); - - if (_value) { - return _value; - } else { - return input; - } - } else if (fallback && cssVariableRegex.test(fallback)) { - return variableToRgba(fallback); - } else if (fallback) { - return fallback; - } - - return input; -}; - -const parseCSSVariable = current => { - const match = cssVariableRegex.exec(current); - if (!match) return [,]; - const [, token, fallback] = match; - return [token, fallback]; -}; - -let namedColorRegex; - -const rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`; - -const createStringInterpolator = config => { - if (!namedColorRegex) namedColorRegex = colors$1 ? new RegExp(`(${Object.keys(colors$1).join('|')})(?!\\w)`, 'g') : /^\b$/; - const output = config.output.map(value => { - return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba); - }); - const keyframes = output.map(value => value.match(numberRegex).map(Number)); - const outputRanges = keyframes[0].map((_, i) => keyframes.map(values => { - if (!(i in values)) { - throw Error('The arity of each "output" value must be equal'); - } - - return values[i]; - })); - const interpolators = outputRanges.map(output => createInterpolator(_extends$2({}, config, { - output - }))); - return input => { - var _output$find; - - const missingUnit = !unitRegex.test(output[0]) && ((_output$find = output.find(value => unitRegex.test(value))) == null ? void 0 : _output$find.replace(numberRegex, '')); - let i = 0; - return output[0].replace(numberRegex, () => `${interpolators[i++](input)}${missingUnit || ''}`).replace(rgbaRegex, rgbaRound); - }; -}; - -const prefix = 'react-spring: '; - -const once = fn => { - const func = fn; - let called = false; - - if (typeof func != 'function') { - throw new TypeError(`${prefix}once requires a function parameter`); - } - - return (...args) => { - if (!called) { - func(...args); - called = true; - } - }; -}; - -const warnInterpolate = once(console.warn); -function deprecateInterpolate() { - warnInterpolate(`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`); -} -once(console.warn); - -function isAnimatedString(value) { - return is.str(value) && (value[0] == '#' || /\d/.test(value) || !isSSR() && cssVariableRegex.test(value) || value in (colors$1 || {})); -} - -const useLayoutEffect = typeof window !== 'undefined' && window.document && window.document.createElement ? React.useLayoutEffect : React.useEffect; - -const useIsMounted = () => { - const isMounted = useRef(false); - useLayoutEffect(() => { - isMounted.current = true; - return () => { - isMounted.current = false; - }; - }, []); - return isMounted; -}; - -function useForceUpdate() { - const update = useState()[1]; - const isMounted = useIsMounted(); - return () => { - if (isMounted.current) { - update(Math.random()); - } - }; -} - -function useMemoOne(getResult, inputs) { - const [initial] = useState(() => ({ - inputs, - result: getResult() - })); - const committed = useRef(); - const prevCache = committed.current; - let cache = prevCache; - - if (cache) { - const useCache = Boolean(inputs && cache.inputs && areInputsEqual(inputs, cache.inputs)); - - if (!useCache) { - cache = { - inputs, - result: getResult() - }; - } - } else { - cache = initial; - } - - useEffect(() => { - committed.current = cache; - - if (prevCache == initial) { - initial.inputs = initial.result = undefined; - } - }, [cache]); - return cache.result; -} - -function areInputsEqual(next, prev) { - if (next.length !== prev.length) { - return false; - } - - for (let i = 0; i < next.length; i++) { - if (next[i] !== prev[i]) { - return false; - } - } - - return true; -} - -const useOnce = effect => useEffect(effect, emptyDeps); -const emptyDeps = []; - -const $node = Symbol.for('Animated:node'); -const isAnimated = value => !!value && value[$node] === value; -const getAnimated = owner => owner && owner[$node]; -const setAnimated = (owner, node) => defineHidden(owner, $node, node); -const getPayload = owner => owner && owner[$node] && owner[$node].getPayload(); -class Animated { - constructor() { - this.payload = void 0; - setAnimated(this, this); - } - - getPayload() { - return this.payload || []; - } - -} - -class AnimatedValue extends Animated { - constructor(_value) { - super(); - this.done = true; - this.elapsedTime = void 0; - this.lastPosition = void 0; - this.lastVelocity = void 0; - this.v0 = void 0; - this.durationProgress = 0; - this._value = _value; - - if (is.num(this._value)) { - this.lastPosition = this._value; - } - } - - static create(value) { - return new AnimatedValue(value); - } - - getPayload() { - return [this]; - } - - getValue() { - return this._value; - } - - setValue(value, step) { - if (is.num(value)) { - this.lastPosition = value; - - if (step) { - value = Math.round(value / step) * step; - - if (this.done) { - this.lastPosition = value; - } - } - } - - if (this._value === value) { - return false; - } - - this._value = value; - return true; - } - - reset() { - const { - done - } = this; - this.done = false; - - if (is.num(this._value)) { - this.elapsedTime = 0; - this.durationProgress = 0; - this.lastPosition = this._value; - if (done) this.lastVelocity = null; - this.v0 = null; - } - } - -} - -class AnimatedString extends AnimatedValue { - constructor(value) { - super(0); - this._string = null; - this._toString = void 0; - this._toString = createInterpolator({ - output: [value, value] - }); - } - - static create(value) { - return new AnimatedString(value); - } - - getValue() { - let value = this._string; - return value == null ? this._string = this._toString(this._value) : value; - } - - setValue(value) { - if (is.str(value)) { - if (value == this._string) { - return false; - } - - this._string = value; - this._value = 1; - } else if (super.setValue(value)) { - this._string = null; - } else { - return false; - } - - return true; - } - - reset(goal) { - if (goal) { - this._toString = createInterpolator({ - output: [this.getValue(), goal] - }); - } - - this._value = 0; - super.reset(); - } - -} - -const TreeContext = { - dependencies: null -}; - -class AnimatedObject extends Animated { - constructor(source) { - super(); - this.source = source; - this.setValue(source); - } - - getValue(animated) { - const values = {}; - eachProp(this.source, (source, key) => { - if (isAnimated(source)) { - values[key] = source.getValue(animated); - } else if (hasFluidValue(source)) { - values[key] = getFluidValue(source); - } else if (!animated) { - values[key] = source; - } - }); - return values; - } - - setValue(source) { - this.source = source; - this.payload = this._makePayload(source); - } - - reset() { - if (this.payload) { - each(this.payload, node => node.reset()); - } - } - - _makePayload(source) { - if (source) { - const payload = new Set(); - eachProp(source, this._addToPayload, payload); - return Array.from(payload); - } - } - - _addToPayload(source) { - if (TreeContext.dependencies && hasFluidValue(source)) { - TreeContext.dependencies.add(source); - } - - const payload = getPayload(source); - - if (payload) { - each(payload, node => this.add(node)); - } - } - -} - -class AnimatedArray extends AnimatedObject { - constructor(source) { - super(source); - } - - static create(source) { - return new AnimatedArray(source); - } - - getValue() { - return this.source.map(node => node.getValue()); - } - - setValue(source) { - const payload = this.getPayload(); - - if (source.length == payload.length) { - return payload.map((node, i) => node.setValue(source[i])).some(Boolean); - } - - super.setValue(source.map(makeAnimated)); - return true; - } - -} - -function makeAnimated(value) { - const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue; - return nodeType.create(value); -} - -function getAnimatedType(value) { - const parentNode = getAnimated(value); - return parentNode ? parentNode.constructor : is.arr(value) ? AnimatedArray : isAnimatedString(value) ? AnimatedString : AnimatedValue; -} - -function _extends$1() { - _extends$1 = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends$1.apply(this, arguments); -} - -const withAnimated = (Component, host) => { - const hasInstance = !is.fun(Component) || Component.prototype && Component.prototype.isReactComponent; - return forwardRef((givenProps, givenRef) => { - const instanceRef = useRef(null); - const ref = hasInstance && useCallback(value => { - instanceRef.current = updateRef(givenRef, value); - }, [givenRef]); - const [props, deps] = getAnimatedState(givenProps, host); - const forceUpdate = useForceUpdate(); - - const callback = () => { - const instance = instanceRef.current; - - if (hasInstance && !instance) { - return; - } - - const didUpdate = instance ? host.applyAnimatedValues(instance, props.getValue(true)) : false; - - if (didUpdate === false) { - forceUpdate(); - } - }; - - const observer = new PropsObserver(callback, deps); - const observerRef = useRef(); - useLayoutEffect(() => { - observerRef.current = observer; - each(deps, dep => addFluidObserver(dep, observer)); - return () => { - if (observerRef.current) { - each(observerRef.current.deps, dep => removeFluidObserver(dep, observerRef.current)); - raf.cancel(observerRef.current.update); - } - }; - }); - useEffect(callback, []); - useOnce(() => () => { - const observer = observerRef.current; - each(observer.deps, dep => removeFluidObserver(dep, observer)); - }); - const usedProps = host.getComponentProps(props.getValue()); - return React.createElement(Component, _extends$1({}, usedProps, { - ref: ref - })); - }); -}; - -class PropsObserver { - constructor(update, deps) { - this.update = update; - this.deps = deps; - } - - eventObserved(event) { - if (event.type == 'change') { - raf.write(this.update); - } - } - -} - -function getAnimatedState(props, host) { - const dependencies = new Set(); - TreeContext.dependencies = dependencies; - if (props.style) props = _extends$1({}, props, { - style: host.createAnimatedStyle(props.style) - }); - props = new AnimatedObject(props); - TreeContext.dependencies = null; - return [props, dependencies]; -} - -function updateRef(ref, value) { - if (ref) { - if (is.fun(ref)) ref(value);else ref.current = value; - } - - return value; -} - -const cacheKey = Symbol.for('AnimatedComponent'); -const createHost = (components, { - applyAnimatedValues: _applyAnimatedValues = () => false, - createAnimatedStyle: _createAnimatedStyle = style => new AnimatedObject(style), - getComponentProps: _getComponentProps = props => props -} = {}) => { - const hostConfig = { - applyAnimatedValues: _applyAnimatedValues, - createAnimatedStyle: _createAnimatedStyle, - getComponentProps: _getComponentProps - }; - - const animated = Component => { - const displayName = getDisplayName(Component) || 'Anonymous'; - - if (is.str(Component)) { - Component = animated[Component] || (animated[Component] = withAnimated(Component, hostConfig)); - } else { - Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig)); - } - - Component.displayName = `Animated(${displayName})`; - return Component; - }; - - eachProp(components, (Component, key) => { - if (is.arr(components)) { - key = getDisplayName(Component); - } - - animated[key] = animated(Component); - }); - return { - animated - }; -}; - -const getDisplayName = arg => is.str(arg) ? arg : arg && is.str(arg.displayName) ? arg.displayName : is.fun(arg) && arg.name || null; - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -const config = { - default: { - tension: 170, - friction: 26 - }, - gentle: { - tension: 120, - friction: 14 - }, - wobbly: { - tension: 180, - friction: 12 - }, - stiff: { - tension: 210, - friction: 20 - }, - slow: { - tension: 280, - friction: 60 - }, - molasses: { - tension: 280, - friction: 120 - } -}; -const c1 = 1.70158; -const c2 = c1 * 1.525; -const c3 = c1 + 1; -const c4 = 2 * Math.PI / 3; -const c5 = 2 * Math.PI / 4.5; - -const bounceOut = x => { - const n1 = 7.5625; - const d1 = 2.75; - - if (x < 1 / d1) { - return n1 * x * x; - } else if (x < 2 / d1) { - return n1 * (x -= 1.5 / d1) * x + 0.75; - } else if (x < 2.5 / d1) { - return n1 * (x -= 2.25 / d1) * x + 0.9375; - } else { - return n1 * (x -= 2.625 / d1) * x + 0.984375; - } -}; - -const easings = { - linear: x => x, - easeInQuad: x => x * x, - easeOutQuad: x => 1 - (1 - x) * (1 - x), - easeInOutQuad: x => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2, - easeInCubic: x => x * x * x, - easeOutCubic: x => 1 - Math.pow(1 - x, 3), - easeInOutCubic: x => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2, - easeInQuart: x => x * x * x * x, - easeOutQuart: x => 1 - Math.pow(1 - x, 4), - easeInOutQuart: x => x < 0.5 ? 8 * x * x * x * x : 1 - Math.pow(-2 * x + 2, 4) / 2, - easeInQuint: x => x * x * x * x * x, - easeOutQuint: x => 1 - Math.pow(1 - x, 5), - easeInOutQuint: x => x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2, - easeInSine: x => 1 - Math.cos(x * Math.PI / 2), - easeOutSine: x => Math.sin(x * Math.PI / 2), - easeInOutSine: x => -(Math.cos(Math.PI * x) - 1) / 2, - easeInExpo: x => x === 0 ? 0 : Math.pow(2, 10 * x - 10), - easeOutExpo: x => x === 1 ? 1 : 1 - Math.pow(2, -10 * x), - easeInOutExpo: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2, - easeInCirc: x => 1 - Math.sqrt(1 - Math.pow(x, 2)), - easeOutCirc: x => Math.sqrt(1 - Math.pow(x - 1, 2)), - easeInOutCirc: x => x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2, - easeInBack: x => c3 * x * x * x - c1 * x * x, - easeOutBack: x => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2), - easeInOutBack: x => x < 0.5 ? Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2, - easeInElastic: x => x === 0 ? 0 : x === 1 ? 1 : -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4), - easeOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1, - easeInOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2 : Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5) / 2 + 1, - easeInBounce: x => 1 - bounceOut(1 - x), - easeOutBounce: bounceOut, - easeInOutBounce: x => x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2 -}; - -_extends({}, config.default, { - mass: 1, - damping: 1, - easing: easings.linear, - clamp: false -}); - -const isFrameValue = value => value instanceof FrameValue; -let nextId$1 = 1; -class FrameValue extends FluidValue { - constructor(...args) { - super(...args); - this.id = nextId$1++; - this.key = void 0; - this._priority = 0; - } - - get priority() { - return this._priority; - } - - set priority(priority) { - if (this._priority != priority) { - this._priority = priority; - - this._onPriorityChange(priority); - } - } - - get() { - const node = getAnimated(this); - return node && node.getValue(); - } - - to(...args) { - return globals.to(this, args); - } - - interpolate(...args) { - deprecateInterpolate(); - return globals.to(this, args); - } - - toJSON() { - return this.get(); - } - - observerAdded(count) { - if (count == 1) this._attach(); - } - - observerRemoved(count) { - if (count == 0) this._detach(); - } - - _attach() {} - - _detach() {} - - _onChange(value, idle = false) { - callFluidObservers(this, { - type: 'change', - parent: this, - value, - idle - }); - } - - _onPriorityChange(priority) { - if (!this.idle) { - frameLoop.sort(this); - } - - callFluidObservers(this, { - type: 'priority', - parent: this, - priority - }); - } - -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -const _excluded$3 = ["children"]; -const SpringContext = _ref => { - let { - children - } = _ref, - props = _objectWithoutPropertiesLoose(_ref, _excluded$3); - - const inherited = useContext(ctx); - const pause = props.pause || !!inherited.pause, - immediate = props.immediate || !!inherited.immediate; - props = useMemoOne(() => ({ - pause, - immediate - }), [pause, immediate]); - const { - Provider - } = ctx; - return React.createElement(Provider, { - value: props - }, children); -}; -const ctx = makeContext(SpringContext, {}); -SpringContext.Provider = ctx.Provider; -SpringContext.Consumer = ctx.Consumer; - -function makeContext(target, init) { - Object.assign(target, React.createContext(init)); - target.Provider._context = target; - target.Consumer._context = target; - return target; -} - -let TransitionPhase; - -(function (TransitionPhase) { - TransitionPhase["MOUNT"] = "mount"; - TransitionPhase["ENTER"] = "enter"; - TransitionPhase["UPDATE"] = "update"; - TransitionPhase["LEAVE"] = "leave"; -})(TransitionPhase || (TransitionPhase = {})); - -class Interpolation extends FrameValue { - constructor(source, args) { - super(); - this.key = void 0; - this.idle = true; - this.calc = void 0; - this._active = new Set(); - this.source = source; - this.calc = createInterpolator(...args); - - const value = this._get(); - - const nodeType = getAnimatedType(value); - setAnimated(this, nodeType.create(value)); - } - - advance(_dt) { - const value = this._get(); - - const oldValue = this.get(); - - if (!isEqual(value, oldValue)) { - getAnimated(this).setValue(value); - - this._onChange(value, this.idle); - } - - if (!this.idle && checkIdle(this._active)) { - becomeIdle(this); - } - } - - _get() { - const inputs = is.arr(this.source) ? this.source.map(getFluidValue) : toArray(getFluidValue(this.source)); - return this.calc(...inputs); - } - - _start() { - if (this.idle && !checkIdle(this._active)) { - this.idle = false; - each(getPayload(this), node => { - node.done = false; - }); - - if (globals.skipAnimation) { - raf.batchedUpdates(() => this.advance()); - becomeIdle(this); - } else { - frameLoop.start(this); - } - } - } - - _attach() { - let priority = 1; - each(toArray(this.source), source => { - if (hasFluidValue(source)) { - addFluidObserver(source, this); - } - - if (isFrameValue(source)) { - if (!source.idle) { - this._active.add(source); - } - - priority = Math.max(priority, source.priority + 1); - } - }); - this.priority = priority; - - this._start(); - } - - _detach() { - each(toArray(this.source), source => { - if (hasFluidValue(source)) { - removeFluidObserver(source, this); - } - }); - - this._active.clear(); - - becomeIdle(this); - } - - eventObserved(event) { - if (event.type == 'change') { - if (event.idle) { - this.advance(); - } else { - this._active.add(event.parent); - - this._start(); - } - } else if (event.type == 'idle') { - this._active.delete(event.parent); - } else if (event.type == 'priority') { - this.priority = toArray(this.source).reduce((highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1), 0); - } - } - -} - -function isIdle(source) { - return source.idle !== false; -} - -function checkIdle(active) { - return !active.size || Array.from(active).every(isIdle); -} - -function becomeIdle(self) { - if (!self.idle) { - self.idle = true; - each(getPayload(self), node => { - node.done = true; - }); - callFluidObservers(self, { - type: 'idle', - parent: self - }); - } -} - -globals.assign({ - createStringInterpolator, - to: (source, args) => new Interpolation(source, args) -}); - -const primitives = ['primitive'].concat(Object.keys(THREE).filter(key => /^[A-Z]/.test(key)).map(key => key[0].toLowerCase() + key.slice(1))); - -globals.assign({ - createStringInterpolator, - colors, - frameLoop: 'demand' -}); -addEffect(() => { - raf.advance(); -}); -createHost(primitives, { - applyAnimatedValues: applyProps -}); - -const V = { - toVector(v, fallback) { - if (v === undefined) v = fallback; - return Array.isArray(v) ? v : [v, v]; - }, - - add(v1, v2) { - return [v1[0] + v2[0], v1[1] + v2[1]]; - }, - - sub(v1, v2) { - return [v1[0] - v2[0], v1[1] - v2[1]]; - }, - - addTo(v1, v2) { - v1[0] += v2[0]; - v1[1] += v2[1]; - }, - - subTo(v1, v2) { - v1[0] -= v2[0]; - v1[1] -= v2[1]; - } - -}; - -function _defineProperty$2(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = null != arguments[i] ? arguments[i] : {}; - i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { - _defineProperty$2(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - - return target; -} - -function call(v, ...args) { - if (typeof v === 'function') { - return v(...args); - } else { - return v; - } -} -function assignDefault(value, fallback) { - return Object.assign({}, fallback, value || {}); -} - -const identity$5 = v => v; -const DEFAULT_RUBBERBAND = 0.15; -const commonConfigResolver = { - enabled(value = true) { - return value; - }, - - eventOptions(value, _k, config) { - return _objectSpread2(_objectSpread2({}, config.shared.eventOptions), value); - }, - - preventDefault(value = false) { - return value; - }, - - triggerAllEvents(value = false) { - return value; - }, - - rubberband(value = 0) { - switch (value) { - case true: - return [DEFAULT_RUBBERBAND, DEFAULT_RUBBERBAND]; - - case false: - return [0, 0]; - - default: - return V.toVector(value); - } - }, - - from(value) { - if (typeof value === 'function') return value; - if (value != null) return V.toVector(value); - }, - - transform(value, _k, config) { - const transform = value || config.shared.transform; - this.hasCustomTransform = !!transform; - - if (process.env.NODE_ENV === 'development') { - const originalTransform = transform || identity$5; - return v => { - const r = originalTransform(v); - - if (!isFinite(r[0]) || !isFinite(r[1])) { - console.warn(`[@use-gesture]: config.transform() must produce a valid result, but it was: [${r[0]},${[1]}]`); - } - - return r; - }; - } - - return transform || identity$5; - }, - - threshold(value) { - return V.toVector(value, 0); - } - -}; - -if (process.env.NODE_ENV === 'development') { - Object.assign(commonConfigResolver, { - domTarget(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`); - } - - return NaN; - }, - - lockDirection(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`lockDirection\` option has been merged with \`axis\`. Use it as in \`{ axis: 'lock' }\``); - } - - return NaN; - }, - - initial(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`initial\` option has been renamed to \`from\`.`); - } - - return NaN; - } - - }); -} - -const DEFAULT_AXIS_THRESHOLD = 0; -const coordinatesConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { - axis(_v, _k, { - axis - }) { - this.lockDirection = axis === 'lock'; - if (!this.lockDirection) return axis; - }, - - axisThreshold(value = DEFAULT_AXIS_THRESHOLD) { - return value; - }, - - bounds(value = {}) { - if (typeof value === 'function') { - return state => coordinatesConfigResolver.bounds(value(state)); - } - - if ('current' in value) { - return () => value.current; - } - - if (typeof HTMLElement === 'function' && value instanceof HTMLElement) { - return value; - } - - const { - left = -Infinity, - right = Infinity, - top = -Infinity, - bottom = Infinity - } = value; - return [[left, right], [top, bottom]]; - } - -}); - -const isBrowser$1 = typeof window !== 'undefined' && window.document && window.document.createElement; - -function supportsTouchEvents() { - return isBrowser$1 && 'ontouchstart' in window; -} - -function isTouchScreen() { - return supportsTouchEvents() || isBrowser$1 && window.navigator.maxTouchPoints > 1; -} - -function supportsPointerEvents() { - return isBrowser$1 && 'onpointerdown' in window; -} - -function supportsPointerLock() { - return isBrowser$1 && 'exitPointerLock' in window.document; -} - -function supportsGestureEvents() { - try { - return 'constructor' in GestureEvent; - } catch (e) { - return false; - } -} - -const SUPPORT = { - isBrowser: isBrowser$1, - gesture: supportsGestureEvents(), - touch: isTouchScreen(), - touchscreen: isTouchScreen(), - pointer: supportsPointerEvents(), - pointerLock: supportsPointerLock() -}; - -const DEFAULT_PREVENT_SCROLL_DELAY = 250; -const DEFAULT_DRAG_DELAY = 180; -const DEFAULT_SWIPE_VELOCITY = 0.5; -const DEFAULT_SWIPE_DISTANCE = 50; -const DEFAULT_SWIPE_DURATION = 250; -const DEFAULT_DRAG_AXIS_THRESHOLD = { - mouse: 0, - touch: 0, - pen: 8 -}; -const dragConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { - device(_v, _k, { - pointer: { - touch = false, - lock = false, - mouse = false - } = {} - }) { - this.pointerLock = lock && SUPPORT.pointerLock; - if (SUPPORT.touch && touch) return 'touch'; - if (this.pointerLock) return 'mouse'; - if (SUPPORT.pointer && !mouse) return 'pointer'; - if (SUPPORT.touch) return 'touch'; - return 'mouse'; - }, - - preventScrollAxis(value, _k, { - preventScroll - }) { - this.preventScrollDelay = typeof preventScroll === 'number' ? preventScroll : preventScroll || preventScroll === undefined && value ? DEFAULT_PREVENT_SCROLL_DELAY : undefined; - if (!SUPPORT.touchscreen || preventScroll === false) return undefined; - return value ? value : preventScroll !== undefined ? 'y' : undefined; - }, - - pointerCapture(_v, _k, { - pointer: { - capture = true, - buttons = 1 - } = {} - }) { - this.pointerButtons = buttons; - return !this.pointerLock && this.device === 'pointer' && capture; - }, - - threshold(value, _k, { - filterTaps = false, - tapsThreshold = 3, - axis = undefined - }) { - const threshold = V.toVector(value, filterTaps ? tapsThreshold : axis ? 1 : 0); - this.filterTaps = filterTaps; - this.tapsThreshold = tapsThreshold; - return threshold; - }, - - swipe({ - velocity = DEFAULT_SWIPE_VELOCITY, - distance = DEFAULT_SWIPE_DISTANCE, - duration = DEFAULT_SWIPE_DURATION - } = {}) { - return { - velocity: this.transform(V.toVector(velocity)), - distance: this.transform(V.toVector(distance)), - duration - }; - }, - - delay(value = 0) { - switch (value) { - case true: - return DEFAULT_DRAG_DELAY; - - case false: - return 0; - - default: - return value; - } - }, - - axisThreshold(value) { - if (!value) return DEFAULT_DRAG_AXIS_THRESHOLD; - return _objectSpread2(_objectSpread2({}, DEFAULT_DRAG_AXIS_THRESHOLD), value); - } - -}); - -if (process.env.NODE_ENV === 'development') { - Object.assign(dragConfigResolver, { - useTouch(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`useTouch\` option has been renamed to \`pointer.touch\`. Use it as in \`{ pointer: { touch: true } }\`.`); - } - - return NaN; - }, - - experimental_preventWindowScrollY(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`experimental_preventWindowScrollY\` option has been renamed to \`preventScroll\`.`); - } - - return NaN; - }, - - swipeVelocity(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`swipeVelocity\` option has been renamed to \`swipe.velocity\`. Use it as in \`{ swipe: { velocity: 0.5 } }\`.`); - } - - return NaN; - }, - - swipeDistance(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`swipeDistance\` option has been renamed to \`swipe.distance\`. Use it as in \`{ swipe: { distance: 50 } }\`.`); - } - - return NaN; - }, - - swipeDuration(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`swipeDuration\` option has been renamed to \`swipe.duration\`. Use it as in \`{ swipe: { duration: 250 } }\`.`); - } - - return NaN; - } - - }); -} - -_objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { - device(_v, _k, { - shared, - pointer: { - touch = false - } = {} - }) { - const sharedConfig = shared; - if (sharedConfig.target && !SUPPORT.touch && SUPPORT.gesture) return 'gesture'; - if (SUPPORT.touch && touch) return 'touch'; - - if (SUPPORT.touchscreen) { - if (SUPPORT.pointer) return 'pointer'; - if (SUPPORT.touch) return 'touch'; - } - }, - - bounds(_v, _k, { - scaleBounds = {}, - angleBounds = {} - }) { - const _scaleBounds = state => { - const D = assignDefault(call(scaleBounds, state), { - min: -Infinity, - max: Infinity - }); - return [D.min, D.max]; - }; - - const _angleBounds = state => { - const A = assignDefault(call(angleBounds, state), { - min: -Infinity, - max: Infinity - }); - return [A.min, A.max]; - }; - - if (typeof scaleBounds !== 'function' && typeof angleBounds !== 'function') return [_scaleBounds(), _angleBounds()]; - return state => [_scaleBounds(state), _angleBounds(state)]; - }, - - threshold(value, _k, config) { - this.lockDirection = config.axis === 'lock'; - const threshold = V.toVector(value, this.lockDirection ? [0.1, 3] : 0); - return threshold; - }, - - modifierKey(value) { - if (value === undefined) return 'ctrlKey'; - return value; - } - -}); - -_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { - mouseOnly: (value = true) => value -}); - -_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { - mouseOnly: (value = true) => value -}); - -var MorphBlendMesh = function (geometry, material) { - Mesh.call(this, geometry, material); - this.animationsMap = {}; - this.animationsList = []; // prepare default animation - // (all frames played together in 1 second) - - var numFrames = Object.keys(this.morphTargetDictionary).length; - var name = '__default'; - var startFrame = 0; - var endFrame = numFrames - 1; - var fps = numFrames / 1; - this.createAnimation(name, startFrame, endFrame, fps); - this.setAnimationWeight(name, 1); -}; - -MorphBlendMesh.prototype = Object.assign(Object.create(Mesh.prototype), { - constructor: MorphBlendMesh, - createAnimation: function (name, start, end, fps) { - var animation = { - start: start, - end: end, - length: end - start + 1, - fps: fps, - duration: (end - start) / fps, - lastFrame: 0, - currentFrame: 0, - active: false, - time: 0, - direction: 1, - weight: 1, - directionBackwards: false, - mirroredLoop: false - }; - this.animationsMap[name] = animation; - this.animationsList.push(animation); - }, - autoCreateAnimations: function (fps) { - var pattern = /([a-z]+)_?(\d+)/i; - var firstAnimation, - frameRanges = {}; - var i = 0; - - for (let key in this.morphTargetDictionary) { - var chunks = key.match(pattern); - - if (chunks && chunks.length > 1) { - var name = chunks[1]; - if (!frameRanges[name]) frameRanges[name] = { - start: Infinity, - end: -Infinity - }; - var range = frameRanges[name]; - if (i < range.start) range.start = i; - if (i > range.end) range.end = i; - if (!firstAnimation) firstAnimation = name; - } - - i++; - } - - for (let name in frameRanges) { - var range = frameRanges[name]; - this.createAnimation(name, range.start, range.end, fps); - } - - this.firstAnimation = firstAnimation; - }, - setAnimationDirectionForward: function (name) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.direction = 1; - animation.directionBackwards = false; - } - }, - setAnimationDirectionBackward: function (name) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.direction = -1; - animation.directionBackwards = true; - } - }, - setAnimationFPS: function (name, fps) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.fps = fps; - animation.duration = (animation.end - animation.start) / animation.fps; - } - }, - setAnimationDuration: function (name, duration) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.duration = duration; - animation.fps = (animation.end - animation.start) / animation.duration; - } - }, - setAnimationWeight: function (name, weight) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.weight = weight; - } - }, - setAnimationTime: function (name, time) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.time = time; - } - }, - getAnimationTime: function (name) { - var time = 0; - var animation = this.animationsMap[name]; - - if (animation) { - time = animation.time; - } - - return time; - }, - getAnimationDuration: function (name) { - var duration = -1; - var animation = this.animationsMap[name]; - - if (animation) { - duration = animation.duration; - } - - return duration; - }, - playAnimation: function (name) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.time = 0; - animation.active = true; - } else { - console.warn('THREE.MorphBlendMesh: animation[' + name + '] undefined in .playAnimation()'); - } - }, - stopAnimation: function (name) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.active = false; - } - }, - update: function (delta) { - for (let i = 0, il = this.animationsList.length; i < il; i++) { - var animation = this.animationsList[i]; - if (!animation.active) continue; - var frameTime = animation.duration / animation.length; - animation.time += animation.direction * delta; - - if (animation.mirroredLoop) { - if (animation.time > animation.duration || animation.time < 0) { - animation.direction *= -1; - - if (animation.time > animation.duration) { - animation.time = animation.duration; - animation.directionBackwards = true; - } - - if (animation.time < 0) { - animation.time = 0; - animation.directionBackwards = false; - } - } - } else { - animation.time = animation.time % animation.duration; - if (animation.time < 0) animation.time += animation.duration; - } - - var keyframe = animation.start + MathUtils.clamp(Math.floor(animation.time / frameTime), 0, animation.length - 1); - var weight = animation.weight; - - if (keyframe !== animation.currentFrame) { - this.morphTargetInfluences[animation.lastFrame] = 0; - this.morphTargetInfluences[animation.currentFrame] = 1 * weight; - this.morphTargetInfluences[keyframe] = 0; - animation.lastFrame = animation.currentFrame; - animation.currentFrame = keyframe; - } - - var mix = animation.time % frameTime / frameTime; - if (animation.directionBackwards) mix = 1 - mix; - - if (animation.currentFrame !== animation.lastFrame) { - this.morphTargetInfluences[animation.currentFrame] = mix * weight; - this.morphTargetInfluences[animation.lastFrame] = (1 - mix) * weight; - } else { - this.morphTargetInfluences[animation.currentFrame] = weight; - } - } - } -}); - -/** - * Ported from: https://github.com/maurizzzio/quickhull3d/ by Mauricio Poppe (https://github.com/maurizzzio) - */ - -var ConvexHull = function () { - var Visible = 0; - var Deleted = 1; - var v1 = new Vector3(); - - function ConvexHull() { - this.tolerance = -1; - this.faces = []; // the generated faces of the convex hull - - this.newFaces = []; // this array holds the faces that are generated within a single iteration - // the vertex lists work as follows: - // - // let 'a' and 'b' be 'Face' instances - // let 'v' be points wrapped as instance of 'Vertex' - // - // [v, v, ..., v, v, v, ...] - // ^ ^ - // | | - // a.outside b.outside - // - - this.assigned = new VertexList(); - this.unassigned = new VertexList(); - this.vertices = []; // vertices of the hull (internal representation of given geometry data) - } - - Object.assign(ConvexHull.prototype, { - setFromPoints: function (points) { - if (Array.isArray(points) !== true) { - console.error('THREE.ConvexHull: Points parameter is not an array.'); - } - - if (points.length < 4) { - console.error('THREE.ConvexHull: The algorithm needs at least four points.'); - } - - this.makeEmpty(); - - for (let i = 0, l = points.length; i < l; i++) { - this.vertices.push(new VertexNode(points[i])); - } - - this.compute(); - return this; - }, - setFromObject: function (object) { - var points = []; - object.updateMatrixWorld(true); - object.traverse(function (node) { - var i, l, point; - var geometry = node.geometry; - - if (geometry !== undefined) { - if (geometry.isGeometry) { - console.error('THREE.ConvexHull no longer supports Geometry. Use THREE.BufferGeometry instead.'); - return; - } else if (geometry.isBufferGeometry) { - var attribute = geometry.attributes.position; - - if (attribute !== undefined) { - for (i = 0, l = attribute.count; i < l; i++) { - point = new Vector3(); - point.fromBufferAttribute(attribute, i).applyMatrix4(node.matrixWorld); - points.push(point); - } - } - } - } - }); - return this.setFromPoints(points); - }, - containsPoint: function (point) { - var faces = this.faces; - - for (let i = 0, l = faces.length; i < l; i++) { - var face = faces[i]; // compute signed distance and check on what half space the point lies - - if (face.distanceToPoint(point) > this.tolerance) return false; - } - - return true; - }, - intersectRay: function (ray, target) { - // based on "Fast Ray-Convex Polyhedron Intersection" by Eric Haines, GRAPHICS GEMS II - var faces = this.faces; - var tNear = -Infinity; - var tFar = Infinity; - - for (let i = 0, l = faces.length; i < l; i++) { - var face = faces[i]; // interpret faces as planes for the further computation - - var vN = face.distanceToPoint(ray.origin); - var vD = face.normal.dot(ray.direction); // if the origin is on the positive side of a plane (so the plane can "see" the origin) and - // the ray is turned away or parallel to the plane, there is no intersection - - if (vN > 0 && vD >= 0) return null; // compute the distance from the ray’s origin to the intersection with the plane - - var t = vD !== 0 ? -vN / vD : 0; // only proceed if the distance is positive. a negative distance means the intersection point - // lies "behind" the origin - - if (t <= 0) continue; // now categorized plane as front-facing or back-facing - - if (vD > 0) { - // plane faces away from the ray, so this plane is a back-face - tFar = Math.min(t, tFar); - } else { - // front-face - tNear = Math.max(t, tNear); - } - - if (tNear > tFar) { - // if tNear ever is greater than tFar, the ray must miss the convex hull - return null; - } - } // evaluate intersection point - // always try tNear first since its the closer intersection point - - - if (tNear !== -Infinity) { - ray.at(tNear, target); - } else { - ray.at(tFar, target); - } - - return target; - }, - intersectsRay: function (ray) { - return this.intersectRay(ray, v1) !== null; - }, - makeEmpty: function () { - this.faces = []; - this.vertices = []; - return this; - }, - // Adds a vertex to the 'assigned' list of vertices and assigns it to the given face - addVertexToFace: function (vertex, face) { - vertex.face = face; - - if (face.outside === null) { - this.assigned.append(vertex); - } else { - this.assigned.insertBefore(face.outside, vertex); - } - - face.outside = vertex; - return this; - }, - // Removes a vertex from the 'assigned' list of vertices and from the given face - removeVertexFromFace: function (vertex, face) { - if (vertex === face.outside) { - // fix face.outside link - if (vertex.next !== null && vertex.next.face === face) { - // face has at least 2 outside vertices, move the 'outside' reference - face.outside = vertex.next; - } else { - // vertex was the only outside vertex that face had - face.outside = null; - } - } - - this.assigned.remove(vertex); - return this; - }, - // Removes all the visible vertices that a given face is able to see which are stored in the 'assigned' vertext list - removeAllVerticesFromFace: function (face) { - if (face.outside !== null) { - // reference to the first and last vertex of this face - var start = face.outside; - var end = face.outside; - - while (end.next !== null && end.next.face === face) { - end = end.next; - } - - this.assigned.removeSubList(start, end); // fix references - - start.prev = end.next = null; - face.outside = null; - return start; - } - }, - // Removes all the visible vertices that 'face' is able to see - deleteFaceVertices: function (face, absorbingFace) { - var faceVertices = this.removeAllVerticesFromFace(face); - - if (faceVertices !== undefined) { - if (absorbingFace === undefined) { - // mark the vertices to be reassigned to some other face - this.unassigned.appendChain(faceVertices); - } else { - // if there's an absorbing face try to assign as many vertices as possible to it - var vertex = faceVertices; - - do { - // we need to buffer the subsequent vertex at this point because the 'vertex.next' reference - // will be changed by upcoming method calls - var nextVertex = vertex.next; - var distance = absorbingFace.distanceToPoint(vertex.point); // check if 'vertex' is able to see 'absorbingFace' - - if (distance > this.tolerance) { - this.addVertexToFace(vertex, absorbingFace); - } else { - this.unassigned.append(vertex); - } // now assign next vertex - - - vertex = nextVertex; - } while (vertex !== null); - } - } - - return this; - }, - // Reassigns as many vertices as possible from the unassigned list to the new faces - resolveUnassignedPoints: function (newFaces) { - if (this.unassigned.isEmpty() === false) { - var vertex = this.unassigned.first(); - - do { - // buffer 'next' reference, see .deleteFaceVertices() - var nextVertex = vertex.next; - var maxDistance = this.tolerance; - var maxFace = null; - - for (let i = 0; i < newFaces.length; i++) { - var face = newFaces[i]; - - if (face.mark === Visible) { - var distance = face.distanceToPoint(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - maxFace = face; - } - - if (maxDistance > 1000 * this.tolerance) break; - } - } // 'maxFace' can be null e.g. if there are identical vertices - - - if (maxFace !== null) { - this.addVertexToFace(vertex, maxFace); - } - - vertex = nextVertex; - } while (vertex !== null); - } - - return this; - }, - // Computes the extremes of a simplex which will be the initial hull - computeExtremes: function () { - var min = new Vector3(); - var max = new Vector3(); - var minVertices = []; - var maxVertices = []; - var i, l, j; // initially assume that the first vertex is the min/max - - for (i = 0; i < 3; i++) { - minVertices[i] = maxVertices[i] = this.vertices[0]; - } - - min.copy(this.vertices[0].point); - max.copy(this.vertices[0].point); // compute the min/max vertex on all six directions - - for (i = 0, l = this.vertices.length; i < l; i++) { - var vertex = this.vertices[i]; - var point = vertex.point; // update the min coordinates - - for (j = 0; j < 3; j++) { - if (point.getComponent(j) < min.getComponent(j)) { - min.setComponent(j, point.getComponent(j)); - minVertices[j] = vertex; - } - } // update the max coordinates - - - for (j = 0; j < 3; j++) { - if (point.getComponent(j) > max.getComponent(j)) { - max.setComponent(j, point.getComponent(j)); - maxVertices[j] = vertex; - } - } - } // use min/max vectors to compute an optimal epsilon - - - this.tolerance = 3 * Number.EPSILON * (Math.max(Math.abs(min.x), Math.abs(max.x)) + Math.max(Math.abs(min.y), Math.abs(max.y)) + Math.max(Math.abs(min.z), Math.abs(max.z))); - return { - min: minVertices, - max: maxVertices - }; - }, - // Computes the initial simplex assigning to its faces all the points - // that are candidates to form part of the hull - computeInitialHull: function () { - var line3, plane, closestPoint; - return function computeInitialHull() { - if (line3 === undefined) { - line3 = new Line3(); - plane = new Plane(); - closestPoint = new Vector3(); - } - - var vertex, - vertices = this.vertices; - var extremes = this.computeExtremes(); - var min = extremes.min; - var max = extremes.max; - var v0, v1, v2, v3; - var i, l, j; // 1. Find the two vertices 'v0' and 'v1' with the greatest 1d separation - // (max.x - min.x) - // (max.y - min.y) - // (max.z - min.z) - - var distance, - maxDistance = 0; - var index = 0; - - for (i = 0; i < 3; i++) { - distance = max[i].point.getComponent(i) - min[i].point.getComponent(i); - - if (distance > maxDistance) { - maxDistance = distance; - index = i; - } - } - - v0 = min[index]; - v1 = max[index]; // 2. The next vertex 'v2' is the one farthest to the line formed by 'v0' and 'v1' - - maxDistance = 0; - line3.set(v0.point, v1.point); - - for (i = 0, l = this.vertices.length; i < l; i++) { - vertex = vertices[i]; - - if (vertex !== v0 && vertex !== v1) { - line3.closestPointToPoint(vertex.point, true, closestPoint); - distance = closestPoint.distanceToSquared(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - v2 = vertex; - } - } - } // 3. The next vertex 'v3' is the one farthest to the plane 'v0', 'v1', 'v2' - - - maxDistance = -1; - plane.setFromCoplanarPoints(v0.point, v1.point, v2.point); - - for (i = 0, l = this.vertices.length; i < l; i++) { - vertex = vertices[i]; - - if (vertex !== v0 && vertex !== v1 && vertex !== v2) { - distance = Math.abs(plane.distanceToPoint(vertex.point)); - - if (distance > maxDistance) { - maxDistance = distance; - v3 = vertex; - } - } - } - - var faces = []; - - if (plane.distanceToPoint(v3.point) < 0) { - // the face is not able to see the point so 'plane.normal' is pointing outside the tetrahedron - faces.push(Face.create(v0, v1, v2), Face.create(v3, v1, v0), Face.create(v3, v2, v1), Face.create(v3, v0, v2)); // set the twin edge - - for (i = 0; i < 3; i++) { - j = (i + 1) % 3; // join face[ i ] i > 0, with the first face - - faces[i + 1].getEdge(2).setTwin(faces[0].getEdge(j)); // join face[ i ] with face[ i + 1 ], 1 <= i <= 3 - - faces[i + 1].getEdge(1).setTwin(faces[j + 1].getEdge(0)); - } - } else { - // the face is able to see the point so 'plane.normal' is pointing inside the tetrahedron - faces.push(Face.create(v0, v2, v1), Face.create(v3, v0, v1), Face.create(v3, v1, v2), Face.create(v3, v2, v0)); // set the twin edge - - for (i = 0; i < 3; i++) { - j = (i + 1) % 3; // join face[ i ] i > 0, with the first face - - faces[i + 1].getEdge(2).setTwin(faces[0].getEdge((3 - i) % 3)); // join face[ i ] with face[ i + 1 ] - - faces[i + 1].getEdge(0).setTwin(faces[j + 1].getEdge(1)); - } - } // the initial hull is the tetrahedron - - - for (i = 0; i < 4; i++) { - this.faces.push(faces[i]); - } // initial assignment of vertices to the faces of the tetrahedron - - - for (i = 0, l = vertices.length; i < l; i++) { - vertex = vertices[i]; - - if (vertex !== v0 && vertex !== v1 && vertex !== v2 && vertex !== v3) { - maxDistance = this.tolerance; - var maxFace = null; - - for (j = 0; j < 4; j++) { - distance = this.faces[j].distanceToPoint(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - maxFace = this.faces[j]; - } - } - - if (maxFace !== null) { - this.addVertexToFace(vertex, maxFace); - } - } - } - - return this; - }; - }(), - // Removes inactive faces - reindexFaces: function () { - var activeFaces = []; - - for (let i = 0; i < this.faces.length; i++) { - var face = this.faces[i]; - - if (face.mark === Visible) { - activeFaces.push(face); - } - } - - this.faces = activeFaces; - return this; - }, - // Finds the next vertex to create faces with the current hull - nextVertexToAdd: function () { - // if the 'assigned' list of vertices is empty, no vertices are left. return with 'undefined' - if (this.assigned.isEmpty() === false) { - var eyeVertex, - maxDistance = 0; // grap the first available face and start with the first visible vertex of that face - - var eyeFace = this.assigned.first().face; - var vertex = eyeFace.outside; // now calculate the farthest vertex that face can see - - do { - var distance = eyeFace.distanceToPoint(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - eyeVertex = vertex; - } - - vertex = vertex.next; - } while (vertex !== null && vertex.face === eyeFace); - - return eyeVertex; - } - }, - // Computes a chain of half edges in CCW order called the 'horizon'. - // For an edge to be part of the horizon it must join a face that can see - // 'eyePoint' and a face that cannot see 'eyePoint'. - computeHorizon: function (eyePoint, crossEdge, face, horizon) { - // moves face's vertices to the 'unassigned' vertex list - this.deleteFaceVertices(face); - face.mark = Deleted; - var edge; - - if (crossEdge === null) { - edge = crossEdge = face.getEdge(0); - } else { - // start from the next edge since 'crossEdge' was already analyzed - // (actually 'crossEdge.twin' was the edge who called this method recursively) - edge = crossEdge.next; - } - - do { - var twinEdge = edge.twin; - var oppositeFace = twinEdge.face; - - if (oppositeFace.mark === Visible) { - if (oppositeFace.distanceToPoint(eyePoint) > this.tolerance) { - // the opposite face can see the vertex, so proceed with next edge - this.computeHorizon(eyePoint, twinEdge, oppositeFace, horizon); - } else { - // the opposite face can't see the vertex, so this edge is part of the horizon - horizon.push(edge); - } - } - - edge = edge.next; - } while (edge !== crossEdge); - - return this; - }, - // Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head' in CCW order - addAdjoiningFace: function (eyeVertex, horizonEdge) { - // all the half edges are created in ccw order thus the face is always pointing outside the hull - var face = Face.create(eyeVertex, horizonEdge.tail(), horizonEdge.head()); - this.faces.push(face); // join face.getEdge( - 1 ) with the horizon's opposite edge face.getEdge( - 1 ) = face.getEdge( 2 ) - - face.getEdge(-1).setTwin(horizonEdge.twin); - return face.getEdge(0); // the half edge whose vertex is the eyeVertex - }, - // Adds 'horizon.length' faces to the hull, each face will be linked with the - // horizon opposite face and the face on the left/right - addNewFaces: function (eyeVertex, horizon) { - this.newFaces = []; - var firstSideEdge = null; - var previousSideEdge = null; - - for (let i = 0; i < horizon.length; i++) { - var horizonEdge = horizon[i]; // returns the right side edge - - var sideEdge = this.addAdjoiningFace(eyeVertex, horizonEdge); - - if (firstSideEdge === null) { - firstSideEdge = sideEdge; - } else { - // joins face.getEdge( 1 ) with previousFace.getEdge( 0 ) - sideEdge.next.setTwin(previousSideEdge); - } - - this.newFaces.push(sideEdge.face); - previousSideEdge = sideEdge; - } // perform final join of new faces - - - firstSideEdge.next.setTwin(previousSideEdge); - return this; - }, - // Adds a vertex to the hull - addVertexToHull: function (eyeVertex) { - var horizon = []; - this.unassigned.clear(); // remove 'eyeVertex' from 'eyeVertex.face' so that it can't be added to the 'unassigned' vertex list - - this.removeVertexFromFace(eyeVertex, eyeVertex.face); - this.computeHorizon(eyeVertex.point, null, eyeVertex.face, horizon); - this.addNewFaces(eyeVertex, horizon); // reassign 'unassigned' vertices to the new faces - - this.resolveUnassignedPoints(this.newFaces); - return this; - }, - cleanup: function () { - this.assigned.clear(); - this.unassigned.clear(); - this.newFaces = []; - return this; - }, - compute: function () { - var vertex; - this.computeInitialHull(); // add all available vertices gradually to the hull - - while ((vertex = this.nextVertexToAdd()) !== undefined) { - this.addVertexToHull(vertex); - } - - this.reindexFaces(); - this.cleanup(); - return this; - } - }); // - - function Face() { - this.normal = new Vector3(); - this.midpoint = new Vector3(); - this.area = 0; - this.constant = 0; // signed distance from face to the origin - - this.outside = null; // reference to a vertex in a vertex list this face can see - - this.mark = Visible; - this.edge = null; - } - - Object.assign(Face, { - create: function (a, b, c) { - var face = new Face(); - var e0 = new HalfEdge(a, face); - var e1 = new HalfEdge(b, face); - var e2 = new HalfEdge(c, face); // join edges - - e0.next = e2.prev = e1; - e1.next = e0.prev = e2; - e2.next = e1.prev = e0; // main half edge reference - - face.edge = e0; - return face.compute(); - } - }); - Object.assign(Face.prototype, { - getEdge: function (i) { - var edge = this.edge; - - while (i > 0) { - edge = edge.next; - i--; - } - - while (i < 0) { - edge = edge.prev; - i++; - } - - return edge; - }, - compute: function () { - var triangle; - return function compute() { - if (triangle === undefined) triangle = new Triangle(); - var a = this.edge.tail(); - var b = this.edge.head(); - var c = this.edge.next.head(); - triangle.set(a.point, b.point, c.point); - triangle.getNormal(this.normal); - triangle.getMidpoint(this.midpoint); - this.area = triangle.getArea(); - this.constant = this.normal.dot(this.midpoint); - return this; - }; - }(), - distanceToPoint: function (point) { - return this.normal.dot(point) - this.constant; - } - }); // Entity for a Doubly-Connected Edge List (DCEL). - - function HalfEdge(vertex, face) { - this.vertex = vertex; - this.prev = null; - this.next = null; - this.twin = null; - this.face = face; - } - - Object.assign(HalfEdge.prototype, { - head: function () { - return this.vertex; - }, - tail: function () { - return this.prev ? this.prev.vertex : null; - }, - length: function () { - var head = this.head(); - var tail = this.tail(); - - if (tail !== null) { - return tail.point.distanceTo(head.point); - } - - return -1; - }, - lengthSquared: function () { - var head = this.head(); - var tail = this.tail(); - - if (tail !== null) { - return tail.point.distanceToSquared(head.point); - } - - return -1; - }, - setTwin: function (edge) { - this.twin = edge; - edge.twin = this; - return this; - } - }); // A vertex as a double linked list node. - - function VertexNode(point) { - this.point = point; - this.prev = null; - this.next = null; - this.face = null; // the face that is able to see this vertex - } // A double linked list that contains vertex nodes. - - - function VertexList() { - this.head = null; - this.tail = null; - } - - Object.assign(VertexList.prototype, { - first: function () { - return this.head; - }, - last: function () { - return this.tail; - }, - clear: function () { - this.head = this.tail = null; - return this; - }, - // Inserts a vertex before the target vertex - insertBefore: function (target, vertex) { - vertex.prev = target.prev; - vertex.next = target; - - if (vertex.prev === null) { - this.head = vertex; - } else { - vertex.prev.next = vertex; - } - - target.prev = vertex; - return this; - }, - // Inserts a vertex after the target vertex - insertAfter: function (target, vertex) { - vertex.prev = target; - vertex.next = target.next; - - if (vertex.next === null) { - this.tail = vertex; - } else { - vertex.next.prev = vertex; - } - - target.next = vertex; - return this; - }, - // Appends a vertex to the end of the linked list - append: function (vertex) { - if (this.head === null) { - this.head = vertex; - } else { - this.tail.next = vertex; - } - - vertex.prev = this.tail; - vertex.next = null; // the tail has no subsequent vertex - - this.tail = vertex; - return this; - }, - // Appends a chain of vertices where 'vertex' is the head. - appendChain: function (vertex) { - if (this.head === null) { - this.head = vertex; - } else { - this.tail.next = vertex; - } - - vertex.prev = this.tail; // ensure that the 'tail' reference points to the last vertex of the chain - - while (vertex.next !== null) { - vertex = vertex.next; - } - - this.tail = vertex; - return this; - }, - // Removes a vertex from the linked list - remove: function (vertex) { - if (vertex.prev === null) { - this.head = vertex.next; - } else { - vertex.prev.next = vertex.next; - } - - if (vertex.next === null) { - this.tail = vertex.prev; - } else { - vertex.next.prev = vertex.prev; - } - - return this; - }, - // Removes a list of vertices whose 'head' is 'a' and whose 'tail' is b - removeSubList: function (a, b) { - if (a.prev === null) { - this.head = b.next; - } else { - a.prev.next = b.next; - } - - if (b.next === null) { - this.tail = a.prev; - } else { - b.next.prev = a.prev; - } - - return this; - }, - isEmpty: function () { - return this.head === null; - } - }); - return ConvexHull; -}(); - -class ConvexGeometry extends BufferGeometry { - constructor(points) { - super(); // buffers - - const vertices = []; - const normals = []; - - if (ConvexHull === undefined) { - console.error('THREE.ConvexBufferGeometry: ConvexBufferGeometry relies on ConvexHull'); - } - - const convexHull = new ConvexHull().setFromPoints(points); // generate vertices and normals - - const faces = convexHull.faces; - - for (let i = 0; i < faces.length; i++) { - const face = faces[i]; - let edge = face.edge; // we move along a doubly-connected edge list to access all face points (see HalfEdge docs) - - do { - const point = edge.head().point; - vertices.push(point.x, point.y, point.z); - normals.push(face.normal.x, face.normal.y, face.normal.z); - edge = edge.next; - } while (edge !== face.edge); - } // build geometry - - - this.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - this.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - } - -} - -/** - * @fileoverview This class can be used to subdivide a convex Geometry object into pieces. - * - * Usage: - * - * Use the function prepareBreakableObject to prepare a Mesh object to be broken. - * - * Then, call the various functions to subdivide the object (subdivideByImpact, cutByPlane) - * - * Sub-objects that are product of subdivision don't need prepareBreakableObject to be called on them. - * - * Requisites for the object: - * - * - Mesh object must have a BufferGeometry (not Geometry) and a Material - * - * - Vertex normals must be planar (not smoothed) - * - * - The geometry must be convex (this is not checked in the library). You can create convex - * geometries with ConvexGeometry. The BoxGeometry, SphereGeometry and other convex primitives - * can also be used. - * - * Note: This lib adds member variables to object's userData member (see prepareBreakableObject function) - * Use with caution and read the code when using with other libs. - * - * @param {double} minSizeForBreak Min size a debris can have to break. - * @param {double} smallDelta Max distance to consider that a point belongs to a plane. - * - */ - -var ConvexObjectBreaker = function (minSizeForBreak, smallDelta) { - this.minSizeForBreak = minSizeForBreak || 1.4; - this.smallDelta = smallDelta || 0.0001; - this.tempLine1 = new Line3(); - this.tempPlane1 = new Plane(); - this.tempPlane2 = new Plane(); - this.tempPlane_Cut = new Plane(); - this.tempCM1 = new Vector3(); - this.tempCM2 = new Vector3(); - this.tempVector3 = new Vector3(); - this.tempVector3_2 = new Vector3(); - this.tempVector3_3 = new Vector3(); - this.tempVector3_P0 = new Vector3(); - this.tempVector3_P1 = new Vector3(); - this.tempVector3_P2 = new Vector3(); - this.tempVector3_N0 = new Vector3(); - this.tempVector3_N1 = new Vector3(); - this.tempVector3_AB = new Vector3(); - this.tempVector3_CB = new Vector3(); - this.tempResultObjects = { - object1: null, - object2: null - }; - this.segments = []; - var n = 30 * 30; - - for (let i = 0; i < n; i++) this.segments[i] = false; -}; - -ConvexObjectBreaker.prototype = { - constructor: ConvexObjectBreaker, - prepareBreakableObject: function (object, mass, velocity, angularVelocity, breakable) { - // object is a Object3d (normally a Mesh), must have a BufferGeometry, and it must be convex. - // Its material property is propagated to its children (sub-pieces) - // mass must be > 0 - if (!object.geometry.isBufferGeometry) { - console.error('THREE.ConvexObjectBreaker.prepareBreakableObject(): Parameter object must have a BufferGeometry.'); - } - - var userData = object.userData; - userData.mass = mass; - userData.velocity = velocity.clone(); - userData.angularVelocity = angularVelocity.clone(); - userData.breakable = breakable; - }, - - /* - * @param {int} maxRadialIterations Iterations for radial cuts. - * @param {int} maxRandomIterations Max random iterations for not-radial cuts - * - * Returns the array of pieces - */ - subdivideByImpact: function (object, pointOfImpact, normal, maxRadialIterations, maxRandomIterations) { - var debris = []; - var tempPlane1 = this.tempPlane1; - var tempPlane2 = this.tempPlane2; - this.tempVector3.addVectors(pointOfImpact, normal); - tempPlane1.setFromCoplanarPoints(pointOfImpact, object.position, this.tempVector3); - var maxTotalIterations = maxRandomIterations + maxRadialIterations; - var scope = this; - - function subdivideRadial(subObject, startAngle, endAngle, numIterations) { - if (Math.random() < numIterations * 0.05 || numIterations > maxTotalIterations) { - debris.push(subObject); - return; - } - - var angle = Math.PI; - - if (numIterations === 0) { - tempPlane2.normal.copy(tempPlane1.normal); - tempPlane2.constant = tempPlane1.constant; - } else { - if (numIterations <= maxRadialIterations) { - angle = (endAngle - startAngle) * (0.2 + 0.6 * Math.random()) + startAngle; // Rotate tempPlane2 at impact point around normal axis and the angle - - scope.tempVector3_2.copy(object.position).sub(pointOfImpact).applyAxisAngle(normal, angle).add(pointOfImpact); - tempPlane2.setFromCoplanarPoints(pointOfImpact, scope.tempVector3, scope.tempVector3_2); - } else { - angle = (0.5 * (numIterations & 1) + 0.2 * (2 - Math.random())) * Math.PI; // Rotate tempPlane2 at object position around normal axis and the angle - - scope.tempVector3_2.copy(pointOfImpact).sub(subObject.position).applyAxisAngle(normal, angle).add(subObject.position); - scope.tempVector3_3.copy(normal).add(subObject.position); - tempPlane2.setFromCoplanarPoints(subObject.position, scope.tempVector3_3, scope.tempVector3_2); - } - } // Perform the cut - - - scope.cutByPlane(subObject, tempPlane2, scope.tempResultObjects); - var obj1 = scope.tempResultObjects.object1; - var obj2 = scope.tempResultObjects.object2; - - if (obj1) { - subdivideRadial(obj1, startAngle, angle, numIterations + 1); - } - - if (obj2) { - subdivideRadial(obj2, angle, endAngle, numIterations + 1); - } - } - - subdivideRadial(object, 0, 2 * Math.PI, 0); - return debris; - }, - cutByPlane: function (object, plane, output) { - // Returns breakable objects in output.object1 and output.object2 members, the resulting 2 pieces of the cut. - // object2 can be null if the plane doesn't cut the object. - // object1 can be null only in case of internal error - // Returned value is number of pieces, 0 for error. - var geometry = object.geometry; - var coords = geometry.attributes.position.array; - var normals = geometry.attributes.normal.array; - var numPoints = coords.length / 3; - var numFaces = numPoints / 3; - var indices = geometry.getIndex(); - - if (indices) { - indices = indices.array; - numFaces = indices.length / 3; - } - - function getVertexIndex(faceIdx, vert) { - // vert = 0, 1 or 2. - var idx = faceIdx * 3 + vert; - return indices ? indices[idx] : idx; - } - - var points1 = []; - var points2 = []; - var delta = this.smallDelta; // Reset segments mark - - var numPointPairs = numPoints * numPoints; - - for (let i = 0; i < numPointPairs; i++) this.segments[i] = false; - - var p0 = this.tempVector3_P0; - var p1 = this.tempVector3_P1; - var n0 = this.tempVector3_N0; - var n1 = this.tempVector3_N1; // Iterate through the faces to mark edges shared by coplanar faces - - for (let i = 0; i < numFaces - 1; i++) { - var a1 = getVertexIndex(i, 0); - var b1 = getVertexIndex(i, 1); - var c1 = getVertexIndex(i, 2); // Assuming all 3 vertices have the same normal - - n0.set(normals[a1], normals[a1] + 1, normals[a1] + 2); - - for (let j = i + 1; j < numFaces; j++) { - var a2 = getVertexIndex(j, 0); - var b2 = getVertexIndex(j, 1); - var c2 = getVertexIndex(j, 2); // Assuming all 3 vertices have the same normal - - n1.set(normals[a2], normals[a2] + 1, normals[a2] + 2); - var coplanar = 1 - n0.dot(n1) < delta; - - if (coplanar) { - if (a1 === a2 || a1 === b2 || a1 === c2) { - if (b1 === a2 || b1 === b2 || b1 === c2) { - this.segments[a1 * numPoints + b1] = true; - this.segments[b1 * numPoints + a1] = true; - } else { - this.segments[c1 * numPoints + a1] = true; - this.segments[a1 * numPoints + c1] = true; - } - } else if (b1 === a2 || b1 === b2 || b1 === c2) { - this.segments[c1 * numPoints + b1] = true; - this.segments[b1 * numPoints + c1] = true; - } - } - } - } // Transform the plane to object local space - - - var localPlane = this.tempPlane_Cut; - object.updateMatrix(); - ConvexObjectBreaker.transformPlaneToLocalSpace(plane, object.matrix, localPlane); // Iterate through the faces adding points to both pieces - - for (let i = 0; i < numFaces; i++) { - var va = getVertexIndex(i, 0); - var vb = getVertexIndex(i, 1); - var vc = getVertexIndex(i, 2); - - for (let segment = 0; segment < 3; segment++) { - var i0 = segment === 0 ? va : segment === 1 ? vb : vc; - var i1 = segment === 0 ? vb : segment === 1 ? vc : va; - var segmentState = this.segments[i0 * numPoints + i1]; - if (segmentState) continue; // The segment already has been processed in another face - // Mark segment as processed (also inverted segment) - - this.segments[i0 * numPoints + i1] = true; - this.segments[i1 * numPoints + i0] = true; - p0.set(coords[3 * i0], coords[3 * i0 + 1], coords[3 * i0 + 2]); - p1.set(coords[3 * i1], coords[3 * i1 + 1], coords[3 * i1 + 2]); // mark: 1 for negative side, 2 for positive side, 3 for coplanar point - - var mark0 = 0; - var d = localPlane.distanceToPoint(p0); - - if (d > delta) { - mark0 = 2; - points2.push(p0.clone()); - } else if (d < -delta) { - mark0 = 1; - points1.push(p0.clone()); - } else { - mark0 = 3; - points1.push(p0.clone()); - points2.push(p0.clone()); - } // mark: 1 for negative side, 2 for positive side, 3 for coplanar point - - - var mark1 = 0; - var d = localPlane.distanceToPoint(p1); - - if (d > delta) { - mark1 = 2; - points2.push(p1.clone()); - } else if (d < -delta) { - mark1 = 1; - points1.push(p1.clone()); - } else { - mark1 = 3; - points1.push(p1.clone()); - points2.push(p1.clone()); - } - - if (mark0 === 1 && mark1 === 2 || mark0 === 2 && mark1 === 1) { - // Intersection of segment with the plane - this.tempLine1.start.copy(p0); - this.tempLine1.end.copy(p1); - var intersection = new Vector3(); - intersection = localPlane.intersectLine(this.tempLine1, intersection); - - if (intersection === undefined) { - // Shouldn't happen - console.error('Internal error: segment does not intersect plane.'); - output.segmentedObject1 = null; - output.segmentedObject2 = null; - return 0; - } - - points1.push(intersection); - points2.push(intersection.clone()); - } - } - } // Calculate debris mass (very fast and imprecise): - - - var newMass = object.userData.mass * 0.5; // Calculate debris Center of Mass (again fast and imprecise) - - this.tempCM1.set(0, 0, 0); - var radius1 = 0; - var numPoints1 = points1.length; - - if (numPoints1 > 0) { - for (let i = 0; i < numPoints1; i++) this.tempCM1.add(points1[i]); - - this.tempCM1.divideScalar(numPoints1); - - for (let i = 0; i < numPoints1; i++) { - var p = points1[i]; - p.sub(this.tempCM1); - radius1 = Math.max(radius1, p.x, p.y, p.z); - } - - this.tempCM1.add(object.position); - } - - this.tempCM2.set(0, 0, 0); - var radius2 = 0; - var numPoints2 = points2.length; - - if (numPoints2 > 0) { - for (let i = 0; i < numPoints2; i++) this.tempCM2.add(points2[i]); - - this.tempCM2.divideScalar(numPoints2); - - for (let i = 0; i < numPoints2; i++) { - var p = points2[i]; - p.sub(this.tempCM2); - radius2 = Math.max(radius2, p.x, p.y, p.z); - } - - this.tempCM2.add(object.position); - } - - var object1 = null; - var object2 = null; - var numObjects = 0; - - if (numPoints1 > 4) { - object1 = new Mesh(new ConvexGeometry(points1), object.material); - object1.position.copy(this.tempCM1); - object1.quaternion.copy(object.quaternion); - this.prepareBreakableObject(object1, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius1 > this.minSizeForBreak); - numObjects++; - } - - if (numPoints2 > 4) { - object2 = new Mesh(new ConvexGeometry(points2), object.material); - object2.position.copy(this.tempCM2); - object2.quaternion.copy(object.quaternion); - this.prepareBreakableObject(object2, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius2 > this.minSizeForBreak); - numObjects++; - } - - output.object1 = object1; - output.object2 = object2; - return numObjects; - } -}; - -ConvexObjectBreaker.transformFreeVector = function (v, m) { - // input: - // vector interpreted as a free vector - // THREE.Matrix4 orthogonal matrix (matrix without scale) - var x = v.x, - y = v.y, - z = v.z; - var e = m.elements; - v.x = e[0] * x + e[4] * y + e[8] * z; - v.y = e[1] * x + e[5] * y + e[9] * z; - v.z = e[2] * x + e[6] * y + e[10] * z; - return v; -}; - -ConvexObjectBreaker.transformFreeVectorInverse = function (v, m) { - // input: - // vector interpreted as a free vector - // THREE.Matrix4 orthogonal matrix (matrix without scale) - var x = v.x, - y = v.y, - z = v.z; - var e = m.elements; - v.x = e[0] * x + e[1] * y + e[2] * z; - v.y = e[4] * x + e[5] * y + e[6] * z; - v.z = e[8] * x + e[9] * y + e[10] * z; - return v; -}; - -ConvexObjectBreaker.transformTiedVectorInverse = function (v, m) { - // input: - // vector interpreted as a tied (ordinary) vector - // THREE.Matrix4 orthogonal matrix (matrix without scale) - var x = v.x, - y = v.y, - z = v.z; - var e = m.elements; - v.x = e[0] * x + e[1] * y + e[2] * z - e[12]; - v.y = e[4] * x + e[5] * y + e[6] * z - e[13]; - v.z = e[8] * x + e[9] * y + e[10] * z - e[14]; - return v; -}; - -ConvexObjectBreaker.transformPlaneToLocalSpace = function () { - var v1 = new Vector3(); - return function transformPlaneToLocalSpace(plane, m, resultPlane) { - resultPlane.normal.copy(plane.normal); - resultPlane.constant = plane.constant; - var referencePoint = ConvexObjectBreaker.transformTiedVectorInverse(plane.coplanarPoint(v1), m); - ConvexObjectBreaker.transformFreeVectorInverse(resultPlane.normal, m); // recalculate constant (like in setFromNormalAndCoplanarPoint) - - resultPlane.constant = -referencePoint.dot(resultPlane.normal); - }; -}(); - -var Gyroscope = function () { - Object3D.call(this); -}; - -Gyroscope.prototype = Object.create(Object3D.prototype); -Gyroscope.prototype.constructor = Gyroscope; - -Gyroscope.prototype.updateMatrixWorld = function () { - var translationObject = new Vector3(); - var quaternionObject = new Quaternion(); - var scaleObject = new Vector3(); - var translationWorld = new Vector3(); - var quaternionWorld = new Quaternion(); - var scaleWorld = new Vector3(); - return function updateMatrixWorld(force) { - this.matrixAutoUpdate && this.updateMatrix(); // update matrixWorld - - if (this.matrixWorldNeedsUpdate || force) { - if (this.parent !== null) { - this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); - this.matrixWorld.decompose(translationWorld, quaternionWorld, scaleWorld); - this.matrix.decompose(translationObject, quaternionObject, scaleObject); - this.matrixWorld.compose(translationWorld, quaternionObject, scaleWorld); - } else { - this.matrixWorld.copy(this.matrix); - } - - this.matrixWorldNeedsUpdate = false; - force = true; - } // update children - - - for (let i = 0, l = this.children.length; i < l; i++) { - this.children[i].updateMatrixWorld(force); - } - }; -}(); - -var MorphAnimMesh = function (geometry, material) { - Mesh.call(this, geometry, material); - this.type = 'MorphAnimMesh'; - this.mixer = new AnimationMixer(this); - this.activeAction = null; -}; - -MorphAnimMesh.prototype = Object.create(Mesh.prototype); -MorphAnimMesh.prototype.constructor = MorphAnimMesh; - -MorphAnimMesh.prototype.setDirectionForward = function () { - this.mixer.timeScale = 1.0; -}; - -MorphAnimMesh.prototype.setDirectionBackward = function () { - this.mixer.timeScale = -1.0; -}; - -MorphAnimMesh.prototype.playAnimation = function (label, fps) { - if (this.activeAction) { - this.activeAction.stop(); - this.activeAction = null; - } - - var clip = AnimationClip.findByName(this, label); - - if (clip) { - var action = this.mixer.clipAction(clip); - action.timeScale = clip.tracks.length * fps / clip.duration; - this.activeAction = action.play(); - } else { - throw new Error('THREE.MorphAnimMesh: animations[' + label + '] undefined in .playAnimation()'); - } -}; - -MorphAnimMesh.prototype.updateAnimation = function (delta) { - this.mixer.update(delta); -}; - -MorphAnimMesh.prototype.copy = function (source) { - Mesh.prototype.copy.call(this, source); - this.mixer = new AnimationMixer(this); - return this; -}; - -Object.create(BufferGeometry.prototype); - -Object.create(BufferGeometry.prototype); - -Object.create(BufferGeometry.prototype); - -Object.create(BufferGeometry.prototype); - -Object.create(BufferGeometry.prototype); - -let webGL2Available; -function isWebGL2Available() { - if (webGL2Available !== undefined) return webGL2Available; - - try { - var _gl$getExtension2; - - let gl; - const canvas = document.createElement('canvas'); - webGL2Available = !!(window.WebGL2RenderingContext && (gl = canvas.getContext('webgl2'))); - if (gl) (_gl$getExtension2 = gl.getExtension('WEBGL_lose_context')) === null || _gl$getExtension2 === void 0 ? void 0 : _gl$getExtension2.loseContext(); - return webGL2Available; - } catch (e) { - return webGL2Available = false; - } -} - -/** - * This class has been made to hold a slice of a volume data - * @class - * @param {Volume} volume The associated volume - * @param {number} [index=0] The index of the slice - * @param {string} [axis='z'] For now only 'x', 'y' or 'z' but later it will change to a normal vector - * @see Volume - */ - -var VolumeSlice = function (volume, index, axis) { - var slice = this; - /** - * @member {Volume} volume The associated volume - */ - - this.volume = volume; - /** - * @member {Number} index The index of the slice, if changed, will automatically call updateGeometry at the next repaint - */ - - index = index || 0; - Object.defineProperty(this, 'index', { - get: function () { - return index; - }, - set: function (value) { - index = value; - slice.geometryNeedsUpdate = true; - return index; - } - }); - /** - * @member {String} axis The normal axis - */ - - this.axis = axis || 'z'; - /** - * @member {HTMLCanvasElement} canvas The final canvas used for the texture - */ - - /** - * @member {CanvasRenderingContext2D} ctx Context of the canvas - */ - - this.canvas = document.createElement('canvas'); - /** - * @member {HTMLCanvasElement} canvasBuffer The intermediary canvas used to paint the data - */ - - /** - * @member {CanvasRenderingContext2D} ctxBuffer Context of the canvas buffer - */ - - this.canvasBuffer = document.createElement('canvas'); - this.updateGeometry(); - var canvasMap = new Texture(this.canvas); - canvasMap.minFilter = LinearFilter; - canvasMap.wrapS = canvasMap.wrapT = ClampToEdgeWrapping; - var material = new MeshBasicMaterial({ - map: canvasMap, - side: DoubleSide, - transparent: true - }); - /** - * @member {Mesh} mesh The mesh ready to get used in the scene - */ - - this.mesh = new Mesh(this.geometry, material); - this.mesh.matrixAutoUpdate = false; - /** - * @member {Boolean} geometryNeedsUpdate If set to true, updateGeometry will be triggered at the next repaint - */ - - this.geometryNeedsUpdate = true; - this.repaint(); - /** - * @member {Number} iLength Width of slice in the original coordinate system, corresponds to the width of the buffer canvas - */ - - /** - * @member {Number} jLength Height of slice in the original coordinate system, corresponds to the height of the buffer canvas - */ - - /** - * @member {Function} sliceAccess Function that allow the slice to access right data - * @see Volume.extractPerpendicularPlane - * @param {Number} i The first coordinate - * @param {Number} j The second coordinate - * @returns {Number} the index corresponding to the voxel in volume.data of the given position in the slice - */ -}; - -VolumeSlice.prototype = { - constructor: VolumeSlice, - - /** - * @member {Function} repaint Refresh the texture and the geometry if geometryNeedsUpdate is set to true - * @memberof VolumeSlice - */ - repaint: function () { - if (this.geometryNeedsUpdate) { - this.updateGeometry(); - } - - var iLength = this.iLength, - jLength = this.jLength, - sliceAccess = this.sliceAccess, - volume = this.volume, - canvas = this.canvasBuffer, - ctx = this.ctxBuffer; // get the imageData and pixel array from the canvas - - var imgData = ctx.getImageData(0, 0, iLength, jLength); - var data = imgData.data; - var volumeData = volume.data; - var upperThreshold = volume.upperThreshold; - var lowerThreshold = volume.lowerThreshold; - var windowLow = volume.windowLow; - var windowHigh = volume.windowHigh; // manipulate some pixel elements - - var pixelCount = 0; - - if (volume.dataType === 'label') { - //this part is currently useless but will be used when colortables will be handled - for (let j = 0; j < jLength; j++) { - for (let i = 0; i < iLength; i++) { - var label = volumeData[sliceAccess(i, j)]; - label = label >= this.colorMap.length ? label % this.colorMap.length + 1 : label; - var color = this.colorMap[label]; - data[4 * pixelCount] = color >> 24 & 0xff; - data[4 * pixelCount + 1] = color >> 16 & 0xff; - data[4 * pixelCount + 2] = color >> 8 & 0xff; - data[4 * pixelCount + 3] = color & 0xff; - pixelCount++; - } - } - } else { - for (let j = 0; j < jLength; j++) { - for (let i = 0; i < iLength; i++) { - var value = volumeData[sliceAccess(i, j)]; - var alpha = 0xff; //apply threshold - - alpha = upperThreshold >= value ? lowerThreshold <= value ? alpha : 0 : 0; //apply window level - - value = Math.floor(255 * (value - windowLow) / (windowHigh - windowLow)); - value = value > 255 ? 255 : value < 0 ? 0 : value | 0; - data[4 * pixelCount] = value; - data[4 * pixelCount + 1] = value; - data[4 * pixelCount + 2] = value; - data[4 * pixelCount + 3] = alpha; - pixelCount++; - } - } - } - - ctx.putImageData(imgData, 0, 0); - this.ctx.drawImage(canvas, 0, 0, iLength, jLength, 0, 0, this.canvas.width, this.canvas.height); - this.mesh.material.map.needsUpdate = true; - }, - - /** - * @member {Function} Refresh the geometry according to axis and index - * @see Volume.extractPerpendicularPlane - * @memberof VolumeSlice - */ - updateGeometry: function () { - var extracted = this.volume.extractPerpendicularPlane(this.axis, this.index); - this.sliceAccess = extracted.sliceAccess; - this.jLength = extracted.jLength; - this.iLength = extracted.iLength; - this.matrix = extracted.matrix; - this.canvas.width = extracted.planeWidth; - this.canvas.height = extracted.planeHeight; - this.canvasBuffer.width = this.iLength; - this.canvasBuffer.height = this.jLength; - this.ctx = this.canvas.getContext('2d'); - this.ctxBuffer = this.canvasBuffer.getContext('2d'); - if (this.geometry) this.geometry.dispose(); // dispose existing geometry - - this.geometry = new PlaneGeometry(extracted.planeWidth, extracted.planeHeight); - - if (this.mesh) { - this.mesh.geometry = this.geometry; //reset mesh matrix - - this.mesh.matrix.identity(); - this.mesh.applyMatrix4(this.matrix); - } - - this.geometryNeedsUpdate = false; - } -}; - -/** - * This class had been written to handle the output of the NRRD loader. - * It contains a volume of data and informations about it. - * For now it only handles 3 dimensional data. - * See the webgl_loader_nrrd.html example and the loaderNRRD.js file to see how to use this class. - * @class - * @param {number} xLength Width of the volume - * @param {number} yLength Length of the volume - * @param {number} zLength Depth of the volume - * @param {string} type The type of data (uint8, uint16, ...) - * @param {ArrayBuffer} arrayBuffer The buffer with volume data - */ - -var Volume = function (xLength, yLength, zLength, type, arrayBuffer) { - if (arguments.length > 0) { - /** - * @member {number} xLength Width of the volume in the IJK coordinate system - */ - this.xLength = Number(xLength) || 1; - /** - * @member {number} yLength Height of the volume in the IJK coordinate system - */ - - this.yLength = Number(yLength) || 1; - /** - * @member {number} zLength Depth of the volume in the IJK coordinate system - */ - - this.zLength = Number(zLength) || 1; - /** - * @member {TypedArray} data Data of the volume - */ - - switch (type) { - case 'Uint8': - case 'uint8': - case 'uchar': - case 'unsigned char': - case 'uint8_t': - this.data = new Uint8Array(arrayBuffer); - break; - - case 'Int8': - case 'int8': - case 'signed char': - case 'int8_t': - this.data = new Int8Array(arrayBuffer); - break; - - case 'Int16': - case 'int16': - case 'short': - case 'short int': - case 'signed short': - case 'signed short int': - case 'int16_t': - this.data = new Int16Array(arrayBuffer); - break; - - case 'Uint16': - case 'uint16': - case 'ushort': - case 'unsigned short': - case 'unsigned short int': - case 'uint16_t': - this.data = new Uint16Array(arrayBuffer); - break; - - case 'Int32': - case 'int32': - case 'int': - case 'signed int': - case 'int32_t': - this.data = new Int32Array(arrayBuffer); - break; - - case 'Uint32': - case 'uint32': - case 'uint': - case 'unsigned int': - case 'uint32_t': - this.data = new Uint32Array(arrayBuffer); - break; - - case 'longlong': - case 'long long': - case 'long long int': - case 'signed long long': - case 'signed long long int': - case 'int64': - case 'int64_t': - case 'ulonglong': - case 'unsigned long long': - case 'unsigned long long int': - case 'uint64': - case 'uint64_t': - throw 'Error in Volume constructor : this type is not supported in JavaScript'; - - case 'Float32': - case 'float32': - case 'float': - this.data = new Float32Array(arrayBuffer); - break; - - case 'Float64': - case 'float64': - case 'double': - this.data = new Float64Array(arrayBuffer); - break; - - default: - this.data = new Uint8Array(arrayBuffer); - } - - if (this.data.length !== this.xLength * this.yLength * this.zLength) { - throw 'Error in Volume constructor, lengths are not matching arrayBuffer size'; - } - } - /** - * @member {Array} spacing Spacing to apply to the volume from IJK to RAS coordinate system - */ - - - this.spacing = [1, 1, 1]; - /** - * @member {Array} offset Offset of the volume in the RAS coordinate system - */ - - this.offset = [0, 0, 0]; - /** - * @member {Martrix3} matrix The IJK to RAS matrix - */ - - this.matrix = new Matrix3(); - this.matrix.identity(); - /** - * @member {Martrix3} inverseMatrix The RAS to IJK matrix - */ - - /** - * @member {number} lowerThreshold The voxels with values under this threshold won't appear in the slices. - * If changed, geometryNeedsUpdate is automatically set to true on all the slices associated to this volume - */ - - var lowerThreshold = -Infinity; - Object.defineProperty(this, 'lowerThreshold', { - get: function () { - return lowerThreshold; - }, - set: function (value) { - lowerThreshold = value; - this.sliceList.forEach(function (slice) { - slice.geometryNeedsUpdate = true; - }); - } - }); - /** - * @member {number} upperThreshold The voxels with values over this threshold won't appear in the slices. - * If changed, geometryNeedsUpdate is automatically set to true on all the slices associated to this volume - */ - - var upperThreshold = Infinity; - Object.defineProperty(this, 'upperThreshold', { - get: function () { - return upperThreshold; - }, - set: function (value) { - upperThreshold = value; - this.sliceList.forEach(function (slice) { - slice.geometryNeedsUpdate = true; - }); - } - }); - /** - * @member {Array} sliceList The list of all the slices associated to this volume - */ - - this.sliceList = []; - /** - * @member {Array} RASDimensions This array holds the dimensions of the volume in the RAS space - */ -}; - -Volume.prototype = { - constructor: Volume, - - /** - * @member {Function} getData Shortcut for data[access(i,j,k)] - * @memberof Volume - * @param {number} i First coordinate - * @param {number} j Second coordinate - * @param {number} k Third coordinate - * @returns {number} value in the data array - */ - getData: function (i, j, k) { - return this.data[k * this.xLength * this.yLength + j * this.xLength + i]; - }, - - /** - * @member {Function} access compute the index in the data array corresponding to the given coordinates in IJK system - * @memberof Volume - * @param {number} i First coordinate - * @param {number} j Second coordinate - * @param {number} k Third coordinate - * @returns {number} index - */ - access: function (i, j, k) { - return k * this.xLength * this.yLength + j * this.xLength + i; - }, - - /** - * @member {Function} reverseAccess Retrieve the IJK coordinates of the voxel corresponding of the given index in the data - * @memberof Volume - * @param {number} index index of the voxel - * @returns {Array} [x,y,z] - */ - reverseAccess: function (index) { - var z = Math.floor(index / (this.yLength * this.xLength)); - var y = Math.floor((index - z * this.yLength * this.xLength) / this.xLength); - var x = index - z * this.yLength * this.xLength - y * this.xLength; - return [x, y, z]; - }, - - /** - * @member {Function} map Apply a function to all the voxels, be careful, the value will be replaced - * @memberof Volume - * @param {Function} functionToMap A function to apply to every voxel, will be called with the following parameters : - * value of the voxel - * index of the voxel - * the data (TypedArray) - * @param {Object} context You can specify a context in which call the function, default if this Volume - * @returns {Volume} this - */ - map: function (functionToMap, context) { - var length = this.data.length; - context = context || this; - - for (let i = 0; i < length; i++) { - this.data[i] = functionToMap.call(context, this.data[i], i, this.data); - } - - return this; - }, - - /** - * @member {Function} extractPerpendicularPlane Compute the orientation of the slice and returns all the information relative to the geometry such as sliceAccess, the plane matrix (orientation and position in RAS coordinate) and the dimensions of the plane in both coordinate system. - * @memberof Volume - * @param {string} axis the normal axis to the slice 'x' 'y' or 'z' - * @param {number} index the index of the slice - * @returns {Object} an object containing all the usefull information on the geometry of the slice - */ - extractPerpendicularPlane: function (axis, RASIndex) { - var iLength, - jLength, - sliceAccess, - planeMatrix = new Matrix4().identity(), - volume = this, - planeWidth, - planeHeight, - firstSpacing, - secondSpacing, - positionOffset, - IJKIndex; - var axisInIJK = new Vector3(), - firstDirection = new Vector3(), - secondDirection = new Vector3(); - var dimensions = new Vector3(this.xLength, this.yLength, this.zLength); - - switch (axis) { - case 'x': - axisInIJK.set(1, 0, 0); - firstDirection.set(0, 0, -1); - secondDirection.set(0, -1, 0); - firstSpacing = this.spacing[2]; - secondSpacing = this.spacing[1]; - IJKIndex = new Vector3(RASIndex, 0, 0); - planeMatrix.multiply(new Matrix4().makeRotationY(Math.PI / 2)); - positionOffset = (volume.RASDimensions[0] - 1) / 2; - planeMatrix.setPosition(new Vector3(RASIndex - positionOffset, 0, 0)); - break; - - case 'y': - axisInIJK.set(0, 1, 0); - firstDirection.set(1, 0, 0); - secondDirection.set(0, 0, 1); - firstSpacing = this.spacing[0]; - secondSpacing = this.spacing[2]; - IJKIndex = new Vector3(0, RASIndex, 0); - planeMatrix.multiply(new Matrix4().makeRotationX(-Math.PI / 2)); - positionOffset = (volume.RASDimensions[1] - 1) / 2; - planeMatrix.setPosition(new Vector3(0, RASIndex - positionOffset, 0)); - break; - - case 'z': - default: - axisInIJK.set(0, 0, 1); - firstDirection.set(1, 0, 0); - secondDirection.set(0, -1, 0); - firstSpacing = this.spacing[0]; - secondSpacing = this.spacing[1]; - IJKIndex = new Vector3(0, 0, RASIndex); - positionOffset = (volume.RASDimensions[2] - 1) / 2; - planeMatrix.setPosition(new Vector3(0, 0, RASIndex - positionOffset)); - break; - } - - firstDirection.applyMatrix4(volume.inverseMatrix).normalize(); - firstDirection.argVar = 'i'; - secondDirection.applyMatrix4(volume.inverseMatrix).normalize(); - secondDirection.argVar = 'j'; - axisInIJK.applyMatrix4(volume.inverseMatrix).normalize(); - iLength = Math.floor(Math.abs(firstDirection.dot(dimensions))); - jLength = Math.floor(Math.abs(secondDirection.dot(dimensions))); - planeWidth = Math.abs(iLength * firstSpacing); - planeHeight = Math.abs(jLength * secondSpacing); - IJKIndex = Math.abs(Math.round(IJKIndex.applyMatrix4(volume.inverseMatrix).dot(axisInIJK))); - var base = [new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1)]; - var iDirection = [firstDirection, secondDirection, axisInIJK].find(function (x) { - return Math.abs(x.dot(base[0])) > 0.9; - }); - var jDirection = [firstDirection, secondDirection, axisInIJK].find(function (x) { - return Math.abs(x.dot(base[1])) > 0.9; - }); - var kDirection = [firstDirection, secondDirection, axisInIJK].find(function (x) { - return Math.abs(x.dot(base[2])) > 0.9; - }); - - sliceAccess = function (i, j) { - var accessI, accessJ, accessK; - var si = iDirection === axisInIJK ? IJKIndex : iDirection.argVar === 'i' ? i : j; - var sj = jDirection === axisInIJK ? IJKIndex : jDirection.argVar === 'i' ? i : j; - var sk = kDirection === axisInIJK ? IJKIndex : kDirection.argVar === 'i' ? i : j; // invert indices if necessary - - var accessI = iDirection.dot(base[0]) > 0 ? si : volume.xLength - 1 - si; - var accessJ = jDirection.dot(base[1]) > 0 ? sj : volume.yLength - 1 - sj; - var accessK = kDirection.dot(base[2]) > 0 ? sk : volume.zLength - 1 - sk; - return volume.access(accessI, accessJ, accessK); - }; - - return { - iLength: iLength, - jLength: jLength, - sliceAccess: sliceAccess, - matrix: planeMatrix, - planeWidth: planeWidth, - planeHeight: planeHeight - }; - }, - - /** - * @member {Function} extractSlice Returns a slice corresponding to the given axis and index - * The coordinate are given in the Right Anterior Superior coordinate format - * @memberof Volume - * @param {string} axis the normal axis to the slice 'x' 'y' or 'z' - * @param {number} index the index of the slice - * @returns {VolumeSlice} the extracted slice - */ - extractSlice: function (axis, index) { - var slice = new VolumeSlice(this, index, axis); - this.sliceList.push(slice); - return slice; - }, - - /** - * @member {Function} repaintAllSlices Call repaint on all the slices extracted from this volume - * @see VolumeSlice.repaint - * @memberof Volume - * @returns {Volume} this - */ - repaintAllSlices: function () { - this.sliceList.forEach(function (slice) { - slice.repaint(); - }); - return this; - }, - - /** - * @member {Function} computeMinMax Compute the minimum and the maximum of the data in the volume - * @memberof Volume - * @returns {Array} [min,max] - */ - computeMinMax: function () { - var min = Infinity; - var max = -Infinity; // buffer the length - - var datasize = this.data.length; - var i = 0; - - for (i = 0; i < datasize; i++) { - if (!isNaN(this.data[i])) { - var value = this.data[i]; - min = Math.min(min, value); - max = Math.max(max, value); - } - } - - this.min = min; - this.max = max; - return [min, max]; - } -}; - -var CSS2DObject = function (element) { - Object3D.call(this); - this.element = element || document.createElement('div'); - this.element.style.position = 'absolute'; - this.addEventListener('removed', function () { - this.traverse(function (object) { - if (object.element instanceof Element && object.element.parentNode !== null) { - object.element.parentNode.removeChild(object.element); - } - }); - }); -}; - -CSS2DObject.prototype = Object.assign(Object.create(Object3D.prototype), { - constructor: CSS2DObject, - copy: function (source, recursive) { - Object3D.prototype.copy.call(this, source, recursive); - this.element = source.element.cloneNode(true); - return this; - } -}); // - -/** - * Based on http://www.emagix.net/academic/mscs-project/item/camera-sync-with-css3-and-webgl-threejs - */ - -var CSS3DObject = function (element) { - Object3D.call(this); - this.element = element || document.createElement('div'); - this.element.style.position = 'absolute'; - this.element.style.pointerEvents = 'auto'; - this.addEventListener('removed', function () { - this.traverse(function (object) { - if (object.element instanceof Element && object.element.parentNode !== null) { - object.element.parentNode.removeChild(object.element); - } - }); - }); -}; - -CSS3DObject.prototype = Object.assign(Object.create(Object3D.prototype), { - constructor: CSS3DObject, - copy: function (source, recursive) { - Object3D.prototype.copy.call(this, source, recursive); - this.element = source.element.cloneNode(true); - return this; - } -}); - -var CSS3DSprite = function (element) { - CSS3DObject.call(this, element); -}; - -CSS3DSprite.prototype = Object.create(CSS3DObject.prototype); -CSS3DSprite.prototype.constructor = CSS3DSprite; // - -var SVGObject = function (node) { - Object3D.call(this); - this.node = node; -}; - -SVGObject.prototype = Object.create(Object3D.prototype); -SVGObject.prototype.constructor = SVGObject; - -function _defineProperty$1(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -new Matrix4(); - -/** - * @param {Array} geometries - * @param {Boolean} useGroups - * @return {BufferGeometry} - */ -const mergeBufferGeometries = (geometries, useGroups) => { - const isIndexed = geometries[0].index !== null; - const attributesUsed = new Set(Object.keys(geometries[0].attributes)); - const morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes)); - const attributes = {}; - const morphAttributes = {}; - const morphTargetsRelative = geometries[0].morphTargetsRelative; - const mergedGeometry = new BufferGeometry(); - let offset = 0; - geometries.forEach((geom, i) => { - let attributesCount = 0; // ensure that all geometries are indexed, or none - - if (isIndexed !== (geom.index !== null)) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.'); - return null; - } // gather attributes, exit early if they're different - - - for (let name in geom.attributes) { - if (!attributesUsed.has(name)) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.'); - return null; - } - - if (attributes[name] === undefined) { - attributes[name] = []; - } - - attributes[name].push(geom.attributes[name]); - attributesCount++; - } // ensure geometries have the same number of attributes - - - if (attributesCount !== attributesUsed.size) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.'); - return null; - } // gather morph attributes, exit early if they're different - - - if (morphTargetsRelative !== geom.morphTargetsRelative) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.'); - return null; - } - - for (let name in geom.morphAttributes) { - if (!morphAttributesUsed.has(name)) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.'); - return null; - } - - if (morphAttributes[name] === undefined) morphAttributes[name] = []; - morphAttributes[name].push(geom.morphAttributes[name]); - } // gather .userData - - - mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || []; - mergedGeometry.userData.mergedUserData.push(geom.userData); - - if (useGroups) { - let count; - - if (geom.index) { - count = geom.index.count; - } else if (geom.attributes.position !== undefined) { - count = geom.attributes.position.count; - } else { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute'); - return null; - } - - mergedGeometry.addGroup(offset, count, i); - offset += count; - } - }); // merge indices - - if (isIndexed) { - let indexOffset = 0; - const mergedIndex = []; - geometries.forEach(geom => { - const index = geom.index; - - for (let j = 0; j < index.count; ++j) { - mergedIndex.push(index.getX(j) + indexOffset); - } - - indexOffset += geom.attributes.position.count; - }); - mergedGeometry.setIndex(mergedIndex); - } // merge attributes - - - for (let name in attributes) { - const mergedAttribute = mergeBufferAttributes(attributes[name]); - - if (!mergedAttribute) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.'); - return null; - } - - mergedGeometry.setAttribute(name, mergedAttribute); - } // merge morph attributes - - - for (let name in morphAttributes) { - const numMorphTargets = morphAttributes[name][0].length; - if (numMorphTargets === 0) break; - mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {}; - mergedGeometry.morphAttributes[name] = []; - - for (let i = 0; i < numMorphTargets; ++i) { - const morphAttributesToMerge = []; - - for (let j = 0; j < morphAttributes[name].length; ++j) { - morphAttributesToMerge.push(morphAttributes[name][j][i]); - } - - const mergedMorphAttribute = mergeBufferAttributes(morphAttributesToMerge); - - if (!mergedMorphAttribute) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.'); - return null; - } - - mergedGeometry.morphAttributes[name].push(mergedMorphAttribute); - } - } - - return mergedGeometry; -}; -/** - * @param {Array} attributes - * @return {BufferAttribute} - */ - -const mergeBufferAttributes = attributes => { - let TypedArray = undefined; - let itemSize = undefined; - let normalized = undefined; - let arrayLength = 0; - attributes.forEach(attr => { - if (TypedArray === undefined) { - TypedArray = attr.array.constructor; - } - - if (TypedArray !== attr.array.constructor) { - console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.'); - return null; - } - - if (itemSize === undefined) itemSize = attr.itemSize; - - if (itemSize !== attr.itemSize) { - console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.'); - return null; - } - - if (normalized === undefined) normalized = attr.normalized; - - if (normalized !== attr.normalized) { - console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.'); - return null; - } - - arrayLength += attr.array.length; - }); - - if (TypedArray && itemSize) { - // @ts-expect-error this works in JS and TS is complaining but it's such a tiny thing I can live with the guilt - const array = new TypedArray(arrayLength); - let offset = 0; - attributes.forEach(attr => { - array.set(attr.array, offset); - offset += attr.array.length; - }); - return new BufferAttribute(array, itemSize, normalized); - } -}; - -new Vector3(); - new Vector3(); - -const NodeShaderStage = { - Vertex: 'vertex', - Fragment: 'fragment' -}; -const NodeUpdateType = { - None: 'none', - Frame: 'frame', - Object: 'object' -}; - -const getNodesKeys = object => { - const props = []; - - for (const name in object) { - const value = object[name]; - - if (value && value.isNode === true) { - props.push(name); - } - } - - return props; -}; -const getValueType = value => { - if (typeof value === 'number') { - return 'float'; - } else if (typeof value === 'boolean') { - return 'bool'; - } else if ((value === null || value === void 0 ? void 0 : value.isVector2) === true) { - return 'vec2'; - } else if ((value === null || value === void 0 ? void 0 : value.isVector3) === true) { - return 'vec3'; - } else if ((value === null || value === void 0 ? void 0 : value.isVector4) === true) { - return 'vec4'; - } else if ((value === null || value === void 0 ? void 0 : value.isMatrix3) === true) { - return 'mat3'; - } else if ((value === null || value === void 0 ? void 0 : value.isMatrix4) === true) { - return 'mat4'; - } else if ((value === null || value === void 0 ? void 0 : value.isColor) === true) { - return 'color'; - } - - return null; -}; -const getValueFromType = (type, ...params) => { - const last4 = type === null || type === void 0 ? void 0 : type.slice(-4); - - if (type === 'color') { - return new Color(...params); - } else if (last4 === 'vec2') { - return new Vector2(...params); - } else if (last4 === 'vec3') { - return new Vector3(...params); - } else if (last4 === 'vec4') { - return new Vector4(...params); - } else if (last4 === 'mat3') { - return new Matrix3(...params); - } else if (last4 === 'mat4') { - return new Matrix4(...params); - } else if (type === 'bool') { - return false; - } else if (type === 'float' || type === 'int' || type === 'uint') { - return 0; - } - - return null; -}; - -let _nodeId = 0; - -class Node { - constructor(nodeType = null) { - this.nodeType = nodeType; - this.updateType = NodeUpdateType.None; - this.uuid = MathUtils.generateUUID(); - Object.defineProperty(this, 'id', { - value: _nodeId++ - }); - } - - get type() { - return this.constructor.name; - } - - getHash() { - return this.uuid; - } - - getUpdateType() { - return this.updateType; - } - - getNodeType() { - return this.nodeType; - } - - update() { - console.warn('Abstract function.'); - } - - generate() { - console.warn('Abstract function.'); - } - - analyze(builder) { - const hash = this.getHash(builder); - const sharedNode = builder.getNodeFromHash(hash); - - if (sharedNode !== undefined && this !== sharedNode) { - return sharedNode.analyze(builder); - } - - const nodeData = builder.getDataFromNode(this); - nodeData.dependenciesCount = nodeData.dependenciesCount === undefined ? 1 : nodeData.dependenciesCount + 1; - const nodeKeys = getNodesKeys(this); - - for (const property of nodeKeys) { - this[property].analyze(builder); - } - } - - build(builder, output = null) { - const hash = this.getHash(builder); - const sharedNode = builder.getNodeFromHash(hash); - - if (sharedNode !== undefined && this !== sharedNode) { - return sharedNode.build(builder, output); - } - - builder.addNode(this); - builder.addStack(this); - const nodeData = builder.getDataFromNode(this); - const isGenerateOnce = this.generate.length === 1; - let snippet = null; - - if (isGenerateOnce) { - const type = this.getNodeType(builder); - snippet = nodeData.snippet; - - if (snippet === undefined) { - snippet = this.generate(builder) || ''; - nodeData.snippet = snippet; - } - - snippet = builder.format(snippet, type, output); - } else { - snippet = this.generate(builder, output) || ''; - } - - builder.removeStack(this); - return snippet; - } - - serialize(json) { - const nodeKeys = getNodesKeys(this); - - if (nodeKeys.length > 0) { - const inputNodes = {}; - - for (const property of nodeKeys) { - inputNodes[property] = this[property].toJSON(json.meta).uuid; - } - - json.inputNodes = inputNodes; - } - } - - deserialize(json) { - if (json.inputNodes !== undefined) { - const nodes = json.meta.nodes; - - for (const property in json.inputNodes) { - const uuid = json.inputNodes[property]; - this[property] = nodes[uuid]; - } - } - } - - toJSON(meta) { - const { - uuid, - type - } = this; - const isRoot = meta === undefined || typeof meta === 'string'; - - if (isRoot) { - meta = { - textures: {}, - images: {}, - nodes: {} - }; - } // serialize - - - let data = meta.nodes[uuid]; - - if (data === undefined) { - data = { - uuid, - type, - meta, - metadata: { - version: 4.5, - type: 'Node', - generator: 'Node.toJSON' - } - }; - meta.nodes[data.uuid] = data; - this.serialize(data); - delete data.meta; - } // TODO: Copied from Object3D.toJSON - - - function extractFromCache(cache) { - const values = []; - - for (const key in cache) { - const data = cache[key]; - delete data.metadata; - values.push(data); - } - - return values; - } - - if (isRoot) { - const textures = extractFromCache(meta.textures); - const images = extractFromCache(meta.images); - const nodes = extractFromCache(meta.nodes); - if (textures.length > 0) data.textures = textures; - if (images.length > 0) data.images = images; - if (nodes.length > 0) data.nodes = nodes; - } - - return data; - } - -} - -Node.prototype.isNode = true; - -class InputNode extends Node { - constructor(value, nodeType = null) { - super(nodeType); - this.value = value; - } - - getNodeType() { - if (this.nodeType === null) { - return getValueType(this.value); - } - - return this.nodeType; - } - - getInputType(builder) { - return this.getNodeType(builder); - } - - serialize(data) { - var _this$value, _this$value$toArray; - - super.serialize(data); - data.value = ((_this$value = this.value) === null || _this$value === void 0 ? void 0 : (_this$value$toArray = _this$value.toArray) === null || _this$value$toArray === void 0 ? void 0 : _this$value$toArray.call(_this$value)) || this.value; - data.valueType = getValueType(this.value); - data.nodeType = this.nodeType; - } - - deserialize(data) { - var _this$value2, _this$value2$fromArra; - - super.deserialize(data); - this.nodeType = data.nodeType; - this.value = getValueFromType(data.valueType); - this.value = ((_this$value2 = this.value) === null || _this$value2 === void 0 ? void 0 : (_this$value2$fromArra = _this$value2.fromArray) === null || _this$value2$fromArra === void 0 ? void 0 : _this$value2$fromArra.call(_this$value2, data.value)) || data.value; - } - - generate() { - console.warn('Abstract function.'); - } - -} - -InputNode.prototype.isInputNode = true; - -class UniformNode extends InputNode { - getUniformHash(builder) { - return this.getHash(builder); - } - - generate(builder, output) { - const type = this.getNodeType(builder); - const hash = this.getUniformHash(builder); - let sharedNode = builder.getNodeFromHash(hash); - - if (sharedNode === undefined) { - builder.setHashNode(this, hash); - sharedNode = this; - } - - const sharedNodeType = sharedNode.getInputType(builder); - const nodeUniform = builder.getUniformFromNode(sharedNode, builder.shaderStage, sharedNodeType); - const propertyName = builder.getPropertyName(nodeUniform); - return builder.format(propertyName, type, output); - } - -} - -UniformNode.prototype.isUniformNode = true; - -class ArrayUniformNode extends UniformNode { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - - getNodeType(builder) { - return this.nodes[0].getNodeType(builder); - } - -} - -ArrayUniformNode.prototype.isArrayUniformNode = true; - -class VaryNode extends Node { - constructor(node, name = null) { - super(); - this.node = node; - this.name = name; - } - - getHash(builder) { - return this.name || super.getHash(builder); - } - - getNodeType(builder) { - // VaryNode is auto type - return this.node.getNodeType(builder); - } - - generate(builder) { - const type = this.getNodeType(builder); - const node = this.node; - const name = this.name; - const nodeVary = builder.getVaryFromNode(this, type); - - if (name !== null) { - nodeVary.name = name; - } - - const propertyName = builder.getPropertyName(nodeVary, NodeShaderStage.Vertex); // force node run in vertex stage - - builder.flowNodeFromShaderStage(NodeShaderStage.Vertex, node, type, propertyName); - return builder.getPropertyName(nodeVary); - } - -} - -class AttributeNode extends Node { - constructor(attributeName, nodeType) { - super(nodeType); - this._attributeName = attributeName; - } - - getHash(builder) { - return this.getAttributeName(builder); - } - - setAttributeName(attributeName) { - this._attributeName = attributeName; - return this; - } - - getAttributeName() { - return this._attributeName; - } - - generate(builder) { - const attribute = builder.getAttribute(this.getAttributeName(builder), this.getNodeType(builder)); - - if (builder.isShaderStage('vertex')) { - return attribute.name; - } else { - const nodeVary = new VaryNode(this); - return nodeVary.build(builder, attribute.type); - } - } - -} - -class BypassNode extends Node { - constructor(returnNode, callNode) { - super(); - this.outputNode = returnNode; - this.callNode = callNode; - } - - getNodeType(builder) { - return this.outputNode.getNodeType(builder); - } - - generate(builder, output) { - const snippet = this.callNode.build(builder, 'void'); - - if (snippet !== '') { - builder.addFlowCode(snippet); - } - - return this.outputNode.build(builder, output); - } - -} - -BypassNode.prototype.isBypassNode = true; - -class CodeNode extends Node { - constructor(code = '', nodeType = 'code') { - super(nodeType); - this.code = code; - this._includes = []; - } - - setIncludes(includes) { - this._includes = includes; - return this; - } - - getIncludes() { - return this._includes; - } - - generate(builder) { - const includes = this.getIncludes(builder); - - for (const include of includes) { - include.build(builder); - } - - const nodeCode = builder.getCodeFromNode(this, this.getNodeType(builder)); - nodeCode.code = this.code; - return nodeCode.code; - } - -} - -CodeNode.prototype.isCodeNode = true; - -class ConstNode extends InputNode { - generateConst(builder) { - return builder.getConst(this.getNodeType(builder), this.value); - } - - generate(builder, output) { - const type = this.getNodeType(builder); - return builder.format(this.generateConst(builder), type, output); - } - -} - -ConstNode.prototype.isConstNode = true; - -class ContextNode extends Node { - constructor(node, context = {}) { - super(); - this.node = node; - this.context = context; - } - - getNodeType(builder) { - return this.node.getNodeType(builder); - } - - generate(builder, output) { - const previousContext = builder.getContext(); - builder.setContext(Object.assign({}, builder.context, this.context)); - const snippet = this.node.build(builder, output); - builder.setContext(previousContext); - return snippet; - } - -} - -ContextNode.prototype.isContextNode = true; - -class TempNode extends Node { - constructor(type) { - super(type); - } - - build(builder, output) { - const type = builder.getVectorType(this.getNodeType(builder, output)); - const nodeData = builder.getDataFromNode(this); - - if (builder.context.temp !== false && type !== 'void ' && output !== 'void' && nodeData.dependenciesCount > 1) { - if (nodeData.snippet === undefined) { - const snippet = super.build(builder, type); - const nodeVar = builder.getVarFromNode(this, type); - const propertyName = builder.getPropertyName(nodeVar); - builder.addFlowCode(`${propertyName} = ${snippet}`); - nodeData.snippet = snippet; - nodeData.propertyName = propertyName; - } - - return builder.format(nodeData.propertyName, type, output); - } - - return super.build(builder, output); - } - -} - -class ExpressionNode extends TempNode { - constructor(snipped = '', nodeType = 'void') { - super(nodeType); - this.snipped = snipped; - } - - generate(builder) { - const type = this.getNodeType(builder); - const snipped = this.snipped; - - if (type === 'void') { - builder.addFlowCode(snipped); - } else { - return `( ${snipped} )`; - } - } - -} - -const vector = ['x', 'y', 'z', 'w']; - -class PropertyNode extends Node { - constructor(name = null, nodeType = 'vec4') { - super(nodeType); - this.name = name; - } - - getHash(builder) { - return this.name || super.getHash(builder); - } - - generate(builder) { - const nodeVary = builder.getVarFromNode(this, this.getNodeType(builder)); - const name = this.name; - - if (name !== null) { - nodeVary.name = name; - } - - return builder.getPropertyName(nodeVary); - } - -} - -class VarNode extends Node { - constructor(node, name = null, nodeType = null) { - super(nodeType); - this.node = node; - this.name = name; - } - - getHash(builder) { - return this.name || super.getHash(builder); - } - - getNodeType(builder) { - return super.getNodeType(builder) || this.node.getNodeType(builder); - } - - generate(builder) { - const type = builder.getVectorType(this.getNodeType(builder)); - const node = this.node; - const name = this.name; - const snippet = node.build(builder, type); - const nodeVar = builder.getVarFromNode(this, type); - - if (name !== null) { - nodeVar.name = name; - } - - const propertyName = builder.getPropertyName(nodeVar); - builder.addFlowCode(`${propertyName} = ${snippet}`); - return propertyName; - } - -} - -VarNode.prototype.isVarNode = true; - -class BufferNode extends UniformNode { - constructor(value, bufferType, bufferCount = 0) { - super(value, bufferType); - this.bufferType = bufferType; - this.bufferCount = bufferCount; - } - - getInputType() { - return 'buffer'; - } - -} - -BufferNode.prototype.isBufferNode = true; - -class Object3DNode extends Node { - constructor(scope = Object3DNode.VIEW_MATRIX, object3d = null) { - super(); - this.scope = scope; - this.object3d = object3d; - this.updateType = NodeUpdateType.Object; - this._uniformNode = new UniformNode(null); - } - - getNodeType() { - const scope = this.scope; - - if (scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX) { - return 'mat4'; - } else if (scope === Object3DNode.NORMAL_MATRIX) { - return 'mat3'; - } else if (scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION) { - return 'vec3'; - } - } - - update(frame) { - const object = this.object3d !== null ? this.object3d : frame.object; - const uniformNode = this._uniformNode; - const camera = frame.camera; - const scope = this.scope; - - if (scope === Object3DNode.VIEW_MATRIX) { - uniformNode.value = object.modelViewMatrix; - } else if (scope === Object3DNode.NORMAL_MATRIX) { - uniformNode.value = object.normalMatrix; - } else if (scope === Object3DNode.WORLD_MATRIX) { - uniformNode.value = object.matrixWorld; - } else if (scope === Object3DNode.POSITION) { - uniformNode.value.setFromMatrixPosition(object.matrixWorld); - } else if (scope === Object3DNode.VIEW_POSITION) { - uniformNode.value.setFromMatrixPosition(object.matrixWorld); - uniformNode.value.applyMatrix4(camera.matrixWorldInverse); - } - } - - generate(builder) { - const scope = this.scope; - - if (scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX) { - this._uniformNode.nodeType = 'mat4'; - } else if (scope === Object3DNode.NORMAL_MATRIX) { - this._uniformNode.nodeType = 'mat3'; - } else if (scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION) { - this._uniformNode.nodeType = 'vec3'; - this._uniformNode.value = new Vector3(); - } - - return this._uniformNode.build(builder); - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - } - -} - -_defineProperty$1(Object3DNode, "VIEW_MATRIX", 'viewMatrix'); - -_defineProperty$1(Object3DNode, "NORMAL_MATRIX", 'normalMatrix'); - -_defineProperty$1(Object3DNode, "WORLD_MATRIX", 'worldMatrix'); - -_defineProperty$1(Object3DNode, "POSITION", 'position'); - -_defineProperty$1(Object3DNode, "VIEW_POSITION", 'viewPosition'); - -class CameraNode extends Object3DNode { - constructor(scope = CameraNode.POSITION) { - super(scope); - } - - getNodeType(builder) { - const scope = this.scope; - - if (scope === CameraNode.PROJECTION_MATRIX) { - return 'mat4'; - } - - return super.getNodeType(builder); - } - - update(frame) { - const camera = frame.camera; - const uniformNode = this._uniformNode; - const scope = this.scope; - - if (scope === CameraNode.PROJECTION_MATRIX) { - uniformNode.value = camera.projectionMatrix; - } else if (scope === CameraNode.VIEW_MATRIX) { - uniformNode.value = camera.matrixWorldInverse; - } else { - this.object3d = camera; - super.update(frame); - } - } - - generate(builder) { - const scope = this.scope; - - if (scope === CameraNode.PROJECTION_MATRIX) { - this._uniformNode.nodeType = 'mat4'; - } - - return super.generate(builder); - } - -} - -_defineProperty$1(CameraNode, "PROJECTION_MATRIX", 'projectionMatrix'); - -class UVNode extends AttributeNode { - constructor(index = 0) { - super(null, 'vec2'); - this.index = index; - } - - getAttributeName() { - const index = this.index; - return 'uv' + (index > 0 ? index + 1 : ''); - } - - serialize(data) { - super.serialize(data); - data.index = this.index; - } - - deserialize(data) { - super.deserialize(data); - this.index = data.index; - } - -} - -UVNode.prototype.isUVNode = true; - -class TextureNode extends UniformNode { - constructor(value, uvNode = new UVNode(), biasNode = null) { - super(value, 'vec4'); - this.uvNode = uvNode; - this.biasNode = biasNode; - } - - getUniformHash() { - return this.value.uuid; - } - - getInputType() { - return 'texture'; - } - - generate(builder, output) { - const texture = this.value; - - if (!texture || texture.isTexture !== true) { - throw new Error('TextureNode: Need a three.js texture.'); - } - - const textureProperty = super.generate(builder, 'texture'); - - if (output === 'sampler') { - return textureProperty + '_sampler'; - } else if (builder.isReference(output)) { - return textureProperty; - } else { - const nodeData = builder.getDataFromNode(this); - let snippet = nodeData.snippet; - - if (snippet === undefined) { - const uvSnippet = this.uvNode.build(builder, 'vec2'); - const biasNode = this.biasNode; - - if (biasNode !== null) { - const biasSnippet = biasNode.build(builder, 'float'); - snippet = builder.getTextureBias(textureProperty, uvSnippet, biasSnippet); - } else { - snippet = builder.getTexture(textureProperty, uvSnippet); - } - - nodeData.snippet = snippet; - } - - return builder.format(snippet, 'vec4', output); - } - } - - serialize(data) { - super.serialize(data); - data.value = this.value.toJSON(data.meta).uuid; - } - - deserialize(data) { - super.deserialize(data); - this.value = data.meta.textures[data.value]; - } - -} - -TextureNode.prototype.isTextureNode = true; - -class ModelNode extends Object3DNode { - constructor(scope = ModelNode.VIEW_MATRIX) { - super(scope); - } - -} - -class JoinNode extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - - getNodeType(builder) { - return builder.getTypeFromLength(this.nodes.reduce((count, cur) => count + builder.getTypeLength(cur.getNodeType(builder)), 0)); - } - - generate(builder) { - const type = this.getNodeType(builder); - const nodes = this.nodes; - const snippetValues = []; - - for (let i = 0; i < nodes.length; i++) { - const input = nodes[i]; - const inputSnippet = input.build(builder); - snippetValues.push(inputSnippet); - } - - return `${builder.getType(type)}( ${snippetValues.join(', ')} )`; - } - -} - -class SplitNode extends Node { - constructor(node, components = 'x') { - super(); - this.node = node; - this.components = components; - } - - getVectorLength() { - let vectorLength = this.components.length; - - for (const c of this.components) { - vectorLength = Math.max(vector.indexOf(c) + 1, vectorLength); - } - - return vectorLength; - } - - getNodeType(builder) { - return builder.getTypeFromLength(this.components.length); - } - - generate(builder) { - const node = this.node; - const nodeTypeLength = builder.getTypeLength(node.getNodeType(builder)); - - if (nodeTypeLength > 1) { - let type = null; - const componentsLength = this.getVectorLength(); - - if (componentsLength >= nodeTypeLength) { - // need expand the input node - type = builder.getTypeFromLength(this.getVectorLength()); - } - - const nodeSnippet = node.build(builder, type); - return `${nodeSnippet}.${this.components}`; - } else { - // ignore components if node is a float - return node.build(builder); - } - } - - serialize(data) { - super.serialize(data); - data.components = this.components; - } - - deserialize(data) { - super.deserialize(data); - this.components = data.components; - } - -} - -class OperatorNode extends TempNode { - constructor(op, aNode, bNode, ...params) { - super(); - this.op = op; - - if (params.length > 0) { - let finalBNode = bNode; - - for (let i = 0; i < params.length; i++) { - finalBNode = new OperatorNode(op, finalBNode, params[i]); - } - - bNode = finalBNode; - } - - this.aNode = aNode; - this.bNode = bNode; - } - - getNodeType(builder, output) { - const op = this.op; - const aNode = this.aNode; - const bNode = this.bNode; - const typeA = aNode.getNodeType(builder); - const typeB = bNode.getNodeType(builder); - - if (typeA === 'void' || typeB === 'void') { - return 'void'; - } else if (op === '=' || op === '%') { - return typeA; - } else if (op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<') { - return 'int'; - } else if (op === '==' || op === '&&' || op === '||' || op === '^^') { - return 'bool'; - } else if (op === '<' || op === '>' || op === '<=' || op === '>=') { - const typeLength = builder.getTypeLength(output); - return typeLength > 1 ? `bvec${typeLength}` : 'bool'; - } else { - if (typeA === 'float' && builder.isMatrix(typeB)) { - return typeB; - } else if (builder.isMatrix(typeA) && builder.isVector(typeB)) { - // matrix x vector - return builder.getVectorFromMatrix(typeA); - } else if (builder.isVector(typeA) && builder.isMatrix(typeB)) { - // vector x matrix - return builder.getVectorFromMatrix(typeB); - } else if (builder.getTypeLength(typeB) > builder.getTypeLength(typeA)) { - // anytype x anytype: use the greater length vector - return typeB; - } - - return typeA; - } - } - - generate(builder, output) { - const op = this.op; - const aNode = this.aNode; - const bNode = this.bNode; - const type = this.getNodeType(builder, output); - let typeA = null; - let typeB = null; - - if (type !== 'void') { - typeA = aNode.getNodeType(builder); - typeB = bNode.getNodeType(builder); - - if (op === '=') { - typeB = typeA; - } else if (op === '<' || op === '>' || op === '<=' || op === '>=') { - if (builder.isVector(typeA)) { - typeB = typeA; - } else { - typeA = typeB = 'float'; - } - } else if (builder.isMatrix(typeA) && builder.isVector(typeB)) { - // matrix x vector - typeB = builder.getVectorFromMatrix(typeA); - } else if (builder.isVector(typeA) && builder.isMatrix(typeB)) { - // vector x matrix - typeA = builder.getVectorFromMatrix(typeB); - } else { - // anytype x anytype - typeA = typeB = type; - } - } else { - typeA = typeB = type; - } - - const a = aNode.build(builder, typeA); - const b = bNode.build(builder, typeB); - const outputLength = builder.getTypeLength(output); - - if (output !== 'void') { - if (op === '=') { - builder.addFlowCode(`${a} ${this.op} ${b}`); - return a; - } else if (op === '>' && outputLength > 1) { - return builder.format(`${builder.getMethod('greaterThan')}( ${a}, ${b} )`, type, output); - } else if (op === '<=' && outputLength > 1) { - return builder.format(`${builder.getMethod('lessThanEqual')}( ${a}, ${b} )`, type, output); - } else { - return builder.format(`( ${a} ${this.op} ${b} )`, type, output); - } - } else if (typeA !== 'void') { - return builder.format(`${a} ${this.op} ${b}`, type, output); - } - } - - serialize(data) { - super.serialize(data); - data.op = this.op; - } - - deserialize(data) { - super.deserialize(data); - this.op = data.op; - } - -} - -class MathNode extends TempNode { - // 1 input - // 2 inputs - // 3 inputs - constructor(method, aNode, bNode = null, cNode = null) { - super(); - this.method = method; - this.aNode = aNode; - this.bNode = bNode; - this.cNode = cNode; - } - - getInputType(builder) { - const aType = this.aNode.getNodeType(builder); - const bType = this.bNode ? this.bNode.getNodeType(builder) : null; - const cType = this.cNode ? this.cNode.getNodeType(builder) : null; - const aLen = builder.getTypeLength(aType); - const bLen = builder.getTypeLength(bType); - const cLen = builder.getTypeLength(cType); - - if (aLen > bLen && aLen > cLen) { - return aType; - } else if (bLen > cLen) { - return bType; - } else if (cLen > aLen) { - return cType; - } - - return aType; - } - - getNodeType(builder) { - const method = this.method; - - if (method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT) { - return 'float'; - } else if (method === MathNode.CROSS) { - return 'vec3'; - } else { - return this.getInputType(builder); - } - } - - generate(builder, output) { - const method = this.method; - const type = this.getNodeType(builder); - const inputType = this.getInputType(builder); - const a = this.aNode; - const b = this.bNode; - const c = this.cNode; - const isWebGL = builder.renderer.isWebGLRenderer === true; - - if (isWebGL && (method === MathNode.DFDX || method === MathNode.DFDY) && output === 'vec3') { - // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988 - return new JoinNode([new MathNode(method, new SplitNode(a, 'x')), new MathNode(method, new SplitNode(a, 'y')), new MathNode(method, new SplitNode(a, 'z'))]).build(builder); - } else if (method === MathNode.TRANSFORM_DIRECTION) { - // dir can be either a direction vector or a normal vector - // upper-left 3x3 of matrix is assumed to be orthogonal - let tA = a; - let tB = b; - - if (builder.isMatrix(tA.getNodeType(builder))) { - tB = new ExpressionNode(`${builder.getType('vec4')}( ${tB.build(builder, 'vec3')}, 0.0 )`, 'vec4'); - } else { - tA = new ExpressionNode(`${builder.getType('vec4')}( ${tA.build(builder, 'vec3')}, 0.0 )`, 'vec4'); - } - - const mulNode = new SplitNode(new OperatorNode('*', tA, tB), 'xyz'); - return new MathNode(MathNode.NORMALIZE, mulNode).build(builder); - } else if (method === MathNode.SATURATE) { - return builder.format(`clamp( ${a.build(builder, inputType)}, 0.0, 1.0 )`, type, output); - } else if (method === MathNode.NEGATE) { - return builder.format('( -' + a.build(builder, inputType) + ' )', type, output); - } else if (method === MathNode.INVERT) { - return builder.format('( 1.0 - ' + a.build(builder, inputType) + ' )', type, output); - } else { - const params = []; - - if (method === MathNode.CROSS) { - params.push(a.build(builder, type), b.build(builder, type)); - } else if (method === MathNode.STEP) { - params.push(a.build(builder, builder.getTypeLength(a.getNodeType(builder)) === 1 ? 'float' : inputType), b.build(builder, inputType)); - } else if (isWebGL && (method === MathNode.MIN || method === MathNode.MAX) || method === MathNode.MOD) { - params.push(a.build(builder, inputType), b.build(builder, builder.getTypeLength(b.getNodeType(builder)) === 1 ? 'float' : inputType)); - } else if (method === MathNode.REFRACT) { - params.push(a.build(builder, inputType), b.build(builder, inputType), c.build(builder, 'float')); - } else if (method === MathNode.MIX) { - params.push(a.build(builder, inputType), b.build(builder, inputType), c.build(builder, builder.getTypeLength(c.getNodeType(builder)) === 1 ? 'float' : inputType)); - } else { - params.push(a.build(builder, inputType)); - - if (c !== null) { - params.push(b.build(builder, inputType), c.build(builder, inputType)); - } else if (b !== null) { - params.push(b.build(builder, inputType)); - } - } - - return builder.format(`${builder.getMethod(method)}( ${params.join(', ')} )`, type, output); - } - } - - serialize(data) { - super.serialize(data); - data.method = this.method; - } - - deserialize(data) { - super.deserialize(data); - this.method = data.method; - } - -} - -_defineProperty$1(MathNode, "RAD", 'radians'); - -_defineProperty$1(MathNode, "DEG", 'degrees'); - -_defineProperty$1(MathNode, "EXP", 'exp'); - -_defineProperty$1(MathNode, "EXP2", 'exp2'); - -_defineProperty$1(MathNode, "LOG", 'log'); - -_defineProperty$1(MathNode, "LOG2", 'log2'); - -_defineProperty$1(MathNode, "SQRT", 'sqrt'); - -_defineProperty$1(MathNode, "INV_SQRT", 'inversesqrt'); - -_defineProperty$1(MathNode, "FLOOR", 'floor'); - -_defineProperty$1(MathNode, "CEIL", 'ceil'); - -_defineProperty$1(MathNode, "NORMALIZE", 'normalize'); - -_defineProperty$1(MathNode, "FRACT", 'fract'); - -_defineProperty$1(MathNode, "SIN", 'sin'); - -_defineProperty$1(MathNode, "COS", 'cos'); - -_defineProperty$1(MathNode, "TAN", 'tan'); - -_defineProperty$1(MathNode, "ASIN", 'asin'); - -_defineProperty$1(MathNode, "ACOS", 'acos'); - -_defineProperty$1(MathNode, "ATAN", 'atan'); - -_defineProperty$1(MathNode, "ABS", 'abs'); - -_defineProperty$1(MathNode, "SIGN", 'sign'); - -_defineProperty$1(MathNode, "LENGTH", 'length'); - -_defineProperty$1(MathNode, "NEGATE", 'negate'); - -_defineProperty$1(MathNode, "INVERT", 'invert'); - -_defineProperty$1(MathNode, "DFDX", 'dFdx'); - -_defineProperty$1(MathNode, "DFDY", 'dFdy'); - -_defineProperty$1(MathNode, "SATURATE", 'saturate'); - -_defineProperty$1(MathNode, "ROUND", 'round'); - -_defineProperty$1(MathNode, "MIN", 'min'); - -_defineProperty$1(MathNode, "MAX", 'max'); - -_defineProperty$1(MathNode, "MOD", 'mod'); - -_defineProperty$1(MathNode, "STEP", 'step'); - -_defineProperty$1(MathNode, "REFLECT", 'reflect'); - -_defineProperty$1(MathNode, "DISTANCE", 'distance'); - -_defineProperty$1(MathNode, "DOT", 'dot'); - -_defineProperty$1(MathNode, "CROSS", 'cross'); - -_defineProperty$1(MathNode, "POW", 'pow'); - -_defineProperty$1(MathNode, "TRANSFORM_DIRECTION", 'transformDirection'); - -_defineProperty$1(MathNode, "MIX", 'mix'); - -_defineProperty$1(MathNode, "CLAMP", 'clamp'); - -_defineProperty$1(MathNode, "REFRACT", 'refract'); - -_defineProperty$1(MathNode, "SMOOTHSTEP", 'smoothstep'); - -_defineProperty$1(MathNode, "FACEFORWARD", 'faceforward'); - -class PositionNode extends Node { - constructor(scope = PositionNode.LOCAL) { - super('vec3'); - this.scope = scope; - } - - getHash() { - return `position-${this.scope}`; - } - - generate(builder) { - const scope = this.scope; - let outputNode = null; - - if (scope === PositionNode.GEOMETRY) { - outputNode = new AttributeNode('position', 'vec3'); - } else if (scope === PositionNode.LOCAL) { - outputNode = new VaryNode(new PositionNode(PositionNode.GEOMETRY)); - } else if (scope === PositionNode.WORLD) { - const vertexPositionNode = new MathNode(MathNode.TRANSFORM_DIRECTION, new ModelNode(ModelNode.WORLD_MATRIX), new PositionNode(PositionNode.LOCAL)); - outputNode = new VaryNode(vertexPositionNode); - } else if (scope === PositionNode.VIEW) { - const vertexPositionNode = new OperatorNode('*', new ModelNode(ModelNode.VIEW_MATRIX), new PositionNode(PositionNode.LOCAL)); - outputNode = new VaryNode(vertexPositionNode); - } else if (scope === PositionNode.VIEW_DIRECTION) { - const vertexPositionNode = new MathNode(MathNode.NEGATE, new PositionNode(PositionNode.VIEW)); - outputNode = new MathNode(MathNode.NORMALIZE, new VaryNode(vertexPositionNode)); - } - - return outputNode.build(builder, this.getNodeType(builder)); - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - } - -} - -_defineProperty$1(PositionNode, "GEOMETRY", 'geometry'); - -_defineProperty$1(PositionNode, "LOCAL", 'local'); - -_defineProperty$1(PositionNode, "WORLD", 'world'); - -_defineProperty$1(PositionNode, "VIEW", 'view'); - -_defineProperty$1(PositionNode, "VIEW_DIRECTION", 'viewDirection'); - -class NormalNode extends Node { - constructor(scope = NormalNode.LOCAL) { - super('vec3'); - this.scope = scope; - } - - getHash() { - return `normal-${this.scope}`; - } - - generate(builder) { - const scope = this.scope; - let outputNode = null; - - if (scope === NormalNode.GEOMETRY) { - outputNode = new AttributeNode('normal', 'vec3'); - } else if (scope === NormalNode.LOCAL) { - outputNode = new VaryNode(new NormalNode(NormalNode.GEOMETRY)); - } else if (scope === NormalNode.VIEW) { - const vertexNormalNode = new OperatorNode('*', new ModelNode(ModelNode.NORMAL_MATRIX), new NormalNode(NormalNode.LOCAL)); - outputNode = new MathNode(MathNode.NORMALIZE, new VaryNode(vertexNormalNode)); - } else if (scope === NormalNode.WORLD) { - // To use INVERSE_TRANSFORM_DIRECTION only inverse the param order like this: MathNode( ..., Vector, Matrix ); - const vertexNormalNode = new MathNode(MathNode.TRANSFORM_DIRECTION, new NormalNode(NormalNode.VIEW), new CameraNode(CameraNode.VIEW_MATRIX)); - outputNode = new MathNode(MathNode.NORMALIZE, new VaryNode(vertexNormalNode)); - } - - return outputNode.build(builder); - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - } - -} - -_defineProperty$1(NormalNode, "GEOMETRY", 'geometry'); - -_defineProperty$1(NormalNode, "LOCAL", 'local'); - -_defineProperty$1(NormalNode, "WORLD", 'world'); - -_defineProperty$1(NormalNode, "VIEW", 'view'); - -class CondNode extends Node { - constructor(node, ifNode, elseNode) { - super(); - this.node = node; - this.ifNode = ifNode; - this.elseNode = elseNode; - } - - getNodeType(builder) { - const ifType = this.ifNode.getNodeType(builder); - const elseType = this.elseNode.getNodeType(builder); - - if (builder.getTypeLength(elseType) > builder.getTypeLength(ifType)) { - return elseType; - } - - return ifType; - } - - generate(builder) { - const type = this.getNodeType(builder); - const context = { - temp: false - }; - const nodeProperty = new PropertyNode(null, type).build(builder); - const nodeSnippet = new ContextNode(this.node - /*, context*/ - ).build(builder, 'bool'), - ifSnippet = new ContextNode(this.ifNode, context).build(builder, type), - elseSnippet = new ContextNode(this.elseNode, context).build(builder, type); - builder.addFlowCode(`if ( ${nodeSnippet} ) { - -\t\t${nodeProperty} = ${ifSnippet}; - -\t} else { - -\t\t${nodeProperty} = ${elseSnippet}; - -\t}`); - return nodeProperty; - } - -} - -class ArrayElementNode extends Node { - constructor(node, indexNode) { - super(); - this.node = node; - this.indexNode = indexNode; - } - - getNodeType(builder) { - return this.node.getNodeType(builder); - } - - generate(builder) { - const nodeSnippet = this.node.build(builder); - const indexSnippet = this.indexNode.build(builder, 'int'); - return `${nodeSnippet}[ ${indexSnippet} ]`; - } - -} - -class ConvertNode extends Node { - constructor(node, convertTo) { - super(); - this.node = node; - this.convertTo = convertTo; - } - - getNodeType() { - return this.convertTo; - } - - generate(builder) { - const convertTo = this.convertTo; - const node = this.node; - - if (builder.isReference(convertTo) === false) { - const convertToSnippet = builder.getType(convertTo); - const nodeSnippet = node.build(builder, convertTo); - return `${builder.getVectorType(convertToSnippet)}( ${nodeSnippet} )`; - } else { - return node.build(builder, convertTo); - } - } - -} - -// core nodes -const NodeHandler = { - construct(NodeClosure, params) { - const inputs = params.shift(); - return NodeClosure(new ShaderNodeObjects(inputs), ...params); - }, - - get: function (node, prop) { - if (typeof prop === 'string' && node[prop] === undefined) { - if (/^[xyzwrgbastpq]{1,4}$/.test(prop) === true) { - // accessing properties ( swizzle ) - prop = prop.replace(/r|s/g, 'x').replace(/g|t/g, 'y').replace(/b|p/g, 'z').replace(/a|q/g, 'w'); - return new ShaderNodeObject(new SplitNode(node, prop)); - } else if (/^\d+$/.test(prop) === true) { - // accessing array - return new ShaderNodeObject(new ArrayElementNode(node, uint(Number(prop)))); - } - } - - return node[prop]; - } -}; -const nodeObjects = new WeakMap(); - -const ShaderNodeObject = function (obj) { - const type = typeof obj; - - if (type === 'number' || type === 'boolean') { - return new ShaderNodeObject(getAutoTypedConstNode(obj)); - } else if (type === 'object') { - if (obj.isNode === true) { - let nodeObject = nodeObjects.get(obj); - - if (nodeObject === undefined) { - nodeObject = new Proxy(obj, NodeHandler); - nodeObjects.set(obj, nodeObject); - nodeObjects.set(nodeObject, nodeObject); - } - - return nodeObject; - } - } - - return obj; -}; - -const ShaderNodeObjects = function (objects) { - for (const name in objects) { - objects[name] = new ShaderNodeObject(objects[name]); - } - - return objects; -}; - -const getShaderNodeArray = array => { - const len = array.length; - - for (let i = 0; i < len; i++) { - array[i] = new ShaderNodeObject(array[i]); - } - - return array; -}; - -const ShaderNodeProxy = function (NodeClass, scope = null, factor = null) { - if (scope === null) { - return (...params) => { - return new ShaderNodeObject(new NodeClass(...getShaderNodeArray(params))); - }; - } else if (factor === null) { - return (...params) => { - return new ShaderNodeObject(new NodeClass(scope, ...getShaderNodeArray(params))); - }; - } else { - factor = new ShaderNodeObject(factor); - return (...params) => { - return new ShaderNodeObject(new NodeClass(scope, ...getShaderNodeArray(params), factor)); - }; - } -}; - -const ShaderNodeScript = function (jsFunc) { - return (inputs, builder) => { - new ShaderNodeObjects(inputs); - return new ShaderNodeObject(jsFunc(inputs, builder)); - }; -}; - -const bools = [false, true]; -const uints = [0, 1, 2, 3]; -const ints = [-1, -2]; -const floats = [0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / (Math.PI * 2), Math.PI / 2]; -const boolsCacheMap = new Map(); - -for (let bool of bools) boolsCacheMap.set(bool, new ConstNode(bool)); - -const uintsCacheMap = new Map(); - -for (let uint of uints) uintsCacheMap.set(uint, new ConstNode(uint, 'uint')); - -const intsCacheMap = new Map([...uintsCacheMap].map(el => new ConstNode(el.value, 'int'))); - -for (let int of ints) intsCacheMap.set(int, new ConstNode(int, 'int')); - -const floatsCacheMap = new Map([...intsCacheMap].map(el => new ConstNode(el.value))); - -for (let float of floats) floatsCacheMap.set(float, new ConstNode(float)); - -for (let float of floats) floatsCacheMap.set(-float, new ConstNode(-float)); - -const constNodesCacheMap = new Map([...boolsCacheMap, ...floatsCacheMap]); - -const getAutoTypedConstNode = value => { - if (constNodesCacheMap.has(value)) { - return constNodesCacheMap.get(value); - } else if (value.isNode === true) { - return value; - } else { - return new ConstNode(value); - } -}; - -const ConvertType = function (type, cacheMap = null) { - return (...params) => { - if (params.length === 0) { - return nodeObject(new ConstNode(getValueFromType(type), type)); - } else { - if (type === 'color' && params[0].isNode !== true) { - params = [getValueFromType(type, ...params)]; - } - - if (params.length === 1 && cacheMap !== null && cacheMap.has(params[0])) { - return cacheMap.get(params[0]); - } - - const nodes = params.map(getAutoTypedConstNode); - return nodeObject(new ConvertNode(nodes.length === 1 ? nodes[0] : new JoinNode(nodes), type)); - } - }; -}; // -// Node Material Shader Syntax -// - - -const ShaderNode = new Proxy(ShaderNodeScript, NodeHandler); -const nodeObject = val => { - return new ShaderNodeObject(val); -}; -const float = new ConvertType('float', floatsCacheMap); -const uint = new ConvertType('uint', uintsCacheMap); -const vec3 = new ConvertType('vec3'); -const join = (...params) => nodeObject(new JoinNode(getShaderNodeArray(params))); -const cond = (...params) => nodeObject(new CondNode(...getShaderNodeArray(params))); -const addTo = (varNode, ...params) => { - varNode.node = add(varNode.node, ...getShaderNodeArray(params)); - return nodeObject(varNode); -}; -const add = new ShaderNodeProxy(OperatorNode, '+'); -const sub = new ShaderNodeProxy(OperatorNode, '-'); -const mul = new ShaderNodeProxy(OperatorNode, '*'); -const div = new ShaderNodeProxy(OperatorNode, '/'); -new ShaderNodeProxy(OperatorNode, '%'); -const equal = new ShaderNodeProxy(OperatorNode, '=='); -const assign$3 = new ShaderNodeProxy(OperatorNode, '='); -new ShaderNodeProxy(OperatorNode, '<'); -const greaterThan = new ShaderNodeProxy(OperatorNode, '>'); -const lessThanEqual = new ShaderNodeProxy(OperatorNode, '<='); -new ShaderNodeProxy(OperatorNode, '>='); -const and = new ShaderNodeProxy(OperatorNode, '&&'); -new ShaderNodeProxy(OperatorNode, '||'); -new ShaderNodeProxy(OperatorNode, '^^'); -new ShaderNodeProxy(OperatorNode, '&'); -new ShaderNodeProxy(OperatorNode, '|'); -new ShaderNodeProxy(OperatorNode, '^'); -new ShaderNodeProxy(OperatorNode, '<<'); -new ShaderNodeProxy(OperatorNode, '>>'); -const element = new ShaderNodeProxy(ArrayElementNode); -new ShaderNodeObject(new NormalNode(NormalNode.GEOMETRY)); -const normalLocal = new ShaderNodeObject(new NormalNode(NormalNode.LOCAL)); -const normalWorld = new ShaderNodeObject(new NormalNode(NormalNode.WORLD)); -new ShaderNodeObject(new NormalNode(NormalNode.VIEW)); -const transformedNormalView = new ShaderNodeObject(new VarNode(new NormalNode(NormalNode.VIEW), 'TransformedNormalView', 'vec3')); -const positionLocal = new ShaderNodeObject(new PositionNode(PositionNode.LOCAL)); -const positionWorld = new ShaderNodeObject(new PositionNode(PositionNode.WORLD)); -const positionView = new ShaderNodeObject(new PositionNode(PositionNode.VIEW)); -const positionViewDirection = new ShaderNodeObject(new PositionNode(PositionNode.VIEW_DIRECTION)); -new ShaderNodeObject(new ModelNode(ModelNode.VIEW_MATRIX)); -const cameraPosition = new ShaderNodeObject(new CameraNode(CameraNode.POSITION)); -const diffuseColor = new ShaderNodeObject(new PropertyNode('DiffuseColor', 'vec4')); -const roughness = new ShaderNodeObject(new PropertyNode('Roughness', 'float')); -new ShaderNodeObject(new PropertyNode('Metalness', 'float')); -new ShaderNodeObject(new PropertyNode('AlphaTest', 'float')); -const specularColor = new ShaderNodeObject(new PropertyNode('SpecularColor', 'color')); -const abs = new ShaderNodeProxy(MathNode, 'abs'); -new ShaderNodeProxy(MathNode, 'acos'); -new ShaderNodeProxy(MathNode, 'asin'); -new ShaderNodeProxy(MathNode, 'atan'); -new ShaderNodeProxy(MathNode, 'ceil'); -new ShaderNodeProxy(MathNode, 'clamp'); -new ShaderNodeProxy(MathNode, 'cos'); -const cross = new ShaderNodeProxy(MathNode, 'cross'); -new ShaderNodeProxy(MathNode, 'degrees'); -const dFdx = new ShaderNodeProxy(MathNode, 'dFdx'); -const dFdy = new ShaderNodeProxy(MathNode, 'dFdy'); -new ShaderNodeProxy(MathNode, 'distance'); -const dot = new ShaderNodeProxy(MathNode, 'dot'); -new ShaderNodeProxy(MathNode, 'exp'); -const exp2 = new ShaderNodeProxy(MathNode, 'exp2'); -new ShaderNodeProxy(MathNode, 'faceforward'); -const floor = new ShaderNodeProxy(MathNode, 'floor'); -const fract = new ShaderNodeProxy(MathNode, 'fract'); -new ShaderNodeProxy(MathNode, 'invert'); -const inversesqrt = new ShaderNodeProxy(MathNode, 'inversesqrt'); -new ShaderNodeProxy(MathNode, 'length'); -new ShaderNodeProxy(MathNode, 'log'); -new ShaderNodeProxy(MathNode, 'log2'); -const max = new ShaderNodeProxy(MathNode, 'max'); -new ShaderNodeProxy(MathNode, 'min'); -const mix = new ShaderNodeProxy(MathNode, 'mix'); -const mod$1 = new ShaderNodeProxy(MathNode, 'mod'); -const negate$2 = new ShaderNodeProxy(MathNode, 'negate'); -const normalize = new ShaderNodeProxy(MathNode, 'normalize'); -const pow = new ShaderNodeProxy(MathNode, 'pow'); -const pow2 = new ShaderNodeProxy(MathNode, 'pow', 2); -new ShaderNodeProxy(MathNode, 'pow', 3); -new ShaderNodeProxy(MathNode, 'pow', 4); -new ShaderNodeProxy(MathNode, 'radians'); -const reflect = new ShaderNodeProxy(MathNode, 'reflect'); -new ShaderNodeProxy(MathNode, 'refract'); -const round = new ShaderNodeProxy(MathNode, 'round'); -const saturate = new ShaderNodeProxy(MathNode, 'saturate'); -const sign = new ShaderNodeProxy(MathNode, 'sign'); -const sin = new ShaderNodeProxy(MathNode, 'sin'); -const smoothstep = new ShaderNodeProxy(MathNode, 'smoothstep'); -const sqrt = new ShaderNodeProxy(MathNode, 'sqrt'); -new ShaderNodeProxy(MathNode, 'step'); -new ShaderNodeProxy(MathNode, 'tan'); -const transformDirection = new ShaderNodeProxy(MathNode, 'transformDirection'); -const EPSILON = float(1e-6); -float(1e6); - -class ReflectNode extends Node { - constructor(scope = ReflectNode.CUBE) { - super('vec3'); - this.scope = scope; - } - - getHash() { - return `reflect-${this.scope}`; - } - - generate(builder) { - const scope = this.scope; - - if (scope === ReflectNode.VECTOR) { - const cameraToFrag = normalize(sub(positionWorld, cameraPosition)); - const reflectVec = reflect(cameraToFrag, normalWorld); - return reflectVec.build(builder); - } else if (scope === ReflectNode.CUBE) { - const reflectVec = nodeObject(new ReflectNode(ReflectNode.VECTOR)); - const cubeUV = join(negate$2(reflectVec.x), reflectVec.yz); - return cubeUV.build(builder); - } - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - } - -} - -_defineProperty$1(ReflectNode, "VECTOR", 'vector'); - -_defineProperty$1(ReflectNode, "CUBE", 'cube'); - -class CubeTextureNode extends TextureNode { - constructor(value, uvNode = new ReflectNode(), biasNode = null) { - super(value, uvNode, biasNode); - } - - getInputType() { - return 'cubeTexture'; - } - - generate(builder, output) { - const texture = this.value; - - if (!texture || texture.isCubeTexture !== true) { - throw new Error('CubeTextureNode: Need a three.js cube texture.'); - } - - const textureProperty = UniformNode.prototype.generate.call(this, builder, 'cubeTexture'); - - if (output === 'sampler') { - return textureProperty + '_sampler'; - } else if (builder.isReference(output)) { - return textureProperty; - } else { - const nodeData = builder.getDataFromNode(this); - let snippet = nodeData.snippet; - - if (snippet === undefined) { - const uvSnippet = this.uvNode.build(builder, 'vec3'); - const biasNode = this.biasNode; - - if (biasNode !== null) { - const biasSnippet = biasNode.build(builder, 'float'); - snippet = builder.getCubeTextureBias(textureProperty, uvSnippet, biasSnippet); - } else { - snippet = builder.getCubeTexture(textureProperty, uvSnippet); - } - - nodeData.snippet = snippet; - } - - return builder.format(snippet, 'vec4', output); - } - } - -} - -CubeTextureNode.prototype.isCubeTextureNode = true; - -class ReferenceNode extends Node { - constructor(property, uniformType, object = null) { - super(); - this.property = property; - this.uniformType = uniformType; - this.object = object; - this.node = null; - this.updateType = NodeUpdateType.Object; - this.setNodeType(uniformType); - } - - setNodeType(uniformType) { - this.node = new UniformNode(null, uniformType); - this.nodeType = uniformType; - - if (uniformType === 'color') { - this.nodeType = 'vec3'; - } else if (uniformType === 'texture') { - this.nodeType = 'vec4'; - } - } - - getNodeType() { - return this.uniformType; - } - - update(frame) { - const object = this.object !== null ? this.object : frame.object; - const value = object[this.property]; - this.node.value = value; - } - - generate(builder) { - return this.node.build(builder, this.getNodeType(builder)); - } - -} - -class MaterialReferenceNode extends ReferenceNode { - constructor(property, inputType, material = null) { - super(property, inputType, material); - this.material = material; - } - - update(frame) { - this.object = this.material !== null ? this.material : frame.material; - super.update(frame); - } - -} - -class MaterialNode extends Node { - constructor(scope = MaterialNode.COLOR) { - super(); - this.scope = scope; - } - - getNodeType(builder) { - const scope = this.scope; - const material = builder.context.material; - - if (scope === MaterialNode.COLOR) { - return material.map !== null ? 'vec4' : 'vec3'; - } else if (scope === MaterialNode.OPACITY) { - return 'float'; - } else if (scope === MaterialNode.SPECULAR) { - return 'vec3'; - } else if (scope === MaterialNode.ROUGHNESS || scope === MaterialNode.METALNESS) { - return 'float'; - } - } - - generate(builder, output) { - const material = builder.context.material; - const scope = this.scope; - let node = null; - - if (scope === MaterialNode.ALPHA_TEST) { - node = new MaterialReferenceNode('alphaTest', 'float'); - } else if (scope === MaterialNode.COLOR) { - const colorNode = new MaterialReferenceNode('color', 'color'); - - if (material.map !== null && material.map !== undefined && material.map.isTexture === true) { - node = new OperatorNode('*', colorNode, new MaterialReferenceNode('map', 'texture')); - } else { - node = colorNode; - } - } else if (scope === MaterialNode.OPACITY) { - const opacityNode = new MaterialReferenceNode('opacity', 'float'); - - if (material.alphaMap !== null && material.alphaMap !== undefined && material.alphaMap.isTexture === true) { - node = new OperatorNode('*', opacityNode, new MaterialReferenceNode('alphaMap', 'texture')); - } else { - node = opacityNode; - } - } else if (scope === MaterialNode.SPECULAR) { - const specularColorNode = new MaterialReferenceNode('specularColor', 'color'); - - if (material.specularColorMap !== null && material.specularColorMap !== undefined && material.specularColorMap.isTexture === true) { - node = new OperatorNode('*', specularColorNode, new MaterialReferenceNode('specularColorMap', 'texture')); - } else { - node = specularColorNode; - } - } else { - const outputType = this.getNodeType(builder); - node = new MaterialReferenceNode(scope, outputType); - } - - return node.build(builder, output); - } - -} - -_defineProperty$1(MaterialNode, "ALPHA_TEST", 'alphaTest'); - -_defineProperty$1(MaterialNode, "COLOR", 'color'); - -_defineProperty$1(MaterialNode, "OPACITY", 'opacity'); - -_defineProperty$1(MaterialNode, "SPECULAR", 'specular'); - -_defineProperty$1(MaterialNode, "ROUGHNESS", 'roughness'); - -_defineProperty$1(MaterialNode, "METALNESS", 'metalness'); - -class PointUVNode extends Node { - constructor() { - super('vec2'); - } - - generate() { - return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )'; - } - -} - -PointUVNode.prototype.isPointUVNode = true; - -new ShaderNode((inputs, builder) => { - const { - index, - weight, - bindMatrix, - bindMatrixInverse, - boneMatrices - } = inputs; - const boneMatX = element(boneMatrices, index.x); - const boneMatY = element(boneMatrices, index.y); - const boneMatZ = element(boneMatrices, index.z); - const boneMatW = element(boneMatrices, index.w); // POSITION - - const skinVertex = mul(bindMatrix, positionLocal); - const skinned = add(mul(mul(boneMatX, skinVertex), weight.x), mul(mul(boneMatY, skinVertex), weight.y), mul(mul(boneMatZ, skinVertex), weight.z), mul(mul(boneMatW, skinVertex), weight.w)); - const skinPosition = mul(bindMatrixInverse, skinned).xyz; // NORMAL - - let skinMatrix = add(mul(weight.x, boneMatX), mul(weight.y, boneMatY), mul(weight.z, boneMatZ), mul(weight.w, boneMatW)); - skinMatrix = mul(mul(bindMatrixInverse, skinMatrix), bindMatrix); - const skinNormal = transformDirection(skinMatrix, normalLocal).xyz; // ASSIGNS - - assign$3(positionLocal, skinPosition).build(builder); - assign$3(normalLocal, skinNormal).build(builder); -}); - -const LinearToLinear = new ShaderNode(inputs => { - return inputs.value; -}); -const LinearTosRGB = new ShaderNode(inputs => { - const { - value - } = inputs; - const rgb = value.rgb; - const a = sub(mul(pow(value.rgb, vec3(0.41666)), 1.055), vec3(0.055)); - const b = mul(rgb, 12.92); - const factor = vec3(lessThanEqual(rgb, vec3(0.0031308))); - const rgbResult = mix(a, b, factor); - return join(rgbResult.r, rgbResult.g, rgbResult.b, value.a); -}); -const EncodingLib = { - LinearToLinear, - LinearTosRGB -}; - -class ColorSpaceNode extends Node { - constructor(method, node) { - super('vec4'); - this.method = method; - this.node = node; - } - - fromEncoding(encoding) { - let method = null; - - if (encoding === LinearEncoding) { - method = 'Linear'; - } else if (encoding === sRGBEncoding) { - method = 'sRGB'; - } - - this.method = 'LinearTo' + method; - return this; - } - - generate(builder) { - const type = this.getNodeType(builder); - const method = this.method; - const node = this.node; - - if (method !== ColorSpaceNode.LINEAR_TO_LINEAR) { - const encodingFunctionNode = EncodingLib[method]; - return encodingFunctionNode({ - value: node - }).build(builder, type); - } else { - return node.build(builder, type); - } - } - -} - -_defineProperty$1(ColorSpaceNode, "LINEAR_TO_LINEAR", 'LinearToLinear'); - -_defineProperty$1(ColorSpaceNode, "LINEAR_TO_SRGB", 'LinearTosRGB'); - -// http://www.thetenthplanet.de/archives/1180 - -new ShaderNode(inputs => { - const { - eye_pos, - surf_norm, - mapN, - faceDirection, - uv - } = inputs; - const q0 = dFdx(eye_pos.xyz); - const q1 = dFdy(eye_pos.xyz); - const st0 = dFdx(uv.st); - const st1 = dFdy(uv.st); - const N = surf_norm; // normalized - - const q1perp = cross(q1, N); - const q0perp = cross(N, q0); - const T = add(mul(q1perp, st0.x), mul(q0perp, st1.x)); - const B = add(mul(q1perp, st0.y), mul(q0perp, st1.y)); - const det = max(dot(T, T), dot(B, B)); - const scale = cond(equal(det, 0), 0, mul(faceDirection, inversesqrt(det))); - return normalize(add(mul(T, mul(mapN.x, scale)), mul(B, mul(mapN.y, scale)), mul(N, mapN.z))); -}); - -const F_Schlick = new ShaderNode(inputs => { - const { - f0, - f90, - dotVH - } = inputs; // Original approximation by Christophe Schlick '94 - // float fresnel = pow( 1.0 - dotVH, 5.0 ); - // Optimized variant (presented by Epic at SIGGRAPH '13) - // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf - - const fresnel = exp2(mul(sub(mul(-5.55473, dotVH), 6.98316), dotVH)); - return add(mul(f0, sub(1.0, fresnel)), mul(f90, fresnel)); -}); // validated - -const BRDF_Lambert = new ShaderNode(inputs => { - return mul(1 / Math.PI, inputs.diffuseColor); // punctual light -}); // validated - -new ShaderNode(inputs => { - const { - lightDistance, - cutoffDistance, - decayExponent - } = inputs; - return cond(and(greaterThan(cutoffDistance, 0), greaterThan(decayExponent, 0)), pow(saturate(add(div(negate$2(lightDistance), cutoffDistance), 1.0)), decayExponent), 1.0); -}); // validated -// -// STANDARD -// -// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2 -// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - -const V_GGX_SmithCorrelated = new ShaderNode(inputs => { - const { - alpha, - dotNL, - dotNV - } = inputs; - const a2 = pow2(alpha); - const gv = mul(dotNL, sqrt(add(a2, mul(sub(1.0, a2), pow2(dotNV))))); - const gl = mul(dotNV, sqrt(add(a2, mul(sub(1.0, a2), pow2(dotNL))))); - return div(0.5, max(add(gv, gl), EPSILON)); -}); // validated -// Microfacet Models for Refraction through Rough Surfaces - equation (33) -// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html -// alpha is "roughness squared" in Disney’s reparameterization - -const D_GGX = new ShaderNode(inputs => { - const { - alpha, - dotNH - } = inputs; - const a2 = pow2(alpha); - const denom = add(mul(pow2(dotNH), sub(a2, 1.0)), 1.0); // avoid alpha = 0 with dotNH = 1 - - return mul(1 / Math.PI, div(a2, pow2(denom))); -}); // validated -// GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility - -const BRDF_GGX = new ShaderNode(inputs => { - const { - lightDirection, - f0, - f90, - roughness - } = inputs; - const alpha = pow2(roughness); // UE4's roughness - - const halfDir = normalize(add(lightDirection, positionViewDirection)); - const dotNL = saturate(dot(transformedNormalView, lightDirection)); - const dotNV = saturate(dot(transformedNormalView, positionViewDirection)); - const dotNH = saturate(dot(transformedNormalView, halfDir)); - const dotVH = saturate(dot(positionViewDirection, halfDir)); - const F = F_Schlick({ - f0, - f90, - dotVH - }); - const V = V_GGX_SmithCorrelated({ - alpha, - dotNL, - dotNV - }); - const D = D_GGX({ - alpha, - dotNH - }); - return mul(F, mul(V, D)); -}); // validated - -const RE_Direct_Physical = new ShaderNode(inputs => { - const { - lightDirection, - lightColor, - directDiffuse, - directSpecular - } = inputs; - const dotNL = saturate(dot(transformedNormalView, lightDirection)); - let irradiance = mul(dotNL, lightColor); - irradiance = mul(irradiance, Math.PI); // punctual light - - addTo(directDiffuse, mul(irradiance, BRDF_Lambert({ - diffuseColor: diffuseColor.rgb - }))); - addTo(directSpecular, mul(irradiance, BRDF_GGX({ - lightDirection, - f0: specularColor, - f90: 1, - roughness - }))); -}); -new ShaderNode((inputs -/*, builder*/ -) => { - // PHYSICALLY_CORRECT_LIGHTS <-> builder.renderer.physicallyCorrectLights === true - RE_Direct_Physical(inputs); -}); - -class TimerNode extends UniformNode { - constructor(scope = TimerNode.LOCAL) { - super(0); - this.scope = scope; - this.scale = 1; - this.updateType = NodeUpdateType.Frame; - } - - update(frame) { - const scope = this.scope; - const scale = this.scale; - - if (scope === TimerNode.LOCAL) { - this.value += frame.deltaTime * scale; - } else if (scope === TimerNode.DELTA) { - this.value = frame.deltaTime * scale; - } else { - // global - this.value = frame.time * scale; - } - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - data.scale = this.scale; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - this.scale = data.scale; - } - -} - -_defineProperty$1(TimerNode, "LOCAL", 'local'); - -_defineProperty$1(TimerNode, "GLOBAL", 'global'); - -_defineProperty$1(TimerNode, "DELTA", 'delta'); - -class OscNode extends Node { - constructor(method = OscNode.SINE, timeNode = new TimerNode()) { - super(); - this.method = method; - this.timeNode = timeNode; - } - - getNodeType(builder) { - return this.timeNode.getNodeType(builder); - } - - generate(builder) { - const method = this.method; - const timeNode = this.timeNode; - let outputNode = null; - - if (method === OscNode.SINE) { - outputNode = add(mul(sin(mul(add(timeNode, 0.75), Math.PI * 2)), 0.5), 0.5); - } else if (method === OscNode.SQUARE) { - outputNode = round(fract(timeNode)); - } else if (method === OscNode.TRIANGLE) { - outputNode = abs(sub(1, mul(fract(add(timeNode, 0.5)), 2))); - } else if (method === OscNode.SAWTOOTH) { - outputNode = fract(timeNode); - } - - return outputNode.build(builder); - } - - serialize(data) { - super.serialize(data); - data.method = this.method; - } - - deserialize(data) { - super.deserialize(data); - this.method = data.method; - } - -} - -_defineProperty$1(OscNode, "SINE", 'sine'); - -_defineProperty$1(OscNode, "SQUARE", 'square'); - -_defineProperty$1(OscNode, "TRIANGLE", 'triangle'); - -_defineProperty$1(OscNode, "SAWTOOTH", 'sawtooth'); - -new ShaderNode(inputs => { - const uv = mul(inputs.uv, 2.0); - const cx = floor(uv.x); - const cy = floor(uv.y); - const result = mod$1(add(cx, cy), 2.0); - return sign(result); -}); - -class FogNode extends Node { - constructor(colorNode, factorNode) { - super('float'); - this.colorNode = colorNode; - this.factorNode = factorNode; - } - - generate(builder) { - return this.factorNode.build(builder, 'float'); - } - -} - -FogNode.prototype.isFogNode = true; - -class FogRangeNode extends FogNode { - constructor(colorNode, nearNode, farNode) { - super(colorNode); - this.nearNode = nearNode; - this.farNode = farNode; - } - - generate(builder) { - this.factorNode = smoothstep(this.nearNode, this.farNode, negate$2(positionView.z)); - return super.generate(builder); - } - -} - -FogRangeNode.prototype.isFogRangeNode = true; - -class GLTFExporter { - constructor() { - _defineProperty$1(this, "pluginCallbacks", void 0); - - this.pluginCallbacks = []; - this.register(function (writer) { - return new GLTFLightExtension(writer); - }); - this.register(function (writer) { - return new GLTFMaterialsUnlitExtension(writer); - }); - this.register(function (writer) { - return new GLTFMaterialsPBRSpecularGlossiness(writer); - }); - this.register(function (writer) { - return new GLTFMaterialsTransmissionExtension(writer); - }); - this.register(function (writer) { - return new GLTFMaterialsVolumeExtension(writer); - }); - } - - register(callback) { - if (this.pluginCallbacks.indexOf(callback) === -1) { - this.pluginCallbacks.push(callback); - } - - return this; - } - - unregister(callback) { - if (this.pluginCallbacks.indexOf(callback) !== -1) { - this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); - } - - return this; - } - - parse(input, onDone, options) { - const writer = new GLTFWriter(); - const plugins = []; - - for (let i = 0, il = this.pluginCallbacks.length; i < il; i++) { - plugins.push(this.pluginCallbacks[i](writer)); - } - - writer.setPlugins(plugins); - writer.write(input, onDone, options); - } - /** - * Static utility functions - */ - - -} //------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - - -_defineProperty$1(GLTFExporter, "Utils", { - insertKeyframe: function (track, time) { - const tolerance = 0.001; // 1ms - - const valueSize = track.getValueSize(); // @ts-expect-error - - const times = new track.TimeBufferType(track.times.length + 1); // @ts-expect-error - - const values = new track.ValueBufferType(track.values.length + valueSize); - /** - * NOTE: createInterpolant does not exist in the type, but it does exist as a property of the class - * https://github.com/mrdoob/three.js/blob/77480d339d737b7505b335101ffd3cf29a30738d/src/animation/KeyframeTrack.js#L117 - */ - // @ts-expect-error - - const interpolant = track.createInterpolant(new track.ValueBufferType(valueSize)); - let index; - - if (track.times.length === 0) { - times[0] = time; - - for (let i = 0; i < valueSize; i++) { - values[i] = 0; - } - - index = 0; - } else if (time < track.times[0]) { - if (Math.abs(track.times[0] - time) < tolerance) return 0; - times[0] = time; - times.set(track.times, 1); - values.set(interpolant.evaluate(time), 0); - values.set(track.values, valueSize); - index = 0; - } else if (time > track.times[track.times.length - 1]) { - if (Math.abs(track.times[track.times.length - 1] - time) < tolerance) { - return track.times.length - 1; - } - - times[times.length - 1] = time; - times.set(track.times, 0); - values.set(track.values, 0); - values.set(interpolant.evaluate(time), track.values.length); - index = times.length - 1; - } else { - for (let i = 0; i < track.times.length; i++) { - if (Math.abs(track.times[i] - time) < tolerance) return i; - - if (track.times[i] < time && track.times[i + 1] > time) { - times.set(track.times.slice(0, i + 1), 0); - times[i + 1] = time; - times.set(track.times.slice(i + 1), i + 2); - values.set(track.values.slice(0, (i + 1) * valueSize), 0); - values.set(interpolant.evaluate(time), (i + 1) * valueSize); - values.set(track.values.slice((i + 1) * valueSize), (i + 2) * valueSize); - index = i + 1; - break; - } - } - } - - track.times = times; - track.values = values; - return index; - }, - mergeMorphTargetTracks: function (clip, root) { - const tracks = []; - const mergedTracks = {}; - const sourceTracks = clip.tracks; - - for (let i = 0; i < sourceTracks.length; ++i) { - let sourceTrack = sourceTracks[i]; - const sourceTrackBinding = PropertyBinding.parseTrackName(sourceTrack.name); - const sourceTrackNode = PropertyBinding.findNode(root, sourceTrackBinding.nodeName); - - if (sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined) { - // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is. - tracks.push(sourceTrack); - continue; - } - - if ( // @ts-expect-error - sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && // @ts-expect-error - sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear) { - // @ts-expect-error - if (sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { - // This should never happen, because glTF morph target animations - // affect all targets already. - throw new Error('THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.'); - } - - console.warn('THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.'); - sourceTrack = sourceTrack.clone(); - sourceTrack.setInterpolation(InterpolateLinear); - } - - const targetCount = sourceTrackNode.morphTargetInfluences.length; - const targetIndex = sourceTrackNode.morphTargetDictionary[sourceTrackBinding.propertyIndex]; - - if (targetIndex === undefined) { - throw new Error('THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex); - } - - let mergedTrack; // If this is the first time we've seen this object, create a new - // track to store merged keyframe data for each morph target. - - if (mergedTracks[sourceTrackNode.uuid] === undefined) { - mergedTrack = sourceTrack.clone(); // @ts-expect-error - - const values = new mergedTrack.ValueBufferType(targetCount * mergedTrack.times.length); - - for (let j = 0; j < mergedTrack.times.length; j++) { - values[j * targetCount + targetIndex] = mergedTrack.values[j]; - } // We need to take into consideration the intended target node - // of our original un-merged morphTarget animation. - - - mergedTrack.name = (sourceTrackBinding.nodeName || '') + '.morphTargetInfluences'; - mergedTrack.values = values; - mergedTracks[sourceTrackNode.uuid] = mergedTrack; - tracks.push(mergedTrack); - continue; - } // @ts-expect-error - - - const sourceInterpolant = sourceTrack.createInterpolant(new sourceTrack.ValueBufferType(1)); - mergedTrack = mergedTracks[sourceTrackNode.uuid]; // For every existing keyframe of the merged track, write a (possibly - // interpolated) value from the source track. - - for (let j = 0; j < mergedTrack.times.length; j++) { - mergedTrack.values[j * targetCount + targetIndex] = sourceInterpolant.evaluate(mergedTrack.times[j]); - } // For every existing keyframe of the source track, write a (possibly - // new) keyframe to the merged track. Values from the previous loop may - // be written again, but keyframes are de-duplicated. - - - for (let j = 0; j < sourceTrack.times.length; j++) { - const keyframeIndex = this.insertKeyframe(mergedTrack, sourceTrack.times[j]); - mergedTrack.values[keyframeIndex * targetCount + targetIndex] = sourceTrack.values[j]; - } - } - - clip.tracks = tracks; - return clip; - } -}); - -const WEBGL_CONSTANTS = { - POINTS: 0x0000, - LINES: 0x0001, - LINE_LOOP: 0x0002, - LINE_STRIP: 0x0003, - TRIANGLES: 0x0004, - TRIANGLE_STRIP: 0x0005, - TRIANGLE_FAN: 0x0006, - UNSIGNED_BYTE: 0x1401, - UNSIGNED_SHORT: 0x1403, - FLOAT: 0x1406, - UNSIGNED_INT: 0x1405, - ARRAY_BUFFER: 0x8892, - ELEMENT_ARRAY_BUFFER: 0x8893, - NEAREST: 0x2600, - LINEAR: 0x2601, - NEAREST_MIPMAP_NEAREST: 0x2700, - LINEAR_MIPMAP_NEAREST: 0x2701, - NEAREST_MIPMAP_LINEAR: 0x2702, - LINEAR_MIPMAP_LINEAR: 0x2703, - CLAMP_TO_EDGE: 33071, - MIRRORED_REPEAT: 33648, - REPEAT: 10497 -}; -const THREE_TO_WEBGL = {}; -THREE_TO_WEBGL[NearestFilter] = WEBGL_CONSTANTS.NEAREST; -THREE_TO_WEBGL[NearestMipmapNearestFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST; -THREE_TO_WEBGL[NearestMipmapLinearFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR; -THREE_TO_WEBGL[LinearFilter] = WEBGL_CONSTANTS.LINEAR; -THREE_TO_WEBGL[LinearMipmapNearestFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST; -THREE_TO_WEBGL[LinearMipmapLinearFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR; -THREE_TO_WEBGL[ClampToEdgeWrapping] = WEBGL_CONSTANTS.CLAMP_TO_EDGE; -THREE_TO_WEBGL[RepeatWrapping] = WEBGL_CONSTANTS.REPEAT; -THREE_TO_WEBGL[MirroredRepeatWrapping] = WEBGL_CONSTANTS.MIRRORED_REPEAT; -const PATH_PROPERTIES = { - scale: 'scale', - position: 'translation', - quaternion: 'rotation', - morphTargetInfluences: 'weights' -}; // GLB constants -// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification - -const GLB_HEADER_BYTES = 12; -const GLB_HEADER_MAGIC = 0x46546c67; -const GLB_VERSION = 2; -const GLB_CHUNK_PREFIX_BYTES = 8; -const GLB_CHUNK_TYPE_JSON = 0x4e4f534a; -const GLB_CHUNK_TYPE_BIN = 0x004e4942; -/** - * Writer - */ - -class GLTFWriter { - constructor() { - _defineProperty$1(this, "plugins", void 0); - - _defineProperty$1(this, "options", void 0); - - _defineProperty$1(this, "pending", void 0); - - _defineProperty$1(this, "buffers", void 0); - - _defineProperty$1(this, "byteOffset", void 0); - - _defineProperty$1(this, "nodeMap", void 0); - - _defineProperty$1(this, "skins", void 0); - - _defineProperty$1(this, "extensionsUsed", void 0); - - _defineProperty$1(this, "uids", void 0); - - _defineProperty$1(this, "uid", void 0); - - _defineProperty$1(this, "json", void 0); - - _defineProperty$1(this, "cache", void 0); - - _defineProperty$1(this, "cachedCanvas", void 0); - - this.plugins = []; - this.options = {}; - this.pending = []; - this.buffers = []; - this.byteOffset = 0; - this.nodeMap = new Map(); - this.skins = []; - this.extensionsUsed = {}; - this.uids = new Map(); - this.uid = 0; - this.json = { - asset: { - version: '2.0', - generator: 'THREE.GLTFExporter' - } - }; - this.cache = { - meshes: new Map(), - attributes: new Map(), - attributesNormalized: new Map(), - materials: new Map(), - textures: new Map(), - images: new Map() - }; - this.cachedCanvas = null; - } - - setPlugins(plugins) { - this.plugins = plugins; - } - /** - * Parse scenes and generate GLTF output - * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes - * @param {Function} onDone Callback on completed - * @param {Object} options options - */ - - - write(input, onDone, options) { - this.options = Object.assign({}, { - // default options - binary: false, - trs: false, - onlyVisible: true, - truncateDrawRange: true, - embedImages: true, - maxTextureSize: Infinity, - animations: [], - includeCustomExtensions: false - }, options); - - if (this.options.animations !== undefined && this.options.animations.length > 0) { - // Only TRS properties, and not matrices, may be targeted by animation. - this.options.trs = true; - } - - this.processInput(input); - const writer = this; - Promise.all(this.pending).then(() => { - const buffers = writer.buffers; - const json = writer.json; - const options = writer.options; - const extensionsUsed = writer.extensionsUsed; // Merge buffers. - - const blob = new Blob(buffers, { - type: 'application/octet-stream' - }); // Declare extensions. - - const extensionsUsedList = Object.keys(extensionsUsed); - if (extensionsUsedList.length > 0) json.extensionsUsed = extensionsUsedList; // Update bytelength of the single buffer. - - if (json.buffers && json.buffers.length > 0) json.buffers[0].byteLength = blob.size; - - if (options.binary) { - // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification - const reader = new window.FileReader(); - reader.readAsArrayBuffer(blob); - - reader.onloadend = () => { - if (reader.result !== null && typeof reader.result !== 'string') { - // Binary chunk. - const binaryChunk = this.getPaddedArrayBuffer(reader.result); - const binaryChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); - binaryChunkPrefix.setUint32(0, binaryChunk.byteLength, true); - binaryChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_BIN, true); // JSON chunk. - - const jsonChunk = this.getPaddedArrayBuffer(this.stringToArrayBuffer(JSON.stringify(json)), 0x20); - const jsonChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); - jsonChunkPrefix.setUint32(0, jsonChunk.byteLength, true); - jsonChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_JSON, true); // GLB header. - - const header = new ArrayBuffer(GLB_HEADER_BYTES); - const headerView = new DataView(header); - headerView.setUint32(0, GLB_HEADER_MAGIC, true); - headerView.setUint32(4, GLB_VERSION, true); - const totalByteLength = GLB_HEADER_BYTES + jsonChunkPrefix.byteLength + jsonChunk.byteLength + binaryChunkPrefix.byteLength + binaryChunk.byteLength; - headerView.setUint32(8, totalByteLength, true); - const glbBlob = new Blob([header, jsonChunkPrefix, jsonChunk, binaryChunkPrefix, binaryChunk], { - type: 'application/octet-stream' - }); - const glbReader = new window.FileReader(); - glbReader.readAsArrayBuffer(glbBlob); - - glbReader.onloadend = function () { - if (glbReader.result !== null && typeof glbReader.result !== 'string') { - onDone(glbReader.result); - } - }; - } - }; - } else { - if (json.buffers && json.buffers.length > 0) { - const reader = new window.FileReader(); - reader.readAsDataURL(blob); - - reader.onloadend = function () { - const base64data = reader.result; - - if (json.buffers !== undefined && base64data !== null) { - json.buffers[0].uri = base64data; - onDone(json); - } - }; - } else { - onDone(json); - } - } - }); - } - /** - * Serializes a userData. - * - * @param {THREE.Object3D|THREE.Material} object - * @param {Object} objectDef - */ - - - serializeUserData(object, objectDef) { - if (Object.keys(object.userData).length === 0) return; - const options = this.options; - const extensionsUsed = this.extensionsUsed; - - try { - const json = JSON.parse(JSON.stringify(object.userData)); - - if (options.includeCustomExtensions && json.gltfExtensions) { - if (objectDef.extensions === undefined) objectDef.extensions = {}; - - for (const extensionName in json.gltfExtensions) { - objectDef.extensions[extensionName] = json.gltfExtensions[extensionName]; - extensionsUsed[extensionName] = true; - } - - delete json.gltfExtensions; - } - - if (Object.keys(json).length > 0) objectDef.extras = json; - } catch (error) { - if (error instanceof Error) { - console.warn("THREE.GLTFExporter: userData of '" + object.name + "' " + "won't be serialized because of JSON.stringify error - " + error.message); - } - } - } - /** - * Assign and return a temporal unique id for an object - * especially which doesn't have .uuid - * @param {Object} object - * @return {Integer} - */ - - - getUID(object) { - if (!this.uids.has(object)) this.uids.set(object, this.uid++); - return this.uids.get(object); - } - /** - * Checks if normal attribute values are normalized. - * - * @param {BufferAttribute} normal - * @returns {Boolean} - */ - - - isNormalizedNormalAttribute(normal) { - const cache = this.cache; - if (cache.attributesNormalized.has(normal)) return false; - const v = new Vector3(); - - for (let i = 0, il = normal.count; i < il; i++) { - // 0.0005 is from glTF-validator - if (Math.abs(v.fromBufferAttribute(normal, i).length() - 1.0) > 0.0005) return false; - } - - return true; - } - /** - * Creates normalized normal buffer attribute. - * - * @param {BufferAttribute} normal - * @returns {BufferAttribute} - * - */ - - - createNormalizedNormalAttribute(normal) { - const cache = this.cache; - if (cache.attributesNormalized.has(normal)) return cache.attributesNormalized.get(normal); - const attribute = normal.clone(); - const v = new Vector3(); - - for (let i = 0, il = attribute.count; i < il; i++) { - v.fromBufferAttribute(attribute, i); - - if (v.x === 0 && v.y === 0 && v.z === 0) { - // if values can't be normalized set (1, 0, 0) - v.setX(1.0); - } else { - v.normalize(); - } - - attribute.setXYZ(i, v.x, v.y, v.z); - } - - cache.attributesNormalized.set(normal, attribute); - return attribute; - } - /** - * Applies a texture transform, if present, to the map definition. Requires - * the KHR_texture_transform extension. - * - * @param {Object} mapDef - * @param {THREE.Texture} texture - */ - - - applyTextureTransform(mapDef, texture) { - let didTransform = false; - const transformDef = {}; - - if (texture.offset.x !== 0 || texture.offset.y !== 0) { - transformDef.offset = texture.offset.toArray(); - didTransform = true; - } - - if (texture.rotation !== 0) { - transformDef.rotation = texture.rotation; - didTransform = true; - } - - if (texture.repeat.x !== 1 || texture.repeat.y !== 1) { - transformDef.scale = texture.repeat.toArray(); - didTransform = true; - } - - if (didTransform) { - mapDef.extensions = mapDef.extensions || {}; - mapDef.extensions['KHR_texture_transform'] = transformDef; - this.extensionsUsed['KHR_texture_transform'] = true; - } - } - /** - * Process a buffer to append to the default one. - * @param {ArrayBuffer} buffer - * @return {Integer} - */ - - - processBuffer(buffer) { - const json = this.json; - const buffers = this.buffers; - if (!json.buffers) json.buffers = [{ - byteLength: 0 - }]; // All buffers are merged before export. - - buffers.push(buffer); - return 0; - } - /** - * Process and generate a BufferView - * @param {BufferAttribute} attribute - * @param {number} componentType - * @param {number} start - * @param {number} count - * @param {number} target (Optional) Target usage of the BufferView - * @return {Object} - */ - - - processBufferView(attribute, componentType, start, count, target) { - const json = this.json; - if (!json.bufferViews) json.bufferViews = []; // Create a new dataview and dump the attribute's array into it - - let componentSize; - - if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) { - componentSize = 1; - } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) { - componentSize = 2; - } else { - componentSize = 4; - } - - const byteLength = this.getPaddedBufferSize(count * attribute.itemSize * componentSize); - const dataView = new DataView(new ArrayBuffer(byteLength)); - let offset = 0; - - for (let i = start; i < start + count; i++) { - for (let a = 0; a < attribute.itemSize; a++) { - let value; - - if (attribute.itemSize > 4) { - // no support for interleaved data for itemSize > 4 - value = attribute.array[i * attribute.itemSize + a]; - } else { - if (a === 0) value = attribute.getX(i);else if (a === 1) value = attribute.getY(i);else if (a === 2) value = attribute.getZ(i);else if (a === 3) value = attribute.getW(i); - } - - if (value !== undefined) { - if (componentType === WEBGL_CONSTANTS.FLOAT) { - dataView.setFloat32(offset, value, true); - } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_INT) { - dataView.setUint32(offset, value, true); - } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) { - dataView.setUint16(offset, value, true); - } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) { - dataView.setUint8(offset, value); - } - } - - offset += componentSize; - } - } - - const bufferViewDef = { - buffer: this.processBuffer(dataView.buffer), - byteOffset: this.byteOffset, - byteLength: byteLength - }; - if (target !== undefined) bufferViewDef.target = target; - - if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) { - // Only define byteStride for vertex attributes. - bufferViewDef.byteStride = attribute.itemSize * componentSize; - } - - this.byteOffset += byteLength; - json.bufferViews.push(bufferViewDef); // @TODO Merge bufferViews where possible. - - const output = { - id: json.bufferViews.length - 1, - byteLength: 0 - }; - return output; - } - /** - * Process and generate a BufferView from an image Blob. - * @param {Blob} blob - * @return {Promise} - */ - - - processBufferViewImage(blob) { - const writer = this; - const json = writer.json; - if (!json.bufferViews) json.bufferViews = []; - return new Promise(resolve => { - const reader = new window.FileReader(); - reader.readAsArrayBuffer(blob); - - reader.onloadend = () => { - if (reader.result !== null && typeof reader.result !== 'string' && json.bufferViews !== undefined) { - const buffer = this.getPaddedArrayBuffer(reader.result); - const bufferViewDef = { - buffer: writer.processBuffer(buffer), - byteOffset: writer.byteOffset, - byteLength: buffer.byteLength - }; - writer.byteOffset += buffer.byteLength; - resolve(json.bufferViews.push(bufferViewDef) - 1); - } - }; - }); - } - /** - * Process attribute to generate an accessor - * @param {BufferAttribute} attribute Attribute to process - * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range - * @param {Integer} start (Optional) - * @param {Integer} count (Optional) - * @return {Integer|null} Index of the processed accessor on the "accessors" array - */ - - - processAccessor(attribute, geometry, start, count) { - const options = this.options; - const json = this.json; - const types = { - 1: 'SCALAR', - 2: 'VEC2', - 3: 'VEC3', - 4: 'VEC4', - 16: 'MAT4' - }; - let componentType; // Detect the component type of the attribute array (float, uint or ushort) - - if (attribute.array.constructor === Float32Array) { - componentType = WEBGL_CONSTANTS.FLOAT; - } else if (attribute.array.constructor === Uint32Array) { - componentType = WEBGL_CONSTANTS.UNSIGNED_INT; - } else if (attribute.array.constructor === Uint16Array) { - componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT; - } else if (attribute.array.constructor === Uint8Array) { - componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE; - } else { - throw new Error('THREE.GLTFExporter: Unsupported bufferAttribute component type.'); - } - - if (start === undefined) start = 0; - if (count === undefined) count = attribute.count; // @TODO Indexed buffer geometry with drawRange not supported yet - - if (options.truncateDrawRange && geometry !== undefined && geometry.index === null) { - const end = start + count; - const end2 = geometry.drawRange.count === Infinity ? attribute.count : geometry.drawRange.start + geometry.drawRange.count; - start = Math.max(start, geometry.drawRange.start); - count = Math.min(end, end2) - start; - if (count < 0) count = 0; - } // Skip creating an accessor if the attribute doesn't have data to export - - - if (count === 0) return null; - const minMax = this.getMinMax(attribute, start, count); - let bufferViewTarget; // If geometry isn't provided, don't infer the target usage of the bufferView. For - // animation samplers, target must not be set. - - if (geometry !== undefined) { - bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER; - } - - if (bufferViewTarget !== undefined) { - const bufferView = this.processBufferView(attribute, componentType, start, count, bufferViewTarget); - const accessorDef = { - bufferView: bufferView.id, - byteOffset: bufferView.byteOffset, - componentType: componentType, - count: count, - max: minMax.max, - min: minMax.min, - type: types[attribute.itemSize] - }; - if (attribute.normalized) accessorDef.normalized = true; - if (!json.accessors) json.accessors = []; - return json.accessors.push(accessorDef) - 1; - } - } - /** - * Process image - * @param {Image} image to process - * @param {Integer} format of the image (RGBAFormat) - * @param {Boolean} flipY before writing out the image - * @return {Integer} Index of the processed texture in the "images" array - */ - - - processImage(image, format, flipY) { - const writer = this; - const cache = writer.cache; - const json = writer.json; - const options = writer.options; - const pending = writer.pending; - if (!cache.images.has(image)) cache.images.set(image, {}); - const cachedImages = cache.images.get(image); - const mimeType = format === RGBAFormat ? 'image/png' : 'image/jpeg'; - const key = mimeType + ':flipY/' + flipY.toString(); - if (cachedImages !== undefined && cachedImages[key] !== undefined) return cachedImages[key]; - if (!json.images) json.images = []; - const imageDef = { - mimeType: mimeType - }; - - if (options.embedImages && options.maxTextureSize !== undefined) { - const canvas = this.cachedCanvas = this.cachedCanvas || document.createElement('canvas'); - canvas.width = Math.min(image.width, options.maxTextureSize); - canvas.height = Math.min(image.height, options.maxTextureSize); - const ctx = canvas.getContext('2d'); - - if (flipY) { - ctx === null || ctx === void 0 ? void 0 : ctx.translate(0, canvas.height); - ctx === null || ctx === void 0 ? void 0 : ctx.scale(1, -1); - } - - if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) { - ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(image, 0, 0, canvas.width, canvas.height); - } else { - if (format !== RGBAFormat) { - console.error('GLTFExporter: Only RGBA format is supported.'); - } - - if (image.width > options.maxTextureSize || image.height > options.maxTextureSize) { - console.warn('GLTFExporter: Image size is bigger than maxTextureSize', image); - } - - const data = new Uint8ClampedArray(image.height * image.width * 4); - - if (image instanceof ImageData) { - for (let i = 0; i < data.length; i += 4) { - data[i + 0] = image.data[i + 0]; - data[i + 1] = image.data[i + 1]; - data[i + 2] = image.data[i + 2]; - data[i + 3] = image.data[i + 3]; - } - } - - ctx === null || ctx === void 0 ? void 0 : ctx.putImageData(new ImageData(data, image.width, image.height), 0, 0); - } - - if (options.binary) { - pending.push(new Promise(function (resolve) { - canvas.toBlob(function (blob) { - if (blob !== null) { - writer.processBufferViewImage(blob).then(function (bufferViewIndex) { - imageDef.bufferView = bufferViewIndex; // @ts-expect-error - - resolve(); - }); - } - }, mimeType); - })); - } else { - imageDef.uri = canvas.toDataURL(mimeType); - } - } else if (image instanceof Image) { - imageDef.uri = image.src; - } - - const index = json.images.push(imageDef) - 1; - if (cachedImages !== undefined) cachedImages[key] = index; - return index; - } - /** - * Process sampler - * @param {Texture} map Texture to process - * @return {Integer} Index of the processed texture in the "samplers" array - */ - - - processSampler(map) { - const json = this.json; - if (!json.samplers) json.samplers = []; - const samplerDef = { - magFilter: THREE_TO_WEBGL[map.magFilter], - minFilter: THREE_TO_WEBGL[map.minFilter], - wrapS: THREE_TO_WEBGL[map.wrapS], - wrapT: THREE_TO_WEBGL[map.wrapT] - }; - return json.samplers.push(samplerDef) - 1; - } - /** - * Process texture - * @param {Texture} map Map to process - * @return {Integer} Index of the processed texture in the "textures" array - */ - - - processTexture(map) { - const cache = this.cache; - const json = this.json; - if (cache.textures.has(map)) return cache.textures.get(map); - if (!json.textures) json.textures = []; - const textureDef = { - sampler: this.processSampler(map), - source: this.processImage(map.image, map.format, map.flipY) - }; - if (map.name) textureDef.name = map.name; - - this._invokeAll(function (ext) { - ext.writeTexture && ext.writeTexture(map, textureDef); - }); - - const index = json.textures.push(textureDef) - 1; - cache.textures.set(map, index); - return index; - } - /** - * Process material - * @param {THREE.Material} material Material to process - * @return {Integer|null} Index of the processed material in the "materials" array - */ - - - processMaterial(material) { - const cache = this.cache; - const json = this.json; - if (cache.materials.has(material)) return cache.materials.get(material); - - if (material instanceof ShaderMaterial && material.isShaderMaterial) { - console.warn('GLTFExporter: THREE.ShaderMaterial not supported.'); - return null; - } - - if (!json.materials) json.materials = []; // @QUESTION Should we avoid including any attribute that has the default value? - - const materialDef = { - pbrMetallicRoughness: {} - }; - - if (!(material instanceof MeshStandardMaterial && material.isMeshStandardMaterial && material instanceof MeshBasicMaterial && // @ts-expect-error - material.isMeshBasicMaterial)) { - console.warn('GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.'); - } - - if (material instanceof MeshStandardMaterial || material instanceof MeshPhysicalMaterial) { - // pbrMetallicRoughness.baseColorFactor - const color = material.color.toArray().concat([material.opacity]); - - if (!this.equalArray(color, [1, 1, 1, 1])) { - materialDef.pbrMetallicRoughness.baseColorFactor = color; - } - } - - if (material instanceof MeshStandardMaterial && material.isMeshStandardMaterial) { - materialDef.pbrMetallicRoughness.metallicFactor = material.metalness; - materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness; - } else { - materialDef.pbrMetallicRoughness.metallicFactor = 0.5; - materialDef.pbrMetallicRoughness.roughnessFactor = 0.5; - } // pbrMetallicRoughness.metallicRoughnessTexture - - - if (material instanceof MeshStandardMaterial && material.metalnessMap || material instanceof MeshStandardMaterial && material.roughnessMap) { - if (material.metalnessMap === material.roughnessMap && material.metalnessMap !== null) { - const metalRoughMapDef = { - index: this.processTexture(material.metalnessMap) - }; - this.applyTextureTransform(metalRoughMapDef, material.metalnessMap); - materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; - } else { - console.warn('THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.'); - } - } // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture - - - if ((material instanceof MeshStandardMaterial || material instanceof MeshPhysicalMaterial) && material.map) { - const baseColorMapDef = { - index: this.processTexture(material.map) - }; - this.applyTextureTransform(baseColorMapDef, material.map); - materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef; - } - - if ((material instanceof MeshStandardMaterial || material instanceof MeshPhysicalMaterial) && material.emissive) { - // note: emissive components are limited to stay within the 0 - 1 range to accommodate glTF spec. see #21849 and #22000. - const emissive = material.emissive.clone().multiplyScalar(material.emissiveIntensity); - const maxEmissiveComponent = Math.max(emissive.r, emissive.g, emissive.b); - - if (maxEmissiveComponent > 1) { - emissive.multiplyScalar(1 / maxEmissiveComponent); - console.warn('THREE.GLTFExporter: Some emissive components exceed 1; emissive has been limited'); - } - - if (maxEmissiveComponent > 0) { - materialDef.emissiveFactor = emissive.toArray(); - } // emissiveTexture - - - if (material.emissiveMap) { - const emissiveMapDef = { - index: this.processTexture(material.emissiveMap) - }; - this.applyTextureTransform(emissiveMapDef, material.emissiveMap); - materialDef.emissiveTexture = emissiveMapDef; - } - } // normalTexture - - - if ((material instanceof MeshMatcapMaterial || material instanceof MeshNormalMaterial || material instanceof MeshPhongMaterial || material instanceof MeshStandardMaterial || material instanceof MeshToonMaterial) && material.normalMap) { - const normalMapDef = { - index: this.processTexture(material.normalMap) - }; - - if (material.normalScale && material.normalScale.x !== 1) { - // glTF normal scale is univariate. Ignore `y`, which may be flipped. - // Context: https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 - normalMapDef.scale = material.normalScale.x; - } - - this.applyTextureTransform(normalMapDef, material.normalMap); - materialDef.normalTexture = normalMapDef; - } // occlusionTexture - - - if ((material instanceof MeshBasicMaterial || material instanceof MeshLambertMaterial || material instanceof MeshPhongMaterial || material instanceof MeshStandardMaterial || material instanceof MeshToonMaterial) && material.aoMap) { - const occlusionMapDef = { - index: this.processTexture(material.aoMap), - texCoord: 1 - }; - - if (material.aoMapIntensity !== 1.0) { - occlusionMapDef.strength = material.aoMapIntensity; - } - - this.applyTextureTransform(occlusionMapDef, material.aoMap); - materialDef.occlusionTexture = occlusionMapDef; - } // alphaMode - - - if (material.transparent) { - materialDef.alphaMode = 'BLEND'; - } else { - if (material.alphaTest > 0.0) { - materialDef.alphaMode = 'MASK'; - materialDef.alphaCutoff = material.alphaTest; - } - } // doubleSided - - - if (material.side === DoubleSide) materialDef.doubleSided = true; - if (material.name !== '') materialDef.name = material.name; - this.serializeUserData(material, materialDef); - - this._invokeAll(function (ext) { - ext.writeMaterial && ext.writeMaterial(material, materialDef); - }); - - const index = json.materials.push(materialDef) - 1; - cache.materials.set(material, index); - return index; - } - /** - * Process mesh - * @param {THREE.Mesh} mesh Mesh to process - * @return {Integer|null} Index of the processed mesh in the "meshes" array - */ - - - processMesh(mesh) { - const cache = this.cache; - const json = this.json; - const meshCacheKeyParts = [mesh.geometry.uuid]; - - if (Array.isArray(mesh.material)) { - for (let i = 0, l = mesh.material.length; i < l; i++) { - meshCacheKeyParts.push(mesh.material[i].uuid); - } - } else { - meshCacheKeyParts.push(mesh.material.uuid); - } - - const meshCacheKey = meshCacheKeyParts.join(':'); - if (cache.meshes.has(meshCacheKey)) return cache.meshes.get(meshCacheKey); - const geometry = mesh.geometry; - let mode; // Use the correct mode - - if (mesh instanceof LineSegments && mesh.isLineSegments) { - mode = WEBGL_CONSTANTS.LINES; - } else if (mesh instanceof LineLoop && mesh.isLineLoop) { - mode = WEBGL_CONSTANTS.LINE_LOOP; - } else if (mesh instanceof Line$2 && mesh.isLine) { - mode = WEBGL_CONSTANTS.LINE_STRIP; - } else if (mesh instanceof Points && mesh.isPoints) { - mode = WEBGL_CONSTANTS.POINTS; - } else { - mode = (mesh.material instanceof MeshBasicMaterial || mesh.material instanceof MeshDepthMaterial || mesh.material instanceof MeshLambertMaterial || mesh.material instanceof MeshNormalMaterial || mesh.material instanceof MeshPhongMaterial || mesh.material instanceof MeshStandardMaterial || mesh.material instanceof MeshToonMaterial || mesh.material instanceof ShaderMaterial) && mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES; - } - - if (!geometry.isBufferGeometry) { - throw new Error('THREE.GLTFExporter: Geometry is not of type THREE.BufferGeometry.'); - } - - const meshDef = {}; - const attributes = {}; - const primitives = []; - const targets = []; // Conversion between attributes names in threejs and gltf spec - - const nameConversion = { - uv: 'TEXCOORD_0', - uv2: 'TEXCOORD_1', - color: 'COLOR_0', - skinWeight: 'WEIGHTS_0', - skinIndex: 'JOINTS_0' - }; - const originalNormal = geometry.getAttribute('normal'); - - if (originalNormal !== undefined && !(originalNormal instanceof InterleavedBufferAttribute) && !this.isNormalizedNormalAttribute(originalNormal)) { - console.warn('THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.'); - geometry.setAttribute('normal', this.createNormalizedNormalAttribute(originalNormal)); - } // @QUESTION Detect if .vertexColors = true? - // For every attribute create an accessor - - - let modifiedAttribute = null; - - for (let attributeName in geometry.attributes) { - // Ignore morph target attributes, which are exported later. - if (attributeName.substr(0, 5) === 'morph') continue; - const attribute = geometry.attributes[attributeName]; - attributeName = nameConversion[attributeName] || attributeName.toUpperCase(); // Prefix all geometry attributes except the ones specifically - // listed in the spec; non-spec attributes are considered custom. - - const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/; - if (!validVertexAttributes.test(attributeName)) attributeName = '_' + attributeName; - - if (cache.attributes.has(this.getUID(attribute))) { - attributes[attributeName] = cache.attributes.get(this.getUID(attribute)); - continue; - } // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT. - - - modifiedAttribute = null; - const array = attribute.array; - - if (attributeName === 'JOINTS_0' && !(array instanceof Uint16Array) && !(array instanceof Uint8Array)) { - console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'); - modifiedAttribute = new BufferAttribute(new Uint16Array(array), attribute.itemSize, attribute.normalized); - } - - const accessor = modifiedAttribute !== null && this.processAccessor(modifiedAttribute || attribute, geometry); - - if (accessor) { - attributes[attributeName] = accessor; - cache.attributes.set(this.getUID(attribute), accessor); - } - } - - if (originalNormal !== undefined) geometry.setAttribute('normal', originalNormal); // Skip if no exportable attributes found - - if (Object.keys(attributes).length === 0) return null; // Morph targets - - if (mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0) { - const weights = []; - const targetNames = []; - const reverseDictionary = {}; - - if (mesh.morphTargetDictionary !== undefined) { - for (const key in mesh.morphTargetDictionary) { - reverseDictionary[mesh.morphTargetDictionary[key]] = key; - } - } - - for (let i = 0; i < mesh.morphTargetInfluences.length; ++i) { - const target = {}; - let warned = false; - - for (const attributeName in geometry.morphAttributes) { - // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT. - // Three.js doesn't support TANGENT yet. - if (attributeName !== 'position' && attributeName !== 'normal') { - if (!warned) { - console.warn('GLTFExporter: Only POSITION and NORMAL morph are supported.'); - warned = true; - } - - continue; - } - - const attribute = geometry.morphAttributes[attributeName][i]; - const gltfAttributeName = attributeName.toUpperCase(); // Three.js morph attribute has absolute values while the one of glTF has relative values. - // - // glTF 2.0 Specification: - // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets - - const baseAttribute = geometry.attributes[attributeName]; - - if (cache.attributes.has(this.getUID(attribute))) { - target[gltfAttributeName] = cache.attributes.get(this.getUID(attribute)); - continue; - } // Clones attribute not to override - - - const relativeAttribute = attribute.clone(); - - if (!geometry.morphTargetsRelative) { - for (let j = 0, jl = attribute.count; j < jl; j++) { - relativeAttribute.setXYZ(j, attribute.getX(j) - baseAttribute.getX(j), attribute.getY(j) - baseAttribute.getY(j), attribute.getZ(j) - baseAttribute.getZ(j)); - } - } - - const accessor = this.processAccessor(relativeAttribute, geometry); - - if (accessor != undefined) { - target[gltfAttributeName] = accessor; - } - - cache.attributes.set(this.getUID(baseAttribute), target[gltfAttributeName]); - } - - targets.push(target); - weights.push(mesh.morphTargetInfluences[i]); - if (mesh.morphTargetDictionary !== undefined) targetNames.push(reverseDictionary[i]); - } - - meshDef.weights = weights; - - if (targetNames.length > 0) { - meshDef.extras = {}; - meshDef.extras.targetNames = targetNames; - } - } - - const isMultiMaterial = Array.isArray(mesh.material); - if (isMultiMaterial && geometry.groups.length === 0) return null; - const materials = isMultiMaterial ? mesh.material : [mesh.material]; - const groups = isMultiMaterial ? geometry.groups : [{ - materialIndex: 0, - start: undefined, - count: undefined - }]; - - for (let i = 0, il = groups.length; i < il; i++) { - const primitive = { - mode: mode, - attributes: attributes - }; - - if (geometry instanceof Object3D || geometry instanceof Material) { - this.serializeUserData(geometry, primitive); - } - - if (targets.length > 0) primitive.targets = targets; - - if (geometry.index !== null) { - let cacheKey = this.getUID(geometry.index); - - if (groups[i].start !== undefined || groups[i].count !== undefined) { - // @ts-expect-error - cacheKey += `:${groups[i].start}:${groups[i].count}`; - } - - if (cache.attributes.has(cacheKey)) { - primitive.indices = cache.attributes.get(cacheKey); - } else { - primitive.indices = this.processAccessor(geometry.index, geometry, groups[i].start, groups[i].count); - cache.attributes.set(cacheKey, primitive.indices); - } - - if (primitive.indices === null) delete primitive.indices; - } - - const materialIndex = groups[i].materialIndex; - - if (materialIndex !== undefined && Array.isArray(materials)) { - const targetMaterials = materials[materialIndex]; - - if (!Array.isArray(targetMaterials)) { - const material = this.processMaterial(targetMaterials); - if (material !== null) primitive.material = material; - primitives.push(primitive); - } - } - } - - meshDef.primitives = primitives; - if (!json.meshes) json.meshes = []; - - this._invokeAll(function (ext) { - ext.writeMesh && ext.writeMesh(mesh, meshDef); - }); - - const index = json.meshes.push(meshDef) - 1; - cache.meshes.set(meshCacheKey, index); - return index; - } - /** - * Process camera - * @param {THREE.Camera} camera Camera to process - * @return {Integer} Index of the processed mesh in the "camera" array - */ - - - processCamera(camera) { - const json = this.json; - if (!json.cameras) json.cameras = []; - const isOrtho = camera instanceof OrthographicCamera && camera.isOrthographicCamera; - const cameraDef = { - type: isOrtho ? 'orthographic' : 'perspective' - }; - - if (camera instanceof OrthographicCamera && isOrtho) { - cameraDef.orthographic = { - xmag: camera.right * 2, - ymag: camera.top * 2, - zfar: camera.far <= 0 ? 0.001 : camera.far, - znear: camera.near < 0 ? 0 : camera.near - }; - } else if (camera instanceof PerspectiveCamera) { - cameraDef.perspective = { - aspectRatio: camera.aspect, - yfov: MathUtils.degToRad(camera.fov), - zfar: camera.far <= 0 ? 0.001 : camera.far, - znear: camera.near < 0 ? 0 : camera.near - }; - } // Question: Is saving "type" as name intentional? - - - if (camera.name !== '') cameraDef.name = camera.type; - return json.cameras.push(cameraDef) - 1; - } - /** - * Creates glTF animation entry from AnimationClip object. - * - * Status: - * - Only properties listed in PATH_PROPERTIES may be animated. - * - * @param {THREE.AnimationClip} clip - * @param {THREE.Object3D} root - * @return {number|null} - */ - - - processAnimation(clip, root) { - const json = this.json; - const nodeMap = this.nodeMap; - if (!json.animations) json.animations = []; - clip = GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(), root); - const tracks = clip.tracks; - const channels = []; - const samplers = []; - - for (let i = 0; i < tracks.length; ++i) { - const track = tracks[i]; - const trackBinding = PropertyBinding.parseTrackName(track.name); - let trackNode = PropertyBinding.findNode(root, trackBinding.nodeName); - const trackProperty = PATH_PROPERTIES[trackBinding.propertyName]; - - if (trackBinding.objectName === 'bones') { - if (trackNode.isSkinnedMesh) { - trackNode = trackNode.skeleton.getBoneByName(trackBinding.objectIndex); - } else { - trackNode = undefined; - } - } - - if (!trackNode || !trackProperty) { - console.warn('THREE.GLTFExporter: Could not export animation track "%s".', track.name); - return null; - } - - const inputItemSize = 1; - let outputItemSize = track.values.length / track.times.length; - - if (trackProperty === PATH_PROPERTIES.morphTargetInfluences) { - outputItemSize /= trackNode.morphTargetInfluences.length; - } - - let interpolation; // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE - // Detecting glTF cubic spline interpolant by checking factory method's special property - // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return - // valid value from .getInterpolation(). - // @ts-expect-error - - if (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { - interpolation = 'CUBICSPLINE'; // itemSize of CUBICSPLINE keyframe is 9 - // (VEC3 * 3: inTangent, splineVertex, and outTangent) - // but needs to be stored as VEC3 so dividing by 3 here. - - outputItemSize /= 3; - } else if (track.getInterpolation() === InterpolateDiscrete) { - interpolation = 'STEP'; - } else { - interpolation = 'LINEAR'; - } - - samplers.push({ - input: this.processAccessor(new BufferAttribute(track.times, inputItemSize)), - output: this.processAccessor(new BufferAttribute(track.values, outputItemSize)), - interpolation: interpolation - }); - channels.push({ - sampler: samplers.length - 1, - target: { - node: nodeMap.get(trackNode), - path: trackProperty - } - }); - } - - json.animations.push({ - name: clip.name || 'clip_' + json.animations.length, - samplers: samplers, - channels: channels - }); - return json.animations.length - 1; - } - /** - * @param {THREE.Object3D} object - * @return {number|null} - */ - - - processSkin(object) { - const json = this.json; - const nodeMap = this.nodeMap; - - if (json.nodes !== undefined && object instanceof SkinnedMesh) { - const node = json.nodes[nodeMap.get(object)]; - const skeleton = object.skeleton; - if (skeleton === undefined) return null; - const rootJoint = object.skeleton.bones[0]; - if (rootJoint === undefined) return null; - const joints = []; - const inverseBindMatrices = new Float32Array(skeleton.bones.length * 16); - const temporaryBoneInverse = new Matrix4(); - - for (let i = 0; i < skeleton.bones.length; ++i) { - joints.push(nodeMap.get(skeleton.bones[i])); - temporaryBoneInverse.copy(skeleton.boneInverses[i]); - temporaryBoneInverse.multiply(object.bindMatrix).toArray(inverseBindMatrices, i * 16); - } - - if (json.skins === undefined) json.skins = []; - json.skins.push({ - inverseBindMatrices: this.processAccessor(new BufferAttribute(inverseBindMatrices, 16)), - joints: joints, - skeleton: nodeMap.get(rootJoint) - }); - const skinIndex = node.skin = json.skins.length - 1; - return skinIndex; - } else { - return null; - } - } - /** - * Process Object3D node - * @param {THREE.Object3D} node Object3D to processNode - * @return {Integer} Index of the node in the nodes list - */ - - - processNode(object) { - const json = this.json; - const options = this.options; - const nodeMap = this.nodeMap; - if (!json.nodes) json.nodes = []; - const nodeDef = {}; - - if (options.trs) { - const rotation = object.quaternion.toArray(); - const position = object.position.toArray(); - const scale = object.scale.toArray(); - - if (!this.equalArray(rotation, [0, 0, 0, 1])) { - nodeDef.rotation = rotation; - } - - if (!this.equalArray(position, [0, 0, 0])) { - nodeDef.translation = position; - } - - if (!this.equalArray(scale, [1, 1, 1])) { - nodeDef.scale = scale; - } - } else { - if (object.matrixAutoUpdate) { - object.updateMatrix(); - } - - if (!this.isIdentityMatrix(object.matrix)) { - nodeDef.matrix = object.matrix.elements; - } - } // We don't export empty strings name because it represents no-name in Three.js. - - - if (object.name !== '') nodeDef.name = String(object.name); - this.serializeUserData(object, nodeDef); - - if ((object instanceof Mesh && object.isMesh || object instanceof Line$2 && object.isLine || object instanceof Points && object.isPoints) && object instanceof Mesh) { - const meshIndex = this.processMesh(object); - if (meshIndex !== null) nodeDef.mesh = meshIndex; - } else if (object instanceof Camera && object.isCamera) { - nodeDef.camera = this.processCamera(object); - } - - if (object instanceof SkinnedMesh && object.isSkinnedMesh) this.skins.push(object); - - if (object.children.length > 0) { - const children = []; - - for (let i = 0, l = object.children.length; i < l; i++) { - const child = object.children[i]; - - if (child.visible || !options.onlyVisible) { - const nodeIndex = this.processNode(child); - if (nodeIndex !== null) children.push(nodeIndex); - } - } - - if (children.length > 0) nodeDef.children = children; - } - - this._invokeAll(function (ext) { - ext.writeNode && ext.writeNode(object, nodeDef); - }); - - const nodeIndex = json.nodes.push(nodeDef) - 1; - nodeMap.set(object, nodeIndex); - return nodeIndex; - } - /** - * Process Scene - * @param {Scene} node Scene to process - */ - - - processScene(scene) { - const json = this.json; - const options = this.options; - - if (!json.scenes) { - json.scenes = []; - json.scene = 0; - } - - const sceneDef = {}; - if (scene.name !== '') sceneDef.name = scene.name; - json.scenes.push(sceneDef); - const nodes = []; - - for (let i = 0, l = scene.children.length; i < l; i++) { - const child = scene.children[i]; - - if (child.visible || !options.onlyVisible) { - const nodeIndex = this.processNode(child); - if (nodeIndex !== null) nodes.push(nodeIndex); - } - } - - if (nodes.length > 0) sceneDef.nodes = nodes; - this.serializeUserData(scene, sceneDef); - } - - processObjects(objects) { - const scene = new Scene$1(); - scene.name = 'AuxScene'; - - for (let i = 0; i < objects.length; i++) { - // We push directly to children instead of calling `add` to prevent - // modify the .parent and break its original scene and hierarchy - scene.children.push(objects[i]); - } - - this.processScene(scene); - } - /** - * @param {THREE.Object3D|Array} input - */ - - - processInput(input) { - const options = this.options; - input = input instanceof Array ? input : [input]; - - this._invokeAll(function (ext) { - ext.beforeParse && ext.beforeParse(input); - }); - - const objectsWithoutScene = []; - - for (let i = 0; i < input.length; i++) { - const inputScene = input[i]; - - if (inputScene instanceof Scene$1) { - this.processScene(inputScene); - } else { - objectsWithoutScene.push(input[i]); - } - } - - if (objectsWithoutScene.length > 0) this.processObjects(objectsWithoutScene); - - for (let i = 0; i < this.skins.length; ++i) { - this.processSkin(this.skins[i]); - } - - for (let i = 0; options.animations !== undefined && i < options.animations.length; ++i) { - this.processAnimation(options.animations[i], input[0]); - } - - this._invokeAll(function (ext) { - ext.afterParse && ext.afterParse(input); - }); - } - - _invokeAll(func) { - for (let i = 0, il = this.plugins.length; i < il; i++) { - func(this.plugins[i]); - } - } //------------------------------------------------------------------------------ - // Utility functions - //------------------------------------------------------------------------------ - - /** - * Compare two arrays - * @param {Array} array1 Array 1 to compare - * @param {Array} array2 Array 2 to compare - * @return {Boolean} Returns true if both arrays are equal - */ - - - equalArray(array1, array2) { - return array1.length === array2.length && array1.every(function (element, index) { - return element === array2[index]; - }); - } - /** - * Converts a string to an ArrayBuffer. - * @param {string} text - * @return {ArrayBuffer} - */ - - - stringToArrayBuffer(text) { - if (window.TextEncoder !== undefined) { - return new TextEncoder().encode(text).buffer; - } - - const array = new Uint8Array(new ArrayBuffer(text.length)); - - for (let i = 0, il = text.length; i < il; i++) { - const value = text.charCodeAt(i); // Replacing multi-byte character with space(0x20). - - array[i] = value > 0xff ? 0x20 : value; - } - - return array.buffer; - } - - isIdentityMatrix(matrix) { - return this.equalArray(matrix.elements, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); - } - - getMinMax(attribute, start, count) { - const output = { - min: new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY), - max: new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY) - }; - - for (let i = start; i < start + count; i++) { - for (let a = 0; a < attribute.itemSize; a++) { - let value; - - if (attribute.itemSize > 4) { - // no support for interleaved data for itemSize > 4 - value = attribute.array[i * attribute.itemSize + a]; - } else { - if (a === 0) value = attribute.getX(i);else if (a === 1) value = attribute.getY(i);else if (a === 2) value = attribute.getZ(i);else if (a === 3) value = attribute.getW(i); - } - - if (value !== undefined) { - output.min[a] = Math.min(output.min[a], value); - output.max[a] = Math.max(output.max[a], value); - } - } - } - - return output; - } - /** - * Get the required size + padding for a buffer, rounded to the next 4-byte boundary. - * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment - */ - - - getPaddedBufferSize(bufferSize) { - return Math.ceil(bufferSize / 4) * 4; - } - /** - * Returns a buffer aligned to 4-byte boundary. - * - * @param {ArrayBuffer} arrayBuffer Buffer to pad - * @param {Integer} paddingByte (Optional) - * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer - */ - - - getPaddedArrayBuffer(arrayBuffer, paddingByte = 0) { - const paddedLength = this.getPaddedBufferSize(arrayBuffer.byteLength); - - if (paddedLength !== arrayBuffer.byteLength) { - const array = new Uint8Array(paddedLength); - array.set(new Uint8Array(arrayBuffer)); - - if (paddingByte !== 0) { - for (let i = arrayBuffer.byteLength; i < paddedLength; i++) { - array[i] = paddingByte; - } - } - - return array.buffer; - } - - return arrayBuffer; - } - -} -/** - * Punctual Lights Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual - */ - - -class GLTFLightExtension { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_lights_punctual'; - } - - writeNode(light, nodeDef) { - if (!light.isLight) return; - - if (!(light instanceof DirectionalLight$1 && light.isDirectionalLight) && // @ts-expect-error - !(light instanceof PointLight && light.isPointLight) && !(light instanceof SpotLight && light.isSpotLight)) { - console.warn('THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light); - return; - } - - const writer = this.writer; - const json = writer.json; - const extensionsUsed = writer.extensionsUsed; - const lightDef = {}; - if (light.name) lightDef.name = light.name; - lightDef.color = light.color.toArray(); - lightDef.intensity = light.intensity; - - if (light instanceof DirectionalLight$1 && light.isDirectionalLight) { - lightDef.type = 'directional'; - } else if (light instanceof PointLight && // @ts-expect-error - light.isPointLight) { - lightDef.type = 'point'; - if (light.distance > 0) lightDef.range = light.distance; - } else if (light instanceof SpotLight && light.isSpotLight) { - lightDef.type = 'spot'; - if (light.distance > 0) lightDef.range = light.distance; - lightDef.spot = {}; - lightDef.spot.innerConeAngle = (light.penumbra - 1.0) * light.angle * -1.0; - lightDef.spot.outerConeAngle = light.angle; - } - - if (!(light instanceof DirectionalLight$1) && light.decay !== undefined && light.decay !== 2) { - console.warn('THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, ' + 'and expects light.decay=2.'); - } - - if (!(light instanceof PointLight) && light.target && (light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== -1)) { - console.warn('THREE.GLTFExporter: Light direction may be lost. For best results, ' + 'make light.target a child of the light with position 0,0,-1.'); - } - - if (!extensionsUsed[this.name]) { - json.extensions = json.extensions || {}; - json.extensions[this.name] = { - lights: [] - }; - extensionsUsed[this.name] = true; - } - - if (json.extensions !== undefined) { - const lights = json.extensions[this.name].lights; - lights.push(lightDef); - nodeDef.extensions = nodeDef.extensions || {}; - nodeDef.extensions[this.name] = { - light: lights.length - 1 - }; - } - } - -} -/** - * Unlit Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit - */ - - -class GLTFMaterialsUnlitExtension { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_materials_unlit'; - } - - writeMaterial(material, materialDef) { - if (!(material instanceof MeshBasicMaterial && // @ts-expect-error - material.isMeshBasicMaterial)) { - return; - } - - const writer = this.writer; - const extensionsUsed = writer.extensionsUsed; - materialDef.extensions = materialDef.extensions || {}; - materialDef.extensions[this.name] = {}; - extensionsUsed[this.name] = true; - materialDef.pbrMetallicRoughness.metallicFactor = 0.0; - materialDef.pbrMetallicRoughness.roughnessFactor = 0.9; - } - -} -/** - * Specular-Glossiness Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness - */ - - -class GLTFMaterialsPBRSpecularGlossiness { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_materials_pbrSpecularGlossiness'; - } - - writeMaterial(material, materialDef) { - // @ts-expect-error - if (!material.isGLTFSpecularGlossinessMaterial) return; - const writer = this.writer; - const extensionsUsed = writer.extensionsUsed; - const extensionDef = {}; - - if (materialDef.pbrMetallicRoughness.baseColorFactor) { - extensionDef.diffuseFactor = materialDef.pbrMetallicRoughness.baseColorFactor; - } - - if (material instanceof MeshPhongMaterial) { - const specularFactor = [1, 1, 1]; - material.specular.toArray(specularFactor, 0); - extensionDef.specularFactor = specularFactor; - extensionDef.glossinessFactor = // @ts-expect-error - material.glossiness; - } - - if (materialDef.pbrMetallicRoughness.baseColorTexture) { - extensionDef.diffuseTexture = materialDef.pbrMetallicRoughness.baseColorTexture; - } - - if ((material instanceof MeshBasicMaterial || material instanceof MeshLambertMaterial || material instanceof MeshPhongMaterial) && material.specularMap) { - const specularMapDef = { - index: writer.processTexture(material.specularMap) - }; - writer.applyTextureTransform(specularMapDef, material.specularMap); - extensionDef.specularGlossinessTexture = specularMapDef; - } - - materialDef.extensions = materialDef.extensions || {}; - materialDef.extensions[this.name] = extensionDef; - extensionsUsed[this.name] = true; - } - -} -/** - * Transmission Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission - */ - - -class GLTFMaterialsTransmissionExtension { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_materials_transmission'; - } - - writeMaterial(material, materialDef) { - if (!(material instanceof MeshPhysicalMaterial && // @ts-expect-error - material.isMeshPhysicalMaterial) || material.transmission === 0) { - return; - } - - const writer = this.writer; - const extensionsUsed = writer.extensionsUsed; - const extensionDef = {}; - extensionDef.transmissionFactor = material.transmission; - - if (material.transmissionMap) { - const transmissionMapDef = { - index: writer.processTexture(material.transmissionMap) - }; - writer.applyTextureTransform(transmissionMapDef, material.transmissionMap); - extensionDef.transmissionTexture = transmissionMapDef; - } - - materialDef.extensions = materialDef.extensions || {}; - materialDef.extensions[this.name] = extensionDef; - extensionsUsed[this.name] = true; - } - -} -/** - * Materials Volume Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume - */ - - -class GLTFMaterialsVolumeExtension { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_materials_volume'; - } - - writeMaterial(material, materialDef) { - if (!(material instanceof MeshPhysicalMaterial && // @ts-expect-error - material.isMeshPhysicalMaterial) || material.thickness === 0) { - return; - } - - const writer = this.writer; - const extensionsUsed = writer.extensionsUsed; - const extensionDef = {}; - extensionDef.thickness = material.thickness; - - if (material.thicknessMap) { - const thicknessMapDef = { - index: writer.processTexture(material.thicknessMap) - }; - writer.applyTextureTransform(thicknessMapDef, material.thicknessMap); - extensionDef.thicknessTexture = thicknessMapDef; - } - - extensionDef.attenuationDistance = material.attenuationDistance; - extensionDef.attenuationColor = //@ts-expect-error - material.attenuationTint.toArray(); - materialDef.extensions = materialDef.extensions || {}; - materialDef.extensions[this.name] = extensionDef; - extensionsUsed[this.name] = true; - } - -} - -// DEFLATE is a complex format; to read this code, you should probably check the RFC first: - -// aliases for shorter compressed code (most minifers don't do this) -var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array; -// fixed length extra bits -var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); -// fixed distance extra bits -// see fleb note -var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); -// get base, reverse index map from extra bits -var freb = function (eb, start) { - var b = new u16(31); - for (var i = 0; i < 31; ++i) { - b[i] = start += 1 << eb[i - 1]; - } - // numbers here are at max 18 bits - var r = new u32(b[30]); - for (var i = 1; i < 30; ++i) { - for (var j = b[i]; j < b[i + 1]; ++j) { - r[j] = ((j - b[i]) << 5) | i; - } - } - return [b, r]; -}; -var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1]; -// we can ignore the fact that the other numbers are wrong; they never happen anyway -fl[28] = 258, revfl[258] = 28; -freb(fdeb, 0); -// map of value to reverse (assuming 16 bits) -var rev = new u16(32768); -for (var i$3 = 0; i$3 < 32768; ++i$3) { - // reverse table algorithm from SO - var x$1 = ((i$3 & 0xAAAA) >>> 1) | ((i$3 & 0x5555) << 1); - x$1 = ((x$1 & 0xCCCC) >>> 2) | ((x$1 & 0x3333) << 2); - x$1 = ((x$1 & 0xF0F0) >>> 4) | ((x$1 & 0x0F0F) << 4); - rev[i$3] = (((x$1 & 0xFF00) >>> 8) | ((x$1 & 0x00FF) << 8)) >>> 1; -} -// fixed length tree -var flt = new u8(288); -for (var i$3 = 0; i$3 < 144; ++i$3) - flt[i$3] = 8; -for (var i$3 = 144; i$3 < 256; ++i$3) - flt[i$3] = 9; -for (var i$3 = 256; i$3 < 280; ++i$3) - flt[i$3] = 7; -for (var i$3 = 280; i$3 < 288; ++i$3) - flt[i$3] = 8; -// fixed distance tree -var fdt = new u8(32); -for (var i$3 = 0; i$3 < 32; ++i$3) - fdt[i$3] = 5; -// empty -var et = /*#__PURE__*/ new u8(0); -// text decoder -var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); -// text decoder stream -var tds = 0; -try { - td.decode(et, { stream: true }); - tds = 1; -} -catch (e) { } - -/** - * Export draco compressed files from threejs geometry objects. - * - * Draco files are compressed and usually are smaller than conventional 3D file formats. - * - * The exporter receives a options object containing - * - decodeSpeed, indicates how to tune the encoder regarding decode speed (0 gives better speed but worst quality) - * - encodeSpeed, indicates how to tune the encoder parameters (0 gives better speed but worst quality) - * - encoderMethod - * - quantization, indicates the presision of each type of data stored in the draco file in the order (POSITION, NORMAL, COLOR, TEX_COORD, GENERIC) - * - exportUvs - * - exportNormals - */ - -class DRACOExporter { - // Encoder methods - // Geometry type - // Attribute type - parse(object, options = { - decodeSpeed: 5, - encodeSpeed: 5, - encoderMethod: DRACOExporter.MESH_EDGEBREAKER_ENCODING, - quantization: [16, 8, 8, 8, 8], - exportUvs: true, - exportNormals: true, - exportColor: false - }) { - if (object instanceof BufferGeometry && object.isBufferGeometry) { - throw new Error('DRACOExporter: The first parameter of parse() is now an instance of Mesh or Points.'); - } - - if (DracoEncoderModule === undefined) { - throw new Error('THREE.DRACOExporter: required the draco_encoder to work.'); - } - - const geometry = object.geometry; - const dracoEncoder = DracoEncoderModule(); - const encoder = new dracoEncoder.Encoder(); - let builder; - let dracoObject; - - if (!geometry.isBufferGeometry) { - throw new Error('THREE.DRACOExporter.parse(geometry, options): geometry is not a THREE.BufferGeometry instance.'); - } - - if (object instanceof Mesh && object.isMesh) { - builder = new dracoEncoder.MeshBuilder(); - dracoObject = new dracoEncoder.Mesh(); - const vertices = geometry.getAttribute('position'); // @ts-expect-error - - builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); - const faces = geometry.getIndex(); - - if (faces !== null) { - // @ts-expect-error - builder.AddFacesToMesh(dracoObject, faces.count / 3, faces.array); - } else { - const faces = new (vertices.count > 65535 ? Uint32Array : Uint16Array)(vertices.count); - - for (let i = 0; i < faces.length; i++) { - faces[i] = i; - } - - builder.AddFacesToMesh(dracoObject, vertices.count, faces); - } - - if (options.exportNormals) { - const normals = geometry.getAttribute('normal'); - - if (normals !== undefined) { - // @ts-expect-error - builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array); - } - } - - if (options.exportUvs) { - const uvs = geometry.getAttribute('uv'); - - if (uvs !== undefined) { - // @ts-expect-error - builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array); - } - } - - if (options.exportColor) { - const colors = geometry.getAttribute('color'); - - if (colors !== undefined) { - // @ts-expect-error - builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array); - } - } - } else if (object instanceof Points && object.isPoints) { - // @ts-expect-error - builder = new dracoEncoder.PointCloudBuilder(); // @ts-expect-error - - dracoObject = new dracoEncoder.PointCloud(); - const vertices = geometry.getAttribute('position'); - builder.AddFloatAttribute(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); - - if (options.exportColor) { - const colors = geometry.getAttribute('color'); - - if (colors !== undefined) { - builder.AddFloatAttribute(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array); - } - } - } else { - throw new Error('DRACOExporter: Unsupported object type.'); - } //Compress using draco encoder - - - const encodedData = new dracoEncoder.DracoInt8Array(); //Sets the desired encoding and decoding speed for the given options from 0 (slowest speed, but the best compression) to 10 (fastest, but the worst compression). - - const encodeSpeed = options.encodeSpeed !== undefined ? options.encodeSpeed : 5; - const decodeSpeed = options.decodeSpeed !== undefined ? options.decodeSpeed : 5; - encoder.SetSpeedOptions(encodeSpeed, decodeSpeed); // Sets the desired encoding method for a given geometry. - - if (options.encoderMethod !== undefined) { - encoder.SetEncodingMethod(options.encoderMethod); - } // Sets the quantization (number of bits used to represent) compression options for a named attribute. - // The attribute values will be quantized in a box defined by the maximum extent of the attribute values. - - - if (options.quantization !== undefined) { - for (let i = 0; i < 5; i++) { - if (options.quantization[i] !== undefined) { - encoder.SetAttributeQuantization(i, options.quantization[i]); - } - } - } - - let length; - - if (object instanceof Mesh && object.isMesh) { - length = encoder.EncodeMeshToDracoBuffer(dracoObject, encodedData); - } else { - // @ts-expect-error - length = encoder.EncodePointCloudToDracoBuffer(dracoObject, true, encodedData); - } - - dracoEncoder.destroy(dracoObject); - - if (length === 0) { - throw new Error('THREE.DRACOExporter: Draco encoding failed.'); - } //Copy encoded data to buffer. - - - const outputData = new Int8Array(new ArrayBuffer(length)); - - for (let i = 0; i < length; i++) { - outputData[i] = encodedData.GetValue(i); - } - - dracoEncoder.destroy(encodedData); - dracoEncoder.destroy(encoder); - dracoEncoder.destroy(builder); - return outputData; - } - -} - -_defineProperty$1(DRACOExporter, "MESH_EDGEBREAKER_ENCODING", 1); - -_defineProperty$1(DRACOExporter, "MESH_SEQUENTIAL_ENCODING", 0); - -_defineProperty$1(DRACOExporter, "POINT_CLOUD", 0); - -_defineProperty$1(DRACOExporter, "TRIANGULAR_MESH", 1); - -_defineProperty$1(DRACOExporter, "INVALID", -1); - -_defineProperty$1(DRACOExporter, "POSITION", 0); - -_defineProperty$1(DRACOExporter, "NORMAL", 1); - -_defineProperty$1(DRACOExporter, "COLOR", 2); - -_defineProperty$1(DRACOExporter, "TEX_COORD", 3); - -_defineProperty$1(DRACOExporter, "GENERIC", 4); - -var mmdparser = {exports: {}}; - -(function (module, exports) { - (function (global, factory) { - factory(exports) ; - }(commonjsGlobal, (function (exports) { - /** - * @author Takahiro / https://github.com/takahirox - * - * Simple CharsetEncoder. - */ - - function CharsetEncoder() { - } - - /* - * Converts from Shift_JIS Uint8Array data to Unicode strings. - */ - CharsetEncoder.prototype.s2u = function(uint8Array) { - var t = this.s2uTable; - var str = ''; - var p = 0; - - while(p < uint8Array.length) { - var key = uint8Array[p++]; - - if(! ((key >= 0x00 && key <= 0x7e) || - (key >= 0xa1 && key <= 0xdf)) && - p < uint8Array.length) { - key = (key << 8) | uint8Array[p++]; - } - - if(t[key] === undefined) { - console.error('unknown char code ' + key + '.'); - return str; - } - - str += String.fromCharCode(t[key]); - } - - return str; - }; - - CharsetEncoder.prototype.s2uTable = { - 0:0, - 1:1, - 2:2, - 3:3, - 4:4, - 5:5, - 6:6, - 7:7, - 8:8, - 9:9, - 10:10, - 11:11, - 12:12, - 13:13, - 14:14, - 15:15, - 16:16, - 17:17, - 18:18, - 19:19, - 20:20, - 21:21, - 22:22, - 23:23, - 24:24, - 25:25, - 26:26, - 27:27, - 28:28, - 29:29, - 30:30, - 31:31, - 32:32, - 33:33, - 34:34, - 35:35, - 36:36, - 37:37, - 38:38, - 39:39, - 40:40, - 41:41, - 42:42, - 43:43, - 44:44, - 45:45, - 46:46, - 47:47, - 48:48, - 49:49, - 50:50, - 51:51, - 52:52, - 53:53, - 54:54, - 55:55, - 56:56, - 57:57, - 58:58, - 59:59, - 60:60, - 61:61, - 62:62, - 63:63, - 64:64, - 65:65, - 66:66, - 67:67, - 68:68, - 69:69, - 70:70, - 71:71, - 72:72, - 73:73, - 74:74, - 75:75, - 76:76, - 77:77, - 78:78, - 79:79, - 80:80, - 81:81, - 82:82, - 83:83, - 84:84, - 85:85, - 86:86, - 87:87, - 88:88, - 89:89, - 90:90, - 91:91, - 92:92, - 93:93, - 94:94, - 95:95, - 96:96, - 97:97, - 98:98, - 99:99, - 100:100, - 101:101, - 102:102, - 103:103, - 104:104, - 105:105, - 106:106, - 107:107, - 108:108, - 109:109, - 110:110, - 111:111, - 112:112, - 113:113, - 114:114, - 115:115, - 116:116, - 117:117, - 118:118, - 119:119, - 120:120, - 121:121, - 122:122, - 123:123, - 124:124, - 125:125, - 126:126, - 161:65377, - 162:65378, - 163:65379, - 164:65380, - 165:65381, - 166:65382, - 167:65383, - 168:65384, - 169:65385, - 170:65386, - 171:65387, - 172:65388, - 173:65389, - 174:65390, - 175:65391, - 176:65392, - 177:65393, - 178:65394, - 179:65395, - 180:65396, - 181:65397, - 182:65398, - 183:65399, - 184:65400, - 185:65401, - 186:65402, - 187:65403, - 188:65404, - 189:65405, - 190:65406, - 191:65407, - 192:65408, - 193:65409, - 194:65410, - 195:65411, - 196:65412, - 197:65413, - 198:65414, - 199:65415, - 200:65416, - 201:65417, - 202:65418, - 203:65419, - 204:65420, - 205:65421, - 206:65422, - 207:65423, - 208:65424, - 209:65425, - 210:65426, - 211:65427, - 212:65428, - 213:65429, - 214:65430, - 215:65431, - 216:65432, - 217:65433, - 218:65434, - 219:65435, - 220:65436, - 221:65437, - 222:65438, - 223:65439, - 33088:12288, - 33089:12289, - 33090:12290, - 33091:65292, - 33092:65294, - 33093:12539, - 33094:65306, - 33095:65307, - 33096:65311, - 33097:65281, - 33098:12443, - 33099:12444, - 33100:180, - 33101:65344, - 33102:168, - 33103:65342, - 33104:65507, - 33105:65343, - 33106:12541, - 33107:12542, - 33108:12445, - 33109:12446, - 33110:12291, - 33111:20189, - 33112:12293, - 33113:12294, - 33114:12295, - 33115:12540, - 33116:8213, - 33117:8208, - 33118:65295, - 33119:65340, - 33120:65374, - 33121:8741, - 33122:65372, - 33123:8230, - 33124:8229, - 33125:8216, - 33126:8217, - 33127:8220, - 33128:8221, - 33129:65288, - 33130:65289, - 33131:12308, - 33132:12309, - 33133:65339, - 33134:65341, - 33135:65371, - 33136:65373, - 33137:12296, - 33138:12297, - 33139:12298, - 33140:12299, - 33141:12300, - 33142:12301, - 33143:12302, - 33144:12303, - 33145:12304, - 33146:12305, - 33147:65291, - 33148:65293, - 33149:177, - 33150:215, - 33152:247, - 33153:65309, - 33154:8800, - 33155:65308, - 33156:65310, - 33157:8806, - 33158:8807, - 33159:8734, - 33160:8756, - 33161:9794, - 33162:9792, - 33163:176, - 33164:8242, - 33165:8243, - 33166:8451, - 33167:65509, - 33168:65284, - 33169:65504, - 33170:65505, - 33171:65285, - 33172:65283, - 33173:65286, - 33174:65290, - 33175:65312, - 33176:167, - 33177:9734, - 33178:9733, - 33179:9675, - 33180:9679, - 33181:9678, - 33182:9671, - 33183:9670, - 33184:9633, - 33185:9632, - 33186:9651, - 33187:9650, - 33188:9661, - 33189:9660, - 33190:8251, - 33191:12306, - 33192:8594, - 33193:8592, - 33194:8593, - 33195:8595, - 33196:12307, - 33208:8712, - 33209:8715, - 33210:8838, - 33211:8839, - 33212:8834, - 33213:8835, - 33214:8746, - 33215:8745, - 33224:8743, - 33225:8744, - 33226:65506, - 33227:8658, - 33228:8660, - 33229:8704, - 33230:8707, - 33242:8736, - 33243:8869, - 33244:8978, - 33245:8706, - 33246:8711, - 33247:8801, - 33248:8786, - 33249:8810, - 33250:8811, - 33251:8730, - 33252:8765, - 33253:8733, - 33254:8757, - 33255:8747, - 33256:8748, - 33264:8491, - 33265:8240, - 33266:9839, - 33267:9837, - 33268:9834, - 33269:8224, - 33270:8225, - 33271:182, - 33276:9711, - 33359:65296, - 33360:65297, - 33361:65298, - 33362:65299, - 33363:65300, - 33364:65301, - 33365:65302, - 33366:65303, - 33367:65304, - 33368:65305, - 33376:65313, - 33377:65314, - 33378:65315, - 33379:65316, - 33380:65317, - 33381:65318, - 33382:65319, - 33383:65320, - 33384:65321, - 33385:65322, - 33386:65323, - 33387:65324, - 33388:65325, - 33389:65326, - 33390:65327, - 33391:65328, - 33392:65329, - 33393:65330, - 33394:65331, - 33395:65332, - 33396:65333, - 33397:65334, - 33398:65335, - 33399:65336, - 33400:65337, - 33401:65338, - 33409:65345, - 33410:65346, - 33411:65347, - 33412:65348, - 33413:65349, - 33414:65350, - 33415:65351, - 33416:65352, - 33417:65353, - 33418:65354, - 33419:65355, - 33420:65356, - 33421:65357, - 33422:65358, - 33423:65359, - 33424:65360, - 33425:65361, - 33426:65362, - 33427:65363, - 33428:65364, - 33429:65365, - 33430:65366, - 33431:65367, - 33432:65368, - 33433:65369, - 33434:65370, - 33439:12353, - 33440:12354, - 33441:12355, - 33442:12356, - 33443:12357, - 33444:12358, - 33445:12359, - 33446:12360, - 33447:12361, - 33448:12362, - 33449:12363, - 33450:12364, - 33451:12365, - 33452:12366, - 33453:12367, - 33454:12368, - 33455:12369, - 33456:12370, - 33457:12371, - 33458:12372, - 33459:12373, - 33460:12374, - 33461:12375, - 33462:12376, - 33463:12377, - 33464:12378, - 33465:12379, - 33466:12380, - 33467:12381, - 33468:12382, - 33469:12383, - 33470:12384, - 33471:12385, - 33472:12386, - 33473:12387, - 33474:12388, - 33475:12389, - 33476:12390, - 33477:12391, - 33478:12392, - 33479:12393, - 33480:12394, - 33481:12395, - 33482:12396, - 33483:12397, - 33484:12398, - 33485:12399, - 33486:12400, - 33487:12401, - 33488:12402, - 33489:12403, - 33490:12404, - 33491:12405, - 33492:12406, - 33493:12407, - 33494:12408, - 33495:12409, - 33496:12410, - 33497:12411, - 33498:12412, - 33499:12413, - 33500:12414, - 33501:12415, - 33502:12416, - 33503:12417, - 33504:12418, - 33505:12419, - 33506:12420, - 33507:12421, - 33508:12422, - 33509:12423, - 33510:12424, - 33511:12425, - 33512:12426, - 33513:12427, - 33514:12428, - 33515:12429, - 33516:12430, - 33517:12431, - 33518:12432, - 33519:12433, - 33520:12434, - 33521:12435, - 33600:12449, - 33601:12450, - 33602:12451, - 33603:12452, - 33604:12453, - 33605:12454, - 33606:12455, - 33607:12456, - 33608:12457, - 33609:12458, - 33610:12459, - 33611:12460, - 33612:12461, - 33613:12462, - 33614:12463, - 33615:12464, - 33616:12465, - 33617:12466, - 33618:12467, - 33619:12468, - 33620:12469, - 33621:12470, - 33622:12471, - 33623:12472, - 33624:12473, - 33625:12474, - 33626:12475, - 33627:12476, - 33628:12477, - 33629:12478, - 33630:12479, - 33631:12480, - 33632:12481, - 33633:12482, - 33634:12483, - 33635:12484, - 33636:12485, - 33637:12486, - 33638:12487, - 33639:12488, - 33640:12489, - 33641:12490, - 33642:12491, - 33643:12492, - 33644:12493, - 33645:12494, - 33646:12495, - 33647:12496, - 33648:12497, - 33649:12498, - 33650:12499, - 33651:12500, - 33652:12501, - 33653:12502, - 33654:12503, - 33655:12504, - 33656:12505, - 33657:12506, - 33658:12507, - 33659:12508, - 33660:12509, - 33661:12510, - 33662:12511, - 33664:12512, - 33665:12513, - 33666:12514, - 33667:12515, - 33668:12516, - 33669:12517, - 33670:12518, - 33671:12519, - 33672:12520, - 33673:12521, - 33674:12522, - 33675:12523, - 33676:12524, - 33677:12525, - 33678:12526, - 33679:12527, - 33680:12528, - 33681:12529, - 33682:12530, - 33683:12531, - 33684:12532, - 33685:12533, - 33686:12534, - 33695:913, - 33696:914, - 33697:915, - 33698:916, - 33699:917, - 33700:918, - 33701:919, - 33702:920, - 33703:921, - 33704:922, - 33705:923, - 33706:924, - 33707:925, - 33708:926, - 33709:927, - 33710:928, - 33711:929, - 33712:931, - 33713:932, - 33714:933, - 33715:934, - 33716:935, - 33717:936, - 33718:937, - 33727:945, - 33728:946, - 33729:947, - 33730:948, - 33731:949, - 33732:950, - 33733:951, - 33734:952, - 33735:953, - 33736:954, - 33737:955, - 33738:956, - 33739:957, - 33740:958, - 33741:959, - 33742:960, - 33743:961, - 33744:963, - 33745:964, - 33746:965, - 33747:966, - 33748:967, - 33749:968, - 33750:969, - 33856:1040, - 33857:1041, - 33858:1042, - 33859:1043, - 33860:1044, - 33861:1045, - 33862:1025, - 33863:1046, - 33864:1047, - 33865:1048, - 33866:1049, - 33867:1050, - 33868:1051, - 33869:1052, - 33870:1053, - 33871:1054, - 33872:1055, - 33873:1056, - 33874:1057, - 33875:1058, - 33876:1059, - 33877:1060, - 33878:1061, - 33879:1062, - 33880:1063, - 33881:1064, - 33882:1065, - 33883:1066, - 33884:1067, - 33885:1068, - 33886:1069, - 33887:1070, - 33888:1071, - 33904:1072, - 33905:1073, - 33906:1074, - 33907:1075, - 33908:1076, - 33909:1077, - 33910:1105, - 33911:1078, - 33912:1079, - 33913:1080, - 33914:1081, - 33915:1082, - 33916:1083, - 33917:1084, - 33918:1085, - 33920:1086, - 33921:1087, - 33922:1088, - 33923:1089, - 33924:1090, - 33925:1091, - 33926:1092, - 33927:1093, - 33928:1094, - 33929:1095, - 33930:1096, - 33931:1097, - 33932:1098, - 33933:1099, - 33934:1100, - 33935:1101, - 33936:1102, - 33937:1103, - 33951:9472, - 33952:9474, - 33953:9484, - 33954:9488, - 33955:9496, - 33956:9492, - 33957:9500, - 33958:9516, - 33959:9508, - 33960:9524, - 33961:9532, - 33962:9473, - 33963:9475, - 33964:9487, - 33965:9491, - 33966:9499, - 33967:9495, - 33968:9507, - 33969:9523, - 33970:9515, - 33971:9531, - 33972:9547, - 33973:9504, - 33974:9519, - 33975:9512, - 33976:9527, - 33977:9535, - 33978:9501, - 33979:9520, - 33980:9509, - 33981:9528, - 33982:9538, - 34624:9312, - 34625:9313, - 34626:9314, - 34627:9315, - 34628:9316, - 34629:9317, - 34630:9318, - 34631:9319, - 34632:9320, - 34633:9321, - 34634:9322, - 34635:9323, - 34636:9324, - 34637:9325, - 34638:9326, - 34639:9327, - 34640:9328, - 34641:9329, - 34642:9330, - 34643:9331, - 34644:8544, - 34645:8545, - 34646:8546, - 34647:8547, - 34648:8548, - 34649:8549, - 34650:8550, - 34651:8551, - 34652:8552, - 34653:8553, - 34655:13129, - 34656:13076, - 34657:13090, - 34658:13133, - 34659:13080, - 34660:13095, - 34661:13059, - 34662:13110, - 34663:13137, - 34664:13143, - 34665:13069, - 34666:13094, - 34667:13091, - 34668:13099, - 34669:13130, - 34670:13115, - 34671:13212, - 34672:13213, - 34673:13214, - 34674:13198, - 34675:13199, - 34676:13252, - 34677:13217, - 34686:13179, - 34688:12317, - 34689:12319, - 34690:8470, - 34691:13261, - 34692:8481, - 34693:12964, - 34694:12965, - 34695:12966, - 34696:12967, - 34697:12968, - 34698:12849, - 34699:12850, - 34700:12857, - 34701:13182, - 34702:13181, - 34703:13180, - 34704:8786, - 34705:8801, - 34706:8747, - 34707:8750, - 34708:8721, - 34709:8730, - 34710:8869, - 34711:8736, - 34712:8735, - 34713:8895, - 34714:8757, - 34715:8745, - 34716:8746, - 34975:20124, - 34976:21782, - 34977:23043, - 34978:38463, - 34979:21696, - 34980:24859, - 34981:25384, - 34982:23030, - 34983:36898, - 34984:33909, - 34985:33564, - 34986:31312, - 34987:24746, - 34988:25569, - 34989:28197, - 34990:26093, - 34991:33894, - 34992:33446, - 34993:39925, - 34994:26771, - 34995:22311, - 34996:26017, - 34997:25201, - 34998:23451, - 34999:22992, - 35000:34427, - 35001:39156, - 35002:32098, - 35003:32190, - 35004:39822, - 35005:25110, - 35006:31903, - 35007:34999, - 35008:23433, - 35009:24245, - 35010:25353, - 35011:26263, - 35012:26696, - 35013:38343, - 35014:38797, - 35015:26447, - 35016:20197, - 35017:20234, - 35018:20301, - 35019:20381, - 35020:20553, - 35021:22258, - 35022:22839, - 35023:22996, - 35024:23041, - 35025:23561, - 35026:24799, - 35027:24847, - 35028:24944, - 35029:26131, - 35030:26885, - 35031:28858, - 35032:30031, - 35033:30064, - 35034:31227, - 35035:32173, - 35036:32239, - 35037:32963, - 35038:33806, - 35039:34915, - 35040:35586, - 35041:36949, - 35042:36986, - 35043:21307, - 35044:20117, - 35045:20133, - 35046:22495, - 35047:32946, - 35048:37057, - 35049:30959, - 35050:19968, - 35051:22769, - 35052:28322, - 35053:36920, - 35054:31282, - 35055:33576, - 35056:33419, - 35057:39983, - 35058:20801, - 35059:21360, - 35060:21693, - 35061:21729, - 35062:22240, - 35063:23035, - 35064:24341, - 35065:39154, - 35066:28139, - 35067:32996, - 35068:34093, - 35136:38498, - 35137:38512, - 35138:38560, - 35139:38907, - 35140:21515, - 35141:21491, - 35142:23431, - 35143:28879, - 35144:32701, - 35145:36802, - 35146:38632, - 35147:21359, - 35148:40284, - 35149:31418, - 35150:19985, - 35151:30867, - 35152:33276, - 35153:28198, - 35154:22040, - 35155:21764, - 35156:27421, - 35157:34074, - 35158:39995, - 35159:23013, - 35160:21417, - 35161:28006, - 35162:29916, - 35163:38287, - 35164:22082, - 35165:20113, - 35166:36939, - 35167:38642, - 35168:33615, - 35169:39180, - 35170:21473, - 35171:21942, - 35172:23344, - 35173:24433, - 35174:26144, - 35175:26355, - 35176:26628, - 35177:27704, - 35178:27891, - 35179:27945, - 35180:29787, - 35181:30408, - 35182:31310, - 35183:38964, - 35184:33521, - 35185:34907, - 35186:35424, - 35187:37613, - 35188:28082, - 35189:30123, - 35190:30410, - 35191:39365, - 35192:24742, - 35193:35585, - 35194:36234, - 35195:38322, - 35196:27022, - 35197:21421, - 35198:20870, - 35200:22290, - 35201:22576, - 35202:22852, - 35203:23476, - 35204:24310, - 35205:24616, - 35206:25513, - 35207:25588, - 35208:27839, - 35209:28436, - 35210:28814, - 35211:28948, - 35212:29017, - 35213:29141, - 35214:29503, - 35215:32257, - 35216:33398, - 35217:33489, - 35218:34199, - 35219:36960, - 35220:37467, - 35221:40219, - 35222:22633, - 35223:26044, - 35224:27738, - 35225:29989, - 35226:20985, - 35227:22830, - 35228:22885, - 35229:24448, - 35230:24540, - 35231:25276, - 35232:26106, - 35233:27178, - 35234:27431, - 35235:27572, - 35236:29579, - 35237:32705, - 35238:35158, - 35239:40236, - 35240:40206, - 35241:40644, - 35242:23713, - 35243:27798, - 35244:33659, - 35245:20740, - 35246:23627, - 35247:25014, - 35248:33222, - 35249:26742, - 35250:29281, - 35251:20057, - 35252:20474, - 35253:21368, - 35254:24681, - 35255:28201, - 35256:31311, - 35257:38899, - 35258:19979, - 35259:21270, - 35260:20206, - 35261:20309, - 35262:20285, - 35263:20385, - 35264:20339, - 35265:21152, - 35266:21487, - 35267:22025, - 35268:22799, - 35269:23233, - 35270:23478, - 35271:23521, - 35272:31185, - 35273:26247, - 35274:26524, - 35275:26550, - 35276:27468, - 35277:27827, - 35278:28779, - 35279:29634, - 35280:31117, - 35281:31166, - 35282:31292, - 35283:31623, - 35284:33457, - 35285:33499, - 35286:33540, - 35287:33655, - 35288:33775, - 35289:33747, - 35290:34662, - 35291:35506, - 35292:22057, - 35293:36008, - 35294:36838, - 35295:36942, - 35296:38686, - 35297:34442, - 35298:20420, - 35299:23784, - 35300:25105, - 35301:29273, - 35302:30011, - 35303:33253, - 35304:33469, - 35305:34558, - 35306:36032, - 35307:38597, - 35308:39187, - 35309:39381, - 35310:20171, - 35311:20250, - 35312:35299, - 35313:22238, - 35314:22602, - 35315:22730, - 35316:24315, - 35317:24555, - 35318:24618, - 35319:24724, - 35320:24674, - 35321:25040, - 35322:25106, - 35323:25296, - 35324:25913, - 35392:39745, - 35393:26214, - 35394:26800, - 35395:28023, - 35396:28784, - 35397:30028, - 35398:30342, - 35399:32117, - 35400:33445, - 35401:34809, - 35402:38283, - 35403:38542, - 35404:35997, - 35405:20977, - 35406:21182, - 35407:22806, - 35408:21683, - 35409:23475, - 35410:23830, - 35411:24936, - 35412:27010, - 35413:28079, - 35414:30861, - 35415:33995, - 35416:34903, - 35417:35442, - 35418:37799, - 35419:39608, - 35420:28012, - 35421:39336, - 35422:34521, - 35423:22435, - 35424:26623, - 35425:34510, - 35426:37390, - 35427:21123, - 35428:22151, - 35429:21508, - 35430:24275, - 35431:25313, - 35432:25785, - 35433:26684, - 35434:26680, - 35435:27579, - 35436:29554, - 35437:30906, - 35438:31339, - 35439:35226, - 35440:35282, - 35441:36203, - 35442:36611, - 35443:37101, - 35444:38307, - 35445:38548, - 35446:38761, - 35447:23398, - 35448:23731, - 35449:27005, - 35450:38989, - 35451:38990, - 35452:25499, - 35453:31520, - 35454:27179, - 35456:27263, - 35457:26806, - 35458:39949, - 35459:28511, - 35460:21106, - 35461:21917, - 35462:24688, - 35463:25324, - 35464:27963, - 35465:28167, - 35466:28369, - 35467:33883, - 35468:35088, - 35469:36676, - 35470:19988, - 35471:39993, - 35472:21494, - 35473:26907, - 35474:27194, - 35475:38788, - 35476:26666, - 35477:20828, - 35478:31427, - 35479:33970, - 35480:37340, - 35481:37772, - 35482:22107, - 35483:40232, - 35484:26658, - 35485:33541, - 35486:33841, - 35487:31909, - 35488:21000, - 35489:33477, - 35490:29926, - 35491:20094, - 35492:20355, - 35493:20896, - 35494:23506, - 35495:21002, - 35496:21208, - 35497:21223, - 35498:24059, - 35499:21914, - 35500:22570, - 35501:23014, - 35502:23436, - 35503:23448, - 35504:23515, - 35505:24178, - 35506:24185, - 35507:24739, - 35508:24863, - 35509:24931, - 35510:25022, - 35511:25563, - 35512:25954, - 35513:26577, - 35514:26707, - 35515:26874, - 35516:27454, - 35517:27475, - 35518:27735, - 35519:28450, - 35520:28567, - 35521:28485, - 35522:29872, - 35523:29976, - 35524:30435, - 35525:30475, - 35526:31487, - 35527:31649, - 35528:31777, - 35529:32233, - 35530:32566, - 35531:32752, - 35532:32925, - 35533:33382, - 35534:33694, - 35535:35251, - 35536:35532, - 35537:36011, - 35538:36996, - 35539:37969, - 35540:38291, - 35541:38289, - 35542:38306, - 35543:38501, - 35544:38867, - 35545:39208, - 35546:33304, - 35547:20024, - 35548:21547, - 35549:23736, - 35550:24012, - 35551:29609, - 35552:30284, - 35553:30524, - 35554:23721, - 35555:32747, - 35556:36107, - 35557:38593, - 35558:38929, - 35559:38996, - 35560:39000, - 35561:20225, - 35562:20238, - 35563:21361, - 35564:21916, - 35565:22120, - 35566:22522, - 35567:22855, - 35568:23305, - 35569:23492, - 35570:23696, - 35571:24076, - 35572:24190, - 35573:24524, - 35574:25582, - 35575:26426, - 35576:26071, - 35577:26082, - 35578:26399, - 35579:26827, - 35580:26820, - 35648:27231, - 35649:24112, - 35650:27589, - 35651:27671, - 35652:27773, - 35653:30079, - 35654:31048, - 35655:23395, - 35656:31232, - 35657:32000, - 35658:24509, - 35659:35215, - 35660:35352, - 35661:36020, - 35662:36215, - 35663:36556, - 35664:36637, - 35665:39138, - 35666:39438, - 35667:39740, - 35668:20096, - 35669:20605, - 35670:20736, - 35671:22931, - 35672:23452, - 35673:25135, - 35674:25216, - 35675:25836, - 35676:27450, - 35677:29344, - 35678:30097, - 35679:31047, - 35680:32681, - 35681:34811, - 35682:35516, - 35683:35696, - 35684:25516, - 35685:33738, - 35686:38816, - 35687:21513, - 35688:21507, - 35689:21931, - 35690:26708, - 35691:27224, - 35692:35440, - 35693:30759, - 35694:26485, - 35695:40653, - 35696:21364, - 35697:23458, - 35698:33050, - 35699:34384, - 35700:36870, - 35701:19992, - 35702:20037, - 35703:20167, - 35704:20241, - 35705:21450, - 35706:21560, - 35707:23470, - 35708:24339, - 35709:24613, - 35710:25937, - 35712:26429, - 35713:27714, - 35714:27762, - 35715:27875, - 35716:28792, - 35717:29699, - 35718:31350, - 35719:31406, - 35720:31496, - 35721:32026, - 35722:31998, - 35723:32102, - 35724:26087, - 35725:29275, - 35726:21435, - 35727:23621, - 35728:24040, - 35729:25298, - 35730:25312, - 35731:25369, - 35732:28192, - 35733:34394, - 35734:35377, - 35735:36317, - 35736:37624, - 35737:28417, - 35738:31142, - 35739:39770, - 35740:20136, - 35741:20139, - 35742:20140, - 35743:20379, - 35744:20384, - 35745:20689, - 35746:20807, - 35747:31478, - 35748:20849, - 35749:20982, - 35750:21332, - 35751:21281, - 35752:21375, - 35753:21483, - 35754:21932, - 35755:22659, - 35756:23777, - 35757:24375, - 35758:24394, - 35759:24623, - 35760:24656, - 35761:24685, - 35762:25375, - 35763:25945, - 35764:27211, - 35765:27841, - 35766:29378, - 35767:29421, - 35768:30703, - 35769:33016, - 35770:33029, - 35771:33288, - 35772:34126, - 35773:37111, - 35774:37857, - 35775:38911, - 35776:39255, - 35777:39514, - 35778:20208, - 35779:20957, - 35780:23597, - 35781:26241, - 35782:26989, - 35783:23616, - 35784:26354, - 35785:26997, - 35786:29577, - 35787:26704, - 35788:31873, - 35789:20677, - 35790:21220, - 35791:22343, - 35792:24062, - 35793:37670, - 35794:26020, - 35795:27427, - 35796:27453, - 35797:29748, - 35798:31105, - 35799:31165, - 35800:31563, - 35801:32202, - 35802:33465, - 35803:33740, - 35804:34943, - 35805:35167, - 35806:35641, - 35807:36817, - 35808:37329, - 35809:21535, - 35810:37504, - 35811:20061, - 35812:20534, - 35813:21477, - 35814:21306, - 35815:29399, - 35816:29590, - 35817:30697, - 35818:33510, - 35819:36527, - 35820:39366, - 35821:39368, - 35822:39378, - 35823:20855, - 35824:24858, - 35825:34398, - 35826:21936, - 35827:31354, - 35828:20598, - 35829:23507, - 35830:36935, - 35831:38533, - 35832:20018, - 35833:27355, - 35834:37351, - 35835:23633, - 35836:23624, - 35904:25496, - 35905:31391, - 35906:27795, - 35907:38772, - 35908:36705, - 35909:31402, - 35910:29066, - 35911:38536, - 35912:31874, - 35913:26647, - 35914:32368, - 35915:26705, - 35916:37740, - 35917:21234, - 35918:21531, - 35919:34219, - 35920:35347, - 35921:32676, - 35922:36557, - 35923:37089, - 35924:21350, - 35925:34952, - 35926:31041, - 35927:20418, - 35928:20670, - 35929:21009, - 35930:20804, - 35931:21843, - 35932:22317, - 35933:29674, - 35934:22411, - 35935:22865, - 35936:24418, - 35937:24452, - 35938:24693, - 35939:24950, - 35940:24935, - 35941:25001, - 35942:25522, - 35943:25658, - 35944:25964, - 35945:26223, - 35946:26690, - 35947:28179, - 35948:30054, - 35949:31293, - 35950:31995, - 35951:32076, - 35952:32153, - 35953:32331, - 35954:32619, - 35955:33550, - 35956:33610, - 35957:34509, - 35958:35336, - 35959:35427, - 35960:35686, - 35961:36605, - 35962:38938, - 35963:40335, - 35964:33464, - 35965:36814, - 35966:39912, - 35968:21127, - 35969:25119, - 35970:25731, - 35971:28608, - 35972:38553, - 35973:26689, - 35974:20625, - 35975:27424, - 35976:27770, - 35977:28500, - 35978:31348, - 35979:32080, - 35980:34880, - 35981:35363, - 35982:26376, - 35983:20214, - 35984:20537, - 35985:20518, - 35986:20581, - 35987:20860, - 35988:21048, - 35989:21091, - 35990:21927, - 35991:22287, - 35992:22533, - 35993:23244, - 35994:24314, - 35995:25010, - 35996:25080, - 35997:25331, - 35998:25458, - 35999:26908, - 36000:27177, - 36001:29309, - 36002:29356, - 36003:29486, - 36004:30740, - 36005:30831, - 36006:32121, - 36007:30476, - 36008:32937, - 36009:35211, - 36010:35609, - 36011:36066, - 36012:36562, - 36013:36963, - 36014:37749, - 36015:38522, - 36016:38997, - 36017:39443, - 36018:40568, - 36019:20803, - 36020:21407, - 36021:21427, - 36022:24187, - 36023:24358, - 36024:28187, - 36025:28304, - 36026:29572, - 36027:29694, - 36028:32067, - 36029:33335, - 36030:35328, - 36031:35578, - 36032:38480, - 36033:20046, - 36034:20491, - 36035:21476, - 36036:21628, - 36037:22266, - 36038:22993, - 36039:23396, - 36040:24049, - 36041:24235, - 36042:24359, - 36043:25144, - 36044:25925, - 36045:26543, - 36046:28246, - 36047:29392, - 36048:31946, - 36049:34996, - 36050:32929, - 36051:32993, - 36052:33776, - 36053:34382, - 36054:35463, - 36055:36328, - 36056:37431, - 36057:38599, - 36058:39015, - 36059:40723, - 36060:20116, - 36061:20114, - 36062:20237, - 36063:21320, - 36064:21577, - 36065:21566, - 36066:23087, - 36067:24460, - 36068:24481, - 36069:24735, - 36070:26791, - 36071:27278, - 36072:29786, - 36073:30849, - 36074:35486, - 36075:35492, - 36076:35703, - 36077:37264, - 36078:20062, - 36079:39881, - 36080:20132, - 36081:20348, - 36082:20399, - 36083:20505, - 36084:20502, - 36085:20809, - 36086:20844, - 36087:21151, - 36088:21177, - 36089:21246, - 36090:21402, - 36091:21475, - 36092:21521, - 36160:21518, - 36161:21897, - 36162:22353, - 36163:22434, - 36164:22909, - 36165:23380, - 36166:23389, - 36167:23439, - 36168:24037, - 36169:24039, - 36170:24055, - 36171:24184, - 36172:24195, - 36173:24218, - 36174:24247, - 36175:24344, - 36176:24658, - 36177:24908, - 36178:25239, - 36179:25304, - 36180:25511, - 36181:25915, - 36182:26114, - 36183:26179, - 36184:26356, - 36185:26477, - 36186:26657, - 36187:26775, - 36188:27083, - 36189:27743, - 36190:27946, - 36191:28009, - 36192:28207, - 36193:28317, - 36194:30002, - 36195:30343, - 36196:30828, - 36197:31295, - 36198:31968, - 36199:32005, - 36200:32024, - 36201:32094, - 36202:32177, - 36203:32789, - 36204:32771, - 36205:32943, - 36206:32945, - 36207:33108, - 36208:33167, - 36209:33322, - 36210:33618, - 36211:34892, - 36212:34913, - 36213:35611, - 36214:36002, - 36215:36092, - 36216:37066, - 36217:37237, - 36218:37489, - 36219:30783, - 36220:37628, - 36221:38308, - 36222:38477, - 36224:38917, - 36225:39321, - 36226:39640, - 36227:40251, - 36228:21083, - 36229:21163, - 36230:21495, - 36231:21512, - 36232:22741, - 36233:25335, - 36234:28640, - 36235:35946, - 36236:36703, - 36237:40633, - 36238:20811, - 36239:21051, - 36240:21578, - 36241:22269, - 36242:31296, - 36243:37239, - 36244:40288, - 36245:40658, - 36246:29508, - 36247:28425, - 36248:33136, - 36249:29969, - 36250:24573, - 36251:24794, - 36252:39592, - 36253:29403, - 36254:36796, - 36255:27492, - 36256:38915, - 36257:20170, - 36258:22256, - 36259:22372, - 36260:22718, - 36261:23130, - 36262:24680, - 36263:25031, - 36264:26127, - 36265:26118, - 36266:26681, - 36267:26801, - 36268:28151, - 36269:30165, - 36270:32058, - 36271:33390, - 36272:39746, - 36273:20123, - 36274:20304, - 36275:21449, - 36276:21766, - 36277:23919, - 36278:24038, - 36279:24046, - 36280:26619, - 36281:27801, - 36282:29811, - 36283:30722, - 36284:35408, - 36285:37782, - 36286:35039, - 36287:22352, - 36288:24231, - 36289:25387, - 36290:20661, - 36291:20652, - 36292:20877, - 36293:26368, - 36294:21705, - 36295:22622, - 36296:22971, - 36297:23472, - 36298:24425, - 36299:25165, - 36300:25505, - 36301:26685, - 36302:27507, - 36303:28168, - 36304:28797, - 36305:37319, - 36306:29312, - 36307:30741, - 36308:30758, - 36309:31085, - 36310:25998, - 36311:32048, - 36312:33756, - 36313:35009, - 36314:36617, - 36315:38555, - 36316:21092, - 36317:22312, - 36318:26448, - 36319:32618, - 36320:36001, - 36321:20916, - 36322:22338, - 36323:38442, - 36324:22586, - 36325:27018, - 36326:32948, - 36327:21682, - 36328:23822, - 36329:22524, - 36330:30869, - 36331:40442, - 36332:20316, - 36333:21066, - 36334:21643, - 36335:25662, - 36336:26152, - 36337:26388, - 36338:26613, - 36339:31364, - 36340:31574, - 36341:32034, - 36342:37679, - 36343:26716, - 36344:39853, - 36345:31545, - 36346:21273, - 36347:20874, - 36348:21047, - 36416:23519, - 36417:25334, - 36418:25774, - 36419:25830, - 36420:26413, - 36421:27578, - 36422:34217, - 36423:38609, - 36424:30352, - 36425:39894, - 36426:25420, - 36427:37638, - 36428:39851, - 36429:30399, - 36430:26194, - 36431:19977, - 36432:20632, - 36433:21442, - 36434:23665, - 36435:24808, - 36436:25746, - 36437:25955, - 36438:26719, - 36439:29158, - 36440:29642, - 36441:29987, - 36442:31639, - 36443:32386, - 36444:34453, - 36445:35715, - 36446:36059, - 36447:37240, - 36448:39184, - 36449:26028, - 36450:26283, - 36451:27531, - 36452:20181, - 36453:20180, - 36454:20282, - 36455:20351, - 36456:21050, - 36457:21496, - 36458:21490, - 36459:21987, - 36460:22235, - 36461:22763, - 36462:22987, - 36463:22985, - 36464:23039, - 36465:23376, - 36466:23629, - 36467:24066, - 36468:24107, - 36469:24535, - 36470:24605, - 36471:25351, - 36472:25903, - 36473:23388, - 36474:26031, - 36475:26045, - 36476:26088, - 36477:26525, - 36478:27490, - 36480:27515, - 36481:27663, - 36482:29509, - 36483:31049, - 36484:31169, - 36485:31992, - 36486:32025, - 36487:32043, - 36488:32930, - 36489:33026, - 36490:33267, - 36491:35222, - 36492:35422, - 36493:35433, - 36494:35430, - 36495:35468, - 36496:35566, - 36497:36039, - 36498:36060, - 36499:38604, - 36500:39164, - 36501:27503, - 36502:20107, - 36503:20284, - 36504:20365, - 36505:20816, - 36506:23383, - 36507:23546, - 36508:24904, - 36509:25345, - 36510:26178, - 36511:27425, - 36512:28363, - 36513:27835, - 36514:29246, - 36515:29885, - 36516:30164, - 36517:30913, - 36518:31034, - 36519:32780, - 36520:32819, - 36521:33258, - 36522:33940, - 36523:36766, - 36524:27728, - 36525:40575, - 36526:24335, - 36527:35672, - 36528:40235, - 36529:31482, - 36530:36600, - 36531:23437, - 36532:38635, - 36533:19971, - 36534:21489, - 36535:22519, - 36536:22833, - 36537:23241, - 36538:23460, - 36539:24713, - 36540:28287, - 36541:28422, - 36542:30142, - 36543:36074, - 36544:23455, - 36545:34048, - 36546:31712, - 36547:20594, - 36548:26612, - 36549:33437, - 36550:23649, - 36551:34122, - 36552:32286, - 36553:33294, - 36554:20889, - 36555:23556, - 36556:25448, - 36557:36198, - 36558:26012, - 36559:29038, - 36560:31038, - 36561:32023, - 36562:32773, - 36563:35613, - 36564:36554, - 36565:36974, - 36566:34503, - 36567:37034, - 36568:20511, - 36569:21242, - 36570:23610, - 36571:26451, - 36572:28796, - 36573:29237, - 36574:37196, - 36575:37320, - 36576:37675, - 36577:33509, - 36578:23490, - 36579:24369, - 36580:24825, - 36581:20027, - 36582:21462, - 36583:23432, - 36584:25163, - 36585:26417, - 36586:27530, - 36587:29417, - 36588:29664, - 36589:31278, - 36590:33131, - 36591:36259, - 36592:37202, - 36593:39318, - 36594:20754, - 36595:21463, - 36596:21610, - 36597:23551, - 36598:25480, - 36599:27193, - 36600:32172, - 36601:38656, - 36602:22234, - 36603:21454, - 36604:21608, - 36672:23447, - 36673:23601, - 36674:24030, - 36675:20462, - 36676:24833, - 36677:25342, - 36678:27954, - 36679:31168, - 36680:31179, - 36681:32066, - 36682:32333, - 36683:32722, - 36684:33261, - 36685:33311, - 36686:33936, - 36687:34886, - 36688:35186, - 36689:35728, - 36690:36468, - 36691:36655, - 36692:36913, - 36693:37195, - 36694:37228, - 36695:38598, - 36696:37276, - 36697:20160, - 36698:20303, - 36699:20805, - 36700:21313, - 36701:24467, - 36702:25102, - 36703:26580, - 36704:27713, - 36705:28171, - 36706:29539, - 36707:32294, - 36708:37325, - 36709:37507, - 36710:21460, - 36711:22809, - 36712:23487, - 36713:28113, - 36714:31069, - 36715:32302, - 36716:31899, - 36717:22654, - 36718:29087, - 36719:20986, - 36720:34899, - 36721:36848, - 36722:20426, - 36723:23803, - 36724:26149, - 36725:30636, - 36726:31459, - 36727:33308, - 36728:39423, - 36729:20934, - 36730:24490, - 36731:26092, - 36732:26991, - 36733:27529, - 36734:28147, - 36736:28310, - 36737:28516, - 36738:30462, - 36739:32020, - 36740:24033, - 36741:36981, - 36742:37255, - 36743:38918, - 36744:20966, - 36745:21021, - 36746:25152, - 36747:26257, - 36748:26329, - 36749:28186, - 36750:24246, - 36751:32210, - 36752:32626, - 36753:26360, - 36754:34223, - 36755:34295, - 36756:35576, - 36757:21161, - 36758:21465, - 36759:22899, - 36760:24207, - 36761:24464, - 36762:24661, - 36763:37604, - 36764:38500, - 36765:20663, - 36766:20767, - 36767:21213, - 36768:21280, - 36769:21319, - 36770:21484, - 36771:21736, - 36772:21830, - 36773:21809, - 36774:22039, - 36775:22888, - 36776:22974, - 36777:23100, - 36778:23477, - 36779:23558, - 36780:23567, - 36781:23569, - 36782:23578, - 36783:24196, - 36784:24202, - 36785:24288, - 36786:24432, - 36787:25215, - 36788:25220, - 36789:25307, - 36790:25484, - 36791:25463, - 36792:26119, - 36793:26124, - 36794:26157, - 36795:26230, - 36796:26494, - 36797:26786, - 36798:27167, - 36799:27189, - 36800:27836, - 36801:28040, - 36802:28169, - 36803:28248, - 36804:28988, - 36805:28966, - 36806:29031, - 36807:30151, - 36808:30465, - 36809:30813, - 36810:30977, - 36811:31077, - 36812:31216, - 36813:31456, - 36814:31505, - 36815:31911, - 36816:32057, - 36817:32918, - 36818:33750, - 36819:33931, - 36820:34121, - 36821:34909, - 36822:35059, - 36823:35359, - 36824:35388, - 36825:35412, - 36826:35443, - 36827:35937, - 36828:36062, - 36829:37284, - 36830:37478, - 36831:37758, - 36832:37912, - 36833:38556, - 36834:38808, - 36835:19978, - 36836:19976, - 36837:19998, - 36838:20055, - 36839:20887, - 36840:21104, - 36841:22478, - 36842:22580, - 36843:22732, - 36844:23330, - 36845:24120, - 36846:24773, - 36847:25854, - 36848:26465, - 36849:26454, - 36850:27972, - 36851:29366, - 36852:30067, - 36853:31331, - 36854:33976, - 36855:35698, - 36856:37304, - 36857:37664, - 36858:22065, - 36859:22516, - 36860:39166, - 36928:25325, - 36929:26893, - 36930:27542, - 36931:29165, - 36932:32340, - 36933:32887, - 36934:33394, - 36935:35302, - 36936:39135, - 36937:34645, - 36938:36785, - 36939:23611, - 36940:20280, - 36941:20449, - 36942:20405, - 36943:21767, - 36944:23072, - 36945:23517, - 36946:23529, - 36947:24515, - 36948:24910, - 36949:25391, - 36950:26032, - 36951:26187, - 36952:26862, - 36953:27035, - 36954:28024, - 36955:28145, - 36956:30003, - 36957:30137, - 36958:30495, - 36959:31070, - 36960:31206, - 36961:32051, - 36962:33251, - 36963:33455, - 36964:34218, - 36965:35242, - 36966:35386, - 36967:36523, - 36968:36763, - 36969:36914, - 36970:37341, - 36971:38663, - 36972:20154, - 36973:20161, - 36974:20995, - 36975:22645, - 36976:22764, - 36977:23563, - 36978:29978, - 36979:23613, - 36980:33102, - 36981:35338, - 36982:36805, - 36983:38499, - 36984:38765, - 36985:31525, - 36986:35535, - 36987:38920, - 36988:37218, - 36989:22259, - 36990:21416, - 36992:36887, - 36993:21561, - 36994:22402, - 36995:24101, - 36996:25512, - 36997:27700, - 36998:28810, - 36999:30561, - 37000:31883, - 37001:32736, - 37002:34928, - 37003:36930, - 37004:37204, - 37005:37648, - 37006:37656, - 37007:38543, - 37008:29790, - 37009:39620, - 37010:23815, - 37011:23913, - 37012:25968, - 37013:26530, - 37014:36264, - 37015:38619, - 37016:25454, - 37017:26441, - 37018:26905, - 37019:33733, - 37020:38935, - 37021:38592, - 37022:35070, - 37023:28548, - 37024:25722, - 37025:23544, - 37026:19990, - 37027:28716, - 37028:30045, - 37029:26159, - 37030:20932, - 37031:21046, - 37032:21218, - 37033:22995, - 37034:24449, - 37035:24615, - 37036:25104, - 37037:25919, - 37038:25972, - 37039:26143, - 37040:26228, - 37041:26866, - 37042:26646, - 37043:27491, - 37044:28165, - 37045:29298, - 37046:29983, - 37047:30427, - 37048:31934, - 37049:32854, - 37050:22768, - 37051:35069, - 37052:35199, - 37053:35488, - 37054:35475, - 37055:35531, - 37056:36893, - 37057:37266, - 37058:38738, - 37059:38745, - 37060:25993, - 37061:31246, - 37062:33030, - 37063:38587, - 37064:24109, - 37065:24796, - 37066:25114, - 37067:26021, - 37068:26132, - 37069:26512, - 37070:30707, - 37071:31309, - 37072:31821, - 37073:32318, - 37074:33034, - 37075:36012, - 37076:36196, - 37077:36321, - 37078:36447, - 37079:30889, - 37080:20999, - 37081:25305, - 37082:25509, - 37083:25666, - 37084:25240, - 37085:35373, - 37086:31363, - 37087:31680, - 37088:35500, - 37089:38634, - 37090:32118, - 37091:33292, - 37092:34633, - 37093:20185, - 37094:20808, - 37095:21315, - 37096:21344, - 37097:23459, - 37098:23554, - 37099:23574, - 37100:24029, - 37101:25126, - 37102:25159, - 37103:25776, - 37104:26643, - 37105:26676, - 37106:27849, - 37107:27973, - 37108:27927, - 37109:26579, - 37110:28508, - 37111:29006, - 37112:29053, - 37113:26059, - 37114:31359, - 37115:31661, - 37116:32218, - 37184:32330, - 37185:32680, - 37186:33146, - 37187:33307, - 37188:33337, - 37189:34214, - 37190:35438, - 37191:36046, - 37192:36341, - 37193:36984, - 37194:36983, - 37195:37549, - 37196:37521, - 37197:38275, - 37198:39854, - 37199:21069, - 37200:21892, - 37201:28472, - 37202:28982, - 37203:20840, - 37204:31109, - 37205:32341, - 37206:33203, - 37207:31950, - 37208:22092, - 37209:22609, - 37210:23720, - 37211:25514, - 37212:26366, - 37213:26365, - 37214:26970, - 37215:29401, - 37216:30095, - 37217:30094, - 37218:30990, - 37219:31062, - 37220:31199, - 37221:31895, - 37222:32032, - 37223:32068, - 37224:34311, - 37225:35380, - 37226:38459, - 37227:36961, - 37228:40736, - 37229:20711, - 37230:21109, - 37231:21452, - 37232:21474, - 37233:20489, - 37234:21930, - 37235:22766, - 37236:22863, - 37237:29245, - 37238:23435, - 37239:23652, - 37240:21277, - 37241:24803, - 37242:24819, - 37243:25436, - 37244:25475, - 37245:25407, - 37246:25531, - 37248:25805, - 37249:26089, - 37250:26361, - 37251:24035, - 37252:27085, - 37253:27133, - 37254:28437, - 37255:29157, - 37256:20105, - 37257:30185, - 37258:30456, - 37259:31379, - 37260:31967, - 37261:32207, - 37262:32156, - 37263:32865, - 37264:33609, - 37265:33624, - 37266:33900, - 37267:33980, - 37268:34299, - 37269:35013, - 37270:36208, - 37271:36865, - 37272:36973, - 37273:37783, - 37274:38684, - 37275:39442, - 37276:20687, - 37277:22679, - 37278:24974, - 37279:33235, - 37280:34101, - 37281:36104, - 37282:36896, - 37283:20419, - 37284:20596, - 37285:21063, - 37286:21363, - 37287:24687, - 37288:25417, - 37289:26463, - 37290:28204, - 37291:36275, - 37292:36895, - 37293:20439, - 37294:23646, - 37295:36042, - 37296:26063, - 37297:32154, - 37298:21330, - 37299:34966, - 37300:20854, - 37301:25539, - 37302:23384, - 37303:23403, - 37304:23562, - 37305:25613, - 37306:26449, - 37307:36956, - 37308:20182, - 37309:22810, - 37310:22826, - 37311:27760, - 37312:35409, - 37313:21822, - 37314:22549, - 37315:22949, - 37316:24816, - 37317:25171, - 37318:26561, - 37319:33333, - 37320:26965, - 37321:38464, - 37322:39364, - 37323:39464, - 37324:20307, - 37325:22534, - 37326:23550, - 37327:32784, - 37328:23729, - 37329:24111, - 37330:24453, - 37331:24608, - 37332:24907, - 37333:25140, - 37334:26367, - 37335:27888, - 37336:28382, - 37337:32974, - 37338:33151, - 37339:33492, - 37340:34955, - 37341:36024, - 37342:36864, - 37343:36910, - 37344:38538, - 37345:40667, - 37346:39899, - 37347:20195, - 37348:21488, - 37349:22823, - 37350:31532, - 37351:37261, - 37352:38988, - 37353:40441, - 37354:28381, - 37355:28711, - 37356:21331, - 37357:21828, - 37358:23429, - 37359:25176, - 37360:25246, - 37361:25299, - 37362:27810, - 37363:28655, - 37364:29730, - 37365:35351, - 37366:37944, - 37367:28609, - 37368:35582, - 37369:33592, - 37370:20967, - 37371:34552, - 37372:21482, - 37440:21481, - 37441:20294, - 37442:36948, - 37443:36784, - 37444:22890, - 37445:33073, - 37446:24061, - 37447:31466, - 37448:36799, - 37449:26842, - 37450:35895, - 37451:29432, - 37452:40008, - 37453:27197, - 37454:35504, - 37455:20025, - 37456:21336, - 37457:22022, - 37458:22374, - 37459:25285, - 37460:25506, - 37461:26086, - 37462:27470, - 37463:28129, - 37464:28251, - 37465:28845, - 37466:30701, - 37467:31471, - 37468:31658, - 37469:32187, - 37470:32829, - 37471:32966, - 37472:34507, - 37473:35477, - 37474:37723, - 37475:22243, - 37476:22727, - 37477:24382, - 37478:26029, - 37479:26262, - 37480:27264, - 37481:27573, - 37482:30007, - 37483:35527, - 37484:20516, - 37485:30693, - 37486:22320, - 37487:24347, - 37488:24677, - 37489:26234, - 37490:27744, - 37491:30196, - 37492:31258, - 37493:32622, - 37494:33268, - 37495:34584, - 37496:36933, - 37497:39347, - 37498:31689, - 37499:30044, - 37500:31481, - 37501:31569, - 37502:33988, - 37504:36880, - 37505:31209, - 37506:31378, - 37507:33590, - 37508:23265, - 37509:30528, - 37510:20013, - 37511:20210, - 37512:23449, - 37513:24544, - 37514:25277, - 37515:26172, - 37516:26609, - 37517:27880, - 37518:34411, - 37519:34935, - 37520:35387, - 37521:37198, - 37522:37619, - 37523:39376, - 37524:27159, - 37525:28710, - 37526:29482, - 37527:33511, - 37528:33879, - 37529:36015, - 37530:19969, - 37531:20806, - 37532:20939, - 37533:21899, - 37534:23541, - 37535:24086, - 37536:24115, - 37537:24193, - 37538:24340, - 37539:24373, - 37540:24427, - 37541:24500, - 37542:25074, - 37543:25361, - 37544:26274, - 37545:26397, - 37546:28526, - 37547:29266, - 37548:30010, - 37549:30522, - 37550:32884, - 37551:33081, - 37552:33144, - 37553:34678, - 37554:35519, - 37555:35548, - 37556:36229, - 37557:36339, - 37558:37530, - 37559:38263, - 37560:38914, - 37561:40165, - 37562:21189, - 37563:25431, - 37564:30452, - 37565:26389, - 37566:27784, - 37567:29645, - 37568:36035, - 37569:37806, - 37570:38515, - 37571:27941, - 37572:22684, - 37573:26894, - 37574:27084, - 37575:36861, - 37576:37786, - 37577:30171, - 37578:36890, - 37579:22618, - 37580:26626, - 37581:25524, - 37582:27131, - 37583:20291, - 37584:28460, - 37585:26584, - 37586:36795, - 37587:34086, - 37588:32180, - 37589:37716, - 37590:26943, - 37591:28528, - 37592:22378, - 37593:22775, - 37594:23340, - 37595:32044, - 37596:29226, - 37597:21514, - 37598:37347, - 37599:40372, - 37600:20141, - 37601:20302, - 37602:20572, - 37603:20597, - 37604:21059, - 37605:35998, - 37606:21576, - 37607:22564, - 37608:23450, - 37609:24093, - 37610:24213, - 37611:24237, - 37612:24311, - 37613:24351, - 37614:24716, - 37615:25269, - 37616:25402, - 37617:25552, - 37618:26799, - 37619:27712, - 37620:30855, - 37621:31118, - 37622:31243, - 37623:32224, - 37624:33351, - 37625:35330, - 37626:35558, - 37627:36420, - 37628:36883, - 37696:37048, - 37697:37165, - 37698:37336, - 37699:40718, - 37700:27877, - 37701:25688, - 37702:25826, - 37703:25973, - 37704:28404, - 37705:30340, - 37706:31515, - 37707:36969, - 37708:37841, - 37709:28346, - 37710:21746, - 37711:24505, - 37712:25764, - 37713:36685, - 37714:36845, - 37715:37444, - 37716:20856, - 37717:22635, - 37718:22825, - 37719:23637, - 37720:24215, - 37721:28155, - 37722:32399, - 37723:29980, - 37724:36028, - 37725:36578, - 37726:39003, - 37727:28857, - 37728:20253, - 37729:27583, - 37730:28593, - 37731:30000, - 37732:38651, - 37733:20814, - 37734:21520, - 37735:22581, - 37736:22615, - 37737:22956, - 37738:23648, - 37739:24466, - 37740:26007, - 37741:26460, - 37742:28193, - 37743:30331, - 37744:33759, - 37745:36077, - 37746:36884, - 37747:37117, - 37748:37709, - 37749:30757, - 37750:30778, - 37751:21162, - 37752:24230, - 37753:22303, - 37754:22900, - 37755:24594, - 37756:20498, - 37757:20826, - 37758:20908, - 37760:20941, - 37761:20992, - 37762:21776, - 37763:22612, - 37764:22616, - 37765:22871, - 37766:23445, - 37767:23798, - 37768:23947, - 37769:24764, - 37770:25237, - 37771:25645, - 37772:26481, - 37773:26691, - 37774:26812, - 37775:26847, - 37776:30423, - 37777:28120, - 37778:28271, - 37779:28059, - 37780:28783, - 37781:29128, - 37782:24403, - 37783:30168, - 37784:31095, - 37785:31561, - 37786:31572, - 37787:31570, - 37788:31958, - 37789:32113, - 37790:21040, - 37791:33891, - 37792:34153, - 37793:34276, - 37794:35342, - 37795:35588, - 37796:35910, - 37797:36367, - 37798:36867, - 37799:36879, - 37800:37913, - 37801:38518, - 37802:38957, - 37803:39472, - 37804:38360, - 37805:20685, - 37806:21205, - 37807:21516, - 37808:22530, - 37809:23566, - 37810:24999, - 37811:25758, - 37812:27934, - 37813:30643, - 37814:31461, - 37815:33012, - 37816:33796, - 37817:36947, - 37818:37509, - 37819:23776, - 37820:40199, - 37821:21311, - 37822:24471, - 37823:24499, - 37824:28060, - 37825:29305, - 37826:30563, - 37827:31167, - 37828:31716, - 37829:27602, - 37830:29420, - 37831:35501, - 37832:26627, - 37833:27233, - 37834:20984, - 37835:31361, - 37836:26932, - 37837:23626, - 37838:40182, - 37839:33515, - 37840:23493, - 37841:37193, - 37842:28702, - 37843:22136, - 37844:23663, - 37845:24775, - 37846:25958, - 37847:27788, - 37848:35930, - 37849:36929, - 37850:38931, - 37851:21585, - 37852:26311, - 37853:37389, - 37854:22856, - 37855:37027, - 37856:20869, - 37857:20045, - 37858:20970, - 37859:34201, - 37860:35598, - 37861:28760, - 37862:25466, - 37863:37707, - 37864:26978, - 37865:39348, - 37866:32260, - 37867:30071, - 37868:21335, - 37869:26976, - 37870:36575, - 37871:38627, - 37872:27741, - 37873:20108, - 37874:23612, - 37875:24336, - 37876:36841, - 37877:21250, - 37878:36049, - 37879:32905, - 37880:34425, - 37881:24319, - 37882:26085, - 37883:20083, - 37884:20837, - 37952:22914, - 37953:23615, - 37954:38894, - 37955:20219, - 37956:22922, - 37957:24525, - 37958:35469, - 37959:28641, - 37960:31152, - 37961:31074, - 37962:23527, - 37963:33905, - 37964:29483, - 37965:29105, - 37966:24180, - 37967:24565, - 37968:25467, - 37969:25754, - 37970:29123, - 37971:31896, - 37972:20035, - 37973:24316, - 37974:20043, - 37975:22492, - 37976:22178, - 37977:24745, - 37978:28611, - 37979:32013, - 37980:33021, - 37981:33075, - 37982:33215, - 37983:36786, - 37984:35223, - 37985:34468, - 37986:24052, - 37987:25226, - 37988:25773, - 37989:35207, - 37990:26487, - 37991:27874, - 37992:27966, - 37993:29750, - 37994:30772, - 37995:23110, - 37996:32629, - 37997:33453, - 37998:39340, - 37999:20467, - 38000:24259, - 38001:25309, - 38002:25490, - 38003:25943, - 38004:26479, - 38005:30403, - 38006:29260, - 38007:32972, - 38008:32954, - 38009:36649, - 38010:37197, - 38011:20493, - 38012:22521, - 38013:23186, - 38014:26757, - 38016:26995, - 38017:29028, - 38018:29437, - 38019:36023, - 38020:22770, - 38021:36064, - 38022:38506, - 38023:36889, - 38024:34687, - 38025:31204, - 38026:30695, - 38027:33833, - 38028:20271, - 38029:21093, - 38030:21338, - 38031:25293, - 38032:26575, - 38033:27850, - 38034:30333, - 38035:31636, - 38036:31893, - 38037:33334, - 38038:34180, - 38039:36843, - 38040:26333, - 38041:28448, - 38042:29190, - 38043:32283, - 38044:33707, - 38045:39361, - 38046:40614, - 38047:20989, - 38048:31665, - 38049:30834, - 38050:31672, - 38051:32903, - 38052:31560, - 38053:27368, - 38054:24161, - 38055:32908, - 38056:30033, - 38057:30048, - 38058:20843, - 38059:37474, - 38060:28300, - 38061:30330, - 38062:37271, - 38063:39658, - 38064:20240, - 38065:32624, - 38066:25244, - 38067:31567, - 38068:38309, - 38069:40169, - 38070:22138, - 38071:22617, - 38072:34532, - 38073:38588, - 38074:20276, - 38075:21028, - 38076:21322, - 38077:21453, - 38078:21467, - 38079:24070, - 38080:25644, - 38081:26001, - 38082:26495, - 38083:27710, - 38084:27726, - 38085:29256, - 38086:29359, - 38087:29677, - 38088:30036, - 38089:32321, - 38090:33324, - 38091:34281, - 38092:36009, - 38093:31684, - 38094:37318, - 38095:29033, - 38096:38930, - 38097:39151, - 38098:25405, - 38099:26217, - 38100:30058, - 38101:30436, - 38102:30928, - 38103:34115, - 38104:34542, - 38105:21290, - 38106:21329, - 38107:21542, - 38108:22915, - 38109:24199, - 38110:24444, - 38111:24754, - 38112:25161, - 38113:25209, - 38114:25259, - 38115:26000, - 38116:27604, - 38117:27852, - 38118:30130, - 38119:30382, - 38120:30865, - 38121:31192, - 38122:32203, - 38123:32631, - 38124:32933, - 38125:34987, - 38126:35513, - 38127:36027, - 38128:36991, - 38129:38750, - 38130:39131, - 38131:27147, - 38132:31800, - 38133:20633, - 38134:23614, - 38135:24494, - 38136:26503, - 38137:27608, - 38138:29749, - 38139:30473, - 38140:32654, - 38208:40763, - 38209:26570, - 38210:31255, - 38211:21305, - 38212:30091, - 38213:39661, - 38214:24422, - 38215:33181, - 38216:33777, - 38217:32920, - 38218:24380, - 38219:24517, - 38220:30050, - 38221:31558, - 38222:36924, - 38223:26727, - 38224:23019, - 38225:23195, - 38226:32016, - 38227:30334, - 38228:35628, - 38229:20469, - 38230:24426, - 38231:27161, - 38232:27703, - 38233:28418, - 38234:29922, - 38235:31080, - 38236:34920, - 38237:35413, - 38238:35961, - 38239:24287, - 38240:25551, - 38241:30149, - 38242:31186, - 38243:33495, - 38244:37672, - 38245:37618, - 38246:33948, - 38247:34541, - 38248:39981, - 38249:21697, - 38250:24428, - 38251:25996, - 38252:27996, - 38253:28693, - 38254:36007, - 38255:36051, - 38256:38971, - 38257:25935, - 38258:29942, - 38259:19981, - 38260:20184, - 38261:22496, - 38262:22827, - 38263:23142, - 38264:23500, - 38265:20904, - 38266:24067, - 38267:24220, - 38268:24598, - 38269:25206, - 38270:25975, - 38272:26023, - 38273:26222, - 38274:28014, - 38275:29238, - 38276:31526, - 38277:33104, - 38278:33178, - 38279:33433, - 38280:35676, - 38281:36000, - 38282:36070, - 38283:36212, - 38284:38428, - 38285:38468, - 38286:20398, - 38287:25771, - 38288:27494, - 38289:33310, - 38290:33889, - 38291:34154, - 38292:37096, - 38293:23553, - 38294:26963, - 38295:39080, - 38296:33914, - 38297:34135, - 38298:20239, - 38299:21103, - 38300:24489, - 38301:24133, - 38302:26381, - 38303:31119, - 38304:33145, - 38305:35079, - 38306:35206, - 38307:28149, - 38308:24343, - 38309:25173, - 38310:27832, - 38311:20175, - 38312:29289, - 38313:39826, - 38314:20998, - 38315:21563, - 38316:22132, - 38317:22707, - 38318:24996, - 38319:25198, - 38320:28954, - 38321:22894, - 38322:31881, - 38323:31966, - 38324:32027, - 38325:38640, - 38326:25991, - 38327:32862, - 38328:19993, - 38329:20341, - 38330:20853, - 38331:22592, - 38332:24163, - 38333:24179, - 38334:24330, - 38335:26564, - 38336:20006, - 38337:34109, - 38338:38281, - 38339:38491, - 38340:31859, - 38341:38913, - 38342:20731, - 38343:22721, - 38344:30294, - 38345:30887, - 38346:21029, - 38347:30629, - 38348:34065, - 38349:31622, - 38350:20559, - 38351:22793, - 38352:29255, - 38353:31687, - 38354:32232, - 38355:36794, - 38356:36820, - 38357:36941, - 38358:20415, - 38359:21193, - 38360:23081, - 38361:24321, - 38362:38829, - 38363:20445, - 38364:33303, - 38365:37610, - 38366:22275, - 38367:25429, - 38368:27497, - 38369:29995, - 38370:35036, - 38371:36628, - 38372:31298, - 38373:21215, - 38374:22675, - 38375:24917, - 38376:25098, - 38377:26286, - 38378:27597, - 38379:31807, - 38380:33769, - 38381:20515, - 38382:20472, - 38383:21253, - 38384:21574, - 38385:22577, - 38386:22857, - 38387:23453, - 38388:23792, - 38389:23791, - 38390:23849, - 38391:24214, - 38392:25265, - 38393:25447, - 38394:25918, - 38395:26041, - 38396:26379, - 38464:27861, - 38465:27873, - 38466:28921, - 38467:30770, - 38468:32299, - 38469:32990, - 38470:33459, - 38471:33804, - 38472:34028, - 38473:34562, - 38474:35090, - 38475:35370, - 38476:35914, - 38477:37030, - 38478:37586, - 38479:39165, - 38480:40179, - 38481:40300, - 38482:20047, - 38483:20129, - 38484:20621, - 38485:21078, - 38486:22346, - 38487:22952, - 38488:24125, - 38489:24536, - 38490:24537, - 38491:25151, - 38492:26292, - 38493:26395, - 38494:26576, - 38495:26834, - 38496:20882, - 38497:32033, - 38498:32938, - 38499:33192, - 38500:35584, - 38501:35980, - 38502:36031, - 38503:37502, - 38504:38450, - 38505:21536, - 38506:38956, - 38507:21271, - 38508:20693, - 38509:21340, - 38510:22696, - 38511:25778, - 38512:26420, - 38513:29287, - 38514:30566, - 38515:31302, - 38516:37350, - 38517:21187, - 38518:27809, - 38519:27526, - 38520:22528, - 38521:24140, - 38522:22868, - 38523:26412, - 38524:32763, - 38525:20961, - 38526:30406, - 38528:25705, - 38529:30952, - 38530:39764, - 38531:40635, - 38532:22475, - 38533:22969, - 38534:26151, - 38535:26522, - 38536:27598, - 38537:21737, - 38538:27097, - 38539:24149, - 38540:33180, - 38541:26517, - 38542:39850, - 38543:26622, - 38544:40018, - 38545:26717, - 38546:20134, - 38547:20451, - 38548:21448, - 38549:25273, - 38550:26411, - 38551:27819, - 38552:36804, - 38553:20397, - 38554:32365, - 38555:40639, - 38556:19975, - 38557:24930, - 38558:28288, - 38559:28459, - 38560:34067, - 38561:21619, - 38562:26410, - 38563:39749, - 38564:24051, - 38565:31637, - 38566:23724, - 38567:23494, - 38568:34588, - 38569:28234, - 38570:34001, - 38571:31252, - 38572:33032, - 38573:22937, - 38574:31885, - 38575:27665, - 38576:30496, - 38577:21209, - 38578:22818, - 38579:28961, - 38580:29279, - 38581:30683, - 38582:38695, - 38583:40289, - 38584:26891, - 38585:23167, - 38586:23064, - 38587:20901, - 38588:21517, - 38589:21629, - 38590:26126, - 38591:30431, - 38592:36855, - 38593:37528, - 38594:40180, - 38595:23018, - 38596:29277, - 38597:28357, - 38598:20813, - 38599:26825, - 38600:32191, - 38601:32236, - 38602:38754, - 38603:40634, - 38604:25720, - 38605:27169, - 38606:33538, - 38607:22916, - 38608:23391, - 38609:27611, - 38610:29467, - 38611:30450, - 38612:32178, - 38613:32791, - 38614:33945, - 38615:20786, - 38616:26408, - 38617:40665, - 38618:30446, - 38619:26466, - 38620:21247, - 38621:39173, - 38622:23588, - 38623:25147, - 38624:31870, - 38625:36016, - 38626:21839, - 38627:24758, - 38628:32011, - 38629:38272, - 38630:21249, - 38631:20063, - 38632:20918, - 38633:22812, - 38634:29242, - 38635:32822, - 38636:37326, - 38637:24357, - 38638:30690, - 38639:21380, - 38640:24441, - 38641:32004, - 38642:34220, - 38643:35379, - 38644:36493, - 38645:38742, - 38646:26611, - 38647:34222, - 38648:37971, - 38649:24841, - 38650:24840, - 38651:27833, - 38652:30290, - 38720:35565, - 38721:36664, - 38722:21807, - 38723:20305, - 38724:20778, - 38725:21191, - 38726:21451, - 38727:23461, - 38728:24189, - 38729:24736, - 38730:24962, - 38731:25558, - 38732:26377, - 38733:26586, - 38734:28263, - 38735:28044, - 38736:29494, - 38737:29495, - 38738:30001, - 38739:31056, - 38740:35029, - 38741:35480, - 38742:36938, - 38743:37009, - 38744:37109, - 38745:38596, - 38746:34701, - 38747:22805, - 38748:20104, - 38749:20313, - 38750:19982, - 38751:35465, - 38752:36671, - 38753:38928, - 38754:20653, - 38755:24188, - 38756:22934, - 38757:23481, - 38758:24248, - 38759:25562, - 38760:25594, - 38761:25793, - 38762:26332, - 38763:26954, - 38764:27096, - 38765:27915, - 38766:28342, - 38767:29076, - 38768:29992, - 38769:31407, - 38770:32650, - 38771:32768, - 38772:33865, - 38773:33993, - 38774:35201, - 38775:35617, - 38776:36362, - 38777:36965, - 38778:38525, - 38779:39178, - 38780:24958, - 38781:25233, - 38782:27442, - 38784:27779, - 38785:28020, - 38786:32716, - 38787:32764, - 38788:28096, - 38789:32645, - 38790:34746, - 38791:35064, - 38792:26469, - 38793:33713, - 38794:38972, - 38795:38647, - 38796:27931, - 38797:32097, - 38798:33853, - 38799:37226, - 38800:20081, - 38801:21365, - 38802:23888, - 38803:27396, - 38804:28651, - 38805:34253, - 38806:34349, - 38807:35239, - 38808:21033, - 38809:21519, - 38810:23653, - 38811:26446, - 38812:26792, - 38813:29702, - 38814:29827, - 38815:30178, - 38816:35023, - 38817:35041, - 38818:37324, - 38819:38626, - 38820:38520, - 38821:24459, - 38822:29575, - 38823:31435, - 38824:33870, - 38825:25504, - 38826:30053, - 38827:21129, - 38828:27969, - 38829:28316, - 38830:29705, - 38831:30041, - 38832:30827, - 38833:31890, - 38834:38534, - 38835:31452, - 38836:40845, - 38837:20406, - 38838:24942, - 38839:26053, - 38840:34396, - 38841:20102, - 38842:20142, - 38843:20698, - 38844:20001, - 38845:20940, - 38846:23534, - 38847:26009, - 38848:26753, - 38849:28092, - 38850:29471, - 38851:30274, - 38852:30637, - 38853:31260, - 38854:31975, - 38855:33391, - 38856:35538, - 38857:36988, - 38858:37327, - 38859:38517, - 38860:38936, - 38861:21147, - 38862:32209, - 38863:20523, - 38864:21400, - 38865:26519, - 38866:28107, - 38867:29136, - 38868:29747, - 38869:33256, - 38870:36650, - 38871:38563, - 38872:40023, - 38873:40607, - 38874:29792, - 38875:22593, - 38876:28057, - 38877:32047, - 38878:39006, - 38879:20196, - 38880:20278, - 38881:20363, - 38882:20919, - 38883:21169, - 38884:23994, - 38885:24604, - 38886:29618, - 38887:31036, - 38888:33491, - 38889:37428, - 38890:38583, - 38891:38646, - 38892:38666, - 38893:40599, - 38894:40802, - 38895:26278, - 38896:27508, - 38897:21015, - 38898:21155, - 38899:28872, - 38900:35010, - 38901:24265, - 38902:24651, - 38903:24976, - 38904:28451, - 38905:29001, - 38906:31806, - 38907:32244, - 38908:32879, - 38976:34030, - 38977:36899, - 38978:37676, - 38979:21570, - 38980:39791, - 38981:27347, - 38982:28809, - 38983:36034, - 38984:36335, - 38985:38706, - 38986:21172, - 38987:23105, - 38988:24266, - 38989:24324, - 38990:26391, - 38991:27004, - 38992:27028, - 38993:28010, - 38994:28431, - 38995:29282, - 38996:29436, - 38997:31725, - 38998:32769, - 38999:32894, - 39000:34635, - 39001:37070, - 39002:20845, - 39003:40595, - 39004:31108, - 39005:32907, - 39006:37682, - 39007:35542, - 39008:20525, - 39009:21644, - 39010:35441, - 39011:27498, - 39012:36036, - 39013:33031, - 39014:24785, - 39015:26528, - 39016:40434, - 39017:20121, - 39018:20120, - 39019:39952, - 39020:35435, - 39021:34241, - 39022:34152, - 39023:26880, - 39024:28286, - 39025:30871, - 39026:33109, - 39071:24332, - 39072:19984, - 39073:19989, - 39074:20010, - 39075:20017, - 39076:20022, - 39077:20028, - 39078:20031, - 39079:20034, - 39080:20054, - 39081:20056, - 39082:20098, - 39083:20101, - 39084:35947, - 39085:20106, - 39086:33298, - 39087:24333, - 39088:20110, - 39089:20126, - 39090:20127, - 39091:20128, - 39092:20130, - 39093:20144, - 39094:20147, - 39095:20150, - 39096:20174, - 39097:20173, - 39098:20164, - 39099:20166, - 39100:20162, - 39101:20183, - 39102:20190, - 39103:20205, - 39104:20191, - 39105:20215, - 39106:20233, - 39107:20314, - 39108:20272, - 39109:20315, - 39110:20317, - 39111:20311, - 39112:20295, - 39113:20342, - 39114:20360, - 39115:20367, - 39116:20376, - 39117:20347, - 39118:20329, - 39119:20336, - 39120:20369, - 39121:20335, - 39122:20358, - 39123:20374, - 39124:20760, - 39125:20436, - 39126:20447, - 39127:20430, - 39128:20440, - 39129:20443, - 39130:20433, - 39131:20442, - 39132:20432, - 39133:20452, - 39134:20453, - 39135:20506, - 39136:20520, - 39137:20500, - 39138:20522, - 39139:20517, - 39140:20485, - 39141:20252, - 39142:20470, - 39143:20513, - 39144:20521, - 39145:20524, - 39146:20478, - 39147:20463, - 39148:20497, - 39149:20486, - 39150:20547, - 39151:20551, - 39152:26371, - 39153:20565, - 39154:20560, - 39155:20552, - 39156:20570, - 39157:20566, - 39158:20588, - 39159:20600, - 39160:20608, - 39161:20634, - 39162:20613, - 39163:20660, - 39164:20658, - 39232:20681, - 39233:20682, - 39234:20659, - 39235:20674, - 39236:20694, - 39237:20702, - 39238:20709, - 39239:20717, - 39240:20707, - 39241:20718, - 39242:20729, - 39243:20725, - 39244:20745, - 39245:20737, - 39246:20738, - 39247:20758, - 39248:20757, - 39249:20756, - 39250:20762, - 39251:20769, - 39252:20794, - 39253:20791, - 39254:20796, - 39255:20795, - 39256:20799, - 39257:20800, - 39258:20818, - 39259:20812, - 39260:20820, - 39261:20834, - 39262:31480, - 39263:20841, - 39264:20842, - 39265:20846, - 39266:20864, - 39267:20866, - 39268:22232, - 39269:20876, - 39270:20873, - 39271:20879, - 39272:20881, - 39273:20883, - 39274:20885, - 39275:20886, - 39276:20900, - 39277:20902, - 39278:20898, - 39279:20905, - 39280:20906, - 39281:20907, - 39282:20915, - 39283:20913, - 39284:20914, - 39285:20912, - 39286:20917, - 39287:20925, - 39288:20933, - 39289:20937, - 39290:20955, - 39291:20960, - 39292:34389, - 39293:20969, - 39294:20973, - 39296:20976, - 39297:20981, - 39298:20990, - 39299:20996, - 39300:21003, - 39301:21012, - 39302:21006, - 39303:21031, - 39304:21034, - 39305:21038, - 39306:21043, - 39307:21049, - 39308:21071, - 39309:21060, - 39310:21067, - 39311:21068, - 39312:21086, - 39313:21076, - 39314:21098, - 39315:21108, - 39316:21097, - 39317:21107, - 39318:21119, - 39319:21117, - 39320:21133, - 39321:21140, - 39322:21138, - 39323:21105, - 39324:21128, - 39325:21137, - 39326:36776, - 39327:36775, - 39328:21164, - 39329:21165, - 39330:21180, - 39331:21173, - 39332:21185, - 39333:21197, - 39334:21207, - 39335:21214, - 39336:21219, - 39337:21222, - 39338:39149, - 39339:21216, - 39340:21235, - 39341:21237, - 39342:21240, - 39343:21241, - 39344:21254, - 39345:21256, - 39346:30008, - 39347:21261, - 39348:21264, - 39349:21263, - 39350:21269, - 39351:21274, - 39352:21283, - 39353:21295, - 39354:21297, - 39355:21299, - 39356:21304, - 39357:21312, - 39358:21318, - 39359:21317, - 39360:19991, - 39361:21321, - 39362:21325, - 39363:20950, - 39364:21342, - 39365:21353, - 39366:21358, - 39367:22808, - 39368:21371, - 39369:21367, - 39370:21378, - 39371:21398, - 39372:21408, - 39373:21414, - 39374:21413, - 39375:21422, - 39376:21424, - 39377:21430, - 39378:21443, - 39379:31762, - 39380:38617, - 39381:21471, - 39382:26364, - 39383:29166, - 39384:21486, - 39385:21480, - 39386:21485, - 39387:21498, - 39388:21505, - 39389:21565, - 39390:21568, - 39391:21548, - 39392:21549, - 39393:21564, - 39394:21550, - 39395:21558, - 39396:21545, - 39397:21533, - 39398:21582, - 39399:21647, - 39400:21621, - 39401:21646, - 39402:21599, - 39403:21617, - 39404:21623, - 39405:21616, - 39406:21650, - 39407:21627, - 39408:21632, - 39409:21622, - 39410:21636, - 39411:21648, - 39412:21638, - 39413:21703, - 39414:21666, - 39415:21688, - 39416:21669, - 39417:21676, - 39418:21700, - 39419:21704, - 39420:21672, - 39488:21675, - 39489:21698, - 39490:21668, - 39491:21694, - 39492:21692, - 39493:21720, - 39494:21733, - 39495:21734, - 39496:21775, - 39497:21780, - 39498:21757, - 39499:21742, - 39500:21741, - 39501:21754, - 39502:21730, - 39503:21817, - 39504:21824, - 39505:21859, - 39506:21836, - 39507:21806, - 39508:21852, - 39509:21829, - 39510:21846, - 39511:21847, - 39512:21816, - 39513:21811, - 39514:21853, - 39515:21913, - 39516:21888, - 39517:21679, - 39518:21898, - 39519:21919, - 39520:21883, - 39521:21886, - 39522:21912, - 39523:21918, - 39524:21934, - 39525:21884, - 39526:21891, - 39527:21929, - 39528:21895, - 39529:21928, - 39530:21978, - 39531:21957, - 39532:21983, - 39533:21956, - 39534:21980, - 39535:21988, - 39536:21972, - 39537:22036, - 39538:22007, - 39539:22038, - 39540:22014, - 39541:22013, - 39542:22043, - 39543:22009, - 39544:22094, - 39545:22096, - 39546:29151, - 39547:22068, - 39548:22070, - 39549:22066, - 39550:22072, - 39552:22123, - 39553:22116, - 39554:22063, - 39555:22124, - 39556:22122, - 39557:22150, - 39558:22144, - 39559:22154, - 39560:22176, - 39561:22164, - 39562:22159, - 39563:22181, - 39564:22190, - 39565:22198, - 39566:22196, - 39567:22210, - 39568:22204, - 39569:22209, - 39570:22211, - 39571:22208, - 39572:22216, - 39573:22222, - 39574:22225, - 39575:22227, - 39576:22231, - 39577:22254, - 39578:22265, - 39579:22272, - 39580:22271, - 39581:22276, - 39582:22281, - 39583:22280, - 39584:22283, - 39585:22285, - 39586:22291, - 39587:22296, - 39588:22294, - 39589:21959, - 39590:22300, - 39591:22310, - 39592:22327, - 39593:22328, - 39594:22350, - 39595:22331, - 39596:22336, - 39597:22351, - 39598:22377, - 39599:22464, - 39600:22408, - 39601:22369, - 39602:22399, - 39603:22409, - 39604:22419, - 39605:22432, - 39606:22451, - 39607:22436, - 39608:22442, - 39609:22448, - 39610:22467, - 39611:22470, - 39612:22484, - 39613:22482, - 39614:22483, - 39615:22538, - 39616:22486, - 39617:22499, - 39618:22539, - 39619:22553, - 39620:22557, - 39621:22642, - 39622:22561, - 39623:22626, - 39624:22603, - 39625:22640, - 39626:27584, - 39627:22610, - 39628:22589, - 39629:22649, - 39630:22661, - 39631:22713, - 39632:22687, - 39633:22699, - 39634:22714, - 39635:22750, - 39636:22715, - 39637:22712, - 39638:22702, - 39639:22725, - 39640:22739, - 39641:22737, - 39642:22743, - 39643:22745, - 39644:22744, - 39645:22757, - 39646:22748, - 39647:22756, - 39648:22751, - 39649:22767, - 39650:22778, - 39651:22777, - 39652:22779, - 39653:22780, - 39654:22781, - 39655:22786, - 39656:22794, - 39657:22800, - 39658:22811, - 39659:26790, - 39660:22821, - 39661:22828, - 39662:22829, - 39663:22834, - 39664:22840, - 39665:22846, - 39666:31442, - 39667:22869, - 39668:22864, - 39669:22862, - 39670:22874, - 39671:22872, - 39672:22882, - 39673:22880, - 39674:22887, - 39675:22892, - 39676:22889, - 39744:22904, - 39745:22913, - 39746:22941, - 39747:20318, - 39748:20395, - 39749:22947, - 39750:22962, - 39751:22982, - 39752:23016, - 39753:23004, - 39754:22925, - 39755:23001, - 39756:23002, - 39757:23077, - 39758:23071, - 39759:23057, - 39760:23068, - 39761:23049, - 39762:23066, - 39763:23104, - 39764:23148, - 39765:23113, - 39766:23093, - 39767:23094, - 39768:23138, - 39769:23146, - 39770:23194, - 39771:23228, - 39772:23230, - 39773:23243, - 39774:23234, - 39775:23229, - 39776:23267, - 39777:23255, - 39778:23270, - 39779:23273, - 39780:23254, - 39781:23290, - 39782:23291, - 39783:23308, - 39784:23307, - 39785:23318, - 39786:23346, - 39787:23248, - 39788:23338, - 39789:23350, - 39790:23358, - 39791:23363, - 39792:23365, - 39793:23360, - 39794:23377, - 39795:23381, - 39796:23386, - 39797:23387, - 39798:23397, - 39799:23401, - 39800:23408, - 39801:23411, - 39802:23413, - 39803:23416, - 39804:25992, - 39805:23418, - 39806:23424, - 39808:23427, - 39809:23462, - 39810:23480, - 39811:23491, - 39812:23495, - 39813:23497, - 39814:23508, - 39815:23504, - 39816:23524, - 39817:23526, - 39818:23522, - 39819:23518, - 39820:23525, - 39821:23531, - 39822:23536, - 39823:23542, - 39824:23539, - 39825:23557, - 39826:23559, - 39827:23560, - 39828:23565, - 39829:23571, - 39830:23584, - 39831:23586, - 39832:23592, - 39833:23608, - 39834:23609, - 39835:23617, - 39836:23622, - 39837:23630, - 39838:23635, - 39839:23632, - 39840:23631, - 39841:23409, - 39842:23660, - 39843:23662, - 39844:20066, - 39845:23670, - 39846:23673, - 39847:23692, - 39848:23697, - 39849:23700, - 39850:22939, - 39851:23723, - 39852:23739, - 39853:23734, - 39854:23740, - 39855:23735, - 39856:23749, - 39857:23742, - 39858:23751, - 39859:23769, - 39860:23785, - 39861:23805, - 39862:23802, - 39863:23789, - 39864:23948, - 39865:23786, - 39866:23819, - 39867:23829, - 39868:23831, - 39869:23900, - 39870:23839, - 39871:23835, - 39872:23825, - 39873:23828, - 39874:23842, - 39875:23834, - 39876:23833, - 39877:23832, - 39878:23884, - 39879:23890, - 39880:23886, - 39881:23883, - 39882:23916, - 39883:23923, - 39884:23926, - 39885:23943, - 39886:23940, - 39887:23938, - 39888:23970, - 39889:23965, - 39890:23980, - 39891:23982, - 39892:23997, - 39893:23952, - 39894:23991, - 39895:23996, - 39896:24009, - 39897:24013, - 39898:24019, - 39899:24018, - 39900:24022, - 39901:24027, - 39902:24043, - 39903:24050, - 39904:24053, - 39905:24075, - 39906:24090, - 39907:24089, - 39908:24081, - 39909:24091, - 39910:24118, - 39911:24119, - 39912:24132, - 39913:24131, - 39914:24128, - 39915:24142, - 39916:24151, - 39917:24148, - 39918:24159, - 39919:24162, - 39920:24164, - 39921:24135, - 39922:24181, - 39923:24182, - 39924:24186, - 39925:40636, - 39926:24191, - 39927:24224, - 39928:24257, - 39929:24258, - 39930:24264, - 39931:24272, - 39932:24271, - 40000:24278, - 40001:24291, - 40002:24285, - 40003:24282, - 40004:24283, - 40005:24290, - 40006:24289, - 40007:24296, - 40008:24297, - 40009:24300, - 40010:24305, - 40011:24307, - 40012:24304, - 40013:24308, - 40014:24312, - 40015:24318, - 40016:24323, - 40017:24329, - 40018:24413, - 40019:24412, - 40020:24331, - 40021:24337, - 40022:24342, - 40023:24361, - 40024:24365, - 40025:24376, - 40026:24385, - 40027:24392, - 40028:24396, - 40029:24398, - 40030:24367, - 40031:24401, - 40032:24406, - 40033:24407, - 40034:24409, - 40035:24417, - 40036:24429, - 40037:24435, - 40038:24439, - 40039:24451, - 40040:24450, - 40041:24447, - 40042:24458, - 40043:24456, - 40044:24465, - 40045:24455, - 40046:24478, - 40047:24473, - 40048:24472, - 40049:24480, - 40050:24488, - 40051:24493, - 40052:24508, - 40053:24534, - 40054:24571, - 40055:24548, - 40056:24568, - 40057:24561, - 40058:24541, - 40059:24755, - 40060:24575, - 40061:24609, - 40062:24672, - 40064:24601, - 40065:24592, - 40066:24617, - 40067:24590, - 40068:24625, - 40069:24603, - 40070:24597, - 40071:24619, - 40072:24614, - 40073:24591, - 40074:24634, - 40075:24666, - 40076:24641, - 40077:24682, - 40078:24695, - 40079:24671, - 40080:24650, - 40081:24646, - 40082:24653, - 40083:24675, - 40084:24643, - 40085:24676, - 40086:24642, - 40087:24684, - 40088:24683, - 40089:24665, - 40090:24705, - 40091:24717, - 40092:24807, - 40093:24707, - 40094:24730, - 40095:24708, - 40096:24731, - 40097:24726, - 40098:24727, - 40099:24722, - 40100:24743, - 40101:24715, - 40102:24801, - 40103:24760, - 40104:24800, - 40105:24787, - 40106:24756, - 40107:24560, - 40108:24765, - 40109:24774, - 40110:24757, - 40111:24792, - 40112:24909, - 40113:24853, - 40114:24838, - 40115:24822, - 40116:24823, - 40117:24832, - 40118:24820, - 40119:24826, - 40120:24835, - 40121:24865, - 40122:24827, - 40123:24817, - 40124:24845, - 40125:24846, - 40126:24903, - 40127:24894, - 40128:24872, - 40129:24871, - 40130:24906, - 40131:24895, - 40132:24892, - 40133:24876, - 40134:24884, - 40135:24893, - 40136:24898, - 40137:24900, - 40138:24947, - 40139:24951, - 40140:24920, - 40141:24921, - 40142:24922, - 40143:24939, - 40144:24948, - 40145:24943, - 40146:24933, - 40147:24945, - 40148:24927, - 40149:24925, - 40150:24915, - 40151:24949, - 40152:24985, - 40153:24982, - 40154:24967, - 40155:25004, - 40156:24980, - 40157:24986, - 40158:24970, - 40159:24977, - 40160:25003, - 40161:25006, - 40162:25036, - 40163:25034, - 40164:25033, - 40165:25079, - 40166:25032, - 40167:25027, - 40168:25030, - 40169:25018, - 40170:25035, - 40171:32633, - 40172:25037, - 40173:25062, - 40174:25059, - 40175:25078, - 40176:25082, - 40177:25076, - 40178:25087, - 40179:25085, - 40180:25084, - 40181:25086, - 40182:25088, - 40183:25096, - 40184:25097, - 40185:25101, - 40186:25100, - 40187:25108, - 40188:25115, - 40256:25118, - 40257:25121, - 40258:25130, - 40259:25134, - 40260:25136, - 40261:25138, - 40262:25139, - 40263:25153, - 40264:25166, - 40265:25182, - 40266:25187, - 40267:25179, - 40268:25184, - 40269:25192, - 40270:25212, - 40271:25218, - 40272:25225, - 40273:25214, - 40274:25234, - 40275:25235, - 40276:25238, - 40277:25300, - 40278:25219, - 40279:25236, - 40280:25303, - 40281:25297, - 40282:25275, - 40283:25295, - 40284:25343, - 40285:25286, - 40286:25812, - 40287:25288, - 40288:25308, - 40289:25292, - 40290:25290, - 40291:25282, - 40292:25287, - 40293:25243, - 40294:25289, - 40295:25356, - 40296:25326, - 40297:25329, - 40298:25383, - 40299:25346, - 40300:25352, - 40301:25327, - 40302:25333, - 40303:25424, - 40304:25406, - 40305:25421, - 40306:25628, - 40307:25423, - 40308:25494, - 40309:25486, - 40310:25472, - 40311:25515, - 40312:25462, - 40313:25507, - 40314:25487, - 40315:25481, - 40316:25503, - 40317:25525, - 40318:25451, - 40320:25449, - 40321:25534, - 40322:25577, - 40323:25536, - 40324:25542, - 40325:25571, - 40326:25545, - 40327:25554, - 40328:25590, - 40329:25540, - 40330:25622, - 40331:25652, - 40332:25606, - 40333:25619, - 40334:25638, - 40335:25654, - 40336:25885, - 40337:25623, - 40338:25640, - 40339:25615, - 40340:25703, - 40341:25711, - 40342:25718, - 40343:25678, - 40344:25898, - 40345:25749, - 40346:25747, - 40347:25765, - 40348:25769, - 40349:25736, - 40350:25788, - 40351:25818, - 40352:25810, - 40353:25797, - 40354:25799, - 40355:25787, - 40356:25816, - 40357:25794, - 40358:25841, - 40359:25831, - 40360:33289, - 40361:25824, - 40362:25825, - 40363:25260, - 40364:25827, - 40365:25839, - 40366:25900, - 40367:25846, - 40368:25844, - 40369:25842, - 40370:25850, - 40371:25856, - 40372:25853, - 40373:25880, - 40374:25884, - 40375:25861, - 40376:25892, - 40377:25891, - 40378:25899, - 40379:25908, - 40380:25909, - 40381:25911, - 40382:25910, - 40383:25912, - 40384:30027, - 40385:25928, - 40386:25942, - 40387:25941, - 40388:25933, - 40389:25944, - 40390:25950, - 40391:25949, - 40392:25970, - 40393:25976, - 40394:25986, - 40395:25987, - 40396:35722, - 40397:26011, - 40398:26015, - 40399:26027, - 40400:26039, - 40401:26051, - 40402:26054, - 40403:26049, - 40404:26052, - 40405:26060, - 40406:26066, - 40407:26075, - 40408:26073, - 40409:26080, - 40410:26081, - 40411:26097, - 40412:26482, - 40413:26122, - 40414:26115, - 40415:26107, - 40416:26483, - 40417:26165, - 40418:26166, - 40419:26164, - 40420:26140, - 40421:26191, - 40422:26180, - 40423:26185, - 40424:26177, - 40425:26206, - 40426:26205, - 40427:26212, - 40428:26215, - 40429:26216, - 40430:26207, - 40431:26210, - 40432:26224, - 40433:26243, - 40434:26248, - 40435:26254, - 40436:26249, - 40437:26244, - 40438:26264, - 40439:26269, - 40440:26305, - 40441:26297, - 40442:26313, - 40443:26302, - 40444:26300, - 40512:26308, - 40513:26296, - 40514:26326, - 40515:26330, - 40516:26336, - 40517:26175, - 40518:26342, - 40519:26345, - 40520:26352, - 40521:26357, - 40522:26359, - 40523:26383, - 40524:26390, - 40525:26398, - 40526:26406, - 40527:26407, - 40528:38712, - 40529:26414, - 40530:26431, - 40531:26422, - 40532:26433, - 40533:26424, - 40534:26423, - 40535:26438, - 40536:26462, - 40537:26464, - 40538:26457, - 40539:26467, - 40540:26468, - 40541:26505, - 40542:26480, - 40543:26537, - 40544:26492, - 40545:26474, - 40546:26508, - 40547:26507, - 40548:26534, - 40549:26529, - 40550:26501, - 40551:26551, - 40552:26607, - 40553:26548, - 40554:26604, - 40555:26547, - 40556:26601, - 40557:26552, - 40558:26596, - 40559:26590, - 40560:26589, - 40561:26594, - 40562:26606, - 40563:26553, - 40564:26574, - 40565:26566, - 40566:26599, - 40567:27292, - 40568:26654, - 40569:26694, - 40570:26665, - 40571:26688, - 40572:26701, - 40573:26674, - 40574:26702, - 40576:26803, - 40577:26667, - 40578:26713, - 40579:26723, - 40580:26743, - 40581:26751, - 40582:26783, - 40583:26767, - 40584:26797, - 40585:26772, - 40586:26781, - 40587:26779, - 40588:26755, - 40589:27310, - 40590:26809, - 40591:26740, - 40592:26805, - 40593:26784, - 40594:26810, - 40595:26895, - 40596:26765, - 40597:26750, - 40598:26881, - 40599:26826, - 40600:26888, - 40601:26840, - 40602:26914, - 40603:26918, - 40604:26849, - 40605:26892, - 40606:26829, - 40607:26836, - 40608:26855, - 40609:26837, - 40610:26934, - 40611:26898, - 40612:26884, - 40613:26839, - 40614:26851, - 40615:26917, - 40616:26873, - 40617:26848, - 40618:26863, - 40619:26920, - 40620:26922, - 40621:26906, - 40622:26915, - 40623:26913, - 40624:26822, - 40625:27001, - 40626:26999, - 40627:26972, - 40628:27000, - 40629:26987, - 40630:26964, - 40631:27006, - 40632:26990, - 40633:26937, - 40634:26996, - 40635:26941, - 40636:26969, - 40637:26928, - 40638:26977, - 40639:26974, - 40640:26973, - 40641:27009, - 40642:26986, - 40643:27058, - 40644:27054, - 40645:27088, - 40646:27071, - 40647:27073, - 40648:27091, - 40649:27070, - 40650:27086, - 40651:23528, - 40652:27082, - 40653:27101, - 40654:27067, - 40655:27075, - 40656:27047, - 40657:27182, - 40658:27025, - 40659:27040, - 40660:27036, - 40661:27029, - 40662:27060, - 40663:27102, - 40664:27112, - 40665:27138, - 40666:27163, - 40667:27135, - 40668:27402, - 40669:27129, - 40670:27122, - 40671:27111, - 40672:27141, - 40673:27057, - 40674:27166, - 40675:27117, - 40676:27156, - 40677:27115, - 40678:27146, - 40679:27154, - 40680:27329, - 40681:27171, - 40682:27155, - 40683:27204, - 40684:27148, - 40685:27250, - 40686:27190, - 40687:27256, - 40688:27207, - 40689:27234, - 40690:27225, - 40691:27238, - 40692:27208, - 40693:27192, - 40694:27170, - 40695:27280, - 40696:27277, - 40697:27296, - 40698:27268, - 40699:27298, - 40700:27299, - 40768:27287, - 40769:34327, - 40770:27323, - 40771:27331, - 40772:27330, - 40773:27320, - 40774:27315, - 40775:27308, - 40776:27358, - 40777:27345, - 40778:27359, - 40779:27306, - 40780:27354, - 40781:27370, - 40782:27387, - 40783:27397, - 40784:34326, - 40785:27386, - 40786:27410, - 40787:27414, - 40788:39729, - 40789:27423, - 40790:27448, - 40791:27447, - 40792:30428, - 40793:27449, - 40794:39150, - 40795:27463, - 40796:27459, - 40797:27465, - 40798:27472, - 40799:27481, - 40800:27476, - 40801:27483, - 40802:27487, - 40803:27489, - 40804:27512, - 40805:27513, - 40806:27519, - 40807:27520, - 40808:27524, - 40809:27523, - 40810:27533, - 40811:27544, - 40812:27541, - 40813:27550, - 40814:27556, - 40815:27562, - 40816:27563, - 40817:27567, - 40818:27570, - 40819:27569, - 40820:27571, - 40821:27575, - 40822:27580, - 40823:27590, - 40824:27595, - 40825:27603, - 40826:27615, - 40827:27628, - 40828:27627, - 40829:27635, - 40830:27631, - 40832:40638, - 40833:27656, - 40834:27667, - 40835:27668, - 40836:27675, - 40837:27684, - 40838:27683, - 40839:27742, - 40840:27733, - 40841:27746, - 40842:27754, - 40843:27778, - 40844:27789, - 40845:27802, - 40846:27777, - 40847:27803, - 40848:27774, - 40849:27752, - 40850:27763, - 40851:27794, - 40852:27792, - 40853:27844, - 40854:27889, - 40855:27859, - 40856:27837, - 40857:27863, - 40858:27845, - 40859:27869, - 40860:27822, - 40861:27825, - 40862:27838, - 40863:27834, - 40864:27867, - 40865:27887, - 40866:27865, - 40867:27882, - 40868:27935, - 40869:34893, - 40870:27958, - 40871:27947, - 40872:27965, - 40873:27960, - 40874:27929, - 40875:27957, - 40876:27955, - 40877:27922, - 40878:27916, - 40879:28003, - 40880:28051, - 40881:28004, - 40882:27994, - 40883:28025, - 40884:27993, - 40885:28046, - 40886:28053, - 40887:28644, - 40888:28037, - 40889:28153, - 40890:28181, - 40891:28170, - 40892:28085, - 40893:28103, - 40894:28134, - 40895:28088, - 40896:28102, - 40897:28140, - 40898:28126, - 40899:28108, - 40900:28136, - 40901:28114, - 40902:28101, - 40903:28154, - 40904:28121, - 40905:28132, - 40906:28117, - 40907:28138, - 40908:28142, - 40909:28205, - 40910:28270, - 40911:28206, - 40912:28185, - 40913:28274, - 40914:28255, - 40915:28222, - 40916:28195, - 40917:28267, - 40918:28203, - 40919:28278, - 40920:28237, - 40921:28191, - 40922:28227, - 40923:28218, - 40924:28238, - 40925:28196, - 40926:28415, - 40927:28189, - 40928:28216, - 40929:28290, - 40930:28330, - 40931:28312, - 40932:28361, - 40933:28343, - 40934:28371, - 40935:28349, - 40936:28335, - 40937:28356, - 40938:28338, - 40939:28372, - 40940:28373, - 40941:28303, - 40942:28325, - 40943:28354, - 40944:28319, - 40945:28481, - 40946:28433, - 40947:28748, - 40948:28396, - 40949:28408, - 40950:28414, - 40951:28479, - 40952:28402, - 40953:28465, - 40954:28399, - 40955:28466, - 40956:28364, - 57408:28478, - 57409:28435, - 57410:28407, - 57411:28550, - 57412:28538, - 57413:28536, - 57414:28545, - 57415:28544, - 57416:28527, - 57417:28507, - 57418:28659, - 57419:28525, - 57420:28546, - 57421:28540, - 57422:28504, - 57423:28558, - 57424:28561, - 57425:28610, - 57426:28518, - 57427:28595, - 57428:28579, - 57429:28577, - 57430:28580, - 57431:28601, - 57432:28614, - 57433:28586, - 57434:28639, - 57435:28629, - 57436:28652, - 57437:28628, - 57438:28632, - 57439:28657, - 57440:28654, - 57441:28635, - 57442:28681, - 57443:28683, - 57444:28666, - 57445:28689, - 57446:28673, - 57447:28687, - 57448:28670, - 57449:28699, - 57450:28698, - 57451:28532, - 57452:28701, - 57453:28696, - 57454:28703, - 57455:28720, - 57456:28734, - 57457:28722, - 57458:28753, - 57459:28771, - 57460:28825, - 57461:28818, - 57462:28847, - 57463:28913, - 57464:28844, - 57465:28856, - 57466:28851, - 57467:28846, - 57468:28895, - 57469:28875, - 57470:28893, - 57472:28889, - 57473:28937, - 57474:28925, - 57475:28956, - 57476:28953, - 57477:29029, - 57478:29013, - 57479:29064, - 57480:29030, - 57481:29026, - 57482:29004, - 57483:29014, - 57484:29036, - 57485:29071, - 57486:29179, - 57487:29060, - 57488:29077, - 57489:29096, - 57490:29100, - 57491:29143, - 57492:29113, - 57493:29118, - 57494:29138, - 57495:29129, - 57496:29140, - 57497:29134, - 57498:29152, - 57499:29164, - 57500:29159, - 57501:29173, - 57502:29180, - 57503:29177, - 57504:29183, - 57505:29197, - 57506:29200, - 57507:29211, - 57508:29224, - 57509:29229, - 57510:29228, - 57511:29232, - 57512:29234, - 57513:29243, - 57514:29244, - 57515:29247, - 57516:29248, - 57517:29254, - 57518:29259, - 57519:29272, - 57520:29300, - 57521:29310, - 57522:29314, - 57523:29313, - 57524:29319, - 57525:29330, - 57526:29334, - 57527:29346, - 57528:29351, - 57529:29369, - 57530:29362, - 57531:29379, - 57532:29382, - 57533:29380, - 57534:29390, - 57535:29394, - 57536:29410, - 57537:29408, - 57538:29409, - 57539:29433, - 57540:29431, - 57541:20495, - 57542:29463, - 57543:29450, - 57544:29468, - 57545:29462, - 57546:29469, - 57547:29492, - 57548:29487, - 57549:29481, - 57550:29477, - 57551:29502, - 57552:29518, - 57553:29519, - 57554:40664, - 57555:29527, - 57556:29546, - 57557:29544, - 57558:29552, - 57559:29560, - 57560:29557, - 57561:29563, - 57562:29562, - 57563:29640, - 57564:29619, - 57565:29646, - 57566:29627, - 57567:29632, - 57568:29669, - 57569:29678, - 57570:29662, - 57571:29858, - 57572:29701, - 57573:29807, - 57574:29733, - 57575:29688, - 57576:29746, - 57577:29754, - 57578:29781, - 57579:29759, - 57580:29791, - 57581:29785, - 57582:29761, - 57583:29788, - 57584:29801, - 57585:29808, - 57586:29795, - 57587:29802, - 57588:29814, - 57589:29822, - 57590:29835, - 57591:29854, - 57592:29863, - 57593:29898, - 57594:29903, - 57595:29908, - 57596:29681, - 57664:29920, - 57665:29923, - 57666:29927, - 57667:29929, - 57668:29934, - 57669:29938, - 57670:29936, - 57671:29937, - 57672:29944, - 57673:29943, - 57674:29956, - 57675:29955, - 57676:29957, - 57677:29964, - 57678:29966, - 57679:29965, - 57680:29973, - 57681:29971, - 57682:29982, - 57683:29990, - 57684:29996, - 57685:30012, - 57686:30020, - 57687:30029, - 57688:30026, - 57689:30025, - 57690:30043, - 57691:30022, - 57692:30042, - 57693:30057, - 57694:30052, - 57695:30055, - 57696:30059, - 57697:30061, - 57698:30072, - 57699:30070, - 57700:30086, - 57701:30087, - 57702:30068, - 57703:30090, - 57704:30089, - 57705:30082, - 57706:30100, - 57707:30106, - 57708:30109, - 57709:30117, - 57710:30115, - 57711:30146, - 57712:30131, - 57713:30147, - 57714:30133, - 57715:30141, - 57716:30136, - 57717:30140, - 57718:30129, - 57719:30157, - 57720:30154, - 57721:30162, - 57722:30169, - 57723:30179, - 57724:30174, - 57725:30206, - 57726:30207, - 57728:30204, - 57729:30209, - 57730:30192, - 57731:30202, - 57732:30194, - 57733:30195, - 57734:30219, - 57735:30221, - 57736:30217, - 57737:30239, - 57738:30247, - 57739:30240, - 57740:30241, - 57741:30242, - 57742:30244, - 57743:30260, - 57744:30256, - 57745:30267, - 57746:30279, - 57747:30280, - 57748:30278, - 57749:30300, - 57750:30296, - 57751:30305, - 57752:30306, - 57753:30312, - 57754:30313, - 57755:30314, - 57756:30311, - 57757:30316, - 57758:30320, - 57759:30322, - 57760:30326, - 57761:30328, - 57762:30332, - 57763:30336, - 57764:30339, - 57765:30344, - 57766:30347, - 57767:30350, - 57768:30358, - 57769:30355, - 57770:30361, - 57771:30362, - 57772:30384, - 57773:30388, - 57774:30392, - 57775:30393, - 57776:30394, - 57777:30402, - 57778:30413, - 57779:30422, - 57780:30418, - 57781:30430, - 57782:30433, - 57783:30437, - 57784:30439, - 57785:30442, - 57786:34351, - 57787:30459, - 57788:30472, - 57789:30471, - 57790:30468, - 57791:30505, - 57792:30500, - 57793:30494, - 57794:30501, - 57795:30502, - 57796:30491, - 57797:30519, - 57798:30520, - 57799:30535, - 57800:30554, - 57801:30568, - 57802:30571, - 57803:30555, - 57804:30565, - 57805:30591, - 57806:30590, - 57807:30585, - 57808:30606, - 57809:30603, - 57810:30609, - 57811:30624, - 57812:30622, - 57813:30640, - 57814:30646, - 57815:30649, - 57816:30655, - 57817:30652, - 57818:30653, - 57819:30651, - 57820:30663, - 57821:30669, - 57822:30679, - 57823:30682, - 57824:30684, - 57825:30691, - 57826:30702, - 57827:30716, - 57828:30732, - 57829:30738, - 57830:31014, - 57831:30752, - 57832:31018, - 57833:30789, - 57834:30862, - 57835:30836, - 57836:30854, - 57837:30844, - 57838:30874, - 57839:30860, - 57840:30883, - 57841:30901, - 57842:30890, - 57843:30895, - 57844:30929, - 57845:30918, - 57846:30923, - 57847:30932, - 57848:30910, - 57849:30908, - 57850:30917, - 57851:30922, - 57852:30956, - 57920:30951, - 57921:30938, - 57922:30973, - 57923:30964, - 57924:30983, - 57925:30994, - 57926:30993, - 57927:31001, - 57928:31020, - 57929:31019, - 57930:31040, - 57931:31072, - 57932:31063, - 57933:31071, - 57934:31066, - 57935:31061, - 57936:31059, - 57937:31098, - 57938:31103, - 57939:31114, - 57940:31133, - 57941:31143, - 57942:40779, - 57943:31146, - 57944:31150, - 57945:31155, - 57946:31161, - 57947:31162, - 57948:31177, - 57949:31189, - 57950:31207, - 57951:31212, - 57952:31201, - 57953:31203, - 57954:31240, - 57955:31245, - 57956:31256, - 57957:31257, - 57958:31264, - 57959:31263, - 57960:31104, - 57961:31281, - 57962:31291, - 57963:31294, - 57964:31287, - 57965:31299, - 57966:31319, - 57967:31305, - 57968:31329, - 57969:31330, - 57970:31337, - 57971:40861, - 57972:31344, - 57973:31353, - 57974:31357, - 57975:31368, - 57976:31383, - 57977:31381, - 57978:31384, - 57979:31382, - 57980:31401, - 57981:31432, - 57982:31408, - 57984:31414, - 57985:31429, - 57986:31428, - 57987:31423, - 57988:36995, - 57989:31431, - 57990:31434, - 57991:31437, - 57992:31439, - 57993:31445, - 57994:31443, - 57995:31449, - 57996:31450, - 57997:31453, - 57998:31457, - 57999:31458, - 58000:31462, - 58001:31469, - 58002:31472, - 58003:31490, - 58004:31503, - 58005:31498, - 58006:31494, - 58007:31539, - 58008:31512, - 58009:31513, - 58010:31518, - 58011:31541, - 58012:31528, - 58013:31542, - 58014:31568, - 58015:31610, - 58016:31492, - 58017:31565, - 58018:31499, - 58019:31564, - 58020:31557, - 58021:31605, - 58022:31589, - 58023:31604, - 58024:31591, - 58025:31600, - 58026:31601, - 58027:31596, - 58028:31598, - 58029:31645, - 58030:31640, - 58031:31647, - 58032:31629, - 58033:31644, - 58034:31642, - 58035:31627, - 58036:31634, - 58037:31631, - 58038:31581, - 58039:31641, - 58040:31691, - 58041:31681, - 58042:31692, - 58043:31695, - 58044:31668, - 58045:31686, - 58046:31709, - 58047:31721, - 58048:31761, - 58049:31764, - 58050:31718, - 58051:31717, - 58052:31840, - 58053:31744, - 58054:31751, - 58055:31763, - 58056:31731, - 58057:31735, - 58058:31767, - 58059:31757, - 58060:31734, - 58061:31779, - 58062:31783, - 58063:31786, - 58064:31775, - 58065:31799, - 58066:31787, - 58067:31805, - 58068:31820, - 58069:31811, - 58070:31828, - 58071:31823, - 58072:31808, - 58073:31824, - 58074:31832, - 58075:31839, - 58076:31844, - 58077:31830, - 58078:31845, - 58079:31852, - 58080:31861, - 58081:31875, - 58082:31888, - 58083:31908, - 58084:31917, - 58085:31906, - 58086:31915, - 58087:31905, - 58088:31912, - 58089:31923, - 58090:31922, - 58091:31921, - 58092:31918, - 58093:31929, - 58094:31933, - 58095:31936, - 58096:31941, - 58097:31938, - 58098:31960, - 58099:31954, - 58100:31964, - 58101:31970, - 58102:39739, - 58103:31983, - 58104:31986, - 58105:31988, - 58106:31990, - 58107:31994, - 58108:32006, - 58176:32002, - 58177:32028, - 58178:32021, - 58179:32010, - 58180:32069, - 58181:32075, - 58182:32046, - 58183:32050, - 58184:32063, - 58185:32053, - 58186:32070, - 58187:32115, - 58188:32086, - 58189:32078, - 58190:32114, - 58191:32104, - 58192:32110, - 58193:32079, - 58194:32099, - 58195:32147, - 58196:32137, - 58197:32091, - 58198:32143, - 58199:32125, - 58200:32155, - 58201:32186, - 58202:32174, - 58203:32163, - 58204:32181, - 58205:32199, - 58206:32189, - 58207:32171, - 58208:32317, - 58209:32162, - 58210:32175, - 58211:32220, - 58212:32184, - 58213:32159, - 58214:32176, - 58215:32216, - 58216:32221, - 58217:32228, - 58218:32222, - 58219:32251, - 58220:32242, - 58221:32225, - 58222:32261, - 58223:32266, - 58224:32291, - 58225:32289, - 58226:32274, - 58227:32305, - 58228:32287, - 58229:32265, - 58230:32267, - 58231:32290, - 58232:32326, - 58233:32358, - 58234:32315, - 58235:32309, - 58236:32313, - 58237:32323, - 58238:32311, - 58240:32306, - 58241:32314, - 58242:32359, - 58243:32349, - 58244:32342, - 58245:32350, - 58246:32345, - 58247:32346, - 58248:32377, - 58249:32362, - 58250:32361, - 58251:32380, - 58252:32379, - 58253:32387, - 58254:32213, - 58255:32381, - 58256:36782, - 58257:32383, - 58258:32392, - 58259:32393, - 58260:32396, - 58261:32402, - 58262:32400, - 58263:32403, - 58264:32404, - 58265:32406, - 58266:32398, - 58267:32411, - 58268:32412, - 58269:32568, - 58270:32570, - 58271:32581, - 58272:32588, - 58273:32589, - 58274:32590, - 58275:32592, - 58276:32593, - 58277:32597, - 58278:32596, - 58279:32600, - 58280:32607, - 58281:32608, - 58282:32616, - 58283:32617, - 58284:32615, - 58285:32632, - 58286:32642, - 58287:32646, - 58288:32643, - 58289:32648, - 58290:32647, - 58291:32652, - 58292:32660, - 58293:32670, - 58294:32669, - 58295:32666, - 58296:32675, - 58297:32687, - 58298:32690, - 58299:32697, - 58300:32686, - 58301:32694, - 58302:32696, - 58303:35697, - 58304:32709, - 58305:32710, - 58306:32714, - 58307:32725, - 58308:32724, - 58309:32737, - 58310:32742, - 58311:32745, - 58312:32755, - 58313:32761, - 58314:39132, - 58315:32774, - 58316:32772, - 58317:32779, - 58318:32786, - 58319:32792, - 58320:32793, - 58321:32796, - 58322:32801, - 58323:32808, - 58324:32831, - 58325:32827, - 58326:32842, - 58327:32838, - 58328:32850, - 58329:32856, - 58330:32858, - 58331:32863, - 58332:32866, - 58333:32872, - 58334:32883, - 58335:32882, - 58336:32880, - 58337:32886, - 58338:32889, - 58339:32893, - 58340:32895, - 58341:32900, - 58342:32902, - 58343:32901, - 58344:32923, - 58345:32915, - 58346:32922, - 58347:32941, - 58348:20880, - 58349:32940, - 58350:32987, - 58351:32997, - 58352:32985, - 58353:32989, - 58354:32964, - 58355:32986, - 58356:32982, - 58357:33033, - 58358:33007, - 58359:33009, - 58360:33051, - 58361:33065, - 58362:33059, - 58363:33071, - 58364:33099, - 58432:38539, - 58433:33094, - 58434:33086, - 58435:33107, - 58436:33105, - 58437:33020, - 58438:33137, - 58439:33134, - 58440:33125, - 58441:33126, - 58442:33140, - 58443:33155, - 58444:33160, - 58445:33162, - 58446:33152, - 58447:33154, - 58448:33184, - 58449:33173, - 58450:33188, - 58451:33187, - 58452:33119, - 58453:33171, - 58454:33193, - 58455:33200, - 58456:33205, - 58457:33214, - 58458:33208, - 58459:33213, - 58460:33216, - 58461:33218, - 58462:33210, - 58463:33225, - 58464:33229, - 58465:33233, - 58466:33241, - 58467:33240, - 58468:33224, - 58469:33242, - 58470:33247, - 58471:33248, - 58472:33255, - 58473:33274, - 58474:33275, - 58475:33278, - 58476:33281, - 58477:33282, - 58478:33285, - 58479:33287, - 58480:33290, - 58481:33293, - 58482:33296, - 58483:33302, - 58484:33321, - 58485:33323, - 58486:33336, - 58487:33331, - 58488:33344, - 58489:33369, - 58490:33368, - 58491:33373, - 58492:33370, - 58493:33375, - 58494:33380, - 58496:33378, - 58497:33384, - 58498:33386, - 58499:33387, - 58500:33326, - 58501:33393, - 58502:33399, - 58503:33400, - 58504:33406, - 58505:33421, - 58506:33426, - 58507:33451, - 58508:33439, - 58509:33467, - 58510:33452, - 58511:33505, - 58512:33507, - 58513:33503, - 58514:33490, - 58515:33524, - 58516:33523, - 58517:33530, - 58518:33683, - 58519:33539, - 58520:33531, - 58521:33529, - 58522:33502, - 58523:33542, - 58524:33500, - 58525:33545, - 58526:33497, - 58527:33589, - 58528:33588, - 58529:33558, - 58530:33586, - 58531:33585, - 58532:33600, - 58533:33593, - 58534:33616, - 58535:33605, - 58536:33583, - 58537:33579, - 58538:33559, - 58539:33560, - 58540:33669, - 58541:33690, - 58542:33706, - 58543:33695, - 58544:33698, - 58545:33686, - 58546:33571, - 58547:33678, - 58548:33671, - 58549:33674, - 58550:33660, - 58551:33717, - 58552:33651, - 58553:33653, - 58554:33696, - 58555:33673, - 58556:33704, - 58557:33780, - 58558:33811, - 58559:33771, - 58560:33742, - 58561:33789, - 58562:33795, - 58563:33752, - 58564:33803, - 58565:33729, - 58566:33783, - 58567:33799, - 58568:33760, - 58569:33778, - 58570:33805, - 58571:33826, - 58572:33824, - 58573:33725, - 58574:33848, - 58575:34054, - 58576:33787, - 58577:33901, - 58578:33834, - 58579:33852, - 58580:34138, - 58581:33924, - 58582:33911, - 58583:33899, - 58584:33965, - 58585:33902, - 58586:33922, - 58587:33897, - 58588:33862, - 58589:33836, - 58590:33903, - 58591:33913, - 58592:33845, - 58593:33994, - 58594:33890, - 58595:33977, - 58596:33983, - 58597:33951, - 58598:34009, - 58599:33997, - 58600:33979, - 58601:34010, - 58602:34000, - 58603:33985, - 58604:33990, - 58605:34006, - 58606:33953, - 58607:34081, - 58608:34047, - 58609:34036, - 58610:34071, - 58611:34072, - 58612:34092, - 58613:34079, - 58614:34069, - 58615:34068, - 58616:34044, - 58617:34112, - 58618:34147, - 58619:34136, - 58620:34120, - 58688:34113, - 58689:34306, - 58690:34123, - 58691:34133, - 58692:34176, - 58693:34212, - 58694:34184, - 58695:34193, - 58696:34186, - 58697:34216, - 58698:34157, - 58699:34196, - 58700:34203, - 58701:34282, - 58702:34183, - 58703:34204, - 58704:34167, - 58705:34174, - 58706:34192, - 58707:34249, - 58708:34234, - 58709:34255, - 58710:34233, - 58711:34256, - 58712:34261, - 58713:34269, - 58714:34277, - 58715:34268, - 58716:34297, - 58717:34314, - 58718:34323, - 58719:34315, - 58720:34302, - 58721:34298, - 58722:34310, - 58723:34338, - 58724:34330, - 58725:34352, - 58726:34367, - 58727:34381, - 58728:20053, - 58729:34388, - 58730:34399, - 58731:34407, - 58732:34417, - 58733:34451, - 58734:34467, - 58735:34473, - 58736:34474, - 58737:34443, - 58738:34444, - 58739:34486, - 58740:34479, - 58741:34500, - 58742:34502, - 58743:34480, - 58744:34505, - 58745:34851, - 58746:34475, - 58747:34516, - 58748:34526, - 58749:34537, - 58750:34540, - 58752:34527, - 58753:34523, - 58754:34543, - 58755:34578, - 58756:34566, - 58757:34568, - 58758:34560, - 58759:34563, - 58760:34555, - 58761:34577, - 58762:34569, - 58763:34573, - 58764:34553, - 58765:34570, - 58766:34612, - 58767:34623, - 58768:34615, - 58769:34619, - 58770:34597, - 58771:34601, - 58772:34586, - 58773:34656, - 58774:34655, - 58775:34680, - 58776:34636, - 58777:34638, - 58778:34676, - 58779:34647, - 58780:34664, - 58781:34670, - 58782:34649, - 58783:34643, - 58784:34659, - 58785:34666, - 58786:34821, - 58787:34722, - 58788:34719, - 58789:34690, - 58790:34735, - 58791:34763, - 58792:34749, - 58793:34752, - 58794:34768, - 58795:38614, - 58796:34731, - 58797:34756, - 58798:34739, - 58799:34759, - 58800:34758, - 58801:34747, - 58802:34799, - 58803:34802, - 58804:34784, - 58805:34831, - 58806:34829, - 58807:34814, - 58808:34806, - 58809:34807, - 58810:34830, - 58811:34770, - 58812:34833, - 58813:34838, - 58814:34837, - 58815:34850, - 58816:34849, - 58817:34865, - 58818:34870, - 58819:34873, - 58820:34855, - 58821:34875, - 58822:34884, - 58823:34882, - 58824:34898, - 58825:34905, - 58826:34910, - 58827:34914, - 58828:34923, - 58829:34945, - 58830:34942, - 58831:34974, - 58832:34933, - 58833:34941, - 58834:34997, - 58835:34930, - 58836:34946, - 58837:34967, - 58838:34962, - 58839:34990, - 58840:34969, - 58841:34978, - 58842:34957, - 58843:34980, - 58844:34992, - 58845:35007, - 58846:34993, - 58847:35011, - 58848:35012, - 58849:35028, - 58850:35032, - 58851:35033, - 58852:35037, - 58853:35065, - 58854:35074, - 58855:35068, - 58856:35060, - 58857:35048, - 58858:35058, - 58859:35076, - 58860:35084, - 58861:35082, - 58862:35091, - 58863:35139, - 58864:35102, - 58865:35109, - 58866:35114, - 58867:35115, - 58868:35137, - 58869:35140, - 58870:35131, - 58871:35126, - 58872:35128, - 58873:35148, - 58874:35101, - 58875:35168, - 58876:35166, - 58944:35174, - 58945:35172, - 58946:35181, - 58947:35178, - 58948:35183, - 58949:35188, - 58950:35191, - 58951:35198, - 58952:35203, - 58953:35208, - 58954:35210, - 58955:35219, - 58956:35224, - 58957:35233, - 58958:35241, - 58959:35238, - 58960:35244, - 58961:35247, - 58962:35250, - 58963:35258, - 58964:35261, - 58965:35263, - 58966:35264, - 58967:35290, - 58968:35292, - 58969:35293, - 58970:35303, - 58971:35316, - 58972:35320, - 58973:35331, - 58974:35350, - 58975:35344, - 58976:35340, - 58977:35355, - 58978:35357, - 58979:35365, - 58980:35382, - 58981:35393, - 58982:35419, - 58983:35410, - 58984:35398, - 58985:35400, - 58986:35452, - 58987:35437, - 58988:35436, - 58989:35426, - 58990:35461, - 58991:35458, - 58992:35460, - 58993:35496, - 58994:35489, - 58995:35473, - 58996:35493, - 58997:35494, - 58998:35482, - 58999:35491, - 59000:35524, - 59001:35533, - 59002:35522, - 59003:35546, - 59004:35563, - 59005:35571, - 59006:35559, - 59008:35556, - 59009:35569, - 59010:35604, - 59011:35552, - 59012:35554, - 59013:35575, - 59014:35550, - 59015:35547, - 59016:35596, - 59017:35591, - 59018:35610, - 59019:35553, - 59020:35606, - 59021:35600, - 59022:35607, - 59023:35616, - 59024:35635, - 59025:38827, - 59026:35622, - 59027:35627, - 59028:35646, - 59029:35624, - 59030:35649, - 59031:35660, - 59032:35663, - 59033:35662, - 59034:35657, - 59035:35670, - 59036:35675, - 59037:35674, - 59038:35691, - 59039:35679, - 59040:35692, - 59041:35695, - 59042:35700, - 59043:35709, - 59044:35712, - 59045:35724, - 59046:35726, - 59047:35730, - 59048:35731, - 59049:35734, - 59050:35737, - 59051:35738, - 59052:35898, - 59053:35905, - 59054:35903, - 59055:35912, - 59056:35916, - 59057:35918, - 59058:35920, - 59059:35925, - 59060:35938, - 59061:35948, - 59062:35960, - 59063:35962, - 59064:35970, - 59065:35977, - 59066:35973, - 59067:35978, - 59068:35981, - 59069:35982, - 59070:35988, - 59071:35964, - 59072:35992, - 59073:25117, - 59074:36013, - 59075:36010, - 59076:36029, - 59077:36018, - 59078:36019, - 59079:36014, - 59080:36022, - 59081:36040, - 59082:36033, - 59083:36068, - 59084:36067, - 59085:36058, - 59086:36093, - 59087:36090, - 59088:36091, - 59089:36100, - 59090:36101, - 59091:36106, - 59092:36103, - 59093:36111, - 59094:36109, - 59095:36112, - 59096:40782, - 59097:36115, - 59098:36045, - 59099:36116, - 59100:36118, - 59101:36199, - 59102:36205, - 59103:36209, - 59104:36211, - 59105:36225, - 59106:36249, - 59107:36290, - 59108:36286, - 59109:36282, - 59110:36303, - 59111:36314, - 59112:36310, - 59113:36300, - 59114:36315, - 59115:36299, - 59116:36330, - 59117:36331, - 59118:36319, - 59119:36323, - 59120:36348, - 59121:36360, - 59122:36361, - 59123:36351, - 59124:36381, - 59125:36382, - 59126:36368, - 59127:36383, - 59128:36418, - 59129:36405, - 59130:36400, - 59131:36404, - 59132:36426, - 59200:36423, - 59201:36425, - 59202:36428, - 59203:36432, - 59204:36424, - 59205:36441, - 59206:36452, - 59207:36448, - 59208:36394, - 59209:36451, - 59210:36437, - 59211:36470, - 59212:36466, - 59213:36476, - 59214:36481, - 59215:36487, - 59216:36485, - 59217:36484, - 59218:36491, - 59219:36490, - 59220:36499, - 59221:36497, - 59222:36500, - 59223:36505, - 59224:36522, - 59225:36513, - 59226:36524, - 59227:36528, - 59228:36550, - 59229:36529, - 59230:36542, - 59231:36549, - 59232:36552, - 59233:36555, - 59234:36571, - 59235:36579, - 59236:36604, - 59237:36603, - 59238:36587, - 59239:36606, - 59240:36618, - 59241:36613, - 59242:36629, - 59243:36626, - 59244:36633, - 59245:36627, - 59246:36636, - 59247:36639, - 59248:36635, - 59249:36620, - 59250:36646, - 59251:36659, - 59252:36667, - 59253:36665, - 59254:36677, - 59255:36674, - 59256:36670, - 59257:36684, - 59258:36681, - 59259:36678, - 59260:36686, - 59261:36695, - 59262:36700, - 59264:36706, - 59265:36707, - 59266:36708, - 59267:36764, - 59268:36767, - 59269:36771, - 59270:36781, - 59271:36783, - 59272:36791, - 59273:36826, - 59274:36837, - 59275:36834, - 59276:36842, - 59277:36847, - 59278:36999, - 59279:36852, - 59280:36869, - 59281:36857, - 59282:36858, - 59283:36881, - 59284:36885, - 59285:36897, - 59286:36877, - 59287:36894, - 59288:36886, - 59289:36875, - 59290:36903, - 59291:36918, - 59292:36917, - 59293:36921, - 59294:36856, - 59295:36943, - 59296:36944, - 59297:36945, - 59298:36946, - 59299:36878, - 59300:36937, - 59301:36926, - 59302:36950, - 59303:36952, - 59304:36958, - 59305:36968, - 59306:36975, - 59307:36982, - 59308:38568, - 59309:36978, - 59310:36994, - 59311:36989, - 59312:36993, - 59313:36992, - 59314:37002, - 59315:37001, - 59316:37007, - 59317:37032, - 59318:37039, - 59319:37041, - 59320:37045, - 59321:37090, - 59322:37092, - 59323:25160, - 59324:37083, - 59325:37122, - 59326:37138, - 59327:37145, - 59328:37170, - 59329:37168, - 59330:37194, - 59331:37206, - 59332:37208, - 59333:37219, - 59334:37221, - 59335:37225, - 59336:37235, - 59337:37234, - 59338:37259, - 59339:37257, - 59340:37250, - 59341:37282, - 59342:37291, - 59343:37295, - 59344:37290, - 59345:37301, - 59346:37300, - 59347:37306, - 59348:37312, - 59349:37313, - 59350:37321, - 59351:37323, - 59352:37328, - 59353:37334, - 59354:37343, - 59355:37345, - 59356:37339, - 59357:37372, - 59358:37365, - 59359:37366, - 59360:37406, - 59361:37375, - 59362:37396, - 59363:37420, - 59364:37397, - 59365:37393, - 59366:37470, - 59367:37463, - 59368:37445, - 59369:37449, - 59370:37476, - 59371:37448, - 59372:37525, - 59373:37439, - 59374:37451, - 59375:37456, - 59376:37532, - 59377:37526, - 59378:37523, - 59379:37531, - 59380:37466, - 59381:37583, - 59382:37561, - 59383:37559, - 59384:37609, - 59385:37647, - 59386:37626, - 59387:37700, - 59388:37678, - 59456:37657, - 59457:37666, - 59458:37658, - 59459:37667, - 59460:37690, - 59461:37685, - 59462:37691, - 59463:37724, - 59464:37728, - 59465:37756, - 59466:37742, - 59467:37718, - 59468:37808, - 59469:37804, - 59470:37805, - 59471:37780, - 59472:37817, - 59473:37846, - 59474:37847, - 59475:37864, - 59476:37861, - 59477:37848, - 59478:37827, - 59479:37853, - 59480:37840, - 59481:37832, - 59482:37860, - 59483:37914, - 59484:37908, - 59485:37907, - 59486:37891, - 59487:37895, - 59488:37904, - 59489:37942, - 59490:37931, - 59491:37941, - 59492:37921, - 59493:37946, - 59494:37953, - 59495:37970, - 59496:37956, - 59497:37979, - 59498:37984, - 59499:37986, - 59500:37982, - 59501:37994, - 59502:37417, - 59503:38000, - 59504:38005, - 59505:38007, - 59506:38013, - 59507:37978, - 59508:38012, - 59509:38014, - 59510:38017, - 59511:38015, - 59512:38274, - 59513:38279, - 59514:38282, - 59515:38292, - 59516:38294, - 59517:38296, - 59518:38297, - 59520:38304, - 59521:38312, - 59522:38311, - 59523:38317, - 59524:38332, - 59525:38331, - 59526:38329, - 59527:38334, - 59528:38346, - 59529:28662, - 59530:38339, - 59531:38349, - 59532:38348, - 59533:38357, - 59534:38356, - 59535:38358, - 59536:38364, - 59537:38369, - 59538:38373, - 59539:38370, - 59540:38433, - 59541:38440, - 59542:38446, - 59543:38447, - 59544:38466, - 59545:38476, - 59546:38479, - 59547:38475, - 59548:38519, - 59549:38492, - 59550:38494, - 59551:38493, - 59552:38495, - 59553:38502, - 59554:38514, - 59555:38508, - 59556:38541, - 59557:38552, - 59558:38549, - 59559:38551, - 59560:38570, - 59561:38567, - 59562:38577, - 59563:38578, - 59564:38576, - 59565:38580, - 59566:38582, - 59567:38584, - 59568:38585, - 59569:38606, - 59570:38603, - 59571:38601, - 59572:38605, - 59573:35149, - 59574:38620, - 59575:38669, - 59576:38613, - 59577:38649, - 59578:38660, - 59579:38662, - 59580:38664, - 59581:38675, - 59582:38670, - 59583:38673, - 59584:38671, - 59585:38678, - 59586:38681, - 59587:38692, - 59588:38698, - 59589:38704, - 59590:38713, - 59591:38717, - 59592:38718, - 59593:38724, - 59594:38726, - 59595:38728, - 59596:38722, - 59597:38729, - 59598:38748, - 59599:38752, - 59600:38756, - 59601:38758, - 59602:38760, - 59603:21202, - 59604:38763, - 59605:38769, - 59606:38777, - 59607:38789, - 59608:38780, - 59609:38785, - 59610:38778, - 59611:38790, - 59612:38795, - 59613:38799, - 59614:38800, - 59615:38812, - 59616:38824, - 59617:38822, - 59618:38819, - 59619:38835, - 59620:38836, - 59621:38851, - 59622:38854, - 59623:38856, - 59624:38859, - 59625:38876, - 59626:38893, - 59627:40783, - 59628:38898, - 59629:31455, - 59630:38902, - 59631:38901, - 59632:38927, - 59633:38924, - 59634:38968, - 59635:38948, - 59636:38945, - 59637:38967, - 59638:38973, - 59639:38982, - 59640:38991, - 59641:38987, - 59642:39019, - 59643:39023, - 59644:39024, - 59712:39025, - 59713:39028, - 59714:39027, - 59715:39082, - 59716:39087, - 59717:39089, - 59718:39094, - 59719:39108, - 59720:39107, - 59721:39110, - 59722:39145, - 59723:39147, - 59724:39171, - 59725:39177, - 59726:39186, - 59727:39188, - 59728:39192, - 59729:39201, - 59730:39197, - 59731:39198, - 59732:39204, - 59733:39200, - 59734:39212, - 59735:39214, - 59736:39229, - 59737:39230, - 59738:39234, - 59739:39241, - 59740:39237, - 59741:39248, - 59742:39243, - 59743:39249, - 59744:39250, - 59745:39244, - 59746:39253, - 59747:39319, - 59748:39320, - 59749:39333, - 59750:39341, - 59751:39342, - 59752:39356, - 59753:39391, - 59754:39387, - 59755:39389, - 59756:39384, - 59757:39377, - 59758:39405, - 59759:39406, - 59760:39409, - 59761:39410, - 59762:39419, - 59763:39416, - 59764:39425, - 59765:39439, - 59766:39429, - 59767:39394, - 59768:39449, - 59769:39467, - 59770:39479, - 59771:39493, - 59772:39490, - 59773:39488, - 59774:39491, - 59776:39486, - 59777:39509, - 59778:39501, - 59779:39515, - 59780:39511, - 59781:39519, - 59782:39522, - 59783:39525, - 59784:39524, - 59785:39529, - 59786:39531, - 59787:39530, - 59788:39597, - 59789:39600, - 59790:39612, - 59791:39616, - 59792:39631, - 59793:39633, - 59794:39635, - 59795:39636, - 59796:39646, - 59797:39647, - 59798:39650, - 59799:39651, - 59800:39654, - 59801:39663, - 59802:39659, - 59803:39662, - 59804:39668, - 59805:39665, - 59806:39671, - 59807:39675, - 59808:39686, - 59809:39704, - 59810:39706, - 59811:39711, - 59812:39714, - 59813:39715, - 59814:39717, - 59815:39719, - 59816:39720, - 59817:39721, - 59818:39722, - 59819:39726, - 59820:39727, - 59821:39730, - 59822:39748, - 59823:39747, - 59824:39759, - 59825:39757, - 59826:39758, - 59827:39761, - 59828:39768, - 59829:39796, - 59830:39827, - 59831:39811, - 59832:39825, - 59833:39830, - 59834:39831, - 59835:39839, - 59836:39840, - 59837:39848, - 59838:39860, - 59839:39872, - 59840:39882, - 59841:39865, - 59842:39878, - 59843:39887, - 59844:39889, - 59845:39890, - 59846:39907, - 59847:39906, - 59848:39908, - 59849:39892, - 59850:39905, - 59851:39994, - 59852:39922, - 59853:39921, - 59854:39920, - 59855:39957, - 59856:39956, - 59857:39945, - 59858:39955, - 59859:39948, - 59860:39942, - 59861:39944, - 59862:39954, - 59863:39946, - 59864:39940, - 59865:39982, - 59866:39963, - 59867:39973, - 59868:39972, - 59869:39969, - 59870:39984, - 59871:40007, - 59872:39986, - 59873:40006, - 59874:39998, - 59875:40026, - 59876:40032, - 59877:40039, - 59878:40054, - 59879:40056, - 59880:40167, - 59881:40172, - 59882:40176, - 59883:40201, - 59884:40200, - 59885:40171, - 59886:40195, - 59887:40198, - 59888:40234, - 59889:40230, - 59890:40367, - 59891:40227, - 59892:40223, - 59893:40260, - 59894:40213, - 59895:40210, - 59896:40257, - 59897:40255, - 59898:40254, - 59899:40262, - 59900:40264, - 59968:40285, - 59969:40286, - 59970:40292, - 59971:40273, - 59972:40272, - 59973:40281, - 59974:40306, - 59975:40329, - 59976:40327, - 59977:40363, - 59978:40303, - 59979:40314, - 59980:40346, - 59981:40356, - 59982:40361, - 59983:40370, - 59984:40388, - 59985:40385, - 59986:40379, - 59987:40376, - 59988:40378, - 59989:40390, - 59990:40399, - 59991:40386, - 59992:40409, - 59993:40403, - 59994:40440, - 59995:40422, - 59996:40429, - 59997:40431, - 59998:40445, - 59999:40474, - 60000:40475, - 60001:40478, - 60002:40565, - 60003:40569, - 60004:40573, - 60005:40577, - 60006:40584, - 60007:40587, - 60008:40588, - 60009:40594, - 60010:40597, - 60011:40593, - 60012:40605, - 60013:40613, - 60014:40617, - 60015:40632, - 60016:40618, - 60017:40621, - 60018:38753, - 60019:40652, - 60020:40654, - 60021:40655, - 60022:40656, - 60023:40660, - 60024:40668, - 60025:40670, - 60026:40669, - 60027:40672, - 60028:40677, - 60029:40680, - 60030:40687, - 60032:40692, - 60033:40694, - 60034:40695, - 60035:40697, - 60036:40699, - 60037:40700, - 60038:40701, - 60039:40711, - 60040:40712, - 60041:30391, - 60042:40725, - 60043:40737, - 60044:40748, - 60045:40766, - 60046:40778, - 60047:40786, - 60048:40788, - 60049:40803, - 60050:40799, - 60051:40800, - 60052:40801, - 60053:40806, - 60054:40807, - 60055:40812, - 60056:40810, - 60057:40823, - 60058:40818, - 60059:40822, - 60060:40853, - 60061:40860, - 60062:40864, - 60063:22575, - 60064:27079, - 60065:36953, - 60066:29796, - 60067:20956, - 60068:29081, - 60736:32394, - 60737:35100, - 60738:37704, - 60739:37512, - 60740:34012, - 60741:20425, - 60742:28859, - 60743:26161, - 60744:26824, - 60745:37625, - 60746:26363, - 60747:24389, - 60748:20008, - 60749:20193, - 60750:20220, - 60751:20224, - 60752:20227, - 60753:20281, - 60754:20310, - 60755:20370, - 60756:20362, - 60757:20378, - 60758:20372, - 60759:20429, - 60760:20544, - 60761:20514, - 60762:20479, - 60763:20510, - 60764:20550, - 60765:20592, - 60766:20546, - 60767:20628, - 60768:20724, - 60769:20696, - 60770:20810, - 60771:20836, - 60772:20893, - 60773:20926, - 60774:20972, - 60775:21013, - 60776:21148, - 60777:21158, - 60778:21184, - 60779:21211, - 60780:21248, - 60781:21255, - 60782:21284, - 60783:21362, - 60784:21395, - 60785:21426, - 60786:21469, - 60787:64014, - 60788:21660, - 60789:21642, - 60790:21673, - 60791:21759, - 60792:21894, - 60793:22361, - 60794:22373, - 60795:22444, - 60796:22472, - 60797:22471, - 60798:64015, - 60800:64016, - 60801:22686, - 60802:22706, - 60803:22795, - 60804:22867, - 60805:22875, - 60806:22877, - 60807:22883, - 60808:22948, - 60809:22970, - 60810:23382, - 60811:23488, - 60812:29999, - 60813:23512, - 60814:23532, - 60815:23582, - 60816:23718, - 60817:23738, - 60818:23797, - 60819:23847, - 60820:23891, - 60821:64017, - 60822:23874, - 60823:23917, - 60824:23992, - 60825:23993, - 60826:24016, - 60827:24353, - 60828:24372, - 60829:24423, - 60830:24503, - 60831:24542, - 60832:24669, - 60833:24709, - 60834:24714, - 60835:24798, - 60836:24789, - 60837:24864, - 60838:24818, - 60839:24849, - 60840:24887, - 60841:24880, - 60842:24984, - 60843:25107, - 60844:25254, - 60845:25589, - 60846:25696, - 60847:25757, - 60848:25806, - 60849:25934, - 60850:26112, - 60851:26133, - 60852:26171, - 60853:26121, - 60854:26158, - 60855:26142, - 60856:26148, - 60857:26213, - 60858:26199, - 60859:26201, - 60860:64018, - 60861:26227, - 60862:26265, - 60863:26272, - 60864:26290, - 60865:26303, - 60866:26362, - 60867:26382, - 60868:63785, - 60869:26470, - 60870:26555, - 60871:26706, - 60872:26560, - 60873:26625, - 60874:26692, - 60875:26831, - 60876:64019, - 60877:26984, - 60878:64020, - 60879:27032, - 60880:27106, - 60881:27184, - 60882:27243, - 60883:27206, - 60884:27251, - 60885:27262, - 60886:27362, - 60887:27364, - 60888:27606, - 60889:27711, - 60890:27740, - 60891:27782, - 60892:27759, - 60893:27866, - 60894:27908, - 60895:28039, - 60896:28015, - 60897:28054, - 60898:28076, - 60899:28111, - 60900:28152, - 60901:28146, - 60902:28156, - 60903:28217, - 60904:28252, - 60905:28199, - 60906:28220, - 60907:28351, - 60908:28552, - 60909:28597, - 60910:28661, - 60911:28677, - 60912:28679, - 60913:28712, - 60914:28805, - 60915:28843, - 60916:28943, - 60917:28932, - 60918:29020, - 60919:28998, - 60920:28999, - 60921:64021, - 60922:29121, - 60923:29182, - 60924:29361, - 60992:29374, - 60993:29476, - 60994:64022, - 60995:29559, - 60996:29629, - 60997:29641, - 60998:29654, - 60999:29667, - 61000:29650, - 61001:29703, - 61002:29685, - 61003:29734, - 61004:29738, - 61005:29737, - 61006:29742, - 61007:29794, - 61008:29833, - 61009:29855, - 61010:29953, - 61011:30063, - 61012:30338, - 61013:30364, - 61014:30366, - 61015:30363, - 61016:30374, - 61017:64023, - 61018:30534, - 61019:21167, - 61020:30753, - 61021:30798, - 61022:30820, - 61023:30842, - 61024:31024, - 61025:64024, - 61026:64025, - 61027:64026, - 61028:31124, - 61029:64027, - 61030:31131, - 61031:31441, - 61032:31463, - 61033:64028, - 61034:31467, - 61035:31646, - 61036:64029, - 61037:32072, - 61038:32092, - 61039:32183, - 61040:32160, - 61041:32214, - 61042:32338, - 61043:32583, - 61044:32673, - 61045:64030, - 61046:33537, - 61047:33634, - 61048:33663, - 61049:33735, - 61050:33782, - 61051:33864, - 61052:33972, - 61053:34131, - 61054:34137, - 61056:34155, - 61057:64031, - 61058:34224, - 61059:64032, - 61060:64033, - 61061:34823, - 61062:35061, - 61063:35346, - 61064:35383, - 61065:35449, - 61066:35495, - 61067:35518, - 61068:35551, - 61069:64034, - 61070:35574, - 61071:35667, - 61072:35711, - 61073:36080, - 61074:36084, - 61075:36114, - 61076:36214, - 61077:64035, - 61078:36559, - 61079:64036, - 61080:64037, - 61081:36967, - 61082:37086, - 61083:64038, - 61084:37141, - 61085:37159, - 61086:37338, - 61087:37335, - 61088:37342, - 61089:37357, - 61090:37358, - 61091:37348, - 61092:37349, - 61093:37382, - 61094:37392, - 61095:37386, - 61096:37434, - 61097:37440, - 61098:37436, - 61099:37454, - 61100:37465, - 61101:37457, - 61102:37433, - 61103:37479, - 61104:37543, - 61105:37495, - 61106:37496, - 61107:37607, - 61108:37591, - 61109:37593, - 61110:37584, - 61111:64039, - 61112:37589, - 61113:37600, - 61114:37587, - 61115:37669, - 61116:37665, - 61117:37627, - 61118:64040, - 61119:37662, - 61120:37631, - 61121:37661, - 61122:37634, - 61123:37744, - 61124:37719, - 61125:37796, - 61126:37830, - 61127:37854, - 61128:37880, - 61129:37937, - 61130:37957, - 61131:37960, - 61132:38290, - 61133:63964, - 61134:64041, - 61135:38557, - 61136:38575, - 61137:38707, - 61138:38715, - 61139:38723, - 61140:38733, - 61141:38735, - 61142:38737, - 61143:38741, - 61144:38999, - 61145:39013, - 61146:64042, - 61147:64043, - 61148:39207, - 61149:64044, - 61150:39326, - 61151:39502, - 61152:39641, - 61153:39644, - 61154:39797, - 61155:39794, - 61156:39823, - 61157:39857, - 61158:39867, - 61159:39936, - 61160:40304, - 61161:40299, - 61162:64045, - 61163:40473, - 61164:40657, - 61167:8560, - 61168:8561, - 61169:8562, - 61170:8563, - 61171:8564, - 61172:8565, - 61173:8566, - 61174:8567, - 61175:8568, - 61176:8569, - 61177:65506, - 61178:65508, - 61179:65287, - 61180:65282, - 61504:57344, - 61505:57345, - 61506:57346, - 61507:57347, - 61508:57348, - 61509:57349, - 61510:57350, - 61511:57351, - 61512:57352, - 61513:57353, - 61514:57354, - 61515:57355, - 61516:57356, - 61517:57357, - 61518:57358, - 61519:57359, - 61520:57360, - 61521:57361, - 61522:57362, - 61523:57363, - 61524:57364, - 61525:57365, - 61526:57366, - 61527:57367, - 61528:57368, - 61529:57369, - 61530:57370, - 61531:57371, - 61532:57372, - 61533:57373, - 61534:57374, - 61535:57375, - 61536:57376, - 61537:57377, - 61538:57378, - 61539:57379, - 61540:57380, - 61541:57381, - 61542:57382, - 61543:57383, - 61544:57384, - 61545:57385, - 61546:57386, - 61547:57387, - 61548:57388, - 61549:57389, - 61550:57390, - 61551:57391, - 61552:57392, - 61553:57393, - 61554:57394, - 61555:57395, - 61556:57396, - 61557:57397, - 61558:57398, - 61559:57399, - 61560:57400, - 61561:57401, - 61562:57402, - 61563:57403, - 61564:57404, - 61565:57405, - 61566:57406, - 61568:57407, - 61569:57408, - 61570:57409, - 61571:57410, - 61572:57411, - 61573:57412, - 61574:57413, - 61575:57414, - 61576:57415, - 61577:57416, - 61578:57417, - 61579:57418, - 61580:57419, - 61581:57420, - 61582:57421, - 61583:57422, - 61584:57423, - 61585:57424, - 61586:57425, - 61587:57426, - 61588:57427, - 61589:57428, - 61590:57429, - 61591:57430, - 61592:57431, - 61593:57432, - 61594:57433, - 61595:57434, - 61596:57435, - 61597:57436, - 61598:57437, - 61599:57438, - 61600:57439, - 61601:57440, - 61602:57441, - 61603:57442, - 61604:57443, - 61605:57444, - 61606:57445, - 61607:57446, - 61608:57447, - 61609:57448, - 61610:57449, - 61611:57450, - 61612:57451, - 61613:57452, - 61614:57453, - 61615:57454, - 61616:57455, - 61617:57456, - 61618:57457, - 61619:57458, - 61620:57459, - 61621:57460, - 61622:57461, - 61623:57462, - 61624:57463, - 61625:57464, - 61626:57465, - 61627:57466, - 61628:57467, - 61629:57468, - 61630:57469, - 61631:57470, - 61632:57471, - 61633:57472, - 61634:57473, - 61635:57474, - 61636:57475, - 61637:57476, - 61638:57477, - 61639:57478, - 61640:57479, - 61641:57480, - 61642:57481, - 61643:57482, - 61644:57483, - 61645:57484, - 61646:57485, - 61647:57486, - 61648:57487, - 61649:57488, - 61650:57489, - 61651:57490, - 61652:57491, - 61653:57492, - 61654:57493, - 61655:57494, - 61656:57495, - 61657:57496, - 61658:57497, - 61659:57498, - 61660:57499, - 61661:57500, - 61662:57501, - 61663:57502, - 61664:57503, - 61665:57504, - 61666:57505, - 61667:57506, - 61668:57507, - 61669:57508, - 61670:57509, - 61671:57510, - 61672:57511, - 61673:57512, - 61674:57513, - 61675:57514, - 61676:57515, - 61677:57516, - 61678:57517, - 61679:57518, - 61680:57519, - 61681:57520, - 61682:57521, - 61683:57522, - 61684:57523, - 61685:57524, - 61686:57525, - 61687:57526, - 61688:57527, - 61689:57528, - 61690:57529, - 61691:57530, - 61692:57531, - 61760:57532, - 61761:57533, - 61762:57534, - 61763:57535, - 61764:57536, - 61765:57537, - 61766:57538, - 61767:57539, - 61768:57540, - 61769:57541, - 61770:57542, - 61771:57543, - 61772:57544, - 61773:57545, - 61774:57546, - 61775:57547, - 61776:57548, - 61777:57549, - 61778:57550, - 61779:57551, - 61780:57552, - 61781:57553, - 61782:57554, - 61783:57555, - 61784:57556, - 61785:57557, - 61786:57558, - 61787:57559, - 61788:57560, - 61789:57561, - 61790:57562, - 61791:57563, - 61792:57564, - 61793:57565, - 61794:57566, - 61795:57567, - 61796:57568, - 61797:57569, - 61798:57570, - 61799:57571, - 61800:57572, - 61801:57573, - 61802:57574, - 61803:57575, - 61804:57576, - 61805:57577, - 61806:57578, - 61807:57579, - 61808:57580, - 61809:57581, - 61810:57582, - 61811:57583, - 61812:57584, - 61813:57585, - 61814:57586, - 61815:57587, - 61816:57588, - 61817:57589, - 61818:57590, - 61819:57591, - 61820:57592, - 61821:57593, - 61822:57594, - 61824:57595, - 61825:57596, - 61826:57597, - 61827:57598, - 61828:57599, - 61829:57600, - 61830:57601, - 61831:57602, - 61832:57603, - 61833:57604, - 61834:57605, - 61835:57606, - 61836:57607, - 61837:57608, - 61838:57609, - 61839:57610, - 61840:57611, - 61841:57612, - 61842:57613, - 61843:57614, - 61844:57615, - 61845:57616, - 61846:57617, - 61847:57618, - 61848:57619, - 61849:57620, - 61850:57621, - 61851:57622, - 61852:57623, - 61853:57624, - 61854:57625, - 61855:57626, - 61856:57627, - 61857:57628, - 61858:57629, - 61859:57630, - 61860:57631, - 61861:57632, - 61862:57633, - 61863:57634, - 61864:57635, - 61865:57636, - 61866:57637, - 61867:57638, - 61868:57639, - 61869:57640, - 61870:57641, - 61871:57642, - 61872:57643, - 61873:57644, - 61874:57645, - 61875:57646, - 61876:57647, - 61877:57648, - 61878:57649, - 61879:57650, - 61880:57651, - 61881:57652, - 61882:57653, - 61883:57654, - 61884:57655, - 61885:57656, - 61886:57657, - 61887:57658, - 61888:57659, - 61889:57660, - 61890:57661, - 61891:57662, - 61892:57663, - 61893:57664, - 61894:57665, - 61895:57666, - 61896:57667, - 61897:57668, - 61898:57669, - 61899:57670, - 61900:57671, - 61901:57672, - 61902:57673, - 61903:57674, - 61904:57675, - 61905:57676, - 61906:57677, - 61907:57678, - 61908:57679, - 61909:57680, - 61910:57681, - 61911:57682, - 61912:57683, - 61913:57684, - 61914:57685, - 61915:57686, - 61916:57687, - 61917:57688, - 61918:57689, - 61919:57690, - 61920:57691, - 61921:57692, - 61922:57693, - 61923:57694, - 61924:57695, - 61925:57696, - 61926:57697, - 61927:57698, - 61928:57699, - 61929:57700, - 61930:57701, - 61931:57702, - 61932:57703, - 61933:57704, - 61934:57705, - 61935:57706, - 61936:57707, - 61937:57708, - 61938:57709, - 61939:57710, - 61940:57711, - 61941:57712, - 61942:57713, - 61943:57714, - 61944:57715, - 61945:57716, - 61946:57717, - 61947:57718, - 61948:57719, - 62016:57720, - 62017:57721, - 62018:57722, - 62019:57723, - 62020:57724, - 62021:57725, - 62022:57726, - 62023:57727, - 62024:57728, - 62025:57729, - 62026:57730, - 62027:57731, - 62028:57732, - 62029:57733, - 62030:57734, - 62031:57735, - 62032:57736, - 62033:57737, - 62034:57738, - 62035:57739, - 62036:57740, - 62037:57741, - 62038:57742, - 62039:57743, - 62040:57744, - 62041:57745, - 62042:57746, - 62043:57747, - 62044:57748, - 62045:57749, - 62046:57750, - 62047:57751, - 62048:57752, - 62049:57753, - 62050:57754, - 62051:57755, - 62052:57756, - 62053:57757, - 62054:57758, - 62055:57759, - 62056:57760, - 62057:57761, - 62058:57762, - 62059:57763, - 62060:57764, - 62061:57765, - 62062:57766, - 62063:57767, - 62064:57768, - 62065:57769, - 62066:57770, - 62067:57771, - 62068:57772, - 62069:57773, - 62070:57774, - 62071:57775, - 62072:57776, - 62073:57777, - 62074:57778, - 62075:57779, - 62076:57780, - 62077:57781, - 62078:57782, - 62080:57783, - 62081:57784, - 62082:57785, - 62083:57786, - 62084:57787, - 62085:57788, - 62086:57789, - 62087:57790, - 62088:57791, - 62089:57792, - 62090:57793, - 62091:57794, - 62092:57795, - 62093:57796, - 62094:57797, - 62095:57798, - 62096:57799, - 62097:57800, - 62098:57801, - 62099:57802, - 62100:57803, - 62101:57804, - 62102:57805, - 62103:57806, - 62104:57807, - 62105:57808, - 62106:57809, - 62107:57810, - 62108:57811, - 62109:57812, - 62110:57813, - 62111:57814, - 62112:57815, - 62113:57816, - 62114:57817, - 62115:57818, - 62116:57819, - 62117:57820, - 62118:57821, - 62119:57822, - 62120:57823, - 62121:57824, - 62122:57825, - 62123:57826, - 62124:57827, - 62125:57828, - 62126:57829, - 62127:57830, - 62128:57831, - 62129:57832, - 62130:57833, - 62131:57834, - 62132:57835, - 62133:57836, - 62134:57837, - 62135:57838, - 62136:57839, - 62137:57840, - 62138:57841, - 62139:57842, - 62140:57843, - 62141:57844, - 62142:57845, - 62143:57846, - 62144:57847, - 62145:57848, - 62146:57849, - 62147:57850, - 62148:57851, - 62149:57852, - 62150:57853, - 62151:57854, - 62152:57855, - 62153:57856, - 62154:57857, - 62155:57858, - 62156:57859, - 62157:57860, - 62158:57861, - 62159:57862, - 62160:57863, - 62161:57864, - 62162:57865, - 62163:57866, - 62164:57867, - 62165:57868, - 62166:57869, - 62167:57870, - 62168:57871, - 62169:57872, - 62170:57873, - 62171:57874, - 62172:57875, - 62173:57876, - 62174:57877, - 62175:57878, - 62176:57879, - 62177:57880, - 62178:57881, - 62179:57882, - 62180:57883, - 62181:57884, - 62182:57885, - 62183:57886, - 62184:57887, - 62185:57888, - 62186:57889, - 62187:57890, - 62188:57891, - 62189:57892, - 62190:57893, - 62191:57894, - 62192:57895, - 62193:57896, - 62194:57897, - 62195:57898, - 62196:57899, - 62197:57900, - 62198:57901, - 62199:57902, - 62200:57903, - 62201:57904, - 62202:57905, - 62203:57906, - 62204:57907, - 62272:57908, - 62273:57909, - 62274:57910, - 62275:57911, - 62276:57912, - 62277:57913, - 62278:57914, - 62279:57915, - 62280:57916, - 62281:57917, - 62282:57918, - 62283:57919, - 62284:57920, - 62285:57921, - 62286:57922, - 62287:57923, - 62288:57924, - 62289:57925, - 62290:57926, - 62291:57927, - 62292:57928, - 62293:57929, - 62294:57930, - 62295:57931, - 62296:57932, - 62297:57933, - 62298:57934, - 62299:57935, - 62300:57936, - 62301:57937, - 62302:57938, - 62303:57939, - 62304:57940, - 62305:57941, - 62306:57942, - 62307:57943, - 62308:57944, - 62309:57945, - 62310:57946, - 62311:57947, - 62312:57948, - 62313:57949, - 62314:57950, - 62315:57951, - 62316:57952, - 62317:57953, - 62318:57954, - 62319:57955, - 62320:57956, - 62321:57957, - 62322:57958, - 62323:57959, - 62324:57960, - 62325:57961, - 62326:57962, - 62327:57963, - 62328:57964, - 62329:57965, - 62330:57966, - 62331:57967, - 62332:57968, - 62333:57969, - 62334:57970, - 62336:57971, - 62337:57972, - 62338:57973, - 62339:57974, - 62340:57975, - 62341:57976, - 62342:57977, - 62343:57978, - 62344:57979, - 62345:57980, - 62346:57981, - 62347:57982, - 62348:57983, - 62349:57984, - 62350:57985, - 62351:57986, - 62352:57987, - 62353:57988, - 62354:57989, - 62355:57990, - 62356:57991, - 62357:57992, - 62358:57993, - 62359:57994, - 62360:57995, - 62361:57996, - 62362:57997, - 62363:57998, - 62364:57999, - 62365:58000, - 62366:58001, - 62367:58002, - 62368:58003, - 62369:58004, - 62370:58005, - 62371:58006, - 62372:58007, - 62373:58008, - 62374:58009, - 62375:58010, - 62376:58011, - 62377:58012, - 62378:58013, - 62379:58014, - 62380:58015, - 62381:58016, - 62382:58017, - 62383:58018, - 62384:58019, - 62385:58020, - 62386:58021, - 62387:58022, - 62388:58023, - 62389:58024, - 62390:58025, - 62391:58026, - 62392:58027, - 62393:58028, - 62394:58029, - 62395:58030, - 62396:58031, - 62397:58032, - 62398:58033, - 62399:58034, - 62400:58035, - 62401:58036, - 62402:58037, - 62403:58038, - 62404:58039, - 62405:58040, - 62406:58041, - 62407:58042, - 62408:58043, - 62409:58044, - 62410:58045, - 62411:58046, - 62412:58047, - 62413:58048, - 62414:58049, - 62415:58050, - 62416:58051, - 62417:58052, - 62418:58053, - 62419:58054, - 62420:58055, - 62421:58056, - 62422:58057, - 62423:58058, - 62424:58059, - 62425:58060, - 62426:58061, - 62427:58062, - 62428:58063, - 62429:58064, - 62430:58065, - 62431:58066, - 62432:58067, - 62433:58068, - 62434:58069, - 62435:58070, - 62436:58071, - 62437:58072, - 62438:58073, - 62439:58074, - 62440:58075, - 62441:58076, - 62442:58077, - 62443:58078, - 62444:58079, - 62445:58080, - 62446:58081, - 62447:58082, - 62448:58083, - 62449:58084, - 62450:58085, - 62451:58086, - 62452:58087, - 62453:58088, - 62454:58089, - 62455:58090, - 62456:58091, - 62457:58092, - 62458:58093, - 62459:58094, - 62460:58095, - 62528:58096, - 62529:58097, - 62530:58098, - 62531:58099, - 62532:58100, - 62533:58101, - 62534:58102, - 62535:58103, - 62536:58104, - 62537:58105, - 62538:58106, - 62539:58107, - 62540:58108, - 62541:58109, - 62542:58110, - 62543:58111, - 62544:58112, - 62545:58113, - 62546:58114, - 62547:58115, - 62548:58116, - 62549:58117, - 62550:58118, - 62551:58119, - 62552:58120, - 62553:58121, - 62554:58122, - 62555:58123, - 62556:58124, - 62557:58125, - 62558:58126, - 62559:58127, - 62560:58128, - 62561:58129, - 62562:58130, - 62563:58131, - 62564:58132, - 62565:58133, - 62566:58134, - 62567:58135, - 62568:58136, - 62569:58137, - 62570:58138, - 62571:58139, - 62572:58140, - 62573:58141, - 62574:58142, - 62575:58143, - 62576:58144, - 62577:58145, - 62578:58146, - 62579:58147, - 62580:58148, - 62581:58149, - 62582:58150, - 62583:58151, - 62584:58152, - 62585:58153, - 62586:58154, - 62587:58155, - 62588:58156, - 62589:58157, - 62590:58158, - 62592:58159, - 62593:58160, - 62594:58161, - 62595:58162, - 62596:58163, - 62597:58164, - 62598:58165, - 62599:58166, - 62600:58167, - 62601:58168, - 62602:58169, - 62603:58170, - 62604:58171, - 62605:58172, - 62606:58173, - 62607:58174, - 62608:58175, - 62609:58176, - 62610:58177, - 62611:58178, - 62612:58179, - 62613:58180, - 62614:58181, - 62615:58182, - 62616:58183, - 62617:58184, - 62618:58185, - 62619:58186, - 62620:58187, - 62621:58188, - 62622:58189, - 62623:58190, - 62624:58191, - 62625:58192, - 62626:58193, - 62627:58194, - 62628:58195, - 62629:58196, - 62630:58197, - 62631:58198, - 62632:58199, - 62633:58200, - 62634:58201, - 62635:58202, - 62636:58203, - 62637:58204, - 62638:58205, - 62639:58206, - 62640:58207, - 62641:58208, - 62642:58209, - 62643:58210, - 62644:58211, - 62645:58212, - 62646:58213, - 62647:58214, - 62648:58215, - 62649:58216, - 62650:58217, - 62651:58218, - 62652:58219, - 62653:58220, - 62654:58221, - 62655:58222, - 62656:58223, - 62657:58224, - 62658:58225, - 62659:58226, - 62660:58227, - 62661:58228, - 62662:58229, - 62663:58230, - 62664:58231, - 62665:58232, - 62666:58233, - 62667:58234, - 62668:58235, - 62669:58236, - 62670:58237, - 62671:58238, - 62672:58239, - 62673:58240, - 62674:58241, - 62675:58242, - 62676:58243, - 62677:58244, - 62678:58245, - 62679:58246, - 62680:58247, - 62681:58248, - 62682:58249, - 62683:58250, - 62684:58251, - 62685:58252, - 62686:58253, - 62687:58254, - 62688:58255, - 62689:58256, - 62690:58257, - 62691:58258, - 62692:58259, - 62693:58260, - 62694:58261, - 62695:58262, - 62696:58263, - 62697:58264, - 62698:58265, - 62699:58266, - 62700:58267, - 62701:58268, - 62702:58269, - 62703:58270, - 62704:58271, - 62705:58272, - 62706:58273, - 62707:58274, - 62708:58275, - 62709:58276, - 62710:58277, - 62711:58278, - 62712:58279, - 62713:58280, - 62714:58281, - 62715:58282, - 62716:58283, - 62784:58284, - 62785:58285, - 62786:58286, - 62787:58287, - 62788:58288, - 62789:58289, - 62790:58290, - 62791:58291, - 62792:58292, - 62793:58293, - 62794:58294, - 62795:58295, - 62796:58296, - 62797:58297, - 62798:58298, - 62799:58299, - 62800:58300, - 62801:58301, - 62802:58302, - 62803:58303, - 62804:58304, - 62805:58305, - 62806:58306, - 62807:58307, - 62808:58308, - 62809:58309, - 62810:58310, - 62811:58311, - 62812:58312, - 62813:58313, - 62814:58314, - 62815:58315, - 62816:58316, - 62817:58317, - 62818:58318, - 62819:58319, - 62820:58320, - 62821:58321, - 62822:58322, - 62823:58323, - 62824:58324, - 62825:58325, - 62826:58326, - 62827:58327, - 62828:58328, - 62829:58329, - 62830:58330, - 62831:58331, - 62832:58332, - 62833:58333, - 62834:58334, - 62835:58335, - 62836:58336, - 62837:58337, - 62838:58338, - 62839:58339, - 62840:58340, - 62841:58341, - 62842:58342, - 62843:58343, - 62844:58344, - 62845:58345, - 62846:58346, - 62848:58347, - 62849:58348, - 62850:58349, - 62851:58350, - 62852:58351, - 62853:58352, - 62854:58353, - 62855:58354, - 62856:58355, - 62857:58356, - 62858:58357, - 62859:58358, - 62860:58359, - 62861:58360, - 62862:58361, - 62863:58362, - 62864:58363, - 62865:58364, - 62866:58365, - 62867:58366, - 62868:58367, - 62869:58368, - 62870:58369, - 62871:58370, - 62872:58371, - 62873:58372, - 62874:58373, - 62875:58374, - 62876:58375, - 62877:58376, - 62878:58377, - 62879:58378, - 62880:58379, - 62881:58380, - 62882:58381, - 62883:58382, - 62884:58383, - 62885:58384, - 62886:58385, - 62887:58386, - 62888:58387, - 62889:58388, - 62890:58389, - 62891:58390, - 62892:58391, - 62893:58392, - 62894:58393, - 62895:58394, - 62896:58395, - 62897:58396, - 62898:58397, - 62899:58398, - 62900:58399, - 62901:58400, - 62902:58401, - 62903:58402, - 62904:58403, - 62905:58404, - 62906:58405, - 62907:58406, - 62908:58407, - 62909:58408, - 62910:58409, - 62911:58410, - 62912:58411, - 62913:58412, - 62914:58413, - 62915:58414, - 62916:58415, - 62917:58416, - 62918:58417, - 62919:58418, - 62920:58419, - 62921:58420, - 62922:58421, - 62923:58422, - 62924:58423, - 62925:58424, - 62926:58425, - 62927:58426, - 62928:58427, - 62929:58428, - 62930:58429, - 62931:58430, - 62932:58431, - 62933:58432, - 62934:58433, - 62935:58434, - 62936:58435, - 62937:58436, - 62938:58437, - 62939:58438, - 62940:58439, - 62941:58440, - 62942:58441, - 62943:58442, - 62944:58443, - 62945:58444, - 62946:58445, - 62947:58446, - 62948:58447, - 62949:58448, - 62950:58449, - 62951:58450, - 62952:58451, - 62953:58452, - 62954:58453, - 62955:58454, - 62956:58455, - 62957:58456, - 62958:58457, - 62959:58458, - 62960:58459, - 62961:58460, - 62962:58461, - 62963:58462, - 62964:58463, - 62965:58464, - 62966:58465, - 62967:58466, - 62968:58467, - 62969:58468, - 62970:58469, - 62971:58470, - 62972:58471, - 63040:58472, - 63041:58473, - 63042:58474, - 63043:58475, - 63044:58476, - 63045:58477, - 63046:58478, - 63047:58479, - 63048:58480, - 63049:58481, - 63050:58482, - 63051:58483, - 63052:58484, - 63053:58485, - 63054:58486, - 63055:58487, - 63056:58488, - 63057:58489, - 63058:58490, - 63059:58491, - 63060:58492, - 63061:58493, - 63062:58494, - 63063:58495, - 63064:58496, - 63065:58497, - 63066:58498, - 63067:58499, - 63068:58500, - 63069:58501, - 63070:58502, - 63071:58503, - 63072:58504, - 63073:58505, - 63074:58506, - 63075:58507, - 63076:58508, - 63077:58509, - 63078:58510, - 63079:58511, - 63080:58512, - 63081:58513, - 63082:58514, - 63083:58515, - 63084:58516, - 63085:58517, - 63086:58518, - 63087:58519, - 63088:58520, - 63089:58521, - 63090:58522, - 63091:58523, - 63092:58524, - 63093:58525, - 63094:58526, - 63095:58527, - 63096:58528, - 63097:58529, - 63098:58530, - 63099:58531, - 63100:58532, - 63101:58533, - 63102:58534, - 63104:58535, - 63105:58536, - 63106:58537, - 63107:58538, - 63108:58539, - 63109:58540, - 63110:58541, - 63111:58542, - 63112:58543, - 63113:58544, - 63114:58545, - 63115:58546, - 63116:58547, - 63117:58548, - 63118:58549, - 63119:58550, - 63120:58551, - 63121:58552, - 63122:58553, - 63123:58554, - 63124:58555, - 63125:58556, - 63126:58557, - 63127:58558, - 63128:58559, - 63129:58560, - 63130:58561, - 63131:58562, - 63132:58563, - 63133:58564, - 63134:58565, - 63135:58566, - 63136:58567, - 63137:58568, - 63138:58569, - 63139:58570, - 63140:58571, - 63141:58572, - 63142:58573, - 63143:58574, - 63144:58575, - 63145:58576, - 63146:58577, - 63147:58578, - 63148:58579, - 63149:58580, - 63150:58581, - 63151:58582, - 63152:58583, - 63153:58584, - 63154:58585, - 63155:58586, - 63156:58587, - 63157:58588, - 63158:58589, - 63159:58590, - 63160:58591, - 63161:58592, - 63162:58593, - 63163:58594, - 63164:58595, - 63165:58596, - 63166:58597, - 63167:58598, - 63168:58599, - 63169:58600, - 63170:58601, - 63171:58602, - 63172:58603, - 63173:58604, - 63174:58605, - 63175:58606, - 63176:58607, - 63177:58608, - 63178:58609, - 63179:58610, - 63180:58611, - 63181:58612, - 63182:58613, - 63183:58614, - 63184:58615, - 63185:58616, - 63186:58617, - 63187:58618, - 63188:58619, - 63189:58620, - 63190:58621, - 63191:58622, - 63192:58623, - 63193:58624, - 63194:58625, - 63195:58626, - 63196:58627, - 63197:58628, - 63198:58629, - 63199:58630, - 63200:58631, - 63201:58632, - 63202:58633, - 63203:58634, - 63204:58635, - 63205:58636, - 63206:58637, - 63207:58638, - 63208:58639, - 63209:58640, - 63210:58641, - 63211:58642, - 63212:58643, - 63213:58644, - 63214:58645, - 63215:58646, - 63216:58647, - 63217:58648, - 63218:58649, - 63219:58650, - 63220:58651, - 63221:58652, - 63222:58653, - 63223:58654, - 63224:58655, - 63225:58656, - 63226:58657, - 63227:58658, - 63228:58659, - 63296:58660, - 63297:58661, - 63298:58662, - 63299:58663, - 63300:58664, - 63301:58665, - 63302:58666, - 63303:58667, - 63304:58668, - 63305:58669, - 63306:58670, - 63307:58671, - 63308:58672, - 63309:58673, - 63310:58674, - 63311:58675, - 63312:58676, - 63313:58677, - 63314:58678, - 63315:58679, - 63316:58680, - 63317:58681, - 63318:58682, - 63319:58683, - 63320:58684, - 63321:58685, - 63322:58686, - 63323:58687, - 63324:58688, - 63325:58689, - 63326:58690, - 63327:58691, - 63328:58692, - 63329:58693, - 63330:58694, - 63331:58695, - 63332:58696, - 63333:58697, - 63334:58698, - 63335:58699, - 63336:58700, - 63337:58701, - 63338:58702, - 63339:58703, - 63340:58704, - 63341:58705, - 63342:58706, - 63343:58707, - 63344:58708, - 63345:58709, - 63346:58710, - 63347:58711, - 63348:58712, - 63349:58713, - 63350:58714, - 63351:58715, - 63352:58716, - 63353:58717, - 63354:58718, - 63355:58719, - 63356:58720, - 63357:58721, - 63358:58722, - 63360:58723, - 63361:58724, - 63362:58725, - 63363:58726, - 63364:58727, - 63365:58728, - 63366:58729, - 63367:58730, - 63368:58731, - 63369:58732, - 63370:58733, - 63371:58734, - 63372:58735, - 63373:58736, - 63374:58737, - 63375:58738, - 63376:58739, - 63377:58740, - 63378:58741, - 63379:58742, - 63380:58743, - 63381:58744, - 63382:58745, - 63383:58746, - 63384:58747, - 63385:58748, - 63386:58749, - 63387:58750, - 63388:58751, - 63389:58752, - 63390:58753, - 63391:58754, - 63392:58755, - 63393:58756, - 63394:58757, - 63395:58758, - 63396:58759, - 63397:58760, - 63398:58761, - 63399:58762, - 63400:58763, - 63401:58764, - 63402:58765, - 63403:58766, - 63404:58767, - 63405:58768, - 63406:58769, - 63407:58770, - 63408:58771, - 63409:58772, - 63410:58773, - 63411:58774, - 63412:58775, - 63413:58776, - 63414:58777, - 63415:58778, - 63416:58779, - 63417:58780, - 63418:58781, - 63419:58782, - 63420:58783, - 63421:58784, - 63422:58785, - 63423:58786, - 63424:58787, - 63425:58788, - 63426:58789, - 63427:58790, - 63428:58791, - 63429:58792, - 63430:58793, - 63431:58794, - 63432:58795, - 63433:58796, - 63434:58797, - 63435:58798, - 63436:58799, - 63437:58800, - 63438:58801, - 63439:58802, - 63440:58803, - 63441:58804, - 63442:58805, - 63443:58806, - 63444:58807, - 63445:58808, - 63446:58809, - 63447:58810, - 63448:58811, - 63449:58812, - 63450:58813, - 63451:58814, - 63452:58815, - 63453:58816, - 63454:58817, - 63455:58818, - 63456:58819, - 63457:58820, - 63458:58821, - 63459:58822, - 63460:58823, - 63461:58824, - 63462:58825, - 63463:58826, - 63464:58827, - 63465:58828, - 63466:58829, - 63467:58830, - 63468:58831, - 63469:58832, - 63470:58833, - 63471:58834, - 63472:58835, - 63473:58836, - 63474:58837, - 63475:58838, - 63476:58839, - 63477:58840, - 63478:58841, - 63479:58842, - 63480:58843, - 63481:58844, - 63482:58845, - 63483:58846, - 63484:58847, - 63552:58848, - 63553:58849, - 63554:58850, - 63555:58851, - 63556:58852, - 63557:58853, - 63558:58854, - 63559:58855, - 63560:58856, - 63561:58857, - 63562:58858, - 63563:58859, - 63564:58860, - 63565:58861, - 63566:58862, - 63567:58863, - 63568:58864, - 63569:58865, - 63570:58866, - 63571:58867, - 63572:58868, - 63573:58869, - 63574:58870, - 63575:58871, - 63576:58872, - 63577:58873, - 63578:58874, - 63579:58875, - 63580:58876, - 63581:58877, - 63582:58878, - 63583:58879, - 63584:58880, - 63585:58881, - 63586:58882, - 63587:58883, - 63588:58884, - 63589:58885, - 63590:58886, - 63591:58887, - 63592:58888, - 63593:58889, - 63594:58890, - 63595:58891, - 63596:58892, - 63597:58893, - 63598:58894, - 63599:58895, - 63600:58896, - 63601:58897, - 63602:58898, - 63603:58899, - 63604:58900, - 63605:58901, - 63606:58902, - 63607:58903, - 63608:58904, - 63609:58905, - 63610:58906, - 63611:58907, - 63612:58908, - 63613:58909, - 63614:58910, - 63616:58911, - 63617:58912, - 63618:58913, - 63619:58914, - 63620:58915, - 63621:58916, - 63622:58917, - 63623:58918, - 63624:58919, - 63625:58920, - 63626:58921, - 63627:58922, - 63628:58923, - 63629:58924, - 63630:58925, - 63631:58926, - 63632:58927, - 63633:58928, - 63634:58929, - 63635:58930, - 63636:58931, - 63637:58932, - 63638:58933, - 63639:58934, - 63640:58935, - 63641:58936, - 63642:58937, - 63643:58938, - 63644:58939, - 63645:58940, - 63646:58941, - 63647:58942, - 63648:58943, - 63649:58944, - 63650:58945, - 63651:58946, - 63652:58947, - 63653:58948, - 63654:58949, - 63655:58950, - 63656:58951, - 63657:58952, - 63658:58953, - 63659:58954, - 63660:58955, - 63661:58956, - 63662:58957, - 63663:58958, - 63664:58959, - 63665:58960, - 63666:58961, - 63667:58962, - 63668:58963, - 63669:58964, - 63670:58965, - 63671:58966, - 63672:58967, - 63673:58968, - 63674:58969, - 63675:58970, - 63676:58971, - 63677:58972, - 63678:58973, - 63679:58974, - 63680:58975, - 63681:58976, - 63682:58977, - 63683:58978, - 63684:58979, - 63685:58980, - 63686:58981, - 63687:58982, - 63688:58983, - 63689:58984, - 63690:58985, - 63691:58986, - 63692:58987, - 63693:58988, - 63694:58989, - 63695:58990, - 63696:58991, - 63697:58992, - 63698:58993, - 63699:58994, - 63700:58995, - 63701:58996, - 63702:58997, - 63703:58998, - 63704:58999, - 63705:59000, - 63706:59001, - 63707:59002, - 63708:59003, - 63709:59004, - 63710:59005, - 63711:59006, - 63712:59007, - 63713:59008, - 63714:59009, - 63715:59010, - 63716:59011, - 63717:59012, - 63718:59013, - 63719:59014, - 63720:59015, - 63721:59016, - 63722:59017, - 63723:59018, - 63724:59019, - 63725:59020, - 63726:59021, - 63727:59022, - 63728:59023, - 63729:59024, - 63730:59025, - 63731:59026, - 63732:59027, - 63733:59028, - 63734:59029, - 63735:59030, - 63736:59031, - 63737:59032, - 63738:59033, - 63739:59034, - 63740:59035, - 64064:8560, - 64065:8561, - 64066:8562, - 64067:8563, - 64068:8564, - 64069:8565, - 64070:8566, - 64071:8567, - 64072:8568, - 64073:8569, - 64074:8544, - 64075:8545, - 64076:8546, - 64077:8547, - 64078:8548, - 64079:8549, - 64080:8550, - 64081:8551, - 64082:8552, - 64083:8553, - 64084:65506, - 64085:65508, - 64086:65287, - 64087:65282, - 64088:12849, - 64089:8470, - 64090:8481, - 64091:8757, - 64092:32394, - 64093:35100, - 64094:37704, - 64095:37512, - 64096:34012, - 64097:20425, - 64098:28859, - 64099:26161, - 64100:26824, - 64101:37625, - 64102:26363, - 64103:24389, - 64104:20008, - 64105:20193, - 64106:20220, - 64107:20224, - 64108:20227, - 64109:20281, - 64110:20310, - 64111:20370, - 64112:20362, - 64113:20378, - 64114:20372, - 64115:20429, - 64116:20544, - 64117:20514, - 64118:20479, - 64119:20510, - 64120:20550, - 64121:20592, - 64122:20546, - 64123:20628, - 64124:20724, - 64125:20696, - 64126:20810, - 64128:20836, - 64129:20893, - 64130:20926, - 64131:20972, - 64132:21013, - 64133:21148, - 64134:21158, - 64135:21184, - 64136:21211, - 64137:21248, - 64138:21255, - 64139:21284, - 64140:21362, - 64141:21395, - 64142:21426, - 64143:21469, - 64144:64014, - 64145:21660, - 64146:21642, - 64147:21673, - 64148:21759, - 64149:21894, - 64150:22361, - 64151:22373, - 64152:22444, - 64153:22472, - 64154:22471, - 64155:64015, - 64156:64016, - 64157:22686, - 64158:22706, - 64159:22795, - 64160:22867, - 64161:22875, - 64162:22877, - 64163:22883, - 64164:22948, - 64165:22970, - 64166:23382, - 64167:23488, - 64168:29999, - 64169:23512, - 64170:23532, - 64171:23582, - 64172:23718, - 64173:23738, - 64174:23797, - 64175:23847, - 64176:23891, - 64177:64017, - 64178:23874, - 64179:23917, - 64180:23992, - 64181:23993, - 64182:24016, - 64183:24353, - 64184:24372, - 64185:24423, - 64186:24503, - 64187:24542, - 64188:24669, - 64189:24709, - 64190:24714, - 64191:24798, - 64192:24789, - 64193:24864, - 64194:24818, - 64195:24849, - 64196:24887, - 64197:24880, - 64198:24984, - 64199:25107, - 64200:25254, - 64201:25589, - 64202:25696, - 64203:25757, - 64204:25806, - 64205:25934, - 64206:26112, - 64207:26133, - 64208:26171, - 64209:26121, - 64210:26158, - 64211:26142, - 64212:26148, - 64213:26213, - 64214:26199, - 64215:26201, - 64216:64018, - 64217:26227, - 64218:26265, - 64219:26272, - 64220:26290, - 64221:26303, - 64222:26362, - 64223:26382, - 64224:63785, - 64225:26470, - 64226:26555, - 64227:26706, - 64228:26560, - 64229:26625, - 64230:26692, - 64231:26831, - 64232:64019, - 64233:26984, - 64234:64020, - 64235:27032, - 64236:27106, - 64237:27184, - 64238:27243, - 64239:27206, - 64240:27251, - 64241:27262, - 64242:27362, - 64243:27364, - 64244:27606, - 64245:27711, - 64246:27740, - 64247:27782, - 64248:27759, - 64249:27866, - 64250:27908, - 64251:28039, - 64252:28015, - 64320:28054, - 64321:28076, - 64322:28111, - 64323:28152, - 64324:28146, - 64325:28156, - 64326:28217, - 64327:28252, - 64328:28199, - 64329:28220, - 64330:28351, - 64331:28552, - 64332:28597, - 64333:28661, - 64334:28677, - 64335:28679, - 64336:28712, - 64337:28805, - 64338:28843, - 64339:28943, - 64340:28932, - 64341:29020, - 64342:28998, - 64343:28999, - 64344:64021, - 64345:29121, - 64346:29182, - 64347:29361, - 64348:29374, - 64349:29476, - 64350:64022, - 64351:29559, - 64352:29629, - 64353:29641, - 64354:29654, - 64355:29667, - 64356:29650, - 64357:29703, - 64358:29685, - 64359:29734, - 64360:29738, - 64361:29737, - 64362:29742, - 64363:29794, - 64364:29833, - 64365:29855, - 64366:29953, - 64367:30063, - 64368:30338, - 64369:30364, - 64370:30366, - 64371:30363, - 64372:30374, - 64373:64023, - 64374:30534, - 64375:21167, - 64376:30753, - 64377:30798, - 64378:30820, - 64379:30842, - 64380:31024, - 64381:64024, - 64382:64025, - 64384:64026, - 64385:31124, - 64386:64027, - 64387:31131, - 64388:31441, - 64389:31463, - 64390:64028, - 64391:31467, - 64392:31646, - 64393:64029, - 64394:32072, - 64395:32092, - 64396:32183, - 64397:32160, - 64398:32214, - 64399:32338, - 64400:32583, - 64401:32673, - 64402:64030, - 64403:33537, - 64404:33634, - 64405:33663, - 64406:33735, - 64407:33782, - 64408:33864, - 64409:33972, - 64410:34131, - 64411:34137, - 64412:34155, - 64413:64031, - 64414:34224, - 64415:64032, - 64416:64033, - 64417:34823, - 64418:35061, - 64419:35346, - 64420:35383, - 64421:35449, - 64422:35495, - 64423:35518, - 64424:35551, - 64425:64034, - 64426:35574, - 64427:35667, - 64428:35711, - 64429:36080, - 64430:36084, - 64431:36114, - 64432:36214, - 64433:64035, - 64434:36559, - 64435:64036, - 64436:64037, - 64437:36967, - 64438:37086, - 64439:64038, - 64440:37141, - 64441:37159, - 64442:37338, - 64443:37335, - 64444:37342, - 64445:37357, - 64446:37358, - 64447:37348, - 64448:37349, - 64449:37382, - 64450:37392, - 64451:37386, - 64452:37434, - 64453:37440, - 64454:37436, - 64455:37454, - 64456:37465, - 64457:37457, - 64458:37433, - 64459:37479, - 64460:37543, - 64461:37495, - 64462:37496, - 64463:37607, - 64464:37591, - 64465:37593, - 64466:37584, - 64467:64039, - 64468:37589, - 64469:37600, - 64470:37587, - 64471:37669, - 64472:37665, - 64473:37627, - 64474:64040, - 64475:37662, - 64476:37631, - 64477:37661, - 64478:37634, - 64479:37744, - 64480:37719, - 64481:37796, - 64482:37830, - 64483:37854, - 64484:37880, - 64485:37937, - 64486:37957, - 64487:37960, - 64488:38290, - 64489:63964, - 64490:64041, - 64491:38557, - 64492:38575, - 64493:38707, - 64494:38715, - 64495:38723, - 64496:38733, - 64497:38735, - 64498:38737, - 64499:38741, - 64500:38999, - 64501:39013, - 64502:64042, - 64503:64043, - 64504:39207, - 64505:64044, - 64506:39326, - 64507:39502, - 64508:39641, - 64576:39644, - 64577:39797, - 64578:39794, - 64579:39823, - 64580:39857, - 64581:39867, - 64582:39936, - 64583:40304, - 64584:40299, - 64585:64045, - 64586:40473, - 64587:40657 - }; - - /** - * @author takahiro / https://github.com/takahirox - */ - - function DataViewEx ( buffer, littleEndian ) { - - this.dv = new DataView( buffer ); - this.offset = 0; - this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true; - this.encoder = new CharsetEncoder(); - - } - - DataViewEx.prototype = { - - constructor: DataViewEx, - - getInt8: function () { - - var value = this.dv.getInt8( this.offset ); - this.offset += 1; - return value; - - }, - - getInt8Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getInt8() ); - - } - - return a; - - }, - - getUint8: function () { - - var value = this.dv.getUint8( this.offset ); - this.offset += 1; - return value; - - }, - - getUint8Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getUint8() ); - - } - - return a; - - }, - - - getInt16: function () { - - var value = this.dv.getInt16( this.offset, this.littleEndian ); - this.offset += 2; - return value; - - }, - - getInt16Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getInt16() ); - - } - - return a; - - }, - - getUint16: function () { - - var value = this.dv.getUint16( this.offset, this.littleEndian ); - this.offset += 2; - return value; - - }, - - getUint16Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getUint16() ); - - } - - return a; - - }, - - getInt32: function () { - - var value = this.dv.getInt32( this.offset, this.littleEndian ); - this.offset += 4; - return value; - - }, - - getInt32Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getInt32() ); - - } - - return a; - - }, - - getUint32: function () { - - var value = this.dv.getUint32( this.offset, this.littleEndian ); - this.offset += 4; - return value; - - }, - - getUint32Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getUint32() ); - - } - - return a; - - }, - - getFloat32: function () { - - var value = this.dv.getFloat32( this.offset, this.littleEndian ); - this.offset += 4; - return value; - - }, - - getFloat32Array: function( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getFloat32() ); - - } - - return a; - - }, - - getFloat64: function () { - - var value = this.dv.getFloat64( this.offset, this.littleEndian ); - this.offset += 8; - return value; - - }, - - getFloat64Array: function( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getFloat64() ); - - } - - return a; - - }, - - getIndex: function ( type, isUnsigned ) { - - switch ( type ) { - - case 1: - return ( isUnsigned === true ) ? this.getUint8() : this.getInt8(); - - case 2: - return ( isUnsigned === true ) ? this.getUint16() : this.getInt16(); - - case 4: - return this.getInt32(); // No Uint32 - - default: - throw 'unknown number type ' + type + ' exception.'; - - } - - }, - - getIndexArray: function ( type, size, isUnsigned ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getIndex( type, isUnsigned ) ); - - } - - return a; - - }, - - getChars: function ( size ) { - - var str = ''; - - while ( size > 0 ) { - - var value = this.getUint8(); - size--; - - if ( value === 0 ) { - - break; - - } - - str += String.fromCharCode( value ); - - } - - while ( size > 0 ) { - - this.getUint8(); - size--; - - } - - return str; - - }, - - getSjisStringsAsUnicode: function ( size ) { - - var a = []; - - while ( size > 0 ) { - - var value = this.getUint8(); - size--; - - if ( value === 0 ) { - - break; - - } - - a.push( value ); - - } - - while ( size > 0 ) { - - this.getUint8(); - size--; - - } - - return this.encoder.s2u( new Uint8Array( a ) ); - - }, - - getUnicodeStrings: function ( size ) { - - var str = ''; - - while ( size > 0 ) { - - var value = this.getUint16(); - size -= 2; - - if ( value === 0 ) { - - break; - - } - - str += String.fromCharCode( value ); - - } - - while ( size > 0 ) { - - this.getUint8(); - size--; - - } - - return str; - - }, - - getTextBuffer: function () { - - var size = this.getUint32(); - return this.getUnicodeStrings( size ); - - } - - }; - - /** - * @author takahiro / https://github.com/takahirox - */ - - function DataCreationHelper () { - } - - DataCreationHelper.prototype = { - - constructor: DataCreationHelper, - - leftToRightVector3: function ( v ) { - - v[ 2 ] = -v[ 2 ]; - - }, - - leftToRightQuaternion: function ( q ) { - - q[ 0 ] = -q[ 0 ]; - q[ 1 ] = -q[ 1 ]; - - }, - - leftToRightEuler: function ( r ) { - - r[ 0 ] = -r[ 0 ]; - r[ 1 ] = -r[ 1 ]; - - }, - - leftToRightIndexOrder: function ( p ) { - - var tmp = p[ 2 ]; - p[ 2 ] = p[ 0 ]; - p[ 0 ] = tmp; - - }, - - leftToRightVector3Range: function ( v1, v2 ) { - - var tmp = -v2[ 2 ]; - v2[ 2 ] = -v1[ 2 ]; - v1[ 2 ] = tmp; - - }, - - leftToRightEulerRange: function ( r1, r2 ) { - - var tmp1 = -r2[ 0 ]; - var tmp2 = -r2[ 1 ]; - r2[ 0 ] = -r1[ 0 ]; - r2[ 1 ] = -r1[ 1 ]; - r1[ 0 ] = tmp1; - r1[ 1 ] = tmp2; - - } - - }; - - /** - * @author takahiro / https://github.com/takahirox - */ - - function Parser() { - } - - Parser.prototype.parsePmd = function ( buffer, leftToRight ) { - - var pmd = {}; - var dv = new DataViewEx( buffer ); - - pmd.metadata = {}; - pmd.metadata.format = 'pmd'; - pmd.metadata.coordinateSystem = 'left'; - - var parseHeader = function () { - - var metadata = pmd.metadata; - metadata.magic = dv.getChars( 3 ); - - if ( metadata.magic !== 'Pmd' ) { - - throw 'PMD file magic is not Pmd, but ' + metadata.magic; - - } - - metadata.version = dv.getFloat32(); - metadata.modelName = dv.getSjisStringsAsUnicode( 20 ); - metadata.comment = dv.getSjisStringsAsUnicode( 256 ); - - }; - - var parseVertices = function () { - - var parseVertex = function () { - - var p = {}; - p.position = dv.getFloat32Array( 3 ); - p.normal = dv.getFloat32Array( 3 ); - p.uv = dv.getFloat32Array( 2 ); - p.skinIndices = dv.getUint16Array( 2 ); - p.skinWeights = [ dv.getUint8() / 100 ]; - p.skinWeights.push( 1.0 - p.skinWeights[ 0 ] ); - p.edgeFlag = dv.getUint8(); - return p; - - }; - - var metadata = pmd.metadata; - metadata.vertexCount = dv.getUint32(); - - pmd.vertices = []; - - for ( var i = 0; i < metadata.vertexCount; i++ ) { - - pmd.vertices.push( parseVertex() ); - - } - - }; - - var parseFaces = function () { - - var parseFace = function () { - - var p = {}; - p.indices = dv.getUint16Array( 3 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.faceCount = dv.getUint32() / 3; - - pmd.faces = []; - - for ( var i = 0; i < metadata.faceCount; i++ ) { - - pmd.faces.push( parseFace() ); - - } - - }; - - var parseMaterials = function () { - - var parseMaterial = function () { - - var p = {}; - p.diffuse = dv.getFloat32Array( 4 ); - p.shininess = dv.getFloat32(); - p.specular = dv.getFloat32Array( 3 ); - p.ambient = dv.getFloat32Array( 3 ); - p.toonIndex = dv.getInt8(); - p.edgeFlag = dv.getUint8(); - p.faceCount = dv.getUint32() / 3; - p.fileName = dv.getSjisStringsAsUnicode( 20 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.materialCount = dv.getUint32(); - - pmd.materials = []; - - for ( var i = 0; i < metadata.materialCount; i++ ) { - - pmd.materials.push( parseMaterial() ); - - } - - }; - - var parseBones = function () { - - var parseBone = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - p.parentIndex = dv.getInt16(); - p.tailIndex = dv.getInt16(); - p.type = dv.getUint8(); - p.ikIndex = dv.getInt16(); - p.position = dv.getFloat32Array( 3 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.boneCount = dv.getUint16(); - - pmd.bones = []; - - for ( var i = 0; i < metadata.boneCount; i++ ) { - - pmd.bones.push( parseBone() ); - - } - - }; - - var parseIks = function () { - - var parseIk = function () { - - var p = {}; - p.target = dv.getUint16(); - p.effector = dv.getUint16(); - p.linkCount = dv.getUint8(); - p.iteration = dv.getUint16(); - p.maxAngle = dv.getFloat32(); - - p.links = []; - for ( var i = 0; i < p.linkCount; i++ ) { - - var link = {}; - link.index = dv.getUint16(); - p.links.push( link ); - - } - - return p; - - }; - - var metadata = pmd.metadata; - metadata.ikCount = dv.getUint16(); - - pmd.iks = []; - - for ( var i = 0; i < metadata.ikCount; i++ ) { - - pmd.iks.push( parseIk() ); - - } - - }; - - var parseMorphs = function () { - - var parseMorph = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - p.elementCount = dv.getUint32(); - p.type = dv.getUint8(); - - p.elements = []; - for ( var i = 0; i < p.elementCount; i++ ) { - - p.elements.push( { - index: dv.getUint32(), - position: dv.getFloat32Array( 3 ) - } ) ; - - } - - return p; - - }; - - var metadata = pmd.metadata; - metadata.morphCount = dv.getUint16(); - - pmd.morphs = []; - - for ( var i = 0; i < metadata.morphCount; i++ ) { - - pmd.morphs.push( parseMorph() ); - - } - - - }; - - var parseMorphFrames = function () { - - var parseMorphFrame = function () { - - var p = {}; - p.index = dv.getUint16(); - return p; - - }; - - var metadata = pmd.metadata; - metadata.morphFrameCount = dv.getUint8(); - - pmd.morphFrames = []; - - for ( var i = 0; i < metadata.morphFrameCount; i++ ) { - - pmd.morphFrames.push( parseMorphFrame() ); - - } - - }; - - var parseBoneFrameNames = function () { - - var parseBoneFrameName = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 50 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.boneFrameNameCount = dv.getUint8(); - - pmd.boneFrameNames = []; - - for ( var i = 0; i < metadata.boneFrameNameCount; i++ ) { - - pmd.boneFrameNames.push( parseBoneFrameName() ); - - } - - }; - - var parseBoneFrames = function () { - - var parseBoneFrame = function () { - - var p = {}; - p.boneIndex = dv.getInt16(); - p.frameIndex = dv.getUint8(); - return p; - - }; - - var metadata = pmd.metadata; - metadata.boneFrameCount = dv.getUint32(); - - pmd.boneFrames = []; - - for ( var i = 0; i < metadata.boneFrameCount; i++ ) { - - pmd.boneFrames.push( parseBoneFrame() ); - - } - - }; - - var parseEnglishHeader = function () { - - var metadata = pmd.metadata; - metadata.englishCompatibility = dv.getUint8(); - - if ( metadata.englishCompatibility > 0 ) { - - metadata.englishModelName = dv.getSjisStringsAsUnicode( 20 ); - metadata.englishComment = dv.getSjisStringsAsUnicode( 256 ); - - } - - }; - - var parseEnglishBoneNames = function () { - - var parseEnglishBoneName = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - return p; - - }; - - var metadata = pmd.metadata; - - if ( metadata.englishCompatibility === 0 ) { - - return; - - } - - pmd.englishBoneNames = []; - - for ( var i = 0; i < metadata.boneCount; i++ ) { - - pmd.englishBoneNames.push( parseEnglishBoneName() ); - - } - - }; - - var parseEnglishMorphNames = function () { - - var parseEnglishMorphName = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - return p; - - }; - - var metadata = pmd.metadata; - - if ( metadata.englishCompatibility === 0 ) { - - return; - - } - - pmd.englishMorphNames = []; - - for ( var i = 0; i < metadata.morphCount - 1; i++ ) { - - pmd.englishMorphNames.push( parseEnglishMorphName() ); - - } - - }; - - var parseEnglishBoneFrameNames = function () { - - var parseEnglishBoneFrameName = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 50 ); - return p; - - }; - - var metadata = pmd.metadata; - - if ( metadata.englishCompatibility === 0 ) { - - return; - - } - - pmd.englishBoneFrameNames = []; - - for ( var i = 0; i < metadata.boneFrameNameCount; i++ ) { - - pmd.englishBoneFrameNames.push( parseEnglishBoneFrameName() ); - - } - - }; - - var parseToonTextures = function () { - - var parseToonTexture = function () { - - var p = {}; - p.fileName = dv.getSjisStringsAsUnicode( 100 ); - return p; - - }; - - pmd.toonTextures = []; - - for ( var i = 0; i < 10; i++ ) { - - pmd.toonTextures.push( parseToonTexture() ); - - } - - }; - - var parseRigidBodies = function () { - - var parseRigidBody = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - p.boneIndex = dv.getInt16(); - p.groupIndex = dv.getUint8(); - p.groupTarget = dv.getUint16(); - p.shapeType = dv.getUint8(); - p.width = dv.getFloat32(); - p.height = dv.getFloat32(); - p.depth = dv.getFloat32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.weight = dv.getFloat32(); - p.positionDamping = dv.getFloat32(); - p.rotationDamping = dv.getFloat32(); - p.restitution = dv.getFloat32(); - p.friction = dv.getFloat32(); - p.type = dv.getUint8(); - return p; - - }; - - var metadata = pmd.metadata; - metadata.rigidBodyCount = dv.getUint32(); - - pmd.rigidBodies = []; - - for ( var i = 0; i < metadata.rigidBodyCount; i++ ) { - - pmd.rigidBodies.push( parseRigidBody() ); - - } - - }; - - var parseConstraints = function () { - - var parseConstraint = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - p.rigidBodyIndex1 = dv.getUint32(); - p.rigidBodyIndex2 = dv.getUint32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.translationLimitation1 = dv.getFloat32Array( 3 ); - p.translationLimitation2 = dv.getFloat32Array( 3 ); - p.rotationLimitation1 = dv.getFloat32Array( 3 ); - p.rotationLimitation2 = dv.getFloat32Array( 3 ); - p.springPosition = dv.getFloat32Array( 3 ); - p.springRotation = dv.getFloat32Array( 3 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.constraintCount = dv.getUint32(); - - pmd.constraints = []; - - for ( var i = 0; i < metadata.constraintCount; i++ ) { - - pmd.constraints.push( parseConstraint() ); - - } - - }; - - parseHeader(); - parseVertices(); - parseFaces(); - parseMaterials(); - parseBones(); - parseIks(); - parseMorphs(); - parseMorphFrames(); - parseBoneFrameNames(); - parseBoneFrames(); - parseEnglishHeader(); - parseEnglishBoneNames(); - parseEnglishMorphNames(); - parseEnglishBoneFrameNames(); - parseToonTextures(); - parseRigidBodies(); - parseConstraints(); - - if ( leftToRight === true ) this.leftToRightModel( pmd ); - - // console.log( pmd ); // for console debug - - return pmd; - - }; - - Parser.prototype.parsePmx = function ( buffer, leftToRight ) { - - var pmx = {}; - var dv = new DataViewEx( buffer ); - - pmx.metadata = {}; - pmx.metadata.format = 'pmx'; - pmx.metadata.coordinateSystem = 'left'; - - var parseHeader = function () { - - var metadata = pmx.metadata; - metadata.magic = dv.getChars( 4 ); - - // Note: don't remove the last blank space. - if ( metadata.magic !== 'PMX ' ) { - - throw 'PMX file magic is not PMX , but ' + metadata.magic; - - } - - metadata.version = dv.getFloat32(); - - if ( metadata.version !== 2.0 && metadata.version !== 2.1 ) { - - throw 'PMX version ' + metadata.version + ' is not supported.'; - - } - - metadata.headerSize = dv.getUint8(); - metadata.encoding = dv.getUint8(); - metadata.additionalUvNum = dv.getUint8(); - metadata.vertexIndexSize = dv.getUint8(); - metadata.textureIndexSize = dv.getUint8(); - metadata.materialIndexSize = dv.getUint8(); - metadata.boneIndexSize = dv.getUint8(); - metadata.morphIndexSize = dv.getUint8(); - metadata.rigidBodyIndexSize = dv.getUint8(); - metadata.modelName = dv.getTextBuffer(); - metadata.englishModelName = dv.getTextBuffer(); - metadata.comment = dv.getTextBuffer(); - metadata.englishComment = dv.getTextBuffer(); - - }; - - var parseVertices = function () { - - var parseVertex = function () { - - var p = {}; - p.position = dv.getFloat32Array( 3 ); - p.normal = dv.getFloat32Array( 3 ); - p.uv = dv.getFloat32Array( 2 ); - - p.auvs = []; - - for ( var i = 0; i < pmx.metadata.additionalUvNum; i++ ) { - - p.auvs.push( dv.getFloat32Array( 4 ) ); - - } - - p.type = dv.getUint8(); - - var indexSize = metadata.boneIndexSize; - - if ( p.type === 0 ) { // BDEF1 - - p.skinIndices = dv.getIndexArray( indexSize, 1 ); - p.skinWeights = [ 1.0 ]; - - } else if ( p.type === 1 ) { // BDEF2 - - p.skinIndices = dv.getIndexArray( indexSize, 2 ); - p.skinWeights = dv.getFloat32Array( 1 ); - p.skinWeights.push( 1.0 - p.skinWeights[ 0 ] ); - - } else if ( p.type === 2 ) { // BDEF4 - - p.skinIndices = dv.getIndexArray( indexSize, 4 ); - p.skinWeights = dv.getFloat32Array( 4 ); - - } else if ( p.type === 3 ) { // SDEF - - p.skinIndices = dv.getIndexArray( indexSize, 2 ); - p.skinWeights = dv.getFloat32Array( 1 ); - p.skinWeights.push( 1.0 - p.skinWeights[ 0 ] ); - - p.skinC = dv.getFloat32Array( 3 ); - p.skinR0 = dv.getFloat32Array( 3 ); - p.skinR1 = dv.getFloat32Array( 3 ); - - // SDEF is not supported yet and is handled as BDEF2 so far. - // TODO: SDEF support - p.type = 1; - - } else { - - throw 'unsupport bone type ' + p.type + ' exception.'; - - } - - p.edgeRatio = dv.getFloat32(); - return p; - - }; - - var metadata = pmx.metadata; - metadata.vertexCount = dv.getUint32(); - - pmx.vertices = []; - - for ( var i = 0; i < metadata.vertexCount; i++ ) { - - pmx.vertices.push( parseVertex() ); - - } - - }; - - var parseFaces = function () { - - var parseFace = function () { - - var p = {}; - p.indices = dv.getIndexArray( metadata.vertexIndexSize, 3, true ); - return p; - - }; - - var metadata = pmx.metadata; - metadata.faceCount = dv.getUint32() / 3; - - pmx.faces = []; - - for ( var i = 0; i < metadata.faceCount; i++ ) { - - pmx.faces.push( parseFace() ); - - } - - }; - - var parseTextures = function () { - - var parseTexture = function () { - - return dv.getTextBuffer(); - - }; - - var metadata = pmx.metadata; - metadata.textureCount = dv.getUint32(); - - pmx.textures = []; - - for ( var i = 0; i < metadata.textureCount; i++ ) { - - pmx.textures.push( parseTexture() ); - - } - - }; - - var parseMaterials = function () { - - var parseMaterial = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.diffuse = dv.getFloat32Array( 4 ); - p.specular = dv.getFloat32Array( 3 ); - p.shininess = dv.getFloat32(); - p.ambient = dv.getFloat32Array( 3 ); - p.flag = dv.getUint8(); - p.edgeColor = dv.getFloat32Array( 4 ); - p.edgeSize = dv.getFloat32(); - p.textureIndex = dv.getIndex( pmx.metadata.textureIndexSize ); - p.envTextureIndex = dv.getIndex( pmx.metadata.textureIndexSize ); - p.envFlag = dv.getUint8(); - p.toonFlag = dv.getUint8(); - - if ( p.toonFlag === 0 ) { - - p.toonIndex = dv.getIndex( pmx.metadata.textureIndexSize ); - - } else if ( p.toonFlag === 1 ) { - - p.toonIndex = dv.getInt8(); - - } else { - - throw 'unknown toon flag ' + p.toonFlag + ' exception.'; - - } - - p.comment = dv.getTextBuffer(); - p.faceCount = dv.getUint32() / 3; - return p; - - }; - - var metadata = pmx.metadata; - metadata.materialCount = dv.getUint32(); - - pmx.materials = []; - - for ( var i = 0; i < metadata.materialCount; i++ ) { - - pmx.materials.push( parseMaterial() ); - - } - - }; - - var parseBones = function () { - - var parseBone = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.position = dv.getFloat32Array( 3 ); - p.parentIndex = dv.getIndex( pmx.metadata.boneIndexSize ); - p.transformationClass = dv.getUint32(); - p.flag = dv.getUint16(); - - if ( p.flag & 0x1 ) { - - p.connectIndex = dv.getIndex( pmx.metadata.boneIndexSize ); - - } else { - - p.offsetPosition = dv.getFloat32Array( 3 ); - - } - - if ( p.flag & 0x100 || p.flag & 0x200 ) { - - // Note: I don't think Grant is an appropriate name - // but I found that some English translated MMD tools use this term - // so I've named it Grant so far. - // I'd rename to more appropriate name from Grant later. - var grant = {}; - - grant.isLocal = ( p.flag & 0x80 ) !== 0 ? true : false; - grant.affectRotation = ( p.flag & 0x100 ) !== 0 ? true : false; - grant.affectPosition = ( p.flag & 0x200 ) !== 0 ? true : false; - grant.parentIndex = dv.getIndex( pmx.metadata.boneIndexSize ); - grant.ratio = dv.getFloat32(); - - p.grant = grant; - - } - - if ( p.flag & 0x400 ) { - - p.fixAxis = dv.getFloat32Array( 3 ); - - } - - if ( p.flag & 0x800 ) { - - p.localXVector = dv.getFloat32Array( 3 ); - p.localZVector = dv.getFloat32Array( 3 ); - - } - - if ( p.flag & 0x2000 ) { - - p.key = dv.getUint32(); - - } - - if ( p.flag & 0x20 ) { - - var ik = {}; - - ik.effector = dv.getIndex( pmx.metadata.boneIndexSize ); - ik.target = null; - ik.iteration = dv.getUint32(); - ik.maxAngle = dv.getFloat32(); - ik.linkCount = dv.getUint32(); - ik.links = []; - - for ( var i = 0; i < ik.linkCount; i++ ) { - - var link = {}; - link.index = dv.getIndex( pmx.metadata.boneIndexSize ); - link.angleLimitation = dv.getUint8(); - - if ( link.angleLimitation === 1 ) { - - link.lowerLimitationAngle = dv.getFloat32Array( 3 ); - link.upperLimitationAngle = dv.getFloat32Array( 3 ); - - } - - ik.links.push( link ); - - } - - p.ik = ik; - } - - return p; - - }; - - var metadata = pmx.metadata; - metadata.boneCount = dv.getUint32(); - - pmx.bones = []; - - for ( var i = 0; i < metadata.boneCount; i++ ) { - - pmx.bones.push( parseBone() ); - - } - - }; - - var parseMorphs = function () { - - var parseMorph = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.panel = dv.getUint8(); - p.type = dv.getUint8(); - p.elementCount = dv.getUint32(); - p.elements = []; - - for ( var i = 0; i < p.elementCount; i++ ) { - - if ( p.type === 0 ) { // group morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.morphIndexSize ); - m.ratio = dv.getFloat32(); - p.elements.push( m ); - - } else if ( p.type === 1 ) { // vertex morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.vertexIndexSize, true ); - m.position = dv.getFloat32Array( 3 ); - p.elements.push( m ); - - } else if ( p.type === 2 ) { // bone morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.boneIndexSize ); - m.position = dv.getFloat32Array( 3 ); - m.rotation = dv.getFloat32Array( 4 ); - p.elements.push( m ); - - } else if ( p.type === 3 ) { // uv morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.vertexIndexSize, true ); - m.uv = dv.getFloat32Array( 4 ); - p.elements.push( m ); - - } else if ( p.type === 4 ) ; else if ( p.type === 5 ) ; else if ( p.type === 6 ) ; else if ( p.type === 7 ) ; else if ( p.type === 8 ) { // material morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.materialIndexSize ); - m.type = dv.getUint8(); - m.diffuse = dv.getFloat32Array( 4 ); - m.specular = dv.getFloat32Array( 3 ); - m.shininess = dv.getFloat32(); - m.ambient = dv.getFloat32Array( 3 ); - m.edgeColor = dv.getFloat32Array( 4 ); - m.edgeSize = dv.getFloat32(); - m.textureColor = dv.getFloat32Array( 4 ); - m.sphereTextureColor = dv.getFloat32Array( 4 ); - m.toonColor = dv.getFloat32Array( 4 ); - p.elements.push( m ); - - } - - } - - return p; - - }; - - var metadata = pmx.metadata; - metadata.morphCount = dv.getUint32(); - - pmx.morphs = []; - - for ( var i = 0; i < metadata.morphCount; i++ ) { - - pmx.morphs.push( parseMorph() ); - - } - - }; - - var parseFrames = function () { - - var parseFrame = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.type = dv.getUint8(); - p.elementCount = dv.getUint32(); - p.elements = []; - - for ( var i = 0; i < p.elementCount; i++ ) { - - var e = {}; - e.target = dv.getUint8(); - e.index = ( e.target === 0 ) ? dv.getIndex( pmx.metadata.boneIndexSize ) : dv.getIndex( pmx.metadata.morphIndexSize ); - p.elements.push( e ); - - } - - return p; - - }; - - var metadata = pmx.metadata; - metadata.frameCount = dv.getUint32(); - - pmx.frames = []; - - for ( var i = 0; i < metadata.frameCount; i++ ) { - - pmx.frames.push( parseFrame() ); - - } - - }; - - var parseRigidBodies = function () { - - var parseRigidBody = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.boneIndex = dv.getIndex( pmx.metadata.boneIndexSize ); - p.groupIndex = dv.getUint8(); - p.groupTarget = dv.getUint16(); - p.shapeType = dv.getUint8(); - p.width = dv.getFloat32(); - p.height = dv.getFloat32(); - p.depth = dv.getFloat32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.weight = dv.getFloat32(); - p.positionDamping = dv.getFloat32(); - p.rotationDamping = dv.getFloat32(); - p.restitution = dv.getFloat32(); - p.friction = dv.getFloat32(); - p.type = dv.getUint8(); - return p; - - }; - - var metadata = pmx.metadata; - metadata.rigidBodyCount = dv.getUint32(); - - pmx.rigidBodies = []; - - for ( var i = 0; i < metadata.rigidBodyCount; i++ ) { - - pmx.rigidBodies.push( parseRigidBody() ); - - } - - }; - - var parseConstraints = function () { - - var parseConstraint = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.type = dv.getUint8(); - p.rigidBodyIndex1 = dv.getIndex( pmx.metadata.rigidBodyIndexSize ); - p.rigidBodyIndex2 = dv.getIndex( pmx.metadata.rigidBodyIndexSize ); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.translationLimitation1 = dv.getFloat32Array( 3 ); - p.translationLimitation2 = dv.getFloat32Array( 3 ); - p.rotationLimitation1 = dv.getFloat32Array( 3 ); - p.rotationLimitation2 = dv.getFloat32Array( 3 ); - p.springPosition = dv.getFloat32Array( 3 ); - p.springRotation = dv.getFloat32Array( 3 ); - return p; - - }; - - var metadata = pmx.metadata; - metadata.constraintCount = dv.getUint32(); - - pmx.constraints = []; - - for ( var i = 0; i < metadata.constraintCount; i++ ) { - - pmx.constraints.push( parseConstraint() ); - - } - - }; - - parseHeader(); - parseVertices(); - parseFaces(); - parseTextures(); - parseMaterials(); - parseBones(); - parseMorphs(); - parseFrames(); - parseRigidBodies(); - parseConstraints(); - - if ( leftToRight === true ) this.leftToRightModel( pmx ); - - // console.log( pmx ); // for console debug - - return pmx; - - }; - - Parser.prototype.parseVmd = function ( buffer, leftToRight ) { - - var vmd = {}; - var dv = new DataViewEx( buffer ); - - vmd.metadata = {}; - vmd.metadata.coordinateSystem = 'left'; - - var parseHeader = function () { - - var metadata = vmd.metadata; - metadata.magic = dv.getChars( 30 ); - - if ( metadata.magic !== 'Vocaloid Motion Data 0002' ) { - - throw 'VMD file magic is not Vocaloid Motion Data 0002, but ' + metadata.magic; - - } - - metadata.name = dv.getSjisStringsAsUnicode( 20 ); - - }; - - var parseMotions = function () { - - var parseMotion = function () { - - var p = {}; - p.boneName = dv.getSjisStringsAsUnicode( 15 ); - p.frameNum = dv.getUint32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 4 ); - p.interpolation = dv.getUint8Array( 64 ); - return p; - - }; - - var metadata = vmd.metadata; - metadata.motionCount = dv.getUint32(); - - vmd.motions = []; - for ( var i = 0; i < metadata.motionCount; i++ ) { - - vmd.motions.push( parseMotion() ); - - } - - }; - - var parseMorphs = function () { - - var parseMorph = function () { - - var p = {}; - p.morphName = dv.getSjisStringsAsUnicode( 15 ); - p.frameNum = dv.getUint32(); - p.weight = dv.getFloat32(); - return p; - - }; - - var metadata = vmd.metadata; - metadata.morphCount = dv.getUint32(); - - vmd.morphs = []; - for ( var i = 0; i < metadata.morphCount; i++ ) { - - vmd.morphs.push( parseMorph() ); - - } - - }; - - var parseCameras = function () { - - var parseCamera = function () { - - var p = {}; - p.frameNum = dv.getUint32(); - p.distance = dv.getFloat32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.interpolation = dv.getUint8Array( 24 ); - p.fov = dv.getUint32(); - p.perspective = dv.getUint8(); - return p; - - }; - - var metadata = vmd.metadata; - metadata.cameraCount = dv.getUint32(); - - vmd.cameras = []; - for ( var i = 0; i < metadata.cameraCount; i++ ) { - - vmd.cameras.push( parseCamera() ); - - } - - }; - - parseHeader(); - parseMotions(); - parseMorphs(); - parseCameras(); - - if ( leftToRight === true ) this.leftToRightVmd( vmd ); - - // console.log( vmd ); // for console debug - - return vmd; - - }; - - Parser.prototype.parseVpd = function ( text, leftToRight ) { - - var vpd = {}; - - vpd.metadata = {}; - vpd.metadata.coordinateSystem = 'left'; - - vpd.bones = []; - - var commentPatternG = /\/\/\w*(\r|\n|\r\n)/g; - var newlinePattern = /\r|\n|\r\n/; - - var lines = text.replace( commentPatternG, '' ).split( newlinePattern ); - - function throwError () { - - throw 'the file seems not vpd file.'; - - } - - function checkMagic () { - - if ( lines[ 0 ] !== 'Vocaloid Pose Data file' ) { - - throwError(); - - } - - } - - function parseHeader () { - - if ( lines.length < 4 ) { - - throwError(); - - } - - vpd.metadata.parentFile = lines[ 2 ]; - vpd.metadata.boneCount = parseInt( lines[ 3 ] ); - - } - - function parseBones () { - - var boneHeaderPattern = /^\s*(Bone[0-9]+)\s*\{\s*(.*)$/; - var boneVectorPattern = /^\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*;/; - var boneQuaternionPattern = /^\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*;/; - var boneFooterPattern = /^\s*}/; - - var bones = vpd.bones; - var n = null; - var v = null; - var q = null; - - for ( var i = 4; i < lines.length; i++ ) { - - var line = lines[ i ]; - - var result; - - result = line.match( boneHeaderPattern ); - - if ( result !== null ) { - - if ( n !== null ) { - - throwError(); - - } - - n = result[ 2 ]; - - } - - result = line.match( boneVectorPattern ); - - if ( result !== null ) { - - if ( v !== null ) { - - throwError(); - - } - - v = [ - - parseFloat( result[ 1 ] ), - parseFloat( result[ 2 ] ), - parseFloat( result[ 3 ] ) - - ]; - - } - - result = line.match( boneQuaternionPattern ); - - if ( result !== null ) { - - if ( q !== null ) { - - throwError(); - - } - - q = [ - - parseFloat( result[ 1 ] ), - parseFloat( result[ 2 ] ), - parseFloat( result[ 3 ] ), - parseFloat( result[ 4 ] ) - - ]; - - - } - - result = line.match( boneFooterPattern ); - - if ( result !== null ) { - - if ( n === null || v === null || q === null ) { - - throwError(); - - } - - bones.push( { - - name: n, - translation: v, - quaternion: q - - } ); - - n = null; - v = null; - q = null; - - } - - } - - if ( n !== null || v !== null || q !== null ) { - - throwError(); - - } - - } - - checkMagic(); - parseHeader(); - parseBones(); - - if ( leftToRight === true ) this.leftToRightVpd( vpd ); - - // console.log( vpd ); // for console debug - - return vpd; - - }; - - Parser.prototype.mergeVmds = function ( vmds ) { - - var v = {}; - v.metadata = {}; - v.metadata.name = vmds[ 0 ].metadata.name; - v.metadata.coordinateSystem = vmds[ 0 ].metadata.coordinateSystem; - v.metadata.motionCount = 0; - v.metadata.morphCount = 0; - v.metadata.cameraCount = 0; - v.motions = []; - v.morphs = []; - v.cameras = []; - - for ( var i = 0; i < vmds.length; i++ ) { - - var v2 = vmds[ i ]; - - v.metadata.motionCount += v2.metadata.motionCount; - v.metadata.morphCount += v2.metadata.morphCount; - v.metadata.cameraCount += v2.metadata.cameraCount; - - for ( var j = 0; j < v2.metadata.motionCount; j++ ) { - - v.motions.push( v2.motions[ j ] ); - - } - - for ( var j = 0; j < v2.metadata.morphCount; j++ ) { - - v.morphs.push( v2.morphs[ j ] ); - - } - - for ( var j = 0; j < v2.metadata.cameraCount; j++ ) { - - v.cameras.push( v2.cameras[ j ] ); - - } - - } - - return v; - - }; - - Parser.prototype.leftToRightModel = function ( model ) { - - if ( model.metadata.coordinateSystem === 'right' ) { - - return; - - } - - model.metadata.coordinateSystem = 'right'; - - var helper = new DataCreationHelper(); - - for ( var i = 0; i < model.metadata.vertexCount; i++ ) { - - helper.leftToRightVector3( model.vertices[ i ].position ); - helper.leftToRightVector3( model.vertices[ i ].normal ); - - } - - for ( var i = 0; i < model.metadata.faceCount; i++ ) { - - helper.leftToRightIndexOrder( model.faces[ i ].indices ); - - } - - for ( var i = 0; i < model.metadata.boneCount; i++ ) { - - helper.leftToRightVector3( model.bones[ i ].position ); - - } - - // TODO: support other morph for PMX - for ( var i = 0; i < model.metadata.morphCount; i++ ) { - - var m = model.morphs[ i ]; - - if ( model.metadata.format === 'pmx' && m.type !== 1 ) { - - // TODO: implement - continue; - - } - - for ( var j = 0; j < m.elements.length; j++ ) { - - helper.leftToRightVector3( m.elements[ j ].position ); - - } - - } - - for ( var i = 0; i < model.metadata.rigidBodyCount; i++ ) { - - helper.leftToRightVector3( model.rigidBodies[ i ].position ); - helper.leftToRightEuler( model.rigidBodies[ i ].rotation ); - - } - - for ( var i = 0; i < model.metadata.constraintCount; i++ ) { - - helper.leftToRightVector3( model.constraints[ i ].position ); - helper.leftToRightEuler( model.constraints[ i ].rotation ); - helper.leftToRightVector3Range( model.constraints[ i ].translationLimitation1, model.constraints[ i ].translationLimitation2 ); - helper.leftToRightEulerRange( model.constraints[ i ].rotationLimitation1, model.constraints[ i ].rotationLimitation2 ); - - } - - }; - - Parser.prototype.leftToRightVmd = function ( vmd ) { - - if ( vmd.metadata.coordinateSystem === 'right' ) { - - return; - - } - - vmd.metadata.coordinateSystem = 'right'; - - var helper = new DataCreationHelper(); - - for ( var i = 0; i < vmd.metadata.motionCount; i++ ) { - - helper.leftToRightVector3( vmd.motions[ i ].position ); - helper.leftToRightQuaternion( vmd.motions[ i ].rotation ); - - } - - for ( var i = 0; i < vmd.metadata.cameraCount; i++ ) { - - helper.leftToRightVector3( vmd.cameras[ i ].position ); - helper.leftToRightEuler( vmd.cameras[ i ].rotation ); - - } - - }; - - Parser.prototype.leftToRightVpd = function ( vpd ) { - - if ( vpd.metadata.coordinateSystem === 'right' ) { - - return; - - } - - vpd.metadata.coordinateSystem = 'right'; - - var helper = new DataCreationHelper(); - - for ( var i = 0; i < vpd.bones.length; i++ ) { - - helper.leftToRightVector3( vpd.bones[ i ].translation ); - helper.leftToRightQuaternion( vpd.bones[ i ].quaternion ); - - } - - }; - - var MMDParser = { - CharsetEncoder: CharsetEncoder, - Parser: Parser - }; - - exports.MMDParser = MMDParser; - exports.CharsetEncoder = CharsetEncoder; - exports.Parser = Parser; - - Object.defineProperty(exports, '__esModule', { value: true }); - - }))); -} (mmdparser, mmdparser.exports)); - -/** - * CCD Algorithm - * - https://sites.google.com/site/auraliusproject/ccd-algorithm - * - * // ik parameter example - * // - * // target, effector, index in links are bone index in skeleton.bones. - * // the bones relation should be - * // <-- parent child --> - * // links[ n ], links[ n - 1 ], ..., links[ 0 ], effector - * iks = [ { - * target: 1, - * effector: 2, - * links: [ { index: 5, limitation: new Vector3( 1, 0, 0 ) }, { index: 4, enabled: false }, { index : 3 } ], - * iteration: 10, - * minAngle: 0.0, - * maxAngle: 1.0, - * } ]; - */ - -const CCDIKSolver = (() => { - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Array} iks - */ - function CCDIKSolver(mesh, iks) { - this.mesh = mesh; - this.iks = iks || []; - - this._valid(); - } - - CCDIKSolver.prototype = { - constructor: CCDIKSolver, - - /** - * Update IK bones. - * - * @return {CCDIKSolver} - */ - update: (() => { - const q = new Quaternion(); - const targetPos = new Vector3(); - const targetVec = new Vector3(); - const effectorPos = new Vector3(); - const effectorVec = new Vector3(); - const linkPos = new Vector3(); - const invLinkQ = new Quaternion(); - const linkScale = new Vector3(); - const axis = new Vector3(); - const vector = new Vector3(); - return function update() { - const bones = this.mesh.skeleton.bones; - const iks = this.iks; // for reference overhead reduction in loop - - const math = Math; - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - const effector = bones[ik.effector]; - const target = bones[ik.target]; // don't use getWorldPosition() here for the performance - // because it calls updateMatrixWorld( true ) inside. - - targetPos.setFromMatrixPosition(target.matrixWorld); - const links = ik.links; - const iteration = ik.iteration !== undefined ? ik.iteration : 1; - - for (let j = 0; j < iteration; j++) { - let rotated = false; - - for (let k = 0, kl = links.length; k < kl; k++) { - const link = bones[links[k].index]; // skip this link and following links. - // this skip is used for MMD performance optimization. - - if (links[k].enabled === false) break; - const limitation = links[k].limitation; - const rotationMin = links[k].rotationMin; - const rotationMax = links[k].rotationMax; // don't use getWorldPosition/Quaternion() here for the performance - // because they call updateMatrixWorld( true ) inside. - - link.matrixWorld.decompose(linkPos, invLinkQ, linkScale); - invLinkQ.invert(); - effectorPos.setFromMatrixPosition(effector.matrixWorld); // work in link world - - effectorVec.subVectors(effectorPos, linkPos); - effectorVec.applyQuaternion(invLinkQ); - effectorVec.normalize(); - targetVec.subVectors(targetPos, linkPos); - targetVec.applyQuaternion(invLinkQ); - targetVec.normalize(); - let angle = targetVec.dot(effectorVec); - - if (angle > 1.0) { - angle = 1.0; - } else if (angle < -1.0) { - angle = -1.0; - } - - angle = math.acos(angle); // skip if changing angle is too small to prevent vibration of bone - // Refer to http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js - - if (angle < 1e-5) continue; - - if (ik.minAngle !== undefined && angle < ik.minAngle) { - angle = ik.minAngle; - } - - if (ik.maxAngle !== undefined && angle > ik.maxAngle) { - angle = ik.maxAngle; - } - - axis.crossVectors(effectorVec, targetVec); - axis.normalize(); - q.setFromAxisAngle(axis, angle); - link.quaternion.multiply(q); // TODO: re-consider the limitation specification - - if (limitation !== undefined) { - let c = link.quaternion.w; - if (c > 1.0) c = 1.0; - const c2 = math.sqrt(1 - c * c); - link.quaternion.set(limitation.x * c2, limitation.y * c2, limitation.z * c2, c); - } - - if (rotationMin !== undefined) { - link.rotation.setFromVector3(link.rotation.toVector3(vector).max(rotationMin)); - } - - if (rotationMax !== undefined) { - link.rotation.setFromVector3(link.rotation.toVector3(vector).min(rotationMax)); - } - - link.updateMatrixWorld(true); - rotated = true; - } - - if (!rotated) break; - } - } - - return this; - }; - })(), - - /** - * Creates Helper - * - * @return {CCDIKHelper} - */ - createHelper: function () { - return new CCDIKHelper(this.mesh, this.mesh.geometry.userData.MMD.iks); - }, - // private methods - _valid: function () { - const iks = this.iks; - const bones = this.mesh.skeleton.bones; - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - const effector = bones[ik.effector]; - const links = ik.links; - let link0, link1; - link0 = effector; - - for (let j = 0, jl = links.length; j < jl; j++) { - link1 = bones[links[j].index]; - - if (link0.parent !== link1) { - console.warn(`THREE.CCDIKSolver: bone ${link0.name} is not the child of bone ${link1.name}`); - } - - link0 = link1; - } - } - } - }; - /** - * Visualize IK bones - * - * @param {SkinnedMesh} mesh - * @param {Array} iks - */ - - function CCDIKHelper(mesh, iks) { - Object3D.call(this); - this.root = mesh; - this.iks = iks || []; - this.matrix.copy(mesh.matrixWorld); - this.matrixAutoUpdate = false; - this.sphereGeometry = new SphereGeometry(0.25, 16, 8); - this.targetSphereMaterial = new MeshBasicMaterial({ - color: new Color(0xff8888), - depthTest: false, - depthWrite: false, - transparent: true - }); - this.effectorSphereMaterial = new MeshBasicMaterial({ - color: new Color(0x88ff88), - depthTest: false, - depthWrite: false, - transparent: true - }); - this.linkSphereMaterial = new MeshBasicMaterial({ - color: new Color(0x8888ff), - depthTest: false, - depthWrite: false, - transparent: true - }); - this.lineMaterial = new LineBasicMaterial({ - color: new Color(0xff0000), - depthTest: false, - depthWrite: false, - transparent: true - }); - - this._init(); - } - - CCDIKHelper.prototype = Object.assign(Object.create(Object3D.prototype), { - constructor: CCDIKHelper, - - /** - * Updates IK bones visualization. - */ - updateMatrixWorld: (() => { - const matrix = new Matrix4(); - const vector = new Vector3(); - - function getPosition(bone, matrixWorldInv) { - return vector.setFromMatrixPosition(bone.matrixWorld).applyMatrix4(matrixWorldInv); - } - - function setPositionOfBoneToAttributeArray(array, index, bone, matrixWorldInv) { - const v = getPosition(bone, matrixWorldInv); - array[index * 3 + 0] = v.x; - array[index * 3 + 1] = v.y; - array[index * 3 + 2] = v.z; - } - - return function updateMatrixWorld(force) { - const mesh = this.root; - - if (this.visible) { - let offset = 0; - const iks = this.iks; - const bones = mesh.skeleton.bones; - matrix.copy(mesh.matrixWorld).invert(); - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - const targetBone = bones[ik.target]; - const effectorBone = bones[ik.effector]; - const targetMesh = this.children[offset++]; - const effectorMesh = this.children[offset++]; - targetMesh.position.copy(getPosition(targetBone, matrix)); - effectorMesh.position.copy(getPosition(effectorBone, matrix)); - - for (let j = 0, jl = ik.links.length; j < jl; j++) { - var link = ik.links[j]; - var linkBone = bones[link.index]; - const linkMesh = this.children[offset++]; - linkMesh.position.copy(getPosition(linkBone, matrix)); - } - - const line = this.children[offset++]; - const array = line.geometry.attributes.position.array; - setPositionOfBoneToAttributeArray(array, 0, targetBone, matrix); - setPositionOfBoneToAttributeArray(array, 1, effectorBone, matrix); - - for (let j = 0, jl = ik.links.length; j < jl; j++) { - var link = ik.links[j]; - var linkBone = bones[link.index]; - setPositionOfBoneToAttributeArray(array, j + 2, linkBone, matrix); - } - - line.geometry.attributes.position.needsUpdate = true; - } - } - - this.matrix.copy(mesh.matrixWorld); - Object3D.prototype.updateMatrixWorld.call(this, force); - }; - })(), - // private method - _init: function () { - const scope = this; - const iks = this.iks; - - function createLineGeometry(ik) { - const geometry = new BufferGeometry(); - const vertices = new Float32Array((2 + ik.links.length) * 3); - geometry.setAttribute('position', new BufferAttribute(vertices, 3)); - return geometry; - } - - function createTargetMesh() { - return new Mesh(scope.sphereGeometry, scope.targetSphereMaterial); - } - - function createEffectorMesh() { - return new Mesh(scope.sphereGeometry, scope.effectorSphereMaterial); - } - - function createLinkMesh() { - return new Mesh(scope.sphereGeometry, scope.linkSphereMaterial); - } - - function createLine(ik) { - return new Line$2(createLineGeometry(ik), scope.lineMaterial); - } - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - this.add(createTargetMesh()); - this.add(createEffectorMesh()); - - for (let j = 0, jl = ik.links.length; j < jl; j++) { - this.add(createLinkMesh()); - } - - this.add(createLine(ik)); - } - } - }); - return CCDIKSolver; -})(); - -/** - * Dependencies - * - Ammo.js https://github.com/kripken/ammo.js - * - * MMDPhysics calculates physics with Ammo(Bullet based JavaScript Physics engine) - * for MMD model loaded by MMDLoader. - * - * TODO - * - Physics in Worker - */ - -/* global Ammo */ - -const MMDPhysics = (() => { - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Array} rigidBodyParams - * @param {Array} (optional) constraintParams - * @param {Object} params - (optional) - * @param {Number} params.unitStep - Default is 1 / 65. - * @param {Integer} params.maxStepNum - Default is 3. - * @param {Vector3} params.gravity - Default is ( 0, - 9.8 * 10, 0 ) - */ - function MMDPhysics(mesh, rigidBodyParams, constraintParams, params) { - if (typeof Ammo === 'undefined') { - throw new Error('THREE.MMDPhysics: Import ammo.js https://github.com/kripken/ammo.js'); - } - - constraintParams = constraintParams || []; - params = params || {}; - this.manager = new ResourceManager(); - this.mesh = mesh; - /* - * I don't know why but 1/60 unitStep easily breaks models - * so I set it 1/65 so far. - * Don't set too small unitStep because - * the smaller unitStep can make the performance worse. - */ - - this.unitStep = params.unitStep !== undefined ? params.unitStep : 1 / 65; - this.maxStepNum = params.maxStepNum !== undefined ? params.maxStepNum : 3; - this.gravity = new Vector3(0, -9.8 * 10, 0); - if (params.gravity !== undefined) this.gravity.copy(params.gravity); - this.world = params.world !== undefined ? params.world : null; // experimental - - this.bodies = []; - this.constraints = []; - - this._init(mesh, rigidBodyParams, constraintParams); - } - - MMDPhysics.prototype = { - constructor: MMDPhysics, - - /** - * Advances Physics calculation and updates bones. - * - * @param {Number} delta - time in second - * @return {MMDPhysics} - */ - update: function (delta) { - const manager = this.manager; - const mesh = this.mesh; // rigid bodies and constrains are for - // mesh's world scale (1, 1, 1). - // Convert to (1, 1, 1) if it isn't. - - let isNonDefaultScale = false; - const position = manager.allocThreeVector3(); - const quaternion = manager.allocThreeQuaternion(); - const scale = manager.allocThreeVector3(); - mesh.matrixWorld.decompose(position, quaternion, scale); - - if (scale.x !== 1 || scale.y !== 1 || scale.z !== 1) { - isNonDefaultScale = true; - } - - let parent; - - if (isNonDefaultScale) { - parent = mesh.parent; - if (parent !== null) mesh.parent = null; - scale.copy(this.mesh.scale); - mesh.scale.set(1, 1, 1); - mesh.updateMatrixWorld(true); - } // calculate physics and update bones - - - this._updateRigidBodies(); - - this._stepSimulation(delta); - - this._updateBones(); // restore mesh if converted above - - - if (isNonDefaultScale) { - if (parent !== null) mesh.parent = parent; - mesh.scale.copy(scale); - } - - manager.freeThreeVector3(scale); - manager.freeThreeQuaternion(quaternion); - manager.freeThreeVector3(position); - return this; - }, - - /** - * Resets rigid bodies transorm to current bone's. - * - * @return {MMDPhysics} - */ - reset: function () { - for (let i = 0, il = this.bodies.length; i < il; i++) { - this.bodies[i].reset(); - } - - return this; - }, - - /** - * Warm ups Rigid bodies. Calculates cycles steps. - * - * @param {Integer} cycles - * @return {MMDPhysics} - */ - warmup: function (cycles) { - for (let i = 0; i < cycles; i++) { - this.update(1 / 60); - } - - return this; - }, - - /** - * Sets gravity. - * - * @param {Vector3} gravity - * @return {MMDPhysicsHelper} - */ - setGravity: function (gravity) { - this.world.setGravity(new Ammo.btVector3(gravity.x, gravity.y, gravity.z)); - this.gravity.copy(gravity); - return this; - }, - - /** - * Creates MMDPhysicsHelper - * - * @return {MMDPhysicsHelper} - */ - createHelper: function () { - return new MMDPhysicsHelper(this.mesh, this); - }, - // private methods - _init: function (mesh, rigidBodyParams, constraintParams) { - const manager = this.manager; // rigid body/constraint parameters are for - // mesh's default world transform as position(0, 0, 0), - // quaternion(0, 0, 0, 1) and scale(0, 0, 0) - - let parent = mesh.parent; - if (parent !== null) parent = null; - const currentPosition = manager.allocThreeVector3(); - const currentQuaternion = manager.allocThreeQuaternion(); - const currentScale = manager.allocThreeVector3(); - currentPosition.copy(mesh.position); - currentQuaternion.copy(mesh.quaternion); - currentScale.copy(mesh.scale); - mesh.position.set(0, 0, 0); - mesh.quaternion.set(0, 0, 0, 1); - mesh.scale.set(1, 1, 1); - mesh.updateMatrixWorld(true); - - if (this.world === null) { - this.world = this._createWorld(); - this.setGravity(this.gravity); - } - - this._initRigidBodies(rigidBodyParams); - - this._initConstraints(constraintParams); - - if (parent !== null) mesh.parent = parent; - mesh.position.copy(currentPosition); - mesh.quaternion.copy(currentQuaternion); - mesh.scale.copy(currentScale); - mesh.updateMatrixWorld(true); - this.reset(); - manager.freeThreeVector3(currentPosition); - manager.freeThreeQuaternion(currentQuaternion); - manager.freeThreeVector3(currentScale); - }, - _createWorld: function () { - const config = new Ammo.btDefaultCollisionConfiguration(); - const dispatcher = new Ammo.btCollisionDispatcher(config); - const cache = new Ammo.btDbvtBroadphase(); - const solver = new Ammo.btSequentialImpulseConstraintSolver(); - const world = new Ammo.btDiscreteDynamicsWorld(dispatcher, cache, solver, config); - return world; - }, - _initRigidBodies: function (rigidBodies) { - for (let i = 0, il = rigidBodies.length; i < il; i++) { - this.bodies.push(new RigidBody(this.mesh, this.world, rigidBodies[i], this.manager)); - } - }, - _initConstraints: function (constraints) { - for (let i = 0, il = constraints.length; i < il; i++) { - const params = constraints[i]; - const bodyA = this.bodies[params.rigidBodyIndex1]; - const bodyB = this.bodies[params.rigidBodyIndex2]; - this.constraints.push(new Constraint(this.mesh, this.world, bodyA, bodyB, params, this.manager)); - } - }, - _stepSimulation: function (delta) { - const unitStep = this.unitStep; - let stepTime = delta; - let maxStepNum = (delta / unitStep | 0) + 1; - - if (stepTime < unitStep) { - stepTime = unitStep; - maxStepNum = 1; - } - - if (maxStepNum > this.maxStepNum) { - maxStepNum = this.maxStepNum; - } - - this.world.stepSimulation(stepTime, maxStepNum, unitStep); - }, - _updateRigidBodies: function () { - for (let i = 0, il = this.bodies.length; i < il; i++) { - this.bodies[i].updateFromBone(); - } - }, - _updateBones: function () { - for (let i = 0, il = this.bodies.length; i < il; i++) { - this.bodies[i].updateBone(); - } - } - }; - /** - * This manager's responsibilies are - * - * 1. manage Ammo.js and Three.js object resources and - * improve the performance and the memory consumption by - * reusing objects. - * - * 2. provide simple Ammo object operations. - */ - - function ResourceManager() { - // for Three.js - this.threeVector3s = []; - this.threeMatrix4s = []; - this.threeQuaternions = []; - this.threeEulers = []; // for Ammo.js - - this.transforms = []; - this.quaternions = []; - this.vector3s = []; - } - - ResourceManager.prototype = { - constructor: ResourceManager, - allocThreeVector3: function () { - return this.threeVector3s.length > 0 ? this.threeVector3s.pop() : new Vector3(); - }, - freeThreeVector3: function (v) { - this.threeVector3s.push(v); - }, - allocThreeMatrix4: function () { - return this.threeMatrix4s.length > 0 ? this.threeMatrix4s.pop() : new Matrix4(); - }, - freeThreeMatrix4: function (m) { - this.threeMatrix4s.push(m); - }, - allocThreeQuaternion: function () { - return this.threeQuaternions.length > 0 ? this.threeQuaternions.pop() : new Quaternion(); - }, - freeThreeQuaternion: function (q) { - this.threeQuaternions.push(q); - }, - allocThreeEuler: function () { - return this.threeEulers.length > 0 ? this.threeEulers.pop() : new Euler(); - }, - freeThreeEuler: function (e) { - this.threeEulers.push(e); - }, - allocTransform: function () { - return this.transforms.length > 0 ? this.transforms.pop() : new Ammo.btTransform(); - }, - freeTransform: function (t) { - this.transforms.push(t); - }, - allocQuaternion: function () { - return this.quaternions.length > 0 ? this.quaternions.pop() : new Ammo.btQuaternion(); - }, - freeQuaternion: function (q) { - this.quaternions.push(q); - }, - allocVector3: function () { - return this.vector3s.length > 0 ? this.vector3s.pop() : new Ammo.btVector3(); - }, - freeVector3: function (v) { - this.vector3s.push(v); - }, - setIdentity: function (t) { - t.setIdentity(); - }, - getBasis: function (t) { - const q = this.allocQuaternion(); - t.getBasis().getRotation(q); - return q; - }, - getBasisAsMatrix3: function (t) { - const q = this.getBasis(t); - const m = this.quaternionToMatrix3(q); - this.freeQuaternion(q); - return m; - }, - getOrigin: function (t) { - return t.getOrigin(); - }, - setOrigin: function (t, v) { - t.getOrigin().setValue(v.x(), v.y(), v.z()); - }, - copyOrigin: function (t1, t2) { - const o = t2.getOrigin(); - this.setOrigin(t1, o); - }, - setBasis: function (t, q) { - t.setRotation(q); - }, - setBasisFromMatrix3: function (t, m) { - const q = this.matrix3ToQuaternion(m); - this.setBasis(t, q); - this.freeQuaternion(q); - }, - setOriginFromArray3: function (t, a) { - t.getOrigin().setValue(a[0], a[1], a[2]); - }, - setOriginFromThreeVector3: function (t, v) { - t.getOrigin().setValue(v.x, v.y, v.z); - }, - setBasisFromArray3: function (t, a) { - const thQ = this.allocThreeQuaternion(); - const thE = this.allocThreeEuler(); - thE.set(a[0], a[1], a[2]); - this.setBasisFromThreeQuaternion(t, thQ.setFromEuler(thE)); - this.freeThreeEuler(thE); - this.freeThreeQuaternion(thQ); - }, - setBasisFromThreeQuaternion: function (t, a) { - const q = this.allocQuaternion(); - q.setX(a.x); - q.setY(a.y); - q.setZ(a.z); - q.setW(a.w); - this.setBasis(t, q); - this.freeQuaternion(q); - }, - multiplyTransforms: function (t1, t2) { - const t = this.allocTransform(); - this.setIdentity(t); - const m1 = this.getBasisAsMatrix3(t1); - const m2 = this.getBasisAsMatrix3(t2); - const o1 = this.getOrigin(t1); - const o2 = this.getOrigin(t2); - const v1 = this.multiplyMatrix3ByVector3(m1, o2); - const v2 = this.addVector3(v1, o1); - this.setOrigin(t, v2); - const m3 = this.multiplyMatrices3(m1, m2); - this.setBasisFromMatrix3(t, m3); - this.freeVector3(v1); - this.freeVector3(v2); - return t; - }, - inverseTransform: function (t) { - const t2 = this.allocTransform(); - const m1 = this.getBasisAsMatrix3(t); - const o = this.getOrigin(t); - const m2 = this.transposeMatrix3(m1); - const v1 = this.negativeVector3(o); - const v2 = this.multiplyMatrix3ByVector3(m2, v1); - this.setOrigin(t2, v2); - this.setBasisFromMatrix3(t2, m2); - this.freeVector3(v1); - this.freeVector3(v2); - return t2; - }, - multiplyMatrices3: function (m1, m2) { - const m3 = []; - const v10 = this.rowOfMatrix3(m1, 0); - const v11 = this.rowOfMatrix3(m1, 1); - const v12 = this.rowOfMatrix3(m1, 2); - const v20 = this.columnOfMatrix3(m2, 0); - const v21 = this.columnOfMatrix3(m2, 1); - const v22 = this.columnOfMatrix3(m2, 2); - m3[0] = this.dotVectors3(v10, v20); - m3[1] = this.dotVectors3(v10, v21); - m3[2] = this.dotVectors3(v10, v22); - m3[3] = this.dotVectors3(v11, v20); - m3[4] = this.dotVectors3(v11, v21); - m3[5] = this.dotVectors3(v11, v22); - m3[6] = this.dotVectors3(v12, v20); - m3[7] = this.dotVectors3(v12, v21); - m3[8] = this.dotVectors3(v12, v22); - this.freeVector3(v10); - this.freeVector3(v11); - this.freeVector3(v12); - this.freeVector3(v20); - this.freeVector3(v21); - this.freeVector3(v22); - return m3; - }, - addVector3: function (v1, v2) { - const v = this.allocVector3(); - v.setValue(v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z()); - return v; - }, - dotVectors3: function (v1, v2) { - return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z(); - }, - rowOfMatrix3: function (m, i) { - const v = this.allocVector3(); - v.setValue(m[i * 3 + 0], m[i * 3 + 1], m[i * 3 + 2]); - return v; - }, - columnOfMatrix3: function (m, i) { - const v = this.allocVector3(); - v.setValue(m[i + 0], m[i + 3], m[i + 6]); - return v; - }, - negativeVector3: function (v) { - const v2 = this.allocVector3(); - v2.setValue(-v.x(), -v.y(), -v.z()); - return v2; - }, - multiplyMatrix3ByVector3: function (m, v) { - const v4 = this.allocVector3(); - const v0 = this.rowOfMatrix3(m, 0); - const v1 = this.rowOfMatrix3(m, 1); - const v2 = this.rowOfMatrix3(m, 2); - const x = this.dotVectors3(v0, v); - const y = this.dotVectors3(v1, v); - const z = this.dotVectors3(v2, v); - v4.setValue(x, y, z); - this.freeVector3(v0); - this.freeVector3(v1); - this.freeVector3(v2); - return v4; - }, - transposeMatrix3: function (m) { - const m2 = []; - m2[0] = m[0]; - m2[1] = m[3]; - m2[2] = m[6]; - m2[3] = m[1]; - m2[4] = m[4]; - m2[5] = m[7]; - m2[6] = m[2]; - m2[7] = m[5]; - m2[8] = m[8]; - return m2; - }, - quaternionToMatrix3: function (q) { - const m = []; - const x = q.x(); - const y = q.y(); - const z = q.z(); - const w = q.w(); - const xx = x * x; - const yy = y * y; - const zz = z * z; - const xy = x * y; - const yz = y * z; - const zx = z * x; - const xw = x * w; - const yw = y * w; - const zw = z * w; - m[0] = 1 - 2 * (yy + zz); - m[1] = 2 * (xy - zw); - m[2] = 2 * (zx + yw); - m[3] = 2 * (xy + zw); - m[4] = 1 - 2 * (zz + xx); - m[5] = 2 * (yz - xw); - m[6] = 2 * (zx - yw); - m[7] = 2 * (yz + xw); - m[8] = 1 - 2 * (xx + yy); - return m; - }, - matrix3ToQuaternion: function (m) { - const t = m[0] + m[4] + m[8]; - let s, x, y, z, w; - - if (t > 0) { - s = Math.sqrt(t + 1.0) * 2; - w = 0.25 * s; - x = (m[7] - m[5]) / s; - y = (m[2] - m[6]) / s; - z = (m[3] - m[1]) / s; - } else if (m[0] > m[4] && m[0] > m[8]) { - s = Math.sqrt(1.0 + m[0] - m[4] - m[8]) * 2; - w = (m[7] - m[5]) / s; - x = 0.25 * s; - y = (m[1] + m[3]) / s; - z = (m[2] + m[6]) / s; - } else if (m[4] > m[8]) { - s = Math.sqrt(1.0 + m[4] - m[0] - m[8]) * 2; - w = (m[2] - m[6]) / s; - x = (m[1] + m[3]) / s; - y = 0.25 * s; - z = (m[5] + m[7]) / s; - } else { - s = Math.sqrt(1.0 + m[8] - m[0] - m[4]) * 2; - w = (m[3] - m[1]) / s; - x = (m[2] + m[6]) / s; - y = (m[5] + m[7]) / s; - z = 0.25 * s; - } - - const q = this.allocQuaternion(); - q.setX(x); - q.setY(y); - q.setZ(z); - q.setW(w); - return q; - } - }; - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Ammo.btDiscreteDynamicsWorld} world - * @param {Object} params - * @param {ResourceManager} manager - */ - - function RigidBody(mesh, world, params, manager) { - this.mesh = mesh; - this.world = world; - this.params = params; - this.manager = manager; - this.body = null; - this.bone = null; - this.boneOffsetForm = null; - this.boneOffsetFormInverse = null; - - this._init(); - } - - RigidBody.prototype = { - constructor: MMDPhysics.RigidBody, - - /** - * Resets rigid body transform to the current bone's. - * - * @return {RigidBody} - */ - reset: function () { - this._setTransformFromBone(); - - return this; - }, - - /** - * Updates rigid body's transform from the current bone. - * - * @return {RidigBody} - */ - updateFromBone: function () { - if (this.params.boneIndex !== -1 && this.params.type === 0) { - this._setTransformFromBone(); - } - - return this; - }, - - /** - * Updates bone from the current ridid body's transform. - * - * @return {RidigBody} - */ - updateBone: function () { - if (this.params.type === 0 || this.params.boneIndex === -1) { - return this; - } - - this._updateBoneRotation(); - - if (this.params.type === 1) { - this._updateBonePosition(); - } - - this.bone.updateMatrixWorld(true); - - if (this.params.type === 2) { - this._setPositionFromBone(); - } - - return this; - }, - // private methods - _init: function () { - function generateShape(p) { - switch (p.shapeType) { - case 0: - return new Ammo.btSphereShape(p.width); - - case 1: - return new Ammo.btBoxShape(new Ammo.btVector3(p.width, p.height, p.depth)); - - case 2: - return new Ammo.btCapsuleShape(p.width, p.height); - - default: - throw `unknown shape type ${p.shapeType}`; - } - } - - const manager = this.manager; - const params = this.params; - const bones = this.mesh.skeleton.bones; - const bone = params.boneIndex === -1 ? new Bone() : bones[params.boneIndex]; - const shape = generateShape(params); - const weight = params.type === 0 ? 0 : params.weight; - const localInertia = manager.allocVector3(); - localInertia.setValue(0, 0, 0); - - if (weight !== 0) { - shape.calculateLocalInertia(weight, localInertia); - } - - const boneOffsetForm = manager.allocTransform(); - manager.setIdentity(boneOffsetForm); - manager.setOriginFromArray3(boneOffsetForm, params.position); - manager.setBasisFromArray3(boneOffsetForm, params.rotation); - const vector = manager.allocThreeVector3(); - const boneForm = manager.allocTransform(); - manager.setIdentity(boneForm); - manager.setOriginFromThreeVector3(boneForm, bone.getWorldPosition(vector)); - const form = manager.multiplyTransforms(boneForm, boneOffsetForm); - const state = new Ammo.btDefaultMotionState(form); - const info = new Ammo.btRigidBodyConstructionInfo(weight, state, shape, localInertia); - info.set_m_friction(params.friction); - info.set_m_restitution(params.restitution); - const body = new Ammo.btRigidBody(info); - - if (params.type === 0) { - body.setCollisionFlags(body.getCollisionFlags() | 2); - /* - * It'd be better to comment out this line though in general I should call this method - * because I'm not sure why but physics will be more like MMD's - * if I comment out. - */ - - body.setActivationState(4); - } - - body.setDamping(params.positionDamping, params.rotationDamping); - body.setSleepingThresholds(0, 0); - this.world.addRigidBody(body, 1 << params.groupIndex, params.groupTarget); - this.body = body; - this.bone = bone; - this.boneOffsetForm = boneOffsetForm; - this.boneOffsetFormInverse = manager.inverseTransform(boneOffsetForm); - manager.freeVector3(localInertia); - manager.freeTransform(form); - manager.freeTransform(boneForm); - manager.freeThreeVector3(vector); - }, - _getBoneTransform: function () { - const manager = this.manager; - const p = manager.allocThreeVector3(); - const q = manager.allocThreeQuaternion(); - const s = manager.allocThreeVector3(); - this.bone.matrixWorld.decompose(p, q, s); - const tr = manager.allocTransform(); - manager.setOriginFromThreeVector3(tr, p); - manager.setBasisFromThreeQuaternion(tr, q); - const form = manager.multiplyTransforms(tr, this.boneOffsetForm); - manager.freeTransform(tr); - manager.freeThreeVector3(s); - manager.freeThreeQuaternion(q); - manager.freeThreeVector3(p); - return form; - }, - _getWorldTransformForBone: function () { - const manager = this.manager; - const tr = this.body.getCenterOfMassTransform(); - return manager.multiplyTransforms(tr, this.boneOffsetFormInverse); - }, - _setTransformFromBone: function () { - const manager = this.manager; - - const form = this._getBoneTransform(); // TODO: check the most appropriate way to set - //this.body.setWorldTransform( form ); - - - this.body.setCenterOfMassTransform(form); - this.body.getMotionState().setWorldTransform(form); - manager.freeTransform(form); - }, - _setPositionFromBone: function () { - const manager = this.manager; - - const form = this._getBoneTransform(); - - const tr = manager.allocTransform(); - this.body.getMotionState().getWorldTransform(tr); - manager.copyOrigin(tr, form); // TODO: check the most appropriate way to set - //this.body.setWorldTransform( tr ); - - this.body.setCenterOfMassTransform(tr); - this.body.getMotionState().setWorldTransform(tr); - manager.freeTransform(tr); - manager.freeTransform(form); - }, - _updateBoneRotation: function () { - const manager = this.manager; - - const tr = this._getWorldTransformForBone(); - - const q = manager.getBasis(tr); - const thQ = manager.allocThreeQuaternion(); - const thQ2 = manager.allocThreeQuaternion(); - const thQ3 = manager.allocThreeQuaternion(); - thQ.set(q.x(), q.y(), q.z(), q.w()); - thQ2.setFromRotationMatrix(this.bone.matrixWorld); - thQ2.conjugate(); - thQ2.multiply(thQ); //this.bone.quaternion.multiply( thQ2 ); - - thQ3.setFromRotationMatrix(this.bone.matrix); // Renormalizing quaternion here because repeatedly transforming - // quaternion continuously accumulates floating point error and - // can end up being overflow. See #15335 - - this.bone.quaternion.copy(thQ2.multiply(thQ3).normalize()); - manager.freeThreeQuaternion(thQ); - manager.freeThreeQuaternion(thQ2); - manager.freeThreeQuaternion(thQ3); - manager.freeQuaternion(q); - manager.freeTransform(tr); - }, - _updateBonePosition: function () { - const manager = this.manager; - - const tr = this._getWorldTransformForBone(); - - const thV = manager.allocThreeVector3(); - const o = manager.getOrigin(tr); - thV.set(o.x(), o.y(), o.z()); - - if (this.bone.parent) { - this.bone.parent.worldToLocal(thV); - } - - this.bone.position.copy(thV); - manager.freeThreeVector3(thV); - manager.freeTransform(tr); - } - }; - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Ammo.btDiscreteDynamicsWorld} world - * @param {RigidBody} bodyA - * @param {RigidBody} bodyB - * @param {Object} params - * @param {ResourceManager} manager - */ - - function Constraint(mesh, world, bodyA, bodyB, params, manager) { - this.mesh = mesh; - this.world = world; - this.bodyA = bodyA; - this.bodyB = bodyB; - this.params = params; - this.manager = manager; - this.constraint = null; - - this._init(); - } - - Constraint.prototype = { - constructor: Constraint, - // private method - _init: function () { - const manager = this.manager; - const params = this.params; - const bodyA = this.bodyA; - const bodyB = this.bodyB; - const form = manager.allocTransform(); - manager.setIdentity(form); - manager.setOriginFromArray3(form, params.position); - manager.setBasisFromArray3(form, params.rotation); - const formA = manager.allocTransform(); - const formB = manager.allocTransform(); - bodyA.body.getMotionState().getWorldTransform(formA); - bodyB.body.getMotionState().getWorldTransform(formB); - const formInverseA = manager.inverseTransform(formA); - const formInverseB = manager.inverseTransform(formB); - const formA2 = manager.multiplyTransforms(formInverseA, form); - const formB2 = manager.multiplyTransforms(formInverseB, form); - const constraint = new Ammo.btGeneric6DofSpringConstraint(bodyA.body, bodyB.body, formA2, formB2, true); - const lll = manager.allocVector3(); - const lul = manager.allocVector3(); - const all = manager.allocVector3(); - const aul = manager.allocVector3(); - lll.setValue(params.translationLimitation1[0], params.translationLimitation1[1], params.translationLimitation1[2]); - lul.setValue(params.translationLimitation2[0], params.translationLimitation2[1], params.translationLimitation2[2]); - all.setValue(params.rotationLimitation1[0], params.rotationLimitation1[1], params.rotationLimitation1[2]); - aul.setValue(params.rotationLimitation2[0], params.rotationLimitation2[1], params.rotationLimitation2[2]); - constraint.setLinearLowerLimit(lll); - constraint.setLinearUpperLimit(lul); - constraint.setAngularLowerLimit(all); - constraint.setAngularUpperLimit(aul); - - for (let i = 0; i < 3; i++) { - if (params.springPosition[i] !== 0) { - constraint.enableSpring(i, true); - constraint.setStiffness(i, params.springPosition[i]); - } - } - - for (let i = 0; i < 3; i++) { - if (params.springRotation[i] !== 0) { - constraint.enableSpring(i + 3, true); - constraint.setStiffness(i + 3, params.springRotation[i]); - } - } - /* - * Currently(10/31/2016) official ammo.js doesn't support - * btGeneric6DofSpringConstraint.setParam method. - * You need custom ammo.js (add the method into idl) if you wanna use. - * By setting this parameter, physics will be more like MMD's - */ - - - if (constraint.setParam !== undefined) { - for (let i = 0; i < 6; i++) { - // this parameter is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js - constraint.setParam(2, 0.475, i); - } - } - - this.world.addConstraint(constraint, true); - this.constraint = constraint; - manager.freeTransform(form); - manager.freeTransform(formA); - manager.freeTransform(formB); - manager.freeTransform(formInverseA); - manager.freeTransform(formInverseB); - manager.freeTransform(formA2); - manager.freeTransform(formB2); - manager.freeVector3(lll); - manager.freeVector3(lul); - manager.freeVector3(all); - manager.freeVector3(aul); - } - }; - /** - * Visualize Rigid bodies - * - * @param {THREE.SkinnedMesh} mesh - * @param {Physics} physics - */ - - function MMDPhysicsHelper(mesh, physics) { - Object3D.call(this); - this.root = mesh; - this.physics = physics; - this.matrix.copy(mesh.matrixWorld); - this.matrixAutoUpdate = false; - this.materials = []; - this.materials.push(new MeshBasicMaterial({ - color: new Color(0xff8888), - wireframe: true, - depthTest: false, - depthWrite: false, - opacity: 0.25, - transparent: true - })); - this.materials.push(new MeshBasicMaterial({ - color: new Color(0x88ff88), - wireframe: true, - depthTest: false, - depthWrite: false, - opacity: 0.25, - transparent: true - })); - this.materials.push(new MeshBasicMaterial({ - color: new Color(0x8888ff), - wireframe: true, - depthTest: false, - depthWrite: false, - opacity: 0.25, - transparent: true - })); - - this._init(); - } - - MMDPhysicsHelper.prototype = Object.assign(Object.create(Object3D.prototype), { - constructor: MMDPhysicsHelper, - - /** - * Updates Rigid Bodies visualization. - */ - updateMatrixWorld: (() => { - const position = new Vector3(); - const quaternion = new Quaternion(); - const scale = new Vector3(); - const matrixWorldInv = new Matrix4(); - return function updateMatrixWorld(force) { - const mesh = this.root; - - if (this.visible) { - const bodies = this.physics.bodies; - matrixWorldInv.copy(mesh.matrixWorld).decompose(position, quaternion, scale).compose(position, quaternion, scale.set(1, 1, 1)).invert(); - - for (let i = 0, il = bodies.length; i < il; i++) { - const body = bodies[i].body; - const child = this.children[i]; - const tr = body.getCenterOfMassTransform(); - const origin = tr.getOrigin(); - const rotation = tr.getRotation(); - child.position.set(origin.x(), origin.y(), origin.z()).applyMatrix4(matrixWorldInv); - child.quaternion.setFromRotationMatrix(matrixWorldInv).multiply(quaternion.set(rotation.x(), rotation.y(), rotation.z(), rotation.w())); - } - } - - this.matrix.copy(mesh.matrixWorld).decompose(position, quaternion, scale).compose(position, quaternion, scale.set(1, 1, 1)); - Object3D.prototype.updateMatrixWorld.call(this, force); - }; - })(), - // private method - _init: function () { - const bodies = this.physics.bodies; - - function createGeometry(param) { - switch (param.shapeType) { - case 0: - return new SphereGeometry(param.width, 16, 8); - - case 1: - return new BoxGeometry(param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8); - - case 2: - return new createCapsuleGeometry(param.width, param.height, 16, 8); - - default: - return null; - } - } // copy from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mytest37.js?ver=20160815 - - - function createCapsuleGeometry(radius, cylinderHeight, segmentsRadius, segmentsHeight) { - const geometry = new CylinderGeometry(radius, radius, cylinderHeight, segmentsRadius, segmentsHeight, true); - const upperSphere = new Mesh(new SphereGeometry(radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, 0, Math.PI / 2)); - const lowerSphere = new Mesh(new SphereGeometry(radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2)); - upperSphere.position.set(0, cylinderHeight / 2, 0); - lowerSphere.position.set(0, -cylinderHeight / 2, 0); - upperSphere.updateMatrix(); - lowerSphere.updateMatrix(); - geometry.merge(upperSphere.geometry, upperSphere.matrix); - geometry.merge(lowerSphere.geometry, lowerSphere.matrix); - return geometry; - } - - for (let i = 0, il = bodies.length; i < il; i++) { - const param = bodies[i].params; - this.add(new Mesh(createGeometry(param), this.materials[param.type])); - } - } - }); - return MMDPhysics; -})(); - -/** - * MMDAnimationHelper handles animation of MMD assets loaded by MMDLoader - * with MMD special features as IK, Grant, and Physics. - * - * Dependencies - * - ammo.js https://github.com/kripken/ammo.js - * - MMDPhysics - * - CCDIKSolver - * - * TODO - * - more precise grant skinning support. - */ - -(() => { - /** - * @param {Object} params - (optional) - * @param {boolean} params.sync - Whether animation durations of added objects are synched. Default is true. - * @param {Number} params.afterglow - Default is 0.0. - * @param {boolean} params.resetPhysicsOnLoop - Default is true. - */ - function MMDAnimationHelper(params) { - params = params || {}; - this.meshes = []; - this.camera = null; - this.cameraTarget = new Object3D(); - this.cameraTarget.name = 'target'; - this.audio = null; - this.audioManager = null; - this.objects = new WeakMap(); - this.configuration = { - sync: params.sync !== undefined ? params.sync : true, - afterglow: params.afterglow !== undefined ? params.afterglow : 0.0, - resetPhysicsOnLoop: params.resetPhysicsOnLoop !== undefined ? params.resetPhysicsOnLoop : true - }; - this.enabled = { - animation: true, - ik: true, - grant: true, - physics: true, - cameraAnimation: true - }; - - this.onBeforePhysics = () => - /* mesh */ - {}; // experimental - - - this.sharedPhysics = false; - this.masterPhysics = null; - } - - MMDAnimationHelper.prototype = { - constructor: MMDAnimationHelper, - - /** - * Adds an Three.js Object to helper and setups animation. - * The anmation durations of added objects are synched - * if this.configuration.sync is true. - * - * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object - * @param {Object} params - (optional) - * @param {THREE.AnimationClip|Array} params.animation - Only for THREE.SkinnedMesh and THREE.Camera. Default is undefined. - * @param {boolean} params.physics - Only for THREE.SkinnedMesh. Default is true. - * @param {Integer} params.warmup - Only for THREE.SkinnedMesh and physics is true. Default is 60. - * @param {Number} params.unitStep - Only for THREE.SkinnedMesh and physics is true. Default is 1 / 65. - * @param {Integer} params.maxStepNum - Only for THREE.SkinnedMesh and physics is true. Default is 3. - * @param {Vector3} params.gravity - Only for THREE.SkinnedMesh and physics is true. Default ( 0, - 9.8 * 10, 0 ). - * @param {Number} params.delayTime - Only for THREE.Audio. Default is 0.0. - * @return {MMDAnimationHelper} - */ - add: function (object, params) { - params = params || {}; - - if (object.isSkinnedMesh) { - this._addMesh(object, params); - } else if (object.isCamera) { - this._setupCamera(object, params); - } else if (object.type === 'Audio') { - this._setupAudio(object, params); - } else { - throw new Error('THREE.MMDAnimationHelper.add: ' + 'accepts only ' + 'THREE.SkinnedMesh or ' + 'THREE.Camera or ' + 'THREE.Audio instance.'); - } - - if (this.configuration.sync) this._syncDuration(); - return this; - }, - - /** - * Removes an Three.js Object from helper. - * - * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object - * @return {MMDAnimationHelper} - */ - remove: function (object) { - if (object.isSkinnedMesh) { - this._removeMesh(object); - } else if (object.isCamera) { - this._clearCamera(object); - } else if (object.type === 'Audio') { - this._clearAudio(object); - } else { - throw new Error('THREE.MMDAnimationHelper.remove: ' + 'accepts only ' + 'THREE.SkinnedMesh or ' + 'THREE.Camera or ' + 'THREE.Audio instance.'); - } - - if (this.configuration.sync) this._syncDuration(); - return this; - }, - - /** - * Updates the animation. - * - * @param {Number} delta - * @return {MMDAnimationHelper} - */ - update: function (delta) { - if (this.audioManager !== null) this.audioManager.control(delta); - - for (let i = 0; i < this.meshes.length; i++) { - this._animateMesh(this.meshes[i], delta); - } - - if (this.sharedPhysics) this._updateSharedPhysics(delta); - if (this.camera !== null) this._animateCamera(this.camera, delta); - return this; - }, - - /** - * Changes the pose of SkinnedMesh as VPD specifies. - * - * @param {THREE.SkinnedMesh} mesh - * @param {Object} vpd - VPD content parsed MMDParser - * @param {Object} params - (optional) - * @param {boolean} params.resetPose - Default is true. - * @param {boolean} params.ik - Default is true. - * @param {boolean} params.grant - Default is true. - * @return {MMDAnimationHelper} - */ - pose: function (mesh, vpd, params) { - params = params || {}; - if (params.resetPose !== false) mesh.pose(); - const bones = mesh.skeleton.bones; - const boneParams = vpd.bones; - const boneNameDictionary = {}; - - for (let i = 0, il = bones.length; i < il; i++) { - boneNameDictionary[bones[i].name] = i; - } - - const vector = new Vector3(); - const quaternion = new Quaternion(); - - for (let i = 0, il = boneParams.length; i < il; i++) { - const boneParam = boneParams[i]; - const boneIndex = boneNameDictionary[boneParam.name]; - if (boneIndex === undefined) continue; - const bone = bones[boneIndex]; - bone.position.add(vector.fromArray(boneParam.translation)); - bone.quaternion.multiply(quaternion.fromArray(boneParam.quaternion)); - } - - mesh.updateMatrixWorld(true); - - if (params.ik !== false) { - this._createCCDIKSolver(mesh).update(params.saveOriginalBonesBeforeIK); // this param is experimental - - } - - if (params.grant !== false) { - this.createGrantSolver(mesh).update(); - } - - return this; - }, - - /** - * Enabes/Disables an animation feature. - * - * @param {string} key - * @param {boolean} enabled - * @return {MMDAnimationHelper} - */ - enable: function (key, enabled) { - if (this.enabled[key] === undefined) { - throw new Error(`THREE.MMDAnimationHelper.enable: unknown key ${key}`); - } - - this.enabled[key] = enabled; - - if (key === 'physics') { - for (let i = 0, il = this.meshes.length; i < il; i++) { - this._optimizeIK(this.meshes[i], enabled); - } - } - - return this; - }, - - /** - * Creates an GrantSolver instance. - * - * @param {THREE.SkinnedMesh} mesh - * @return {GrantSolver} - */ - createGrantSolver: function (mesh) { - return new GrantSolver(mesh, mesh.geometry.userData.MMD.grants); - }, - // private methods - _addMesh: function (mesh, params) { - if (this.meshes.indexOf(mesh) >= 0) { - throw new Error(`THREE.MMDAnimationHelper._addMesh: SkinnedMesh '${mesh.name}' has already been added.`); - } - - this.meshes.push(mesh); - this.objects.set(mesh, { - looped: false - }); - - this._setupMeshAnimation(mesh, params.animation); - - if (params.physics !== false) { - this._setupMeshPhysics(mesh, params); - } - - return this; - }, - _setupCamera: function (camera, params) { - if (this.camera === camera) { - throw new Error(`THREE.MMDAnimationHelper._setupCamera: Camera '${camera.name}' has already been set.`); - } - - if (this.camera) this.clearCamera(this.camera); - this.camera = camera; - camera.add(this.cameraTarget); - this.objects.set(camera, {}); - - if (params.animation !== undefined) { - this._setupCameraAnimation(camera, params.animation); - } - - return this; - }, - _setupAudio: function (audio, params) { - if (this.audio === audio) { - throw new Error(`THREE.MMDAnimationHelper._setupAudio: Audio '${audio.name}' has already been set.`); - } - - if (this.audio) this.clearAudio(this.audio); - this.audio = audio; - this.audioManager = new AudioManager(audio, params); - this.objects.set(this.audioManager, { - duration: this.audioManager.duration - }); - return this; - }, - _removeMesh: function (mesh) { - let found = false; - let writeIndex = 0; - - for (let i = 0, il = this.meshes.length; i < il; i++) { - if (this.meshes[i] === mesh) { - this.objects.delete(mesh); - found = true; - continue; - } - - this.meshes[writeIndex++] = this.meshes[i]; - } - - if (!found) { - throw new Error(`THREE.MMDAnimationHelper._removeMesh: SkinnedMesh '${mesh.name}' has not been added yet.`); - } - - this.meshes.length = writeIndex; - return this; - }, - _clearCamera: function (camera) { - if (camera !== this.camera) { - throw new Error(`THREE.MMDAnimationHelper._clearCamera: Camera '${camera.name}' has not been set yet.`); - } - - this.camera.remove(this.cameraTarget); - this.objects.delete(this.camera); - this.camera = null; - return this; - }, - _clearAudio: function (audio) { - if (audio !== this.audio) { - throw new Error(`THREE.MMDAnimationHelper._clearAudio: Audio '${audio.name}' has not been set yet.`); - } - - this.objects.delete(this.audioManager); - this.audio = null; - this.audioManager = null; - return this; - }, - _setupMeshAnimation: function (mesh, animation) { - const objects = this.objects.get(mesh); - - if (animation !== undefined) { - const animations = Array.isArray(animation) ? animation : [animation]; - objects.mixer = new AnimationMixer(mesh); - - for (let i = 0, il = animations.length; i < il; i++) { - objects.mixer.clipAction(animations[i]).play(); - } // TODO: find a workaround not to access ._clip looking like a private property - - - objects.mixer.addEventListener('loop', event => { - const tracks = event.action._clip.tracks; - if (tracks.length > 0 && tracks[0].name.slice(0, 6) !== '.bones') return; - objects.looped = true; - }); - } - - objects.ikSolver = this._createCCDIKSolver(mesh); - objects.grantSolver = this.createGrantSolver(mesh); - return this; - }, - _setupCameraAnimation: function (camera, animation) { - const animations = Array.isArray(animation) ? animation : [animation]; - const objects = this.objects.get(camera); - objects.mixer = new AnimationMixer(camera); - - for (let i = 0, il = animations.length; i < il; i++) { - objects.mixer.clipAction(animations[i]).play(); - } - }, - _setupMeshPhysics: function (mesh, params) { - const objects = this.objects.get(mesh); // shared physics is experimental - - if (params.world === undefined && this.sharedPhysics) { - const masterPhysics = this._getMasterPhysics(); - - if (masterPhysics !== null) world = masterPhysics.world; // eslint-disable-line no-undef - } - - objects.physics = this._createMMDPhysics(mesh, params); - - if (objects.mixer && params.animationWarmup !== false) { - this._animateMesh(mesh, 0); - - objects.physics.reset(); - } - - objects.physics.warmup(params.warmup !== undefined ? params.warmup : 60); - - this._optimizeIK(mesh, true); - }, - _animateMesh: function (mesh, delta) { - const objects = this.objects.get(mesh); - const mixer = objects.mixer; - const ikSolver = objects.ikSolver; - const grantSolver = objects.grantSolver; - const physics = objects.physics; - const looped = objects.looped; // alternate solution to save/restore bones but less performant? - //mesh.pose(); - //this._updatePropertyMixersBuffer( mesh ); - - if (mixer && this.enabled.animation) { - this._restoreBones(mesh); - - mixer.update(delta); - - this._saveBones(mesh); - - if (ikSolver && this.enabled.ik) { - mesh.updateMatrixWorld(true); - ikSolver.update(); - } - - if (grantSolver && this.enabled.grant) { - grantSolver.update(); - } - } - - if (looped === true && this.enabled.physics) { - if (physics && this.configuration.resetPhysicsOnLoop) physics.reset(); - objects.looped = false; - } - - if (physics && this.enabled.physics && !this.sharedPhysics) { - this.onBeforePhysics(mesh); - physics.update(delta); - } - }, - _animateCamera: function (camera, delta) { - const mixer = this.objects.get(camera).mixer; - - if (mixer && this.enabled.cameraAnimation) { - mixer.update(delta); - camera.updateProjectionMatrix(); - camera.up.set(0, 1, 0); - camera.up.applyQuaternion(camera.quaternion); - camera.lookAt(this.cameraTarget.position); - } - }, - _optimizeIK: function (mesh, physicsEnabled) { - const iks = mesh.geometry.userData.MMD.iks; - const bones = mesh.geometry.userData.MMD.bones; - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - const links = ik.links; - - for (let j = 0, jl = links.length; j < jl; j++) { - const link = links[j]; - - if (physicsEnabled === true) { - // disable IK of the bone the corresponding rigidBody type of which is 1 or 2 - // because its rotation will be overriden by physics - link.enabled = bones[link.index].rigidBodyType > 0 ? false : true; - } else { - link.enabled = true; - } - } - } - }, - _createCCDIKSolver: function (mesh) { - if (CCDIKSolver === undefined) { - throw new Error('THREE.MMDAnimationHelper: Import CCDIKSolver.'); - } - - return new CCDIKSolver(mesh, mesh.geometry.userData.MMD.iks); - }, - _createMMDPhysics: function (mesh, params) { - if (MMDPhysics === undefined) { - throw new Error('THREE.MMDPhysics: Import MMDPhysics.'); - } - - return new MMDPhysics(mesh, mesh.geometry.userData.MMD.rigidBodies, mesh.geometry.userData.MMD.constraints, params); - }, - - /* - * Detects the longest duration and then sets it to them to sync. - * TODO: Not to access private properties ( ._actions and ._clip ) - */ - _syncDuration: function () { - let max = 0.0; - const objects = this.objects; - const meshes = this.meshes; - const camera = this.camera; - const audioManager = this.audioManager; // get the longest duration - - for (let i = 0, il = meshes.length; i < il; i++) { - var mixer = this.objects.get(meshes[i]).mixer; - if (mixer === undefined) continue; - - for (let j = 0; j < mixer._actions.length; j++) { - var clip = mixer._actions[j]._clip; - - if (!objects.has(clip)) { - objects.set(clip, { - duration: clip.duration - }); - } - - max = Math.max(max, objects.get(clip).duration); - } - } - - if (camera !== null) { - var mixer = this.objects.get(camera).mixer; - - if (mixer !== undefined) { - for (let i = 0, il = mixer._actions.length; i < il; i++) { - var clip = mixer._actions[i]._clip; - - if (!objects.has(clip)) { - objects.set(clip, { - duration: clip.duration - }); - } - - max = Math.max(max, objects.get(clip).duration); - } - } - } - - if (audioManager !== null) { - max = Math.max(max, objects.get(audioManager).duration); - } - - max += this.configuration.afterglow; // update the duration - - for (let i = 0, il = this.meshes.length; i < il; i++) { - var mixer = this.objects.get(this.meshes[i]).mixer; - if (mixer === undefined) continue; - - for (let j = 0, jl = mixer._actions.length; j < jl; j++) { - mixer._actions[j]._clip.duration = max; - } - } - - if (camera !== null) { - var mixer = this.objects.get(camera).mixer; - - if (mixer !== undefined) { - for (let i = 0, il = mixer._actions.length; i < il; i++) { - mixer._actions[i]._clip.duration = max; - } - } - } - - if (audioManager !== null) { - audioManager.duration = max; - } - }, - // workaround - _updatePropertyMixersBuffer: function (mesh) { - const mixer = this.objects.get(mesh).mixer; - const propertyMixers = mixer._bindings; - const accuIndex = mixer._accuIndex; - - for (let i = 0, il = propertyMixers.length; i < il; i++) { - const propertyMixer = propertyMixers[i]; - const buffer = propertyMixer.buffer; - const stride = propertyMixer.valueSize; - const offset = (accuIndex + 1) * stride; - propertyMixer.binding.getValue(buffer, offset); - } - }, - - /* - * Avoiding these two issues by restore/save bones before/after mixer animation. - * - * 1. PropertyMixer used by AnimationMixer holds cache value in .buffer. - * Calculating IK, Grant, and Physics after mixer animation can break - * the cache coherency. - * - * 2. Applying Grant two or more times without reset the posing breaks model. - */ - _saveBones: function (mesh) { - const objects = this.objects.get(mesh); - const bones = mesh.skeleton.bones; - let backupBones = objects.backupBones; - - if (backupBones === undefined) { - backupBones = new Float32Array(bones.length * 7); - objects.backupBones = backupBones; - } - - for (let i = 0, il = bones.length; i < il; i++) { - const bone = bones[i]; - bone.position.toArray(backupBones, i * 7); - bone.quaternion.toArray(backupBones, i * 7 + 3); - } - }, - _restoreBones: function (mesh) { - const objects = this.objects.get(mesh); - const backupBones = objects.backupBones; - if (backupBones === undefined) return; - const bones = mesh.skeleton.bones; - - for (let i = 0, il = bones.length; i < il; i++) { - const bone = bones[i]; - bone.position.fromArray(backupBones, i * 7); - bone.quaternion.fromArray(backupBones, i * 7 + 3); - } - }, - // experimental - _getMasterPhysics: function () { - if (this.masterPhysics !== null) return this.masterPhysics; - - for (let i = 0, il = this.meshes.length; i < il; i++) { - const physics = this.meshes[i].physics; - - if (physics !== undefined && physics !== null) { - this.masterPhysics = physics; - return this.masterPhysics; - } - } - - return null; - }, - _updateSharedPhysics: function (delta) { - if (this.meshes.length === 0 || !this.enabled.physics || !this.sharedPhysics) return; - - const physics = this._getMasterPhysics(); - - if (physics === null) return; - - for (let i = 0, il = this.meshes.length; i < il; i++) { - var p = this.meshes[i].physics; - - if (p !== null && p !== undefined) { - p.updateRigidBodies(); - } - } - - physics.stepSimulation(delta); - - for (let i = 0, il = this.meshes.length; i < il; i++) { - var p = this.meshes[i].physics; - - if (p !== null && p !== undefined) { - p.updateBones(); - } - } - } - }; // - - /** - * @param {THREE.Audio} audio - * @param {Object} params - (optional) - * @param {Nuumber} params.delayTime - */ - - function AudioManager(audio, params) { - params = params || {}; - this.audio = audio; - this.elapsedTime = 0.0; - this.currentTime = 0.0; - this.delayTime = params.delayTime !== undefined ? params.delayTime : 0.0; - this.audioDuration = this.audio.buffer.duration; - this.duration = this.audioDuration + this.delayTime; - } - - AudioManager.prototype = { - constructor: AudioManager, - - /** - * @param {Number} delta - * @return {AudioManager} - */ - control: function (delta) { - this.elapsed += delta; - this.currentTime += delta; - if (this._shouldStopAudio()) this.audio.stop(); - if (this._shouldStartAudio()) this.audio.play(); - return this; - }, - // private methods - _shouldStartAudio: function () { - if (this.audio.isPlaying) return false; - - while (this.currentTime >= this.duration) { - this.currentTime -= this.duration; - } - - if (this.currentTime < this.delayTime) return false; // 'duration' can be bigger than 'audioDuration + delayTime' because of sync configuration - - if (this.currentTime - this.delayTime > this.audioDuration) return false; - return true; - }, - _shouldStopAudio: function () { - return this.audio.isPlaying && this.currentTime >= this.duration; - } - }; - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Array} grants - */ - - function GrantSolver(mesh, grants) { - this.mesh = mesh; - this.grants = grants || []; - } - - GrantSolver.prototype = { - constructor: GrantSolver, - - /** - * @return {GrantSolver} - */ - update: (() => { - const quaternion = new Quaternion(); - return function () { - const bones = this.mesh.skeleton.bones; - const grants = this.grants; - - for (let i = 0, il = grants.length; i < il; i++) { - const grant = grants[i]; - const bone = bones[grant.index]; - const parentBone = bones[grant.parentIndex]; - - if (grant.isLocal) { - // TODO: implement - if (grant.affectPosition) ; // TODO: implement - - - if (grant.affectRotation) ; - } else { - // TODO: implement - if (grant.affectPosition) ; - - if (grant.affectRotation) { - quaternion.set(0, 0, 0, 1); - quaternion.slerp(parentBone.quaternion, grant.ratio); - bone.quaternion.multiply(quaternion); - } - } - } - - return this; - }; - })() - }; - return MMDAnimationHelper; -})(); - -class Reflector extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - this.type = 'Reflector'; - const scope = this; - const color = options.color !== undefined ? new Color(options.color) : new Color(0x7f7f7f); - const textureWidth = options.textureWidth || 512; - const textureHeight = options.textureHeight || 512; - const clipBias = options.clipBias || 0; - const shader = options.shader || Reflector.ReflectorShader; // - - const reflectorPlane = new Plane(); - const normal = new Vector3(); - const reflectorWorldPosition = new Vector3(); - const cameraWorldPosition = new Vector3(); - const rotationMatrix = new Matrix4(); - const lookAtPosition = new Vector3(0, 0, -1); - const clipPlane = new Vector4(); - const view = new Vector3(); - const target = new Vector3(); - const q = new Vector4(); - const textureMatrix = new Matrix4(); - const virtualCamera = new PerspectiveCamera(); - const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight); - const material = new ShaderMaterial({ - uniforms: UniformsUtils.clone(shader.uniforms), - fragmentShader: shader.fragmentShader, - vertexShader: shader.vertexShader - }); - material.uniforms['tDiffuse'].value = renderTarget.texture; - material.uniforms['color'].value = color; - material.uniforms['textureMatrix'].value = textureMatrix; - this.material = material; - - this.onBeforeRender = function (renderer, scene, camera) { - reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); - cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); - rotationMatrix.extractRotation(scope.matrixWorld); - normal.set(0, 0, 1); - normal.applyMatrix4(rotationMatrix); - view.subVectors(reflectorWorldPosition, cameraWorldPosition); // Avoid rendering when reflector is facing away - - if (view.dot(normal) > 0) return; - view.reflect(normal).negate(); - view.add(reflectorWorldPosition); - rotationMatrix.extractRotation(camera.matrixWorld); - lookAtPosition.set(0, 0, -1); - lookAtPosition.applyMatrix4(rotationMatrix); - lookAtPosition.add(cameraWorldPosition); - target.subVectors(reflectorWorldPosition, lookAtPosition); - target.reflect(normal).negate(); - target.add(reflectorWorldPosition); - virtualCamera.position.copy(view); - virtualCamera.up.set(0, 1, 0); - virtualCamera.up.applyMatrix4(rotationMatrix); - virtualCamera.up.reflect(normal); - virtualCamera.lookAt(target); - virtualCamera.far = camera.far; // Used in WebGLBackground - - virtualCamera.updateMatrixWorld(); - virtualCamera.projectionMatrix.copy(camera.projectionMatrix); // Update the texture matrix - - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); - textureMatrix.multiply(virtualCamera.projectionMatrix); - textureMatrix.multiply(virtualCamera.matrixWorldInverse); - textureMatrix.multiply(scope.matrixWorld); // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html - // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf - - reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition); - reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse); - clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant); - const projectionMatrix = virtualCamera.projectionMatrix; - q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; - q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; - q.z = -1.0; - q.w = (1.0 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; // Calculate the scaled plane vector - - clipPlane.multiplyScalar(2.0 / clipPlane.dot(q)); // Replacing the third row of the projection matrix - - projectionMatrix.elements[2] = clipPlane.x; - projectionMatrix.elements[6] = clipPlane.y; - projectionMatrix.elements[10] = clipPlane.z + 1.0 - clipBias; - projectionMatrix.elements[14] = clipPlane.w; // Render - - renderTarget.texture.encoding = renderer.outputEncoding; - scope.visible = false; - const currentRenderTarget = renderer.getRenderTarget(); - const currentXrEnabled = renderer.xr.enabled; - const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; - renderer.xr.enabled = false; // Avoid camera modification - - renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows - - renderer.setRenderTarget(renderTarget); - renderer.state.buffers.depth.setMask(true); // make sure the depth buffer is writable so it can be properly cleared, see #18897 - - if (renderer.autoClear === false) renderer.clear(); - renderer.render(scene, virtualCamera); - renderer.xr.enabled = currentXrEnabled; - renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; - renderer.setRenderTarget(currentRenderTarget); // Restore viewport - - const viewport = camera.viewport; - - if (viewport !== undefined) { - renderer.state.viewport(viewport); - } - - scope.visible = true; - }; - - this.getRenderTarget = function () { - return renderTarget; - }; - - this.dispose = function () { - renderTarget.dispose(); - scope.material.dispose(); - }; - } - -} - -Reflector.prototype.isReflector = true; -Reflector.ReflectorShader = { - uniforms: { - color: { - value: null - }, - tDiffuse: { - value: null - }, - textureMatrix: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - uniform mat4 textureMatrix; - varying vec4 vUv; - - #include - #include - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - #include - - }`, - fragmentShader: - /* glsl */ - ` - uniform vec3 color; - uniform sampler2D tDiffuse; - varying vec4 vUv; - - #include - - float blendOverlay( float base, float blend ) { - - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - - } - - vec3 blendOverlay( vec3 base, vec3 blend ) { - - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - - } - - void main() { - - #include - - vec4 base = texture2DProj( tDiffuse, vUv ); - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - - }` -}; - -class Refractor extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - this.type = 'Refractor'; - const scope = this; - const color = options.color !== undefined ? new Color(options.color) : new Color(0x7f7f7f); - const textureWidth = options.textureWidth || 512; - const textureHeight = options.textureHeight || 512; - const clipBias = options.clipBias || 0; - const shader = options.shader || Refractor.RefractorShader; // - - const virtualCamera = new PerspectiveCamera(); - virtualCamera.matrixAutoUpdate = false; - virtualCamera.userData.refractor = true; // - - const refractorPlane = new Plane(); - const textureMatrix = new Matrix4(); // render target - - const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight); // material - - this.material = new ShaderMaterial({ - uniforms: UniformsUtils.clone(shader.uniforms), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - transparent: true // ensures, refractors are drawn from farthest to closest - - }); - this.material.uniforms['color'].value = color; - this.material.uniforms['tDiffuse'].value = renderTarget.texture; - this.material.uniforms['textureMatrix'].value = textureMatrix; // functions - - const visible = function () { - const refractorWorldPosition = new Vector3(); - const cameraWorldPosition = new Vector3(); - const rotationMatrix = new Matrix4(); - const view = new Vector3(); - const normal = new Vector3(); - return function visible(camera) { - refractorWorldPosition.setFromMatrixPosition(scope.matrixWorld); - cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); - view.subVectors(refractorWorldPosition, cameraWorldPosition); - rotationMatrix.extractRotation(scope.matrixWorld); - normal.set(0, 0, 1); - normal.applyMatrix4(rotationMatrix); - return view.dot(normal) < 0; - }; - }(); - - const updateRefractorPlane = function () { - const normal = new Vector3(); - const position = new Vector3(); - const quaternion = new Quaternion(); - const scale = new Vector3(); - return function updateRefractorPlane() { - scope.matrixWorld.decompose(position, quaternion, scale); - normal.set(0, 0, 1).applyQuaternion(quaternion).normalize(); // flip the normal because we want to cull everything above the plane - - normal.negate(); - refractorPlane.setFromNormalAndCoplanarPoint(normal, position); - }; - }(); - - const updateVirtualCamera = function () { - const clipPlane = new Plane(); - const clipVector = new Vector4(); - const q = new Vector4(); - return function updateVirtualCamera(camera) { - virtualCamera.matrixWorld.copy(camera.matrixWorld); - virtualCamera.matrixWorldInverse.copy(virtualCamera.matrixWorld).invert(); - virtualCamera.projectionMatrix.copy(camera.projectionMatrix); - virtualCamera.far = camera.far; // used in WebGLBackground - // The following code creates an oblique view frustum for clipping. - // see: Lengyel, Eric. “Oblique View Frustum Depth Projection and Clipping”. - // Journal of Game Development, Vol. 1, No. 2 (2005), Charles River Media, pp. 5–16 - - clipPlane.copy(refractorPlane); - clipPlane.applyMatrix4(virtualCamera.matrixWorldInverse); - clipVector.set(clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant); // calculate the clip-space corner point opposite the clipping plane and - // transform it into camera space by multiplying it by the inverse of the projection matrix - - const projectionMatrix = virtualCamera.projectionMatrix; - q.x = (Math.sign(clipVector.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; - q.y = (Math.sign(clipVector.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; - q.z = -1.0; - q.w = (1.0 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; // calculate the scaled plane vector - - clipVector.multiplyScalar(2.0 / clipVector.dot(q)); // replacing the third row of the projection matrix - - projectionMatrix.elements[2] = clipVector.x; - projectionMatrix.elements[6] = clipVector.y; - projectionMatrix.elements[10] = clipVector.z + 1.0 - clipBias; - projectionMatrix.elements[14] = clipVector.w; - }; - }(); // This will update the texture matrix that is used for projective texture mapping in the shader. - // see: http://developer.download.nvidia.com/assets/gamedev/docs/projective_texture_mapping.pdf - - - function updateTextureMatrix(camera) { - // this matrix does range mapping to [ 0, 1 ] - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); // we use "Object Linear Texgen", so we need to multiply the texture matrix T - // (matrix above) with the projection and view matrix of the virtual camera - // and the model matrix of the refractor - - textureMatrix.multiply(camera.projectionMatrix); - textureMatrix.multiply(camera.matrixWorldInverse); - textureMatrix.multiply(scope.matrixWorld); - } // - - - function render(renderer, scene, camera) { - scope.visible = false; - const currentRenderTarget = renderer.getRenderTarget(); - const currentXrEnabled = renderer.xr.enabled; - const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; - renderer.xr.enabled = false; // avoid camera modification - - renderer.shadowMap.autoUpdate = false; // avoid re-computing shadows - - renderer.setRenderTarget(renderTarget); - if (renderer.autoClear === false) renderer.clear(); - renderer.render(scene, virtualCamera); - renderer.xr.enabled = currentXrEnabled; - renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; - renderer.setRenderTarget(currentRenderTarget); // restore viewport - - const viewport = camera.viewport; - - if (viewport !== undefined) { - renderer.state.viewport(viewport); - } - - scope.visible = true; - } // - - - this.onBeforeRender = function (renderer, scene, camera) { - // Render - renderTarget.texture.encoding = renderer.outputEncoding; // ensure refractors are rendered only once per frame - - if (camera.userData.refractor === true) return; // avoid rendering when the refractor is viewed from behind - - if (!visible(camera) === true) return; // update - - updateRefractorPlane(); - updateTextureMatrix(camera); - updateVirtualCamera(camera); - render(renderer, scene, camera); - }; - - this.getRenderTarget = function () { - return renderTarget; - }; - - this.dispose = function () { - renderTarget.dispose(); - scope.material.dispose(); - }; - } - -} - -Refractor.prototype.isRefractor = true; -Refractor.RefractorShader = { - uniforms: { - color: { - value: null - }, - tDiffuse: { - value: null - }, - textureMatrix: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - - uniform mat4 textureMatrix; - - varying vec4 vUv; - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - - uniform vec3 color; - uniform sampler2D tDiffuse; - - varying vec4 vUv; - - float blendOverlay( float base, float blend ) { - - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - - } - - vec3 blendOverlay( vec3 base, vec3 blend ) { - - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - - } - - void main() { - - vec4 base = texture2DProj( tDiffuse, vUv ); - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - - }` -}; - -/** - * A shadow Mesh that follows a shadow-casting Mesh in the scene, but is confined to a single plane. - */ - -const _shadowMatrix = new Matrix4(); - -class ShadowMesh extends Mesh { - constructor(mesh) { - const shadowMaterial = new MeshBasicMaterial({ - color: 0x000000, - transparent: true, - opacity: 0.6, - depthWrite: false - }); - super(mesh.geometry, shadowMaterial); - this.meshMatrix = mesh.matrixWorld; - this.frustumCulled = false; - this.matrixAutoUpdate = false; - } - - update(plane, lightPosition4D) { - // based on https://www.opengl.org/archives/resources/features/StencilTalk/tsld021.htm - const dot = plane.normal.x * lightPosition4D.x + plane.normal.y * lightPosition4D.y + plane.normal.z * lightPosition4D.z + -plane.constant * lightPosition4D.w; - const sme = _shadowMatrix.elements; - sme[0] = dot - lightPosition4D.x * plane.normal.x; - sme[4] = -lightPosition4D.x * plane.normal.y; - sme[8] = -lightPosition4D.x * plane.normal.z; - sme[12] = -lightPosition4D.x * -plane.constant; - sme[1] = -lightPosition4D.y * plane.normal.x; - sme[5] = dot - lightPosition4D.y * plane.normal.y; - sme[9] = -lightPosition4D.y * plane.normal.z; - sme[13] = -lightPosition4D.y * -plane.constant; - sme[2] = -lightPosition4D.z * plane.normal.x; - sme[6] = -lightPosition4D.z * plane.normal.y; - sme[10] = dot - lightPosition4D.z * plane.normal.z; - sme[14] = -lightPosition4D.z * -plane.constant; - sme[3] = -lightPosition4D.w * plane.normal.x; - sme[7] = -lightPosition4D.w * plane.normal.y; - sme[11] = -lightPosition4D.w * plane.normal.z; - sme[15] = dot - lightPosition4D.w * -plane.constant; - this.matrix.multiplyMatrices(_shadowMatrix, this.meshMatrix); - } - -} - -ShadowMesh.prototype.isShadowMesh = true; - -class Lensflare extends Mesh { - constructor() { - super(Lensflare.Geometry, new MeshBasicMaterial({ - opacity: 0, - transparent: true - })); - this.type = 'Lensflare'; - this.frustumCulled = false; - this.renderOrder = Infinity; // - - const positionScreen = new Vector3(); - const positionView = new Vector3(); // textures - - const tempMap = new DataTexture(new Uint8Array(16 * 16 * 3), 16, 16, RGBAFormat); - tempMap.minFilter = NearestFilter; - tempMap.magFilter = NearestFilter; - tempMap.wrapS = ClampToEdgeWrapping; - tempMap.wrapT = ClampToEdgeWrapping; - const occlusionMap = new DataTexture(new Uint8Array(16 * 16 * 3), 16, 16, RGBAFormat); - occlusionMap.minFilter = NearestFilter; - occlusionMap.magFilter = NearestFilter; - occlusionMap.wrapS = ClampToEdgeWrapping; - occlusionMap.wrapT = ClampToEdgeWrapping; // material - - const geometry = Lensflare.Geometry; - const material1a = new RawShaderMaterial({ - uniforms: { - scale: { - value: null - }, - screenPosition: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - attribute vec3 position; - - void main() { - - gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - - precision highp float; - - void main() { - - gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 ); - - }`, - depthTest: true, - depthWrite: false, - transparent: false - }); - const material1b = new RawShaderMaterial({ - uniforms: { - map: { - value: tempMap - }, - scale: { - value: null - }, - screenPosition: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - attribute vec3 position; - attribute vec2 uv; - - varying vec2 vUV; - - void main() { - - vUV = uv; - - gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - - precision highp float; - - uniform sampler2D map; - - varying vec2 vUV; - - void main() { - - gl_FragColor = texture2D( map, vUV ); - - }`, - depthTest: false, - depthWrite: false, - transparent: false - }); // the following object is used for occlusionMap generation - - const mesh1 = new Mesh(geometry, material1a); // - - const elements = []; - const shader = LensflareElement.Shader; - const material2 = new RawShaderMaterial({ - uniforms: { - map: { - value: null - }, - occlusionMap: { - value: occlusionMap - }, - color: { - value: new Color(0xffffff) - }, - scale: { - value: new Vector2() - }, - screenPosition: { - value: new Vector3() - } - }, - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - blending: AdditiveBlending, - transparent: true, - depthWrite: false - }); - const mesh2 = new Mesh(geometry, material2); - - this.addElement = function (element) { - elements.push(element); - }; // - - - const scale = new Vector2(); - const screenPositionPixels = new Vector2(); - const validArea = new Box2(); - const viewport = new Vector4(); - - this.onBeforeRender = function (renderer, scene, camera) { - renderer.getCurrentViewport(viewport); - const invAspect = viewport.w / viewport.z; - const halfViewportWidth = viewport.z / 2.0; - const halfViewportHeight = viewport.w / 2.0; - let size = 16 / viewport.w; - scale.set(size * invAspect, size); - validArea.min.set(viewport.x, viewport.y); - validArea.max.set(viewport.x + (viewport.z - 16), viewport.y + (viewport.w - 16)); // calculate position in screen space - - positionView.setFromMatrixPosition(this.matrixWorld); - positionView.applyMatrix4(camera.matrixWorldInverse); - if (positionView.z > 0) return; // lensflare is behind the camera - - positionScreen.copy(positionView).applyMatrix4(camera.projectionMatrix); // horizontal and vertical coordinate of the lower left corner of the pixels to copy - - screenPositionPixels.x = viewport.x + positionScreen.x * halfViewportWidth + halfViewportWidth - 8; - screenPositionPixels.y = viewport.y + positionScreen.y * halfViewportHeight + halfViewportHeight - 8; // screen cull - - if (validArea.containsPoint(screenPositionPixels)) { - // save current RGB to temp texture - renderer.copyFramebufferToTexture(screenPositionPixels, tempMap); // render pink quad - - let uniforms = material1a.uniforms; - uniforms['scale'].value = scale; - uniforms['screenPosition'].value = positionScreen; - renderer.renderBufferDirect(camera, null, geometry, material1a, mesh1, null); // copy result to occlusionMap - - renderer.copyFramebufferToTexture(screenPositionPixels, occlusionMap); // restore graphics - - uniforms = material1b.uniforms; - uniforms['scale'].value = scale; - uniforms['screenPosition'].value = positionScreen; - renderer.renderBufferDirect(camera, null, geometry, material1b, mesh1, null); // render elements - - const vecX = -positionScreen.x * 2; - const vecY = -positionScreen.y * 2; - - for (let i = 0, l = elements.length; i < l; i++) { - const element = elements[i]; - const uniforms = material2.uniforms; - uniforms['color'].value.copy(element.color); - uniforms['map'].value = element.texture; - uniforms['screenPosition'].value.x = positionScreen.x + vecX * element.distance; - uniforms['screenPosition'].value.y = positionScreen.y + vecY * element.distance; - size = element.size / viewport.w; - const invAspect = viewport.w / viewport.z; - uniforms['scale'].value.set(size * invAspect, size); - material2.uniformsNeedUpdate = true; - renderer.renderBufferDirect(camera, null, geometry, material2, mesh2, null); - } - } - }; - - this.dispose = function () { - material1a.dispose(); - material1b.dispose(); - material2.dispose(); - tempMap.dispose(); - occlusionMap.dispose(); - - for (let i = 0, l = elements.length; i < l; i++) { - elements[i].texture.dispose(); - } - }; - } - -} - -Lensflare.prototype.isLensflare = true; // - -class LensflareElement { - constructor(texture, size = 1, distance = 0, color = new Color(0xffffff)) { - this.texture = texture; - this.size = size; - this.distance = distance; - this.color = color; - } - -} - -LensflareElement.Shader = { - uniforms: { - map: { - value: null - }, - occlusionMap: { - value: null - }, - color: { - value: null - }, - scale: { - value: null - }, - screenPosition: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - uniform sampler2D occlusionMap; - - attribute vec3 position; - attribute vec2 uv; - - varying vec2 vUV; - varying float vVisibility; - - void main() { - - vUV = uv; - - vec2 pos = position.xy; - - vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ); - visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) ); - visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) ); - visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ); - visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) ); - visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ); - visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) ); - visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ); - visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) ); - - vVisibility = visibility.r / 9.0; - vVisibility *= 1.0 - visibility.g / 9.0; - vVisibility *= visibility.b / 9.0; - - gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - - precision highp float; - - uniform sampler2D map; - uniform vec3 color; - - varying vec2 vUV; - varying float vVisibility; - - void main() { - - vec4 texture = texture2D( map, vUV ); - texture.a *= vVisibility; - gl_FragColor = texture; - gl_FragColor.rgb *= color; - - }` -}; - -Lensflare.Geometry = function () { - const geometry = new BufferGeometry(); - const float32Array = new Float32Array([-1, -1, 0, 0, 0, 1, -1, 0, 1, 0, 1, 1, 0, 1, 1, -1, 1, 0, 0, 1]); - const interleavedBuffer = new InterleavedBuffer(float32Array, 5); - geometry.setIndex([0, 1, 2, 0, 2, 3]); - geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); - geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); - return geometry; -}(); - -/** - * Work based on : - * https://github.com/Slayvin: Flat mirror for three.js - * https://home.adelphi.edu/~stemkoski/ : An implementation of water shader based on the flat mirror - * http://29a.ch/ && http://29a.ch/slides/2012/webglwater/ : Water shader explanations in WebGL - */ - -class Water$1 extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - const scope = this; - const textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512; - const textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512; - const clipBias = options.clipBias !== undefined ? options.clipBias : 0.0; - const alpha = options.alpha !== undefined ? options.alpha : 1.0; - const time = options.time !== undefined ? options.time : 0.0; - const normalSampler = options.waterNormals !== undefined ? options.waterNormals : null; - const sunDirection = options.sunDirection !== undefined ? options.sunDirection : new Vector3(0.70707, 0.70707, 0.0); - const sunColor = new Color(options.sunColor !== undefined ? options.sunColor : 0xffffff); - const waterColor = new Color(options.waterColor !== undefined ? options.waterColor : 0x7f7f7f); - const eye = options.eye !== undefined ? options.eye : new Vector3(0, 0, 0); - const distortionScale = options.distortionScale !== undefined ? options.distortionScale : 20.0; - const side = options.side !== undefined ? options.side : FrontSide; - const fog = options.fog !== undefined ? options.fog : false; // - - const mirrorPlane = new Plane(); - const normal = new Vector3(); - const mirrorWorldPosition = new Vector3(); - const cameraWorldPosition = new Vector3(); - const rotationMatrix = new Matrix4(); - const lookAtPosition = new Vector3(0, 0, -1); - const clipPlane = new Vector4(); - const view = new Vector3(); - const target = new Vector3(); - const q = new Vector4(); - const textureMatrix = new Matrix4(); - const mirrorCamera = new PerspectiveCamera(); - const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight); - const mirrorShader = { - uniforms: UniformsUtils.merge([UniformsLib['fog'], UniformsLib['lights'], { - normalSampler: { - value: null - }, - mirrorSampler: { - value: null - }, - alpha: { - value: 1.0 - }, - time: { - value: 0.0 - }, - size: { - value: 1.0 - }, - distortionScale: { - value: 20.0 - }, - textureMatrix: { - value: new Matrix4() - }, - sunColor: { - value: new Color(0x7f7f7f) - }, - sunDirection: { - value: new Vector3(0.70707, 0.70707, 0) - }, - eye: { - value: new Vector3() - }, - waterColor: { - value: new Color(0x555555) - } - }]), - vertexShader: - /* glsl */ - ` - uniform mat4 textureMatrix; - uniform float time; - - varying vec4 mirrorCoord; - varying vec4 worldPosition; - - #include - #include - #include - #include - - void main() { - mirrorCoord = modelMatrix * vec4( position, 1.0 ); - worldPosition = mirrorCoord.xyzw; - mirrorCoord = textureMatrix * mirrorCoord; - vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); - gl_Position = projectionMatrix * mvPosition; - - #include - #include - #include - #include - #include - }`, - fragmentShader: - /* glsl */ - ` - uniform sampler2D mirrorSampler; - uniform float alpha; - uniform float time; - uniform float size; - uniform float distortionScale; - uniform sampler2D normalSampler; - uniform vec3 sunColor; - uniform vec3 sunDirection; - uniform vec3 eye; - uniform vec3 waterColor; - - varying vec4 mirrorCoord; - varying vec4 worldPosition; - - vec4 getNoise( vec2 uv ) { - vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0); - vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 ); - vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 ); - vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 ); - vec4 noise = texture2D( normalSampler, uv0 ) + - texture2D( normalSampler, uv1 ) + - texture2D( normalSampler, uv2 ) + - texture2D( normalSampler, uv3 ); - return noise * 0.5 - 1.0; - } - - void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) { - vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) ); - float direction = max( 0.0, dot( eyeDirection, reflection ) ); - specularColor += pow( direction, shiny ) * sunColor * spec; - diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse; - } - - #include - #include - #include - #include - #include - #include - #include - #include - - void main() { - - #include - vec4 noise = getNoise( worldPosition.xz * size ); - vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) ); - - vec3 diffuseLight = vec3(0.0); - vec3 specularLight = vec3(0.0); - - vec3 worldToEye = eye-worldPosition.xyz; - vec3 eyeDirection = normalize( worldToEye ); - sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight ); - - float distance = length(worldToEye); - - vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale; - vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) ); - - float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 ); - float rf0 = 0.3; - float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 ); - vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor; - vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance); - vec3 outgoingLight = albedo; - gl_FragColor = vec4( outgoingLight, alpha ); - - #include - #include - }` - }; - const material = new ShaderMaterial({ - fragmentShader: mirrorShader.fragmentShader, - vertexShader: mirrorShader.vertexShader, - uniforms: UniformsUtils.clone(mirrorShader.uniforms), - lights: true, - side: side, - fog: fog - }); - material.uniforms['mirrorSampler'].value = renderTarget.texture; - material.uniforms['textureMatrix'].value = textureMatrix; - material.uniforms['alpha'].value = alpha; - material.uniforms['time'].value = time; - material.uniforms['normalSampler'].value = normalSampler; - material.uniforms['sunColor'].value = sunColor; - material.uniforms['waterColor'].value = waterColor; - material.uniforms['sunDirection'].value = sunDirection; - material.uniforms['distortionScale'].value = distortionScale; - material.uniforms['eye'].value = eye; - scope.material = material; - - scope.onBeforeRender = function (renderer, scene, camera) { - mirrorWorldPosition.setFromMatrixPosition(scope.matrixWorld); - cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); - rotationMatrix.extractRotation(scope.matrixWorld); - normal.set(0, 0, 1); - normal.applyMatrix4(rotationMatrix); - view.subVectors(mirrorWorldPosition, cameraWorldPosition); // Avoid rendering when mirror is facing away - - if (view.dot(normal) > 0) return; - view.reflect(normal).negate(); - view.add(mirrorWorldPosition); - rotationMatrix.extractRotation(camera.matrixWorld); - lookAtPosition.set(0, 0, -1); - lookAtPosition.applyMatrix4(rotationMatrix); - lookAtPosition.add(cameraWorldPosition); - target.subVectors(mirrorWorldPosition, lookAtPosition); - target.reflect(normal).negate(); - target.add(mirrorWorldPosition); - mirrorCamera.position.copy(view); - mirrorCamera.up.set(0, 1, 0); - mirrorCamera.up.applyMatrix4(rotationMatrix); - mirrorCamera.up.reflect(normal); - mirrorCamera.lookAt(target); - mirrorCamera.far = camera.far; // Used in WebGLBackground - - mirrorCamera.updateMatrixWorld(); - mirrorCamera.projectionMatrix.copy(camera.projectionMatrix); // Update the texture matrix - - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); - textureMatrix.multiply(mirrorCamera.projectionMatrix); - textureMatrix.multiply(mirrorCamera.matrixWorldInverse); // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html - // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf - - mirrorPlane.setFromNormalAndCoplanarPoint(normal, mirrorWorldPosition); - mirrorPlane.applyMatrix4(mirrorCamera.matrixWorldInverse); - clipPlane.set(mirrorPlane.normal.x, mirrorPlane.normal.y, mirrorPlane.normal.z, mirrorPlane.constant); - const projectionMatrix = mirrorCamera.projectionMatrix; - q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; - q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; - q.z = -1.0; - q.w = (1.0 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; // Calculate the scaled plane vector - - clipPlane.multiplyScalar(2.0 / clipPlane.dot(q)); // Replacing the third row of the projection matrix - - projectionMatrix.elements[2] = clipPlane.x; - projectionMatrix.elements[6] = clipPlane.y; - projectionMatrix.elements[10] = clipPlane.z + 1.0 - clipBias; - projectionMatrix.elements[14] = clipPlane.w; - eye.setFromMatrixPosition(camera.matrixWorld); // Render - - const currentRenderTarget = renderer.getRenderTarget(); - const currentXrEnabled = renderer.xr.enabled; - const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; - scope.visible = false; - renderer.xr.enabled = false; // Avoid camera modification and recursion - - renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows - - renderer.setRenderTarget(renderTarget); - renderer.state.buffers.depth.setMask(true); // make sure the depth buffer is writable so it can be properly cleared, see #18897 - - if (renderer.autoClear === false) renderer.clear(); - renderer.render(scene, mirrorCamera); - scope.visible = true; - renderer.xr.enabled = currentXrEnabled; - renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; - renderer.setRenderTarget(currentRenderTarget); // Restore viewport - - const viewport = camera.viewport; - - if (viewport !== undefined) { - renderer.state.viewport(viewport); - } - }; - } - -} - -Water$1.prototype.isWater = true; - -/** - * Port of http://webglsamples.org/blob/blob.html - */ - -class MarchingCubes extends Mesh { - constructor(resolution, material, enableUvs = false, enableColors = false, maxPolyCount = 10000) { - const geometry = new BufferGeometry(); - super(geometry, material); - const scope = this; // temp buffers used in polygonize - - const vlist = new Float32Array(12 * 3); - const nlist = new Float32Array(12 * 3); - const clist = new Float32Array(12 * 3); - this.enableUvs = enableUvs; - this.enableColors = enableColors; // functions have to be object properties - // prototype functions kill performance - // (tested and it was 4x slower !!!) - - this.init = function (resolution) { - this.resolution = resolution; // parameters - - this.isolation = 80.0; // size of field, 32 is pushing it in Javascript :) - - this.size = resolution; - this.size2 = this.size * this.size; - this.size3 = this.size2 * this.size; - this.halfsize = this.size / 2.0; // deltas - - this.delta = 2.0 / this.size; - this.yd = this.size; - this.zd = this.size2; - this.field = new Float32Array(this.size3); - this.normal_cache = new Float32Array(this.size3 * 3); - this.palette = new Float32Array(this.size3 * 3); // - - this.count = 0; - const maxVertexCount = maxPolyCount * 3; - this.positionArray = new Float32Array(maxVertexCount * 3); - const positionAttribute = new BufferAttribute(this.positionArray, 3); - positionAttribute.setUsage(DynamicDrawUsage); - geometry.setAttribute('position', positionAttribute); - this.normalArray = new Float32Array(maxVertexCount * 3); - const normalAttribute = new BufferAttribute(this.normalArray, 3); - normalAttribute.setUsage(DynamicDrawUsage); - geometry.setAttribute('normal', normalAttribute); - - if (this.enableUvs) { - this.uvArray = new Float32Array(maxVertexCount * 2); - const uvAttribute = new BufferAttribute(this.uvArray, 2); - uvAttribute.setUsage(DynamicDrawUsage); - geometry.setAttribute('uv', uvAttribute); - } - - if (this.enableColors) { - this.colorArray = new Float32Array(maxVertexCount * 3); - const colorAttribute = new BufferAttribute(this.colorArray, 3); - colorAttribute.setUsage(DynamicDrawUsage); - geometry.setAttribute('color', colorAttribute); - } - }; /////////////////////// - // Polygonization - /////////////////////// - - - function lerp(a, b, t) { - return a + (b - a) * t; - } - - function VIntX(q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2) { - const mu = (isol - valp1) / (valp2 - valp1), - nc = scope.normal_cache; - vlist[offset + 0] = x + mu * scope.delta; - vlist[offset + 1] = y; - vlist[offset + 2] = z; - nlist[offset + 0] = lerp(nc[q + 0], nc[q + 3], mu); - nlist[offset + 1] = lerp(nc[q + 1], nc[q + 4], mu); - nlist[offset + 2] = lerp(nc[q + 2], nc[q + 5], mu); - clist[offset + 0] = lerp(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); - clist[offset + 1] = lerp(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); - clist[offset + 2] = lerp(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu); - } - - function VIntY(q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2) { - const mu = (isol - valp1) / (valp2 - valp1), - nc = scope.normal_cache; - vlist[offset + 0] = x; - vlist[offset + 1] = y + mu * scope.delta; - vlist[offset + 2] = z; - const q2 = q + scope.yd * 3; - nlist[offset + 0] = lerp(nc[q + 0], nc[q2 + 0], mu); - nlist[offset + 1] = lerp(nc[q + 1], nc[q2 + 1], mu); - nlist[offset + 2] = lerp(nc[q + 2], nc[q2 + 2], mu); - clist[offset + 0] = lerp(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); - clist[offset + 1] = lerp(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); - clist[offset + 2] = lerp(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu); - } - - function VIntZ(q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2) { - const mu = (isol - valp1) / (valp2 - valp1), - nc = scope.normal_cache; - vlist[offset + 0] = x; - vlist[offset + 1] = y; - vlist[offset + 2] = z + mu * scope.delta; - const q2 = q + scope.zd * 3; - nlist[offset + 0] = lerp(nc[q + 0], nc[q2 + 0], mu); - nlist[offset + 1] = lerp(nc[q + 1], nc[q2 + 1], mu); - nlist[offset + 2] = lerp(nc[q + 2], nc[q2 + 2], mu); - clist[offset + 0] = lerp(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); - clist[offset + 1] = lerp(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); - clist[offset + 2] = lerp(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu); - } - - function compNorm(q) { - const q3 = q * 3; - - if (scope.normal_cache[q3] === 0.0) { - scope.normal_cache[q3 + 0] = scope.field[q - 1] - scope.field[q + 1]; - scope.normal_cache[q3 + 1] = scope.field[q - scope.yd] - scope.field[q + scope.yd]; - scope.normal_cache[q3 + 2] = scope.field[q - scope.zd] - scope.field[q + scope.zd]; - } - } // Returns total number of triangles. Fills triangles. - // (this is where most of time is spent - it's inner work of O(n3) loop ) - - - function polygonize(fx, fy, fz, q, isol) { - // cache indices - const q1 = q + 1, - qy = q + scope.yd, - qz = q + scope.zd, - q1y = q1 + scope.yd, - q1z = q1 + scope.zd, - qyz = q + scope.yd + scope.zd, - q1yz = q1 + scope.yd + scope.zd; - let cubeindex = 0; - const field0 = scope.field[q], - field1 = scope.field[q1], - field2 = scope.field[qy], - field3 = scope.field[q1y], - field4 = scope.field[qz], - field5 = scope.field[q1z], - field6 = scope.field[qyz], - field7 = scope.field[q1yz]; - if (field0 < isol) cubeindex |= 1; - if (field1 < isol) cubeindex |= 2; - if (field2 < isol) cubeindex |= 8; - if (field3 < isol) cubeindex |= 4; - if (field4 < isol) cubeindex |= 16; - if (field5 < isol) cubeindex |= 32; - if (field6 < isol) cubeindex |= 128; - if (field7 < isol) cubeindex |= 64; // if cube is entirely in/out of the surface - bail, nothing to draw - - const bits = edgeTable[cubeindex]; - if (bits === 0) return 0; - const d = scope.delta, - fx2 = fx + d, - fy2 = fy + d, - fz2 = fz + d; // top of the cube - - if (bits & 1) { - compNorm(q); - compNorm(q1); - VIntX(q * 3, 0, isol, fx, fy, fz, field0, field1, q, q1); - } - - if (bits & 2) { - compNorm(q1); - compNorm(q1y); - VIntY(q1 * 3, 3, isol, fx2, fy, fz, field1, field3, q1, q1y); - } - - if (bits & 4) { - compNorm(qy); - compNorm(q1y); - VIntX(qy * 3, 6, isol, fx, fy2, fz, field2, field3, qy, q1y); - } - - if (bits & 8) { - compNorm(q); - compNorm(qy); - VIntY(q * 3, 9, isol, fx, fy, fz, field0, field2, q, qy); - } // bottom of the cube - - - if (bits & 16) { - compNorm(qz); - compNorm(q1z); - VIntX(qz * 3, 12, isol, fx, fy, fz2, field4, field5, qz, q1z); - } - - if (bits & 32) { - compNorm(q1z); - compNorm(q1yz); - VIntY(q1z * 3, 15, isol, fx2, fy, fz2, field5, field7, q1z, q1yz); - } - - if (bits & 64) { - compNorm(qyz); - compNorm(q1yz); - VIntX(qyz * 3, 18, isol, fx, fy2, fz2, field6, field7, qyz, q1yz); - } - - if (bits & 128) { - compNorm(qz); - compNorm(qyz); - VIntY(qz * 3, 21, isol, fx, fy, fz2, field4, field6, qz, qyz); - } // vertical lines of the cube - - - if (bits & 256) { - compNorm(q); - compNorm(qz); - VIntZ(q * 3, 24, isol, fx, fy, fz, field0, field4, q, qz); - } - - if (bits & 512) { - compNorm(q1); - compNorm(q1z); - VIntZ(q1 * 3, 27, isol, fx2, fy, fz, field1, field5, q1, q1z); - } - - if (bits & 1024) { - compNorm(q1y); - compNorm(q1yz); - VIntZ(q1y * 3, 30, isol, fx2, fy2, fz, field3, field7, q1y, q1yz); - } - - if (bits & 2048) { - compNorm(qy); - compNorm(qyz); - VIntZ(qy * 3, 33, isol, fx, fy2, fz, field2, field6, qy, qyz); - } - - cubeindex <<= 4; // re-purpose cubeindex into an offset into triTable - - let o1, - o2, - o3, - numtris = 0, - i = 0; // here is where triangles are created - - while (triTable[cubeindex + i] != -1) { - o1 = cubeindex + i; - o2 = o1 + 1; - o3 = o1 + 2; - posnormtriv(vlist, nlist, clist, 3 * triTable[o1], 3 * triTable[o2], 3 * triTable[o3]); - i += 3; - numtris++; - } - - return numtris; - } - - function posnormtriv(pos, norm, colors, o1, o2, o3) { - const c = scope.count * 3; // positions - - scope.positionArray[c + 0] = pos[o1]; - scope.positionArray[c + 1] = pos[o1 + 1]; - scope.positionArray[c + 2] = pos[o1 + 2]; - scope.positionArray[c + 3] = pos[o2]; - scope.positionArray[c + 4] = pos[o2 + 1]; - scope.positionArray[c + 5] = pos[o2 + 2]; - scope.positionArray[c + 6] = pos[o3]; - scope.positionArray[c + 7] = pos[o3 + 1]; - scope.positionArray[c + 8] = pos[o3 + 2]; // normals - - if (scope.material.flatShading === true) { - const nx = (norm[o1 + 0] + norm[o2 + 0] + norm[o3 + 0]) / 3; - const ny = (norm[o1 + 1] + norm[o2 + 1] + norm[o3 + 1]) / 3; - const nz = (norm[o1 + 2] + norm[o2 + 2] + norm[o3 + 2]) / 3; - scope.normalArray[c + 0] = nx; - scope.normalArray[c + 1] = ny; - scope.normalArray[c + 2] = nz; - scope.normalArray[c + 3] = nx; - scope.normalArray[c + 4] = ny; - scope.normalArray[c + 5] = nz; - scope.normalArray[c + 6] = nx; - scope.normalArray[c + 7] = ny; - scope.normalArray[c + 8] = nz; - } else { - scope.normalArray[c + 0] = norm[o1 + 0]; - scope.normalArray[c + 1] = norm[o1 + 1]; - scope.normalArray[c + 2] = norm[o1 + 2]; - scope.normalArray[c + 3] = norm[o2 + 0]; - scope.normalArray[c + 4] = norm[o2 + 1]; - scope.normalArray[c + 5] = norm[o2 + 2]; - scope.normalArray[c + 6] = norm[o3 + 0]; - scope.normalArray[c + 7] = norm[o3 + 1]; - scope.normalArray[c + 8] = norm[o3 + 2]; - } // uvs - - - if (scope.enableUvs) { - const d = scope.count * 2; - scope.uvArray[d + 0] = pos[o1 + 0]; - scope.uvArray[d + 1] = pos[o1 + 2]; - scope.uvArray[d + 2] = pos[o2 + 0]; - scope.uvArray[d + 3] = pos[o2 + 2]; - scope.uvArray[d + 4] = pos[o3 + 0]; - scope.uvArray[d + 5] = pos[o3 + 2]; - } // colors - - - if (scope.enableColors) { - scope.colorArray[c + 0] = colors[o1 + 0]; - scope.colorArray[c + 1] = colors[o1 + 1]; - scope.colorArray[c + 2] = colors[o1 + 2]; - scope.colorArray[c + 3] = colors[o2 + 0]; - scope.colorArray[c + 4] = colors[o2 + 1]; - scope.colorArray[c + 5] = colors[o2 + 2]; - scope.colorArray[c + 6] = colors[o3 + 0]; - scope.colorArray[c + 7] = colors[o3 + 1]; - scope.colorArray[c + 8] = colors[o3 + 2]; - } - - scope.count += 3; - } ///////////////////////////////////// - // Metaballs - ///////////////////////////////////// - // Adds a reciprocal ball (nice and blobby) that, to be fast, fades to zero after - // a fixed distance, determined by strength and subtract. - - - this.addBall = function (ballx, bally, ballz, strength, subtract, colors) { - const sign = Math.sign(strength); - strength = Math.abs(strength); - const userDefineColor = !(colors === undefined || colors === null); - let ballColor = new Color(ballx, bally, ballz); - - if (userDefineColor) { - try { - ballColor = colors instanceof Color ? colors : Array.isArray(colors) ? new Color(Math.min(Math.abs(colors[0]), 1), Math.min(Math.abs(colors[1]), 1), Math.min(Math.abs(colors[2]), 1)) : new Color(colors); - } catch (err) { - ballColor = new Color(ballx, bally, ballz); - } - } // Let's solve the equation to find the radius: - // 1.0 / (0.000001 + radius^2) * strength - subtract = 0 - // strength / (radius^2) = subtract - // strength = subtract * radius^2 - // radius^2 = strength / subtract - // radius = sqrt(strength / subtract) - - - const radius = this.size * Math.sqrt(strength / subtract), - zs = ballz * this.size, - ys = bally * this.size, - xs = ballx * this.size; - let min_z = Math.floor(zs - radius); - if (min_z < 1) min_z = 1; - let max_z = Math.floor(zs + radius); - if (max_z > this.size - 1) max_z = this.size - 1; - let min_y = Math.floor(ys - radius); - if (min_y < 1) min_y = 1; - let max_y = Math.floor(ys + radius); - if (max_y > this.size - 1) max_y = this.size - 1; - let min_x = Math.floor(xs - radius); - if (min_x < 1) min_x = 1; - let max_x = Math.floor(xs + radius); - if (max_x > this.size - 1) max_x = this.size - 1; // Don't polygonize in the outer layer because normals aren't - // well-defined there. - - let x, y, z, y_offset, z_offset, fx, fy, fz, fz2, fy2, val; - - for (z = min_z; z < max_z; z++) { - z_offset = this.size2 * z; - fz = z / this.size - ballz; - fz2 = fz * fz; - - for (y = min_y; y < max_y; y++) { - y_offset = z_offset + this.size * y; - fy = y / this.size - bally; - fy2 = fy * fy; - - for (x = min_x; x < max_x; x++) { - fx = x / this.size - ballx; - val = strength / (0.000001 + fx * fx + fy2 + fz2) - subtract; - - if (val > 0.0) { - this.field[y_offset + x] += val * sign; // optimization - // http://www.geisswerks.com/ryan/BLOBS/blobs.html - - const ratio = Math.sqrt((x - xs) * (x - xs) + (y - ys) * (y - ys) + (z - zs) * (z - zs)) / radius; - const contrib = 1 - ratio * ratio * ratio * (ratio * (ratio * 6 - 15) + 10); - this.palette[(y_offset + x) * 3 + 0] += ballColor.r * contrib; - this.palette[(y_offset + x) * 3 + 1] += ballColor.g * contrib; - this.palette[(y_offset + x) * 3 + 2] += ballColor.b * contrib; - } - } - } - } - }; - - this.addPlaneX = function (strength, subtract) { - // cache attribute lookups - const size = this.size, - yd = this.yd, - zd = this.zd, - field = this.field; - let x, - y, - z, - xx, - val, - xdiv, - cxy, - dist = size * Math.sqrt(strength / subtract); - if (dist > size) dist = size; - - for (x = 0; x < dist; x++) { - xdiv = x / size; - xx = xdiv * xdiv; - val = strength / (0.0001 + xx) - subtract; - - if (val > 0.0) { - for (y = 0; y < size; y++) { - cxy = x + y * yd; - - for (z = 0; z < size; z++) { - field[zd * z + cxy] += val; - } - } - } - } - }; - - this.addPlaneY = function (strength, subtract) { - // cache attribute lookups - const size = this.size, - yd = this.yd, - zd = this.zd, - field = this.field; - let x, - y, - z, - yy, - val, - ydiv, - cy, - cxy, - dist = size * Math.sqrt(strength / subtract); - if (dist > size) dist = size; - - for (y = 0; y < dist; y++) { - ydiv = y / size; - yy = ydiv * ydiv; - val = strength / (0.0001 + yy) - subtract; - - if (val > 0.0) { - cy = y * yd; - - for (x = 0; x < size; x++) { - cxy = cy + x; - - for (z = 0; z < size; z++) field[zd * z + cxy] += val; - } - } - } - }; - - this.addPlaneZ = function (strength, subtract) { - // cache attribute lookups - const size = this.size, - yd = this.yd, - zd = this.zd, - field = this.field; - let x, - y, - z, - zz, - val, - zdiv, - cz, - cyz, - dist = size * Math.sqrt(strength / subtract); - if (dist > size) dist = size; - - for (z = 0; z < dist; z++) { - zdiv = z / size; - zz = zdiv * zdiv; - val = strength / (0.0001 + zz) - subtract; - - if (val > 0.0) { - cz = zd * z; - - for (y = 0; y < size; y++) { - cyz = cz + y * yd; - - for (x = 0; x < size; x++) field[cyz + x] += val; - } - } - } - }; ///////////////////////////////////// - // Updates - ///////////////////////////////////// - - - this.setCell = function (x, y, z, value) { - const index = this.size2 * z + this.size * y + x; - this.field[index] = value; - }; - - this.getCell = function (x, y, z) { - const index = this.size2 * z + this.size * y + x; - return this.field[index]; - }; - - this.blur = function (intensity = 1) { - const field = this.field; - const fieldCopy = field.slice(); - const size = this.size; - const size2 = this.size2; - - for (let x = 0; x < size; x++) { - for (let y = 0; y < size; y++) { - for (let z = 0; z < size; z++) { - const index = size2 * z + size * y + x; - let val = fieldCopy[index]; - let count = 1; - - for (let x2 = -1; x2 <= 1; x2 += 2) { - const x3 = x2 + x; - if (x3 < 0 || x3 >= size) continue; - - for (let y2 = -1; y2 <= 1; y2 += 2) { - const y3 = y2 + y; - if (y3 < 0 || y3 >= size) continue; - - for (let z2 = -1; z2 <= 1; z2 += 2) { - const z3 = z2 + z; - if (z3 < 0 || z3 >= size) continue; - const index2 = size2 * z3 + size * y3 + x3; - const val2 = fieldCopy[index2]; - count++; - val += intensity * (val2 - val) / count; - } - } - } - - field[index] = val; - } - } - } - }; - - this.reset = function () { - // wipe the normal cache - for (let i = 0; i < this.size3; i++) { - this.normal_cache[i * 3] = 0.0; - this.field[i] = 0.0; - this.palette[i * 3] = this.palette[i * 3 + 1] = this.palette[i * 3 + 2] = 0.0; - } - }; - - this.onBeforeRender = function () { - this.count = 0; // Triangulate. Yeah, this is slow. - - const smin2 = this.size - 2; - - for (let z = 1; z < smin2; z++) { - const z_offset = this.size2 * z; - const fz = (z - this.halfsize) / this.halfsize; //+ 1 - - for (let y = 1; y < smin2; y++) { - const y_offset = z_offset + this.size * y; - const fy = (y - this.halfsize) / this.halfsize; //+ 1 - - for (let x = 1; x < smin2; x++) { - const fx = (x - this.halfsize) / this.halfsize; //+ 1 - - const q = y_offset + x; - polygonize(fx, fy, fz, q, this.isolation); - } - } - } // reset unneeded data - - - for (let i = this.count * 3; i < this.positionArray.length; i++) { - this.positionArray[i] = 0.0; - } // update geometry data - - - geometry.getAttribute('position').needsUpdate = true; - geometry.getAttribute('normal').needsUpdate = true; - if (this.enableUvs) geometry.getAttribute('uv').needsUpdate = true; - if (this.enableColors) geometry.getAttribute('color').needsUpdate = true; // safety check - - if (this.count / 3 > maxPolyCount) { - console.warn('MarchingCubes: Geometry buffers too small for rendering. Please create an instance with a higher poly count.'); - } - }; - - this.init(resolution); - } - -} - -MarchingCubes.prototype.isMarchingCubes = true; ///////////////////////////////////// -// Marching cubes lookup tables -///////////////////////////////////// -// These tables are straight from Paul Bourke's page: -// http://paulbourke.net/geometry/polygonise/ -// who in turn got them from Cory Gene Bloyd. -// prettier-ignore - -const edgeTable = new Int32Array([0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66, 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa, 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33, 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99, 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0]); // prettier-ignore - -const triTable = new Int32Array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1, 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1, 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1, 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1, 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1, 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1, 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1, 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1, 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1, 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1, 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1, 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1, 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1, 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1, 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1, 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1, 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1, 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1, 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1, 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1, 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1, 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1, 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1, 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1, 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1, 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1, 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1, 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1, 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1, 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1, 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1, 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1, 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1, 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1, 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1, 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1, 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1, 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1, 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1, 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1, 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1, 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1, 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1, 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1, 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1, 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1, 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1, 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1, 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1, 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1, 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1, 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1, 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1, 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1, 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1, 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1, 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1, 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1, 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1, 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1, 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1, 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1, 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1, 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1, 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1, 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1, 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1, 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1, 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1, 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1, 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1, 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1, 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1, 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1, 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1, 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1, 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1, 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1, 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1, 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1, 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1, 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1, 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1, 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1, 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1, 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1, 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1, 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1, 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1, 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1, 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1, 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1, 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1, 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1, 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1, 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1, 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1, 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1, 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1, 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1, 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1, 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1, 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1, 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1, 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1, 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1, 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1, 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1, 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1, 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1, 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1, 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1, 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1, 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1, 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1, 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1, 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1, 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1, 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1, 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1, 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1, 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1, 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1, 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1, 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1, 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1, 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1, 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1, 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1, 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1, 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1, 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1, 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1, 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1, 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1, 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1, 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1, 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1, 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1, 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1, 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1, 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1, 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1, 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1, 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1, 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1, 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1, 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]); - -// Ported from Stefan Gustavson's java implementation -// http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf -// Read Stefan's excellent paper for details on how this code works. -// -// Sean McCullough banksean@gmail.com -// -// Added 4D noise -class SimplexNoise { - // To remove the need for index wrapping, double the permutation table length - // A lookup table to traverse the simplex around a given point in 4D. - // Details can be found where this table is used, in the 4D noise method. - - /** - * You can pass in a random number generator object if you like. - * It is assumed to have a random() method. - */ - constructor(r = Math) { - _defineProperty$1(this, "grad3", [[1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1], [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1]]); - - _defineProperty$1(this, "grad4", [[0, 1, 1, 1], [0, 1, 1, -1], [0, 1, -1, 1], [0, 1, -1, -1], [0, -1, 1, 1], [0, -1, 1, -1], [0, -1, -1, 1], [0, -1, -1, -1], [1, 0, 1, 1], [1, 0, 1, -1], [1, 0, -1, 1], [1, 0, -1, -1], [-1, 0, 1, 1], [-1, 0, 1, -1], [-1, 0, -1, 1], [-1, 0, -1, -1], [1, 1, 0, 1], [1, 1, 0, -1], [1, -1, 0, 1], [1, -1, 0, -1], [-1, 1, 0, 1], [-1, 1, 0, -1], [-1, -1, 0, 1], [-1, -1, 0, -1], [1, 1, 1, 0], [1, 1, -1, 0], [1, -1, 1, 0], [1, -1, -1, 0], [-1, 1, 1, 0], [-1, 1, -1, 0], [-1, -1, 1, 0], [-1, -1, -1, 0]]); - - _defineProperty$1(this, "p", []); - - _defineProperty$1(this, "perm", []); - - _defineProperty$1(this, "simplex", [[0, 1, 2, 3], [0, 1, 3, 2], [0, 0, 0, 0], [0, 2, 3, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 3, 0], [0, 2, 1, 3], [0, 0, 0, 0], [0, 3, 1, 2], [0, 3, 2, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 3, 2, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 0, 3], [0, 0, 0, 0], [1, 3, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 3, 0, 1], [2, 3, 1, 0], [1, 0, 2, 3], [1, 0, 3, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 3, 1], [0, 0, 0, 0], [2, 1, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 1, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 1, 2], [3, 0, 2, 1], [0, 0, 0, 0], [3, 1, 2, 0], [2, 1, 0, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 1, 0, 2], [0, 0, 0, 0], [3, 2, 0, 1], [3, 2, 1, 0]]); - - _defineProperty$1(this, "dot", (g, x, y) => { - return g[0] * x + g[1] * y; - }); - - _defineProperty$1(this, "dot3", (g, x, y, z) => { - return g[0] * x + g[1] * y + g[2] * z; - }); - - _defineProperty$1(this, "dot4", (g, x, y, z, w) => { - return g[0] * x + g[1] * y + g[2] * z + g[3] * w; - }); - - _defineProperty$1(this, "noise", (xin, yin) => { - let n0; - let n1; - let n2; // Noise contributions from the three corners - // Skew the input space to determine which simplex cell we're in - - const F2 = 0.5 * (Math.sqrt(3.0) - 1.0); - const s = (xin + yin) * F2; // Hairy factor for 2D - - const i = Math.floor(xin + s); - const j = Math.floor(yin + s); - const G2 = (3.0 - Math.sqrt(3.0)) / 6.0; - const t = (i + j) * G2; - const X0 = i - t; // Unskew the cell origin back to (x,y) space - - const Y0 = j - t; - const x0 = xin - X0; // The x,y distances from the cell origin - - const y0 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. - // Determine which simplex we are in. - // upper triangle, YX order: (0,0)->(0,1)->(1,1) - - let i1 = 0; // Offsets for second (middle) corner of simplex in (i,j) coords - - let j1 = 1; - - if (x0 > y0) { - i1 = 1; - j1 = 0; - } // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and - // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where - // c = (3-sqrt(3))/6 - - - const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords - - const y1 = y0 - j1 + G2; - const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords - - const y2 = y0 - 1.0 + 2.0 * G2; // Work out the hashed gradient indices of the three simplex corners - - const ii = i & 255; - const jj = j & 255; - const gi0 = this.perm[ii + this.perm[jj]] % 12; - const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12; - const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12; // Calculate the contribution from the three corners - - let t0 = 0.5 - x0 * x0 - y0 * y0; - - if (t0 < 0) { - n0 = 0.0; - } else { - t0 *= t0; - n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient - } - - let t1 = 0.5 - x1 * x1 - y1 * y1; - - if (t1 < 0) { - n1 = 0.0; - } else { - t1 *= t1; - n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1); - } - - let t2 = 0.5 - x2 * x2 - y2 * y2; - - if (t2 < 0) { - n2 = 0.0; - } else { - t2 *= t2; - n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2); - } // Add contributions from each corner to get the final noise value. - // The result is scaled to return values in the interval [-1,1]. - - - return 70.0 * (n0 + n1 + n2); - }); - - _defineProperty$1(this, "noise3d", (xin, yin, zin) => { - // Noise contributions from the four corners - let n0; - let n1; - let n2; - let n3; // Skew the input space to determine which simplex cell we're in - - const F3 = 1.0 / 3.0; - const s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D - - const i = Math.floor(xin + s); - const j = Math.floor(yin + s); - const k = Math.floor(zin + s); - const G3 = 1.0 / 6.0; // Very nice and simple unskew factor, too - - const t = (i + j + k) * G3; - const X0 = i - t; // Unskew the cell origin back to (x,y,z) space - - const Y0 = j - t; - const Z0 = k - t; - const x0 = xin - X0; // The x,y,z distances from the cell origin - - const y0 = yin - Y0; - const z0 = zin - Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. - // Determine which simplex we are in. - - let i1; - let j1; - let k1; // Offsets for second corner of simplex in (i,j,k) coords - - let i2; - let j2; - let k2; // Offsets for third corner of simplex in (i,j,k) coords - - if (x0 >= y0) { - if (y0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; // X Y Z order - } else if (x0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 0; - k2 = 1; // X Z Y order - } else { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 1; - j2 = 0; - k2 = 1; - } // Z X Y order - - } else { - // x0 { - // For faster and easier lookups - const grad4 = this.grad4; - const simplex = this.simplex; - const perm = this.perm; // The skewing and unskewing factors are hairy again for the 4D case - - const F4 = (Math.sqrt(5.0) - 1.0) / 4.0; - const G4 = (5.0 - Math.sqrt(5.0)) / 20.0; - let n0; - let n1; - let n2; - let n3; - let n4; // Noise contributions from the five corners - // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in - - const s = (x + y + z + w) * F4; // Factor for 4D skewing - - const i = Math.floor(x + s); - const j = Math.floor(y + s); - const k = Math.floor(z + s); - const l = Math.floor(w + s); - const t = (i + j + k + l) * G4; // Factor for 4D unskewing - - const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space - - const Y0 = j - t; - const Z0 = k - t; - const W0 = l - t; - const x0 = x - X0; // The x,y,z,w distances from the cell origin - - const y0 = y - Y0; - const z0 = z - Z0; - const w0 = w - W0; // For the 4D case, the simplex is a 4D shape I won't even try to describe. - // To find out which of the 24 possible simplices we're in, we need to - // determine the magnitude ordering of x0, y0, z0 and w0. - // The method below is a good way of finding the ordering of x,y,z,w and - // then find the correct traversal order for the simplex we’re in. - // First, six pair-wise comparisons are performed between each possible pair - // of the four coordinates, and the results are used to add up binary bits - // for an integer index. - - const c1 = x0 > y0 ? 32 : 0; - const c2 = x0 > z0 ? 16 : 0; - const c3 = y0 > z0 ? 8 : 0; - const c4 = x0 > w0 ? 4 : 0; - const c5 = y0 > w0 ? 2 : 0; - const c6 = z0 > w0 ? 1 : 0; - const c = c1 + c2 + c3 + c4 + c5 + c6; // The integer offsets for the second simplex corner - - let i1; - let j1; - let k1; - let l1; // The integer offsets for the third simplex corner - - let i2; - let j2; - let k2; - let l2; // The integer offsets for the fourth simplex corner - - let i3; - let j3; - let k3; - let l3; // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. - // Many values of c will never occur, since e.g. x>y>z>w makes x= 3 ? 1 : 0; - j1 = simplex[c][1] >= 3 ? 1 : 0; - k1 = simplex[c][2] >= 3 ? 1 : 0; - l1 = simplex[c][3] >= 3 ? 1 : 0; // The number 2 in the "simplex" array is at the second largest coordinate. - - i2 = simplex[c][0] >= 2 ? 1 : 0; - j2 = simplex[c][1] >= 2 ? 1 : 0; - k2 = simplex[c][2] >= 2 ? 1 : 0; - l2 = simplex[c][3] >= 2 ? 1 : 0; // The number 1 in the "simplex" array is at the second smallest coordinate. - - i3 = simplex[c][0] >= 1 ? 1 : 0; - j3 = simplex[c][1] >= 1 ? 1 : 0; - k3 = simplex[c][2] >= 1 ? 1 : 0; - l3 = simplex[c][3] >= 1 ? 1 : 0; // The fifth corner has all coordinate offsets = 1, so no need to look that up. - - const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords - - const y1 = y0 - j1 + G4; - const z1 = z0 - k1 + G4; - const w1 = w0 - l1 + G4; - const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords - - const y2 = y0 - j2 + 2.0 * G4; - const z2 = z0 - k2 + 2.0 * G4; - const w2 = w0 - l2 + 2.0 * G4; - const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords - - const y3 = y0 - j3 + 3.0 * G4; - const z3 = z0 - k3 + 3.0 * G4; - const w3 = w0 - l3 + 3.0 * G4; - const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords - - const y4 = y0 - 1.0 + 4.0 * G4; - const z4 = z0 - 1.0 + 4.0 * G4; - const w4 = w0 - 1.0 + 4.0 * G4; // Work out the hashed gradient indices of the five simplex corners - - const ii = i & 255; - const jj = j & 255; - const kk = k & 255; - const ll = l & 255; - const gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; - const gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; - const gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; - const gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; - const gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; // Calculate the contribution from the five corners - - let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; - - if (t0 < 0) { - n0 = 0.0; - } else { - t0 *= t0; - n0 = t0 * t0 * this.dot4(grad4[gi0], x0, y0, z0, w0); - } - - let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; - - if (t1 < 0) { - n1 = 0.0; - } else { - t1 *= t1; - n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1); - } - - let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; - - if (t2 < 0) { - n2 = 0.0; - } else { - t2 *= t2; - n2 = t2 * t2 * this.dot4(grad4[gi2], x2, y2, z2, w2); - } - - let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; - - if (t3 < 0) { - n3 = 0.0; - } else { - t3 *= t3; - n3 = t3 * t3 * this.dot4(grad4[gi3], x3, y3, z3, w3); - } - - let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; - - if (t4 < 0) { - n4 = 0.0; - } else { - t4 *= t4; - n4 = t4 * t4 * this.dot4(grad4[gi4], x4, y4, z4, w4); - } // Sum up and scale the result to cover the range [-1,1] - - - return 27.0 * (n0 + n1 + n2 + n3 + n4); - }); - - for (let i = 0; i < 256; i++) { - this.p[i] = Math.floor(r.random() * 256); - } - - for (let i = 0; i < 512; i++) { - this.perm[i] = this.p[i & 255]; - } - } - -} - -/** - * @fileoverview LightningStrike object for creating lightning strikes and voltaic arcs. - * - * - * Usage - * - * var myRay = new LightningStrike( paramsObject ); - * var myRayMesh = new THREE.Mesh( myRay, myMaterial ); - * scene.add( myRayMesh ); - * ... - * myRay.update( currentTime ); - * - * The "currentTime" can vary its rate, go forwards, backwards or even jump, but it cannot be negative. - * - * You should normally leave the ray position to (0, 0, 0). You should control it by changing the sourceOffset and destOffset parameters. - * - * - * LightningStrike parameters - * - * The paramsObject can contain any of the following parameters. - * - * Legend: - * 'LightningStrike' (also called 'ray'): An independent voltaic arc with its ramifications and defined with a set of parameters. - * 'Subray': A ramification of the ray. It is not a LightningStrike object. - * 'Segment': A linear segment piece of a subray. - * 'Leaf segment': A ray segment which cannot be smaller. - * - * - * The following parameters can be changed any time and if they vary smoothly, the ray form will also change smoothly: - * - * @param {Vector3} sourceOffset The point where the ray starts. - * - * @param {Vector3} destOffset The point where the ray ends. - * - * @param {double} timeScale The rate at wich the ray form changes in time. Default: 1 - * - * @param {double} roughness From 0 to 1. The higher the value, the more wrinkled is the ray. Default: 0.9 - * - * @param {double} straightness From 0 to 1. The higher the value, the more straight will be a subray path. Default: 0.7 - * - * @param {Vector3} up0 Ray 'up' direction at the ray starting point. Must be normalized. It should be perpendicular to the ray forward direction but it doesn't matter much. - * - * @param {Vector3} up1 Like the up0 parameter but at the end of the ray. Must be normalized. - * - * @param {double} radius0 Radius of the main ray trunk at the start point. Default: 1 - * - * @param {double} radius1 Radius of the main ray trunk at the end point. Default: 1 - * - * @param {double} radius0Factor The radius0 of a subray is this factor times the radius0 of its parent subray. Default: 0.5 - * - * @param {double} radius1Factor The radius1 of a subray is this factor times the radius1 of its parent subray. Default: 0.2 - * - * @param {minRadius} Minimum value a subray radius0 or radius1 can get. Default: 0.1 - * - * - * The following parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly: - * - * @param {boolean} isEternal If true the ray never extinguishes. Otherwise its life is controlled by the 'birthTime' and 'deathTime' parameters. Default: true if any of those two parameters is undefined. - * - * @param {double} birthTime The time at which the ray starts its life and begins propagating. Only if isEternal is false. Default: None. - * - * @param {double} deathTime The time at which the ray ends vanishing and its life. Only if isEternal is false. Default: None. - * - * @param {double} propagationTimeFactor From 0 to 1. Lifetime factor at which the ray ends propagating and enters the steady phase. For example, 0.1 means it is propagating 1/10 of its lifetime. Default: 0.1 - * - * @param {double} vanishingTimeFactor From 0 to 1. Lifetime factor at which the ray ends the steady phase and begins vanishing. For example, 0.9 means it is vanishing 1/10 of its lifetime. Default: 0.9 - * - * @param {double} subrayPeriod Subrays cycle periodically. This is their time period. Default: 4 - * - * @param {double} subrayDutyCycle From 0 to 1. This is the fraction of time a subray is active. Default: 0.6 - * - * - * These parameters cannot change after lightning creation: - * - * @param {integer} maxIterations: Greater than 0. The number of ray's leaf segments is 2**maxIterations. Default: 9 - * - * @param {boolean} isStatic Set to true only for rays which won't change over time and are not attached to moving objects (Rare case). It is used to set the vertex buffers non-dynamic. You can omit calling update() for these rays. - * - * @param {integer} ramification Greater than 0. Maximum number of child subrays a subray can have. Default: 5 - * - * @param {integer} maxSubrayRecursion Greater than 0. Maximum level of recursion (subray descendant generations). Default: 3 - * - * @param {double} recursionProbability From 0 to 1. The lower the value, the less chance each new generation of subrays has to generate new subrays. Default: 0.6 - * - * @param {boolean} generateUVs If true, the ray geometry will have uv coordinates generated. u runs along the ray, and v across its perimeter. Default: false. - * - * @param {Object} randomGenerator Set here your random number generator which will seed the SimplexNoise and other decisions during ray tree creation. - * It can be used to generate repeatable rays. For that, set also the noiseSeed parameter, and each ray created with that generator and seed pair will be identical in time. - * The randomGenerator parameter should be an object with a random() function similar to Math.random, but seedable. - * It must have also a getSeed() method, which returns the current seed, and a setSeed( seed ) method, which accepts as seed a fractional number from 0 to 1, as well as any other number. - * The default value is an internal generator for some uses and Math.random for others (It is non-repeatable even if noiseSeed is supplied) - * - * @param {double} noiseSeed Seed used to make repeatable rays (see the randomGenerator) - * - * @param {function} onDecideSubrayCreation Set this to change the callback which decides subray creation. You can look at the default callback in the code (createDefaultSubrayCreationCallbacks)for more info. - * - * @param {function} onSubrayCreation This is another callback, more simple than the previous one. It can be used to adapt the form of subrays or other parameters once a subray has been created and initialized. It is used in the examples to adapt subrays to a sphere or to a plane. - * - * - */ - -class LightningStrike extends BufferGeometry { - constructor(rayParameters) { - super(); - this.type = 'LightningStrike'; // Set parameters, and set undefined parameters to default values - - rayParameters = rayParameters || {}; - this.init(LightningStrike.copyParameters(rayParameters, rayParameters)); // Creates and populates the mesh - - this.createMesh(); - } - - update(time) { - if (this.isStatic) return; - - if (this.rayParameters.isEternal || this.rayParameters.birthTime <= time && time <= this.rayParameters.deathTime) { - this.updateMesh(time); - - if (time < this.subrays[0].endPropagationTime) { - this.state = LightningStrike.RAY_PROPAGATING; - } else if (time > this.subrays[0].beginVanishingTime) { - this.state = LightningStrike.RAY_VANISHING; - } else { - this.state = LightningStrike.RAY_STEADY; - } - - this.visible = true; - } else { - this.visible = false; - - if (time < this.rayParameters.birthTime) { - this.state = LightningStrike.RAY_UNBORN; - } else { - this.state = LightningStrike.RAY_EXTINGUISHED; - } - } - } - - init(rayParameters) { - // Init all the state from the parameters - this.rayParameters = rayParameters; // These parameters cannot change after lightning creation: - - this.maxIterations = rayParameters.maxIterations !== undefined ? Math.floor(rayParameters.maxIterations) : 9; - rayParameters.maxIterations = this.maxIterations; - this.isStatic = rayParameters.isStatic !== undefined ? rayParameters.isStatic : false; - rayParameters.isStatic = this.isStatic; - this.ramification = rayParameters.ramification !== undefined ? Math.floor(rayParameters.ramification) : 5; - rayParameters.ramification = this.ramification; - this.maxSubrayRecursion = rayParameters.maxSubrayRecursion !== undefined ? Math.floor(rayParameters.maxSubrayRecursion) : 3; - rayParameters.maxSubrayRecursion = this.maxSubrayRecursion; - this.recursionProbability = rayParameters.recursionProbability !== undefined ? rayParameters.recursionProbability : 0.6; - rayParameters.recursionProbability = this.recursionProbability; - this.generateUVs = rayParameters.generateUVs !== undefined ? rayParameters.generateUVs : false; - rayParameters.generateUVs = this.generateUVs; // Random generator - - if (rayParameters.randomGenerator !== undefined) { - this.randomGenerator = rayParameters.randomGenerator; - this.seedGenerator = rayParameters.randomGenerator; - - if (rayParameters.noiseSeed !== undefined) { - this.seedGenerator.setSeed(rayParameters.noiseSeed); - } - } else { - this.randomGenerator = LightningStrike.createRandomGenerator(); - this.seedGenerator = Math; - } // Ray creation callbacks - - - if (rayParameters.onDecideSubrayCreation !== undefined) { - this.onDecideSubrayCreation = rayParameters.onDecideSubrayCreation; - } else { - this.createDefaultSubrayCreationCallbacks(); - - if (rayParameters.onSubrayCreation !== undefined) { - this.onSubrayCreation = rayParameters.onSubrayCreation; - } - } // Internal state - - - this.state = LightningStrike.RAY_INITIALIZED; - this.maxSubrays = Math.ceil(1 + Math.pow(this.ramification, Math.max(0, this.maxSubrayRecursion - 1))); - rayParameters.maxSubrays = this.maxSubrays; - this.maxRaySegments = 2 * (1 << this.maxIterations); - this.subrays = []; - - for (let i = 0; i < this.maxSubrays; i++) { - this.subrays.push(this.createSubray()); - } - - this.raySegments = []; - - for (let i = 0; i < this.maxRaySegments; i++) { - this.raySegments.push(this.createSegment()); - } - - this.time = 0; - this.timeFraction = 0; - this.currentSegmentCallback = null; - this.currentCreateTriangleVertices = this.generateUVs ? this.createTriangleVerticesWithUVs : this.createTriangleVerticesWithoutUVs; - this.numSubrays = 0; - this.currentSubray = null; - this.currentSegmentIndex = 0; - this.isInitialSegment = false; - this.subrayProbability = 0; - this.currentVertex = 0; - this.currentIndex = 0; - this.currentCoordinate = 0; - this.currentUVCoordinate = 0; - this.vertices = null; - this.uvs = null; - this.indices = null; - this.positionAttribute = null; - this.uvsAttribute = null; - this.simplexX = new SimplexNoise(this.seedGenerator); - this.simplexY = new SimplexNoise(this.seedGenerator); - this.simplexZ = new SimplexNoise(this.seedGenerator); // Temp vectors - - this.forwards = new Vector3(); - this.forwardsFill = new Vector3(); - this.side = new Vector3(); - this.down = new Vector3(); - this.middlePos = new Vector3(); - this.middleLinPos = new Vector3(); - this.newPos = new Vector3(); - this.vPos = new Vector3(); - this.cross1 = new Vector3(); - } - - createMesh() { - const maxDrawableSegmentsPerSubRay = 1 << this.maxIterations; - const maxVerts = 3 * (maxDrawableSegmentsPerSubRay + 1) * this.maxSubrays; - const maxIndices = 18 * maxDrawableSegmentsPerSubRay * this.maxSubrays; - this.vertices = new Float32Array(maxVerts * 3); - this.indices = new Uint32Array(maxIndices); - - if (this.generateUVs) { - this.uvs = new Float32Array(maxVerts * 2); - } // Populate the mesh - - - this.fillMesh(0); - this.setIndex(new Uint32BufferAttribute(this.indices, 1)); - this.positionAttribute = new Float32BufferAttribute(this.vertices, 3); - this.setAttribute('position', this.positionAttribute); - - if (this.generateUVs) { - this.uvsAttribute = new Float32BufferAttribute(new Float32Array(this.uvs), 2); - this.setAttribute('uv', this.uvsAttribute); - } - - if (!this.isStatic) { - this.index.usage = DynamicDrawUsage; - this.positionAttribute.usage = DynamicDrawUsage; - - if (this.generateUVs) { - this.uvsAttribute.usage = DynamicDrawUsage; - } - } // Store buffers for later modification - - - this.vertices = this.positionAttribute.array; - this.indices = this.index.array; - - if (this.generateUVs) { - this.uvs = this.uvsAttribute.array; - } - } - - updateMesh(time) { - this.fillMesh(time); - this.drawRange.count = this.currentIndex; - this.index.needsUpdate = true; - this.positionAttribute.needsUpdate = true; - - if (this.generateUVs) { - this.uvsAttribute.needsUpdate = true; - } - } - - fillMesh(time) { - const scope = this; - this.currentVertex = 0; - this.currentIndex = 0; - this.currentCoordinate = 0; - this.currentUVCoordinate = 0; - this.fractalRay(time, function fillVertices(segment) { - const subray = scope.currentSubray; - - if (time < subray.birthTime) { - //&& ( ! this.rayParameters.isEternal || scope.currentSubray.recursion > 0 ) ) { - return; - } else if (this.rayParameters.isEternal && scope.currentSubray.recursion == 0) { - // Eternal rays don't propagate nor vanish, but its subrays do - scope.createPrism(segment); - scope.onDecideSubrayCreation(segment, scope); - } else if (time < subray.endPropagationTime) { - if (scope.timeFraction >= segment.fraction0 * subray.propagationTimeFactor) { - // Ray propagation has arrived to this segment - scope.createPrism(segment); - scope.onDecideSubrayCreation(segment, scope); - } - } else if (time < subray.beginVanishingTime) { - // Ray is steady (nor propagating nor vanishing) - scope.createPrism(segment); - scope.onDecideSubrayCreation(segment, scope); - } else { - if (scope.timeFraction <= subray.vanishingTimeFactor + segment.fraction1 * (1 - subray.vanishingTimeFactor)) { - // Segment has not yet vanished - scope.createPrism(segment); - } - - scope.onDecideSubrayCreation(segment, scope); - } - }); - } - - addNewSubray() - /*rayParameters*/ - { - return this.subrays[this.numSubrays++]; - } - - initSubray(subray, rayParameters) { - subray.pos0.copy(rayParameters.sourceOffset); - subray.pos1.copy(rayParameters.destOffset); - subray.up0.copy(rayParameters.up0); - subray.up1.copy(rayParameters.up1); - subray.radius0 = rayParameters.radius0; - subray.radius1 = rayParameters.radius1; - subray.birthTime = rayParameters.birthTime; - subray.deathTime = rayParameters.deathTime; - subray.timeScale = rayParameters.timeScale; - subray.roughness = rayParameters.roughness; - subray.straightness = rayParameters.straightness; - subray.propagationTimeFactor = rayParameters.propagationTimeFactor; - subray.vanishingTimeFactor = rayParameters.vanishingTimeFactor; - subray.maxIterations = this.maxIterations; - subray.seed = rayParameters.noiseSeed !== undefined ? rayParameters.noiseSeed : 0; - subray.recursion = 0; - } - - fractalRay(time, segmentCallback) { - this.time = time; - this.currentSegmentCallback = segmentCallback; - this.numSubrays = 0; // Add the top level subray - - this.initSubray(this.addNewSubray(), this.rayParameters); // Process all subrays that are being generated until consuming all of them - - for (let subrayIndex = 0; subrayIndex < this.numSubrays; subrayIndex++) { - const subray = this.subrays[subrayIndex]; - this.currentSubray = subray; - this.randomGenerator.setSeed(subray.seed); - subray.endPropagationTime = MathUtils.lerp(subray.birthTime, subray.deathTime, subray.propagationTimeFactor); - subray.beginVanishingTime = MathUtils.lerp(subray.deathTime, subray.birthTime, 1 - subray.vanishingTimeFactor); - const random1 = this.randomGenerator.random; - subray.linPos0.set(random1(), random1(), random1()).multiplyScalar(1000); - subray.linPos1.set(random1(), random1(), random1()).multiplyScalar(1000); - this.timeFraction = (time - subray.birthTime) / (subray.deathTime - subray.birthTime); - this.currentSegmentIndex = 0; - this.isInitialSegment = true; - const segment = this.getNewSegment(); - segment.iteration = 0; - segment.pos0.copy(subray.pos0); - segment.pos1.copy(subray.pos1); - segment.linPos0.copy(subray.linPos0); - segment.linPos1.copy(subray.linPos1); - segment.up0.copy(subray.up0); - segment.up1.copy(subray.up1); - segment.radius0 = subray.radius0; - segment.radius1 = subray.radius1; - segment.fraction0 = 0; - segment.fraction1 = 1; - segment.positionVariationFactor = 1 - subray.straightness; - this.subrayProbability = this.ramification * Math.pow(this.recursionProbability, subray.recursion) / (1 << subray.maxIterations); - this.fractalRayRecursive(segment); - } - - this.currentSegmentCallback = null; - this.currentSubray = null; - } - - fractalRayRecursive(segment) { - // Leave recursion condition - if (segment.iteration >= this.currentSubray.maxIterations) { - this.currentSegmentCallback(segment); - return; - } // Interpolation - - - this.forwards.subVectors(segment.pos1, segment.pos0); - let lForwards = this.forwards.length(); - - if (lForwards < 0.000001) { - this.forwards.set(0, 0, 0.01); - lForwards = this.forwards.length(); - } - - const middleRadius = (segment.radius0 + segment.radius1) * 0.5; - const middleFraction = (segment.fraction0 + segment.fraction1) * 0.5; - const timeDimension = this.time * this.currentSubray.timeScale * Math.pow(2, segment.iteration); - this.middlePos.lerpVectors(segment.pos0, segment.pos1, 0.5); - this.middleLinPos.lerpVectors(segment.linPos0, segment.linPos1, 0.5); - const p = this.middleLinPos; // Noise - - this.newPos.set(this.simplexX.noise4d(p.x, p.y, p.z, timeDimension), this.simplexY.noise4d(p.x, p.y, p.z, timeDimension), this.simplexZ.noise4d(p.x, p.y, p.z, timeDimension)); - this.newPos.multiplyScalar(segment.positionVariationFactor * lForwards); - this.newPos.add(this.middlePos); // Recursion - - const newSegment1 = this.getNewSegment(); - newSegment1.pos0.copy(segment.pos0); - newSegment1.pos1.copy(this.newPos); - newSegment1.linPos0.copy(segment.linPos0); - newSegment1.linPos1.copy(this.middleLinPos); - newSegment1.up0.copy(segment.up0); - newSegment1.up1.copy(segment.up1); - newSegment1.radius0 = segment.radius0; - newSegment1.radius1 = middleRadius; - newSegment1.fraction0 = segment.fraction0; - newSegment1.fraction1 = middleFraction; - newSegment1.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; - newSegment1.iteration = segment.iteration + 1; - const newSegment2 = this.getNewSegment(); - newSegment2.pos0.copy(this.newPos); - newSegment2.pos1.copy(segment.pos1); - newSegment2.linPos0.copy(this.middleLinPos); - newSegment2.linPos1.copy(segment.linPos1); - this.cross1.crossVectors(segment.up0, this.forwards.normalize()); - newSegment2.up0.crossVectors(this.forwards, this.cross1).normalize(); - newSegment2.up1.copy(segment.up1); - newSegment2.radius0 = middleRadius; - newSegment2.radius1 = segment.radius1; - newSegment2.fraction0 = middleFraction; - newSegment2.fraction1 = segment.fraction1; - newSegment2.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; - newSegment2.iteration = segment.iteration + 1; - this.fractalRayRecursive(newSegment1); - this.fractalRayRecursive(newSegment2); - } - - createPrism(segment) { - // Creates one triangular prism and its vertices at the segment - this.forwardsFill.subVectors(segment.pos1, segment.pos0).normalize(); - - if (this.isInitialSegment) { - this.currentCreateTriangleVertices(segment.pos0, segment.up0, this.forwardsFill, segment.radius0, 0); - this.isInitialSegment = false; - } - - this.currentCreateTriangleVertices(segment.pos1, segment.up0, this.forwardsFill, segment.radius1, segment.fraction1); - this.createPrismFaces(); - } - - createTriangleVerticesWithoutUVs(pos, up, forwards, radius) { - // Create an equilateral triangle (only vertices) - this.side.crossVectors(up, forwards).multiplyScalar(radius * LightningStrike.COS30DEG); - this.down.copy(up).multiplyScalar(-radius * LightningStrike.SIN30DEG); - const p = this.vPos; - const v = this.vertices; - p.copy(pos).sub(this.side).add(this.down); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - p.copy(pos).add(this.side).add(this.down); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - p.copy(up).multiplyScalar(radius).add(pos); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - this.currentVertex += 3; - } - - createTriangleVerticesWithUVs(pos, up, forwards, radius, u) { - // Create an equilateral triangle (only vertices) - this.side.crossVectors(up, forwards).multiplyScalar(radius * LightningStrike.COS30DEG); - this.down.copy(up).multiplyScalar(-radius * LightningStrike.SIN30DEG); - const p = this.vPos; - const v = this.vertices; - const uv = this.uvs; - p.copy(pos).sub(this.side).add(this.down); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - uv[this.currentUVCoordinate++] = u; - uv[this.currentUVCoordinate++] = 0; - p.copy(pos).add(this.side).add(this.down); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - uv[this.currentUVCoordinate++] = u; - uv[this.currentUVCoordinate++] = 0.5; - p.copy(up).multiplyScalar(radius).add(pos); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - uv[this.currentUVCoordinate++] = u; - uv[this.currentUVCoordinate++] = 1; - this.currentVertex += 3; - } - - createPrismFaces(vertex - /*, index*/ - ) { - const indices = this.indices; - var vertex = this.currentVertex - 6; - indices[this.currentIndex++] = vertex + 1; - indices[this.currentIndex++] = vertex + 2; - indices[this.currentIndex++] = vertex + 5; - indices[this.currentIndex++] = vertex + 1; - indices[this.currentIndex++] = vertex + 5; - indices[this.currentIndex++] = vertex + 4; - indices[this.currentIndex++] = vertex + 0; - indices[this.currentIndex++] = vertex + 1; - indices[this.currentIndex++] = vertex + 4; - indices[this.currentIndex++] = vertex + 0; - indices[this.currentIndex++] = vertex + 4; - indices[this.currentIndex++] = vertex + 3; - indices[this.currentIndex++] = vertex + 2; - indices[this.currentIndex++] = vertex + 0; - indices[this.currentIndex++] = vertex + 3; - indices[this.currentIndex++] = vertex + 2; - indices[this.currentIndex++] = vertex + 3; - indices[this.currentIndex++] = vertex + 5; - } - - createDefaultSubrayCreationCallbacks() { - const random1 = this.randomGenerator.random; - - this.onDecideSubrayCreation = (segment, lightningStrike) => { - // Decide subrays creation at parent (sub)ray segment - const subray = lightningStrike.currentSubray; - const period = lightningStrike.rayParameters.subrayPeriod; - const dutyCycle = lightningStrike.rayParameters.subrayDutyCycle; - const phase0 = lightningStrike.rayParameters.isEternal && subray.recursion == 0 ? -random1() * period : MathUtils.lerp(subray.birthTime, subray.endPropagationTime, segment.fraction0) - random1() * period; - const phase = lightningStrike.time - phase0; - const currentCycle = Math.floor(phase / period); - const childSubraySeed = random1() * (currentCycle + 1); - const isActive = phase % period <= dutyCycle * period; - let probability = 0; - - if (isActive) { - probability = lightningStrike.subrayProbability; // Distribution test: probability *= segment.fraction0 > 0.5 && segment.fraction0 < 0.9 ? 1 / 0.4 : 0; - } - - if (subray.recursion < lightningStrike.maxSubrayRecursion && lightningStrike.numSubrays < lightningStrike.maxSubrays && random1() < probability) { - const childSubray = lightningStrike.addNewSubray(); - const parentSeed = lightningStrike.randomGenerator.getSeed(); - childSubray.seed = childSubraySeed; - lightningStrike.randomGenerator.setSeed(childSubraySeed); - childSubray.recursion = subray.recursion + 1; - childSubray.maxIterations = Math.max(1, subray.maxIterations - 1); - childSubray.linPos0.set(random1(), random1(), random1()).multiplyScalar(1000); - childSubray.linPos1.set(random1(), random1(), random1()).multiplyScalar(1000); - childSubray.up0.copy(subray.up0); - childSubray.up1.copy(subray.up1); - childSubray.radius0 = segment.radius0 * lightningStrike.rayParameters.radius0Factor; - childSubray.radius1 = Math.min(lightningStrike.rayParameters.minRadius, segment.radius1 * lightningStrike.rayParameters.radius1Factor); - childSubray.birthTime = phase0 + currentCycle * period; - childSubray.deathTime = childSubray.birthTime + period * dutyCycle; - - if (!lightningStrike.rayParameters.isEternal && subray.recursion == 0) { - childSubray.birthTime = Math.max(childSubray.birthTime, subray.birthTime); - childSubray.deathTime = Math.min(childSubray.deathTime, subray.deathTime); - } - - childSubray.timeScale = subray.timeScale * 2; - childSubray.roughness = subray.roughness; - childSubray.straightness = subray.straightness; - childSubray.propagationTimeFactor = subray.propagationTimeFactor; - childSubray.vanishingTimeFactor = subray.vanishingTimeFactor; - lightningStrike.onSubrayCreation(segment, subray, childSubray, lightningStrike); - lightningStrike.randomGenerator.setSeed(parentSeed); - } - }; - - const vec1Pos = new Vector3(); - const vec2Forward = new Vector3(); - const vec3Side = new Vector3(); - const vec4Up = new Vector3(); - - this.onSubrayCreation = (segment, parentSubray, childSubray, lightningStrike) => { - // Decide childSubray origin and destination positions (pos0 and pos1) and possibly other properties of childSubray - // Just use the default cone position generator - lightningStrike.subrayCylinderPosition(segment, parentSubray, childSubray, 0.5, 0.6, 0.2); - }; - - this.subrayConePosition = (segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor) => { - // Sets childSubray pos0 and pos1 in a cone - childSubray.pos0.copy(segment.pos0); - vec1Pos.subVectors(parentSubray.pos1, parentSubray.pos0); - vec2Forward.copy(vec1Pos).normalize(); - vec1Pos.multiplyScalar(segment.fraction0 + (1 - segment.fraction0) * (random1() * heightFactor)); - const length = vec1Pos.length(); - vec3Side.crossVectors(parentSubray.up0, vec2Forward); - const angle = 2 * Math.PI * random1(); - vec3Side.multiplyScalar(Math.cos(angle)); - vec4Up.copy(parentSubray.up0).multiplyScalar(Math.sin(angle)); - childSubray.pos1.copy(vec3Side).add(vec4Up).multiplyScalar(length * sideWidthFactor * (minSideWidthFactor + random1() * (1 - minSideWidthFactor))).add(vec1Pos).add(parentSubray.pos0); - }; - - this.subrayCylinderPosition = (segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor) => { - // Sets childSubray pos0 and pos1 in a cylinder - childSubray.pos0.copy(segment.pos0); - vec1Pos.subVectors(parentSubray.pos1, parentSubray.pos0); - vec2Forward.copy(vec1Pos).normalize(); - vec1Pos.multiplyScalar(segment.fraction0 + (1 - segment.fraction0) * ((2 * random1() - 1) * heightFactor)); - const length = vec1Pos.length(); - vec3Side.crossVectors(parentSubray.up0, vec2Forward); - const angle = 2 * Math.PI * random1(); - vec3Side.multiplyScalar(Math.cos(angle)); - vec4Up.copy(parentSubray.up0).multiplyScalar(Math.sin(angle)); - childSubray.pos1.copy(vec3Side).add(vec4Up).multiplyScalar(length * sideWidthFactor * (minSideWidthFactor + random1() * (1 - minSideWidthFactor))).add(vec1Pos).add(parentSubray.pos0); - }; - } - - createSubray() { - return { - seed: 0, - maxIterations: 0, - recursion: 0, - pos0: new Vector3(), - pos1: new Vector3(), - linPos0: new Vector3(), - linPos1: new Vector3(), - up0: new Vector3(), - up1: new Vector3(), - radius0: 0, - radius1: 0, - birthTime: 0, - deathTime: 0, - timeScale: 0, - roughness: 0, - straightness: 0, - propagationTimeFactor: 0, - vanishingTimeFactor: 0, - endPropagationTime: 0, - beginVanishingTime: 0 - }; - } - - createSegment() { - return { - iteration: 0, - pos0: new Vector3(), - pos1: new Vector3(), - linPos0: new Vector3(), - linPos1: new Vector3(), - up0: new Vector3(), - up1: new Vector3(), - radius0: 0, - radius1: 0, - fraction0: 0, - fraction1: 0, - positionVariationFactor: 0 - }; - } - - getNewSegment() { - return this.raySegments[this.currentSegmentIndex++]; - } - - copy(source) { - super.copy(source); - this.init(LightningStrike.copyParameters({}, source.rayParameters)); - return this; - } +var THREE = /*#__PURE__*/Object.freeze({ + __proto__: null, + ACESFilmicToneMapping: ACESFilmicToneMapping, + AddEquation: AddEquation, + AddOperation: AddOperation, + AdditiveAnimationBlendMode: AdditiveAnimationBlendMode, + AdditiveBlending: AdditiveBlending, + AlphaFormat: AlphaFormat, + AlwaysDepth: AlwaysDepth, + AlwaysStencilFunc: AlwaysStencilFunc, + AmbientLight: AmbientLight$1, + AmbientLightProbe: AmbientLightProbe, + AnimationClip: AnimationClip, + AnimationLoader: AnimationLoader, + AnimationMixer: AnimationMixer, + AnimationObjectGroup: AnimationObjectGroup, + AnimationUtils: AnimationUtils, + ArcCurve: ArcCurve, + ArrayCamera: ArrayCamera, + ArrowHelper: ArrowHelper, + Audio: Audio, + AudioAnalyser: AudioAnalyser, + AudioContext: AudioContext, + AudioListener: AudioListener, + AudioLoader: AudioLoader, + AxesHelper: AxesHelper, + BackSide: BackSide, + BasicDepthPacking: BasicDepthPacking, + BasicShadowMap: BasicShadowMap, + Bone: Bone, + BooleanKeyframeTrack: BooleanKeyframeTrack, + Box2: Box2, + Box3: Box3, + Box3Helper: Box3Helper, + BoxBufferGeometry: BoxGeometry, + BoxGeometry: BoxGeometry, + BoxHelper: BoxHelper, + BufferAttribute: BufferAttribute, + BufferGeometry: BufferGeometry, + BufferGeometryLoader: BufferGeometryLoader, + ByteType: ByteType, + Cache: Cache, + Camera: Camera, + CameraHelper: CameraHelper, + CanvasTexture: CanvasTexture, + CapsuleBufferGeometry: CapsuleGeometry, + CapsuleGeometry: CapsuleGeometry, + CatmullRomCurve3: CatmullRomCurve3, + CineonToneMapping: CineonToneMapping, + CircleBufferGeometry: CircleGeometry, + CircleGeometry: CircleGeometry, + ClampToEdgeWrapping: ClampToEdgeWrapping, + Clock: Clock, + Color: Color, + ColorKeyframeTrack: ColorKeyframeTrack, + ColorManagement: ColorManagement, + CompressedTexture: CompressedTexture, + CompressedTextureLoader: CompressedTextureLoader, + ConeBufferGeometry: ConeGeometry, + ConeGeometry: ConeGeometry, + CubeCamera: CubeCamera, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + CubeTexture: CubeTexture, + CubeTextureLoader: CubeTextureLoader, + CubeUVReflectionMapping: CubeUVReflectionMapping, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + CubicInterpolant: CubicInterpolant, + CullFaceBack: CullFaceBack, + CullFaceFront: CullFaceFront, + CullFaceFrontBack: CullFaceFrontBack, + CullFaceNone: CullFaceNone, + Curve: Curve, + CurvePath: CurvePath, + CustomBlending: CustomBlending, + CustomToneMapping: CustomToneMapping, + CylinderBufferGeometry: CylinderGeometry, + CylinderGeometry: CylinderGeometry, + Cylindrical: Cylindrical, + Data3DTexture: Data3DTexture, + DataArrayTexture: DataArrayTexture, + DataTexture: DataTexture, + DataTexture2DArray: DataTexture2DArray, + DataTexture3D: DataTexture3D, + DataTextureLoader: DataTextureLoader, + DataUtils: DataUtils, + DecrementStencilOp: DecrementStencilOp, + DecrementWrapStencilOp: DecrementWrapStencilOp, + DefaultLoadingManager: DefaultLoadingManager, + DepthFormat: DepthFormat, + DepthStencilFormat: DepthStencilFormat, + DepthTexture: DepthTexture, + DirectionalLight: DirectionalLight$1, + DirectionalLightHelper: DirectionalLightHelper, + DiscreteInterpolant: DiscreteInterpolant, + DodecahedronBufferGeometry: DodecahedronGeometry, + DodecahedronGeometry: DodecahedronGeometry, + DoubleSide: DoubleSide, + DstAlphaFactor: DstAlphaFactor, + DstColorFactor: DstColorFactor, + DynamicCopyUsage: DynamicCopyUsage, + DynamicDrawUsage: DynamicDrawUsage, + DynamicReadUsage: DynamicReadUsage, + EdgesGeometry: EdgesGeometry, + EllipseCurve: EllipseCurve, + EqualDepth: EqualDepth, + EqualStencilFunc: EqualStencilFunc, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + Euler: Euler, + EventDispatcher: EventDispatcher, + ExtrudeBufferGeometry: ExtrudeGeometry, + ExtrudeGeometry: ExtrudeGeometry, + FileLoader: FileLoader, + FlatShading: FlatShading, + Float16BufferAttribute: Float16BufferAttribute, + Float32BufferAttribute: Float32BufferAttribute, + Float64BufferAttribute: Float64BufferAttribute, + FloatType: FloatType, + Fog: Fog, + FogExp2: FogExp2, + Font: Font, + FontLoader: FontLoader, + FramebufferTexture: FramebufferTexture, + FrontSide: FrontSide, + Frustum: Frustum, + GLBufferAttribute: GLBufferAttribute, + GLSL1: GLSL1, + GLSL3: GLSL3, + GreaterDepth: GreaterDepth, + GreaterEqualDepth: GreaterEqualDepth, + GreaterEqualStencilFunc: GreaterEqualStencilFunc, + GreaterStencilFunc: GreaterStencilFunc, + GridHelper: GridHelper, + Group: Group, + HalfFloatType: HalfFloatType, + HemisphereLight: HemisphereLight, + HemisphereLightHelper: HemisphereLightHelper, + HemisphereLightProbe: HemisphereLightProbe, + IcosahedronBufferGeometry: IcosahedronGeometry, + IcosahedronGeometry: IcosahedronGeometry, + ImageBitmapLoader: ImageBitmapLoader, + ImageLoader: ImageLoader, + ImageUtils: ImageUtils, + ImmediateRenderObject: ImmediateRenderObject, + IncrementStencilOp: IncrementStencilOp, + IncrementWrapStencilOp: IncrementWrapStencilOp, + InstancedBufferAttribute: InstancedBufferAttribute, + InstancedBufferGeometry: InstancedBufferGeometry, + InstancedInterleavedBuffer: InstancedInterleavedBuffer, + InstancedMesh: InstancedMesh, + Int16BufferAttribute: Int16BufferAttribute, + Int32BufferAttribute: Int32BufferAttribute, + Int8BufferAttribute: Int8BufferAttribute, + IntType: IntType, + InterleavedBuffer: InterleavedBuffer, + InterleavedBufferAttribute: InterleavedBufferAttribute, + Interpolant: Interpolant, + InterpolateDiscrete: InterpolateDiscrete, + InterpolateLinear: InterpolateLinear, + InterpolateSmooth: InterpolateSmooth, + InvertStencilOp: InvertStencilOp, + KeepStencilOp: KeepStencilOp, + KeyframeTrack: KeyframeTrack, + LOD: LOD, + LatheBufferGeometry: LatheGeometry, + LatheGeometry: LatheGeometry, + Layers: Layers, + LessDepth: LessDepth, + LessEqualDepth: LessEqualDepth, + LessEqualStencilFunc: LessEqualStencilFunc, + LessStencilFunc: LessStencilFunc, + Light: Light, + LightProbe: LightProbe, + Line: Line$2, + Line3: Line3, + LineBasicMaterial: LineBasicMaterial, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + LineDashedMaterial: LineDashedMaterial, + LineLoop: LineLoop, + LineSegments: LineSegments, + LinearEncoding: LinearEncoding, + LinearFilter: LinearFilter, + LinearInterpolant: LinearInterpolant, + LinearMipMapLinearFilter: LinearMipMapLinearFilter, + LinearMipMapNearestFilter: LinearMipMapNearestFilter, + LinearMipmapLinearFilter: LinearMipmapLinearFilter, + LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearSRGBColorSpace: LinearSRGBColorSpace, + LinearToneMapping: LinearToneMapping, + Loader: Loader, + LoaderUtils: LoaderUtils, + LoadingManager: LoadingManager, + LoopOnce: LoopOnce, + LoopPingPong: LoopPingPong, + LoopRepeat: LoopRepeat, + LuminanceAlphaFormat: LuminanceAlphaFormat, + LuminanceFormat: LuminanceFormat, + MOUSE: MOUSE, + Material: Material, + MaterialLoader: MaterialLoader, + MathUtils: MathUtils, + Matrix3: Matrix3, + Matrix4: Matrix4, + MaxEquation: MaxEquation, + Mesh: Mesh, + MeshBasicMaterial: MeshBasicMaterial, + MeshDepthMaterial: MeshDepthMaterial, + MeshDistanceMaterial: MeshDistanceMaterial, + MeshLambertMaterial: MeshLambertMaterial, + MeshMatcapMaterial: MeshMatcapMaterial, + MeshNormalMaterial: MeshNormalMaterial, + MeshPhongMaterial: MeshPhongMaterial, + MeshPhysicalMaterial: MeshPhysicalMaterial, + MeshStandardMaterial: MeshStandardMaterial, + MeshToonMaterial: MeshToonMaterial, + MinEquation: MinEquation, + MirroredRepeatWrapping: MirroredRepeatWrapping, + MixOperation: MixOperation, + MultiplyBlending: MultiplyBlending, + MultiplyOperation: MultiplyOperation, + NearestFilter: NearestFilter, + NearestMipMapLinearFilter: NearestMipMapLinearFilter, + NearestMipMapNearestFilter: NearestMipMapNearestFilter, + NearestMipmapLinearFilter: NearestMipmapLinearFilter, + NearestMipmapNearestFilter: NearestMipmapNearestFilter, + NeverDepth: NeverDepth, + NeverStencilFunc: NeverStencilFunc, + NoBlending: NoBlending, + NoColorSpace: NoColorSpace, + NoToneMapping: NoToneMapping, + NormalAnimationBlendMode: NormalAnimationBlendMode, + NormalBlending: NormalBlending, + NotEqualDepth: NotEqualDepth, + NotEqualStencilFunc: NotEqualStencilFunc, + NumberKeyframeTrack: NumberKeyframeTrack, + Object3D: Object3D, + ObjectLoader: ObjectLoader, + ObjectSpaceNormalMap: ObjectSpaceNormalMap, + OctahedronBufferGeometry: OctahedronGeometry, + OctahedronGeometry: OctahedronGeometry, + OneFactor: OneFactor, + OneMinusDstAlphaFactor: OneMinusDstAlphaFactor, + OneMinusDstColorFactor: OneMinusDstColorFactor, + OneMinusSrcAlphaFactor: OneMinusSrcAlphaFactor, + OneMinusSrcColorFactor: OneMinusSrcColorFactor, + OrthographicCamera: OrthographicCamera, + PCFShadowMap: PCFShadowMap, + PCFSoftShadowMap: PCFSoftShadowMap, + PMREMGenerator: PMREMGenerator, + ParametricGeometry: ParametricGeometry, + Path: Path, + PerspectiveCamera: PerspectiveCamera, + Plane: Plane, + PlaneBufferGeometry: PlaneGeometry, + PlaneGeometry: PlaneGeometry, + PlaneHelper: PlaneHelper, + PointLight: PointLight, + PointLightHelper: PointLightHelper, + Points: Points, + PointsMaterial: PointsMaterial, + PolarGridHelper: PolarGridHelper, + PolyhedronBufferGeometry: PolyhedronGeometry, + PolyhedronGeometry: PolyhedronGeometry, + PositionalAudio: PositionalAudio, + PropertyBinding: PropertyBinding, + PropertyMixer: PropertyMixer, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + Quaternion: Quaternion, + QuaternionKeyframeTrack: QuaternionKeyframeTrack, + QuaternionLinearInterpolant: QuaternionLinearInterpolant, + REVISION: REVISION, + RGBADepthPacking: RGBADepthPacking, + RGBAFormat: RGBAFormat, + RGBAIntegerFormat: RGBAIntegerFormat, + RGBA_ASTC_10x10_Format: RGBA_ASTC_10x10_Format, + RGBA_ASTC_10x5_Format: RGBA_ASTC_10x5_Format, + RGBA_ASTC_10x6_Format: RGBA_ASTC_10x6_Format, + RGBA_ASTC_10x8_Format: RGBA_ASTC_10x8_Format, + RGBA_ASTC_12x10_Format: RGBA_ASTC_12x10_Format, + RGBA_ASTC_12x12_Format: RGBA_ASTC_12x12_Format, + RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format, + RGBA_ASTC_5x4_Format: RGBA_ASTC_5x4_Format, + RGBA_ASTC_5x5_Format: RGBA_ASTC_5x5_Format, + RGBA_ASTC_6x5_Format: RGBA_ASTC_6x5_Format, + RGBA_ASTC_6x6_Format: RGBA_ASTC_6x6_Format, + RGBA_ASTC_8x5_Format: RGBA_ASTC_8x5_Format, + RGBA_ASTC_8x6_Format: RGBA_ASTC_8x6_Format, + RGBA_ASTC_8x8_Format: RGBA_ASTC_8x8_Format, + RGBA_BPTC_Format: RGBA_BPTC_Format, + RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format, + RGBA_PVRTC_2BPPV1_Format: RGBA_PVRTC_2BPPV1_Format, + RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format, + RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format, + RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format, + RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format, + RGBFormat: RGBFormat, + RGB_ETC1_Format: RGB_ETC1_Format, + RGB_ETC2_Format: RGB_ETC2_Format, + RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format, + RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format, + RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format, + RGFormat: RGFormat, + RGIntegerFormat: RGIntegerFormat, + RawShaderMaterial: RawShaderMaterial, + Ray: Ray, + Raycaster: Raycaster, + RectAreaLight: RectAreaLight, + RedFormat: RedFormat, + RedIntegerFormat: RedIntegerFormat, + ReinhardToneMapping: ReinhardToneMapping, + RepeatWrapping: RepeatWrapping, + ReplaceStencilOp: ReplaceStencilOp, + ReverseSubtractEquation: ReverseSubtractEquation, + RingBufferGeometry: RingGeometry, + RingGeometry: RingGeometry, + SRGBColorSpace: SRGBColorSpace, + Scene: Scene$1, + ShaderChunk: ShaderChunk, + ShaderLib: ShaderLib, + ShaderMaterial: ShaderMaterial, + ShadowMaterial: ShadowMaterial, + Shape: Shape, + ShapeBufferGeometry: ShapeGeometry, + ShapeGeometry: ShapeGeometry, + ShapePath: ShapePath, + ShapeUtils: ShapeUtils, + ShortType: ShortType, + Skeleton: Skeleton, + SkeletonHelper: SkeletonHelper, + SkinnedMesh: SkinnedMesh, + SmoothShading: SmoothShading, + Source: Source, + Sphere: Sphere, + SphereBufferGeometry: SphereGeometry, + SphereGeometry: SphereGeometry, + Spherical: Spherical, + SphericalHarmonics3: SphericalHarmonics3, + SplineCurve: SplineCurve, + SpotLight: SpotLight, + SpotLightHelper: SpotLightHelper, + Sprite: Sprite, + SpriteMaterial: SpriteMaterial, + SrcAlphaFactor: SrcAlphaFactor, + SrcAlphaSaturateFactor: SrcAlphaSaturateFactor, + SrcColorFactor: SrcColorFactor, + StaticCopyUsage: StaticCopyUsage, + StaticDrawUsage: StaticDrawUsage, + StaticReadUsage: StaticReadUsage, + StereoCamera: StereoCamera, + StreamCopyUsage: StreamCopyUsage, + StreamDrawUsage: StreamDrawUsage, + StreamReadUsage: StreamReadUsage, + StringKeyframeTrack: StringKeyframeTrack, + SubtractEquation: SubtractEquation, + SubtractiveBlending: SubtractiveBlending, + TOUCH: TOUCH, + TangentSpaceNormalMap: TangentSpaceNormalMap, + TetrahedronBufferGeometry: TetrahedronGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TextGeometry: TextGeometry, + Texture: Texture, + TextureLoader: TextureLoader, + TorusBufferGeometry: TorusGeometry, + TorusGeometry: TorusGeometry, + TorusKnotBufferGeometry: TorusKnotGeometry, + TorusKnotGeometry: TorusKnotGeometry, + Triangle: Triangle, + TriangleFanDrawMode: TriangleFanDrawMode, + TriangleStripDrawMode: TriangleStripDrawMode, + TrianglesDrawMode: TrianglesDrawMode, + TubeBufferGeometry: TubeGeometry, + TubeGeometry: TubeGeometry, + UVMapping: UVMapping, + Uint16BufferAttribute: Uint16BufferAttribute, + Uint32BufferAttribute: Uint32BufferAttribute, + Uint8BufferAttribute: Uint8BufferAttribute, + Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute, + Uniform: Uniform, + UniformsLib: UniformsLib, + UniformsUtils: UniformsUtils, + UnsignedByteType: UnsignedByteType, + UnsignedInt248Type: UnsignedInt248Type, + UnsignedIntType: UnsignedIntType, + UnsignedShort4444Type: UnsignedShort4444Type, + UnsignedShort5551Type: UnsignedShort5551Type, + UnsignedShortType: UnsignedShortType, + VSMShadowMap: VSMShadowMap, + Vector2: Vector2, + Vector3: Vector3, + Vector4: Vector4, + VectorKeyframeTrack: VectorKeyframeTrack, + VideoTexture: VideoTexture, + WebGL1Renderer: WebGL1Renderer, + WebGL3DRenderTarget: WebGL3DRenderTarget, + WebGLArrayRenderTarget: WebGLArrayRenderTarget, + WebGLCubeRenderTarget: WebGLCubeRenderTarget, + WebGLMultipleRenderTargets: WebGLMultipleRenderTargets, + WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget, + WebGLRenderTarget: WebGLRenderTarget, + WebGLRenderer: WebGLRenderer, + WebGLUtils: WebGLUtils, + WireframeGeometry: WireframeGeometry, + WrapAroundEnding: WrapAroundEnding, + ZeroCurvatureEnding: ZeroCurvatureEnding, + ZeroFactor: ZeroFactor, + ZeroSlopeEnding: ZeroSlopeEnding, + ZeroStencilOp: ZeroStencilOp, + _SRGBAFormat: _SRGBAFormat, + sRGBEncoding: sRGBEncoding +}); - clone() { - return new this.constructor(LightningStrike.copyParameters({}, this.rayParameters)); - } +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } -LightningStrike.prototype.isLightningStrike = true; // Ray states - -LightningStrike.RAY_INITIALIZED = 0; -LightningStrike.RAY_UNBORN = 1; -LightningStrike.RAY_PROPAGATING = 2; -LightningStrike.RAY_STEADY = 3; -LightningStrike.RAY_VANISHING = 4; -LightningStrike.RAY_EXTINGUISHED = 5; -LightningStrike.COS30DEG = Math.cos(30 * Math.PI / 180); -LightningStrike.SIN30DEG = Math.sin(30 * Math.PI / 180); - -LightningStrike.createRandomGenerator = () => { - const numSeeds = 2053; - const seeds = []; - - for (let i = 0; i < numSeeds; i++) { - seeds.push(Math.random()); - } - - const generator = { - currentSeed: 0, - random: function () { - const value = seeds[generator.currentSeed]; - generator.currentSeed = (generator.currentSeed + 1) % numSeeds; - return value; - }, - getSeed: function () { - return generator.currentSeed / numSeeds; - }, - setSeed: function (seed) { - generator.currentSeed = Math.floor(seed * numSeeds) % numSeeds; - } - }; - return generator; -}; - -LightningStrike.copyParameters = (dest, source) => { - source = source || {}; - dest = dest || {}; - - const vecCopy = v => { - if (source === dest) { - return v; - } else { - return v.clone(); - } - }; +var constants = {exports: {}}; - dest.sourceOffset = source.sourceOffset !== undefined ? vecCopy(source.sourceOffset) : new Vector3(0, 100, 0), dest.destOffset = source.destOffset !== undefined ? vecCopy(source.destOffset) : new Vector3(0, 0, 0), dest.timeScale = source.timeScale !== undefined ? source.timeScale : 1, dest.roughness = source.roughness !== undefined ? source.roughness : 0.9, dest.straightness = source.straightness !== undefined ? source.straightness : 0.7, dest.up0 = source.up0 !== undefined ? vecCopy(source.up0) : new Vector3(0, 0, 1); - dest.up1 = source.up1 !== undefined ? vecCopy(source.up1) : new Vector3(0, 0, 1), dest.radius0 = source.radius0 !== undefined ? source.radius0 : 1, dest.radius1 = source.radius1 !== undefined ? source.radius1 : 1, dest.radius0Factor = source.radius0Factor !== undefined ? source.radius0Factor : 0.5, dest.radius1Factor = source.radius1Factor !== undefined ? source.radius1Factor : 0.2, dest.minRadius = source.minRadius !== undefined ? source.minRadius : 0.2, // These parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly: - dest.isEternal = source.isEternal !== undefined ? source.isEternal : source.birthTime === undefined || source.deathTime === undefined, dest.birthTime = source.birthTime, dest.deathTime = source.deathTime, dest.propagationTimeFactor = source.propagationTimeFactor !== undefined ? source.propagationTimeFactor : 0.1, dest.vanishingTimeFactor = source.vanishingTimeFactor !== undefined ? source.vanishingTimeFactor : 0.9, dest.subrayPeriod = source.subrayPeriod !== undefined ? source.subrayPeriod : 4, dest.subrayDutyCycle = source.subrayDutyCycle !== undefined ? source.subrayDutyCycle : 0.6; // These parameters cannot change after lightning creation: - - dest.maxIterations = source.maxIterations !== undefined ? source.maxIterations : 9; - dest.isStatic = source.isStatic !== undefined ? source.isStatic : false; - dest.ramification = source.ramification !== undefined ? source.ramification : 5; - dest.maxSubrayRecursion = source.maxSubrayRecursion !== undefined ? source.maxSubrayRecursion : 3; - dest.recursionProbability = source.recursionProbability !== undefined ? source.recursionProbability : 0.6; - dest.generateUVs = source.generateUVs !== undefined ? source.generateUVs : false; - dest.randomGenerator = source.randomGenerator, dest.noiseSeed = source.noiseSeed, dest.onDecideSubrayCreation = source.onDecideSubrayCreation, dest.onSubrayCreation = source.onSubrayCreation; - return dest; -}; +var reactReconcilerConstants_production_min = {}; /** - * @fileoverview Lightning strike object generator - * - * - * Usage - * - * const myStorm = new LightningStorm( paramsObject ); - * myStorm.position.set( ... ); - * scene.add( myStorm ); - * ... - * myStorm.update( currentTime ); - * - * The "currentTime" can only go forwards or be stopped. - * - * - * LightningStorm parameters: - * - * @param {double} size Size of the storm. If no 'onRayPosition' parameter is defined, it means the side of the rectangle the storm covers. - * - * @param {double} minHeight Minimum height a ray can start at. If no 'onRayPosition' parameter is defined, it means the height above plane y = 0. - * - * @param {double} maxHeight Maximum height a ray can start at. If no 'onRayPosition' parameter is defined, it means the height above plane y = 0. - * - * @param {double} maxSlope The maximum inclination slope of a ray. If no 'onRayPosition' parameter is defined, it means the slope relative to plane y = 0. - * - * @param {integer} maxLightnings Greater than 0. The maximum number of simultaneous rays. - * - * @param {double} lightningMinPeriod minimum time between two consecutive rays. - * - * @param {double} lightningMaxPeriod maximum time between two consecutive rays. - * - * @param {double} lightningMinDuration The minimum time a ray can last. - * - * @param {double} lightningMaxDuration The maximum time a ray can last. - * - * @param {Object} lightningParameters The parameters for created rays. See LightningStrike (geometry) - * - * @param {Material} lightningMaterial The THREE.Material used for the created rays. - * - * @param {function} onRayPosition Optional callback with two Vector3 parameters (source, dest). You can set here the start and end points for each created ray, using the standard size, minHeight, etc parameters and other values in your algorithm. - * - * @param {function} onLightningDown This optional callback is called with one parameter (lightningStrike) when a ray ends propagating, so it has hit the ground. + * @license React + * react-reconciler-constants.production.min.js * + * Copyright (c) Facebook, Inc. and its affiliates. * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -class LightningStorm extends Object3D { - constructor(stormParams = {}) { - super(); // Parameters - - this.stormParams = stormParams; - stormParams.size = stormParams.size !== undefined ? stormParams.size : 1000.0; - stormParams.minHeight = stormParams.minHeight !== undefined ? stormParams.minHeight : 80.0; - stormParams.maxHeight = stormParams.maxHeight !== undefined ? stormParams.maxHeight : 100.0; - stormParams.maxSlope = stormParams.maxSlope !== undefined ? stormParams.maxSlope : 1.1; - stormParams.maxLightnings = stormParams.maxLightnings !== undefined ? stormParams.maxLightnings : 3; - stormParams.lightningMinPeriod = stormParams.lightningMinPeriod !== undefined ? stormParams.lightningMinPeriod : 3.0; - stormParams.lightningMaxPeriod = stormParams.lightningMaxPeriod !== undefined ? stormParams.lightningMaxPeriod : 7.0; - stormParams.lightningMinDuration = stormParams.lightningMinDuration !== undefined ? stormParams.lightningMinDuration : 1.0; - stormParams.lightningMaxDuration = stormParams.lightningMaxDuration !== undefined ? stormParams.lightningMaxDuration : 2.5; - this.lightningParameters = LightningStrike.copyParameters(stormParams.lightningParameters, stormParams.lightningParameters); - this.lightningParameters.isEternal = false; - this.lightningMaterial = stormParams.lightningMaterial !== undefined ? stormParams.lightningMaterial : new MeshBasicMaterial({ - color: 0xb0ffff - }); - - if (stormParams.onRayPosition !== undefined) { - this.onRayPosition = stormParams.onRayPosition; - } else { - this.onRayPosition = function (source, dest) { - dest.set((Math.random() - 0.5) * stormParams.size, 0, (Math.random() - 0.5) * stormParams.size); - const height = MathUtils.lerp(stormParams.minHeight, stormParams.maxHeight, Math.random()); - source.set(stormParams.maxSlope * (2 * Math.random() - 1), 1, stormParams.maxSlope * (2 * Math.random() - 1)).multiplyScalar(height).add(dest); - }; - } - - this.onLightningDown = stormParams.onLightningDown; // Internal state - - this.inited = false; - this.nextLightningTime = 0; - this.lightningsMeshes = []; - this.deadLightningsMeshes = []; - - for (let i = 0; i < this.stormParams.maxLightnings; i++) { - const lightning = new LightningStrike(LightningStrike.copyParameters({}, this.lightningParameters)); - const mesh = new Mesh(lightning, this.lightningMaterial); - this.deadLightningsMeshes.push(mesh); - } - } - - update(time) { - if (!this.inited) { - this.nextLightningTime = this.getNextLightningTime(time) * Math.random(); - this.inited = true; - } - - if (time >= this.nextLightningTime) { - // Lightning creation - const lightningMesh = this.deadLightningsMeshes.pop(); - - if (lightningMesh) { - const lightningParams1 = LightningStrike.copyParameters(lightningMesh.geometry.rayParameters, this.lightningParameters); - lightningParams1.birthTime = time; - lightningParams1.deathTime = time + MathUtils.lerp(this.stormParams.lightningMinDuration, this.stormParams.lightningMaxDuration, Math.random()); - this.onRayPosition(lightningParams1.sourceOffset, lightningParams1.destOffset); - lightningParams1.noiseSeed = Math.random(); - this.add(lightningMesh); - this.lightningsMeshes.push(lightningMesh); - } // Schedule next lightning - - - this.nextLightningTime = this.getNextLightningTime(time); - } - - let i = 0, - il = this.lightningsMeshes.length; - - while (i < il) { - const mesh = this.lightningsMeshes[i]; - const lightning = mesh.geometry; - const prevState = lightning.state; - lightning.update(time); - - if (prevState === LightningStrike.RAY_PROPAGATING && lightning.state > prevState) { - if (this.onLightningDown) { - this.onLightningDown(lightning); - } - } - - if (lightning.state === LightningStrike.RAY_EXTINGUISHED) { - // Lightning is to be destroyed - this.lightningsMeshes.splice(this.lightningsMeshes.indexOf(mesh), 1); - this.deadLightningsMeshes.push(mesh); - this.remove(mesh); - il--; - } else { - i++; - } - } - } - - getNextLightningTime(currentTime) { - return currentTime + MathUtils.lerp(this.stormParams.lightningMinPeriod, this.stormParams.lightningMaxPeriod, Math.random()) / (this.stormParams.maxLightnings + 1); - } - - copy(source) { - super.copy(source); - this.stormParams.size = source.stormParams.size; - this.stormParams.minHeight = source.stormParams.minHeight; - this.stormParams.maxHeight = source.stormParams.maxHeight; - this.stormParams.maxSlope = source.stormParams.maxSlope; - this.stormParams.maxLightnings = source.stormParams.maxLightnings; - this.stormParams.lightningMinPeriod = source.stormParams.lightningMinPeriod; - this.stormParams.lightningMaxPeriod = source.stormParams.lightningMaxPeriod; - this.stormParams.lightningMinDuration = source.stormParams.lightningMinDuration; - this.stormParams.lightningMaxDuration = source.stormParams.lightningMaxDuration; - this.lightningParameters = LightningStrike.copyParameters({}, source.lightningParameters); - this.lightningMaterial = source.stormParams.lightningMaterial; - this.onLightningDown = source.onLightningDown; - return this; - } - - clone() { - return new this.constructor(this.stormParams).copy(this); - } - -} - -LightningStorm.prototype.isLightningStorm = true; - -class ReflectorForSSRPass extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - this.type = 'ReflectorForSSRPass'; - const scope = this; - const color = options.color !== undefined ? new Color(options.color) : new Color(0x7f7f7f); - const textureWidth = options.textureWidth || 512; - const textureHeight = options.textureHeight || 512; - const clipBias = options.clipBias || 0; - const shader = options.shader || ReflectorForSSRPass.ReflectorShader; - const useDepthTexture = options.useDepthTexture === true; - const yAxis = new Vector3(0, 1, 0); - const vecTemp0 = new Vector3(); - const vecTemp1 = new Vector3(); // - - scope.needsUpdate = false; - scope.maxDistance = ReflectorForSSRPass.ReflectorShader.uniforms.maxDistance.value; - scope.opacity = ReflectorForSSRPass.ReflectorShader.uniforms.opacity.value; - scope.color = color; - scope.resolution = options.resolution || new Vector2(window.innerWidth, window.innerHeight); - scope._distanceAttenuation = ReflectorForSSRPass.ReflectorShader.defines.DISTANCE_ATTENUATION; - Object.defineProperty(scope, 'distanceAttenuation', { - get() { - return scope._distanceAttenuation; - }, - - set(val) { - if (scope._distanceAttenuation === val) return; - scope._distanceAttenuation = val; - scope.material.defines.DISTANCE_ATTENUATION = val; - scope.material.needsUpdate = true; - } - - }); - scope._fresnel = ReflectorForSSRPass.ReflectorShader.defines.FRESNEL; - Object.defineProperty(scope, 'fresnel', { - get() { - return scope._fresnel; - }, - - set(val) { - if (scope._fresnel === val) return; - scope._fresnel = val; - scope.material.defines.FRESNEL = val; - scope.material.needsUpdate = true; - } - - }); - const normal = new Vector3(); - const reflectorWorldPosition = new Vector3(); - const cameraWorldPosition = new Vector3(); - const rotationMatrix = new Matrix4(); - const lookAtPosition = new Vector3(0, 0, -1); - const view = new Vector3(); - const target = new Vector3(); - const textureMatrix = new Matrix4(); - const virtualCamera = new PerspectiveCamera(); - let depthTexture; - - if (useDepthTexture) { - depthTexture = new DepthTexture(); - depthTexture.type = UnsignedShortType; - depthTexture.minFilter = NearestFilter; - depthTexture.magFilter = NearestFilter; - } - - const parameters = { - depthTexture: useDepthTexture ? depthTexture : null - }; - const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, parameters); - const material = new ShaderMaterial({ - transparent: useDepthTexture, - defines: Object.assign({}, ReflectorForSSRPass.ReflectorShader.defines, { - useDepthTexture - }), - uniforms: UniformsUtils.clone(shader.uniforms), - fragmentShader: shader.fragmentShader, - vertexShader: shader.vertexShader - }); - material.uniforms['tDiffuse'].value = renderTarget.texture; - material.uniforms['color'].value = scope.color; - material.uniforms['textureMatrix'].value = textureMatrix; - - if (useDepthTexture) { - material.uniforms['tDepth'].value = renderTarget.depthTexture; - } - - this.material = material; - const globalPlane = new Plane(new Vector3(0, 1, 0), clipBias); - const globalPlanes = [globalPlane]; - - this.doRender = function (renderer, scene, camera) { - material.uniforms['maxDistance'].value = scope.maxDistance; - material.uniforms['color'].value = scope.color; - material.uniforms['opacity'].value = scope.opacity; - vecTemp0.copy(camera.position).normalize(); - vecTemp1.copy(vecTemp0).reflect(yAxis); - material.uniforms['fresnelCoe'].value = (vecTemp0.dot(vecTemp1) + 1) / 2; // TODO: Also need to use glsl viewPosition and viewNormal per pixel. - - reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); - cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); - rotationMatrix.extractRotation(scope.matrixWorld); - normal.set(0, 0, 1); - normal.applyMatrix4(rotationMatrix); - view.subVectors(reflectorWorldPosition, cameraWorldPosition); // Avoid rendering when reflector is facing away - - if (view.dot(normal) > 0) return; - view.reflect(normal).negate(); - view.add(reflectorWorldPosition); - rotationMatrix.extractRotation(camera.matrixWorld); - lookAtPosition.set(0, 0, -1); - lookAtPosition.applyMatrix4(rotationMatrix); - lookAtPosition.add(cameraWorldPosition); - target.subVectors(reflectorWorldPosition, lookAtPosition); - target.reflect(normal).negate(); - target.add(reflectorWorldPosition); - virtualCamera.position.copy(view); - virtualCamera.up.set(0, 1, 0); - virtualCamera.up.applyMatrix4(rotationMatrix); - virtualCamera.up.reflect(normal); - virtualCamera.lookAt(target); - virtualCamera.far = camera.far; // Used in WebGLBackground - - virtualCamera.updateMatrixWorld(); - virtualCamera.projectionMatrix.copy(camera.projectionMatrix); - material.uniforms['virtualCameraNear'].value = camera.near; - material.uniforms['virtualCameraFar'].value = camera.far; - material.uniforms['virtualCameraMatrixWorld'].value = virtualCamera.matrixWorld; - material.uniforms['virtualCameraProjectionMatrix'].value = camera.projectionMatrix; - material.uniforms['virtualCameraProjectionMatrixInverse'].value = camera.projectionMatrixInverse; - material.uniforms['resolution'].value = scope.resolution; // Update the texture matrix - - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); - textureMatrix.multiply(virtualCamera.projectionMatrix); - textureMatrix.multiply(virtualCamera.matrixWorldInverse); - textureMatrix.multiply(scope.matrixWorld); // Render - - renderTarget.texture.encoding = renderer.outputEncoding; // scope.visible = false; - - const currentRenderTarget = renderer.getRenderTarget(); - const currentXrEnabled = renderer.xr.enabled; - const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; - const currentClippingPlanes = renderer.clippingPlanes; - renderer.xr.enabled = false; // Avoid camera modification - - renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows - - renderer.clippingPlanes = globalPlanes; - renderer.setRenderTarget(renderTarget); - renderer.state.buffers.depth.setMask(true); // make sure the depth buffer is writable so it can be properly cleared, see #18897 - - if (renderer.autoClear === false) renderer.clear(); - renderer.render(scene, virtualCamera); - renderer.xr.enabled = currentXrEnabled; - renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; - renderer.clippingPlanes = currentClippingPlanes; - renderer.setRenderTarget(currentRenderTarget); // Restore viewport - - const viewport = camera.viewport; - - if (viewport !== undefined) { - renderer.state.viewport(viewport); - } // scope.visible = true; - - }; - - this.getRenderTarget = function () { - return renderTarget; - }; - } +var hasRequiredReactReconcilerConstants_production_min; +function requireReactReconcilerConstants_production_min () { + if (hasRequiredReactReconcilerConstants_production_min) return reactReconcilerConstants_production_min; + hasRequiredReactReconcilerConstants_production_min = 1; +reactReconcilerConstants_production_min.ConcurrentRoot=1;reactReconcilerConstants_production_min.ContinuousEventPriority=4;reactReconcilerConstants_production_min.DefaultEventPriority=16;reactReconcilerConstants_production_min.DiscreteEventPriority=1;reactReconcilerConstants_production_min.IdleEventPriority=536870912;reactReconcilerConstants_production_min.LegacyRoot=0; + return reactReconcilerConstants_production_min; } -ReflectorForSSRPass.prototype.isReflectorForSSRPass = true; -ReflectorForSSRPass.ReflectorShader = { - defines: { - DISTANCE_ATTENUATION: true, - FRESNEL: true - }, - uniforms: { - color: { - value: null - }, - tDiffuse: { - value: null - }, - tDepth: { - value: null - }, - textureMatrix: { - value: new Matrix4() - }, - maxDistance: { - value: 180 - }, - opacity: { - value: 0.5 - }, - fresnelCoe: { - value: null - }, - virtualCameraNear: { - value: null - }, - virtualCameraFar: { - value: null - }, - virtualCameraProjectionMatrix: { - value: new Matrix4() - }, - virtualCameraMatrixWorld: { - value: new Matrix4() - }, - virtualCameraProjectionMatrixInverse: { - value: new Matrix4() - }, - resolution: { - value: new Vector2() - } - }, - vertexShader: - /* glsl */ - ` - uniform mat4 textureMatrix; - varying vec4 vUv; - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - uniform vec3 color; - uniform sampler2D tDiffuse; - uniform sampler2D tDepth; - uniform float maxDistance; - uniform float opacity; - uniform float fresnelCoe; - uniform float virtualCameraNear; - uniform float virtualCameraFar; - uniform mat4 virtualCameraProjectionMatrix; - uniform mat4 virtualCameraProjectionMatrixInverse; - uniform mat4 virtualCameraMatrixWorld; - uniform vec2 resolution; - varying vec4 vUv; - #include - float blendOverlay( float base, float blend ) { - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - } - vec3 blendOverlay( vec3 base, vec3 blend ) { - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - } - float getDepth( const in vec2 uv ) { - return texture2D( tDepth, uv ).x; - } - float getViewZ( const in float depth ) { - return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar ); - } - vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { - vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc - clipPosition *= clipW; //clip - return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view - } - void main() { - vec4 base = texture2DProj( tDiffuse, vUv ); - #ifdef useDepthTexture - vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy; - uv.x=1.-uv.x; - float depth = texture2DProj( tDepth, vUv ).r; - float viewZ = getViewZ( depth ); - float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3]; - vec3 viewPosition=getViewPosition( uv, depth, clipW ); - vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz; - if(worldPosition.y>maxDistance) discard; - float op=opacity; - #ifdef DISTANCE_ATTENUATION - float ratio=1.-(worldPosition.y/maxDistance); - float attenuation=ratio*ratio; - op=opacity*attenuation; - #endif - #ifdef FRESNEL - op*=fresnelCoe; - #endif - gl_FragColor = vec4( blendOverlay( base.rgb, color ), op ); - #else - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - #endif - } - ` -}; +var reactReconcilerConstants_development = {}; /** - * Based on "A Practical Analytic Model for Daylight" - * aka The Preetham Model, the de facto standard analytic skydome model - * https://www.researchgate.net/publication/220720443_A_Practical_Analytic_Model_for_Daylight - * - * First implemented by Simon Wallner - * http://www.simonwallner.at/projects/atmospheric-scattering - * - * Improved by Martin Upitis - * http://blenderartists.org/forum/showthread.php?245954-preethams-sky-impementation-HDR + * @license React + * react-reconciler-constants.development.js * - * Three.js integration by zz85 http://twitter.com/blurspline - */ - -class Sky extends Mesh { - constructor() { - super(new BoxGeometry(1, 1, 1), Sky.material); - } - -} - -_defineProperty$1(Sky, "SkyShader", { - uniforms: { - turbidity: { - value: 2 - }, - rayleigh: { - value: 1 - }, - mieCoefficient: { - value: 0.005 - }, - mieDirectionalG: { - value: 0.8 - }, - sunPosition: { - value: new Vector3() - }, - up: { - value: new Vector3(0, 1, 0) - } - }, - vertexShader: ['uniform vec3 sunPosition;', 'uniform float rayleigh;', 'uniform float turbidity;', 'uniform float mieCoefficient;', 'uniform vec3 up;', 'varying vec3 vWorldPosition;', 'varying vec3 vSunDirection;', 'varying float vSunfade;', 'varying vec3 vBetaR;', 'varying vec3 vBetaM;', 'varying float vSunE;', // constants for atmospheric scattering - 'const float e = 2.71828182845904523536028747135266249775724709369995957;', 'const float pi = 3.141592653589793238462643383279502884197169;', // wavelength of used primaries, according to preetham - 'const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );', // this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function: - // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) - 'const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );', // mie stuff - // K coefficient for the primaries - 'const float v = 4.0;', 'const vec3 K = vec3( 0.686, 0.678, 0.666 );', // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K - 'const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );', // earth shadow hack - // cutoffAngle = pi / 1.95; - 'const float cutoffAngle = 1.6110731556870734;', 'const float steepness = 1.5;', 'const float EE = 1000.0;', 'float sunIntensity( float zenithAngleCos ) {', ' zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );', ' return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );', '}', 'vec3 totalMie( float T ) {', ' float c = ( 0.2 * T ) * 10E-18;', ' return 0.434 * c * MieConst;', '}', 'void main() {', ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );', ' vWorldPosition = worldPosition.xyz;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', ' gl_Position.z = gl_Position.w;', // set z to camera.far - ' vSunDirection = normalize( sunPosition );', ' vSunE = sunIntensity( dot( vSunDirection, up ) );', ' vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );', ' float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );', // extinction (absorbtion + out scattering) - // rayleigh coefficients - ' vBetaR = totalRayleigh * rayleighCoefficient;', // mie coefficients - ' vBetaM = totalMie( turbidity ) * mieCoefficient;', '}'].join('\n'), - fragmentShader: ['varying vec3 vWorldPosition;', 'varying vec3 vSunDirection;', 'varying float vSunfade;', 'varying vec3 vBetaR;', 'varying vec3 vBetaM;', 'varying float vSunE;', 'uniform float mieDirectionalG;', 'uniform vec3 up;', 'const vec3 cameraPos = vec3( 0.0, 0.0, 0.0 );', // constants for atmospheric scattering - 'const float pi = 3.141592653589793238462643383279502884197169;', 'const float n = 1.0003;', // refractive index of air - 'const float N = 2.545E25;', // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius) - // optical length at zenith for molecules - 'const float rayleighZenithLength = 8.4E3;', 'const float mieZenithLength = 1.25E3;', // 66 arc seconds -> degrees, and the cosine of that - 'const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;', // 3.0 / ( 16.0 * pi ) - 'const float THREE_OVER_SIXTEENPI = 0.05968310365946075;', // 1.0 / ( 4.0 * pi ) - 'const float ONE_OVER_FOURPI = 0.07957747154594767;', 'float rayleighPhase( float cosTheta ) {', ' return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );', '}', 'float hgPhase( float cosTheta, float g ) {', ' float g2 = pow( g, 2.0 );', ' float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );', ' return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );', '}', 'void main() {', ' vec3 direction = normalize( vWorldPosition - cameraPos );', // optical length - // cutoff angle at 90 to avoid singularity in next formula. - ' float zenithAngle = acos( max( 0.0, dot( up, direction ) ) );', ' float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );', ' float sR = rayleighZenithLength * inverse;', ' float sM = mieZenithLength * inverse;', // combined extinction factor - ' vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );', // in scattering - ' float cosTheta = dot( direction, vSunDirection );', ' float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );', ' vec3 betaRTheta = vBetaR * rPhase;', ' float mPhase = hgPhase( cosTheta, mieDirectionalG );', ' vec3 betaMTheta = vBetaM * mPhase;', ' vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );', ' Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) );', // nightsky - ' float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]', ' float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]', ' vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );', ' vec3 L0 = vec3( 0.1 ) * Fex;', // composition + solar disc - ' float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta );', ' L0 += ( vSunE * 19000.0 * Fex ) * sundisk;', ' vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );', ' vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );', ' gl_FragColor = vec4( retColor, 1.0 );', '#include ', '#include ', '}'].join('\n') -}); - -_defineProperty$1(Sky, "material", new ShaderMaterial({ - name: 'SkyShader', - fragmentShader: Sky.SkyShader.fragmentShader, - vertexShader: Sky.SkyShader.vertexShader, - uniforms: UniformsUtils.clone(Sky.SkyShader.uniforms), - side: BackSide, - depthWrite: false -})); - -/** - * References: - * http://www.valvesoftware.com/publications/2010/siggraph2010_vlachos_waterflow.pdf - * http://graphicsrunner.blogspot.de/2010/08/water-using-flow-maps.html + * Copyright (c) Facebook, Inc. and its affiliates. * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -class Water2 extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - this.type = 'Water'; - const scope = this; - const color = options.color !== undefined ? new Color(options.color) : new Color(0xffffff); - const textureWidth = options.textureWidth || 512; - const textureHeight = options.textureHeight || 512; - const clipBias = options.clipBias || 0; - const flowDirection = options.flowDirection || new Vector2(1, 0); - const flowSpeed = options.flowSpeed || 0.03; - const reflectivity = options.reflectivity || 0.02; - const scale = options.scale || 1; - const shader = options.shader || Water.WaterShader; - const encoding = options.encoding !== undefined ? options.encoding : LinearEncoding; - const textureLoader = new TextureLoader(); - const flowMap = options.flowMap || undefined; - const normalMap0 = options.normalMap0 || textureLoader.load('textures/water/Water_1_M_Normal.jpg'); - const normalMap1 = options.normalMap1 || textureLoader.load('textures/water/Water_2_M_Normal.jpg'); - const cycle = 0.15; // a cycle of a flow map phase - - const halfCycle = cycle * 0.5; - const textureMatrix = new Matrix4(); - const clock = new Clock(); // internal components - - if (Reflector === undefined) { - console.error('THREE.Water: Required component Reflector not found.'); - return; - } - - if (Refractor === undefined) { - console.error('THREE.Water: Required component Refractor not found.'); - return; - } - - const reflector = new Reflector(geometry, { - textureWidth: textureWidth, - textureHeight: textureHeight, - clipBias: clipBias, - encoding: encoding - }); - const refractor = new Refractor(geometry, { - textureWidth: textureWidth, - textureHeight: textureHeight, - clipBias: clipBias, - encoding: encoding - }); - reflector.matrixAutoUpdate = false; - refractor.matrixAutoUpdate = false; // material - - this.material = new ShaderMaterial({ - uniforms: UniformsUtils.merge([UniformsLib['fog'], shader.uniforms]), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - transparent: true, - fog: true - }); - - if (flowMap !== undefined) { - this.material.defines.USE_FLOWMAP = ''; - this.material.uniforms['tFlowMap'] = { - type: 't', - value: flowMap - }; - } else { - this.material.uniforms['flowDirection'] = { - type: 'v2', - value: flowDirection - }; - } // maps - - - normalMap0.wrapS = normalMap0.wrapT = RepeatWrapping; - normalMap1.wrapS = normalMap1.wrapT = RepeatWrapping; - this.material.uniforms['tReflectionMap'].value = reflector.getRenderTarget().texture; - this.material.uniforms['tRefractionMap'].value = refractor.getRenderTarget().texture; - this.material.uniforms['tNormalMap0'].value = normalMap0; - this.material.uniforms['tNormalMap1'].value = normalMap1; // water - - this.material.uniforms['color'].value = color; - this.material.uniforms['reflectivity'].value = reflectivity; - this.material.uniforms['textureMatrix'].value = textureMatrix; // inital values - - this.material.uniforms['config'].value.x = 0; // flowMapOffset0 - - this.material.uniforms['config'].value.y = halfCycle; // flowMapOffset1 - - this.material.uniforms['config'].value.z = halfCycle; // halfCycle - - this.material.uniforms['config'].value.w = scale; // scale - // functions - - function updateTextureMatrix(camera) { - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); - textureMatrix.multiply(camera.projectionMatrix); - textureMatrix.multiply(camera.matrixWorldInverse); - textureMatrix.multiply(scope.matrixWorld); - } - - function updateFlow() { - const delta = clock.getDelta(); - const config = scope.material.uniforms['config']; - config.value.x += flowSpeed * delta; // flowMapOffset0 - - config.value.y = config.value.x + halfCycle; // flowMapOffset1 - // Important: The distance between offsets should be always the value of "halfCycle". - // Moreover, both offsets should be in the range of [ 0, cycle ]. - // This approach ensures a smooth water flow and avoids "reset" effects. - - if (config.value.x >= cycle) { - config.value.x = 0; - config.value.y = halfCycle; - } else if (config.value.y >= cycle) { - config.value.y = config.value.y - cycle; - } - } // - - - this.onBeforeRender = function (renderer, scene, camera) { - updateTextureMatrix(camera); - updateFlow(); - scope.visible = false; - reflector.matrixWorld.copy(scope.matrixWorld); - refractor.matrixWorld.copy(scope.matrixWorld); - reflector.onBeforeRender(renderer, scene, camera); - refractor.onBeforeRender(renderer, scene, camera); - scope.visible = true; - }; - } - -} - -Water2.prototype.isWater = true; -Water2.WaterShader = { - uniforms: { - color: { - type: 'c', - value: null - }, - reflectivity: { - type: 'f', - value: 0 - }, - tReflectionMap: { - type: 't', - value: null - }, - tRefractionMap: { - type: 't', - value: null - }, - tNormalMap0: { - type: 't', - value: null - }, - tNormalMap1: { - type: 't', - value: null - }, - textureMatrix: { - type: 'm4', - value: null - }, - config: { - type: 'v4', - value: new Vector4() - } - }, - vertexShader: - /* glsl */ - ` - - #include - #include - #include - - uniform mat4 textureMatrix; - - varying vec4 vCoord; - varying vec2 vUv; - varying vec3 vToEye; - - void main() { - - vUv = uv; - vCoord = textureMatrix * vec4( position, 1.0 ); - - vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); - vToEye = cameraPosition - worldPosition.xyz; - - vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex - gl_Position = projectionMatrix * mvPosition; - - #include - #include - - }`, - fragmentShader: - /* glsl */ - ` - - #include - #include - #include - - uniform sampler2D tReflectionMap; - uniform sampler2D tRefractionMap; - uniform sampler2D tNormalMap0; - uniform sampler2D tNormalMap1; - - #ifdef USE_FLOWMAP - uniform sampler2D tFlowMap; - #else - uniform vec2 flowDirection; - #endif - - uniform vec3 color; - uniform float reflectivity; - uniform vec4 config; - - varying vec4 vCoord; - varying vec2 vUv; - varying vec3 vToEye; - - void main() { +var hasRequiredReactReconcilerConstants_development; - #include +function requireReactReconcilerConstants_development () { + if (hasRequiredReactReconcilerConstants_development) return reactReconcilerConstants_development; + hasRequiredReactReconcilerConstants_development = 1; - float flowMapOffset0 = config.x; - float flowMapOffset1 = config.y; - float halfCycle = config.z; - float scale = config.w; + if (process.env.NODE_ENV !== "production") { + (function() { - vec3 toEye = normalize( vToEye ); + var SyncLane = + /* */ + 1; + var InputContinuousLane = + /* */ + 4; + var DefaultLane = + /* */ + 16; + var IdleLane = + /* */ + 536870912; - // determine flow direction - vec2 flow; - #ifdef USE_FLOWMAP - flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0; - #else - flow = flowDirection; - #endif - flow.x *= - 1.0; + var DiscreteEventPriority = SyncLane; + var ContinuousEventPriority = InputContinuousLane; + var DefaultEventPriority = DefaultLane; + var IdleEventPriority = IdleLane; - // sample normal maps (distort uvs with flowdata) - vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 ); - vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 ); + var LegacyRoot = 0; + var ConcurrentRoot = 1; - // linear interpolate to get the final normal color - float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle; - vec4 normalColor = mix( normalColor0, normalColor1, flowLerp ); + reactReconcilerConstants_development.ConcurrentRoot = ConcurrentRoot; + reactReconcilerConstants_development.ContinuousEventPriority = ContinuousEventPriority; + reactReconcilerConstants_development.DefaultEventPriority = DefaultEventPriority; + reactReconcilerConstants_development.DiscreteEventPriority = DiscreteEventPriority; + reactReconcilerConstants_development.IdleEventPriority = IdleEventPriority; + reactReconcilerConstants_development.LegacyRoot = LegacyRoot; + })(); + } + return reactReconcilerConstants_development; +} - // calculate normal vector - vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) ); +(function (module) { - // calculate the fresnel term to blend reflection and refraction maps - float theta = max( dot( toEye, normal ), 0.0 ); - float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 ); + if (process.env.NODE_ENV === 'production') { + module.exports = requireReactReconcilerConstants_production_min(); + } else { + module.exports = requireReactReconcilerConstants_development(); + } +} (constants)); - // calculate final uv coords - vec3 coord = vCoord.xyz / vCoord.w; - vec2 uv = coord.xy + coord.z * normal.xz * 0.05; +function createStore$3(createState) { + let state; + const listeners = /* @__PURE__ */ new Set(); + const setState = (partial, replace) => { + const nextState = typeof partial === "function" ? partial(state) : partial; + if (nextState !== state) { + const previousState = state; + state = replace ? nextState : Object.assign({}, state, nextState); + listeners.forEach((listener) => listener(state, previousState)); + } + }; + const getState = () => state; + const subscribeWithSelector = (listener, selector = getState, equalityFn = Object.is) => { + console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware"); + let currentSlice = selector(state); + function listenerToAdd() { + const nextSlice = selector(state); + if (!equalityFn(currentSlice, nextSlice)) { + const previousSlice = currentSlice; + listener(currentSlice = nextSlice, previousSlice); + } + } + listeners.add(listenerToAdd); + return () => listeners.delete(listenerToAdd); + }; + const subscribe = (listener, selector, equalityFn) => { + if (selector || equalityFn) { + return subscribeWithSelector(listener, selector, equalityFn); + } + listeners.add(listener); + return () => listeners.delete(listener); + }; + const destroy = () => listeners.clear(); + const api = { setState, getState, subscribe, destroy }; + state = createState(setState, getState, api); + return api; +} - vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) ); - vec4 refractColor = texture2D( tRefractionMap, uv ); +const isSSR$3 = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); +const useIsomorphicLayoutEffect$2 = isSSR$3 ? useEffect : useLayoutEffect$1; +function create$4(createState) { + const api = typeof createState === "function" ? createStore$3(createState) : createState; + const useStore = (selector = api.getState, equalityFn = Object.is) => { + const [, forceUpdate] = useReducer((c) => c + 1, 0); + const state = api.getState(); + const stateRef = useRef(state); + const selectorRef = useRef(selector); + const equalityFnRef = useRef(equalityFn); + const erroredRef = useRef(false); + const currentSliceRef = useRef(); + if (currentSliceRef.current === void 0) { + currentSliceRef.current = selector(state); + } + let newStateSlice; + let hasNewStateSlice = false; + if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) { + newStateSlice = selector(state); + hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice); + } + useIsomorphicLayoutEffect$2(() => { + if (hasNewStateSlice) { + currentSliceRef.current = newStateSlice; + } + stateRef.current = state; + selectorRef.current = selector; + equalityFnRef.current = equalityFn; + erroredRef.current = false; + }); + const stateBeforeSubscriptionRef = useRef(state); + useIsomorphicLayoutEffect$2(() => { + const listener = () => { + try { + const nextState = api.getState(); + const nextStateSlice = selectorRef.current(nextState); + if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) { + stateRef.current = nextState; + currentSliceRef.current = nextStateSlice; + forceUpdate(); + } + } catch (error) { + erroredRef.current = true; + forceUpdate(); + } + }; + const unsubscribe = api.subscribe(listener); + if (api.getState() !== stateBeforeSubscriptionRef.current) { + listener(); + } + return unsubscribe; + }, []); + const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current; + useDebugValue(sliceToReturn); + return sliceToReturn; + }; + Object.assign(useStore, api); + useStore[Symbol.iterator] = function() { + console.warn("[useStore, api] = create() is deprecated and will be removed in v4"); + const items = [useStore, api]; + return { + next() { + const done = items.length <= 0; + return { value: items.shift(), done }; + } + }; + }; + return useStore; +} - // multiply water color with the mix of both textures - gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance ); +var reactReconciler = {exports: {}}; - #include - #include - #include +var scheduler$1 = {exports: {}}; - }` -}; +var scheduler_production_min = {}; /** - * This class generates custom mipmaps for a roughness map by encoding the lost variation in the - * normal map mip levels as increased roughness in the corresponding roughness mip levels. This - * helps with rendering accuracy for MeshStandardMaterial, and also helps with anti-aliasing when - * using PMREM. If the normal map is larger than the roughness map, the roughness map will be - * enlarged to match the dimensions of the normal map. + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -var _mipmapMaterial = _getMipmapMaterial(); - -var _mesh = new Mesh(new PlaneGeometry(2, 2), _mipmapMaterial); - -var _flatCamera = new OrthographicCamera(0, 1, 0, 1, 0, 1); - -var _tempTarget = null; -var _renderer = null; - -function RoughnessMipmapper(renderer) { - _renderer = renderer; +var hasRequiredScheduler_production_min; - _renderer.compile(_mesh, _flatCamera); +function requireScheduler_production_min () { + if (hasRequiredScheduler_production_min) return scheduler_production_min; + hasRequiredScheduler_production_min = 1; + (function (exports) { +function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} + function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; + "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} + function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; + function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; + exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; +} (scheduler_production_min)); + return scheduler_production_min; } -RoughnessMipmapper.prototype = { - constructor: RoughnessMipmapper, - generateMipmaps: function (material) { - if ('roughnessMap' in material === false) return; - var { - roughnessMap, - normalMap - } = material; - - if (roughnessMap === null || normalMap === null || !roughnessMap.generateMipmaps || material.userData.roughnessUpdated) { - return; - } - - material.userData.roughnessUpdated = true; - var width = Math.max(roughnessMap.image.width, normalMap.image.width); - var height = Math.max(roughnessMap.image.height, normalMap.image.height); - if (!MathUtils.isPowerOfTwo(width) || !MathUtils.isPowerOfTwo(height)) return; - - var oldTarget = _renderer.getRenderTarget(); - - var autoClear = _renderer.autoClear; - _renderer.autoClear = false; - - if (_tempTarget === null || _tempTarget.width !== width || _tempTarget.height !== height) { - if (_tempTarget !== null) _tempTarget.dispose(); - _tempTarget = new WebGLRenderTarget(width, height, { - depthBuffer: false - }); - _tempTarget.scissorTest = true; - } +var scheduler_development = {}; - if (width !== roughnessMap.image.width || height !== roughnessMap.image.height) { - var params = { - wrapS: roughnessMap.wrapS, - wrapT: roughnessMap.wrapT, - magFilter: roughnessMap.magFilter, - minFilter: roughnessMap.minFilter, - depthBuffer: false - }; - var newRoughnessTarget = new WebGLRenderTarget(width, height, params); - newRoughnessTarget.texture.generateMipmaps = true; // Setting the render target causes the memory to be allocated. +/** + * @license React + * scheduler.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ - _renderer.setRenderTarget(newRoughnessTarget); +var hasRequiredScheduler_development; - material.roughnessMap = newRoughnessTarget.texture; - if (material.metalnessMap == roughnessMap) material.metalnessMap = material.roughnessMap; - if (material.aoMap == roughnessMap) material.aoMap = material.roughnessMap; - } +function requireScheduler_development () { + if (hasRequiredScheduler_development) return scheduler_development; + hasRequiredScheduler_development = 1; + (function (exports) { - _mipmapMaterial.uniforms.roughnessMap.value = roughnessMap; - _mipmapMaterial.uniforms.normalMap.value = normalMap; - var position = new Vector2(0, 0); - var texelSize = _mipmapMaterial.uniforms.texelSize.value; + if (process.env.NODE_ENV !== "production") { + (function() { - for (let mip = 0; width >= 1 && height >= 1; ++mip, width /= 2, height /= 2) { - // Rendering to a mip level is not allowed in webGL1. Instead we must set - // up a secondary texture to write the result to, then copy it back to the - // proper mipmap level. - texelSize.set(1.0 / width, 1.0 / height); - if (mip == 0) texelSize.set(0.0, 0.0); + /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ + if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === + 'function' + ) { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); + } + var enableSchedulerDebugging = false; + var enableProfiling = false; + var frameYieldMs = 5; - _tempTarget.viewport.set(position.x, position.y, width, height); + function push(heap, node) { + var index = heap.length; + heap.push(node); + siftUp(heap, node, index); + } + function peek(heap) { + return heap.length === 0 ? null : heap[0]; + } + function pop(heap) { + if (heap.length === 0) { + return null; + } - _tempTarget.scissor.set(position.x, position.y, width, height); + var first = heap[0]; + var last = heap.pop(); - _renderer.setRenderTarget(_tempTarget); + if (last !== first) { + heap[0] = last; + siftDown(heap, last, 0); + } - _renderer.render(_mesh, _flatCamera); + return first; + } - _renderer.copyFramebufferToTexture(position, material.roughnessMap, mip); + function siftUp(heap, node, i) { + var index = i; - _mipmapMaterial.uniforms.roughnessMap.value = material.roughnessMap; - } + while (index > 0) { + var parentIndex = index - 1 >>> 1; + var parent = heap[parentIndex]; - if (roughnessMap !== material.roughnessMap) roughnessMap.dispose(); + if (compare(parent, node) > 0) { + // The parent is larger. Swap positions. + heap[parentIndex] = node; + heap[index] = parent; + index = parentIndex; + } else { + // The parent is smaller. Exit. + return; + } + } + } - _renderer.setRenderTarget(oldTarget); + function siftDown(heap, node, i) { + var index = i; + var length = heap.length; + var halfLength = length >>> 1; - _renderer.autoClear = autoClear; - }, - dispose: function () { - _mipmapMaterial.dispose(); + while (index < halfLength) { + var leftIndex = (index + 1) * 2 - 1; + var left = heap[leftIndex]; + var rightIndex = leftIndex + 1; + var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. - _mesh.geometry.dispose(); + if (compare(left, node) < 0) { + if (rightIndex < length && compare(right, left) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + heap[index] = left; + heap[leftIndex] = node; + index = leftIndex; + } + } else if (rightIndex < length && compare(right, node) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + // Neither child is smaller. Exit. + return; + } + } + } - if (_tempTarget != null) _tempTarget.dispose(); - } -}; + function compare(a, b) { + // Compare sort index first, then task id. + var diff = a.sortIndex - b.sortIndex; + return diff !== 0 ? diff : a.id - b.id; + } -function _getMipmapMaterial() { - var shaderMaterial = new RawShaderMaterial({ - uniforms: { - roughnessMap: { - value: null - }, - normalMap: { - value: null - }, - texelSize: { - value: new Vector2(1, 1) - } - }, - vertexShader: - /* glsl */ - ` - precision mediump float; - precision mediump int; + // TODO: Use symbols? + var ImmediatePriority = 1; + var UserBlockingPriority = 2; + var NormalPriority = 3; + var LowPriority = 4; + var IdlePriority = 5; - attribute vec3 position; - attribute vec2 uv; + function markTaskErrored(task, ms) { + } - varying vec2 vUv; + /* eslint-disable no-var */ - void main() { + var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; - vUv = uv; + if (hasPerformanceNow) { + var localPerformance = performance; - gl_Position = vec4( position, 1.0 ); + exports.unstable_now = function () { + return localPerformance.now(); + }; + } else { + var localDate = Date; + var initialTime = localDate.now(); - } - `, - fragmentShader: - /* glsl */ - ` - precision mediump float; - precision mediump int; + exports.unstable_now = function () { + return localDate.now() - initialTime; + }; + } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. + // Math.pow(2, 30) - 1 + // 0b111111111111111111111111111111 - varying vec2 vUv; - uniform sampler2D roughnessMap; - uniform sampler2D normalMap; - uniform vec2 texelSize; + var maxSigned31BitInt = 1073741823; // Times out immediately - #define ENVMAP_TYPE_CUBE_UV + var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out - vec4 envMapTexelToLinear( vec4 a ) { return a; } + var USER_BLOCKING_PRIORITY_TIMEOUT = 250; + var NORMAL_PRIORITY_TIMEOUT = 5000; + var LOW_PRIORITY_TIMEOUT = 10000; // Never times out - #include + var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap - float roughnessToVariance( float roughness ) { + var taskQueue = []; + var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. - float variance = 0.0; + var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. + var currentTask = null; + var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. - if ( roughness >= r1 ) { + var isPerformingWork = false; + var isHostCallbackScheduled = false; + var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. - variance = ( r0 - roughness ) * ( v1 - v0 ) / ( r0 - r1 ) + v0; + var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; + var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; + var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom - } else if ( roughness >= r4 ) { + typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; - variance = ( r1 - roughness ) * ( v4 - v1 ) / ( r1 - r4 ) + v1; + function advanceTimers(currentTime) { + // Check for tasks that are no longer delayed and add them to the queue. + var timer = peek(timerQueue); - } else if ( roughness >= r5 ) { + while (timer !== null) { + if (timer.callback === null) { + // Timer was cancelled. + pop(timerQueue); + } else if (timer.startTime <= currentTime) { + // Timer fired. Transfer to the task queue. + pop(timerQueue); + timer.sortIndex = timer.expirationTime; + push(taskQueue, timer); + } else { + // Remaining timers are pending. + return; + } - variance = ( r4 - roughness ) * ( v5 - v4 ) / ( r4 - r5 ) + v4; + timer = peek(timerQueue); + } + } - } else { + function handleTimeout(currentTime) { + isHostTimeoutScheduled = false; + advanceTimers(currentTime); - float roughness2 = roughness * roughness; + if (!isHostCallbackScheduled) { + if (peek(taskQueue) !== null) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } else { + var firstTimer = peek(timerQueue); - variance = 1.79 * roughness2 * roughness2; + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + } + } + } - } + function flushWork(hasTimeRemaining, initialTime) { - return variance; - } + isHostCallbackScheduled = false; - float varianceToRoughness( float variance ) { + if (isHostTimeoutScheduled) { + // We scheduled a timeout but it's no longer needed. Cancel it. + isHostTimeoutScheduled = false; + cancelHostTimeout(); + } - float roughness = 0.0; + isPerformingWork = true; + var previousPriorityLevel = currentPriorityLevel; - if ( variance >= v1 ) { + try { + var currentTime; if (enableProfiling) ; else { + // No catch in prod code path. + return workLoop(hasTimeRemaining, initialTime); + } + } finally { + currentTask = null; + currentPriorityLevel = previousPriorityLevel; + isPerformingWork = false; + } + } - roughness = ( v0 - variance ) * ( r1 - r0 ) / ( v0 - v1 ) + r0; + function workLoop(hasTimeRemaining, initialTime) { + var currentTime = initialTime; + advanceTimers(currentTime); + currentTask = peek(taskQueue); - } else if ( variance >= v4 ) { + while (currentTask !== null && !(enableSchedulerDebugging )) { + if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { + // This currentTask hasn't expired, and we've reached the deadline. + break; + } - roughness = ( v1 - variance ) * ( r4 - r1 ) / ( v1 - v4 ) + r1; + var callback = currentTask.callback; - } else if ( variance >= v5 ) { + if (typeof callback === 'function') { + currentTask.callback = null; + currentPriorityLevel = currentTask.priorityLevel; + var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; - roughness = ( v4 - variance ) * ( r5 - r4 ) / ( v4 - v5 ) + r4; + var continuationCallback = callback(didUserCallbackTimeout); + currentTime = exports.unstable_now(); - } else { + if (typeof continuationCallback === 'function') { + currentTask.callback = continuationCallback; + } else { - roughness = pow( 0.559 * variance, 0.25 ); // 0.559 = 1.0 / 1.79 + if (currentTask === peek(taskQueue)) { + pop(taskQueue); + } + } - } + advanceTimers(currentTime); + } else { + pop(taskQueue); + } - return roughness; + currentTask = peek(taskQueue); + } // Return whether there's additional work - } - void main() { + if (currentTask !== null) { + return true; + } else { + var firstTimer = peek(timerQueue); - gl_FragColor = texture2D( roughnessMap, vUv, - 1.0 ); + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } - if ( texelSize.x == 0.0 ) return; + return false; + } + } - float roughness = gl_FragColor.g; + function unstable_runWithPriority(priorityLevel, eventHandler) { + switch (priorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + case LowPriority: + case IdlePriority: + break; - float variance = roughnessToVariance( roughness ); + default: + priorityLevel = NormalPriority; + } - vec3 avgNormal; + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; - for ( float x = - 1.0; x < 2.0; x += 2.0 ) { + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } - for ( float y = - 1.0; y < 2.0; y += 2.0 ) { + function unstable_next(eventHandler) { + var priorityLevel; - vec2 uv = vUv + vec2( x, y ) * 0.25 * texelSize; + switch (currentPriorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + // Shift down to normal priority + priorityLevel = NormalPriority; + break; - avgNormal += normalize( texture2D( normalMap, uv, - 1.0 ).xyz - 0.5 ); + default: + // Anything lower than normal priority should remain at the current level. + priorityLevel = currentPriorityLevel; + break; + } - } + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; - } + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } - variance += 1.0 - 0.25 * length( avgNormal ); + function unstable_wrapCallback(callback) { + var parentPriorityLevel = currentPriorityLevel; + return function () { + // This is a fork of runWithPriority, inlined for performance. + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = parentPriorityLevel; - gl_FragColor.g = varianceToRoughness( variance ); + try { + return callback.apply(this, arguments); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + }; + } - } - `, - blending: NoBlending, - depthTest: false, - depthWrite: false - }); - shaderMaterial.type = 'RoughnessMipmapper'; - return shaderMaterial; -} + function unstable_scheduleCallback(priorityLevel, callback, options) { + var currentTime = exports.unstable_now(); + var startTime; -({ - retarget: function () { - var pos = new Vector3(), - quat = new Quaternion(), - scale = new Vector3(), - bindBoneMatrix = new Matrix4(), - relativeMatrix = new Matrix4(), - globalMatrix = new Matrix4(); - return function (target, source, options) { - options = options || {}; - options.preserveMatrix = options.preserveMatrix !== undefined ? options.preserveMatrix : true; - options.preservePosition = options.preservePosition !== undefined ? options.preservePosition : true; - options.preserveHipPosition = options.preserveHipPosition !== undefined ? options.preserveHipPosition : false; - options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false; - options.hip = options.hip !== undefined ? options.hip : 'hip'; - options.names = options.names || {}; - var sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones(source), - bones = target.isObject3D ? target.skeleton.bones : this.getBones(target), - bindBones, - bone, - name, - boneTo, - bonesPosition, - i; // reset bones - - if (target.isObject3D) { - target.skeleton.pose(); - } else { - options.useTargetMatrix = true; - options.preserveMatrix = false; - } + if (typeof options === 'object' && options !== null) { + var delay = options.delay; - if (options.preservePosition) { - bonesPosition = []; + if (typeof delay === 'number' && delay > 0) { + startTime = currentTime + delay; + } else { + startTime = currentTime; + } + } else { + startTime = currentTime; + } - for (i = 0; i < bones.length; i++) { - bonesPosition.push(bones[i].position.clone()); - } - } + var timeout; - if (options.preserveMatrix) { - // reset matrix - target.updateMatrixWorld(); - target.matrixWorld.identity(); // reset children matrix + switch (priorityLevel) { + case ImmediatePriority: + timeout = IMMEDIATE_PRIORITY_TIMEOUT; + break; - for (i = 0; i < target.children.length; ++i) { - target.children[i].updateMatrixWorld(true); - } - } + case UserBlockingPriority: + timeout = USER_BLOCKING_PRIORITY_TIMEOUT; + break; - if (options.offsets) { - bindBones = []; + case IdlePriority: + timeout = IDLE_PRIORITY_TIMEOUT; + break; - for (i = 0; i < bones.length; ++i) { - bone = bones[i]; - name = options.names[bone.name] || bone.name; + case LowPriority: + timeout = LOW_PRIORITY_TIMEOUT; + break; - if (options.offsets && options.offsets[name]) { - bone.matrix.multiply(options.offsets[name]); - bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); - bone.updateMatrixWorld(); - } + case NormalPriority: + default: + timeout = NORMAL_PRIORITY_TIMEOUT; + break; + } - bindBones.push(bone.matrixWorld.clone()); - } - } + var expirationTime = startTime + timeout; + var newTask = { + id: taskIdCounter++, + callback: callback, + priorityLevel: priorityLevel, + startTime: startTime, + expirationTime: expirationTime, + sortIndex: -1 + }; - for (i = 0; i < bones.length; ++i) { - bone = bones[i]; - name = options.names[bone.name] || bone.name; - boneTo = this.getBoneByName(name, sourceBones); - globalMatrix.copy(bone.matrixWorld); + if (startTime > currentTime) { + // This is a delayed task. + newTask.sortIndex = startTime; + push(timerQueue, newTask); - if (boneTo) { - boneTo.updateMatrixWorld(); + if (peek(taskQueue) === null && newTask === peek(timerQueue)) { + // All tasks are delayed, and this is the task with the earliest delay. + if (isHostTimeoutScheduled) { + // Cancel an existing timeout. + cancelHostTimeout(); + } else { + isHostTimeoutScheduled = true; + } // Schedule a timeout. - if (options.useTargetMatrix) { - relativeMatrix.copy(boneTo.matrixWorld); - } else { - relativeMatrix.copy(target.matrixWorld).invert(); - relativeMatrix.multiply(boneTo.matrixWorld); - } // ignore scale to extract rotation + requestHostTimeout(handleTimeout, startTime - currentTime); + } + } else { + newTask.sortIndex = expirationTime; + push(taskQueue, newTask); + // wait until the next time we yield. - scale.setFromMatrixScale(relativeMatrix); - relativeMatrix.scale(scale.set(1 / scale.x, 1 / scale.y, 1 / scale.z)); // apply to global matrix - globalMatrix.makeRotationFromQuaternion(quat.setFromRotationMatrix(relativeMatrix)); + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } - if (target.isObject3D) { - var boneIndex = bones.indexOf(bone), - wBindMatrix = bindBones ? bindBones[boneIndex] : bindBoneMatrix.copy(target.skeleton.boneInverses[boneIndex]).invert(); - globalMatrix.multiply(wBindMatrix); - } + return newTask; + } - globalMatrix.copyPosition(relativeMatrix); - } + function unstable_pauseExecution() { + } - if (bone.parent && bone.parent.isBone) { - bone.matrix.copy(bone.parent.matrixWorld).invert(); - bone.matrix.multiply(globalMatrix); - } else { - bone.matrix.copy(globalMatrix); - } + function unstable_continueExecution() { - if (options.preserveHipPosition && name === options.hip) { - bone.matrix.setPosition(pos.set(0, bone.position.y, 0)); - } + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } - bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); - bone.updateMatrixWorld(); - } + function unstable_getFirstCallbackNode() { + return peek(taskQueue); + } - if (options.preservePosition) { - for (i = 0; i < bones.length; ++i) { - bone = bones[i]; - name = options.names[bone.name] || bone.name; + function unstable_cancelCallback(task) { + // remove from the queue because you can't remove arbitrary nodes from an + // array based heap, only the first one.) - if (name !== options.hip) { - bone.position.copy(bonesPosition[i]); - } - } - } - if (options.preserveMatrix) { - // restore matrix - target.updateMatrixWorld(true); - } - }; - }(), - retargetClip: function (target, source, clip, options) { - options = options || {}; - options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false; - options.fps = options.fps !== undefined ? options.fps : 30; - options.names = options.names || []; - - if (!source.isObject3D) { - source = this.getHelperFromSkeleton(source); - } + task.callback = null; + } - var numFrames = Math.round(clip.duration * (options.fps / 1000) * 1000), - delta = 1 / options.fps, - convertedTracks = [], - mixer = new AnimationMixer(source), - bones = this.getBones(target.skeleton), - boneDatas = [], - positionOffset, - bone, - boneTo, - boneData, - name, - i, - j; - mixer.clipAction(clip).play(); - mixer.update(0); - source.updateMatrixWorld(); - - for (i = 0; i < numFrames; ++i) { - var time = i * delta; - this.retarget(target, source, options); - - for (j = 0; j < bones.length; ++j) { - name = options.names[bones[j].name] || bones[j].name; - boneTo = this.getBoneByName(name, source.skeleton); - - if (boneTo) { - bone = bones[j]; - boneData = boneDatas[j] = boneDatas[j] || { - bone: bone - }; + function unstable_getCurrentPriorityLevel() { + return currentPriorityLevel; + } - if (options.hip === name) { - if (!boneData.pos) { - boneData.pos = { - times: new Float32Array(numFrames), - values: new Float32Array(numFrames * 3) - }; - } + var isMessageLoopRunning = false; + var scheduledHostCallback = null; + var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main + // thread, like user events. By default, it yields multiple times per frame. + // It does not attempt to align with frame boundaries, since most tasks don't + // need to be frame aligned; for those that do, use requestAnimationFrame. - if (options.useFirstFramePosition) { - if (i === 0) { - positionOffset = bone.position.clone(); - } + var frameInterval = frameYieldMs; + var startTime = -1; - bone.position.sub(positionOffset); - } + function shouldYieldToHost() { + var timeElapsed = exports.unstable_now() - startTime; - boneData.pos.times[i] = time; - bone.position.toArray(boneData.pos.values, i * 3); - } + if (timeElapsed < frameInterval) { + // The main thread has only been blocked for a really short amount of time; + // smaller than a single frame. Don't yield yet. + return false; + } // The main thread has been blocked for a non-negligible amount of time. We - if (!boneData.quat) { - boneData.quat = { - times: new Float32Array(numFrames), - values: new Float32Array(numFrames * 4) - }; - } - boneData.quat.times[i] = time; - bone.quaternion.toArray(boneData.quat.values, i * 4); - } - } + return true; + } - mixer.update(delta); - source.updateMatrixWorld(); - } + function requestPaint() { - for (i = 0; i < boneDatas.length; ++i) { - boneData = boneDatas[i]; + } - if (boneData) { - if (boneData.pos) { - convertedTracks.push(new VectorKeyframeTrack('.bones[' + boneData.bone.name + '].position', boneData.pos.times, boneData.pos.values)); - } + function forceFrameRate(fps) { + if (fps < 0 || fps > 125) { + // Using console['error'] to evade Babel and ESLint + console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); + return; + } - convertedTracks.push(new QuaternionKeyframeTrack('.bones[' + boneData.bone.name + '].quaternion', boneData.quat.times, boneData.quat.values)); - } - } + if (fps > 0) { + frameInterval = Math.floor(1000 / fps); + } else { + // reset the framerate + frameInterval = frameYieldMs; + } + } - mixer.uncacheAction(clip); - return new AnimationClip(clip.name, -1, convertedTracks); - }, - getHelperFromSkeleton: function (skeleton) { - var source = new SkeletonHelper(skeleton.bones[0]); - source.skeleton = skeleton; - return source; - }, - getSkeletonOffsets: function () { - var targetParentPos = new Vector3(), - targetPos = new Vector3(), - sourceParentPos = new Vector3(), - sourcePos = new Vector3(), - targetDir = new Vector2(), - sourceDir = new Vector2(); - return function (target, source, options) { - options = options || {}; - options.hip = options.hip !== undefined ? options.hip : 'hip'; - options.names = options.names || {}; - - if (!source.isObject3D) { - source = this.getHelperFromSkeleton(source); - } + var performWorkUntilDeadline = function () { + if (scheduledHostCallback !== null) { + var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread + // has been blocked. - var nameKeys = Object.keys(options.names), - nameValues = Object.values(options.names), - sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones(source), - bones = target.isObject3D ? target.skeleton.bones : this.getBones(target), - offsets = [], - bone, - boneTo, - name, - i; - target.skeleton.pose(); - - for (i = 0; i < bones.length; ++i) { - bone = bones[i]; - name = options.names[bone.name] || bone.name; - boneTo = this.getBoneByName(name, sourceBones); - - if (boneTo && name !== options.hip) { - var boneParent = this.getNearestBone(bone.parent, nameKeys), - boneToParent = this.getNearestBone(boneTo.parent, nameValues); - boneParent.updateMatrixWorld(); - boneToParent.updateMatrixWorld(); - targetParentPos.setFromMatrixPosition(boneParent.matrixWorld); - targetPos.setFromMatrixPosition(bone.matrixWorld); - sourceParentPos.setFromMatrixPosition(boneToParent.matrixWorld); - sourcePos.setFromMatrixPosition(boneTo.matrixWorld); - targetDir.subVectors(new Vector2(targetPos.x, targetPos.y), new Vector2(targetParentPos.x, targetParentPos.y)).normalize(); - sourceDir.subVectors(new Vector2(sourcePos.x, sourcePos.y), new Vector2(sourceParentPos.x, sourceParentPos.y)).normalize(); - var laterialAngle = targetDir.angle() - sourceDir.angle(); - var offset = new Matrix4().makeRotationFromEuler(new Euler(0, 0, laterialAngle)); - bone.matrix.multiply(offset); - bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); - bone.updateMatrixWorld(); - offsets[name] = offset; - } - } + startTime = currentTime; + var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the + // error can be observed. + // + // Intentionally not using a try-catch, since that makes some debugging + // techniques harder. Instead, if `scheduledHostCallback` errors, then + // `hasMoreWork` will remain true, and we'll continue the work loop. - return offsets; - }; - }(), - renameBones: function (skeleton, names) { - var bones = this.getBones(skeleton); + var hasMoreWork = true; - for (let i = 0; i < bones.length; ++i) { - var bone = bones[i]; + try { + hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); + } finally { + if (hasMoreWork) { + // If there's more work, schedule the next message event at the end + // of the preceding one. + schedulePerformWorkUntilDeadline(); + } else { + isMessageLoopRunning = false; + scheduledHostCallback = null; + } + } + } else { + isMessageLoopRunning = false; + } // Yielding to the browser will give it a chance to paint, so we can + }; - if (names[bone.name]) { - bone.name = names[bone.name]; - } - } + var schedulePerformWorkUntilDeadline; - return this; - }, - getBones: function (skeleton) { - return Array.isArray(skeleton) ? skeleton : skeleton.bones; - }, - getBoneByName: function (name, skeleton) { - for (let i = 0, bones = this.getBones(skeleton); i < bones.length; i++) { - if (name === bones[i].name) return bones[i]; - } - }, - getNearestBone: function (bone, names) { - while (bone.isBone) { - if (names.indexOf(bone.name) !== -1) { - return bone; - } + if (typeof localSetImmediate === 'function') { + // Node.js and old IE. + // There's a few reasons for why we prefer setImmediate. + // + // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. + // (Even though this is a DOM fork of the Scheduler, you could get here + // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) + // https://github.com/facebook/react/issues/20756 + // + // But also, it runs earlier which is the semantic we want. + // If other browsers ever implement it, it's better to use it. + // Although both of these would be inferior to native scheduling. + schedulePerformWorkUntilDeadline = function () { + localSetImmediate(performWorkUntilDeadline); + }; + } else if (typeof MessageChannel !== 'undefined') { + // DOM and Worker environments. + // We prefer MessageChannel because of the 4ms setTimeout clamping. + var channel = new MessageChannel(); + var port = channel.port2; + channel.port1.onmessage = performWorkUntilDeadline; - bone = bone.parent; - } - }, - findBoneTrackData: function (name, tracks) { - var regexp = /\[(.*)\]\.(.*)/, - result = { - name: name - }; + schedulePerformWorkUntilDeadline = function () { + port.postMessage(null); + }; + } else { + // We should only fallback here in non-browser environments. + schedulePerformWorkUntilDeadline = function () { + localSetTimeout(performWorkUntilDeadline, 0); + }; + } - for (let i = 0; i < tracks.length; ++i) { - // 1 is track name - // 2 is track type - var trackData = regexp.exec(tracks[i].name); + function requestHostCallback(callback) { + scheduledHostCallback = callback; - if (trackData && name === trackData[1]) { - result[trackData[2]] = i; - } - } + if (!isMessageLoopRunning) { + isMessageLoopRunning = true; + schedulePerformWorkUntilDeadline(); + } + } - return result; - }, - getEqualsBonesNames: function (skeleton, targetSkeleton) { - var sourceBones = this.getBones(skeleton), - targetBones = this.getBones(targetSkeleton), - bones = []; - - search: for (let i = 0; i < sourceBones.length; i++) { - var boneName = sourceBones[i].name; - - for (let j = 0; j < targetBones.length; j++) { - if (boneName === targetBones[j].name) { - bones.push(boneName); - continue search; - } - } - } + function requestHostTimeout(callback, ms) { + taskTimeoutID = localSetTimeout(function () { + callback(exports.unstable_now()); + }, ms); + } - return bones; - }, - clone: function (source) { - var sourceLookup = new Map(); - var cloneLookup = new Map(); - var clone = source.clone(); - parallelTraverse(source, clone, function (sourceNode, clonedNode) { - sourceLookup.set(clonedNode, sourceNode); - cloneLookup.set(sourceNode, clonedNode); - }); - clone.traverse(function (node) { - if (!node.isSkinnedMesh) return; - var clonedMesh = node; - var sourceMesh = sourceLookup.get(node); - var sourceBones = sourceMesh.skeleton.bones; - clonedMesh.skeleton = sourceMesh.skeleton.clone(); - clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix); - clonedMesh.skeleton.bones = sourceBones.map(function (bone) { - return cloneLookup.get(bone); - }); - clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix); - }); - return clone; - } -}); + function cancelHostTimeout() { + localClearTimeout(taskTimeoutID); + taskTimeoutID = -1; + } -function parallelTraverse(a, b, callback) { - callback(a, b); + var unstable_requestPaint = requestPaint; + var unstable_Profiling = null; - for (let i = 0; i < a.children.length; i++) { - parallelTraverse(a.children[i], b.children[i], callback); - } + exports.unstable_IdlePriority = IdlePriority; + exports.unstable_ImmediatePriority = ImmediatePriority; + exports.unstable_LowPriority = LowPriority; + exports.unstable_NormalPriority = NormalPriority; + exports.unstable_Profiling = unstable_Profiling; + exports.unstable_UserBlockingPriority = UserBlockingPriority; + exports.unstable_cancelCallback = unstable_cancelCallback; + exports.unstable_continueExecution = unstable_continueExecution; + exports.unstable_forceFrameRate = forceFrameRate; + exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; + exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; + exports.unstable_next = unstable_next; + exports.unstable_pauseExecution = unstable_pauseExecution; + exports.unstable_requestPaint = unstable_requestPaint; + exports.unstable_runWithPriority = unstable_runWithPriority; + exports.unstable_scheduleCallback = unstable_scheduleCallback; + exports.unstable_shouldYield = shouldYieldToHost; + exports.unstable_wrapCallback = unstable_wrapCallback; + /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ + if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === + 'function' + ) { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); + } + + })(); + } +} (scheduler_development)); + return scheduler_development; } -/** - * Unpack RGBA depth shader - * - show RGBA encoded depth as monochrome color - */ -const UnpackDepthRGBAShader = { - uniforms: { - tDiffuse: { - value: null - }, - opacity: { - value: 1.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform float opacity;', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', '#include ', 'void main() {', ' float depth = 1.0 - unpackRGBAToDepth( texture2D( tDiffuse, vUv ) );', ' gl_FragColor = vec4( vec3( depth ), opacity );', '}'].join('\n') -}; +(function (module) { + + if (process.env.NODE_ENV === 'production') { + module.exports = requireScheduler_production_min(); + } else { + module.exports = requireScheduler_development(); + } +} (scheduler$1)); /** - * This is a helper for visualising a given light's shadow map. - * It works for shadow casting lights: DirectionalLight and SpotLight. - * It renders out the shadow map and displays it on a HUD. - * - * Example usage: - * 1) Import ShadowMapViewer into your app. - * - * 2) Create a shadow casting light and name it optionally: - * var light = new DirectionalLight( 0xffffff, 1 ); - * light.castShadow = true; - * light.name = 'Sun'; - * - * 3) Create a shadow map viewer for that light and set its size and position optionally: - * var shadowMapViewer = new ShadowMapViewer( light ); - * shadowMapViewer.size.set( 128, 128 ); //width, height default: 256, 256 - * shadowMapViewer.position.set( 10, 10 ); //x, y in pixel default: 0, 0 (top left corner) - * - * 4) Render the shadow map viewer in your render loop: - * shadowMapViewer.render( renderer ); + * @license React + * react-reconciler.production.min.js * - * 5) Optionally: Update the shadow map viewer on window resize: - * shadowMapViewer.updateForWindowResize(); + * Copyright (c) Facebook, Inc. and its affiliates. * - * 6) If you set the position or size members directly, you need to call shadowMapViewer.update(); + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -var ShadowMapViewer = function (light) { - //- Internals - var scope = this; - var doRenderLabel = light.name !== undefined && light.name !== ''; - var userAutoClearSetting; //Holds the initial position and dimension of the HUD - - var frame = { - x: 10, - y: 10, - width: 256, - height: 256 - }; - var camera = new OrthographicCamera(window.innerWidth / -2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / -2, 1, 10); - camera.position.set(0, 0, 2); - var scene = new Scene$1(); //HUD for shadow map - - var shader = UnpackDepthRGBAShader; - var uniforms = UniformsUtils.clone(shader.uniforms); - var material = new ShaderMaterial({ - uniforms: uniforms, - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - }); - var plane = new PlaneGeometry(frame.width, frame.height); - var mesh = new Mesh(plane, material); - scene.add(mesh); //Label for light's name - - var labelCanvas, labelMesh; - - if (doRenderLabel) { - labelCanvas = document.createElement('canvas'); - var context = labelCanvas.getContext('2d'); - context.font = 'Bold 20px Arial'; - var labelWidth = context.measureText(light.name).width; - labelCanvas.width = labelWidth; - labelCanvas.height = 25; //25 to account for g, p, etc. - - context.font = 'Bold 20px Arial'; - context.fillStyle = 'rgba( 255, 0, 0, 1 )'; - context.fillText(light.name, 0, 20); - var labelTexture = new Texture(labelCanvas); - labelTexture.magFilter = LinearFilter; - labelTexture.minFilter = LinearFilter; - labelTexture.needsUpdate = true; - var labelMaterial = new MeshBasicMaterial({ - map: labelTexture, - side: DoubleSide - }); - labelMaterial.transparent = true; - var labelPlane = new PlaneGeometry(labelCanvas.width, labelCanvas.height); - labelMesh = new Mesh(labelPlane, labelMaterial); - scene.add(labelMesh); - } - - function resetPosition() { - scope.position.set(scope.position.x, scope.position.y); - } //- API - // Set to false to disable displaying this shadow map - - - this.enabled = true; // Set the size of the displayed shadow map on the HUD - - this.size = { - width: frame.width, - height: frame.height, - set: function (width, height) { - this.width = width; - this.height = height; - mesh.scale.set(this.width / frame.width, this.height / frame.height, 1); //Reset the position as it is off when we scale stuff - - resetPosition(); - } - }; // Set the position of the displayed shadow map on the HUD - - this.position = { - x: frame.x, - y: frame.y, - set: function (x, y) { - this.x = x; - this.y = y; - var width = scope.size.width; - var height = scope.size.height; - mesh.position.set(-window.innerWidth / 2 + width / 2 + this.x, window.innerHeight / 2 - height / 2 - this.y, 0); - - if (doRenderLabel) { - labelMesh.position.set(mesh.position.x, mesh.position.y - scope.size.height / 2 + labelCanvas.height / 2, 0); - } - } - }; - - this.render = function (renderer) { - if (this.enabled) { - //Because a light's .shadowMap is only initialised after the first render pass - //we have to make sure the correct map is sent into the shader, otherwise we - //always end up with the scene's first added shadow casting light's shadowMap - //in the shader - //See: https://github.com/mrdoob/three.js/issues/5932 - uniforms.tDiffuse.value = light.shadow.map.texture; - userAutoClearSetting = renderer.autoClear; - renderer.autoClear = false; // To allow render overlay - - renderer.clearDepth(); - renderer.render(scene, camera); - renderer.autoClear = userAutoClearSetting; //Restore user's setting - } - }; - - this.updateForWindowResize = function () { - if (this.enabled) { - camera.left = window.innerWidth / -2; - camera.right = window.innerWidth / 2; - camera.top = window.innerHeight / 2; - camera.bottom = window.innerHeight / -2; - camera.updateProjectionMatrix(); - this.update(); - } - }; - - this.update = function () { - this.position.set(this.position.x, this.position.y); - this.size.set(this.size.width, this.size.height); - }; //Force an update to set position/size - - - this.update(); -}; +var reactReconciler_production_min; +var hasRequiredReactReconciler_production_min; -ShadowMapViewer.prototype.constructor = ShadowMapViewer; +function requireReactReconciler_production_min () { + if (hasRequiredReactReconciler_production_min) return reactReconciler_production_min; + hasRequiredReactReconciler_production_min = 1; + reactReconciler_production_min = function $$$reconciler($$$hostConfig) { + var exports = {}; +var aa=React__default,ba=scheduler$1.exports,ca=Object.assign;function n(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;ch||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{bc=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?ac(a):""}var dc=Object.prototype.hasOwnProperty,ec=[],fc=-1;function gc(a){return {current:a}} + function x(a){0>fc||(a.current=ec[fc],ec[fc]=null,fc--);}function y(a,b){fc++;ec[fc]=a.current;a.current=b;}var hc={},A=gc(hc),B=gc(!1),ic=hc;function jc(a,b){var c=a.type.contextTypes;if(!c)return hc;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} + function C(a){a=a.childContextTypes;return null!==a&&void 0!==a}function kc(){x(B);x(A);}function lc(a,b,c){if(A.current!==hc)throw Error(n(168));y(A,b);y(B,c);}function mc(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(n(108,xa(a)||"Unknown",e));return ca({},c,d)} + function nc(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||hc;ic=A.current;y(A,a);y(B,B.current);return !0}function oc(a,b,c){var d=a.stateNode;if(!d)throw Error(n(169));c?(a=mc(a,b,ic),d.__reactInternalMemoizedMergedChildContext=a,x(B),x(A),y(A,a)):x(B);y(B,c);}var qc=Math.clz32?Math.clz32:pc,rc=Math.log,sc=Math.LN2;function pc(a){a>>>=0;return 0===a?32:31-(rc(a)/sc|0)|0}var tc=64,uc=4194304; + function vc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; + default:return a}}function wc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=vc(h):(f&=g,0!==f&&(d=vc(f)));}else g=c&~e,0!==g?d=vc(g):0!==f&&(d=vc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}function Bc(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-qc(b);a[b]=c;} + function Cc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0>=g;e-=g;Nd=1<<32-qc(b)+e|c<u?(t=w,w=null):t=w.sibling;var q=r(e,w,h[u],k);if(null===q){null===w&&(w=t);break}a&&w&&null===q.alternate&&b(e,w);g=f(q,g,u);null===m?l=q:m.sibling=q;m=q;w=t;}if(u===h.length)return c(e,w),I&&Pd(e,u),l;if(null===w){for(;uu?(q=m,m=null):q=m.sibling;var V=r(e,m,t.value,k);if(null===V){null===m&&(m=q);break}a&&m&&null===V.alternate&&b(e,m);g=f(V,g,u);null===w?l=V:w.sibling=V;w=V;m=q;}if(t.done)return c(e, + m),I&&Pd(e,u),l;if(null===m){for(;!t.done;u++,t=h.next())t=v(e,t.value,k),null!==t&&(g=f(t,g,u),null===w?l=t:w.sibling=t,w=t);I&&Pd(e,u);return l}for(m=d(e,m);!t.done;u++,t=h.next())t=z(m,e,u,t.value,k),null!==t&&(a&&null!==t.alternate&&m.delete(null===t.key?u:t.key),g=f(t,g,u),null===w?l=t:w.sibling=t,w=t);a&&m.forEach(function(a){return b(e,a)});I&&Pd(e,u);return l}function da(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ia&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!== + f){switch(f.$$typeof){case fa:a:{for(var k=f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ia){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===ra&&he(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=fe(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===ia?(d=ne(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=le(f.type,f.key,f.props,null,a.mode,h),h.ref=fe(a,d,f),h.return= + a,a=h);}return g(a);case ha:a:{for(l=f.key;null!==d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=me(f,a.mode,h);d.return=a;a=d;}return g(a);case ra:return l=f._init,da(a,d,l(f._payload),h)}if(Ea(f))return q(a,d,f,h);if(ua(f))return N(a,d,f,h);ge(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&& + 6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=ke(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return da}var oe=ie(!0),pe=ie(!1),qe={},re=gc(qe),se=gc(qe),te=gc(qe);function ue(a){if(a===qe)throw Error(n(174));return a}function ve(a,b){y(te,b);y(se,a);y(re,qe);a=Ga(b);x(re);y(re,a);}function we(){x(re);x(se);x(te);}function xe(a){var b=ue(te.current),c=ue(re.current);b=Ha(c,a.type,b);c!==b&&(y(se,a),y(re,b));}function ye(a){se.current===a&&(x(re),x(se));}var J=gc(0); + function ze(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||Ib(c)||Jb(c)))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Ae=[]; + function Be(){for(var a=0;ac?c:4;a(!0);var d=De.transition;De.transition={};try{a(!1),b();}finally{D=c,De.transition=d;}}function rf(){return Re().memoizedState}function sf(a,b,c){var d=zd(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};tf(a)?uf(b,c):(vf(a,b,c),c=H(),a=Ad(a,d,c),null!==a&&wf(a,b,d));} + function df(a,b,c){var d=zd(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(tf(a))uf(b,e);else {vf(a,b,e);var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(Rc(h,g))return}catch(k){}finally{}c=H();a=Ad(a,d,c);null!==a&&wf(a,b,d);}}function tf(a){var b=a.alternate;return a===K||null!==b&&b===K} + function uf(a,b){Ge=Fe=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function vf(a,b,c){null!==F&&0!==(a.mode&1)&&0===(G&2)?(a=b.interleaved,null===a?(c.next=c,null===md?md=[b]:md.push(b)):(c.next=a.next,a.next=c),b.interleaved=c):(a=b.pending,null===a?c.next=c:(c.next=a.next,a.next=c),b.pending=c);}function wf(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Dc(a,c);}} + var Oe={readContext:ld,useCallback:O,useContext:O,useEffect:O,useImperativeHandle:O,useInsertionEffect:O,useLayoutEffect:O,useMemo:O,useReducer:O,useRef:O,useState:O,useDebugValue:O,useDeferredValue:O,useTransition:O,useMutableSource:O,useSyncExternalStore:O,useId:O,unstable_isNewReconciler:!1},Le={readContext:ld,useCallback:function(a,b){Qe().memoizedState=[a,void 0===b?null:b];return a},useContext:ld,useEffect:hf,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ff(4194308, + 4,lf.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ff(4194308,4,a,b)},useInsertionEffect:function(a,b){return ff(4,2,a,b)},useMemo:function(a,b){var c=Qe();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Qe();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=sf.bind(null,K,a);return [d.memoizedState,a]},useRef:function(a){var b= + Qe();a={current:a};return b.memoizedState=a},useState:cf,useDebugValue:nf,useDeferredValue:function(a){var b=cf(a),c=b[0],d=b[1];hf(function(){var b=De.transition;De.transition={};try{d(a);}finally{De.transition=b;}},[a]);return c},useTransition:function(){var a=cf(!1),b=a[0];a=qf.bind(null,a[1]);Qe().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=K,e=Qe();if(I){if(void 0===c)throw Error(n(407));c=c();}else {c=b();if(null===F)throw Error(n(349)); + 0!==(Ee&30)||af(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;hf(Ye.bind(null,d,f,a),[a]);d.flags|=2048;Ze(9,$e.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Qe(),b=F.identifierPrefix;if(I){var c=Od;var d=Nd;c=(d&~(1<<32-qc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=He++;0Uf&&(b.flags|=128,d=!0,Qf(e,!1),b.lanes=4194304);}else {if(!d)if(a=ze(f),null!==a){if(b.flags|=128,d=!0,a=a.updateQueue,null!==a&&(b.updateQueue=a,b.flags|=4),Qf(e,!0),null===e.tail&&"hidden"===e.tailMode&&!f.alternate&&!I)return P(b),null}else 2*E()-e.renderingStartTime>Uf&&1073741824!==c&&(b.flags|=128,d=!0,Qf(e,!1),b.lanes=4194304);e.isBackwards?(f.sibling=b.child,b.child=f):(a=e.last,null!==a?a.sibling=f:b.child=f,e.last=f);}if(null!== + e.tail)return b=e.tail,e.rendering=b,e.tail=b.sibling,e.renderingStartTime=E(),b.sibling=null,a=J.current,y(J,d?a&1|2:a&1),b;P(b);return null;case 22:case 23:return Vf(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(Wf&1073741824)&&(P(b),Ua&&b.subtreeFlags&6&&(b.flags|=8192)):P(b),null;case 24:return null;case 25:return null}throw Error(n(156,b.tag));}var Xf=ea.ReactCurrentOwner,kd=!1; + function R(a,b,c,d){b.child=null===a?pe(b,null,c,d):oe(b,a.child,c,d);}function Yf(a,b,c,d,e){c=c.render;var f=b.ref;jd(b,e);d=Ke(a,b,c,d,f,e);c=Pe();if(null!==a&&!kd)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zf(a,b,e);I&&c&&Rd(b);b.flags|=1;R(a,b,d,e);return b.child} + function $f(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!ag(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,bg(a,b,f,d,e);a=le(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Zc;if(c(g,d)&&a.ref===b.ref)return Zf(a,b,e)}b.flags|=1;a=je(f,d);a.ref=b.ref;a.return=b;return b.child=a} + function bg(a,b,c,d,e){if(null!==a&&Zc(a.memoizedProps,d)&&a.ref===b.ref)if(kd=!1,0!==(a.lanes&e))0!==(a.flags&131072)&&(kd=!0);else return b.lanes=a.lanes,Zf(a,b,e);return cg(a,b,c,d,e)} + function dg(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null},y(eg,Wf),Wf|=c;else if(0!==(c&1073741824))b.memoizedState={baseLanes:0,cachePool:null},d=null!==f?f.baseLanes:c,y(eg,Wf),Wf|=d;else return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null},b.updateQueue=null,y(eg,Wf),Wf|=a,null;else null!==f?(d=f.baseLanes|c,b.memoizedState=null): + d=c,y(eg,Wf),Wf|=d;R(a,b,e,c);return b.child}function fg(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152;}function cg(a,b,c,d,e){var f=C(c)?ic:A.current;f=jc(b,f);jd(b,e);c=Ke(a,b,c,d,f,e);d=Pe();if(null!==a&&!kd)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zf(a,b,e);I&&d&&Rd(b);b.flags|=1;R(a,b,c,e);return b.child} + function gg(a,b,c,d,e){if(C(c)){var f=!0;nc(b);}else f=!1;jd(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),Dd(b,c,d),Fd(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=ld(l):(l=C(c)?ic:A.current,l=jc(b,l));var m=c.getDerivedStateFromProps,v="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;v||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!== + typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Ed(b,g,d,l);nd=!1;var r=b.memoizedState;g.state=r;ud(b,d,g,e);k=b.memoizedState;h!==d||r!==k||B.current||nd?("function"===typeof m&&(yd(b,c,m,d),k=b.memoizedState),(h=nd||Cd(b,c,h,d,r,k,l))?(v||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&& + (b.flags|=4194308)):("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1);}else {g=b.stateNode;pd(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:ad(b.type,h);g.props=l;v=b.pendingProps;r=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=ld(k):(k=C(c)?ic:A.current,k=jc(b,k));var z=c.getDerivedStateFromProps;(m="function"===typeof z||"function"=== + typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==v||r!==k)&&Ed(b,g,d,k);nd=!1;r=b.memoizedState;g.state=r;ud(b,d,g,e);var q=b.memoizedState;h!==v||r!==q||B.current||nd?("function"===typeof z&&(yd(b,c,z,d),q=b.memoizedState),(l=nd||Cd(b,c,l,d,r,q,k)||!1)?(m||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d, + q,k),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,q,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=q),g.props=d,g.state=q,g.context=k,d=l):("function"!== + typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1);}return hg(a,b,c,d,f,e)} + function hg(a,b,c,d,e,f){fg(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&oc(b,c,!1),Zf(a,b,f);d=b.stateNode;Xf.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=oe(b,a.child,null,f),b.child=oe(b,null,h,f)):R(a,b,h,f);b.memoizedState=d.state;e&&oc(b,c,!0);return b.child}function ig(a){var b=a.stateNode;b.pendingContext?lc(a,b.pendingContext,b.pendingContext!==b.context):b.context&&lc(a,b.context,!1);ve(a,b.containerInfo);} + function jg(a,b,c,d,e){de();ee(e);b.flags|=256;R(a,b,c,d);return b.child}var kg={dehydrated:null,treeContext:null,retryLane:0};function lg(a){return {baseLanes:a,cachePool:null}} + function mg(a,b,c){var d=b.pendingProps,e=J.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;y(J,e&1);if(null===a){ae(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:Jb(a)?b.lanes=8:b.lanes=1073741824,null;e=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,e={mode:"hidden",children:e},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=e): + f=ng(e,d,0,null),a=ne(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=lg(c),b.memoizedState=kg,a):og(b,e)}e=a.memoizedState;if(null!==e){h=e.dehydrated;if(null!==h){if(g){if(b.flags&256)return b.flags&=-257,pg(a,b,c,Error(n(422)));if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=ng({mode:"visible",children:d.children},e,0,null);f=ne(f,e,c,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&oe(b,a.child, + null,c);b.child.memoizedState=lg(c);b.memoizedState=kg;return f}if(0===(b.mode&1))b=pg(a,b,c,null);else if(Jb(h))b=pg(a,b,c,Error(n(419)));else if(d=0!==(c&a.childLanes),kd||d){d=F;if(null!==d){switch(c&-c){case 4:f=2;break;case 16:f=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:f=32;break;case 536870912:f= + 268435456;break;default:f=0;}d=0!==(f&(d.suspendedLanes|c))?0:f;0!==d&&d!==e.retryLane&&(e.retryLane=d,Ad(a,d,-1));}Tf();b=pg(a,b,c,Error(n(421)));}else Ib(h)?(b.flags|=128,b.child=a.child,b=qg.bind(null,a),Kb(h,b),b=null):(c=e.treeContext,p&&(Ud=Ob(h),Td=b,I=!0,Wd=null,Vd=!1,null!==c&&(Kd[Ld++]=Nd,Kd[Ld++]=Od,Kd[Ld++]=Md,Nd=c.id,Od=c.overflow,Md=b)),b=og(b,b.pendingProps.children),b.flags|=4096);return b}if(f)return d=rg(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState= + null===e?lg(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kg,d;c=sg(a,b,d.children,c);b.memoizedState=null;return c}if(f)return d=rg(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState=null===e?lg(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kg,d;c=sg(a,b,d.children,c);b.memoizedState=null;return c} + function og(a,b){b=ng({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function sg(a,b,c,d){var e=a.child;a=e.sibling;c=je(e,{mode:"visible",children:c});0===(b.mode&1)&&(c.lanes=d);c.return=b;c.sibling=null;null!==a&&(d=b.deletions,null===d?(b.deletions=[a],b.flags|=16):d.push(a));return b.child=c} + function rg(a,b,c,d,e){var f=b.mode;a=a.child;var g=a.sibling,h={mode:"hidden",children:c};0===(f&1)&&b.child!==a?(c=b.child,c.childLanes=0,c.pendingProps=h,b.deletions=null):(c=je(a,h),c.subtreeFlags=a.subtreeFlags&14680064);null!==g?d=je(g,d):(d=ne(d,f,e,null),d.flags|=2);d.return=b;c.return=b;c.sibling=d;b.child=c;return d}function pg(a,b,c,d){null!==d&&ee(d);oe(b,a.child,null,c);a=og(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a} + function tg(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);id(a.return,b,c);}function ug(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e);} + function vg(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;R(a,b,d.children,c);d=J.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else {if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&tg(a,c,b);else if(19===a.tag)tg(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return;}a.sibling.return=a.return;a=a.sibling;}d&=1;}y(J,d);if(0===(b.mode&1))b.memoizedState= + null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===ze(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);ug(b,!1,e,c,f);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===ze(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a;}ug(b,!0,c,null,f);break;case "together":ug(b,!1,null,null,void 0);break;default:b.memoizedState=null;}return b.child} + function Zf(a,b,c){null!==a&&(b.dependencies=a.dependencies);vd|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(n(153));if(null!==b.child){a=b.child;c=je(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=je(a,a.pendingProps),c.return=b;c.sibling=null;}return b.child} + function wg(a,b,c){switch(b.tag){case 3:ig(b);de();break;case 5:xe(b);break;case 1:C(b.type)&&nc(b);break;case 4:ve(b,b.stateNode.containerInfo);break;case 10:gd(b,b.type._context,b.memoizedProps.value);break;case 13:var d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return y(J,J.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return mg(a,b,c);y(J,J.current&1);a=Zf(a,b,c);return null!==a?a.sibling:null}y(J,J.current&1);break;case 19:d=0!==(c&b.childLanes);if(0!==(a.flags&128)){if(d)return vg(a, + b,c);b.flags|=128;}var e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);y(J,J.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,dg(a,b,c)}return Zf(a,b,c)} + function xg(a,b){Sd(b);switch(b.tag){case 1:return C(b.type)&&kc(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return we(),x(B),x(A),Be(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return ye(b),null;case 13:x(J);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(n(340));de();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return x(J),null;case 4:return we(),null;case 10:return hd(b.type._context),null;case 22:case 23:return Vf(), + null;case 24:return null;default:return null}}var yg=!1,zg=!1,Ag="function"===typeof WeakSet?WeakSet:Set,S=null;function Bg(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){T(a,b,d);}else c.current=null;}function Cg(a,b,c){try{c();}catch(d){T(a,b,d);}}var Dg=!1; + function Eg(a,b){Ia(a.containerInfo);for(S=b;null!==S;)if(a=S,b=a.child,0!==(a.subtreeFlags&1028)&&null!==b)b.return=a,S=b;else for(;null!==S;){a=S;try{var c=a.alternate;if(0!==(a.flags&1024))switch(a.tag){case 0:case 11:case 15:break;case 1:if(null!==c){var d=c.memoizedProps,e=c.memoizedState,f=a.stateNode,g=f.getSnapshotBeforeUpdate(a.elementType===a.type?d:ad(a.type,d),e);f.__reactInternalSnapshotBeforeUpdate=g;}break;case 3:Ua&&xb(a.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break; + default:throw Error(n(163));}}catch(h){T(a,a.return,h);}b=a.sibling;if(null!==b){b.return=a.return;S=b;break}S=a.return;}c=Dg;Dg=!1;return c}function Fg(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Cg(b,c,f);}e=e.next;}while(e!==d)}}function Gg(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}} + function Hg(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=Fa(c);break;default:a=c;}"function"===typeof b?b(a):b.current=a;}} + function Ig(a,b,c){if(Oc&&"function"===typeof Oc.onCommitFiberUnmount)try{Oc.onCommitFiberUnmount(Nc,b);}catch(g){}switch(b.tag){case 0:case 11:case 14:case 15:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var d=a=a.next;do{var e=d,f=e.destroy;e=e.tag;void 0!==f&&(0!==(e&2)?Cg(b,c,f):0!==(e&4)&&Cg(b,c,f));d=d.next;}while(d!==a)}break;case 1:Bg(b,c);a=b.stateNode;if("function"===typeof a.componentWillUnmount)try{a.props=b.memoizedProps,a.state=b.memoizedState,a.componentWillUnmount();}catch(g){T(b, + c,g);}break;case 5:Bg(b,c);break;case 4:Ua?Jg(a,b,c):Va&&Va&&(b=b.stateNode.containerInfo,c=zb(b),Cb(b,c));}}function Kg(a,b,c){for(var d=b;;)if(Ig(a,d,c),null===d.child||Ua&&4===d.tag){if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;}d.sibling.return=d.return;d=d.sibling;}else d.child.return=d,d=d.child;} + function Lg(a){var b=a.alternate;null!==b&&(a.alternate=null,Lg(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&Za(b));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Mg(a){return 5===a.tag||3===a.tag||4===a.tag} + function Ng(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Mg(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}} + function Og(a){if(Ua){a:{for(var b=a.return;null!==b;){if(Mg(b))break a;b=b.return;}throw Error(n(160));}var c=b;switch(c.tag){case 5:b=c.stateNode;c.flags&32&&(sb(b),c.flags&=-33);c=Ng(a);Pg(a,c,b);break;case 3:case 4:b=c.stateNode.containerInfo;c=Ng(a);Qg(a,c,b);break;default:throw Error(n(161));}}}function Qg(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?pb(c,a,b):kb(c,a);else if(4!==d&&(a=a.child,null!==a))for(Qg(a,b,c),a=a.sibling;null!==a;)Qg(a,b,c),a=a.sibling;} + function Pg(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?ob(c,a,b):jb(c,a);else if(4!==d&&(a=a.child,null!==a))for(Pg(a,b,c),a=a.sibling;null!==a;)Pg(a,b,c),a=a.sibling;} + function Jg(a,b,c){for(var d=b,e=!1,f,g;;){if(!e){e=d.return;a:for(;;){if(null===e)throw Error(n(160));f=e.stateNode;switch(e.tag){case 5:g=!1;break a;case 3:f=f.containerInfo;g=!0;break a;case 4:f=f.containerInfo;g=!0;break a}e=e.return;}e=!0;}if(5===d.tag||6===d.tag)Kg(a,d,c),g?rb(f,d.stateNode):qb(f,d.stateNode);else if(18===d.tag)g?Wb(f,d.stateNode):Vb(f,d.stateNode);else if(4===d.tag){if(null!==d.child){f=d.stateNode.containerInfo;g=!0;d.child.return=d;d=d.child;continue}}else if(Ig(a,d,c),null!== + d.child){d.child.return=d;d=d.child;continue}if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;4===d.tag&&(e=!1);}d.sibling.return=d.return;d=d.sibling;}} + function Rg(a,b){if(Ua){switch(b.tag){case 0:case 11:case 14:case 15:Fg(3,b,b.return);Gg(3,b);Fg(5,b,b.return);return;case 1:return;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps;a=null!==a?a.memoizedProps:d;var e=b.type,f=b.updateQueue;b.updateQueue=null;null!==f&&nb(c,f,e,a,d,b);}return;case 6:if(null===b.stateNode)throw Error(n(162));c=b.memoizedProps;lb(b.stateNode,null!==a?a.memoizedProps:c,c);return;case 3:p&&null!==a&&a.memoizedState.isDehydrated&&Tb(b.stateNode.containerInfo);return; + case 12:return;case 13:Sg(b);return;case 19:Sg(b);return;case 17:return}throw Error(n(163));}switch(b.tag){case 0:case 11:case 14:case 15:Fg(3,b,b.return);Gg(3,b);Fg(5,b,b.return);return;case 12:return;case 13:Sg(b);return;case 19:Sg(b);return;case 3:p&&null!==a&&a.memoizedState.isDehydrated&&Tb(b.stateNode.containerInfo);break;case 22:case 23:return}a:if(Va){switch(b.tag){case 1:case 5:case 6:break a;case 3:case 4:b=b.stateNode;Cb(b.containerInfo,b.pendingChildren);break a}throw Error(n(163));}} + function Sg(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Ag);b.forEach(function(b){var d=Tg.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}} + function Ug(a,b){for(S=b;null!==S;){b=S;var c=b.deletions;if(null!==c)for(var d=0;d";case bh:return ":has("+(ih(a)||"")+")";case ch:return '[role="'+a.value+'"]';case eh:return '"'+a.value+'"';case dh:return '[data-testname="'+a.value+'"]';default:throw Error(n(365));}} + function jh(a,b){var c=[];a=[a,0];for(var d=0;de&&(e=g);d&=~f;}d=e;d=E()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lh(d/1960))-d;if(10a?16:a;if(null===uh)var d=!1;else {a=uh;uh=null;vh=0;if(0!==(G&6))throw Error(n(331));var e=G;G|=4;for(S=a.current;null!==S;){var f=S,g=f.child;if(0!==(S.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kE()-Vg?Ih(a,0):qh|=c);Z(a,b);}function Vh(a,b){0===b&&(0===(a.mode&1)?b=1:(b=uc,uc<<=1,0===(uc&130023424)&&(uc=4194304)));var c=H();a=Ah(a,b);null!==a&&(Bc(a,b,c),Z(a,c));}function qg(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Vh(a,c);} + function Tg(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(n(314));}null!==d&&d.delete(b);Vh(a,c);}var Sh; + Sh=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||B.current)kd=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return kd=!1,wg(a,b,c);kd=0!==(a.flags&131072)?!0:!1;}else kd=!1,I&&0!==(b.flags&1048576)&&Qd(b,Jd,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;var e=jc(b,A.current);jd(b,c);e=Ke(null,b,d,a,e,c);var f=Pe();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof? + (b.tag=1,b.memoizedState=null,b.updateQueue=null,C(d)?(f=!0,nc(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,od(b),e.updater=Bd,b.stateNode=e,e._reactInternals=b,Fd(b,d,a,c),b=hg(null,b,d,!0,f,c)):(b.tag=0,I&&f&&Rd(b),R(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Wh(d);a=ad(d,a);switch(e){case 0:b=cg(null,b,d,a,c);break a;case 1:b=gg(null,b,d, + a,c);break a;case 11:b=Yf(null,b,d,a,c);break a;case 14:b=$f(null,b,d,ad(d.type,a),c);break a}throw Error(n(306,d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),cg(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),gg(a,b,d,e,c);case 3:a:{ig(b);if(null===a)throw Error(n(387));d=b.pendingProps;f=b.memoizedState;e=f.element;pd(a,b);ud(b,d,null,c);var g=b.memoizedState;d=g.element;if(p&&f.isDehydrated)if(f={element:d,isDehydrated:!1, + cache:g.cache,transitions:g.transitions},b.updateQueue.baseState=f,b.memoizedState=f,b.flags&256){e=Error(n(423));b=jg(a,b,d,c,e);break a}else if(d!==e){e=Error(n(424));b=jg(a,b,d,c,e);break a}else for(p&&(Ud=Nb(b.stateNode.containerInfo),Td=b,I=!0,Wd=null,Vd=!1),c=pe(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {de();if(d===e){b=Zf(a,b,c);break a}R(a,b,d,c);}b=b.child;}return b;case 5:return xe(b),null===a&&ae(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children, + Oa(d,e)?g=null:null!==f&&Oa(d,f)&&(b.flags|=32),fg(a,b),R(a,b,g,c),b.child;case 6:return null===a&&ae(b),null;case 13:return mg(a,b,c);case 4:return ve(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=oe(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),Yf(a,b,d,e,c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:return R(a,b,b.pendingProps.children,c),b.child;case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d= + b.type._context;e=b.pendingProps;f=b.memoizedProps;g=e.value;gd(b,d,g);if(null!==f)if(Rc(f.value,g)){if(f.children===e.children&&!B.current){b=Zf(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=qd(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|= + c);id(f.return,c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(n(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);id(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}R(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,jd(b,c),e=ld(e),d=d(e),b.flags|= + 1,R(a,b,d,c),b.child;case 14:return d=b.type,e=ad(d,b.pendingProps),e=ad(d.type,e),$f(a,b,d,e,c);case 15:return bg(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),b.tag=1,C(d)?(a=!0,nc(b)):a=!1,jd(b,c),Dd(b,d,e),Fd(b,d,e,c),hg(null,b,d,!0,a,c);case 19:return vg(a,b,c);case 22:return dg(a,b,c)}throw Error(n(156,b.tag));};function Dh(a,b){return Fc(a,b)} + function Xh(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Yd(a,b,c,d){return new Xh(a,b,c,d)}function ag(a){a=a.prototype;return !(!a||!a.isReactComponent)} + function Wh(a){if("function"===typeof a)return ag(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===na)return 11;if(a===qa)return 14}return 2} + function je(a,b){var c=a.alternate;null===c?(c=Yd(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; + c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} + function le(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)ag(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ia:return ne(c.children,e,f,b);case ja:g=8;e|=8;break;case ka:return a=Yd(12,c,b,e|2),a.elementType=ka,a.lanes=f,a;case oa:return a=Yd(13,c,b,e),a.elementType=oa,a.lanes=f,a;case pa:return a=Yd(19,c,b,e),a.elementType=pa,a.lanes=f,a;case sa:return ng(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case la:g=10;break a;case ma:g=9;break a;case na:g=11; + break a;case qa:g=14;break a;case ra:g=16;d=null;break a}throw Error(n(130,null==a?a:typeof a,""));}b=Yd(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function ne(a,b,c,d){a=Yd(7,a,d,b);a.lanes=c;return a}function ng(a,b,c,d){a=Yd(22,a,d,b);a.elementType=sa;a.lanes=c;a.stateNode={};return a}function ke(a,b,c){a=Yd(6,a,null,b);a.lanes=c;return a} + function me(a,b,c){b=Yd(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} + function Yh(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=Sa;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=Ac(0);this.expirationTimes=Ac(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=Ac(0);this.identifierPrefix=d;this.onRecoverableError=e;p&&(this.mutableSourceEagerHydrationData= + null);}function Zh(a,b,c,d,e,f,g,h,k){a=new Yh(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Yd(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null};od(f);return a} + function $h(a){if(!a)return hc;a=a._reactInternals;a:{if(ya(a)!==a||1!==a.tag)throw Error(n(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(C(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return;}while(null!==b);throw Error(n(171));}if(1===a.tag){var c=a.type;if(C(c))return mc(a,c,b)}return b} + function ai(a){var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(n(188));a=Object.keys(a).join(",");throw Error(n(268,a));}a=Ba(b);return null===a?null:a.stateNode}function bi(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c=l&&f>=v&&e<=m&&g<=r){a.splice(b,1);break}else if(!(d!==l||c.width!==k.width||rg)){v>f&&(k.height+=v-f,k.y=f);re)){l>d&&(k.width+= + l-d,k.x=d);mc&&(c=g)),g ")+"\n\nNo matching component was found for:\n ")+a.join(" > ")}return null}; + exports.getPublicRootInstance=function(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return Fa(a.child.stateNode);default:return a.child.stateNode}}; + exports.injectIntoDevTools=function(a){a={bundleType:a.bundleType,version:a.version,rendererPackageName:a.rendererPackageName,rendererConfig:a.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ea.ReactCurrentDispatcher,findHostInstanceByFiber:di,findFiberByHostInstance:a.findFiberByHostInstance|| + ei,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.0.0-fc46dba67-20220329"};if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)a=!1;else {var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)a=!0;else {try{Nc=b.inject(a),Oc=b;}catch(c){}a=b.checkDCE?!0:!1;}}return a};exports.isAlreadyRendering=function(){return !1}; + exports.observeVisibleRects=function(a,b,c,d){if(!bb)throw Error(n(363));a=kh(a,b);var e=ib(a,c,d).disconnect;return {disconnect:function(){e();}}};exports.registerMutableSourceForHydration=function(a,b){var c=b._getVersion;c=c(b._source);null==a.mutableSourceEagerHydrationData?a.mutableSourceEagerHydrationData=[b,c]:a.mutableSourceEagerHydrationData.push(b,c);};exports.runWithPriority=function(a,b){var c=D;try{return D=a,b()}finally{D=c;}};exports.shouldError=function(){return null}; + exports.shouldSuspend=function(){return !1};exports.updateContainer=function(a,b,c,d){var e=b.current,f=H(),g=zd(e);c=$h(c);null===b.context?b.context=c:b.pendingContext=c;b=qd(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);rd(e,b);a=Ad(e,g,f);null!==a&&sd(a,e,g);return g}; -/** - * Depth-of-field shader with bokeh - * ported from GLSL shader by Martins Upitis - * http://blenderartists.org/forum/showthread.php?237488-GLSL-depth-of-field-with-bokeh-v2-4-(update) - * - * Requires #define RINGS and SAMPLES integers - */ + return exports; + }; + return reactReconciler_production_min; +} -({ - uniforms: { - textureWidth: { - value: 1.0 - }, - textureHeight: { - value: 1.0 - }, - focalDepth: { - value: 1.0 - }, - focalLength: { - value: 24.0 - }, - fstop: { - value: 0.9 - }, - tColor: { - value: null - }, - tDepth: { - value: null - }, - maxblur: { - value: 1.0 - }, - showFocus: { - value: 0 - }, - manualdof: { - value: 0 - }, - vignetting: { - value: 0 - }, - depthblur: { - value: 0 - }, - threshold: { - value: 0.5 - }, - gain: { - value: 2.0 - }, - bias: { - value: 0.5 - }, - fringe: { - value: 0.7 - }, - znear: { - value: 0.1 - }, - zfar: { - value: 100 - }, - noise: { - value: 1 - }, - dithering: { - value: 0.0001 - }, - pentagon: { - value: 0 - }, - shaderFocus: { - value: 1 - }, - focusCoords: { - value: new Vector2() - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', 'varying vec2 vUv;', 'uniform sampler2D tColor;', 'uniform sampler2D tDepth;', 'uniform float textureWidth;', 'uniform float textureHeight;', 'uniform float focalDepth; //focal distance value in meters, but you may use autofocus option below', 'uniform float focalLength; //focal length in mm', 'uniform float fstop; //f-stop value', 'uniform bool showFocus; //show debug focus point and focal range (red = focal point, green = focal range)', '/*', 'make sure that these two values are the same for your camera, otherwise distances will be wrong.', '*/', 'uniform float znear; // camera clipping start', 'uniform float zfar; // camera clipping end', '//------------------------------------------', '//user variables', 'const int samples = SAMPLES; //samples on the first ring', 'const int rings = RINGS; //ring count', 'const int maxringsamples = rings * samples;', 'uniform bool manualdof; // manual dof calculation', 'float ndofstart = 1.0; // near dof blur start', 'float ndofdist = 2.0; // near dof blur falloff distance', 'float fdofstart = 1.0; // far dof blur start', 'float fdofdist = 3.0; // far dof blur falloff distance', 'float CoC = 0.03; //circle of confusion size in mm (35mm film = 0.03mm)', 'uniform bool vignetting; // use optical lens vignetting', 'float vignout = 1.3; // vignetting outer border', 'float vignin = 0.0; // vignetting inner border', 'float vignfade = 22.0; // f-stops till vignete fades', 'uniform bool shaderFocus;', '// disable if you use external focalDepth value', 'uniform vec2 focusCoords;', '// autofocus point on screen (0.0,0.0 - left lower corner, 1.0,1.0 - upper right)', '// if center of screen use vec2(0.5, 0.5);', 'uniform float maxblur;', '//clamp value of max blur (0.0 = no blur, 1.0 default)', 'uniform float threshold; // highlight threshold;', 'uniform float gain; // highlight gain;', 'uniform float bias; // bokeh edge bias', 'uniform float fringe; // bokeh chromatic aberration / fringing', 'uniform bool noise; //use noise instead of pattern for sample dithering', 'uniform float dithering;', 'uniform bool depthblur; // blur the depth buffer', 'float dbsize = 1.25; // depth blur size', '/*', 'next part is experimental', 'not looking good with small sample and ring count', 'looks okay starting from samples = 4, rings = 4', '*/', 'uniform bool pentagon; //use pentagon as bokeh shape?', 'float feather = 0.4; //pentagon shape feather', '//------------------------------------------', 'float penta(vec2 coords) {', ' //pentagonal shape', ' float scale = float(rings) - 1.3;', ' vec4 HS0 = vec4( 1.0, 0.0, 0.0, 1.0);', ' vec4 HS1 = vec4( 0.309016994, 0.951056516, 0.0, 1.0);', ' vec4 HS2 = vec4(-0.809016994, 0.587785252, 0.0, 1.0);', ' vec4 HS3 = vec4(-0.809016994,-0.587785252, 0.0, 1.0);', ' vec4 HS4 = vec4( 0.309016994,-0.951056516, 0.0, 1.0);', ' vec4 HS5 = vec4( 0.0 ,0.0 , 1.0, 1.0);', ' vec4 one = vec4( 1.0 );', ' vec4 P = vec4((coords),vec2(scale, scale));', ' vec4 dist = vec4(0.0);', ' float inorout = -4.0;', ' dist.x = dot( P, HS0 );', ' dist.y = dot( P, HS1 );', ' dist.z = dot( P, HS2 );', ' dist.w = dot( P, HS3 );', ' dist = smoothstep( -feather, feather, dist );', ' inorout += dot( dist, one );', ' dist.x = dot( P, HS4 );', ' dist.y = HS5.w - abs( P.z );', ' dist = smoothstep( -feather, feather, dist );', ' inorout += dist.x;', ' return clamp( inorout, 0.0, 1.0 );', '}', 'float bdepth(vec2 coords) {', ' // Depth buffer blur', ' float d = 0.0;', ' float kernel[9];', ' vec2 offset[9];', ' vec2 wh = vec2(1.0/textureWidth,1.0/textureHeight) * dbsize;', ' offset[0] = vec2(-wh.x,-wh.y);', ' offset[1] = vec2( 0.0, -wh.y);', ' offset[2] = vec2( wh.x -wh.y);', ' offset[3] = vec2(-wh.x, 0.0);', ' offset[4] = vec2( 0.0, 0.0);', ' offset[5] = vec2( wh.x, 0.0);', ' offset[6] = vec2(-wh.x, wh.y);', ' offset[7] = vec2( 0.0, wh.y);', ' offset[8] = vec2( wh.x, wh.y);', ' kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0;', ' kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0;', ' kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0;', ' for( int i=0; i<9; i++ ) {', ' float tmp = texture2D(tDepth, coords + offset[i]).r;', ' d += tmp * kernel[i];', ' }', ' return d;', '}', 'vec3 color(vec2 coords,float blur) {', ' //processing the sample', ' vec3 col = vec3(0.0);', ' vec2 texel = vec2(1.0/textureWidth,1.0/textureHeight);', ' col.r = texture2D(tColor,coords + vec2(0.0,1.0)*texel*fringe*blur).r;', ' col.g = texture2D(tColor,coords + vec2(-0.866,-0.5)*texel*fringe*blur).g;', ' col.b = texture2D(tColor,coords + vec2(0.866,-0.5)*texel*fringe*blur).b;', ' vec3 lumcoeff = vec3(0.299,0.587,0.114);', ' float lum = dot(col.rgb, lumcoeff);', ' float thresh = max((lum-threshold)*gain, 0.0);', ' return col+mix(vec3(0.0),col,thresh*blur);', '}', 'vec3 debugFocus(vec3 col, float blur, float depth) {', ' float edge = 0.002*depth; //distance based edge smoothing', ' float m = clamp(smoothstep(0.0,edge,blur),0.0,1.0);', ' float e = clamp(smoothstep(1.0-edge,1.0,blur),0.0,1.0);', ' col = mix(col,vec3(1.0,0.5,0.0),(1.0-m)*0.6);', ' col = mix(col,vec3(0.0,0.5,1.0),((1.0-e)-(1.0-m))*0.2);', ' return col;', '}', 'float linearize(float depth) {', ' return -zfar * znear / (depth * (zfar - znear) - zfar);', '}', 'float vignette() {', ' float dist = distance(vUv.xy, vec2(0.5,0.5));', ' dist = smoothstep(vignout+(fstop/vignfade), vignin+(fstop/vignfade), dist);', ' return clamp(dist,0.0,1.0);', '}', 'float gather(float i, float j, int ringsamples, inout vec3 col, float w, float h, float blur) {', ' float rings2 = float(rings);', ' float step = PI*2.0 / float(ringsamples);', ' float pw = cos(j*step)*i;', ' float ph = sin(j*step)*i;', ' float p = 1.0;', ' if (pentagon) {', ' p = penta(vec2(pw,ph));', ' }', ' col += color(vUv.xy + vec2(pw*w,ph*h), blur) * mix(1.0, i/rings2, bias) * p;', ' return 1.0 * mix(1.0, i /rings2, bias) * p;', '}', 'void main() {', ' //scene depth calculation', ' float depth = linearize(texture2D(tDepth,vUv.xy).x);', ' // Blur depth?', ' if ( depthblur ) {', ' depth = linearize(bdepth(vUv.xy));', ' }', ' //focal plane calculation', ' float fDepth = focalDepth;', ' if (shaderFocus) {', ' fDepth = linearize(texture2D(tDepth,focusCoords).x);', ' }', ' // dof blur factor calculation', ' float blur = 0.0;', ' if (manualdof) {', ' float a = depth-fDepth; // Focal plane', ' float b = (a-fdofstart)/fdofdist; // Far DoF', ' float c = (-a-ndofstart)/ndofdist; // Near Dof', ' blur = (a>0.0) ? b : c;', ' } else {', ' float f = focalLength; // focal length in mm', ' float d = fDepth*1000.0; // focal plane in mm', ' float o = depth*1000.0; // depth in mm', ' float a = (o*f)/(o-f);', ' float b = (d*f)/(d-f);', ' float c = (d-f)/(d*fstop*CoC);', ' blur = abs(a-b)*c;', ' }', ' blur = clamp(blur,0.0,1.0);', ' // calculation of pattern for dithering', ' vec2 noise = vec2(rand(vUv.xy), rand( vUv.xy + vec2( 0.4, 0.6 ) ) )*dithering*blur;', ' // getting blur x and y step factor', ' float w = (1.0/textureWidth)*blur*maxblur+noise.x;', ' float h = (1.0/textureHeight)*blur*maxblur+noise.y;', ' // calculation of final color', ' vec3 col = vec3(0.0);', ' if(blur < 0.05) {', ' //some optimization thingy', ' col = texture2D(tColor, vUv.xy).rgb;', ' } else {', ' col = texture2D(tColor, vUv.xy).rgb;', ' float s = 1.0;', ' int ringsamples;', ' for (int i = 1; i <= rings; i++) {', ' /*unboxstart*/', ' ringsamples = i * samples;', ' for (int j = 0 ; j < maxringsamples ; j++) {', ' if (j >= ringsamples) break;', ' s += gather(float(i), float(j), ringsamples, col, w, h, blur);', ' }', ' /*unboxend*/', ' }', ' col /= s; //divide by sample count', ' }', ' if (showFocus) {', ' col = debugFocus(col, blur, depth);', ' }', ' if (vignetting) {', ' col *= vignette();', ' }', ' gl_FragColor.rgb = col;', ' gl_FragColor.a = 1.0;', '} '].join('\n') -}); +var reactReconciler_development = {exports: {}}; /** - * Utility class for sampling weighted random points on the surface of a mesh. + * @license React + * react-reconciler.development.js * - * Building the sampler is a one-time O(n) operation. Once built, any number of - * random samples may be selected in O(logn) time. Memory usage is O(n). + * Copyright (c) Facebook, Inc. and its affiliates. * - * References: - * - http://www.joesfer.com/?p=84 - * - https://stackoverflow.com/a/4322940/1314762 + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -(function () { - var _face = new Triangle(); - - var _color = new Vector3(); - - function MeshSurfaceSampler(mesh) { - var geometry = mesh.geometry; - - if (!geometry.isBufferGeometry || geometry.attributes.position.itemSize !== 3) { - throw new Error('THREE.MeshSurfaceSampler: Requires BufferGeometry triangle mesh.'); - } - - if (geometry.index) { - console.warn('THREE.MeshSurfaceSampler: Converting geometry to non-indexed BufferGeometry.'); - geometry = geometry.toNonIndexed(); - } - - this.geometry = geometry; - this.randomFunction = Math.random; - this.positionAttribute = this.geometry.getAttribute('position'); - this.colorAttribute = this.geometry.getAttribute('color'); - this.weightAttribute = null; - this.distribution = null; - } - - MeshSurfaceSampler.prototype = { - constructor: MeshSurfaceSampler, - setWeightAttribute: function (name) { - this.weightAttribute = name ? this.geometry.getAttribute(name) : null; - return this; - }, - build: function () { - var positionAttribute = this.positionAttribute; - var weightAttribute = this.weightAttribute; - var faceWeights = new Float32Array(positionAttribute.count / 3); // Accumulate weights for each mesh face. - - for (let i = 0; i < positionAttribute.count; i += 3) { - var faceWeight = 1; - - if (weightAttribute) { - faceWeight = weightAttribute.getX(i) + weightAttribute.getX(i + 1) + weightAttribute.getX(i + 2); - } - - _face.a.fromBufferAttribute(positionAttribute, i); - - _face.b.fromBufferAttribute(positionAttribute, i + 1); - - _face.c.fromBufferAttribute(positionAttribute, i + 2); - - faceWeight *= _face.getArea(); - faceWeights[i / 3] = faceWeight; - } // Store cumulative total face weights in an array, where weight index - // corresponds to face index. - - - this.distribution = new Float32Array(positionAttribute.count / 3); - var cumulativeTotal = 0; - - for (let i = 0; i < faceWeights.length; i++) { - cumulativeTotal += faceWeights[i]; - this.distribution[i] = cumulativeTotal; - } - - return this; - }, - setRandomGenerator: function (randomFunction) { - this.randomFunction = randomFunction; - return this; - }, - sample: function (targetPosition, targetNormal, targetColor) { - var cumulativeTotal = this.distribution[this.distribution.length - 1]; - var faceIndex = this.binarySearch(this.randomFunction() * cumulativeTotal); - return this.sampleFace(faceIndex, targetPosition, targetNormal, targetColor); - }, - binarySearch: function (x) { - var dist = this.distribution; - var start = 0; - var end = dist.length - 1; - var index = -1; - - while (start <= end) { - var mid = Math.ceil((start + end) / 2); - - if (mid === 0 || dist[mid - 1] <= x && dist[mid] > x) { - index = mid; - break; - } else if (x < dist[mid]) { - end = mid - 1; - } else { - start = mid + 1; - } - } - - return index; - }, - sampleFace: function (faceIndex, targetPosition, targetNormal, targetColor) { - var u = this.randomFunction(); - var v = this.randomFunction(); - - if (u + v > 1) { - u = 1 - u; - v = 1 - v; - } - - _face.a.fromBufferAttribute(this.positionAttribute, faceIndex * 3); - - _face.b.fromBufferAttribute(this.positionAttribute, faceIndex * 3 + 1); - - _face.c.fromBufferAttribute(this.positionAttribute, faceIndex * 3 + 2); - - targetPosition.set(0, 0, 0).addScaledVector(_face.a, u).addScaledVector(_face.b, v).addScaledVector(_face.c, 1 - (u + v)); - - if (targetNormal !== undefined) { - _face.getNormal(targetNormal); - } - - if (targetColor !== undefined && this.colorAttribute !== undefined) { - _face.a.fromBufferAttribute(this.colorAttribute, faceIndex * 3); - - _face.b.fromBufferAttribute(this.colorAttribute, faceIndex * 3 + 1); - - _face.c.fromBufferAttribute(this.colorAttribute, faceIndex * 3 + 2); - - _color.set(0, 0, 0).addScaledVector(_face.a, u).addScaledVector(_face.b, v).addScaledVector(_face.c, 1 - (u + v)); - - targetColor.r = _color.x; - targetColor.g = _color.y; - targetColor.b = _color.z; - } - - return this; - } - }; - return MeshSurfaceSampler; -})(); - -var a$2 = { - c: null, - // center - u: [new Vector3(), new Vector3(), new Vector3()], - // basis vectors - e: [] // half width - -}; -var b$1 = { - c: null, - // center - u: [new Vector3(), new Vector3(), new Vector3()], - // basis vectors - e: [] // half width - -}; -var R$1 = [[], [], []]; -var AbsR = [[], [], []]; -var t$1 = []; -var xAxis = new Vector3(); -var yAxis = new Vector3(); -var zAxis = new Vector3(); -var v1 = new Vector3(); -var size = new Vector3(); -var closestPoint = new Vector3(); -var rotationMatrix = new Matrix3(); -var aabb$1 = new Box3(); -var matrix = new Matrix4(); -var inverse = new Matrix4(); -var localRay = new Ray(); // OBB - -function OBB(center = new Vector3(), halfSize = new Vector3(), rotation = new Matrix3()) { - this.center = center; - this.halfSize = halfSize; - this.rotation = rotation; -} - -Object.assign(OBB.prototype, { - set: function (center, halfSize, rotation) { - this.center = center; - this.halfSize = halfSize; - this.rotation = rotation; - return this; - }, - copy: function (obb) { - this.center.copy(obb.center); - this.halfSize.copy(obb.halfSize); - this.rotation.copy(obb.rotation); - return this; - }, - clone: function () { - return new this.constructor().copy(this); - }, - getSize: function (result) { - return result.copy(this.halfSize).multiplyScalar(2); - }, - - /** - * Reference: Closest Point on OBB to Point in Real-Time Collision Detection - * by Christer Ericson (chapter 5.1.4) - */ - clampPoint: function (point, result) { - var halfSize = this.halfSize; - v1.subVectors(point, this.center); - this.rotation.extractBasis(xAxis, yAxis, zAxis); // start at the center position of the OBB - - result.copy(this.center); // project the target onto the OBB axes and walk towards that point - - var x = MathUtils.clamp(v1.dot(xAxis), -halfSize.x, halfSize.x); - result.add(xAxis.multiplyScalar(x)); - var y = MathUtils.clamp(v1.dot(yAxis), -halfSize.y, halfSize.y); - result.add(yAxis.multiplyScalar(y)); - var z = MathUtils.clamp(v1.dot(zAxis), -halfSize.z, halfSize.z); - result.add(zAxis.multiplyScalar(z)); - return result; - }, - containsPoint: function (point) { - v1.subVectors(point, this.center); - this.rotation.extractBasis(xAxis, yAxis, zAxis); // project v1 onto each axis and check if these points lie inside the OBB - - return Math.abs(v1.dot(xAxis)) <= this.halfSize.x && Math.abs(v1.dot(yAxis)) <= this.halfSize.y && Math.abs(v1.dot(zAxis)) <= this.halfSize.z; - }, - intersectsBox3: function (box3) { - return this.intersectsOBB(obb$1.fromBox3(box3)); - }, - intersectsSphere: function (sphere) { - // find the point on the OBB closest to the sphere center - this.clampPoint(sphere.center, closestPoint); // if that point is inside the sphere, the OBB and sphere intersect - - return closestPoint.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; - }, - - /** - * Reference: OBB-OBB Intersection in Real-Time Collision Detection - * by Christer Ericson (chapter 4.4.1) - * - */ - intersectsOBB: function (obb, epsilon = Number.EPSILON) { - // prepare data structures (the code uses the same nomenclature like the reference) - a$2.c = this.center; - a$2.e[0] = this.halfSize.x; - a$2.e[1] = this.halfSize.y; - a$2.e[2] = this.halfSize.z; - this.rotation.extractBasis(a$2.u[0], a$2.u[1], a$2.u[2]); - b$1.c = obb.center; - b$1.e[0] = obb.halfSize.x; - b$1.e[1] = obb.halfSize.y; - b$1.e[2] = obb.halfSize.z; - obb.rotation.extractBasis(b$1.u[0], b$1.u[1], b$1.u[2]); // compute rotation matrix expressing b in a's coordinate frame - - for (let i = 0; i < 3; i++) { - for (let j = 0; j < 3; j++) { - R$1[i][j] = a$2.u[i].dot(b$1.u[j]); - } - } // compute translation vector - - - v1.subVectors(b$1.c, a$2.c); // bring translation into a's coordinate frame - - t$1[0] = v1.dot(a$2.u[0]); - t$1[1] = v1.dot(a$2.u[1]); - t$1[2] = v1.dot(a$2.u[2]); // compute common subexpressions. Add in an epsilon term to - // counteract arithmetic errors when two edges are parallel and - // their cross product is (near) null - - for (let i = 0; i < 3; i++) { - for (let j = 0; j < 3; j++) { - AbsR[i][j] = Math.abs(R$1[i][j]) + epsilon; - } - } - - var ra, rb; // test axes L = A0, L = A1, L = A2 - - for (let i = 0; i < 3; i++) { - ra = a$2.e[i]; - rb = b$1.e[0] * AbsR[i][0] + b$1.e[1] * AbsR[i][1] + b$1.e[2] * AbsR[i][2]; - if (Math.abs(t$1[i]) > ra + rb) return false; - } // test axes L = B0, L = B1, L = B2 - - - for (let i = 0; i < 3; i++) { - ra = a$2.e[0] * AbsR[0][i] + a$2.e[1] * AbsR[1][i] + a$2.e[2] * AbsR[2][i]; - rb = b$1.e[i]; - if (Math.abs(t$1[0] * R$1[0][i] + t$1[1] * R$1[1][i] + t$1[2] * R$1[2][i]) > ra + rb) return false; - } // test axis L = A0 x B0 - - - ra = a$2.e[1] * AbsR[2][0] + a$2.e[2] * AbsR[1][0]; - rb = b$1.e[1] * AbsR[0][2] + b$1.e[2] * AbsR[0][1]; - if (Math.abs(t$1[2] * R$1[1][0] - t$1[1] * R$1[2][0]) > ra + rb) return false; // test axis L = A0 x B1 - - ra = a$2.e[1] * AbsR[2][1] + a$2.e[2] * AbsR[1][1]; - rb = b$1.e[0] * AbsR[0][2] + b$1.e[2] * AbsR[0][0]; - if (Math.abs(t$1[2] * R$1[1][1] - t$1[1] * R$1[2][1]) > ra + rb) return false; // test axis L = A0 x B2 - - ra = a$2.e[1] * AbsR[2][2] + a$2.e[2] * AbsR[1][2]; - rb = b$1.e[0] * AbsR[0][1] + b$1.e[1] * AbsR[0][0]; - if (Math.abs(t$1[2] * R$1[1][2] - t$1[1] * R$1[2][2]) > ra + rb) return false; // test axis L = A1 x B0 - - ra = a$2.e[0] * AbsR[2][0] + a$2.e[2] * AbsR[0][0]; - rb = b$1.e[1] * AbsR[1][2] + b$1.e[2] * AbsR[1][1]; - if (Math.abs(t$1[0] * R$1[2][0] - t$1[2] * R$1[0][0]) > ra + rb) return false; // test axis L = A1 x B1 - - ra = a$2.e[0] * AbsR[2][1] + a$2.e[2] * AbsR[0][1]; - rb = b$1.e[0] * AbsR[1][2] + b$1.e[2] * AbsR[1][0]; - if (Math.abs(t$1[0] * R$1[2][1] - t$1[2] * R$1[0][1]) > ra + rb) return false; // test axis L = A1 x B2 - - ra = a$2.e[0] * AbsR[2][2] + a$2.e[2] * AbsR[0][2]; - rb = b$1.e[0] * AbsR[1][1] + b$1.e[1] * AbsR[1][0]; - if (Math.abs(t$1[0] * R$1[2][2] - t$1[2] * R$1[0][2]) > ra + rb) return false; // test axis L = A2 x B0 - - ra = a$2.e[0] * AbsR[1][0] + a$2.e[1] * AbsR[0][0]; - rb = b$1.e[1] * AbsR[2][2] + b$1.e[2] * AbsR[2][1]; - if (Math.abs(t$1[1] * R$1[0][0] - t$1[0] * R$1[1][0]) > ra + rb) return false; // test axis L = A2 x B1 - - ra = a$2.e[0] * AbsR[1][1] + a$2.e[1] * AbsR[0][1]; - rb = b$1.e[0] * AbsR[2][2] + b$1.e[2] * AbsR[2][0]; - if (Math.abs(t$1[1] * R$1[0][1] - t$1[0] * R$1[1][1]) > ra + rb) return false; // test axis L = A2 x B2 - - ra = a$2.e[0] * AbsR[1][2] + a$2.e[1] * AbsR[0][2]; - rb = b$1.e[0] * AbsR[2][1] + b$1.e[1] * AbsR[2][0]; - if (Math.abs(t$1[1] * R$1[0][2] - t$1[0] * R$1[1][2]) > ra + rb) return false; // since no separating axis is found, the OBBs must be intersecting - - return true; - }, - - /** - * Reference: Testing Box Against Plane in Real-Time Collision Detection - * by Christer Ericson (chapter 5.2.3) - */ - intersectsPlane: function (plane) { - this.rotation.extractBasis(xAxis, yAxis, zAxis); // compute the projection interval radius of this OBB onto L(t) = this->center + t * p.normal; - - const r = this.halfSize.x * Math.abs(plane.normal.dot(xAxis)) + this.halfSize.y * Math.abs(plane.normal.dot(yAxis)) + this.halfSize.z * Math.abs(plane.normal.dot(zAxis)); // compute distance of the OBB's center from the plane - - const d = plane.normal.dot(this.center) - plane.constant; // Intersection occurs when distance d falls within [-r,+r] interval - - return Math.abs(d) <= r; - }, - - /** - * Performs a ray/OBB intersection test and stores the intersection point - * to the given 3D vector. If no intersection is detected, *null* is returned. - */ - intersectRay: function (ray, result) { - // the idea is to perform the intersection test in the local space - // of the OBB. - this.getSize(size); - aabb$1.setFromCenterAndSize(v1.set(0, 0, 0), size); // create a 4x4 transformation matrix - - matrix4FromRotationMatrix(matrix, this.rotation); - matrix.setPosition(this.center); // transform ray to the local space of the OBB - - inverse.copy(matrix).invert(); - localRay.copy(ray).applyMatrix4(inverse); // perform ray <-> AABB intersection test - - if (localRay.intersectBox(aabb$1, result)) { - // transform the intersection point back to world space - return result.applyMatrix4(matrix); - } else { - return null; - } - }, - - /** - * Performs a ray/OBB intersection test. Returns either true or false if - * there is a intersection or not. - */ - intersectsRay: function (ray) { - return this.intersectRay(ray, v1) !== null; - }, - fromBox3: function (box3) { - box3.getCenter(this.center); - box3.getSize(this.halfSize).multiplyScalar(0.5); - this.rotation.identity(); - return this; - }, - equals: function (obb) { - return obb.center.equals(this.center) && obb.halfSize.equals(this.halfSize) && obb.rotation.equals(this.rotation); - }, - applyMatrix4: function (matrix) { - var e = matrix.elements; - var sx = v1.set(e[0], e[1], e[2]).length(); - var sy = v1.set(e[4], e[5], e[6]).length(); - var sz = v1.set(e[8], e[9], e[10]).length(); - var det = matrix.determinant(); - if (det < 0) sx = -sx; - rotationMatrix.setFromMatrix4(matrix); - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; - rotationMatrix.elements[0] *= invSX; - rotationMatrix.elements[1] *= invSX; - rotationMatrix.elements[2] *= invSX; - rotationMatrix.elements[3] *= invSY; - rotationMatrix.elements[4] *= invSY; - rotationMatrix.elements[5] *= invSY; - rotationMatrix.elements[6] *= invSZ; - rotationMatrix.elements[7] *= invSZ; - rotationMatrix.elements[8] *= invSZ; - this.rotation.multiply(rotationMatrix); - this.halfSize.x *= sx; - this.halfSize.y *= sy; - this.halfSize.z *= sz; - v1.setFromMatrixPosition(matrix); - this.center.add(v1); - return this; - } -}); - -function matrix4FromRotationMatrix(matrix4, matrix3) { - var e = matrix4.elements; - var me = matrix3.elements; - e[0] = me[0]; - e[1] = me[1]; - e[2] = me[2]; - e[3] = 0; - e[4] = me[3]; - e[5] = me[4]; - e[6] = me[5]; - e[7] = 0; - e[8] = me[6]; - e[9] = me[7]; - e[10] = me[8]; - e[11] = 0; - e[12] = 0; - e[13] = 0; - e[14] = 0; - e[15] = 1; -} - -var obb$1 = new OBB(); - -var Capsule = function () { - var _v1 = new Vector3(); - - var _v2 = new Vector3(); - - var _v3 = new Vector3(); - - var EPS = 1e-10; +var hasRequiredReactReconciler_development; - function Capsule(start, end, radius) { - this.start = start == undefined ? new Vector3(0, 0, 0) : start; - this.end = end == undefined ? new Vector3(0, 1, 0) : end; - this.radius = radius == undefined ? 1 : radius; - } +function requireReactReconciler_development () { + if (hasRequiredReactReconciler_development) return reactReconciler_development.exports; + hasRequiredReactReconciler_development = 1; - Object.assign(Capsule.prototype, { - clone: function () { - return new Capsule(this.start.clone(), this.end.clone(), this.radius); - }, - set: function (start, end, radius) { - this.start.copy(start); - this.end.copy(end); - this.radius = radius; - }, - copy: function (capsule) { - this.start.copy(capsule.start); - this.end.copy(capsule.end); - this.radius = capsule.radius; - }, - getCenter: function (target) { - return target.copy(this.end).add(this.start).multiplyScalar(0.5); - }, - translate: function (v) { - this.start.add(v); - this.end.add(v); - }, - checkAABBAxis: function (p1x, p1y, p2x, p2y, minx, maxx, miny, maxy, radius) { - return (minx - p1x < radius || minx - p2x < radius) && (p1x - maxx < radius || p2x - maxx < radius) && (miny - p1y < radius || miny - p2y < radius) && (p1y - maxy < radius || p2y - maxy < radius); - }, - intersectsBox: function (box) { - return this.checkAABBAxis(this.start.x, this.start.y, this.end.x, this.end.y, box.min.x, box.max.x, box.min.y, box.max.y, this.radius) && this.checkAABBAxis(this.start.x, this.start.z, this.end.x, this.end.z, box.min.x, box.max.x, box.min.z, box.max.z, this.radius) && this.checkAABBAxis(this.start.y, this.start.z, this.end.y, this.end.z, box.min.y, box.max.y, box.min.z, box.max.z, this.radius); - }, - lineLineMinimumPoints: function (line1, line2) { - var r = _v1.copy(line1.end).sub(line1.start); + if (process.env.NODE_ENV !== "production") { + reactReconciler_development.exports = function $$$reconciler($$$hostConfig) { + var exports = {}; - var s = _v2.copy(line2.end).sub(line2.start); + var React = React__default; + var Scheduler = scheduler$1.exports; - var w = _v3.copy(line2.start).sub(line1.start); + var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - var a = r.dot(s), - b = r.dot(r), - c = s.dot(s), - d = s.dot(w), - e = r.dot(w); - var t1, - t2, - divisor = b * c - a * a; + var suppressWarning = false; + function setSuppressWarning(newSuppressWarning) { + { + suppressWarning = newSuppressWarning; + } + } // In DEV, calls to console.warn and console.error get replaced + // by calls to these methods by a Babel plugin. + // + // In PROD (or in packages without access to React internals), + // they are left as they are instead. - if (Math.abs(divisor) < EPS) { - var d1 = -d / c; - var d2 = (a - d) / c; + function warn(format) { + { + if (!suppressWarning) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } - if (Math.abs(d1 - 0.5) < Math.abs(d2 - 0.5)) { - t1 = 0; - t2 = d1; - } else { - t1 = 1; - t2 = d2; - } - } else { - t1 = (d * a + e * c) / divisor; - t2 = (t1 * a - d) / c; - } + printWarning('warn', format, args); + } + } + } + function error(format) { + { + if (!suppressWarning) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } - t2 = Math.max(0, Math.min(1, t2)); - t1 = Math.max(0, Math.min(1, t1)); - var point1 = r.multiplyScalar(t1).add(line1.start); - var point2 = s.multiplyScalar(t2).add(line2.start); - return [point1, point2]; - } - }); - return Capsule; -}(); + printWarning('error', format, args); + } + } + } -(function () { - var _v1 = new Vector3(); + function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); - var _v2 = new Vector3(); + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion - var _plane = new Plane(); - var _line1 = new Line3(); + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix - var _line2 = new Line3(); + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging - var _sphere = new Sphere(); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } - var _capsule = new Capsule(); + var assign = Object.assign; - function Octree(box) { - this.triangles = []; - this.box = box; - this.subTrees = []; - } + /** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + * + * Note that this module is currently shared and assumed to be stateless. + * If this becomes an actual Map, that will break. + */ + function get(key) { + return key._reactInternals; + } + function set(key, value) { + key._reactInternals = value; + } - Object.assign(Octree.prototype, { - addTriangle: function (triangle) { - if (!this.bounds) this.bounds = new Box3(); - this.bounds.min.x = Math.min(this.bounds.min.x, triangle.a.x, triangle.b.x, triangle.c.x); - this.bounds.min.y = Math.min(this.bounds.min.y, triangle.a.y, triangle.b.y, triangle.c.y); - this.bounds.min.z = Math.min(this.bounds.min.z, triangle.a.z, triangle.b.z, triangle.c.z); - this.bounds.max.x = Math.max(this.bounds.max.x, triangle.a.x, triangle.b.x, triangle.c.x); - this.bounds.max.y = Math.max(this.bounds.max.y, triangle.a.y, triangle.b.y, triangle.c.y); - this.bounds.max.z = Math.max(this.bounds.max.z, triangle.a.z, triangle.b.z, triangle.c.z); - this.triangles.push(triangle); - return this; - }, - calcBox: function () { - this.box = this.bounds.clone(); // offset small ammount to account for regular grid + // ----------------------------------------------------------------------------- + var enablePersistentOffscreenHostContainer = false; // ----------------------------------------------------------------------------- + // the react-reconciler package. - this.box.min.x -= 0.01; - this.box.min.y -= 0.01; - this.box.min.z -= 0.01; - return this; - }, - split: function (level) { - if (!this.box) return; - - var subTrees = [], - halfsize = _v2.copy(this.box.max).sub(this.box.min).multiplyScalar(0.5), - box, - v, - triangle; - - for (let x = 0; x < 2; x++) { - for (let y = 0; y < 2; y++) { - for (let z = 0; z < 2; z++) { - box = new Box3(); - v = _v1.set(x, y, z); - box.min.copy(this.box.min).add(v.multiply(halfsize)); - box.max.copy(box.min).add(halfsize); - subTrees.push(new Octree(box)); - } - } - } + var enableNewReconciler = false; // Support legacy Primer support on internal FB www - while (triangle = this.triangles.pop()) { - for (let i = 0; i < subTrees.length; i++) { - if (subTrees[i].box.intersectsTriangle(triangle)) { - subTrees[i].triangles.push(triangle); - } - } - } + var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics. - for (let i = 0; i < subTrees.length; i++) { - var len = subTrees[i].triangles.length; + var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber - if (len > 8 && level < 16) { - subTrees[i].split(level + 1); - } + var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz + var warnAboutStringRefs = false; // ----------------------------------------------------------------------------- + // Debugging and DevTools + // ----------------------------------------------------------------------------- + // Adds user timing marks for e.g. state updates, suspense, and work loop stuff, + // for an experimental timeline tool. - if (len != 0) { - this.subTrees.push(subTrees[i]); - } - } + var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState - return this; - }, - build: function () { - this.calcBox(); - this.split(0); - return this; - }, - getRayTriangles: function (ray, triangles) { - for (let i = 0; i < this.subTrees.length; i++) { - var subTree = this.subTrees[i]; - if (!ray.intersectsBox(subTree.box)) continue; - - if (subTree.triangles.length > 0) { - for (let j = 0; j < subTree.triangles.length; j++) { - if (triangles.indexOf(subTree.triangles[j]) === -1) triangles.push(subTree.triangles[j]); - } - } else { - subTree.getRayTriangles(ray, triangles); - } - } + var enableProfilerTimer = true; // Record durations for commit and passive effects phases. - return triangles; - }, - triangleCapsuleIntersect: function (capsule, triangle) { - var point1, point2, line1, line2; - triangle.getPlane(_plane); - var d1 = _plane.distanceToPoint(capsule.start) - capsule.radius; - var d2 = _plane.distanceToPoint(capsule.end) - capsule.radius; + var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update". - if (d1 > 0 && d2 > 0 || d1 < -capsule.radius && d2 < -capsule.radius) { - return false; - } + var FunctionComponent = 0; + var ClassComponent = 1; + var IndeterminateComponent = 2; // Before we know whether it is function or class - var delta = Math.abs(d1 / (Math.abs(d1) + Math.abs(d2))); + var HostRoot = 3; // Root of a host tree. Could be nested inside another node. - var intersectPoint = _v1.copy(capsule.start).lerp(capsule.end, delta); + var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. - if (triangle.containsPoint(intersectPoint)) { - return { - normal: _plane.normal.clone(), - point: intersectPoint.clone(), - depth: Math.abs(Math.min(d1, d2)) - }; - } + var HostComponent = 5; + var HostText = 6; + var Fragment = 7; + var Mode = 8; + var ContextConsumer = 9; + var ContextProvider = 10; + var ForwardRef = 11; + var Profiler = 12; + var SuspenseComponent = 13; + var MemoComponent = 14; + var SimpleMemoComponent = 15; + var LazyComponent = 16; + var IncompleteClassComponent = 17; + var DehydratedFragment = 18; + var SuspenseListComponent = 19; + var ScopeComponent = 21; + var OffscreenComponent = 22; + var LegacyHiddenComponent = 23; + var CacheComponent = 24; + var TracingMarkerComponent = 25; - var r2 = capsule.radius * capsule.radius; - line1 = _line1.set(capsule.start, capsule.end); - var lines = [[triangle.a, triangle.b], [triangle.b, triangle.c], [triangle.c, triangle.a]]; + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. + var REACT_ELEMENT_TYPE = Symbol.for('react.element'); + var REACT_PORTAL_TYPE = Symbol.for('react.portal'); + var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); + var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); + var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); + var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); + var REACT_CONTEXT_TYPE = Symbol.for('react.context'); + var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); + var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); + var REACT_MEMO_TYPE = Symbol.for('react.memo'); + var REACT_LAZY_TYPE = Symbol.for('react.lazy'); + var REACT_SCOPE_TYPE = Symbol.for('react.scope'); + var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); + var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); + var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); + var REACT_CACHE_TYPE = Symbol.for('react.cache'); + var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker'); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } - for (let i = 0; i < lines.length; i++) { - line2 = _line2.set(lines[i][0], lines[i][1]); - [point1, point2] = capsule.lineLineMinimumPoints(line1, line2); + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (point1.distanceToSquared(point2) < r2) { - return { - normal: point1.clone().sub(point2).normalize(), - point: point2.clone(), - depth: capsule.radius - point1.distanceTo(point2) - }; - } - } + if (typeof maybeIterator === 'function') { + return maybeIterator; + } - return false; - }, - triangleSphereIntersect: function (sphere, triangle) { - triangle.getPlane(_plane); - if (!sphere.intersectsPlane(_plane)) return false; - var depth = Math.abs(_plane.distanceToSphere(sphere)); - var r2 = sphere.radius * sphere.radius - depth * depth; + return null; + } - var plainPoint = _plane.projectPoint(sphere.center, _v1); + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; - if (triangle.containsPoint(sphere.center)) { - return { - normal: _plane.normal.clone(), - point: plainPoint.clone(), - depth: Math.abs(_plane.distanceToSphere(sphere)) - }; - } + if (displayName) { + return displayName; + } - var lines = [[triangle.a, triangle.b], [triangle.b, triangle.c], [triangle.c, triangle.a]]; + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; + } // Keep in sync with react-reconciler/getComponentNameFromFiber - for (let i = 0; i < lines.length; i++) { - _line1.set(lines[i][0], lines[i][1]); - _line1.closestPointToPoint(plainPoint, true, _v2); + function getContextName(type) { + return type.displayName || 'Context'; + } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. - var d = _v2.distanceToSquared(sphere.center); - if (d < r2) { - return { - normal: sphere.center.clone().sub(_v2).normalize(), - point: _v2.clone(), - depth: sphere.radius - Math.sqrt(d) - }; - } - } + function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } - return false; - }, - getSphereTriangles: function (sphere, triangles) { - for (let i = 0; i < this.subTrees.length; i++) { - var subTree = this.subTrees[i]; - if (!sphere.intersectsBox(subTree.box)) continue; - - if (subTree.triangles.length > 0) { - for (let j = 0; j < subTree.triangles.length; j++) { - if (triangles.indexOf(subTree.triangles[j]) === -1) triangles.push(subTree.triangles[j]); - } - } else { - subTree.getSphereTriangles(sphere, triangles); - } - } - }, - getCapsuleTriangles: function (capsule, triangles) { - for (let i = 0; i < this.subTrees.length; i++) { - var subTree = this.subTrees[i]; - if (!capsule.intersectsBox(subTree.box)) continue; - - if (subTree.triangles.length > 0) { - for (let j = 0; j < subTree.triangles.length; j++) { - if (triangles.indexOf(subTree.triangles[j]) === -1) triangles.push(subTree.triangles[j]); - } - } else { - subTree.getCapsuleTriangles(capsule, triangles); - } - } - }, + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } - sphereIntersect(sphere) { - _sphere.copy(sphere); + if (typeof type === 'function') { + return type.displayName || type.name || null; + } - var triangles = [], - result, - hit = false; - this.getSphereTriangles(sphere, triangles); + if (typeof type === 'string') { + return type; + } - for (let i = 0; i < triangles.length; i++) { - if (result = this.triangleSphereIntersect(_sphere, triangles[i])) { - hit = true; + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; - _sphere.center.add(result.normal.multiplyScalar(result.depth)); - } - } + case REACT_PORTAL_TYPE: + return 'Portal'; - if (hit) { - var collisionVector = _sphere.center.clone().sub(sphere.center); + case REACT_PROFILER_TYPE: + return 'Profiler'; - var depth = collisionVector.length(); - return { - normal: collisionVector.normalize(), - depth: depth - }; - } + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; - return false; - }, + case REACT_SUSPENSE_TYPE: + return 'Suspense'; - capsuleIntersect: function (capsule) { - _capsule.copy(capsule); + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; - var triangles = [], - result, - hit = false; - this.getCapsuleTriangles(_capsule, triangles); + } - for (let i = 0; i < triangles.length; i++) { - if (result = this.triangleCapsuleIntersect(_capsule, triangles[i])) { - hit = true; + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; - _capsule.translate(result.normal.multiplyScalar(result.depth)); - } - } + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; - if (hit) { - var collisionVector = _capsule.getCenter(new Vector3()).sub(capsule.getCenter(_v1)); + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); - var depth = collisionVector.length(); - return { - normal: collisionVector.normalize(), - depth: depth - }; - } + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; - return false; - }, - rayIntersect: function (ray) { - if (ray.direction.length() === 0) return; - var triangles = [], - triangle, - position, - distance = 1e100, - result; - this.getRayTriangles(ray, triangles); - - for (let i = 0; i < triangles.length; i++) { - result = ray.intersectTriangle(triangles[i].a, triangles[i].b, triangles[i].c, true, _v1); - - if (result) { - var newdistance = result.sub(ray.origin).length(); - - if (distance > newdistance) { - position = result.clone().add(ray.origin); - distance = newdistance; - triangle = triangles[i]; - } - } - } + if (outerName !== null) { + return outerName; + } - return distance < 1e100 ? { - distance: distance, - triangle: triangle, - position: position - } : false; - }, - fromGraphNode: function (group) { - group.traverse(obj => { - if (obj.type === 'Mesh') { - obj.updateMatrix(); - obj.updateWorldMatrix(); - var geometry, - isTemp = false; - - if (obj.geometry.index) { - isTemp = true; - geometry = obj.geometry.clone().toNonIndexed(); - } else { - geometry = obj.geometry; - } + return getComponentNameFromType(type.type) || 'Memo'; - var positions = geometry.attributes.position.array; - var transform = obj.matrixWorld; - - for (let i = 0; i < positions.length; i += 9) { - var v1 = new Vector3(positions[i], positions[i + 1], positions[i + 2]); - var v2 = new Vector3(positions[i + 3], positions[i + 4], positions[i + 5]); - var v3 = new Vector3(positions[i + 6], positions[i + 7], positions[i + 8]); - v1.applyMatrix4(transform); - v2.applyMatrix4(transform); - v3.applyMatrix4(transform); - this.addTriangle(new Triangle(v1, v2, v3)); - } + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; - if (isTemp) { - geometry.dispose(); - } - } - }); - this.build(); - return this; - } - }); - return Octree; -})(); + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } -var Lut = function (colormap, numberofcolors) { - this.lut = []; - this.setColorMap(colormap, numberofcolors); - return this; -}; + // eslint-disable-next-line no-fallthrough + } + } -Lut.prototype = { - constructor: Lut, - lut: [], - map: [], - n: 256, - minV: 0, - maxV: 1, - set: function (value) { - if (value instanceof Lut) { - this.copy(value); - } + return null; + } - return this; - }, - setMin: function (min) { - this.minV = min; - return this; - }, - setMax: function (max) { - this.maxV = max; - return this; - }, - setColorMap: function (colormap, numberofcolors) { - this.map = ColorMapKeywords[colormap] || ColorMapKeywords.rainbow; - this.n = numberofcolors || 32; - var step = 1.0 / this.n; - this.lut.length = 0; - - for (let i = 0; i <= 1; i += step) { - for (let j = 0; j < this.map.length - 1; j++) { - if (i >= this.map[j][0] && i < this.map[j + 1][0]) { - var min = this.map[j][0]; - var max = this.map[j + 1][0]; - var minColor = new Color(this.map[j][1]); - var maxColor = new Color(this.map[j + 1][1]); - var color = minColor.lerp(maxColor, (i - min) / (max - min)); - this.lut.push(color); - } - } - } + function getWrappedName$1(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ''; + return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); + } // Keep in sync with shared/getComponentNameFromType - return this; - }, - copy: function (lut) { - this.lut = lut.lut; - this.map = lut.map; - this.n = lut.n; - this.minV = lut.minV; - this.maxV = lut.maxV; - return this; - }, - getColor: function (alpha) { - if (alpha <= this.minV) { - alpha = this.minV; - } else if (alpha >= this.maxV) { - alpha = this.maxV; - } - alpha = (alpha - this.minV) / (this.maxV - this.minV); - var colorPosition = Math.round(alpha * this.n); - colorPosition == this.n ? colorPosition -= 1 : colorPosition; - return this.lut[colorPosition]; - }, - addColorMap: function (colormapName, arrayOfColors) { - ColorMapKeywords[colormapName] = arrayOfColors; - }, - createCanvas: function () { - var canvas = document.createElement('canvas'); - canvas.width = 1; - canvas.height = this.n; - this.updateCanvas(canvas); - return canvas; - }, - updateCanvas: function (canvas) { - var ctx = canvas.getContext('2d', { - alpha: false - }); - var imageData = ctx.getImageData(0, 0, 1, this.n); - var data = imageData.data; - var k = 0; - var step = 1.0 / this.n; - - for (let i = 1; i >= 0; i -= step) { - for (let j = this.map.length - 1; j >= 0; j--) { - if (i < this.map[j][0] && i >= this.map[j - 1][0]) { - var min = this.map[j - 1][0]; - var max = this.map[j][0]; - var minColor = new Color(this.map[j - 1][1]); - var maxColor = new Color(this.map[j][1]); - var color = minColor.lerp(maxColor, (i - min) / (max - min)); - data[k * 4] = Math.round(color.r * 255); - data[k * 4 + 1] = Math.round(color.g * 255); - data[k * 4 + 2] = Math.round(color.b * 255); - data[k * 4 + 3] = 255; - k += 1; - } - } - } + function getContextName$1(type) { + return type.displayName || 'Context'; + } - ctx.putImageData(imageData, 0, 0); - return canvas; - } -}; -var ColorMapKeywords = { - rainbow: [[0.0, 0x0000ff], [0.2, 0x00ffff], [0.5, 0x00ff00], [0.8, 0xffff00], [1.0, 0xff0000]], - cooltowarm: [[0.0, 0x3c4ec2], [0.2, 0x9bbcff], [0.5, 0xdcdcdc], [0.8, 0xf6a385], [1.0, 0xb40426]], - blackbody: [[0.0, 0x000000], [0.2, 0x780000], [0.5, 0xe63200], [0.8, 0xffff00], [1.0, 0xffffff]], - grayscale: [[0.0, 0x000000], [0.2, 0x404040], [0.5, 0x7f7f80], [0.8, 0xbfbfbf], [1.0, 0xffffff]] -}; + function getComponentNameFromFiber(fiber) { + var tag = fiber.tag, + type = fiber.type; -let STATE; + switch (tag) { + case CacheComponent: + return 'Cache'; -(function (STATE) { - STATE[STATE["NONE"] = -1] = "NONE"; - STATE[STATE["ROTATE"] = 0] = "ROTATE"; - STATE[STATE["DOLLY"] = 1] = "DOLLY"; - STATE[STATE["PAN"] = 2] = "PAN"; - STATE[STATE["TOUCH_ROTATE"] = 3] = "TOUCH_ROTATE"; - STATE[STATE["TOUCH_PAN"] = 4] = "TOUCH_PAN"; - STATE[STATE["TOUCH_DOLLY_PAN"] = 5] = "TOUCH_DOLLY_PAN"; - STATE[STATE["TOUCH_DOLLY_ROTATE"] = 6] = "TOUCH_DOLLY_ROTATE"; -})(STATE || (STATE = {})); + case ContextConsumer: + var context = type; + return getContextName$1(context) + '.Consumer'; -new Vector3(); + case ContextProvider: + var provider = type; + return getContextName$1(provider._context) + '.Provider'; -// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). -// -// Orbit - left mouse / touch: one-finger move -// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish -// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move - -const moduloWrapAround = (offset, capacity) => (offset % capacity + capacity) % capacity; - -class OrbitControls$1 extends EventDispatcher { - // Set to false to disable this control - // "target" sets the location of focus, where the object orbits around - // How far you can dolly in and out ( PerspectiveCamera only ) - // How far you can zoom in and out ( OrthographicCamera only ) - // How far you can orbit vertically, upper and lower limits. - // Range is 0 to Math.PI radians. - // radians - // radians - // How far you can orbit horizontally, upper and lower limits. - // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) - // radians - // radians - // Set to true to enable damping (inertia) - // If damping is enabled, you must call controls.update() in your animation loop - // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. - // Set to false to disable zooming - // Set to false to disable rotating - // Set to false to disable panning - // if false, pan orthogonal to world-space direction camera.up - // pixels moved per arrow key push - // Set to true to automatically rotate around the target - // If auto-rotate is enabled, you must call controls.update() in your animation loop - // 30 seconds per orbit when fps is 60 - // true if you want to reverse the orbit to mouse drag from left to right = orbits left - // The four arrow keys - // Mouse buttons - // Touch fingers - // the target DOM element for key events - constructor(object, domElement) { - super(); + case DehydratedFragment: + return 'DehydratedFragment'; - _defineProperty$1(this, "object", void 0); + case ForwardRef: + return getWrappedName$1(type, type.render, 'ForwardRef'); - _defineProperty$1(this, "domElement", void 0); + case Fragment: + return 'Fragment'; - _defineProperty$1(this, "enabled", true); + case HostComponent: + // Host component type is the display name (e.g. "div", "View") + return type; - _defineProperty$1(this, "target", new Vector3()); + case HostPortal: + return 'Portal'; - _defineProperty$1(this, "minDistance", 0); + case HostRoot: + return 'Root'; - _defineProperty$1(this, "maxDistance", Infinity); + case HostText: + return 'Text'; - _defineProperty$1(this, "minZoom", 0); + case LazyComponent: + // Name comes from the type in this case; we don't have a tag. + return getComponentNameFromType(type); - _defineProperty$1(this, "maxZoom", Infinity); + case Mode: + if (type === REACT_STRICT_MODE_TYPE) { + // Don't be less specific than shared/getComponentNameFromType + return 'StrictMode'; + } - _defineProperty$1(this, "minPolarAngle", 0); + return 'Mode'; - _defineProperty$1(this, "maxPolarAngle", Math.PI); + case OffscreenComponent: + return 'Offscreen'; - _defineProperty$1(this, "minAzimuthAngle", -Infinity); + case Profiler: + return 'Profiler'; - _defineProperty$1(this, "maxAzimuthAngle", Infinity); + case ScopeComponent: + return 'Scope'; - _defineProperty$1(this, "enableDamping", false); + case SuspenseComponent: + return 'Suspense'; - _defineProperty$1(this, "dampingFactor", 0.05); + case SuspenseListComponent: + return 'SuspenseList'; - _defineProperty$1(this, "enableZoom", true); + case TracingMarkerComponent: + return 'TracingMarker'; + // The display name for this tags come from the user-provided type: - _defineProperty$1(this, "zoomSpeed", 1.0); + case ClassComponent: + case FunctionComponent: + case IncompleteClassComponent: + case IndeterminateComponent: + case MemoComponent: + case SimpleMemoComponent: + if (typeof type === 'function') { + return type.displayName || type.name || null; + } - _defineProperty$1(this, "enableRotate", true); + if (typeof type === 'string') { + return type; + } - _defineProperty$1(this, "rotateSpeed", 1.0); + break; - _defineProperty$1(this, "enablePan", true); + } - _defineProperty$1(this, "panSpeed", 1.0); + return null; + } - _defineProperty$1(this, "screenSpacePanning", true); + // Don't change these two values. They're used by React Dev Tools. + var NoFlags = + /* */ + 0; + var PerformedWork = + /* */ + 1; // You can change the rest (and add more). - _defineProperty$1(this, "keyPanSpeed", 7.0); + var Placement = + /* */ + 2; + var Update = + /* */ + 4; + var PlacementAndUpdate = + /* */ + Placement | Update; + var ChildDeletion = + /* */ + 16; + var ContentReset = + /* */ + 32; + var Callback = + /* */ + 64; + var DidCapture = + /* */ + 128; + var ForceClientRender = + /* */ + 256; + var Ref = + /* */ + 512; + var Snapshot = + /* */ + 1024; + var Passive = + /* */ + 2048; + var Hydrating = + /* */ + 4096; + var HydratingAndUpdate = + /* */ + Hydrating | Update; + var Visibility = + /* */ + 8192; + var StoreConsistency = + /* */ + 16384; + var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit) - _defineProperty$1(this, "autoRotate", false); + var HostEffectMask = + /* */ + 32767; // These are not really side effects, but we still reuse this field. - _defineProperty$1(this, "autoRotateSpeed", 2.0); + var Incomplete = + /* */ + 32768; + var ShouldCapture = + /* */ + 65536; + var ForceUpdateForLegacySuspense = + /* */ + 131072; + var Forked = + /* */ + 1048576; // Static tags describe aspects of a fiber that are not specific to a render, + // e.g. a fiber uses a passive effect (even if there are no updates on this particular render). + // This enables us to defer more work in the unmount case, + // since we can defer traversing the tree during layout to look for Passive effects, + // and instead rely on the static flag as a signal that there may be cleanup work. - _defineProperty$1(this, "reverseOrbit", false); + var RefStatic = + /* */ + 2097152; + var LayoutStatic = + /* */ + 4194304; + var PassiveStatic = + /* */ + 8388608; // These flags allow us to traverse to fibers that have effects on mount + // without traversing the entire tree after every commit for + // double invoking - _defineProperty$1(this, "keys", { - LEFT: 'ArrowLeft', - UP: 'ArrowUp', - RIGHT: 'ArrowRight', - BOTTOM: 'ArrowDown' - }); + var MountLayoutDev = + /* */ + 16777216; + var MountPassiveDev = + /* */ + 33554432; // Groups of flags that are used in the commit phase to skip over trees that + // don't contain effects, by checking subtreeFlags. - _defineProperty$1(this, "mouseButtons", { - LEFT: MOUSE.ROTATE, - MIDDLE: MOUSE.DOLLY, - RIGHT: MOUSE.PAN - }); + var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility + // flag logic (see #20043) + Update | Snapshot | ( 0); + var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; + var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask - _defineProperty$1(this, "touches", { - ONE: TOUCH.ROTATE, - TWO: TOUCH.DOLLY_PAN - }); + var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones. + // This allows certain concepts to persist without recalculating them, + // e.g. whether a subtree contains passive effects or portals. - _defineProperty$1(this, "target0", void 0); + var StaticMask = LayoutStatic | PassiveStatic | RefStatic; - _defineProperty$1(this, "position0", void 0); + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + function getNearestMountedFiber(fiber) { + var node = fiber; + var nearestMounted = fiber; - _defineProperty$1(this, "zoom0", void 0); + if (!fiber.alternate) { + // If there is no alternate, this might be a new tree that isn't inserted + // yet. If it is, then it will have a pending insertion effect on it. + var nextNode = node; - _defineProperty$1(this, "_domElementKeyEvents", null); + do { + node = nextNode; - _defineProperty$1(this, "getPolarAngle", void 0); + if ((node.flags & (Placement | Hydrating)) !== NoFlags) { + // This is an insertion or in-progress hydration. The nearest possible + // mounted fiber is the parent but we need to continue to figure out + // if that one is still mounted. + nearestMounted = node.return; + } - _defineProperty$1(this, "getAzimuthalAngle", void 0); + nextNode = node.return; + } while (nextNode); + } else { + while (node.return) { + node = node.return; + } + } - _defineProperty$1(this, "setPolarAngle", void 0); + if (node.tag === HostRoot) { + // TODO: Check if this was a nested HostRoot when used with + // renderContainerIntoSubtree. + return nearestMounted; + } // If we didn't hit the root, that means that we're in an disconnected tree + // that has been unmounted. - _defineProperty$1(this, "setAzimuthalAngle", void 0); - _defineProperty$1(this, "getDistance", void 0); + return null; + } + function isFiberMounted(fiber) { + return getNearestMountedFiber(fiber) === fiber; + } + function isMounted(component) { + { + var owner = ReactCurrentOwner.current; - _defineProperty$1(this, "listenToKeyEvents", void 0); + if (owner !== null && owner.tag === ClassComponent) { + var ownerFiber = owner; + var instance = ownerFiber.stateNode; - _defineProperty$1(this, "saveState", void 0); + if (!instance._warnedAboutRefsInRender) { + error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component'); + } - _defineProperty$1(this, "reset", void 0); + instance._warnedAboutRefsInRender = true; + } + } - _defineProperty$1(this, "update", void 0); + var fiber = get(component); - _defineProperty$1(this, "connect", void 0); + if (!fiber) { + return false; + } - _defineProperty$1(this, "dispose", void 0); + return getNearestMountedFiber(fiber) === fiber; + } - this.object = object; - this.domElement = domElement; // for reset + function assertIsMounted(fiber) { + if (getNearestMountedFiber(fiber) !== fiber) { + throw new Error('Unable to find node on an unmounted component.'); + } + } - this.target0 = this.target.clone(); - this.position0 = this.object.position.clone(); - this.zoom0 = this.object instanceof PerspectiveCamera ? this.object.zoom : 1; // - // public methods - // + function findCurrentFiberUsingSlowPath(fiber) { + var alternate = fiber.alternate; - this.getPolarAngle = () => spherical.phi; + if (!alternate) { + // If there is no alternate, then we only need to check if it is mounted. + var nearestMounted = getNearestMountedFiber(fiber); - this.getAzimuthalAngle = () => spherical.theta; + if (nearestMounted === null) { + throw new Error('Unable to find node on an unmounted component.'); + } - this.setPolarAngle = value => { - // use modulo wrapping to safeguard value - let phi = moduloWrapAround(value, 2 * Math.PI); - let currentPhi = spherical.phi; // convert to the equivalent shortest angle + if (nearestMounted !== fiber) { + return null; + } - if (currentPhi < 0) currentPhi += 2 * Math.PI; - if (phi < 0) phi += 2 * Math.PI; - let phiDist = Math.abs(phi - currentPhi); + return fiber; + } // If we have two possible branches, we'll walk backwards up to the root + // to see what path the root points to. On the way we may hit one of the + // special cases and we'll deal with them. - if (2 * Math.PI - phiDist < phiDist) { - if (phi < currentPhi) { - phi += 2 * Math.PI; - } else { - currentPhi += 2 * Math.PI; - } - } - sphericalDelta.phi = phi - currentPhi; - scope.update(); - }; + var a = fiber; + var b = alternate; - this.setAzimuthalAngle = value => { - // use modulo wrapping to safeguard value - let theta = moduloWrapAround(value, 2 * Math.PI); - let currentTheta = spherical.theta; // convert to the equivalent shortest angle + while (true) { + var parentA = a.return; - if (currentTheta < 0) currentTheta += 2 * Math.PI; - if (theta < 0) theta += 2 * Math.PI; - let thetaDist = Math.abs(theta - currentTheta); + if (parentA === null) { + // We're at the root. + break; + } - if (2 * Math.PI - thetaDist < thetaDist) { - if (theta < currentTheta) { - theta += 2 * Math.PI; - } else { - currentTheta += 2 * Math.PI; - } - } + var parentB = parentA.alternate; - sphericalDelta.theta = theta - currentTheta; - scope.update(); - }; + if (parentB === null) { + // There is no alternate. This is an unusual case. Currently, it only + // happens when a Suspense component is hidden. An extra fragment fiber + // is inserted in between the Suspense fiber and its children. Skip + // over this extra fragment fiber and proceed to the next parent. + var nextParent = parentA.return; - this.getDistance = () => scope.object.position.distanceTo(scope.target); + if (nextParent !== null) { + a = b = nextParent; + continue; + } // If there's no parent, we're at the root. - this.listenToKeyEvents = domElement => { - domElement.addEventListener('keydown', onKeyDown); - this._domElementKeyEvents = domElement; - }; - this.saveState = () => { - scope.target0.copy(scope.target); - scope.position0.copy(scope.object.position); - scope.zoom0 = scope.object instanceof PerspectiveCamera ? scope.object.zoom : 1; - }; + break; + } // If both copies of the parent fiber point to the same child, we can + // assume that the child is current. This happens when we bailout on low + // priority: the bailed out fiber's child reuses the current child. - this.reset = () => { - scope.target.copy(scope.target0); - scope.object.position.copy(scope.position0); - if (scope.object instanceof PerspectiveCamera) { - scope.object.zoom = scope.zoom0; - scope.object.updateProjectionMatrix(); - } + if (parentA.child === parentB.child) { + var child = parentA.child; - scope.dispatchEvent(changeEvent); - scope.update(); - state = STATE.NONE; - }; // this method is exposed, but perhaps it would be better if we can make it private... + while (child) { + if (child === a) { + // We've determined that A is the current branch. + assertIsMounted(parentA); + return fiber; + } + if (child === b) { + // We've determined that B is the current branch. + assertIsMounted(parentA); + return alternate; + } - this.update = (() => { - const offset = new Vector3(); // so camera.up is the orbit axis + child = child.sibling; + } // We should never have an alternate for any mounting node. So the only + // way this could possibly happen is if this was unmounted, if at all. - const quat = new Quaternion().setFromUnitVectors(object.up, new Vector3(0, 1, 0)); - const quatInverse = quat.clone().invert(); - const lastPosition = new Vector3(); - const lastQuaternion = new Quaternion(); - const twoPI = 2 * Math.PI; - return function update() { - const position = scope.object.position; - offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space - offset.applyQuaternion(quat); // angle from z-axis around y-axis + throw new Error('Unable to find node on an unmounted component.'); + } - spherical.setFromVector3(offset); + if (a.return !== b.return) { + // The return pointer of A and the return pointer of B point to different + // fibers. We assume that return pointers never criss-cross, so A must + // belong to the child set of A.return, and B must belong to the child + // set of B.return. + a = parentA; + b = parentB; + } else { + // The return pointers point to the same fiber. We'll have to use the + // default, slow path: scan the child sets of each parent alternate to see + // which child belongs to which set. + // + // Search parent A's child set + var didFindChild = false; + var _child = parentA.child; - if (scope.autoRotate && state === STATE.NONE) { - rotateLeft(getAutoRotationAngle()); - } + while (_child) { + if (_child === a) { + didFindChild = true; + a = parentA; + b = parentB; + break; + } - if (scope.enableDamping) { - spherical.theta += sphericalDelta.theta * scope.dampingFactor; - spherical.phi += sphericalDelta.phi * scope.dampingFactor; - } else { - spherical.theta += sphericalDelta.theta; - spherical.phi += sphericalDelta.phi; - } // restrict theta to be between desired limits + if (_child === b) { + didFindChild = true; + b = parentA; + a = parentB; + break; + } + _child = _child.sibling; + } - let min = scope.minAzimuthAngle; - let max = scope.maxAzimuthAngle; + if (!didFindChild) { + // Search parent B's child set + _child = parentB.child; - if (isFinite(min) && isFinite(max)) { - if (min < -Math.PI) min += twoPI;else if (min > Math.PI) min -= twoPI; - if (max < -Math.PI) max += twoPI;else if (max > Math.PI) max -= twoPI; + while (_child) { + if (_child === a) { + didFindChild = true; + a = parentB; + b = parentA; + break; + } - if (min <= max) { - spherical.theta = Math.max(min, Math.min(max, spherical.theta)); - } else { - spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta); - } - } // restrict phi to be between desired limits + if (_child === b) { + didFindChild = true; + b = parentB; + a = parentA; + break; + } + _child = _child.sibling; + } - spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi)); - spherical.makeSafe(); - spherical.radius *= scale; // restrict radius to be between desired limits + if (!didFindChild) { + throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.'); + } + } + } - spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location + if (a.alternate !== b) { + throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.'); + } + } // If the root is not a host container, we're in a disconnected tree. I.e. + // unmounted. - if (scope.enableDamping === true) { - scope.target.addScaledVector(panOffset, scope.dampingFactor); - } else { - scope.target.add(panOffset); - } - offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space + if (a.tag !== HostRoot) { + throw new Error('Unable to find node on an unmounted component.'); + } - offset.applyQuaternion(quatInverse); - position.copy(scope.target).add(offset); - scope.object.lookAt(scope.target); + if (a.stateNode.current === a) { + // We've determined that A is the current branch. + return fiber; + } // Otherwise B has to be current branch. - if (scope.enableDamping === true) { - sphericalDelta.theta *= 1 - scope.dampingFactor; - sphericalDelta.phi *= 1 - scope.dampingFactor; - panOffset.multiplyScalar(1 - scope.dampingFactor); - } else { - sphericalDelta.set(0, 0, 0); - panOffset.set(0, 0, 0); - } - scale = 1; // update condition is: - // min(camera displacement, camera rotation in radians)^2 > EPS - // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + return alternate; + } + function findCurrentHostFiber(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null; + } - if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) { - scope.dispatchEvent(changeEvent); - lastPosition.copy(scope.object.position); - lastQuaternion.copy(scope.object.quaternion); - zoomChanged = false; - return true; - } + function findCurrentHostFiberImpl(node) { + // Next we'll drill down this component to find the first HostComponent/Text. + if (node.tag === HostComponent || node.tag === HostText) { + return node; + } - return false; - }; - })(); // https://github.com/mrdoob/three.js/issues/20575 + var child = node.child; + while (child !== null) { + var match = findCurrentHostFiberImpl(child); - this.connect = domElement => { - if (domElement === document) { - console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'); - } + if (match !== null) { + return match; + } - scope.domElement = domElement; // disables touch scroll - // touch-action needs to be defined for pointer events to work on mobile - // https://stackoverflow.com/a/48254578 + child = child.sibling; + } - scope.domElement.style.touchAction = 'none'; - scope.domElement.addEventListener('contextmenu', onContextMenu); - scope.domElement.addEventListener('pointerdown', onPointerDown); - scope.domElement.addEventListener('pointercancel', onPointerCancel); - scope.domElement.addEventListener('wheel', onMouseWheel); - }; + return null; + } - this.dispose = () => { - var _scope$domElement, _scope$domElement2, _scope$domElement3, _scope$domElement4, _scope$domElement5, _scope$domElement6; + function findCurrentHostFiberWithNoPortals(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null; + } - (_scope$domElement = scope.domElement) === null || _scope$domElement === void 0 ? void 0 : _scope$domElement.removeEventListener('contextmenu', onContextMenu); - (_scope$domElement2 = scope.domElement) === null || _scope$domElement2 === void 0 ? void 0 : _scope$domElement2.removeEventListener('pointerdown', onPointerDown); - (_scope$domElement3 = scope.domElement) === null || _scope$domElement3 === void 0 ? void 0 : _scope$domElement3.removeEventListener('pointercancel', onPointerCancel); - (_scope$domElement4 = scope.domElement) === null || _scope$domElement4 === void 0 ? void 0 : _scope$domElement4.removeEventListener('wheel', onMouseWheel); - (_scope$domElement5 = scope.domElement) === null || _scope$domElement5 === void 0 ? void 0 : _scope$domElement5.ownerDocument.removeEventListener('pointermove', onPointerMove); - (_scope$domElement6 = scope.domElement) === null || _scope$domElement6 === void 0 ? void 0 : _scope$domElement6.ownerDocument.removeEventListener('pointerup', onPointerUp); + function findCurrentHostFiberWithNoPortalsImpl(node) { + // Next we'll drill down this component to find the first HostComponent/Text. + if (node.tag === HostComponent || node.tag === HostText) { + return node; + } - if (scope._domElementKeyEvents !== null) { - scope._domElementKeyEvents.removeEventListener('keydown', onKeyDown); - } //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? + var child = node.child; - }; // - // internals - // + while (child !== null) { + if (child.tag !== HostPortal) { + var match = findCurrentHostFiberWithNoPortalsImpl(child); + if (match !== null) { + return match; + } + } - const scope = this; - const changeEvent = { - type: 'change' - }; - const startEvent = { - type: 'start' - }; - const endEvent = { - type: 'end' - }; - const STATE = { - NONE: -1, - ROTATE: 0, - DOLLY: 1, - PAN: 2, - TOUCH_ROTATE: 3, - TOUCH_PAN: 4, - TOUCH_DOLLY_PAN: 5, - TOUCH_DOLLY_ROTATE: 6 - }; - let state = STATE.NONE; - const EPS = 0.000001; // current position in spherical coordinates - - const spherical = new Spherical(); - const sphericalDelta = new Spherical(); - let scale = 1; - const panOffset = new Vector3(); - let zoomChanged = false; - const rotateStart = new Vector2(); - const rotateEnd = new Vector2(); - const rotateDelta = new Vector2(); - const panStart = new Vector2(); - const panEnd = new Vector2(); - const panDelta = new Vector2(); - const dollyStart = new Vector2(); - const dollyEnd = new Vector2(); - const dollyDelta = new Vector2(); - const pointers = []; - const pointerPositions = {}; - - function getAutoRotationAngle() { - return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - } + child = child.sibling; + } - function getZoomScale() { - return Math.pow(0.95, scope.zoomSpeed); - } + return null; + } - function rotateLeft(angle) { - if (scope.reverseOrbit) { - sphericalDelta.theta += angle; - } else { - sphericalDelta.theta -= angle; - } - } + var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare - function rotateUp(angle) { - if (scope.reverseOrbit) { - sphericalDelta.phi += angle; - } else { - sphericalDelta.phi -= angle; - } - } + function isArray(a) { + return isArrayImpl(a); + } - const panLeft = (() => { - const v = new Vector3(); - return function panLeft(distance, objectMatrix) { - v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix + // This is a host config that's used for the `react-reconciler` package on npm. + // It is only used by third-party renderers. + // + // Its API lets you pass the host config as an argument. + // However, inside the `react-reconciler` we treat host config as a module. + // This file is a shim between two worlds. + // + // It works because the `react-reconciler` bundle is wrapped in something like: + // + // module.exports = function ($$$config) { + // /* reconciler code */ + // } + // + // So `$$$config` looks like a global variable, but it's + // really an argument to a top-level wrapping function. + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + var getPublicInstance = $$$hostConfig.getPublicInstance; + var getRootHostContext = $$$hostConfig.getRootHostContext; + var getChildHostContext = $$$hostConfig.getChildHostContext; + var prepareForCommit = $$$hostConfig.prepareForCommit; + var resetAfterCommit = $$$hostConfig.resetAfterCommit; + var createInstance = $$$hostConfig.createInstance; + var appendInitialChild = $$$hostConfig.appendInitialChild; + var finalizeInitialChildren = $$$hostConfig.finalizeInitialChildren; + var prepareUpdate = $$$hostConfig.prepareUpdate; + var shouldSetTextContent = $$$hostConfig.shouldSetTextContent; + var createTextInstance = $$$hostConfig.createTextInstance; + var scheduleTimeout = $$$hostConfig.scheduleTimeout; + var cancelTimeout = $$$hostConfig.cancelTimeout; + var noTimeout = $$$hostConfig.noTimeout; + $$$hostConfig.now; + var isPrimaryRenderer = $$$hostConfig.isPrimaryRenderer; + var warnsIfNotActing = $$$hostConfig.warnsIfNotActing; + var supportsMutation = $$$hostConfig.supportsMutation; + var supportsPersistence = $$$hostConfig.supportsPersistence; + var supportsHydration = $$$hostConfig.supportsHydration; + var getInstanceFromNode = $$$hostConfig.getInstanceFromNode; + $$$hostConfig.beforeActiveInstanceBlur; + $$$hostConfig.afterActiveInstanceBlur; + var preparePortalMount = $$$hostConfig.preparePortalMount; + $$$hostConfig.preparePortalMount; + $$$hostConfig.getInstanceFromScope; + var getCurrentEventPriority = $$$hostConfig.getCurrentEventPriority; + var detachDeletedInstance = $$$hostConfig.detachDeletedInstance; // ------------------- + // Microtasks + // (optional) + // ------------------- - v.multiplyScalar(-distance); - panOffset.add(v); - }; - })(); + var supportsMicrotasks = $$$hostConfig.supportsMicrotasks; + var scheduleMicrotask = $$$hostConfig.scheduleMicrotask; // ------------------- + // Test selectors + // (optional) + // ------------------- - const panUp = (() => { - const v = new Vector3(); - return function panUp(distance, objectMatrix) { - if (scope.screenSpacePanning === true) { - v.setFromMatrixColumn(objectMatrix, 1); - } else { - v.setFromMatrixColumn(objectMatrix, 0); - v.crossVectors(scope.object.up, v); - } + var supportsTestSelectors = $$$hostConfig.supportsTestSelectors; + var findFiberRoot = $$$hostConfig.findFiberRoot; + var getBoundingRect = $$$hostConfig.getBoundingRect; + var getTextContent = $$$hostConfig.getTextContent; + var isHiddenSubtree = $$$hostConfig.isHiddenSubtree; + var matchAccessibilityRole = $$$hostConfig.matchAccessibilityRole; + var setFocusIfFocusable = $$$hostConfig.setFocusIfFocusable; + var setupIntersectionObserver = $$$hostConfig.setupIntersectionObserver; // ------------------- + // Mutation + // (optional) + // ------------------- - v.multiplyScalar(distance); - panOffset.add(v); - }; - })(); // deltaX and deltaY are in pixels; right and down are positive + var appendChild = $$$hostConfig.appendChild; + var appendChildToContainer = $$$hostConfig.appendChildToContainer; + var commitTextUpdate = $$$hostConfig.commitTextUpdate; + var commitMount = $$$hostConfig.commitMount; + var commitUpdate = $$$hostConfig.commitUpdate; + var insertBefore = $$$hostConfig.insertBefore; + var insertInContainerBefore = $$$hostConfig.insertInContainerBefore; + var removeChild = $$$hostConfig.removeChild; + var removeChildFromContainer = $$$hostConfig.removeChildFromContainer; + var resetTextContent = $$$hostConfig.resetTextContent; + var hideInstance = $$$hostConfig.hideInstance; + var hideTextInstance = $$$hostConfig.hideTextInstance; + var unhideInstance = $$$hostConfig.unhideInstance; + var unhideTextInstance = $$$hostConfig.unhideTextInstance; + var clearContainer = $$$hostConfig.clearContainer; // ------------------- + // Persistence + // (optional) + // ------------------- + var cloneInstance = $$$hostConfig.cloneInstance; + var createContainerChildSet = $$$hostConfig.createContainerChildSet; + var appendChildToContainerChildSet = $$$hostConfig.appendChildToContainerChildSet; + var finalizeContainerChildren = $$$hostConfig.finalizeContainerChildren; + var replaceContainerChildren = $$$hostConfig.replaceContainerChildren; + $$$hostConfig.getOffscreenContainerType; + var getOffscreenContainerProps = $$$hostConfig.getOffscreenContainerProps; + var cloneHiddenInstance = $$$hostConfig.cloneHiddenInstance; + var cloneHiddenTextInstance = $$$hostConfig.cloneHiddenTextInstance; // ------------------- + // Hydration + // (optional) + // ------------------- - const pan = (() => { - const offset = new Vector3(); - return function pan(deltaX, deltaY) { - const element = scope.domElement; + var canHydrateInstance = $$$hostConfig.canHydrateInstance; + var canHydrateTextInstance = $$$hostConfig.canHydrateTextInstance; + var canHydrateSuspenseInstance = $$$hostConfig.canHydrateSuspenseInstance; + var isSuspenseInstancePending = $$$hostConfig.isSuspenseInstancePending; + var isSuspenseInstanceFallback = $$$hostConfig.isSuspenseInstanceFallback; + var registerSuspenseInstanceRetry = $$$hostConfig.registerSuspenseInstanceRetry; + var getNextHydratableSibling = $$$hostConfig.getNextHydratableSibling; + var getFirstHydratableChild = $$$hostConfig.getFirstHydratableChild; + var getFirstHydratableChildWithinContainer = $$$hostConfig.getFirstHydratableChildWithinContainer; + var getFirstHydratableChildWithinSuspenseInstance = $$$hostConfig.getFirstHydratableChildWithinSuspenseInstance; + var hydrateInstance = $$$hostConfig.hydrateInstance; + var hydrateTextInstance = $$$hostConfig.hydrateTextInstance; + var hydrateSuspenseInstance = $$$hostConfig.hydrateSuspenseInstance; + var getNextHydratableInstanceAfterSuspenseInstance = $$$hostConfig.getNextHydratableInstanceAfterSuspenseInstance; + var commitHydratedContainer = $$$hostConfig.commitHydratedContainer; + var commitHydratedSuspenseInstance = $$$hostConfig.commitHydratedSuspenseInstance; + var clearSuspenseBoundary = $$$hostConfig.clearSuspenseBoundary; + var clearSuspenseBoundaryFromContainer = $$$hostConfig.clearSuspenseBoundaryFromContainer; + var shouldDeleteUnhydratedTailInstances = $$$hostConfig.shouldDeleteUnhydratedTailInstances; + var didNotMatchHydratedContainerTextInstance = $$$hostConfig.didNotMatchHydratedContainerTextInstance; + var didNotMatchHydratedTextInstance = $$$hostConfig.didNotMatchHydratedTextInstance; + var didNotHydrateInstanceWithinContainer = $$$hostConfig.didNotHydrateInstanceWithinContainer; + var didNotHydrateInstanceWithinSuspenseInstance = $$$hostConfig.didNotHydrateInstanceWithinSuspenseInstance; + var didNotHydrateInstance = $$$hostConfig.didNotHydrateInstance; + var didNotFindHydratableInstanceWithinContainer = $$$hostConfig.didNotFindHydratableInstanceWithinContainer; + var didNotFindHydratableTextInstanceWithinContainer = $$$hostConfig.didNotFindHydratableTextInstanceWithinContainer; + var didNotFindHydratableSuspenseInstanceWithinContainer = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinContainer; + var didNotFindHydratableInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableInstanceWithinSuspenseInstance; + var didNotFindHydratableTextInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableTextInstanceWithinSuspenseInstance; + var didNotFindHydratableSuspenseInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinSuspenseInstance; + var didNotFindHydratableInstance = $$$hostConfig.didNotFindHydratableInstance; + var didNotFindHydratableTextInstance = $$$hostConfig.didNotFindHydratableTextInstance; + var didNotFindHydratableSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstance; + var errorHydratingContainer = $$$hostConfig.errorHydratingContainer; - if (element && scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) { - // perspective - const position = scope.object.position; - offset.copy(position).sub(scope.target); - let targetDistance = offset.length(); // half of the fov is center to top of screen + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; - targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed + function disabledLog() {} - panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix); - panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix); - } else if (element && scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { - // orthographic - panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix); - panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix); - } else { - // camera neither orthographic nor perspective - console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.'); - scope.enablePan = false; - } - }; - })(); - - function dollyOut(dollyScale) { - if (scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) { - scale /= dollyScale; - } else if (scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { - scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale)); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - } else { - console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.'); - scope.enableZoom = false; - } - } + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 - function dollyIn(dollyScale) { - if (scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) { - scale *= dollyScale; - } else if (scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { - scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale)); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - } else { - console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.'); - scope.enableZoom = false; - } - } // - // event callbacks - update the object state - // + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } - function handleMouseDownRotate(event) { - rotateStart.set(event.clientX, event.clientY); - } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; - function handleMouseDownDolly(event) { - dollyStart.set(event.clientX, event.clientY); - } + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. - function handleMouseDownPan(event) { - panStart.set(event.clientX, event.clientY); - } + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } - function handleMouseMoveRotate(event) { - rotateEnd.set(event.clientX, event.clientY); - rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); - const element = scope.domElement; + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } + } - if (element) { - rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. - rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); - } - rotateStart.copy(rotateEnd); - scope.update(); - } + return '\n' + prefix + name; + } + } + var reentry = false; + var componentFrameCache; - function handleMouseMoveDolly(event) { - dollyEnd.set(event.clientX, event.clientY); - dollyDelta.subVectors(dollyEnd, dollyStart); + { + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } - if (dollyDelta.y > 0) { - dollyOut(getZoomScale()); - } else if (dollyDelta.y < 0) { - dollyIn(getZoomScale()); - } + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } - dollyStart.copy(dollyEnd); - scope.update(); - } + { + var frame = componentFrameCache.get(fn); - function handleMouseMovePan(event) { - panEnd.set(event.clientX, event.clientY); - panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); - pan(panDelta.x, panDelta.y); - panStart.copy(panEnd); - scope.update(); - } + if (frame !== undefined) { + return frame; + } + } - function handleMouseWheel(event) { - if (event.deltaY < 0) { - dollyIn(getZoomScale()); - } else if (event.deltaY > 0) { - dollyOut(getZoomScale()); - } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. - scope.update(); - } + Error.prepareStackTrace = undefined; + var previousDispatcher; - function handleKeyDown(event) { - let needsUpdate = false; + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. - switch (event.code) { - case scope.keys.UP: - pan(0, scope.keyPanSpeed); - needsUpdate = true; - break; + ReactCurrentDispatcher.current = null; + disableLogs(); + } - case scope.keys.BOTTOM: - pan(0, -scope.keyPanSpeed); - needsUpdate = true; - break; + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe - case scope.keys.LEFT: - pan(scope.keyPanSpeed, 0); - needsUpdate = true; - break; - case scope.keys.RIGHT: - pan(-scope.keyPanSpeed, 0); - needsUpdate = true; - break; - } + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); - if (needsUpdate) { - // prevent the browser from scrolling on cursor keys - event.preventDefault(); - scope.update(); - } - } + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } - function handleTouchStartRotate() { - if (pointers.length == 1) { - rotateStart.set(pointers[0].pageX, pointers[0].pageY); - } else { - const x = 0.5 * (pointers[0].pageX + pointers[1].pageX); - const y = 0.5 * (pointers[0].pageY + pointers[1].pageY); - rotateStart.set(x, y); - } - } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } - function handleTouchStartPan() { - if (pointers.length == 1) { - panStart.set(pointers[0].pageX, pointers[0].pageY); - } else { - const x = 0.5 * (pointers[0].pageX + pointers[1].pageX); - const y = 0.5 * (pointers[0].pageY + pointers[1].pageY); - panStart.set(x, y); - } - } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } - function handleTouchStartDolly() { - const dx = pointers[0].pageX - pointers[1].pageX; - const dy = pointers[0].pageY - pointers[1].pageY; - const distance = Math.sqrt(dx * dx + dy * dy); - dollyStart.set(0, distance); - } + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; - function handleTouchStartDollyPan() { - if (scope.enableZoom) handleTouchStartDolly(); - if (scope.enablePan) handleTouchStartPan(); - } + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } - function handleTouchStartDollyRotate() { - if (scope.enableZoom) handleTouchStartDolly(); - if (scope.enableRotate) handleTouchStartRotate(); - } + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. - function handleTouchMoveRotate(event) { - if (pointers.length == 1) { - rotateEnd.set(event.pageX, event.pageY); - } else { - const position = getSecondPointerPosition(event); - const x = 0.5 * (event.pageX + position.x); - const y = 0.5 * (event.pageY + position.y); - rotateEnd.set(x, y); - } + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. - rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); - const element = scope.domElement; - if (element) { - rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } - rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); - } + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. - rotateStart.copy(rotateEnd); - } - function handleTouchMovePan(event) { - if (pointers.length == 1) { - panEnd.set(event.pageX, event.pageY); - } else { - const position = getSecondPointerPosition(event); - const x = 0.5 * (event.pageX + position.x); - const y = 0.5 * (event.pageY + position.y); - panEnd.set(x, y); - } + return _frame; + } + } while (s >= 1 && c >= 0); + } - panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); - pan(panDelta.x, panDelta.y); - panStart.copy(panEnd); - } + break; + } + } + } + } finally { + reentry = false; - function handleTouchMoveDolly(event) { - const position = getSecondPointerPosition(event); - const dx = event.pageX - position.x; - const dy = event.pageY - position.y; - const distance = Math.sqrt(dx * dx + dy * dy); - dollyEnd.set(0, distance); - dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed)); - dollyOut(dollyDelta.y); - dollyStart.copy(dollyEnd); - } + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } - function handleTouchMoveDollyPan(event) { - if (scope.enableZoom) handleTouchMoveDolly(event); - if (scope.enablePan) handleTouchMovePan(event); - } + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. - function handleTouchMoveDollyRotate(event) { - if (scope.enableZoom) handleTouchMoveDolly(event); - if (scope.enableRotate) handleTouchMoveRotate(event); - } // - // event handlers - FSM: listen for events and reset state - // + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; - function onPointerDown(event) { - if (scope.enabled === false) return; + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } - if (pointers.length === 0) { - var _scope$domElement7, _scope$domElement8; + return syntheticFrame; + } - (_scope$domElement7 = scope.domElement) === null || _scope$domElement7 === void 0 ? void 0 : _scope$domElement7.ownerDocument.addEventListener('pointermove', onPointerMove); - (_scope$domElement8 = scope.domElement) === null || _scope$domElement8 === void 0 ? void 0 : _scope$domElement8.ownerDocument.addEventListener('pointerup', onPointerUp); - } + function describeClassComponentFrame(ctor, source, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } - addPointer(event); + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } - if (event.pointerType === 'touch') { - onTouchStart(event); - } else { - onMouseDown(event); - } - } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - function onPointerMove(event) { - if (scope.enabled === false) return; + if (type == null) { + return ''; + } - if (event.pointerType === 'touch') { - onTouchMove(event); - } else { - onMouseMove(event); - } - } + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } - function onPointerUp(event) { - removePointer(event); + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } - if (pointers.length === 0) { - var _scope$domElement9, _scope$domElement10, _scope$domElement11; + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); - (_scope$domElement9 = scope.domElement) === null || _scope$domElement9 === void 0 ? void 0 : _scope$domElement9.releasePointerCapture(event.pointerId); - (_scope$domElement10 = scope.domElement) === null || _scope$domElement10 === void 0 ? void 0 : _scope$domElement10.ownerDocument.removeEventListener('pointermove', onPointerMove); - (_scope$domElement11 = scope.domElement) === null || _scope$domElement11 === void 0 ? void 0 : _scope$domElement11.ownerDocument.removeEventListener('pointerup', onPointerUp); - } + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } - scope.dispatchEvent(endEvent); - state = STATE.NONE; - } + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); - function onPointerCancel(event) { - removePointer(event); - } + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - function onMouseDown(event) { - let mouseAction; + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; - switch (event.button) { - case 0: - mouseAction = scope.mouseButtons.LEFT; - break; + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } - case 1: - mouseAction = scope.mouseButtons.MIDDLE; - break; + return ''; + } - case 2: - mouseAction = scope.mouseButtons.RIGHT; - break; + var hasOwnProperty = Object.prototype.hasOwnProperty; - default: - mouseAction = -1; - } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - switch (mouseAction) { - case MOUSE.DOLLY: - if (scope.enableZoom === false) return; - handleMouseDownDolly(event); - state = STATE.DOLLY; - break; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } + } - case MOUSE.ROTATE: - if (event.ctrlKey || event.metaKey || event.shiftKey) { - if (scope.enablePan === false) return; - handleMouseDownPan(event); - state = STATE.PAN; - } else { - if (scope.enableRotate === false) return; - handleMouseDownRotate(event); - state = STATE.ROTATE; - } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); - break; + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. - case MOUSE.PAN: - if (event.ctrlKey || event.metaKey || event.shiftKey) { - if (scope.enableRotate === false) return; - handleMouseDownRotate(event); - state = STATE.ROTATE; - } else { - if (scope.enablePan === false) return; - handleMouseDownPan(event); - state = STATE.PAN; - } + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } - break; + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } - default: - state = STATE.NONE; - } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); - if (state !== STATE.NONE) { - scope.dispatchEvent(startEvent); - } - } + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); - function onMouseMove(event) { - if (scope.enabled === false) return; + setCurrentlyValidatingElement(null); + } - switch (state) { - case STATE.ROTATE: - if (scope.enableRotate === false) return; - handleMouseMoveRotate(event); - break; + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); - case STATE.DOLLY: - if (scope.enableZoom === false) return; - handleMouseMoveDolly(event); - break; + error('Failed %s type: %s', location, error$1.message); - case STATE.PAN: - if (scope.enablePan === false) return; - handleMouseMovePan(event); - break; - } - } + setCurrentlyValidatingElement(null); + } + } + } + } + } - function onMouseWheel(event) { - if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) { - return; - } + var valueStack = []; + var fiberStack; - event.preventDefault(); - scope.dispatchEvent(startEvent); - handleMouseWheel(event); - scope.dispatchEvent(endEvent); - } + { + fiberStack = []; + } - function onKeyDown(event) { - if (scope.enabled === false || scope.enablePan === false) return; - handleKeyDown(event); - } + var index = -1; - function onTouchStart(event) { - trackPointer(event); + function createCursor(defaultValue) { + return { + current: defaultValue + }; + } - switch (pointers.length) { - case 1: - switch (scope.touches.ONE) { - case TOUCH.ROTATE: - if (scope.enableRotate === false) return; - handleTouchStartRotate(); - state = STATE.TOUCH_ROTATE; - break; + function pop(cursor, fiber) { + if (index < 0) { + { + error('Unexpected pop.'); + } - case TOUCH.PAN: - if (scope.enablePan === false) return; - handleTouchStartPan(); - state = STATE.TOUCH_PAN; - break; + return; + } - default: - state = STATE.NONE; - } + { + if (fiber !== fiberStack[index]) { + error('Unexpected Fiber popped.'); + } + } - break; + cursor.current = valueStack[index]; + valueStack[index] = null; - case 2: - switch (scope.touches.TWO) { - case TOUCH.DOLLY_PAN: - if (scope.enableZoom === false && scope.enablePan === false) return; - handleTouchStartDollyPan(); - state = STATE.TOUCH_DOLLY_PAN; - break; + { + fiberStack[index] = null; + } - case TOUCH.DOLLY_ROTATE: - if (scope.enableZoom === false && scope.enableRotate === false) return; - handleTouchStartDollyRotate(); - state = STATE.TOUCH_DOLLY_ROTATE; - break; + index--; + } - default: - state = STATE.NONE; - } + function push(cursor, value, fiber) { + index++; + valueStack[index] = cursor.current; - break; + { + fiberStack[index] = fiber; + } - default: - state = STATE.NONE; - } + cursor.current = value; + } - if (state !== STATE.NONE) { - scope.dispatchEvent(startEvent); - } - } + var warnedAboutMissingGetChildContext; - function onTouchMove(event) { - trackPointer(event); + { + warnedAboutMissingGetChildContext = {}; + } - switch (state) { - case STATE.TOUCH_ROTATE: - if (scope.enableRotate === false) return; - handleTouchMoveRotate(event); - scope.update(); - break; + var emptyContextObject = {}; - case STATE.TOUCH_PAN: - if (scope.enablePan === false) return; - handleTouchMovePan(event); - scope.update(); - break; + { + Object.freeze(emptyContextObject); + } // A cursor to the current merged context object on the stack. - case STATE.TOUCH_DOLLY_PAN: - if (scope.enableZoom === false && scope.enablePan === false) return; - handleTouchMoveDollyPan(event); - scope.update(); - break; - case STATE.TOUCH_DOLLY_ROTATE: - if (scope.enableZoom === false && scope.enableRotate === false) return; - handleTouchMoveDollyRotate(event); - scope.update(); - break; + var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. - default: - state = STATE.NONE; - } - } + var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. + // We use this to get access to the parent context after we have already + // pushed the next context provider, and now need to merge their contexts. - function onContextMenu(event) { - if (scope.enabled === false) return; - event.preventDefault(); - } + var previousContext = emptyContextObject; - function addPointer(event) { - pointers.push(event); - } + function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) { + { + if (didPushOwnContextIfProvider && isContextProvider(Component)) { + // If the fiber is a context provider itself, when we read its context + // we may have already pushed its own child context on the stack. A context + // provider should not "see" its own child context. Therefore we read the + // previous (parent) context instead for a context provider. + return previousContext; + } - function removePointer(event) { - delete pointerPositions[event.pointerId]; + return contextStackCursor.current; + } + } - for (let i = 0; i < pointers.length; i++) { - if (pointers[i].pointerId == event.pointerId) { - pointers.splice(i, 1); - return; - } - } - } + function cacheContext(workInProgress, unmaskedContext, maskedContext) { + { + var instance = workInProgress.stateNode; + instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; + instance.__reactInternalMemoizedMaskedChildContext = maskedContext; + } + } - function trackPointer(event) { - let position = pointerPositions[event.pointerId]; + function getMaskedContext(workInProgress, unmaskedContext) { + { + var type = workInProgress.type; + var contextTypes = type.contextTypes; - if (position === undefined) { - position = new Vector2(); - pointerPositions[event.pointerId] = position; - } + if (!contextTypes) { + return emptyContextObject; + } // Avoid recreating masked context unless unmasked context has changed. + // Failing to do this will result in unnecessary calls to componentWillReceiveProps. + // This may trigger infinite loops if componentWillReceiveProps calls setState. - position.set(event.pageX, event.pageY); - } - function getSecondPointerPosition(event) { - const pointer = event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0]; - return pointerPositions[pointer.pointerId]; - } // connect events + var instance = workInProgress.stateNode; + if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { + return instance.__reactInternalMemoizedMaskedChildContext; + } - if (domElement !== undefined) this.connect(domElement); // force an update at start + var context = {}; - this.update(); - } + for (var key in contextTypes) { + context[key] = unmaskedContext[key]; + } -} // This set of controls performs orbiting, dollying (zooming), and panning. + { + var name = getComponentNameFromFiber(workInProgress) || 'Unknown'; + checkPropTypes(contextTypes, context, 'context', name); + } // Cache unmasked context so we can avoid recreating masked context unless necessary. + // Context is created before the class component is instantiated so check for instance. -({ - camera: new Matrix4(), - gizmos: new Matrix4() -}); //events -class Pass$1 { - constructor() { - _defineProperty$1(this, "enabled", true); + if (instance) { + cacheContext(workInProgress, unmaskedContext, context); + } - _defineProperty$1(this, "needsSwap", true); + return context; + } + } - _defineProperty$1(this, "clear", false); + function hasContextChanged() { + { + return didPerformWorkStackCursor.current; + } + } - _defineProperty$1(this, "renderToScreen", false); - } + function isContextProvider(type) { + { + var childContextTypes = type.childContextTypes; + return childContextTypes !== null && childContextTypes !== undefined; + } + } - setSize( - /* eslint-disable @typescript-eslint/no-unused-vars */ + function popContext(fiber) { + { + pop(didPerformWorkStackCursor, fiber); + pop(contextStackCursor, fiber); + } + } - /* eslint-disable no-unused-vars */ - width, height) {} + function popTopLevelContextObject(fiber) { + { + pop(didPerformWorkStackCursor, fiber); + pop(contextStackCursor, fiber); + } + } - render( - /* eslint-disable @typescript-eslint/no-unused-vars */ + function pushTopLevelContextObject(fiber, context, didChange) { + { + if (contextStackCursor.current !== emptyContextObject) { + throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } - /* eslint-disable no-unused-vars */ - renderer, writeBuffer, readBuffer, deltaTime, maskActive) { - console.error('THREE.Pass: .render() must be implemented in derived pass.'); - } + push(contextStackCursor, context, fiber); + push(didPerformWorkStackCursor, didChange, fiber); + } + } -} // Helper for passes that need to fill the viewport with a single quad. + function processChildContext(fiber, type, parentContext) { + { + var instance = fiber.stateNode; + var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. + // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== 'function') { + { + var componentName = getComponentNameFromFiber(fiber) || 'Unknown'; -class FullScreenQuad { - constructor(material) { - _defineProperty$1(this, "camera", new OrthographicCamera(-1, 1, 1, -1, 0, 1)); + if (!warnedAboutMissingGetChildContext[componentName]) { + warnedAboutMissingGetChildContext[componentName] = true; - _defineProperty$1(this, "geometry", new PlaneGeometry(2, 2)); + error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); + } + } - _defineProperty$1(this, "mesh", void 0); + return parentContext; + } - this.mesh = new Mesh(this.geometry, material); - } + var childContext = instance.getChildContext(); - get material() { - return this.mesh.material; - } + for (var contextKey in childContext) { + if (!(contextKey in childContextTypes)) { + throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); + } + } - set material(value) { - this.mesh.material = value; - } + { + var name = getComponentNameFromFiber(fiber) || 'Unknown'; + checkPropTypes(childContextTypes, childContext, 'child context', name); + } - dispose() { - this.mesh.geometry.dispose(); - } + return assign({}, parentContext, childContext); + } + } - render(renderer) { - renderer.render(this.mesh, this.camera); - } + function pushContextProvider(workInProgress) { + { + var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. + // If the instance does not exist yet, we will push null at first, + // and replace it on the stack later when invalidating the context. -} + var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later. + // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. -/** - * WebGL port of Subpixel Morphological Antialiasing (SMAA) v2.8 - * Preset: SMAA 1x Medium (with color edge detection) - * https://github.com/iryoku/smaa/releases/tag/v2.8 - */ + previousContext = contextStackCursor.current; + push(contextStackCursor, memoizedMergedChildContext, workInProgress); + push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress); + return true; + } + } -({ - defines: { - SMAA_THRESHOLD: '0.1' - }, - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2(1 / 1024, 1 / 512) - } - }, - vertexShader: ['uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 3 ];', 'void SMAAEdgeDetectionVS( vec2 texcoord ) {', ' vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 );', // WebGL port note: Changed sign in W component - ' vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 );', // WebGL port note: Changed sign in W component - ' vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 );', // WebGL port note: Changed sign in W component - '}', 'void main() {', ' vUv = uv;', ' SMAAEdgeDetectionVS( vUv );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 3 ];', 'vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) {', ' vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD );', // Calculate color deltas: - ' vec4 delta;', ' vec3 C = texture2D( colorTex, texcoord ).rgb;', ' vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb;', ' vec3 t = abs( C - Cleft );', ' delta.x = max( max( t.r, t.g ), t.b );', ' vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb;', ' t = abs( C - Ctop );', ' delta.y = max( max( t.r, t.g ), t.b );', // We do the usual threshold: - ' vec2 edges = step( threshold, delta.xy );', // Then discard if there is no edge: - ' if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 )', ' discard;', // Calculate right and bottom deltas: - ' vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb;', ' t = abs( C - Cright );', ' delta.z = max( max( t.r, t.g ), t.b );', ' vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb;', ' t = abs( C - Cbottom );', ' delta.w = max( max( t.r, t.g ), t.b );', // Calculate the maximum delta in the direct neighborhood: - ' float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w );', // Calculate left-left and top-top deltas: - ' vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb;', ' t = abs( C - Cleftleft );', ' delta.z = max( max( t.r, t.g ), t.b );', ' vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb;', ' t = abs( C - Ctoptop );', ' delta.w = max( max( t.r, t.g ), t.b );', // Calculate the final maximum delta: - ' maxDelta = max( max( maxDelta, delta.z ), delta.w );', // Local contrast adaptation in action: - ' edges.xy *= step( 0.5 * maxDelta, delta.xy );', ' return vec4( edges, 0.0, 0.0 );', '}', 'void main() {', ' gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse );', '}'].join('\n') -}); -({ - defines: { - SMAA_MAX_SEARCH_STEPS: '8', - SMAA_AREATEX_MAX_DISTANCE: '16', - SMAA_AREATEX_PIXEL_SIZE: '( 1.0 / vec2( 160.0, 560.0 ) )', - SMAA_AREATEX_SUBTEX_SIZE: '( 1.0 / 7.0 )' - }, - uniforms: { - tDiffuse: { - value: null - }, - tArea: { - value: null - }, - tSearch: { - value: null - }, - resolution: { - value: new Vector2(1 / 1024, 1 / 512) - } - }, - vertexShader: ['uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 3 ];', 'varying vec2 vPixcoord;', 'void SMAABlendingWeightCalculationVS( vec2 texcoord ) {', ' vPixcoord = texcoord / resolution;', // We will use these offsets for the searches later on (see @PSEUDO_GATHER4): - ' vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 );', // WebGL port note: Changed sign in Y and W components - ' vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 );', // WebGL port note: Changed sign in Y and W components - // And these for the searches, they indicate the ends of the loops: - ' vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS );', '}', 'void main() {', ' vUv = uv;', ' SMAABlendingWeightCalculationVS( vUv );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 )', 'uniform sampler2D tDiffuse;', 'uniform sampler2D tArea;', 'uniform sampler2D tSearch;', 'uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[3];', 'varying vec2 vPixcoord;', '#if __VERSION__ == 100', 'vec2 round( vec2 x ) {', ' return sign( x ) * floor( abs( x ) + 0.5 );', '}', '#endif', 'float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) {', // Not required if searchTex accesses are set to point: - // float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0); - // e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE + - // e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE; - ' e.r = bias + e.r * scale;', ' return 255.0 * texture2D( searchTex, e, 0.0 ).r;', '}', 'float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {', - /** - * @PSEUDO_GATHER4 - * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to - * sample between edge, thus fetching four edges in a row. - * Sampling with different offsets in each direction allows to disambiguate - * which edges are active from the four fetched ones. - */ - ' vec2 e = vec2( 0.0, 1.0 );', ' for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) {', // WebGL port note: Changed while to for - ' e = texture2D( edgesTex, texcoord, 0.0 ).rg;', ' texcoord -= vec2( 2.0, 0.0 ) * resolution;', ' if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break;', ' }', // We correct the previous (-0.25, -0.125) offset we applied: - ' texcoord.x += 0.25 * resolution.x;', // The searches are bias by 1, so adjust the coords accordingly: - ' texcoord.x += resolution.x;', // Disambiguate the length added by the last step: - ' texcoord.x += 2.0 * resolution.x;', // Undo last step - ' texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5);', ' return texcoord.x;', '}', 'float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {', ' vec2 e = vec2( 0.0, 1.0 );', ' for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) {', // WebGL port note: Changed while to for - ' e = texture2D( edgesTex, texcoord, 0.0 ).rg;', ' texcoord += vec2( 2.0, 0.0 ) * resolution;', ' if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break;', ' }', ' texcoord.x -= 0.25 * resolution.x;', ' texcoord.x -= resolution.x;', ' texcoord.x -= 2.0 * resolution.x;', ' texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 );', ' return texcoord.x;', '}', 'float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {', ' vec2 e = vec2( 1.0, 0.0 );', ' for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) {', // WebGL port note: Changed while to for - ' e = texture2D( edgesTex, texcoord, 0.0 ).rg;', ' texcoord += vec2( 0.0, 2.0 ) * resolution;', // WebGL port note: Changed sign - ' if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break;', ' }', ' texcoord.y -= 0.25 * resolution.y;', // WebGL port note: Changed sign - ' texcoord.y -= resolution.y;', // WebGL port note: Changed sign - ' texcoord.y -= 2.0 * resolution.y;', // WebGL port note: Changed sign - ' texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 );', // WebGL port note: Changed sign - ' return texcoord.y;', '}', 'float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {', ' vec2 e = vec2( 1.0, 0.0 );', ' for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) {', // WebGL port note: Changed while to for - ' e = texture2D( edgesTex, texcoord, 0.0 ).rg;', ' texcoord -= vec2( 0.0, 2.0 ) * resolution;', // WebGL port note: Changed sign - ' if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break;', ' }', ' texcoord.y += 0.25 * resolution.y;', // WebGL port note: Changed sign - ' texcoord.y += resolution.y;', // WebGL port note: Changed sign - ' texcoord.y += 2.0 * resolution.y;', // WebGL port note: Changed sign - ' texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 );', // WebGL port note: Changed sign - ' return texcoord.y;', '}', 'vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) {', // Rounding prevents precision errors of bilinear filtering: - ' vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist;', // We do a scale and bias for mapping to texel space: - ' texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE );', // Move to proper place, according to the subpixel offset: - ' texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;', ' return texture2D( areaTex, texcoord, 0.0 ).rg;', '}', 'vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) {', ' vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 );', ' vec2 e = texture2D( edgesTex, texcoord ).rg;', ' if ( e.g > 0.0 ) {', // Edge at north - ' vec2 d;', // Find the distance to the left: - ' vec2 coords;', ' coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x );', ' coords.y = offset[ 1 ].y;', // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET) - ' d.x = coords.x;', // Now fetch the left crossing edges, two at a time using bilinear - // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to - // discern what value each edge has: - ' float e1 = texture2D( edgesTex, coords, 0.0 ).r;', // Find the distance to the right: - ' coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y );', ' d.y = coords.x;', // We want the distances to be in pixel units (doing this here allow to - // better interleave arithmetic and memory accesses): - ' d = d / resolution.x - pixcoord.x;', // SMAAArea below needs a sqrt, as the areas texture is compressed - // quadratically: - ' vec2 sqrt_d = sqrt( abs( d ) );', // Fetch the right crossing edges: - ' coords.y -= 1.0 * resolution.y;', // WebGL port note: Added - ' float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r;', // Ok, we know how this pattern looks like, now it is time for getting - // the actual area: - ' weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) );', ' }', ' if ( e.r > 0.0 ) {', // Edge at west - ' vec2 d;', // Find the distance to the top: - ' vec2 coords;', ' coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z );', ' coords.x = offset[ 0 ].x;', // offset[1].x = texcoord.x - 0.25 * resolution.x; - ' d.x = coords.y;', // Fetch the top crossing edges: - ' float e1 = texture2D( edgesTex, coords, 0.0 ).g;', // Find the distance to the bottom: - ' coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w );', ' d.y = coords.y;', // We want the distances to be in pixel units: - ' d = d / resolution.y - pixcoord.y;', // SMAAArea below needs a sqrt, as the areas texture is compressed - // quadratically: - ' vec2 sqrt_d = sqrt( abs( d ) );', // Fetch the bottom crossing edges: - ' coords.y -= 1.0 * resolution.y;', // WebGL port note: Added - ' float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g;', // Get the area for this direction: - ' weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) );', ' }', ' return weights;', '}', 'void main() {', ' gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) );', '}'].join('\n') -}); -({ - uniforms: { - tDiffuse: { - value: null - }, - tColor: { - value: null - }, - resolution: { - value: new Vector2(1 / 1024, 1 / 512) - } - }, - vertexShader: ['uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 2 ];', 'void SMAANeighborhoodBlendingVS( vec2 texcoord ) {', ' vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 );', // WebGL port note: Changed sign in W component - ' vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 );', // WebGL port note: Changed sign in W component - '}', 'void main() {', ' vUv = uv;', ' SMAANeighborhoodBlendingVS( vUv );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform sampler2D tColor;', 'uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 2 ];', 'vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) {', // Fetch the blending weights for current pixel: - ' vec4 a;', ' a.xz = texture2D( blendTex, texcoord ).xz;', ' a.y = texture2D( blendTex, offset[ 1 ].zw ).g;', ' a.w = texture2D( blendTex, offset[ 1 ].xy ).a;', // Is there any blending weight with a value greater than 0.0? - ' if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) {', ' return texture2D( colorTex, texcoord, 0.0 );', ' } else {', // Up to 4 lines can be crossing a pixel (one through each edge). We - // favor blending by choosing the line with the maximum weight for each - // direction: - ' vec2 offset;', ' offset.x = a.a > a.b ? a.a : -a.b;', // left vs. right - ' offset.y = a.g > a.r ? -a.g : a.r;', // top vs. bottom // WebGL port note: Changed signs - // Then we go in the direction that has the maximum weight: - ' if ( abs( offset.x ) > abs( offset.y )) {', // horizontal vs. vertical - ' offset.y = 0.0;', ' } else {', ' offset.x = 0.0;', ' }', // Fetch the opposite color and lerp by hand: - ' vec4 C = texture2D( colorTex, texcoord, 0.0 );', ' texcoord += sign( offset ) * resolution;', ' vec4 Cop = texture2D( colorTex, texcoord, 0.0 );', ' float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y );', // WebGL port note: Added gamma correction - ' C.xyz = pow(C.xyz, vec3(2.2));', ' Cop.xyz = pow(Cop.xyz, vec3(2.2));', ' vec4 mixed = mix(C, Cop, s);', ' mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2));', ' return mixed;', ' }', '}', 'void main() {', ' gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse );', '}'].join('\n') -}); + function invalidateContextProvider(workInProgress, type, didChange) { + { + var instance = workInProgress.stateNode; -/** - * Full-screen textured quad shader - */ -const CopyShader = { - uniforms: { - tDiffuse: { - value: null - }, - opacity: { - value: 1.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform float opacity;', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' gl_FragColor = opacity * texel;', '}'].join('\n') -}; + if (!instance) { + throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** - * References: - * http://john-chapman-graphics.blogspot.com/2013/01/ssao-tutorial.html - * https://learnopengl.com/Advanced-Lighting/SSAO - * https://github.com/McNopper/OpenGL/blob/master/Example28/shader/ssao.frag.glsl - */ + if (didChange) { + // Merge parent and own context. + // Skip this if we're not updating due to sCU. + // This avoids unnecessarily recomputing memoized values. + var mergedContext = processChildContext(workInProgress, type, previousContext); + instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. + // It is important to unwind the context in the reverse order. -const SSAOShader = { - defines: { - PERSPECTIVE_CAMERA: 1, - KERNEL_SIZE: 32 - }, - uniforms: { - tDiffuse: { - value: null - }, - tNormal: { - value: null - }, - tDepth: { - value: null - }, - tNoise: { - value: null - }, - kernel: { - value: null - }, - cameraNear: { - value: null - }, - cameraFar: { - value: null - }, - resolution: { - value: new Vector2() - }, - cameraProjectionMatrix: { - value: new Matrix4() - }, - cameraInverseProjectionMatrix: { - value: new Matrix4() - }, - kernelRadius: { - value: 8 - }, - minDistance: { - value: 0.005 - }, - maxDistance: { - value: 0.05 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform sampler2D tNormal;', 'uniform sampler2D tDepth;', 'uniform sampler2D tNoise;', 'uniform vec3 kernel[ KERNEL_SIZE ];', 'uniform vec2 resolution;', 'uniform float cameraNear;', 'uniform float cameraFar;', 'uniform mat4 cameraProjectionMatrix;', 'uniform mat4 cameraInverseProjectionMatrix;', 'uniform float kernelRadius;', 'uniform float minDistance;', // avoid artifacts caused by neighbour fragments with minimal depth difference - 'uniform float maxDistance;', // avoid the influence of fragments which are too far away - 'varying vec2 vUv;', '#include ', 'float getDepth( const in vec2 screenPosition ) {', ' return texture2D( tDepth, screenPosition ).x;', '}', 'float getLinearDepth( const in vec2 screenPosition ) {', ' #if PERSPECTIVE_CAMERA == 1', ' float fragCoordZ = texture2D( tDepth, screenPosition ).x;', ' float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );', ' return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );', ' #else', ' return texture2D( tDepth, screenPosition ).x;', ' #endif', '}', 'float getViewZ( const in float depth ) {', ' #if PERSPECTIVE_CAMERA == 1', ' return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );', ' #else', ' return orthographicDepthToViewZ( depth, cameraNear, cameraFar );', ' #endif', '}', 'vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {', ' float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];', ' vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );', ' clipPosition *= clipW; // unprojection.', ' return ( cameraInverseProjectionMatrix * clipPosition ).xyz;', '}', 'vec3 getViewNormal( const in vec2 screenPosition ) {', ' return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );', '}', 'void main() {', ' float depth = getDepth( vUv );', ' float viewZ = getViewZ( depth );', ' vec3 viewPosition = getViewPosition( vUv, depth, viewZ );', ' vec3 viewNormal = getViewNormal( vUv );', ' vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 );', ' vec3 random = texture2D( tNoise, vUv * noiseScale ).xyz;', // compute matrix used to reorient a kernel vector - ' vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) );', ' vec3 bitangent = cross( viewNormal, tangent );', ' mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal );', ' float occlusion = 0.0;', ' for ( int i = 0; i < KERNEL_SIZE; i ++ ) {', ' vec3 sampleVector = kernelMatrix * kernel[ i ];', // reorient sample vector in view space - ' vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius );', // calculate sample point - ' vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 );', // project point and calculate NDC - ' samplePointNDC /= samplePointNDC.w;', ' vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5;', // compute uv coordinates - ' float realDepth = getLinearDepth( samplePointUv );', // get linear depth from depth texture - ' float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar );', // compute linear depth of the sample view Z value - ' float delta = sampleDepth - realDepth;', ' if ( delta > minDistance && delta < maxDistance ) {', // if fragment is before sample point, increase occlusion - ' occlusion += 1.0;', ' }', ' }', ' occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 );', ' gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 );', '}'].join('\n') -}; -const SSAODepthShader = { - defines: { - PERSPECTIVE_CAMERA: 1 - }, - uniforms: { - tDepth: { - value: null - }, - cameraNear: { - value: null - }, - cameraFar: { - value: null - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDepth;', 'uniform float cameraNear;', 'uniform float cameraFar;', 'varying vec2 vUv;', '#include ', 'float getLinearDepth( const in vec2 screenPosition ) {', ' #if PERSPECTIVE_CAMERA == 1', ' float fragCoordZ = texture2D( tDepth, screenPosition ).x;', ' float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );', ' return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );', ' #else', ' return texture2D( tDepth, screenPosition ).x;', ' #endif', '}', 'void main() {', ' float depth = getLinearDepth( vUv );', ' gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );', '}'].join('\n') -}; -const SSAOBlurShader = { - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2() - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform vec2 resolution;', 'varying vec2 vUv;', 'void main() {', ' vec2 texelSize = ( 1.0 / resolution );', ' float result = 0.0;', ' for ( int i = - 2; i <= 2; i ++ ) {', ' for ( int j = - 2; j <= 2; j ++ ) {', ' vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize;', ' result += texture2D( tDiffuse, vUv + offset ).r;', ' }', ' }', ' gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 );', '}'].join('\n') -}; + pop(didPerformWorkStackCursor, workInProgress); + pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. -class SSAOPass extends Pass$1 { - constructor(scene, camera, width, height) { - super(); - this.width = width !== undefined ? width : 512; - this.height = height !== undefined ? height : 512; - this.clear = true; - this.camera = camera; - this.scene = scene; - this.kernelRadius = 8; - this.kernelSize = 32; - this.kernel = []; - this.noiseTexture = null; - this.output = 0; - this.minDistance = 0.005; - this.maxDistance = 0.1; - this._visibilityCache = new Map(); // - - this.generateSampleKernel(); - this.generateRandomKernelRotations(); // beauty render target - - const depthTexture = new DepthTexture(); - depthTexture.format = DepthStencilFormat; - depthTexture.type = UnsignedInt248Type; - this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height); // normal render target with depth buffer - - this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: NearestFilter, - magFilter: NearestFilter, - depthTexture: depthTexture - }); // ssao render target + push(contextStackCursor, mergedContext, workInProgress); + push(didPerformWorkStackCursor, didChange, workInProgress); + } else { + pop(didPerformWorkStackCursor, workInProgress); + push(didPerformWorkStackCursor, didChange, workInProgress); + } + } + } - this.ssaoRenderTarget = new WebGLRenderTarget(this.width, this.height); - this.blurRenderTarget = this.ssaoRenderTarget.clone(); // ssao material + function findCurrentUnmaskedContext(fiber) { + { + // Currently this is only used with renderSubtreeIntoContainer; not sure if it + // makes sense elsewhere + if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { + throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } - if (SSAOShader === undefined) { - console.error('THREE.SSAOPass: The pass relies on SSAOShader.'); - } + var node = fiber; - this.ssaoMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSAOShader.defines), - uniforms: UniformsUtils.clone(SSAOShader.uniforms), - vertexShader: SSAOShader.vertexShader, - fragmentShader: SSAOShader.fragmentShader, - blending: NoBlending - }); - this.ssaoMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.ssaoMaterial.uniforms['tNormal'].value = this.normalRenderTarget.texture; - this.ssaoMaterial.uniforms['tDepth'].value = this.normalRenderTarget.depthTexture; - this.ssaoMaterial.uniforms['tNoise'].value = this.noiseTexture; - this.ssaoMaterial.uniforms['kernel'].value = this.kernel; - this.ssaoMaterial.uniforms['cameraNear'].value = this.camera.near; - this.ssaoMaterial.uniforms['cameraFar'].value = this.camera.far; - this.ssaoMaterial.uniforms['resolution'].value.set(this.width, this.height); - this.ssaoMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssaoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); // normal material - - this.normalMaterial = new MeshNormalMaterial(); - this.normalMaterial.blending = NoBlending; // blur material - - this.blurMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSAOBlurShader.defines), - uniforms: UniformsUtils.clone(SSAOBlurShader.uniforms), - vertexShader: SSAOBlurShader.vertexShader, - fragmentShader: SSAOBlurShader.fragmentShader - }); - this.blurMaterial.uniforms['tDiffuse'].value = this.ssaoRenderTarget.texture; - this.blurMaterial.uniforms['resolution'].value.set(this.width, this.height); // material for rendering the depth - - this.depthRenderMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSAODepthShader.defines), - uniforms: UniformsUtils.clone(SSAODepthShader.uniforms), - vertexShader: SSAODepthShader.vertexShader, - fragmentShader: SSAODepthShader.fragmentShader, - blending: NoBlending - }); - this.depthRenderMaterial.uniforms['tDepth'].value = this.normalRenderTarget.depthTexture; - this.depthRenderMaterial.uniforms['cameraNear'].value = this.camera.near; - this.depthRenderMaterial.uniforms['cameraFar'].value = this.camera.far; // material for rendering the content of a render target - - this.copyMaterial = new ShaderMaterial({ - uniforms: UniformsUtils.clone(CopyShader.uniforms), - vertexShader: CopyShader.vertexShader, - fragmentShader: CopyShader.fragmentShader, - transparent: true, - depthTest: false, - depthWrite: false, - blendSrc: DstColorFactor, - blendDst: ZeroFactor, - blendEquation: AddEquation, - blendSrcAlpha: DstAlphaFactor, - blendDstAlpha: ZeroFactor, - blendEquationAlpha: AddEquation - }); - this.fsQuad = new FullScreenQuad(null); - this.originalClearColor = new Color(); - } + do { + switch (node.tag) { + case HostRoot: + return node.stateNode.context; - dispose() { - // dispose render targets - this.beautyRenderTarget.dispose(); - this.normalRenderTarget.dispose(); - this.ssaoRenderTarget.dispose(); - this.blurRenderTarget.dispose(); // dispose materials + case ClassComponent: + { + var Component = node.type; - this.normalMaterial.dispose(); - this.blurMaterial.dispose(); - this.copyMaterial.dispose(); - this.depthRenderMaterial.dispose(); // dipsose full screen quad + if (isContextProvider(Component)) { + return node.stateNode.__reactInternalMemoizedMergedChildContext; + } - this.fsQuad.dispose(); - } + break; + } + } - render(renderer, writeBuffer - /*, readBuffer, deltaTime, maskActive */ - ) { - if (renderer.capabilities.isWebGL2 === false) this.noiseTexture.format = LuminanceFormat; // render beauty + node = node.return; + } while (node !== null); - renderer.setRenderTarget(this.beautyRenderTarget); - renderer.clear(); - renderer.render(this.scene, this.camera); // render normals and depth (honor only meshes, points and lines do not contribute to SSAO) + throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } + } - this.overrideVisibility(); - this.renderOverride(renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0); - this.restoreVisibility(); // render SSAO + var LegacyRoot = 0; + var ConcurrentRoot = 1; - this.ssaoMaterial.uniforms['kernelRadius'].value = this.kernelRadius; - this.ssaoMaterial.uniforms['minDistance'].value = this.minDistance; - this.ssaoMaterial.uniforms['maxDistance'].value = this.maxDistance; - this.renderPass(renderer, this.ssaoMaterial, this.ssaoRenderTarget); // render blur + var NoMode = + /* */ + 0; // TODO: Remove ConcurrentMode by reading from the root tag instead - this.renderPass(renderer, this.blurMaterial, this.blurRenderTarget); // output result to screen + var ConcurrentMode = + /* */ + 1; + var ProfileMode = + /* */ + 2; + var StrictLegacyMode = + /* */ + 8; + var StrictEffectsMode = + /* */ + 16; - switch (this.output) { - case SSAOPass.OUTPUT.SSAO: - this.copyMaterial.uniforms['tDiffuse'].value = this.ssaoRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + // TODO: This is pretty well supported by browsers. Maybe we can drop it. + var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. + // Based on: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 - case SSAOPass.OUTPUT.Blur: - this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + var log = Math.log; + var LN2 = Math.LN2; - case SSAOPass.OUTPUT.Beauty: - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + function clz32Fallback(x) { + var asUint = x >>> 0; - case SSAOPass.OUTPUT.Depth: - this.renderPass(renderer, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); - break; + if (asUint === 0) { + return 32; + } - case SSAOPass.OUTPUT.Normal: - this.copyMaterial.uniforms['tDiffuse'].value = this.normalRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + return 31 - (log(asUint) / LN2 | 0) | 0; + } - case SSAOPass.OUTPUT.Default: - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget.texture; - this.copyMaterial.blending = CustomBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + // If those values are changed that package should be rebuilt and redeployed. - default: - console.warn('THREE.SSAOPass: Unknown output type.'); - } - } + var TotalLanes = 31; + var NoLanes = + /* */ + 0; + var NoLane = + /* */ + 0; + var SyncLane = + /* */ + 1; + var InputContinuousHydrationLane = + /* */ + 2; + var InputContinuousLane = + /* */ + 4; + var DefaultHydrationLane = + /* */ + 8; + var DefaultLane = + /* */ + 16; + var TransitionHydrationLane = + /* */ + 32; + var TransitionLanes = + /* */ + 4194240; + var TransitionLane1 = + /* */ + 64; + var TransitionLane2 = + /* */ + 128; + var TransitionLane3 = + /* */ + 256; + var TransitionLane4 = + /* */ + 512; + var TransitionLane5 = + /* */ + 1024; + var TransitionLane6 = + /* */ + 2048; + var TransitionLane7 = + /* */ + 4096; + var TransitionLane8 = + /* */ + 8192; + var TransitionLane9 = + /* */ + 16384; + var TransitionLane10 = + /* */ + 32768; + var TransitionLane11 = + /* */ + 65536; + var TransitionLane12 = + /* */ + 131072; + var TransitionLane13 = + /* */ + 262144; + var TransitionLane14 = + /* */ + 524288; + var TransitionLane15 = + /* */ + 1048576; + var TransitionLane16 = + /* */ + 2097152; + var RetryLanes = + /* */ + 130023424; + var RetryLane1 = + /* */ + 4194304; + var RetryLane2 = + /* */ + 8388608; + var RetryLane3 = + /* */ + 16777216; + var RetryLane4 = + /* */ + 33554432; + var RetryLane5 = + /* */ + 67108864; + var SomeRetryLane = RetryLane1; + var SelectiveHydrationLane = + /* */ + 134217728; + var NonIdleLanes = + /* */ + 268435455; + var IdleHydrationLane = + /* */ + 268435456; + var IdleLane = + /* */ + 536870912; + var OffscreenLane = + /* */ + 1073741824; // This function is used for the experimental timeline (react-devtools-timeline) + // It should be kept in sync with the Lanes values above. - renderPass(renderer, passMaterial, renderTarget, clearColor, clearAlpha) { - // save original state - renderer.getClearColor(this.originalClearColor); - const originalClearAlpha = renderer.getClearAlpha(); - const originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); // setup pass state + function getLabelForLane(lane) { + { + if (lane & SyncLane) { + return 'Sync'; + } - renderer.autoClear = false; + if (lane & InputContinuousHydrationLane) { + return 'InputContinuousHydration'; + } - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + if (lane & InputContinuousLane) { + return 'InputContinuous'; + } - this.fsQuad.material = passMaterial; - this.fsQuad.render(renderer); // restore original state + if (lane & DefaultHydrationLane) { + return 'DefaultHydration'; + } - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - } + if (lane & DefaultLane) { + return 'Default'; + } - renderOverride(renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { - renderer.getClearColor(this.originalClearColor); - const originalClearAlpha = renderer.getClearAlpha(); - const originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); - renderer.autoClear = false; - clearColor = overrideMaterial.clearColor || clearColor; - clearAlpha = overrideMaterial.clearAlpha || clearAlpha; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + if (lane & TransitionHydrationLane) { + return 'TransitionHydration'; + } - this.scene.overrideMaterial = overrideMaterial; - renderer.render(this.scene, this.camera); - this.scene.overrideMaterial = null; // restore original state + if (lane & TransitionLanes) { + return 'Transition'; + } - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - } + if (lane & RetryLanes) { + return 'Retry'; + } - setSize(width, height) { - this.width = width; - this.height = height; - this.beautyRenderTarget.setSize(width, height); - this.ssaoRenderTarget.setSize(width, height); - this.normalRenderTarget.setSize(width, height); - this.blurRenderTarget.setSize(width, height); - this.ssaoMaterial.uniforms['resolution'].value.set(width, height); - this.ssaoMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssaoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - this.blurMaterial.uniforms['resolution'].value.set(width, height); - } - - generateSampleKernel() { - const kernelSize = this.kernelSize; - const kernel = this.kernel; - - for (let i = 0; i < kernelSize; i++) { - const sample = new Vector3(); - sample.x = Math.random() * 2 - 1; - sample.y = Math.random() * 2 - 1; - sample.z = Math.random(); - sample.normalize(); - let scale = i / kernelSize; - scale = MathUtils.lerp(0.1, 1, scale * scale); - sample.multiplyScalar(scale); - kernel.push(sample); - } - } + if (lane & SelectiveHydrationLane) { + return 'SelectiveHydration'; + } - generateRandomKernelRotations() { - const width = 4, - height = 4; + if (lane & IdleHydrationLane) { + return 'IdleHydration'; + } - if (SimplexNoise === undefined) { - console.error('THREE.SSAOPass: The pass relies on SimplexNoise.'); - } + if (lane & IdleLane) { + return 'Idle'; + } - const simplex = new SimplexNoise(); - const size = width * height; - const data = new Float32Array(size); + if (lane & OffscreenLane) { + return 'Offscreen'; + } + } + } + var NoTimestamp = -1; + var nextTransitionLane = TransitionLane1; + var nextRetryLane = RetryLane1; - for (let i = 0; i < size; i++) { - const x = Math.random() * 2 - 1; - const y = Math.random() * 2 - 1; - const z = 0; - data[i] = simplex.noise3d(x, y, z); - } + function getHighestPriorityLanes(lanes) { + switch (getHighestPriorityLane(lanes)) { + case SyncLane: + return SyncLane; - this.noiseTexture = new DataTexture(data, width, height, RedFormat, FloatType); - this.noiseTexture.wrapS = RepeatWrapping; - this.noiseTexture.wrapT = RepeatWrapping; - this.noiseTexture.needsUpdate = true; - } + case InputContinuousHydrationLane: + return InputContinuousHydrationLane; - overrideVisibility() { - const scene = this.scene; - const cache = this._visibilityCache; - scene.traverse(function (object) { - cache.set(object, object.visible); - if (object.isPoints || object.isLine) object.visible = false; - }); - } + case InputContinuousLane: + return InputContinuousLane; - restoreVisibility() { - const scene = this.scene; - const cache = this._visibilityCache; - scene.traverse(function (object) { - const visible = cache.get(object); - object.visible = visible; - }); - cache.clear(); - } + case DefaultHydrationLane: + return DefaultHydrationLane; -} + case DefaultLane: + return DefaultLane; -SSAOPass.OUTPUT = { - Default: 0, - SSAO: 1, - Blur: 2, - Beauty: 3, - Depth: 4, - Normal: 5 -}; + case TransitionHydrationLane: + return TransitionHydrationLane; -var TexturePass = function (map, opacity) { - if (CopyShader === undefined) console.error('THREE.TexturePass relies on CopyShader'); - var shader = CopyShader; - this.map = map; - this.opacity = opacity !== undefined ? opacity : 1.0; - this.uniforms = UniformsUtils.clone(shader.uniforms); - this.material = new ShaderMaterial({ - uniforms: this.uniforms, - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - depthTest: false, - depthWrite: false - }); - this.needsSwap = false; - this.fsQuad = new FullScreenQuad(null); -}; + case TransitionLane1: + case TransitionLane2: + case TransitionLane3: + case TransitionLane4: + case TransitionLane5: + case TransitionLane6: + case TransitionLane7: + case TransitionLane8: + case TransitionLane9: + case TransitionLane10: + case TransitionLane11: + case TransitionLane12: + case TransitionLane13: + case TransitionLane14: + case TransitionLane15: + case TransitionLane16: + return lanes & TransitionLanes; -TexturePass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: TexturePass, - render: function (renderer, writeBuffer, readBuffer - /*, deltaTime, maskActive */ - ) { - var oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - this.fsQuad.material = this.material; - this.uniforms['opacity'].value = this.opacity; - this.uniforms['tDiffuse'].value = this.map; - this.material.transparent = this.opacity < 1.0; - renderer.setRenderTarget(this.renderToScreen ? null : readBuffer); - if (this.clear) renderer.clear(); - this.fsQuad.render(renderer); - renderer.autoClear = oldAutoClear; - } -}); + case RetryLane1: + case RetryLane2: + case RetryLane3: + case RetryLane4: + case RetryLane5: + return lanes & RetryLanes; -/** - * Luminosity - * http://en.wikipedia.org/wiki/Luminosity - */ -const LuminosityShader = { - uniforms: { - tDiffuse: { - value: null - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' float l = linearToRelativeLuminance( texel.rgb );', ' gl_FragColor = vec4( l, l, l, texel.w );', '}'].join('\n') -}; + case SelectiveHydrationLane: + return SelectiveHydrationLane; -/** - * Full-screen tone-mapping shader based on http://www.cis.rit.edu/people/faculty/ferwerda/publications/sig02_paper.pdf - */ -const ToneMapShader = { - uniforms: { - tDiffuse: { - value: null - }, - averageLuminance: { - value: 1.0 - }, - luminanceMap: { - value: null - }, - maxLuminance: { - value: 16.0 - }, - minLuminance: { - value: 0.01 - }, - middleGrey: { - value: 0.6 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'uniform float middleGrey;', 'uniform float minLuminance;', 'uniform float maxLuminance;', '#ifdef ADAPTED_LUMINANCE', ' uniform sampler2D luminanceMap;', '#else', ' uniform float averageLuminance;', '#endif', 'vec3 ToneMap( vec3 vColor ) {', ' #ifdef ADAPTED_LUMINANCE', // Get the calculated average luminance - ' float fLumAvg = texture2D(luminanceMap, vec2(0.5, 0.5)).r;', ' #else', ' float fLumAvg = averageLuminance;', ' #endif', // Calculate the luminance of the current pixel - ' float fLumPixel = linearToRelativeLuminance( vColor );', // Apply the modified operator (Eq. 4) - ' float fLumScaled = (fLumPixel * middleGrey) / max( minLuminance, fLumAvg );', ' float fLumCompressed = (fLumScaled * (1.0 + (fLumScaled / (maxLuminance * maxLuminance)))) / (1.0 + fLumScaled);', ' return fLumCompressed * vColor;', '}', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' gl_FragColor = vec4( ToneMap( texel.xyz ), texel.w );', '}'].join('\n') -}; + case IdleHydrationLane: + return IdleHydrationLane; -/** - * Generate a texture that represents the luminosity of the current scene, adapted over time - * to simulate the optic nerve responding to the amount of light it is receiving. - * Based on a GDC2007 presentation by Wolfgang Engel titled "Post-Processing Pipeline" - * - * Full-screen tone-mapping shader based on http://www.graphics.cornell.edu/~jaf/publications/sig02_paper.pdf - */ + case IdleLane: + return IdleLane; -var AdaptiveToneMappingPass = function (adaptive, resolution) { - this.resolution = resolution !== undefined ? resolution : 256; - this.needsInit = true; - this.adaptive = adaptive !== undefined ? !!adaptive : true; - this.luminanceRT = null; - this.previousLuminanceRT = null; - this.currentLuminanceRT = null; - if (CopyShader === undefined) console.error('THREE.AdaptiveToneMappingPass relies on CopyShader'); - var copyShader = CopyShader; - this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); - this.materialCopy = new ShaderMaterial({ - uniforms: this.copyUniforms, - vertexShader: copyShader.vertexShader, - fragmentShader: copyShader.fragmentShader, - blending: NoBlending, - depthTest: false - }); - if (LuminosityShader === undefined) console.error('THREE.AdaptiveToneMappingPass relies on LuminosityShader'); - this.materialLuminance = new ShaderMaterial({ - uniforms: UniformsUtils.clone(LuminosityShader.uniforms), - vertexShader: LuminosityShader.vertexShader, - fragmentShader: LuminosityShader.fragmentShader, - blending: NoBlending - }); - this.adaptLuminanceShader = { - defines: { - MIP_LEVEL_1X1: (Math.log(this.resolution) / Math.log(2.0)).toFixed(1) - }, - uniforms: { - lastLum: { - value: null - }, - currentLum: { - value: null - }, - minLuminance: { - value: 0.01 - }, - delta: { - value: 0.016 - }, - tau: { - value: 1.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['varying vec2 vUv;', 'uniform sampler2D lastLum;', 'uniform sampler2D currentLum;', 'uniform float minLuminance;', 'uniform float delta;', 'uniform float tau;', 'void main() {', ' vec4 lastLum = texture2D( lastLum, vUv, MIP_LEVEL_1X1 );', ' vec4 currentLum = texture2D( currentLum, vUv, MIP_LEVEL_1X1 );', ' float fLastLum = max( minLuminance, lastLum.r );', ' float fCurrentLum = max( minLuminance, currentLum.r );', //The adaption seems to work better in extreme lighting differences - //if the input luminance is squared. - ' fCurrentLum *= fCurrentLum;', // Adapt the luminance using Pattanaik's technique - ' float fAdaptedLum = fLastLum + (fCurrentLum - fLastLum) * (1.0 - exp(-delta * tau));', // "fAdaptedLum = sqrt(fAdaptedLum);", - ' gl_FragColor.r = fAdaptedLum;', '}'].join('\n') - }; - this.materialAdaptiveLum = new ShaderMaterial({ - uniforms: UniformsUtils.clone(this.adaptLuminanceShader.uniforms), - vertexShader: this.adaptLuminanceShader.vertexShader, - fragmentShader: this.adaptLuminanceShader.fragmentShader, - defines: Object.assign({}, this.adaptLuminanceShader.defines), - blending: NoBlending - }); - if (ToneMapShader === undefined) console.error('THREE.AdaptiveToneMappingPass relies on ToneMapShader'); - this.materialToneMap = new ShaderMaterial({ - uniforms: UniformsUtils.clone(ToneMapShader.uniforms), - vertexShader: ToneMapShader.vertexShader, - fragmentShader: ToneMapShader.fragmentShader, - blending: NoBlending - }); - this.fsQuad = new FullScreenQuad(null); -}; + case OffscreenLane: + return OffscreenLane; -AdaptiveToneMappingPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: AdaptiveToneMappingPass, - render: function (renderer, writeBuffer, readBuffer, deltaTime - /*, maskActive*/ - ) { - if (this.needsInit) { - this.reset(renderer); - this.luminanceRT.texture.type = readBuffer.texture.type; - this.previousLuminanceRT.texture.type = readBuffer.texture.type; - this.currentLuminanceRT.texture.type = readBuffer.texture.type; - this.needsInit = false; - } + default: + { + error('Should have found matching lanes. This is a bug in React.'); + } // This shouldn't be reachable, but as a fallback, return the entire bitmask. - if (this.adaptive) { - //Render the luminance of the current scene into a render target with mipmapping enabled - this.fsQuad.material = this.materialLuminance; - this.materialLuminance.uniforms.tDiffuse.value = readBuffer.texture; - renderer.setRenderTarget(this.currentLuminanceRT); - this.fsQuad.render(renderer); //Use the new luminance values, the previous luminance and the frame delta to - //adapt the luminance over time. - - this.fsQuad.material = this.materialAdaptiveLum; - this.materialAdaptiveLum.uniforms.delta.value = deltaTime; - this.materialAdaptiveLum.uniforms.lastLum.value = this.previousLuminanceRT.texture; - this.materialAdaptiveLum.uniforms.currentLum.value = this.currentLuminanceRT.texture; - renderer.setRenderTarget(this.luminanceRT); - this.fsQuad.render(renderer); //Copy the new adapted luminance value so that it can be used by the next frame. - - this.fsQuad.material = this.materialCopy; - this.copyUniforms.tDiffuse.value = this.luminanceRT.texture; - renderer.setRenderTarget(this.previousLuminanceRT); - this.fsQuad.render(renderer); - } - this.fsQuad.material = this.materialToneMap; - this.materialToneMap.uniforms.tDiffuse.value = readBuffer.texture; + return lanes; + } + } - if (this.renderToScreen) { - renderer.setRenderTarget(null); - this.fsQuad.render(renderer); - } else { - renderer.setRenderTarget(writeBuffer); - if (this.clear) renderer.clear(); - this.fsQuad.render(renderer); - } - }, - reset: function () { - // render targets - if (this.luminanceRT) { - this.luminanceRT.dispose(); - } + function getNextLanes(root, wipLanes) { + // Early bailout if there's no pending work left. + var pendingLanes = root.pendingLanes; - if (this.currentLuminanceRT) { - this.currentLuminanceRT.dispose(); - } + if (pendingLanes === NoLanes) { + return NoLanes; + } - if (this.previousLuminanceRT) { - this.previousLuminanceRT.dispose(); - } + var nextLanes = NoLanes; + var suspendedLanes = root.suspendedLanes; + var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished, + // even if the work is suspended. - var pars = { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }; // was RGB format. changed to RGBA format. see discussion in #8415 / #8450 + var nonIdlePendingLanes = pendingLanes & NonIdleLanes; - this.luminanceRT = new WebGLRenderTarget(this.resolution, this.resolution, pars); - this.luminanceRT.texture.name = 'AdaptiveToneMappingPass.l'; - this.luminanceRT.texture.generateMipmaps = false; - this.previousLuminanceRT = new WebGLRenderTarget(this.resolution, this.resolution, pars); - this.previousLuminanceRT.texture.name = 'AdaptiveToneMappingPass.pl'; - this.previousLuminanceRT.texture.generateMipmaps = false; // We only need mipmapping for the current luminosity because we want a down-sampled version to sample in our adaptive shader + if (nonIdlePendingLanes !== NoLanes) { + var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; - pars.minFilter = LinearMipmapLinearFilter; - pars.generateMipmaps = true; - this.currentLuminanceRT = new WebGLRenderTarget(this.resolution, this.resolution, pars); - this.currentLuminanceRT.texture.name = 'AdaptiveToneMappingPass.cl'; + if (nonIdleUnblockedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); + } else { + var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; - if (this.adaptive) { - this.materialToneMap.defines['ADAPTED_LUMINANCE'] = ''; - this.materialToneMap.uniforms.luminanceMap.value = this.luminanceRT.texture; - } //Put something in the adaptive luminance texture so that the scene can render initially + if (nonIdlePingedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); + } + } + } else { + // The only remaining work is Idle. + var unblockedLanes = pendingLanes & ~suspendedLanes; + if (unblockedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(unblockedLanes); + } else { + if (pingedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(pingedLanes); + } + } + } - this.fsQuad.material = new MeshBasicMaterial({ - color: 0x777777 - }); - this.materialLuminance.needsUpdate = true; - this.materialAdaptiveLum.needsUpdate = true; - this.materialToneMap.needsUpdate = true; // renderer.render( this.scene, this.camera, this.luminanceRT ); - // renderer.render( this.scene, this.camera, this.previousLuminanceRT ); - // renderer.render( this.scene, this.camera, this.currentLuminanceRT ); - }, - setAdaptive: function (adaptive) { - if (adaptive) { - this.adaptive = true; - this.materialToneMap.defines['ADAPTED_LUMINANCE'] = ''; - this.materialToneMap.uniforms.luminanceMap.value = this.luminanceRT.texture; - } else { - this.adaptive = false; - delete this.materialToneMap.defines['ADAPTED_LUMINANCE']; - this.materialToneMap.uniforms.luminanceMap.value = null; - } + if (nextLanes === NoLanes) { + // This should only be reachable if we're suspended + // TODO: Consider warning in this path if a fallback timer is not scheduled. + return NoLanes; + } // If we're already in the middle of a render, switching lanes will interrupt + // it and we'll lose our progress. We should only do this if the new lanes are + // higher priority. - this.materialToneMap.needsUpdate = true; - }, - setAdaptionRate: function (rate) { - if (rate) { - this.materialAdaptiveLum.uniforms.tau.value = Math.abs(rate); - } - }, - setMinLuminance: function (minLum) { - if (minLum) { - this.materialToneMap.uniforms.minLuminance.value = minLum; - this.materialAdaptiveLum.uniforms.minLuminance.value = minLum; - } - }, - setMaxLuminance: function (maxLum) { - if (maxLum) { - this.materialToneMap.uniforms.maxLuminance.value = maxLum; - } - }, - setAverageLuminance: function (avgLum) { - if (avgLum) { - this.materialToneMap.uniforms.averageLuminance.value = avgLum; - } - }, - setMiddleGrey: function (middleGrey) { - if (middleGrey) { - this.materialToneMap.uniforms.middleGrey.value = middleGrey; - } - }, - dispose: function () { - if (this.luminanceRT) { - this.luminanceRT.dispose(); - } - if (this.previousLuminanceRT) { - this.previousLuminanceRT.dispose(); - } + if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't + // bother waiting until the root is complete. + (wipLanes & suspendedLanes) === NoLanes) { + var nextLane = getHighestPriorityLane(nextLanes); + var wipLane = getHighestPriorityLane(wipLanes); - if (this.currentLuminanceRT) { - this.currentLuminanceRT.dispose(); - } + if ( // Tests whether the next lane is equal or lower priority than the wip + // one. This works because the bits decrease in priority as you go left. + nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The + // only difference between default updates and transition updates is that + // default updates do not support refresh transitions. + nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) { + // Keep working on the existing in-progress tree. Do not interrupt. + return wipLanes; + } + } - if (this.materialLuminance) { - this.materialLuminance.dispose(); - } + if ((nextLanes & InputContinuousLane) !== NoLanes) { + // When updates are sync by default, we entangle continuous priority updates + // and default updates, so they render in the same batch. The only reason + // they use separate lanes is because continuous updates should interrupt + // transitions, but default updates should not. + nextLanes |= pendingLanes & DefaultLane; + } // Check for entangled lanes and add them to the batch. + // + // A lane is said to be entangled with another when it's not allowed to render + // in a batch that does not also include the other lane. Typically we do this + // when multiple updates have the same source, and we only want to respond to + // the most recent event from that source. + // + // Note that we apply entanglements *after* checking for partial work above. + // This means that if a lane is entangled during an interleaved event while + // it's already rendering, we won't interrupt it. This is intentional, since + // entanglement is usually "best effort": we'll try our best to render the + // lanes in the same batch, but it's not worth throwing out partially + // completed work in order to do it. + // TODO: Reconsider this. The counter-argument is that the partial work + // represents an intermediate state, which we don't want to show to the user. + // And by spending extra time finishing it, we're increasing the amount of + // time it takes to show the final state, which is what they are actually + // waiting for. + // + // For those exceptions where entanglement is semantically important, like + // useMutableSource, we should ensure that there is no partial work at the + // time we apply the entanglement. - if (this.materialAdaptiveLum) { - this.materialAdaptiveLum.dispose(); - } - if (this.materialCopy) { - this.materialCopy.dispose(); - } + var entangledLanes = root.entangledLanes; - if (this.materialToneMap) { - this.materialToneMap.dispose(); - } - } -}); + if (entangledLanes !== NoLanes) { + var entanglements = root.entanglements; + var lanes = nextLanes & entangledLanes; -/** - * Luminosity - * http://en.wikipedia.org/wiki/Luminosity - */ + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + nextLanes |= entanglements[index]; + lanes &= ~lane; + } + } -const LuminosityHighPassShader = { - shaderID: 'luminosityHighPass', - uniforms: { - tDiffuse: { - value: null - }, - luminosityThreshold: { - value: 1.0 - }, - smoothWidth: { - value: 1.0 - }, - defaultColor: { - value: new Color(0x000000) - }, - defaultOpacity: { - value: 0.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform vec3 defaultColor;', 'uniform float defaultOpacity;', 'uniform float luminosityThreshold;', 'uniform float smoothWidth;', 'varying vec2 vUv;', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' vec3 luma = vec3( 0.299, 0.587, 0.114 );', ' float v = dot( texel.xyz, luma );', ' vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );', ' float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );', ' gl_FragColor = mix( outputColor, texel, alpha );', '}'].join('\n') -}; + return nextLanes; + } + function getMostRecentEventTime(root, lanes) { + var eventTimes = root.eventTimes; + var mostRecentEventTime = NoTimestamp; -/** - * UnrealBloomPass is inspired by the bloom pass of Unreal Engine. It creates a - * mip map chain of bloom textures and blurs them with different radii. Because - * of the weighted combination of mips, and because larger blurs are done on - * higher mips, this effect provides good quality and performance. - * - * Reference: - * - https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/ - */ + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + var eventTime = eventTimes[index]; -var UnrealBloomPass = function (resolution, strength, radius, threshold) { - this.strength = strength !== undefined ? strength : 1; - this.radius = radius; - this.threshold = threshold; - this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); // create color only once here, reuse it later inside the render function + if (eventTime > mostRecentEventTime) { + mostRecentEventTime = eventTime; + } - this.clearColor = new Color(0, 0, 0); // render targets + lanes &= ~lane; + } - var pars = { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }; - this.renderTargetsHorizontal = []; - this.renderTargetsVertical = []; - this.nMips = 5; - var resx = Math.round(this.resolution.x / 2); - var resy = Math.round(this.resolution.y / 2); - this.renderTargetBright = new WebGLRenderTarget(resx, resy, pars); - this.renderTargetBright.texture.name = 'UnrealBloomPass.bright'; - this.renderTargetBright.texture.generateMipmaps = false; - - for (let i = 0; i < this.nMips; i++) { - var renderTargetHorizonal = new WebGLRenderTarget(resx, resy, pars); - renderTargetHorizonal.texture.name = 'UnrealBloomPass.h' + i; - renderTargetHorizonal.texture.generateMipmaps = false; - this.renderTargetsHorizontal.push(renderTargetHorizonal); - var renderTargetVertical = new WebGLRenderTarget(resx, resy, pars); - renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i; - renderTargetVertical.texture.generateMipmaps = false; - this.renderTargetsVertical.push(renderTargetVertical); - resx = Math.round(resx / 2); - resy = Math.round(resy / 2); - } // luminosity high pass material - - - if (LuminosityHighPassShader === undefined) console.error('THREE.UnrealBloomPass relies on LuminosityHighPassShader'); - var highPassShader = LuminosityHighPassShader; - this.highPassUniforms = UniformsUtils.clone(highPassShader.uniforms); - this.highPassUniforms['luminosityThreshold'].value = threshold; - this.highPassUniforms['smoothWidth'].value = 0.01; - this.materialHighPassFilter = new ShaderMaterial({ - uniforms: this.highPassUniforms, - vertexShader: highPassShader.vertexShader, - fragmentShader: highPassShader.fragmentShader, - defines: {} - }); // Gaussian Blur Materials - - this.separableBlurMaterials = []; - var kernelSizeArray = [3, 5, 7, 9, 11]; - var resx = Math.round(this.resolution.x / 2); - var resy = Math.round(this.resolution.y / 2); - - for (let i = 0; i < this.nMips; i++) { - this.separableBlurMaterials.push(this.getSeperableBlurMaterial(kernelSizeArray[i])); - this.separableBlurMaterials[i].uniforms['texSize'].value = new Vector2(resx, resy); - resx = Math.round(resx / 2); - resy = Math.round(resy / 2); - } // Composite material - - - this.compositeMaterial = this.getCompositeMaterial(this.nMips); - this.compositeMaterial.uniforms['blurTexture1'].value = this.renderTargetsVertical[0].texture; - this.compositeMaterial.uniforms['blurTexture2'].value = this.renderTargetsVertical[1].texture; - this.compositeMaterial.uniforms['blurTexture3'].value = this.renderTargetsVertical[2].texture; - this.compositeMaterial.uniforms['blurTexture4'].value = this.renderTargetsVertical[3].texture; - this.compositeMaterial.uniforms['blurTexture5'].value = this.renderTargetsVertical[4].texture; - this.compositeMaterial.uniforms['bloomStrength'].value = strength; - this.compositeMaterial.uniforms['bloomRadius'].value = 0.1; - this.compositeMaterial.needsUpdate = true; - var bloomFactors = [1.0, 0.8, 0.6, 0.4, 0.2]; - this.compositeMaterial.uniforms['bloomFactors'].value = bloomFactors; - this.bloomTintColors = [new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1)]; - this.compositeMaterial.uniforms['bloomTintColors'].value = this.bloomTintColors; // copy material - - if (CopyShader === undefined) { - console.error('THREE.UnrealBloomPass relies on CopyShader'); - } - - var copyShader = CopyShader; - this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); - this.copyUniforms['opacity'].value = 1.0; - this.materialCopy = new ShaderMaterial({ - uniforms: this.copyUniforms, - vertexShader: copyShader.vertexShader, - fragmentShader: copyShader.fragmentShader, - blending: AdditiveBlending, - depthTest: false, - depthWrite: false, - transparent: true - }); - this.enabled = true; - this.needsSwap = false; - this._oldClearColor = new Color(); - this.oldClearAlpha = 1; - this.basic = new MeshBasicMaterial(); - this.fsQuad = new FullScreenQuad(null); -}; + return mostRecentEventTime; + } -UnrealBloomPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: UnrealBloomPass, - dispose: function () { - for (let i = 0; i < this.renderTargetsHorizontal.length; i++) { - this.renderTargetsHorizontal[i].dispose(); - } + function computeExpirationTime(lane, currentTime) { + switch (lane) { + case SyncLane: + case InputContinuousHydrationLane: + case InputContinuousLane: + // User interactions should expire slightly more quickly. + // + // NOTE: This is set to the corresponding constant as in Scheduler.js. + // When we made it larger, a product metric in www regressed, suggesting + // there's a user interaction that's being starved by a series of + // synchronous updates. If that theory is correct, the proper solution is + // to fix the starvation. However, this scenario supports the idea that + // expiration times are an important safeguard when starvation + // does happen. + return currentTime + 250; - for (let i = 0; i < this.renderTargetsVertical.length; i++) { - this.renderTargetsVertical[i].dispose(); - } + case DefaultHydrationLane: + case DefaultLane: + case TransitionHydrationLane: + case TransitionLane1: + case TransitionLane2: + case TransitionLane3: + case TransitionLane4: + case TransitionLane5: + case TransitionLane6: + case TransitionLane7: + case TransitionLane8: + case TransitionLane9: + case TransitionLane10: + case TransitionLane11: + case TransitionLane12: + case TransitionLane13: + case TransitionLane14: + case TransitionLane15: + case TransitionLane16: + return currentTime + 5000; - this.renderTargetBright.dispose(); - }, - setSize: function (width, height) { - var resx = Math.round(width / 2); - var resy = Math.round(height / 2); - this.renderTargetBright.setSize(resx, resy); - - for (let i = 0; i < this.nMips; i++) { - this.renderTargetsHorizontal[i].setSize(resx, resy); - this.renderTargetsVertical[i].setSize(resx, resy); - this.separableBlurMaterials[i].uniforms['texSize'].value = new Vector2(resx, resy); - resx = Math.round(resx / 2); - resy = Math.round(resy / 2); - } - }, - render: function (renderer, writeBuffer, readBuffer, deltaTime, maskActive) { - renderer.getClearColor(this._oldClearColor); - this.oldClearAlpha = renderer.getClearAlpha(); - var oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - renderer.setClearColor(this.clearColor, 0); - if (maskActive) renderer.state.buffers.stencil.setTest(false); // Render input to screen + case RetryLane1: + case RetryLane2: + case RetryLane3: + case RetryLane4: + case RetryLane5: + // TODO: Retries should be allowed to expire if they are CPU bound for + // too long, but when I made this change it caused a spike in browser + // crashes. There must be some other underlying bug; not super urgent but + // ideally should figure out why and fix it. Unfortunately we don't have + // a repro for the crashes, only detected via production metrics. + return NoTimestamp; - if (this.renderToScreen) { - this.fsQuad.material = this.basic; - this.basic.map = readBuffer.texture; - renderer.setRenderTarget(null); - renderer.clear(); - this.fsQuad.render(renderer); - } // 1. Extract Bright Areas - - - this.highPassUniforms['tDiffuse'].value = readBuffer.texture; - this.highPassUniforms['luminosityThreshold'].value = this.threshold; - this.fsQuad.material = this.materialHighPassFilter; - renderer.setRenderTarget(this.renderTargetBright); - renderer.clear(); - this.fsQuad.render(renderer); // 2. Blur All the mips progressively - - var inputRenderTarget = this.renderTargetBright; - - for (let i = 0; i < this.nMips; i++) { - this.fsQuad.material = this.separableBlurMaterials[i]; - this.separableBlurMaterials[i].uniforms['colorTexture'].value = inputRenderTarget.texture; - this.separableBlurMaterials[i].uniforms['direction'].value = UnrealBloomPass.BlurDirectionX; - renderer.setRenderTarget(this.renderTargetsHorizontal[i]); - renderer.clear(); - this.fsQuad.render(renderer); - this.separableBlurMaterials[i].uniforms['colorTexture'].value = this.renderTargetsHorizontal[i].texture; - this.separableBlurMaterials[i].uniforms['direction'].value = UnrealBloomPass.BlurDirectionY; - renderer.setRenderTarget(this.renderTargetsVertical[i]); - renderer.clear(); - this.fsQuad.render(renderer); - inputRenderTarget = this.renderTargetsVertical[i]; - } // Composite All the mips - - - this.fsQuad.material = this.compositeMaterial; - this.compositeMaterial.uniforms['bloomStrength'].value = this.strength; - this.compositeMaterial.uniforms['bloomRadius'].value = this.radius; - this.compositeMaterial.uniforms['bloomTintColors'].value = this.bloomTintColors; - renderer.setRenderTarget(this.renderTargetsHorizontal[0]); - renderer.clear(); - this.fsQuad.render(renderer); // Blend it additively over the input texture - - this.fsQuad.material = this.materialCopy; - this.copyUniforms['tDiffuse'].value = this.renderTargetsHorizontal[0].texture; - if (maskActive) renderer.state.buffers.stencil.setTest(true); + case SelectiveHydrationLane: + case IdleHydrationLane: + case IdleLane: + case OffscreenLane: + // Anything idle priority or lower should never expire. + return NoTimestamp; - if (this.renderToScreen) { - renderer.setRenderTarget(null); - this.fsQuad.render(renderer); - } else { - renderer.setRenderTarget(readBuffer); - this.fsQuad.render(renderer); - } // Restore renderer settings + default: + { + error('Should have found matching lanes. This is a bug in React.'); + } + return NoTimestamp; + } + } - renderer.setClearColor(this._oldClearColor, this.oldClearAlpha); - renderer.autoClear = oldAutoClear; - }, - getSeperableBlurMaterial: function (kernelRadius) { - return new ShaderMaterial({ - defines: { - KERNEL_RADIUS: kernelRadius, - SIGMA: kernelRadius - }, - uniforms: { - colorTexture: { - value: null - }, - texSize: { - value: new Vector2(0.5, 0.5) - }, - direction: { - value: new Vector2(0.5, 0.5) - } - }, - vertexShader: 'varying vec2 vUv;\n\ - void main() {\n\ - vUv = uv;\n\ - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\ - }', - fragmentShader: '#include \ - varying vec2 vUv;\n\ - uniform sampler2D colorTexture;\n\ - uniform vec2 texSize;\ - uniform vec2 direction;\ - \ - float gaussianPdf(in float x, in float sigma) {\ - return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\ - }\ - void main() {\n\ - vec2 invSize = 1.0 / texSize;\ - float fSigma = float(SIGMA);\ - float weightSum = gaussianPdf(0.0, fSigma);\ - vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\ - for( int i = 1; i < KERNEL_RADIUS; i ++ ) {\ - float x = float(i);\ - float w = gaussianPdf(x, fSigma);\ - vec2 uvOffset = direction * invSize * x;\ - vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\ - vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\ - diffuseSum += (sample1 + sample2) * w;\ - weightSum += 2.0 * w;\ - }\ - gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\n\ - }' - }); - }, - getCompositeMaterial: function (nMips) { - return new ShaderMaterial({ - defines: { - NUM_MIPS: nMips - }, - uniforms: { - blurTexture1: { - value: null - }, - blurTexture2: { - value: null - }, - blurTexture3: { - value: null - }, - blurTexture4: { - value: null - }, - blurTexture5: { - value: null - }, - dirtTexture: { - value: null - }, - bloomStrength: { - value: 1.0 - }, - bloomFactors: { - value: null - }, - bloomTintColors: { - value: null - }, - bloomRadius: { - value: 0.0 - } - }, - vertexShader: 'varying vec2 vUv;\n\ - void main() {\n\ - vUv = uv;\n\ - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\ - }', - fragmentShader: 'varying vec2 vUv;\ - uniform sampler2D blurTexture1;\ - uniform sampler2D blurTexture2;\ - uniform sampler2D blurTexture3;\ - uniform sampler2D blurTexture4;\ - uniform sampler2D blurTexture5;\ - uniform sampler2D dirtTexture;\ - uniform float bloomStrength;\ - uniform float bloomRadius;\ - uniform float bloomFactors[NUM_MIPS];\ - uniform vec3 bloomTintColors[NUM_MIPS];\ - \ - float lerpBloomFactor(const in float factor) { \ - float mirrorFactor = 1.2 - factor;\ - return mix(factor, mirrorFactor, bloomRadius);\ - }\ - \ - void main() {\ - gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + \ - lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + \ - lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + \ - lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + \ - lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );\ - }' - }); - } -}); -UnrealBloomPass.BlurDirectionX = new Vector2(1.0, 0.0); -UnrealBloomPass.BlurDirectionY = new Vector2(0.0, 1.0); - -var CubeTexturePass = function (camera, envMap, opacity) { - this.camera = camera; - this.needsSwap = false; - this.cubeShader = ShaderLib['cube']; - this.cubeMesh = new Mesh(new BoxGeometry(10, 10, 10), new ShaderMaterial({ - uniforms: UniformsUtils.clone(this.cubeShader.uniforms), - vertexShader: this.cubeShader.vertexShader, - fragmentShader: this.cubeShader.fragmentShader, - depthTest: false, - depthWrite: false, - side: BackSide - })); - Object.defineProperty(this.cubeMesh.material, 'envMap', { - get: function () { - return this.uniforms.envMap.value; - } - }); - this.envMap = envMap; - this.opacity = opacity !== undefined ? opacity : 1.0; - this.cubeScene = new Scene$1(); - this.cubeCamera = new PerspectiveCamera(); - this.cubeScene.add(this.cubeMesh); -}; + function markStarvedLanesAsExpired(root, currentTime) { + // TODO: This gets called every time we yield. We can optimize by storing + // the earliest expiration time on the root. Then use that to quickly bail out + // of this function. + var pendingLanes = root.pendingLanes; + var suspendedLanes = root.suspendedLanes; + var pingedLanes = root.pingedLanes; + var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their + // expiration time. If so, we'll assume the update is being starved and mark + // it as expired to force it to finish. -CubeTexturePass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: CubeTexturePass, - render: function (renderer, writeBuffer, readBuffer - /*, deltaTime, maskActive*/ - ) { - var oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - this.cubeCamera.projectionMatrix.copy(this.camera.projectionMatrix); - this.cubeCamera.quaternion.setFromRotationMatrix(this.camera.matrixWorld); - this.cubeMesh.material.uniforms.envMap.value = this.envMap; - this.cubeMesh.material.uniforms.flipEnvMap.value = this.envMap.isCubeTexture && this.envMap._needsFlipEnvMap ? -1 : 1; - this.cubeMesh.material.uniforms.opacity.value = this.opacity; - this.cubeMesh.material.transparent = this.opacity < 1.0; - renderer.setRenderTarget(this.renderToScreen ? null : readBuffer); - if (this.clear) renderer.clear(); - renderer.render(this.cubeScene, this.cubeCamera); - renderer.autoClear = oldAutoClear; - } -}); + var lanes = pendingLanes; -const SAOShader = { - defines: { - NUM_SAMPLES: 7, - NUM_RINGS: 4, - NORMAL_TEXTURE: 0, - DIFFUSE_TEXTURE: 0, - DEPTH_PACKING: 1, - PERSPECTIVE_CAMERA: 1 - }, - uniforms: { - tDepth: { - value: null - }, - tDiffuse: { - value: null - }, - tNormal: { - value: null - }, - size: { - value: new Vector2(512, 512) - }, - cameraNear: { - value: 1 - }, - cameraFar: { - value: 100 - }, - cameraProjectionMatrix: { - value: new Matrix4() - }, - cameraInverseProjectionMatrix: { - value: new Matrix4() - }, - scale: { - value: 1.0 - }, - intensity: { - value: 0.1 - }, - bias: { - value: 0.5 - }, - minResolution: { - value: 0.0 - }, - kernelRadius: { - value: 100.0 - }, - randomSeed: { - value: 0.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', 'varying vec2 vUv;', '#if DIFFUSE_TEXTURE == 1', 'uniform sampler2D tDiffuse;', '#endif', 'uniform sampler2D tDepth;', '#if NORMAL_TEXTURE == 1', 'uniform sampler2D tNormal;', '#endif', 'uniform float cameraNear;', 'uniform float cameraFar;', 'uniform mat4 cameraProjectionMatrix;', 'uniform mat4 cameraInverseProjectionMatrix;', 'uniform float scale;', 'uniform float intensity;', 'uniform float bias;', 'uniform float kernelRadius;', 'uniform float minResolution;', 'uniform vec2 size;', 'uniform float randomSeed;', '// RGBA depth', '#include ', 'vec4 getDefaultColor( const in vec2 screenPosition ) {', ' #if DIFFUSE_TEXTURE == 1', ' return texture2D( tDiffuse, vUv );', ' #else', ' return vec4( 1.0 );', ' #endif', '}', 'float getDepth( const in vec2 screenPosition ) {', ' #if DEPTH_PACKING == 1', ' return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );', ' #else', ' return texture2D( tDepth, screenPosition ).x;', ' #endif', '}', 'float getViewZ( const in float depth ) {', ' #if PERSPECTIVE_CAMERA == 1', ' return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );', ' #else', ' return orthographicDepthToViewZ( depth, cameraNear, cameraFar );', ' #endif', '}', 'vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {', ' float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];', ' vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );', ' clipPosition *= clipW; // unprojection.', ' return ( cameraInverseProjectionMatrix * clipPosition ).xyz;', '}', 'vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) {', ' #if NORMAL_TEXTURE == 1', ' return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );', ' #else', ' return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );', ' #endif', '}', 'float scaleDividedByCameraFar;', 'float minResolutionMultipliedByCameraFar;', 'float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {', ' vec3 viewDelta = sampleViewPosition - centerViewPosition;', ' float viewDistance = length( viewDelta );', ' float scaledScreenDistance = scaleDividedByCameraFar * viewDistance;', ' return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) );', '}', '// moving costly divides into consts', 'const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );', 'const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );', 'float getAmbientOcclusion( const in vec3 centerViewPosition ) {', ' // precompute some variables require in getOcclusion.', ' scaleDividedByCameraFar = scale / cameraFar;', ' minResolutionMultipliedByCameraFar = minResolution * cameraFar;', ' vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv );', ' // jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/', ' float angle = rand( vUv + randomSeed ) * PI2;', ' vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size;', ' vec2 radiusStep = radius;', ' float occlusionSum = 0.0;', ' float weightSum = 0.0;', ' for( int i = 0; i < NUM_SAMPLES; i ++ ) {', ' vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius;', ' radius += radiusStep;', ' angle += ANGLE_STEP;', ' float sampleDepth = getDepth( sampleUv );', ' if( sampleDepth >= ( 1.0 - EPSILON ) ) {', ' continue;', ' }', ' float sampleViewZ = getViewZ( sampleDepth );', ' vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ );', ' occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );', ' weightSum += 1.0;', ' }', ' if( weightSum == 0.0 ) discard;', ' return occlusionSum * ( intensity / weightSum );', '}', 'void main() {', ' float centerDepth = getDepth( vUv );', ' if( centerDepth >= ( 1.0 - EPSILON ) ) {', ' discard;', ' }', ' float centerViewZ = getViewZ( centerDepth );', ' vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ );', ' float ambientOcclusion = getAmbientOcclusion( viewPosition );', ' gl_FragColor = getDefaultColor( vUv );', ' gl_FragColor.xyz *= 1.0 - ambientOcclusion;', '}'].join('\n') -}; + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + var expirationTime = expirationTimes[index]; -const DepthLimitedBlurShader = { - defines: { - KERNEL_RADIUS: 4, - DEPTH_PACKING: 1, - PERSPECTIVE_CAMERA: 1 - }, - uniforms: { - tDiffuse: { - value: null - }, - size: { - value: new Vector2(512, 512) - }, - sampleUvOffsets: { - value: [new Vector2(0, 0)] - }, - sampleWeights: { - value: [1.0] - }, - tDepth: { - value: null - }, - cameraNear: { - value: 10 - }, - cameraFar: { - value: 1000 - }, - depthCutoff: { - value: 10 - } - }, - vertexShader: ['#include ', 'uniform vec2 size;', 'varying vec2 vUv;', 'varying vec2 vInvSize;', 'void main() {', ' vUv = uv;', ' vInvSize = 1.0 / size;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', '#include ', 'uniform sampler2D tDiffuse;', 'uniform sampler2D tDepth;', 'uniform float cameraNear;', 'uniform float cameraFar;', 'uniform float depthCutoff;', 'uniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ];', 'uniform float sampleWeights[ KERNEL_RADIUS + 1 ];', 'varying vec2 vUv;', 'varying vec2 vInvSize;', 'float getDepth( const in vec2 screenPosition ) {', ' #if DEPTH_PACKING == 1', ' return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );', ' #else', ' return texture2D( tDepth, screenPosition ).x;', ' #endif', '}', 'float getViewZ( const in float depth ) {', ' #if PERSPECTIVE_CAMERA == 1', ' return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );', ' #else', ' return orthographicDepthToViewZ( depth, cameraNear, cameraFar );', ' #endif', '}', 'void main() {', ' float depth = getDepth( vUv );', ' if( depth >= ( 1.0 - EPSILON ) ) {', ' discard;', ' }', ' float centerViewZ = -getViewZ( depth );', ' bool rBreak = false, lBreak = false;', ' float weightSum = sampleWeights[0];', ' vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum;', ' for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {', ' float sampleWeight = sampleWeights[i];', ' vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize;', ' vec2 sampleUv = vUv + sampleUvOffset;', ' float viewZ = -getViewZ( getDepth( sampleUv ) );', ' if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true;', ' if( ! rBreak ) {', ' diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;', ' weightSum += sampleWeight;', ' }', ' sampleUv = vUv - sampleUvOffset;', ' viewZ = -getViewZ( getDepth( sampleUv ) );', ' if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true;', ' if( ! lBreak ) {', ' diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;', ' weightSum += sampleWeight;', ' }', ' }', ' gl_FragColor = diffuseSum / weightSum;', '}'].join('\n') -}; -const BlurShaderUtils = { - createSampleWeights: (kernelRadius, stdDev) => { - const gaussian = (x, stdDev) => { - return Math.exp(-(x * x) / (2.0 * (stdDev * stdDev))) / (Math.sqrt(2.0 * Math.PI) * stdDev); - }; + if (expirationTime === NoTimestamp) { + // Found a pending lane with no expiration time. If it's not suspended, or + // if it's pinged, assume it's CPU-bound. Compute a new expiration time + // using the current time. + if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) { + // Assumes timestamps are monotonically increasing. + expirationTimes[index] = computeExpirationTime(lane, currentTime); + } + } else if (expirationTime <= currentTime) { + // This lane expired + root.expiredLanes |= lane; + } - const weights = []; + lanes &= ~lane; + } + } // This returns the highest priority pending lanes regardless of whether they + // are suspended. - for (let i = 0; i <= kernelRadius; i++) { - weights.push(gaussian(i, stdDev)); - } + function getHighestPriorityPendingLanes(root) { + return getHighestPriorityLanes(root.pendingLanes); + } + function getLanesToRetrySynchronouslyOnError(root) { + var everythingButOffscreen = root.pendingLanes & ~OffscreenLane; - return weights; - }, - createSampleOffsets: (kernelRadius, uvIncrement) => { - const offsets = []; + if (everythingButOffscreen !== NoLanes) { + return everythingButOffscreen; + } - for (let i = 0; i <= kernelRadius; i++) { - offsets.push(uvIncrement.clone().multiplyScalar(i)); - } + if (everythingButOffscreen & OffscreenLane) { + return OffscreenLane; + } - return offsets; - }, - configure: (shader, kernelRadius, stdDev, uvIncrement) => { - shader.defines['KERNEL_RADIUS'] = kernelRadius; - shader.uniforms['sampleUvOffsets'].value = BlurShaderUtils.createSampleOffsets(kernelRadius, uvIncrement); - shader.uniforms['sampleWeights'].value = BlurShaderUtils.createSampleWeights(kernelRadius, stdDev); - shader.needsUpdate = true; - } -}; + return NoLanes; + } + function includesSyncLane(lanes) { + return (lanes & SyncLane) !== NoLanes; + } + function includesNonIdleWork(lanes) { + return (lanes & NonIdleLanes) !== NoLanes; + } + function includesOnlyRetries(lanes) { + return (lanes & RetryLanes) === lanes; + } + function includesOnlyTransitions(lanes) { + return (lanes & TransitionLanes) === lanes; + } + function includesBlockingLane(root, lanes) { -/** - * SAO implementation inspired from bhouston previous SAO work - */ + var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane; + return (lanes & SyncDefaultLanes) !== NoLanes; + } + function includesExpiredLane(root, lanes) { + // This is a separate check from includesBlockingLane because a lane can + // expire after a render has already started. + return (lanes & root.expiredLanes) !== NoLanes; + } + function isTransitionLane(lane) { + return (lane & TransitionLanes) !== 0; + } + function claimNextTransitionLane() { + // Cycle through the lanes, assigning each new transition to the next lane. + // In most cases, this means every transition gets its own lane, until we + // run out of lanes and cycle back to the beginning. + var lane = nextTransitionLane; + nextTransitionLane <<= 1; -var SAOPass = function (scene, camera, depthTexture, useNormals, resolution) { - this.scene = scene; - this.camera = camera; - this.clear = true; - this.needsSwap = false; - this.supportsDepthTextureExtension = depthTexture !== undefined ? depthTexture : false; - this.supportsNormalTexture = useNormals !== undefined ? useNormals : false; - this.originalClearColor = new Color(); - this._oldClearColor = new Color(); - this.oldClearAlpha = 1; - this.params = { - output: 0, - saoBias: 0.5, - saoIntensity: 0.18, - saoScale: 1, - saoKernelRadius: 100, - saoMinResolution: 0, - saoBlur: true, - saoBlurRadius: 8, - saoBlurStdDev: 4, - saoBlurDepthCutoff: 0.01 - }; - this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); - this.saoRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }); - this.blurIntermediateRenderTarget = this.saoRenderTarget.clone(); - this.beautyRenderTarget = this.saoRenderTarget.clone(); - this.normalRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { - minFilter: NearestFilter, - magFilter: NearestFilter, - format: RGBAFormat - }); - this.depthRenderTarget = this.normalRenderTarget.clone(); + if ((nextTransitionLane & TransitionLanes) === 0) { + nextTransitionLane = TransitionLane1; + } - if (this.supportsDepthTextureExtension) { - var depthTexture = new DepthTexture(); - depthTexture.type = UnsignedShortType; - this.beautyRenderTarget.depthTexture = depthTexture; - this.beautyRenderTarget.depthBuffer = true; - } + return lane; + } + function claimNextRetryLane() { + var lane = nextRetryLane; + nextRetryLane <<= 1; - this.depthMaterial = new MeshDepthMaterial(); - this.depthMaterial.depthPacking = RGBADepthPacking; - this.depthMaterial.blending = NoBlending; - this.normalMaterial = new MeshNormalMaterial(); - this.normalMaterial.blending = NoBlending; + if ((nextRetryLane & RetryLanes) === 0) { + nextRetryLane = RetryLane1; + } - if (SAOShader === undefined) { - console.error('THREE.SAOPass relies on SAOShader'); - } + return lane; + } + function getHighestPriorityLane(lanes) { + return lanes & -lanes; + } + function pickArbitraryLane(lanes) { + // This wrapper function gets inlined. Only exists so to communicate that it + // doesn't matter which bit is selected; you can pick any bit without + // affecting the algorithms where its used. Here I'm using + // getHighestPriorityLane because it requires the fewest operations. + return getHighestPriorityLane(lanes); + } - this.saoMaterial = new ShaderMaterial({ - defines: Object.assign({}, SAOShader.defines), - fragmentShader: SAOShader.fragmentShader, - vertexShader: SAOShader.vertexShader, - uniforms: UniformsUtils.clone(SAOShader.uniforms) - }); - this.saoMaterial.extensions.derivatives = true; - this.saoMaterial.defines['DEPTH_PACKING'] = this.supportsDepthTextureExtension ? 0 : 1; - this.saoMaterial.defines['NORMAL_TEXTURE'] = this.supportsNormalTexture ? 1 : 0; - this.saoMaterial.defines['PERSPECTIVE_CAMERA'] = this.camera.isPerspectiveCamera ? 1 : 0; - this.saoMaterial.uniforms['tDepth'].value = this.supportsDepthTextureExtension ? depthTexture : this.depthRenderTarget.texture; - this.saoMaterial.uniforms['tNormal'].value = this.normalRenderTarget.texture; - this.saoMaterial.uniforms['size'].value.set(this.resolution.x, this.resolution.y); - this.saoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - this.saoMaterial.uniforms['cameraProjectionMatrix'].value = this.camera.projectionMatrix; - this.saoMaterial.blending = NoBlending; - - if (DepthLimitedBlurShader === undefined) { - console.error('THREE.SAOPass relies on DepthLimitedBlurShader'); - } - - this.vBlurMaterial = new ShaderMaterial({ - uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), - defines: Object.assign({}, DepthLimitedBlurShader.defines), - vertexShader: DepthLimitedBlurShader.vertexShader, - fragmentShader: DepthLimitedBlurShader.fragmentShader - }); - this.vBlurMaterial.defines['DEPTH_PACKING'] = this.supportsDepthTextureExtension ? 0 : 1; - this.vBlurMaterial.defines['PERSPECTIVE_CAMERA'] = this.camera.isPerspectiveCamera ? 1 : 0; - this.vBlurMaterial.uniforms['tDiffuse'].value = this.saoRenderTarget.texture; - this.vBlurMaterial.uniforms['tDepth'].value = this.supportsDepthTextureExtension ? depthTexture : this.depthRenderTarget.texture; - this.vBlurMaterial.uniforms['size'].value.set(this.resolution.x, this.resolution.y); - this.vBlurMaterial.blending = NoBlending; - this.hBlurMaterial = new ShaderMaterial({ - uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), - defines: Object.assign({}, DepthLimitedBlurShader.defines), - vertexShader: DepthLimitedBlurShader.vertexShader, - fragmentShader: DepthLimitedBlurShader.fragmentShader - }); - this.hBlurMaterial.defines['DEPTH_PACKING'] = this.supportsDepthTextureExtension ? 0 : 1; - this.hBlurMaterial.defines['PERSPECTIVE_CAMERA'] = this.camera.isPerspectiveCamera ? 1 : 0; - this.hBlurMaterial.uniforms['tDiffuse'].value = this.blurIntermediateRenderTarget.texture; - this.hBlurMaterial.uniforms['tDepth'].value = this.supportsDepthTextureExtension ? depthTexture : this.depthRenderTarget.texture; - this.hBlurMaterial.uniforms['size'].value.set(this.resolution.x, this.resolution.y); - this.hBlurMaterial.blending = NoBlending; - - if (CopyShader === undefined) { - console.error('THREE.SAOPass relies on CopyShader'); - } - - this.materialCopy = new ShaderMaterial({ - uniforms: UniformsUtils.clone(CopyShader.uniforms), - vertexShader: CopyShader.vertexShader, - fragmentShader: CopyShader.fragmentShader, - blending: NoBlending - }); - this.materialCopy.transparent = true; - this.materialCopy.depthTest = false; - this.materialCopy.depthWrite = false; - this.materialCopy.blending = CustomBlending; - this.materialCopy.blendSrc = DstColorFactor; - this.materialCopy.blendDst = ZeroFactor; - this.materialCopy.blendEquation = AddEquation; - this.materialCopy.blendSrcAlpha = DstAlphaFactor; - this.materialCopy.blendDstAlpha = ZeroFactor; - this.materialCopy.blendEquationAlpha = AddEquation; - - if (UnpackDepthRGBAShader === undefined) { - console.error('THREE.SAOPass relies on UnpackDepthRGBAShader'); - } - - this.depthCopy = new ShaderMaterial({ - uniforms: UniformsUtils.clone(UnpackDepthRGBAShader.uniforms), - vertexShader: UnpackDepthRGBAShader.vertexShader, - fragmentShader: UnpackDepthRGBAShader.fragmentShader, - blending: NoBlending - }); - this.fsQuad = new FullScreenQuad(null); -}; + function pickArbitraryLaneIndex(lanes) { + return 31 - clz32(lanes); + } -SAOPass.OUTPUT = { - Beauty: 1, - Default: 0, - SAO: 2, - Depth: 3, - Normal: 4 -}; -SAOPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: SAOPass, - render: function (renderer, writeBuffer, readBuffer - /*, deltaTime, maskActive*/ - ) { - // Rendering readBuffer first when rendering to screen - if (this.renderToScreen) { - this.materialCopy.blending = NoBlending; - this.materialCopy.uniforms['tDiffuse'].value = readBuffer.texture; - this.materialCopy.needsUpdate = true; - this.renderPass(renderer, this.materialCopy, null); - } + function laneToIndex(lane) { + return pickArbitraryLaneIndex(lane); + } - if (this.params.output === 1) { - return; - } + function includesSomeLane(a, b) { + return (a & b) !== NoLanes; + } + function isSubsetOfLanes(set, subset) { + return (set & subset) === subset; + } + function mergeLanes(a, b) { + return a | b; + } + function removeLanes(set, subset) { + return set & ~subset; + } + function intersectLanes(a, b) { + return a & b; + } // Seems redundant, but it changes the type from a single lane (used for + // updates) to a group of lanes (used for flushing work). - renderer.getClearColor(this._oldClearColor); - this.oldClearAlpha = renderer.getClearAlpha(); - var oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - renderer.setRenderTarget(this.depthRenderTarget); - renderer.clear(); - this.saoMaterial.uniforms['bias'].value = this.params.saoBias; - this.saoMaterial.uniforms['intensity'].value = this.params.saoIntensity; - this.saoMaterial.uniforms['scale'].value = this.params.saoScale; - this.saoMaterial.uniforms['kernelRadius'].value = this.params.saoKernelRadius; - this.saoMaterial.uniforms['minResolution'].value = this.params.saoMinResolution; - this.saoMaterial.uniforms['cameraNear'].value = this.camera.near; - this.saoMaterial.uniforms['cameraFar'].value = this.camera.far; // this.saoMaterial.uniforms['randomSeed'].value = Math.random(); - - var depthCutoff = this.params.saoBlurDepthCutoff * (this.camera.far - this.camera.near); - this.vBlurMaterial.uniforms['depthCutoff'].value = depthCutoff; - this.hBlurMaterial.uniforms['depthCutoff'].value = depthCutoff; - this.vBlurMaterial.uniforms['cameraNear'].value = this.camera.near; - this.vBlurMaterial.uniforms['cameraFar'].value = this.camera.far; - this.hBlurMaterial.uniforms['cameraNear'].value = this.camera.near; - this.hBlurMaterial.uniforms['cameraFar'].value = this.camera.far; - this.params.saoBlurRadius = Math.floor(this.params.saoBlurRadius); - - if (this.prevStdDev !== this.params.saoBlurStdDev || this.prevNumSamples !== this.params.saoBlurRadius) { - BlurShaderUtils.configure(this.vBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(0, 1)); - BlurShaderUtils.configure(this.hBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(1, 0)); - this.prevStdDev = this.params.saoBlurStdDev; - this.prevNumSamples = this.params.saoBlurRadius; - } // Rendering scene to depth texture - - - renderer.setClearColor(0x000000); - renderer.setRenderTarget(this.beautyRenderTarget); - renderer.clear(); - renderer.render(this.scene, this.camera); // Re-render scene if depth texture extension is not supported - - if (!this.supportsDepthTextureExtension) { - // Clear rule : far clipping plane in both RGBA and Basic encoding - this.renderOverride(renderer, this.depthMaterial, this.depthRenderTarget, 0x000000, 1.0); - } + function laneToLanes(lane) { + return lane; + } + function higherPriorityLane(a, b) { + // This works because the bit ranges decrease in priority as you go left. + return a !== NoLane && a < b ? a : b; + } + function createLaneMap(initial) { + // Intentionally pushing one by one. + // https://v8.dev/blog/elements-kinds#avoid-creating-holes + var laneMap = []; - if (this.supportsNormalTexture) { - // Clear rule : default normal is facing the camera - this.renderOverride(renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0); - } // Rendering SAO texture + for (var i = 0; i < TotalLanes; i++) { + laneMap.push(initial); + } + return laneMap; + } + function markRootUpdated(root, updateLane, eventTime) { + root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update + // could unblock them. Clear the suspended lanes so that we can try rendering + // them again. + // + // TODO: We really only need to unsuspend only lanes that are in the + // `subtreeLanes` of the updated fiber, or the update lanes of the return + // path. This would exclude suspended updates in an unrelated sibling tree, + // since there's no way for this update to unblock it. + // + // We don't do this if the incoming update is idle, because we never process + // idle updates until after all the regular updates have finished; there's no + // way it could unblock a transition. - this.renderPass(renderer, this.saoMaterial, this.saoRenderTarget, 0xffffff, 1.0); // Blurring SAO texture + if (updateLane !== IdleLane) { + root.suspendedLanes = NoLanes; + root.pingedLanes = NoLanes; + } - if (this.params.saoBlur) { - this.renderPass(renderer, this.vBlurMaterial, this.blurIntermediateRenderTarget, 0xffffff, 1.0); - this.renderPass(renderer, this.hBlurMaterial, this.saoRenderTarget, 0xffffff, 1.0); - } + var eventTimes = root.eventTimes; + var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most + // recent event, and we assume time is monotonically increasing. - var outputMaterial = this.materialCopy; // Setting up SAO rendering + eventTimes[index] = eventTime; + } + function markRootSuspended(root, suspendedLanes) { + root.suspendedLanes |= suspendedLanes; + root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times. - if (this.params.output === 3) { - if (this.supportsDepthTextureExtension) { - this.materialCopy.uniforms['tDiffuse'].value = this.beautyRenderTarget.depthTexture; - this.materialCopy.needsUpdate = true; - } else { - this.depthCopy.uniforms['tDiffuse'].value = this.depthRenderTarget.texture; - this.depthCopy.needsUpdate = true; - outputMaterial = this.depthCopy; - } - } else if (this.params.output === 4) { - this.materialCopy.uniforms['tDiffuse'].value = this.normalRenderTarget.texture; - this.materialCopy.needsUpdate = true; - } else { - this.materialCopy.uniforms['tDiffuse'].value = this.saoRenderTarget.texture; - this.materialCopy.needsUpdate = true; - } // Blending depends on output, only want a CustomBlending when showing SAO + var expirationTimes = root.expirationTimes; + var lanes = suspendedLanes; + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + expirationTimes[index] = NoTimestamp; + lanes &= ~lane; + } + } + function markRootPinged(root, pingedLanes, eventTime) { + root.pingedLanes |= root.suspendedLanes & pingedLanes; + } + function markRootFinished(root, remainingLanes) { + var noLongerPendingLanes = root.pendingLanes & ~remainingLanes; + root.pendingLanes = remainingLanes; // Let's try everything again - if (this.params.output === 0) { - outputMaterial.blending = CustomBlending; - } else { - outputMaterial.blending = NoBlending; - } // Rendering SAOPass result on top of previous pass + root.suspendedLanes = 0; + root.pingedLanes = 0; + root.expiredLanes &= remainingLanes; + root.mutableReadLanes &= remainingLanes; + root.entangledLanes &= remainingLanes; + var entanglements = root.entanglements; + var eventTimes = root.eventTimes; + var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work + var lanes = noLongerPendingLanes; - this.renderPass(renderer, outputMaterial, this.renderToScreen ? null : readBuffer); - renderer.setClearColor(this._oldClearColor, this.oldClearAlpha); - renderer.autoClear = oldAutoClear; - }, - renderPass: function (renderer, passMaterial, renderTarget, clearColor, clearAlpha) { - // save original state - renderer.getClearColor(this.originalClearColor); - var originalClearAlpha = renderer.getClearAlpha(); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); // setup pass state - - renderer.autoClear = false; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + entanglements[index] = NoLanes; + eventTimes[index] = NoTimestamp; + expirationTimes[index] = NoTimestamp; + lanes &= ~lane; + } + } + function markRootEntangled(root, entangledLanes) { + // In addition to entangling each of the given lanes with each other, we also + // have to consider _transitive_ entanglements. For each lane that is already + // entangled with *any* of the given lanes, that lane is now transitively + // entangled with *all* the given lanes. + // + // Translated: If C is entangled with A, then entangling A with B also + // entangles C with B. + // + // If this is hard to grasp, it might help to intentionally break this + // function and look at the tests that fail in ReactTransition-test.js. Try + // commenting out one of the conditions below. + var rootEntangledLanes = root.entangledLanes |= entangledLanes; + var entanglements = root.entanglements; + var lanes = rootEntangledLanes; - this.fsQuad.material = passMaterial; - this.fsQuad.render(renderer); // restore original state + while (lanes) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - renderOverride: function (renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { - renderer.getClearColor(this.originalClearColor); - var originalClearAlpha = renderer.getClearAlpha(); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); - renderer.autoClear = false; - clearColor = overrideMaterial.clearColor || clearColor; - clearAlpha = overrideMaterial.clearAlpha || clearAlpha; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + if ( // Is this one of the newly entangled lanes? + lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes? + entanglements[index] & entangledLanes) { + entanglements[index] |= entangledLanes; + } - this.scene.overrideMaterial = overrideMaterial; - renderer.render(this.scene, this.camera); - this.scene.overrideMaterial = null; // restore original state + lanes &= ~lane; + } + } + function getBumpedLaneForHydration(root, renderLanes) { + var renderLane = getHighestPriorityLane(renderLanes); + var lane; - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - setSize: function (width, height) { - this.beautyRenderTarget.setSize(width, height); - this.saoRenderTarget.setSize(width, height); - this.blurIntermediateRenderTarget.setSize(width, height); - this.normalRenderTarget.setSize(width, height); - this.depthRenderTarget.setSize(width, height); - this.saoMaterial.uniforms['size'].value.set(width, height); - this.saoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - this.saoMaterial.uniforms['cameraProjectionMatrix'].value = this.camera.projectionMatrix; - this.saoMaterial.needsUpdate = true; - this.vBlurMaterial.uniforms['size'].value.set(width, height); - this.vBlurMaterial.needsUpdate = true; - this.hBlurMaterial.uniforms['size'].value.set(width, height); - this.hBlurMaterial.needsUpdate = true; - } -}); + switch (renderLane) { + case InputContinuousLane: + lane = InputContinuousHydrationLane; + break; -/** - * Dot screen shader - * based on glfx.js sepia shader - * https://github.com/evanw/glfx.js - */ + case DefaultLane: + lane = DefaultHydrationLane; + break; -({ - uniforms: { - tDiffuse: { - value: null - }, - tSize: { - value: new Vector2(256, 256) - }, - center: { - value: new Vector2(0.5, 0.5) - }, - angle: { - value: 1.57 - }, - scale: { - value: 1.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform vec2 center;', 'uniform float angle;', 'uniform float scale;', 'uniform vec2 tSize;', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'float pattern() {', ' float s = sin( angle ), c = cos( angle );', ' vec2 tex = vUv * tSize - center;', ' vec2 point = vec2( c * tex.x - s * tex.y, s * tex.x + c * tex.y ) * scale;', ' return ( sin( point.x ) * sin( point.y ) ) * 4.0;', '}', 'void main() {', ' vec4 color = texture2D( tDiffuse, vUv );', ' float average = ( color.r + color.g + color.b ) / 3.0;', ' gl_FragColor = vec4( vec3( average * 10.0 - 5.0 + pattern() ), color.a );', '}'].join('\n') -}); + case TransitionLane1: + case TransitionLane2: + case TransitionLane3: + case TransitionLane4: + case TransitionLane5: + case TransitionLane6: + case TransitionLane7: + case TransitionLane8: + case TransitionLane9: + case TransitionLane10: + case TransitionLane11: + case TransitionLane12: + case TransitionLane13: + case TransitionLane14: + case TransitionLane15: + case TransitionLane16: + case RetryLane1: + case RetryLane2: + case RetryLane3: + case RetryLane4: + case RetryLane5: + lane = TransitionHydrationLane; + break; -/** - * References: - * https://lettier.github.io/3d-game-shaders-for-beginners/screen-space-reflection.html - */ + case IdleLane: + lane = IdleHydrationLane; + break; -const SSRShader = { - defines: { - MAX_STEP: 0, - isPerspectiveCamera: true, - isDistanceAttenuation: true, - isFresnel: true, - isInfiniteThick: false, - isSelective: false - }, - uniforms: { - tDiffuse: { - value: null - }, - tNormal: { - value: null - }, - tMetalness: { - value: null - }, - tDepth: { - value: null - }, - cameraNear: { - value: null - }, - cameraFar: { - value: null - }, - resolution: { - value: new Vector2() - }, - cameraProjectionMatrix: { - value: new Matrix4() - }, - cameraInverseProjectionMatrix: { - value: new Matrix4() - }, - opacity: { - value: 0.5 - }, - maxDistance: { - value: 180 - }, - cameraRange: { - value: 0 - }, - surfDist: { - value: 0.007 - }, - thickTolerance: { - value: 0.03 - } - }, - vertexShader: - /* glsl */ - ` + default: + // Everything else is already either a hydration lane, or shouldn't + // be retried at a hydration lane. + lane = NoLane; + break; + } // Check if the lane we chose is suspended. If so, that indicates that we + // already attempted and failed to hydrate at that level. Also check if we're + // already rendering that lane, which is rare but could happen. - varying vec2 vUv; - void main() { + if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) { + // Give up trying to hydrate and fall back to client render. + return NoLane; + } + + return lane; + } + function addFiberToLanesMap(root, fiber, lanes) { - vUv = uv; + if (!isDevToolsPresent) { + return; + } - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - } + while (lanes > 0) { + var index = laneToIndex(lanes); + var lane = 1 << index; + var updaters = pendingUpdatersLaneMap[index]; + updaters.add(fiber); + lanes &= ~lane; + } + } + function movePendingFibersToMemoized(root, lanes) { - `, - fragmentShader: - /* glsl */ - ` - // precision highp float; - precision highp sampler2D; - varying vec2 vUv; - uniform sampler2D tDepth; - uniform sampler2D tNormal; - uniform sampler2D tMetalness; - uniform sampler2D tDiffuse; - uniform float cameraRange; - uniform vec2 resolution; - uniform float opacity; - uniform float cameraNear; - uniform float cameraFar; - uniform float maxDistance; - uniform float surfDist; - uniform mat4 cameraProjectionMatrix; - uniform mat4 cameraInverseProjectionMatrix; - uniform float thickTolerance; - #include - float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) { - //x0: point, x1: linePointA, x2: linePointB - //https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html - return length(cross(x0-x1,x0-x2))/length(x2-x1); - } - float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){ - // https://mathworld.wolfram.com/Point-PlaneDistance.html - //// https://en.wikipedia.org/wiki/Plane_(geometry) - //// http://paulbourke.net/geometry/pointlineplane/ - float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z; - float x0=point.x,y0=point.y,z0=point.z; - float x=planePoint.x,y=planePoint.y,z=planePoint.z; - float d=-(a*x+b*y+c*z); - float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c); - return distance; - } - float getDepth( const in vec2 uv ) { - return texture2D( tDepth, uv ).x; - } - float getViewZ( const in float depth ) { - #ifdef isPerspectiveCamera - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - #else - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - #endif - } - vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { - vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc - clipPosition *= clipW; //clip - return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view - } - vec3 getViewNormal( const in vec2 uv ) { - return unpackRGBToNormal( texture2D( tNormal, uv ).xyz ); - } - vec2 viewPositionToXY(vec3 viewPosition){ - vec2 xy; - vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1); - xy=clip.xy;//clip - float clipW=clip.w; - xy/=clipW;//NDC - xy=(xy+1.)/2.;//uv - xy*=resolution;//screen - return xy; - } - void main(){ - #ifdef isSelective - float metalness=texture2D(tMetalness,vUv).r; - if(metalness==0.) return; - #endif - - float depth = getDepth( vUv ); - float viewZ = getViewZ( depth ); - if(-viewZ>=cameraFar) return; - - float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3]; - vec3 viewPosition=getViewPosition( vUv, depth, clipW ); - - vec2 d0=gl_FragCoord.xy; - vec2 d1; - - vec3 viewNormal=getViewNormal( vUv ); - - #ifdef isPerspectiveCamera - vec3 viewIncidenceDir=normalize(viewPosition); - vec3 viewReflectDir=reflect(viewIncidenceDir,viewNormal); - #else - vec3 viewIncidenceDir=vec3(0,0,-1); - vec3 viewReflectDir=reflect(viewIncidenceDir,viewNormal); - #endif - - float maxReflectRayLen=maxDistance/dot(-viewIncidenceDir,viewNormal); - // dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html - // if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta) - // maxDistance/maxReflectRayLen=cos(theta) - // maxDistance/maxReflectRayLen==dot(a,b) - // maxReflectRayLen==maxDistance/dot(a,b) - - vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen; - #ifdef isPerspectiveCamera - if(d1viewPosition.z>-cameraNear){ - //https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx - float t=(-cameraNear-viewPosition.z)/viewReflectDir.z; - d1viewPosition=viewPosition+viewReflectDir*t; - } - #endif - d1=viewPositionToXY(d1viewPosition); - - float totalLen=length(d1-d0); - float xLen=d1.x-d0.x; - float yLen=d1.y-d0.y; - float totalStep=max(abs(xLen),abs(yLen)); - float xSpan=xLen/totalStep; - float ySpan=yLen/totalStep; - for(float i=0.;i=totalStep) break; - vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan); - if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break; - float s=length(xy-d0)/totalLen; - vec2 uv=xy/resolution; - - float d = getDepth(uv); - float vZ = getViewZ( d ); - if(-vZ>=cameraFar) continue; - float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3]; - vec3 vP=getViewPosition( uv, d, cW ); - - #ifdef isPerspectiveCamera - // https://www.comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf - float recipVPZ=1./viewPosition.z; - float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ)); - float sD=surfDist*cW; - #else - float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z); - float sD=surfDist; - #endif - if(viewReflectRayZ-sD>vZ) continue; - - #ifdef isInfiniteThick - if(viewReflectRayZ+thickTolerance*clipW=0.) continue; - float distance=pointPlaneDistance(vP,viewPosition,viewNormal); - if(distance>maxDistance) break; - #ifdef isDistanceAttenuation - float ratio=1.-(distance/maxDistance); - float attenuation=ratio*ratio; - op=opacity*attenuation; - #endif - #ifdef isFresnel - float fresnel=(dot(viewIncidenceDir,viewReflectDir)+1.)/2.; - op*=fresnel; - #endif - vec4 reflectColor=texture2D(tDiffuse,uv); - gl_FragColor.xyz=reflectColor.xyz; - gl_FragColor.a=op; - break; - } - } - } - ` -}; -const SSRDepthShader = { - defines: { - PERSPECTIVE_CAMERA: 1 - }, - uniforms: { - tDepth: { - value: null - }, - cameraNear: { - value: null - }, - cameraFar: { - value: null - } - }, - vertexShader: - /* glsl */ - ` + if (!isDevToolsPresent) { + return; + } - varying vec2 vUv; + var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; + var memoizedUpdaters = root.memoizedUpdaters; - void main() { + while (lanes > 0) { + var index = laneToIndex(lanes); + var lane = 1 << index; + var updaters = pendingUpdatersLaneMap[index]; - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + if (updaters.size > 0) { + updaters.forEach(function (fiber) { + var alternate = fiber.alternate; - } + if (alternate === null || !memoizedUpdaters.has(alternate)) { + memoizedUpdaters.add(fiber); + } + }); + updaters.clear(); + } - `, - fragmentShader: - /* glsl */ - ` + lanes &= ~lane; + } + } - uniform sampler2D tDepth; + var DiscreteEventPriority = SyncLane; + var ContinuousEventPriority = InputContinuousLane; + var DefaultEventPriority = DefaultLane; + var IdleEventPriority = IdleLane; + var currentUpdatePriority = NoLane; + function getCurrentUpdatePriority() { + return currentUpdatePriority; + } + function setCurrentUpdatePriority(newPriority) { + currentUpdatePriority = newPriority; + } + function runWithPriority(priority, fn) { + var previousPriority = currentUpdatePriority; - uniform float cameraNear; - uniform float cameraFar; + try { + currentUpdatePriority = priority; + return fn(); + } finally { + currentUpdatePriority = previousPriority; + } + } + function higherEventPriority(a, b) { + return a !== 0 && a < b ? a : b; + } + function lowerEventPriority(a, b) { + return a === 0 || a > b ? a : b; + } + function isHigherEventPriority(a, b) { + return a !== 0 && a < b; + } + function lanesToEventPriority(lanes) { + var lane = getHighestPriorityLane(lanes); - varying vec2 vUv; + if (!isHigherEventPriority(DiscreteEventPriority, lane)) { + return DiscreteEventPriority; + } - #include + if (!isHigherEventPriority(ContinuousEventPriority, lane)) { + return ContinuousEventPriority; + } - float getLinearDepth( const in vec2 uv ) { + if (includesNonIdleWork(lane)) { + return DefaultEventPriority; + } - #if PERSPECTIVE_CAMERA == 1 + return IdleEventPriority; + } - float fragCoordZ = texture2D( tDepth, uv ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + // This module only exists as an ESM wrapper around the external CommonJS + var scheduleCallback = Scheduler.unstable_scheduleCallback; + var cancelCallback = Scheduler.unstable_cancelCallback; + var shouldYield = Scheduler.unstable_shouldYield; + var requestPaint = Scheduler.unstable_requestPaint; + var now$1 = Scheduler.unstable_now; + var ImmediatePriority = Scheduler.unstable_ImmediatePriority; + var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; + var NormalPriority = Scheduler.unstable_NormalPriority; + var IdlePriority = Scheduler.unstable_IdlePriority; + // this doesn't actually exist on the scheduler, but it *does* + // on scheduler/unstable_mock, which we'll need for internal testing + var unstable_yieldValue = Scheduler.unstable_yieldValue; + var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue; - #else + var rendererID = null; + var injectedHook = null; + var injectedProfilingHooks = null; + var hasLoggedError = false; + var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined'; + function injectInternals(internals) { + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { + // No DevTools + return false; + } - return texture2D( tDepth, uv ).x; + var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; - #endif + if (hook.isDisabled) { + // This isn't a real property on the hook, but it can be set to opt out + // of DevTools integration and associated warnings and logs. + // https://github.com/facebook/react/issues/3877 + return true; + } - } + if (!hook.supportsFiber) { + { + error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools'); + } // DevTools exists, even though it doesn't support Fiber. - void main() { - float depth = getLinearDepth( vUv ); - float d = 1.0 - depth; - // d=(d-.999)*1000.; - gl_FragColor = vec4( vec3( d ), 1.0 ); + return true; + } - } + try { + if (enableSchedulingProfiler) { + // Conditionally inject these hooks only if Timeline profiler is supported by this build. + // This gives DevTools a way to feature detect that isn't tied to version number + // (since profiling and timeline are controlled by different feature flags). + internals = assign({}, internals, { + getLaneLabelMap: getLaneLabelMap, + injectProfilingHooks: injectProfilingHooks + }); + } - ` -}; -const SSRBlurShader = { - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2() - }, - opacity: { - value: 0.5 - } - }, - vertexShader: - /* glsl */ - ` + rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. - varying vec2 vUv; + injectedHook = hook; + } catch (err) { + // Catch all errors because it is unsafe to throw during initialization. + { + error('React instrumentation encountered an error: %s.', err); + } + } - void main() { + if (hook.checkDCE) { + // This is the real DevTools. + return true; + } else { + // This is likely a hook installed by Fast Refresh runtime. + return false; + } + } + function onScheduleRoot(root, children) { + { + if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') { + try { + injectedHook.onScheduleFiberRoot(rendererID, root, children); + } catch (err) { + if ( !hasLoggedError) { + hasLoggedError = true; - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + function onCommitRoot(root, eventPriority) { + if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { + try { + var didError = (root.current.flags & DidCapture) === DidCapture; - } + if (enableProfilerTimer) { + var schedulerPriority; - `, - fragmentShader: - /* glsl */ - ` + switch (eventPriority) { + case DiscreteEventPriority: + schedulerPriority = ImmediatePriority; + break; - uniform sampler2D tDiffuse; - uniform vec2 resolution; - varying vec2 vUv; - void main() { - //reverse engineering from PhotoShop blur filter, then change coefficient + case ContinuousEventPriority: + schedulerPriority = UserBlockingPriority; + break; - vec2 texelSize = ( 1.0 / resolution ); + case DefaultEventPriority: + schedulerPriority = NormalPriority; + break; - vec4 c=texture2D(tDiffuse,vUv); + case IdleEventPriority: + schedulerPriority = IdlePriority; + break; - vec2 offset; + default: + schedulerPriority = NormalPriority; + break; + } - offset=(vec2(-1,0))*texelSize; - vec4 cl=texture2D(tDiffuse,vUv+offset); + injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError); + } + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; - offset=(vec2(1,0))*texelSize; - vec4 cr=texture2D(tDiffuse,vUv+offset); + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + function onPostCommitRoot(root) { + if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') { + try { + injectedHook.onPostCommitFiberRoot(rendererID, root); + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; - offset=(vec2(0,-1))*texelSize; - vec4 cb=texture2D(tDiffuse,vUv+offset); + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + function onCommitUnmount(fiber) { + if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') { + try { + injectedHook.onCommitFiberUnmount(rendererID, fiber); + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; - offset=(vec2(0,1))*texelSize; - vec4 ct=texture2D(tDiffuse,vUv+offset); + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + function setIsStrictModeForDevtools(newIsStrictMode) { + { + if (typeof unstable_yieldValue === 'function') { + // We're in a test because Scheduler.unstable_yieldValue only exists + // in SchedulerMock. To reduce the noise in strict mode tests, + // suppress warnings and disable scheduler yielding during the double render + unstable_setDisableYieldValue(newIsStrictMode); + setSuppressWarning(newIsStrictMode); + } - // float coeCenter=.5; - // float coeSide=.125; - float coeCenter=.2; - float coeSide=.2; - float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide; - vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a; - gl_FragColor=vec4(rgb,a); + if (injectedHook && typeof injectedHook.setStrictMode === 'function') { + try { + injectedHook.setStrictMode(rendererID, newIsStrictMode); + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; - } - ` -}; + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + } // Profiler API hooks -var SSRPass = function ({ - renderer, - scene, - camera, - width, - height, - selects, - encoding, - isPerspectiveCamera = true, - isBouncing = false, - morphTargets = false, - groundReflector -}) { - this.width = width !== undefined ? width : 512; - this.height = height !== undefined ? height : 512; - this.clear = true; - this.renderer = renderer; - this.scene = scene; - this.camera = camera; - this.groundReflector = groundReflector; - this.opacity = SSRShader.uniforms.opacity.value; - this.output = 0; - this.maxDistance = SSRShader.uniforms.maxDistance.value; - this.surfDist = SSRShader.uniforms.surfDist.value; - this.encoding = encoding; - this.tempColor = new Color(); - this._selects = selects; - this.isSelective = Array.isArray(this._selects); - Object.defineProperty(this, 'selects', { - get() { - return this._selects; - }, + function injectProfilingHooks(profilingHooks) { + injectedProfilingHooks = profilingHooks; + } - set(val) { - if (this._selects === val) return; - this._selects = val; + function getLaneLabelMap() { + { + var map = new Map(); + var lane = 1; - if (Array.isArray(val)) { - this.isSelective = true; - this.ssrMaterial.defines.isSelective = true; - this.ssrMaterial.needsUpdate = true; - } else { - this.isSelective = false; - this.ssrMaterial.defines.isSelective = false; - this.ssrMaterial.needsUpdate = true; - } - } + for (var index = 0; index < TotalLanes; index++) { + var label = getLabelForLane(lane); + map.set(lane, label); + lane *= 2; + } - }); - this._isBouncing = isBouncing; ///todo: don't need defineProperty + return map; + } + } - Object.defineProperty(this, 'isBouncing', { - get() { - return this._isBouncing; - }, + function markCommitStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') { + injectedProfilingHooks.markCommitStarted(lanes); + } + } + } + function markCommitStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') { + injectedProfilingHooks.markCommitStopped(); + } + } + } + function markComponentRenderStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') { + injectedProfilingHooks.markComponentRenderStarted(fiber); + } + } + } + function markComponentRenderStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') { + injectedProfilingHooks.markComponentRenderStopped(); + } + } + } + function markComponentPassiveEffectMountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') { + injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); + } + } + } + function markComponentPassiveEffectMountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') { + injectedProfilingHooks.markComponentPassiveEffectMountStopped(); + } + } + } + function markComponentPassiveEffectUnmountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') { + injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); + } + } + } + function markComponentPassiveEffectUnmountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') { + injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); + } + } + } + function markComponentLayoutEffectMountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') { + injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); + } + } + } + function markComponentLayoutEffectMountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') { + injectedProfilingHooks.markComponentLayoutEffectMountStopped(); + } + } + } + function markComponentLayoutEffectUnmountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') { + injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); + } + } + } + function markComponentLayoutEffectUnmountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') { + injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); + } + } + } + function markComponentErrored(fiber, thrownValue, lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') { + injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); + } + } + } + function markComponentSuspended(fiber, wakeable, lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') { + injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); + } + } + } + function markLayoutEffectsStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') { + injectedProfilingHooks.markLayoutEffectsStarted(lanes); + } + } + } + function markLayoutEffectsStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') { + injectedProfilingHooks.markLayoutEffectsStopped(); + } + } + } + function markPassiveEffectsStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') { + injectedProfilingHooks.markPassiveEffectsStarted(lanes); + } + } + } + function markPassiveEffectsStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') { + injectedProfilingHooks.markPassiveEffectsStopped(); + } + } + } + function markRenderStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') { + injectedProfilingHooks.markRenderStarted(lanes); + } + } + } + function markRenderYielded() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') { + injectedProfilingHooks.markRenderYielded(); + } + } + } + function markRenderStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') { + injectedProfilingHooks.markRenderStopped(); + } + } + } + function markRenderScheduled(lane) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') { + injectedProfilingHooks.markRenderScheduled(lane); + } + } + } + function markForceUpdateScheduled(fiber, lane) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') { + injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); + } + } + } + function markStateUpdateScheduled(fiber, lane) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') { + injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); + } + } + } - set(val) { - if (this._isBouncing === val) return; - this._isBouncing = val; + /** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ + function is(x, y) { + return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare + ; + } - if (val) { - this.ssrMaterial.uniforms['tDiffuse'].value = this.prevRenderTarget.texture; - } else { - this.ssrMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - } - } + var objectIs = typeof Object.is === 'function' ? Object.is : is; - }); - this.isBlur = true; - this._isDistanceAttenuation = SSRShader.defines.isDistanceAttenuation; - Object.defineProperty(this, 'isDistanceAttenuation', { - get() { - return this._isDistanceAttenuation; - }, + var syncQueue = null; + var includesLegacySyncCallbacks = false; + var isFlushingSyncQueue = false; + function scheduleSyncCallback(callback) { + // Push this callback into an internal queue. We'll flush these either in + // the next tick, or earlier if something calls `flushSyncCallbackQueue`. + if (syncQueue === null) { + syncQueue = [callback]; + } else { + // Push onto existing queue. Don't need to schedule a callback because + // we already scheduled one when we created the queue. + syncQueue.push(callback); + } + } + function scheduleLegacySyncCallback(callback) { + includesLegacySyncCallbacks = true; + scheduleSyncCallback(callback); + } + function flushSyncCallbacksOnlyInLegacyMode() { + // Only flushes the queue if there's a legacy sync callback scheduled. + // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So + // it might make more sense for the queue to be a list of roots instead of a + // list of generic callbacks. Then we can have two: one for legacy roots, one + // for concurrent roots. And this method would only flush the legacy ones. + if (includesLegacySyncCallbacks) { + flushSyncCallbacks(); + } + } + function flushSyncCallbacks() { + if (!isFlushingSyncQueue && syncQueue !== null) { + // Prevent re-entrance. + isFlushingSyncQueue = true; + var i = 0; + var previousUpdatePriority = getCurrentUpdatePriority(); - set(val) { - if (this._isDistanceAttenuation === val) return; - this._isDistanceAttenuation = val; - this.ssrMaterial.defines.isDistanceAttenuation = val; - this.ssrMaterial.needsUpdate = true; - } + try { + var isSync = true; + var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this + // queue is in the render or commit phases. - }); - this._isFresnel = SSRShader.defines.isFresnel; - Object.defineProperty(this, 'isFresnel', { - get() { - return this._isFresnel; - }, + setCurrentUpdatePriority(DiscreteEventPriority); - set(val) { - if (this._isFresnel === val) return; - this._isFresnel = val; - this.ssrMaterial.defines.isFresnel = val; - this.ssrMaterial.needsUpdate = true; - } + for (; i < queue.length; i++) { + var callback = queue[i]; - }); - this._isInfiniteThick = SSRShader.defines.isInfiniteThick; - Object.defineProperty(this, 'isInfiniteThick', { - get() { - return this._isInfiniteThick; - }, + do { + callback = callback(isSync); + } while (callback !== null); + } - set(val) { - if (this._isInfiniteThick === val) return; - this._isInfiniteThick = val; - this.ssrMaterial.defines.isInfiniteThick = val; - this.ssrMaterial.needsUpdate = true; - } + syncQueue = null; + includesLegacySyncCallbacks = false; + } catch (error) { + // If something throws, leave the remaining callbacks on the queue. + if (syncQueue !== null) { + syncQueue = syncQueue.slice(i + 1); + } // Resume flushing in the next tick - }); - this.thickTolerance = SSRShader.uniforms.thickTolerance.value; // beauty render target with depth buffer - - var depthTexture = new DepthTexture(); - depthTexture.type = UnsignedShortType; - depthTexture.minFilter = NearestFilter; - depthTexture.maxFilter = NearestFilter; - this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat, - depthTexture: depthTexture, - depthBuffer: true - }); //for bouncing - - this.prevRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }); // normal render target - - this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: NearestFilter, - magFilter: NearestFilter, - format: RGBAFormat, - type: HalfFloatType - }); // metalness render target - // if (this.isSelective) { - - this.metalnessRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: NearestFilter, - magFilter: NearestFilter, - format: RGBAFormat - }); // } - // ssr render target - - this.ssrRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }); - this.blurRenderTarget = this.ssrRenderTarget.clone(); - this.blurRenderTarget2 = this.ssrRenderTarget.clone(); // this.blurRenderTarget3 = this.ssrRenderTarget.clone(); - // ssr material - - if (SSRShader === undefined) { - console.error('THREE.SSRPass: The pass relies on SSRShader.'); - } - - this.ssrMaterial = new ShaderMaterial({ - defines: Object.assign({ - MAX_STEP: Math.sqrt(window.innerWidth * window.innerWidth + window.innerHeight * window.innerHeight) - }, SSRShader.defines), - uniforms: UniformsUtils.clone(SSRShader.uniforms), - vertexShader: SSRShader.vertexShader, - fragmentShader: SSRShader.fragmentShader, - blending: NoBlending - }); - if (!isPerspectiveCamera) { - this.ssrMaterial.defines.isPerspectiveCamera = isPerspectiveCamera; - this.ssrMaterial.needsUpdate = true; - } + scheduleCallback(ImmediatePriority, flushSyncCallbacks); + throw error; + } finally { + setCurrentUpdatePriority(previousUpdatePriority); + isFlushingSyncQueue = false; + } + } - this.ssrMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.ssrMaterial.uniforms['tNormal'].value = this.normalRenderTarget.texture; // if (this.isSelective) { + return null; + } - this.ssrMaterial.defines.isSelective = this.isSelective; - this.ssrMaterial.needsUpdate = true; - this.ssrMaterial.uniforms['tMetalness'].value = this.metalnessRenderTarget.texture; // } + // This is imported by the event replaying implementation in React DOM. It's + // in a separate file to break a circular dependency between the renderer and + // the reconciler. + function isRootDehydrated(root) { + var currentState = root.current.memoizedState; + return currentState.isDehydrated; + } - this.ssrMaterial.uniforms['tDepth'].value = this.beautyRenderTarget.depthTexture; - this.ssrMaterial.uniforms['cameraNear'].value = this.camera.near; - this.ssrMaterial.uniforms['cameraFar'].value = this.camera.far; - this.ssrMaterial.uniforms['surfDist'].value = this.surfDist; - this.ssrMaterial.uniforms['resolution'].value.set(this.width, this.height); - this.ssrMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssrMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); // normal material + var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; + var NoTransition = null; + function requestCurrentTransition() { + return ReactCurrentBatchConfig.transition; + } - this.normalMaterial = new MeshNormalMaterial({ - morphTargets - }); - this.normalMaterial.blending = NoBlending; // if (this.isSelective) { - // metalnessOn material - - this.metalnessOnMaterial = new MeshBasicMaterial({ - color: 'white' - }); // metalnessOff material - - this.metalnessOffMaterial = new MeshBasicMaterial({ - color: 'black' - }); // } - // blur material - - this.blurMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSRBlurShader.defines), - uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), - vertexShader: SSRBlurShader.vertexShader, - fragmentShader: SSRBlurShader.fragmentShader - }); - this.blurMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.blurMaterial.uniforms['resolution'].value.set(this.width, this.height); // blur material 2 - - this.blurMaterial2 = new ShaderMaterial({ - defines: Object.assign({}, SSRBlurShader.defines), - uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), - vertexShader: SSRBlurShader.vertexShader, - fragmentShader: SSRBlurShader.fragmentShader - }); - this.blurMaterial2.uniforms['tDiffuse'].value = this.blurRenderTarget.texture; - this.blurMaterial2.uniforms['resolution'].value.set(this.width, this.height); // // blur material 3 - // this.blurMaterial3 = new ShaderMaterial({ - // defines: Object.assign({}, SSRBlurShader.defines), - // uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), - // vertexShader: SSRBlurShader.vertexShader, - // fragmentShader: SSRBlurShader.fragmentShader - // }); - // this.blurMaterial3.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture; - // this.blurMaterial3.uniforms['resolution'].value.set(this.width, this.height); - // material for rendering the depth - - this.depthRenderMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSRDepthShader.defines), - uniforms: UniformsUtils.clone(SSRDepthShader.uniforms), - vertexShader: SSRDepthShader.vertexShader, - fragmentShader: SSRDepthShader.fragmentShader, - blending: NoBlending - }); - this.depthRenderMaterial.uniforms['tDepth'].value = this.beautyRenderTarget.depthTexture; - this.depthRenderMaterial.uniforms['cameraNear'].value = this.camera.near; - this.depthRenderMaterial.uniforms['cameraFar'].value = this.camera.far; // material for rendering the content of a render target - - this.copyMaterial = new ShaderMaterial({ - uniforms: UniformsUtils.clone(CopyShader.uniforms), - vertexShader: CopyShader.vertexShader, - fragmentShader: CopyShader.fragmentShader, - transparent: true, - depthTest: false, - depthWrite: false, - blendSrc: SrcAlphaFactor, - blendDst: OneMinusSrcAlphaFactor, - blendEquation: AddEquation, - blendSrcAlpha: SrcAlphaFactor, - blendDstAlpha: OneMinusSrcAlphaFactor, - blendEquationAlpha: AddEquation // premultipliedAlpha:true, + /** + * Performs equality by iterating through keys on an object and returning false + * when any key has values which are not strictly equal between the arguments. + * Returns true when the values of all keys are strictly equal. + */ - }); - this.fsQuad = new FullScreenQuad(null); - this.originalClearColor = new Color(); -}; + function shallowEqual(objA, objB) { + if (objectIs(objA, objB)) { + return true; + } -SSRPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: SSRPass, - dispose: function () { - // dispose render targets - this.beautyRenderTarget.dispose(); - this.prevRenderTarget.dispose(); - this.normalRenderTarget.dispose(); // if (this.isSelective) + if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { + return false; + } - this.metalnessRenderTarget.dispose(); - this.ssrRenderTarget.dispose(); - this.blurRenderTarget.dispose(); - this.blurRenderTarget2.dispose(); // this.blurRenderTarget3.dispose(); - // dispose materials + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); - this.normalMaterial.dispose(); // if (this.isSelective) { + if (keysA.length !== keysB.length) { + return false; + } // Test for A's keys different from B. - this.metalnessOnMaterial.dispose(); - this.metalnessOffMaterial.dispose(); // } - this.blurMaterial.dispose(); - this.blurMaterial2.dispose(); - this.copyMaterial.dispose(); - this.depthRenderMaterial.dispose(); // dipsose full screen quad + for (var i = 0; i < keysA.length; i++) { + var currentKey = keysA[i]; - this.fsQuad.dispose(); - }, - render: function (renderer, writeBuffer - /*, readBuffer, deltaTime, maskActive */ - ) { - // render beauty and depth - if (this.encoding) this.beautyRenderTarget.texture.encoding = this.encoding; - renderer.setRenderTarget(this.beautyRenderTarget); - renderer.clear(); - - if (this.groundReflector) { - this.groundReflector.doRender(this.renderer, this.scene, this.camera); - this.groundReflector.visible = true; - } + if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) { + return false; + } + } - renderer.render(this.scene, this.camera); - if (this.groundReflector) this.groundReflector.visible = false; // render normals - - this.renderOverride(renderer, this.normalMaterial, this.normalRenderTarget, 0, 0); // render metalnesses - - if (this.isSelective) { - this.renderMetalness(renderer, this.metalnessOnMaterial, this.metalnessRenderTarget, 0, 0); - } // render SSR - - - this.ssrMaterial.uniforms['opacity'].value = this.opacity; - this.ssrMaterial.uniforms['maxDistance'].value = this.maxDistance; - this.ssrMaterial.uniforms['surfDist'].value = this.surfDist; - this.ssrMaterial.uniforms['thickTolerance'].value = this.thickTolerance; - this.renderPass(renderer, this.ssrMaterial, this.ssrRenderTarget); // render blur - - if (this.isBlur) { - this.renderPass(renderer, this.blurMaterial, this.blurRenderTarget); - this.renderPass(renderer, this.blurMaterial2, this.blurRenderTarget2); // this.renderPass(renderer, this.blurMaterial3, this.blurRenderTarget3); - } // output result to screen - - - switch (this.output) { - case SSRPass.OUTPUT.Default: - if (this.isBouncing) { - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); - if (this.isBlur) this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;else this.copyMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.copyMaterial.blending = NormalBlending; - this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); - this.copyMaterial.uniforms['tDiffuse'].value = this.prevRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - } else { - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - if (this.isBlur) this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;else this.copyMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.copyMaterial.blending = NormalBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - } + return true; + } - break; + function describeFiber(fiber) { + fiber._debugOwner ? fiber._debugOwner.type : null ; + fiber._debugSource ; - case SSRPass.OUTPUT.SSR: - if (this.isBlur) this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;else this.copyMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - - if (this.isBouncing) { - if (this.isBlur) this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;else this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); - this.copyMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.copyMaterial.blending = NormalBlending; - this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); - } + switch (fiber.tag) { + case HostComponent: + return describeBuiltInComponentFrame(fiber.type); - break; + case LazyComponent: + return describeBuiltInComponentFrame('Lazy'); - case SSRPass.OUTPUT.Beauty: - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + case SuspenseComponent: + return describeBuiltInComponentFrame('Suspense'); - case SSRPass.OUTPUT.Depth: - this.renderPass(renderer, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); - break; + case SuspenseListComponent: + return describeBuiltInComponentFrame('SuspenseList'); - case SSRPass.OUTPUT.Normal: - this.copyMaterial.uniforms['tDiffuse'].value = this.normalRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + case FunctionComponent: + case IndeterminateComponent: + case SimpleMemoComponent: + return describeFunctionComponentFrame(fiber.type); - case SSRPass.OUTPUT.Metalness: - this.copyMaterial.uniforms['tDiffuse'].value = this.metalnessRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + case ForwardRef: + return describeFunctionComponentFrame(fiber.type.render); - default: - console.warn('THREE.SSRPass: Unknown output type.'); - } - }, - renderPass: function (renderer, passMaterial, renderTarget, clearColor, clearAlpha) { - // save original state - this.originalClearColor.copy(renderer.getClearColor(this.tempColor)); - var originalClearAlpha = renderer.getClearAlpha(this.tempColor); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); // setup pass state - - renderer.autoClear = false; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + case ClassComponent: + return describeClassComponentFrame(fiber.type); - this.fsQuad.material = passMaterial; - this.fsQuad.render(renderer); // restore original state + default: + return ''; + } + } - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - renderOverride: function (renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { - this.originalClearColor.copy(renderer.getClearColor(this.tempColor)); - var originalClearAlpha = renderer.getClearAlpha(this.tempColor); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); - renderer.autoClear = false; - clearColor = overrideMaterial.clearColor || clearColor; - clearAlpha = overrideMaterial.clearAlpha || clearAlpha; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + function getStackByFiberInDevAndProd(workInProgress) { + try { + var info = ''; + var node = workInProgress; - this.scene.overrideMaterial = overrideMaterial; - renderer.render(this.scene, this.camera); - this.scene.overrideMaterial = null; // restore original state + do { + info += describeFiber(node); + node = node.return; + } while (node); - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - renderMetalness: function (renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { - this.originalClearColor.copy(renderer.getClearColor(this.tempColor)); - var originalClearAlpha = renderer.getClearAlpha(this.tempColor); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); - renderer.autoClear = false; - clearColor = overrideMaterial.clearColor || clearColor; - clearAlpha = overrideMaterial.clearAlpha || clearAlpha; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + return info; + } catch (x) { + return '\nError generating stack: ' + x.message + '\n' + x.stack; + } + } - this.scene.traverseVisible(child => { - child._SSRPassMaterialBack = child.material; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + var current = null; + var isRendering = false; + function getCurrentFiberOwnerNameInDevOrNull() { + { + if (current === null) { + return null; + } - if (this._selects.includes(child)) { - child.material = this.metalnessOnMaterial; - } else { - child.material = this.metalnessOffMaterial; - } - }); - renderer.render(this.scene, this.camera); - this.scene.traverseVisible(child => { - child.material = child._SSRPassMaterialBack; - }); // restore original state + var owner = current._debugOwner; - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - setSize: function (width, height) { - this.width = width; - this.height = height; - this.ssrMaterial.defines.MAX_STEP = Math.sqrt(width * width + height * height); - this.ssrMaterial.needsUpdate = true; - this.beautyRenderTarget.setSize(width, height); - this.prevRenderTarget.setSize(width, height); - this.ssrRenderTarget.setSize(width, height); - this.normalRenderTarget.setSize(width, height); // if (this.isSelective) - - this.metalnessRenderTarget.setSize(width, height); - this.blurRenderTarget.setSize(width, height); - this.blurRenderTarget2.setSize(width, height); // this.blurRenderTarget3.setSize(width, height); - - this.ssrMaterial.uniforms['resolution'].value.set(width, height); - this.ssrMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssrMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - this.blurMaterial.uniforms['resolution'].value.set(width, height); - this.blurMaterial2.uniforms['resolution'].value.set(width, height); - } -}); -SSRPass.OUTPUT = { - Default: 0, - SSR: 1, - Beauty: 3, - Depth: 4, - Normal: 5, - Metalness: 7 -}; + if (owner !== null && typeof owner !== 'undefined') { + return getComponentNameFromFiber(owner); + } + } -/** - * - * Supersample Anti-Aliasing Render Pass - * - * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results. - * - * References: https://en.wikipedia.org/wiki/Supersampling - * - */ + return null; + } -var SSAARenderPass = function (scene, camera, clearColor, clearAlpha) { - this.scene = scene; - this.camera = camera; - this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16. - - this.unbiased = true; // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black. - - this.clearColor = clearColor !== undefined ? clearColor : 0x000000; - this.clearAlpha = clearAlpha !== undefined ? clearAlpha : 0; - this._oldClearColor = new Color(); - if (CopyShader === undefined) console.error('THREE.SSAARenderPass relies on CopyShader'); - var copyShader = CopyShader; - this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); - this.copyMaterial = new ShaderMaterial({ - uniforms: this.copyUniforms, - vertexShader: copyShader.vertexShader, - fragmentShader: copyShader.fragmentShader, - premultipliedAlpha: true, - transparent: true, - blending: AdditiveBlending, - depthTest: false, - depthWrite: false - }); - this.fsQuad = new FullScreenQuad(this.copyMaterial); -}; + function getCurrentFiberStackInDev() { + { + if (current === null) { + return ''; + } // Safe because if current fiber exists, we are reconciling, + // and it is guaranteed to be the work-in-progress version. -SSAARenderPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: SSAARenderPass, - dispose: function () { - if (this.sampleRenderTarget) { - this.sampleRenderTarget.dispose(); - this.sampleRenderTarget = null; - } - }, - setSize: function (width, height) { - if (this.sampleRenderTarget) this.sampleRenderTarget.setSize(width, height); - }, - render: function (renderer, writeBuffer, readBuffer) { - if (!this.sampleRenderTarget) { - this.sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }); - this.sampleRenderTarget.texture.name = 'SSAARenderPass.sample'; - } - var jitterOffsets = SSAARenderPass.JitterVectors[Math.max(0, Math.min(this.sampleLevel, 5))]; - var autoClear = renderer.autoClear; - renderer.autoClear = false; - renderer.getClearColor(this._oldClearColor); - var oldClearAlpha = renderer.getClearAlpha(); - var baseSampleWeight = 1.0 / jitterOffsets.length; - var roundingRange = 1 / 32; - this.copyUniforms['tDiffuse'].value = this.sampleRenderTarget.texture; - var width = readBuffer.width, - height = readBuffer.height; // render the scene multiple times, each slightly jitter offset from the last and accumulate the results. - - for (let i = 0; i < jitterOffsets.length; i++) { - var jitterOffset = jitterOffsets[i]; - - if (this.camera.setViewOffset) { - this.camera.setViewOffset(width, height, jitterOffset[0] * 0.0625, jitterOffset[1] * 0.0625, // 0.0625 = 1 / 16 - width, height); - } + return getStackByFiberInDevAndProd(current); + } + } - var sampleWeight = baseSampleWeight; + function resetCurrentFiber() { + { + ReactDebugCurrentFrame$1.getCurrentStack = null; + current = null; + isRendering = false; + } + } + function setCurrentFiber(fiber) { + { + ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev; + current = fiber; + isRendering = false; + } + } + function setIsRendering(rendering) { + { + isRendering = rendering; + } + } - if (this.unbiased) { - // the theory is that equal weights for each sample lead to an accumulation of rounding errors. - // The following equation varies the sampleWeight per sample so that it is uniformly distributed - // across a range of values whose rounding errors cancel each other out. - var uniformCenteredDistribution = -0.5 + (i + 0.5) / jitterOffsets.length; - sampleWeight += roundingRange * uniformCenteredDistribution; - } + var ReactStrictModeWarnings = { + recordUnsafeLifecycleWarnings: function (fiber, instance) {}, + flushPendingUnsafeLifecycleWarnings: function () {}, + recordLegacyContextWarning: function (fiber, instance) {}, + flushLegacyContextWarning: function () {}, + discardPendingWarnings: function () {} + }; - this.copyUniforms['opacity'].value = sampleWeight; - renderer.setClearColor(this.clearColor, this.clearAlpha); - renderer.setRenderTarget(this.sampleRenderTarget); - renderer.clear(); - renderer.render(this.scene, this.camera); - renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer); + { + var findStrictRoot = function (fiber) { + var maybeStrictRoot = null; + var node = fiber; - if (i === 0) { - renderer.setClearColor(0x000000, 0.0); - renderer.clear(); - } + while (node !== null) { + if (node.mode & StrictLegacyMode) { + maybeStrictRoot = node; + } - this.fsQuad.render(renderer); - } + node = node.return; + } - if (this.camera.clearViewOffset) this.camera.clearViewOffset(); - renderer.autoClear = autoClear; - renderer.setClearColor(this._oldClearColor, oldClearAlpha); - } -}); // These jitter vectors are specified in integers because it is easier. -// I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5) -// before being used, thus these integers need to be scaled by 1/16. -// -// Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 + return maybeStrictRoot; + }; -SSAARenderPass.JitterVectors = [[[0, 0]], [[4, 4], [-4, -4]], [[-2, -6], [6, -2], [-6, 2], [2, 6]], [[1, -3], [-1, 3], [5, 1], [-3, -5], [-5, 5], [-7, -1], [3, 7], [7, -7]], [[1, 1], [-1, -3], [-3, 2], [4, -1], [-5, -2], [2, 5], [5, 3], [3, -5], [-2, 6], [0, -7], [-4, -6], [-6, 4], [-8, 0], [7, -4], [6, 7], [-7, -8]], [[-4, -7], [-7, -5], [-3, -5], [-5, -4], [-1, -4], [-2, -2], [-6, -1], [-4, 0], [-7, 1], [-1, 2], [-6, 3], [-3, 3], [-7, 6], [-3, 6], [-5, 7], [-1, 7], [5, -7], [1, -6], [6, -5], [4, -4], [2, -3], [7, -2], [1, -1], [4, -1], [2, 1], [6, 2], [0, 4], [4, 4], [2, 5], [7, 5], [5, 6], [3, 7]]]; + var setToSortedString = function (set) { + var array = []; + set.forEach(function (value) { + array.push(value); + }); + return array.sort().join(', '); + }; -/** - * - * Temporal Anti-Aliasing Render Pass - * - * When there is no motion in the scene, the TAA render pass accumulates jittered camera samples across frames to create a high quality anti-aliased result. - * - * References: - * - * TODO: Add support for motion vector pas so that accumulation of samples across frames can occur on dynamics scenes. - * - */ + var pendingComponentWillMountWarnings = []; + var pendingUNSAFE_ComponentWillMountWarnings = []; + var pendingComponentWillReceivePropsWarnings = []; + var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; + var pendingComponentWillUpdateWarnings = []; + var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. -var TAARenderPass = function (scene, camera, clearColor, clearAlpha) { - if (SSAARenderPass === undefined) { - console.error('THREE.TAARenderPass relies on SSAARenderPass'); - } + var didWarnAboutUnsafeLifecycles = new Set(); - SSAARenderPass.call(this, scene, camera, clearColor, clearAlpha); - this.sampleLevel = 0; - this.accumulate = false; -}; + ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) { + // Dedupe strategy: Warn once per component. + if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { + return; + } -TAARenderPass.JitterVectors = SSAARenderPass.JitterVectors; -TAARenderPass.prototype = Object.assign(Object.create(SSAARenderPass.prototype), { - constructor: TAARenderPass, - render: function (renderer, writeBuffer, readBuffer, deltaTime) { - if (!this.accumulate) { - SSAARenderPass.prototype.render.call(this, renderer, writeBuffer, readBuffer, deltaTime); - this.accumulateIndex = -1; - return; - } + if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components. + instance.componentWillMount.__suppressDeprecationWarning !== true) { + pendingComponentWillMountWarnings.push(fiber); + } - var jitterOffsets = TAARenderPass.JitterVectors[5]; + if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') { + pendingUNSAFE_ComponentWillMountWarnings.push(fiber); + } - if (!this.sampleRenderTarget) { - this.sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, this.params); - this.sampleRenderTarget.texture.name = 'TAARenderPass.sample'; - } + if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { + pendingComponentWillReceivePropsWarnings.push(fiber); + } - if (!this.holdRenderTarget) { - this.holdRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, this.params); - this.holdRenderTarget.texture.name = 'TAARenderPass.hold'; - } + if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') { + pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); + } - if (this.accumulate && this.accumulateIndex === -1) { - SSAARenderPass.prototype.render.call(this, renderer, this.holdRenderTarget, readBuffer, deltaTime); - this.accumulateIndex = 0; - } + if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { + pendingComponentWillUpdateWarnings.push(fiber); + } - var autoClear = renderer.autoClear; - renderer.autoClear = false; - var sampleWeight = 1.0 / jitterOffsets.length; + if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') { + pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); + } + }; - if (this.accumulateIndex >= 0 && this.accumulateIndex < jitterOffsets.length) { - this.copyUniforms['opacity'].value = sampleWeight; - this.copyUniforms['tDiffuse'].value = writeBuffer.texture; // render the scene multiple times, each slightly jitter offset from the last and accumulate the results. + ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () { + // We do an initial pass to gather component names + var componentWillMountUniqueNames = new Set(); - var numSamplesPerFrame = Math.pow(2, this.sampleLevel); + if (pendingComponentWillMountWarnings.length > 0) { + pendingComponentWillMountWarnings.forEach(function (fiber) { + componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingComponentWillMountWarnings = []; + } - for (let i = 0; i < numSamplesPerFrame; i++) { - var j = this.accumulateIndex; - var jitterOffset = jitterOffsets[j]; + var UNSAFE_componentWillMountUniqueNames = new Set(); - if (this.camera.setViewOffset) { - this.camera.setViewOffset(readBuffer.width, readBuffer.height, jitterOffset[0] * 0.0625, jitterOffset[1] * 0.0625, // 0.0625 = 1 / 16 - readBuffer.width, readBuffer.height); - } + if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { + pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) { + UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingUNSAFE_ComponentWillMountWarnings = []; + } - renderer.setRenderTarget(writeBuffer); - renderer.clear(); - renderer.render(this.scene, this.camera); - renderer.setRenderTarget(this.sampleRenderTarget); - if (this.accumulateIndex === 0) renderer.clear(); - this.fsQuad.render(renderer); - this.accumulateIndex++; - if (this.accumulateIndex >= jitterOffsets.length) break; - } + var componentWillReceivePropsUniqueNames = new Set(); - if (this.camera.clearViewOffset) this.camera.clearViewOffset(); - } + if (pendingComponentWillReceivePropsWarnings.length > 0) { + pendingComponentWillReceivePropsWarnings.forEach(function (fiber) { + componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingComponentWillReceivePropsWarnings = []; + } - var accumulationWeight = this.accumulateIndex * sampleWeight; + var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); - if (accumulationWeight > 0) { - this.copyUniforms['opacity'].value = 1.0; - this.copyUniforms['tDiffuse'].value = this.sampleRenderTarget.texture; - renderer.setRenderTarget(writeBuffer); - renderer.clear(); - this.fsQuad.render(renderer); - } + if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { + pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) { + UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingUNSAFE_ComponentWillReceivePropsWarnings = []; + } - if (accumulationWeight < 1.0) { - this.copyUniforms['opacity'].value = 1.0 - accumulationWeight; - this.copyUniforms['tDiffuse'].value = this.holdRenderTarget.texture; - renderer.setRenderTarget(writeBuffer); - if (accumulationWeight === 0) renderer.clear(); - this.fsQuad.render(renderer); - } + var componentWillUpdateUniqueNames = new Set(); - renderer.autoClear = autoClear; - } -}); + if (pendingComponentWillUpdateWarnings.length > 0) { + pendingComponentWillUpdateWarnings.forEach(function (fiber) { + componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingComponentWillUpdateWarnings = []; + } -/** - * Convolution shader - * ported from o3d sample to WebGL / GLSL - * http://o3d.googlecode.com/svn/trunk/samples/convolution.html - */ + var UNSAFE_componentWillUpdateUniqueNames = new Set(); -({ - defines: { - KERNEL_SIZE_FLOAT: '25.0', - KERNEL_SIZE_INT: '25' - }, - uniforms: { - tDiffuse: { - value: null - }, - uImageIncrement: { - value: new Vector2(0.001953125, 0.0) - }, - cKernel: { - value: [] - } - }, - vertexShader: ['uniform vec2 uImageIncrement;', 'varying vec2 vUv;', 'void main() {', ' vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform float cKernel[ KERNEL_SIZE_INT ];', 'uniform sampler2D tDiffuse;', 'uniform vec2 uImageIncrement;', 'varying vec2 vUv;', 'void main() {', ' vec2 imageCoord = vUv;', ' vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );', ' for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {', ' sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];', ' imageCoord += uImageIncrement;', ' }', ' gl_FragColor = sum;', '}'].join('\n'), - buildKernel: function (sigma) { - // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway. - function gauss(x, sigma) { - return Math.exp(-(x * x) / (2.0 * sigma * sigma)); - } + if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { + pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) { + UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingUNSAFE_ComponentWillUpdateWarnings = []; + } // Finally, we flush all the warnings + // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' - const kMaxKernelSize = 25; - const kernelSize = Math.min(2 * Math.ceil(sigma * 3.0) + 1, kMaxKernelSize); - const halfWidth = (kernelSize - 1) * 0.5; - const values = new Array(kernelSize); - let sum = 0.0; - for (let i = 0; i < kernelSize; ++i) { - values[i] = gauss(i - halfWidth, sigma); - sum += values[i]; - } // normalize the kernel + if (UNSAFE_componentWillMountUniqueNames.size > 0) { + var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); + error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames); + } - for (let i = 0; i < kernelSize; ++i) values[i] /= sum; + if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { + var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames); - return values; - } -}); + error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames); + } -/*********************************/ + if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { + var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames); -/********** INTERPOLATION ********/ + error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2); + } -/*********************************/ -// Spline Interpolation -// Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation + if (componentWillMountUniqueNames.size > 0) { + var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); + warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3); + } -class GLTFCubicSplineInterpolant extends Interpolant { - constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { - super(parameterPositions, sampleValues, sampleSize, resultBuffer); - } + if (componentWillReceivePropsUniqueNames.size > 0) { + var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames); - copySampleValue_(index) { - // Copies a sample value to the result buffer. See description of glTF - // CUBICSPLINE values layout in interpolate_() function below. - const result = this.resultBuffer, - values = this.sampleValues, - valueSize = this.valueSize, - offset = index * valueSize * 3 + valueSize; + warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4); + } - for (let i = 0; i !== valueSize; i++) { - result[i] = values[offset + i]; - } + if (componentWillUpdateUniqueNames.size > 0) { + var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); - return result; - } + warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5); + } + }; -} + var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. -GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; -GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; + var didWarnAboutLegacyContext = new Set(); -GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) { - const result = this.resultBuffer; - const values = this.sampleValues; - const stride = this.valueSize; - const stride2 = stride * 2; - const stride3 = stride * 3; - const td = t1 - t0; - const p = (t - t0) / td; - const pp = p * p; - const ppp = pp * p; - const offset1 = i1 * stride3; - const offset0 = offset1 - stride3; - const s2 = -2 * ppp + 3 * pp; - const s3 = ppp - pp; - const s0 = 1 - s2; - const s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations: - // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] + ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) { + var strictRoot = findStrictRoot(fiber); - for (let i = 0; i !== stride; i++) { - const p0 = values[offset0 + i + stride]; // splineVertex_k + if (strictRoot === null) { + error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - const m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k) + return; + } // Dedup strategy: Warn once per component. - const p1 = values[offset1 + i + stride]; // splineVertex_k+1 - const m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k) + if (didWarnAboutLegacyContext.has(fiber.type)) { + return; + } - result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; - } + var warningsForRoot = pendingLegacyContextWarning.get(strictRoot); - return result; -}; + if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') { + if (warningsForRoot === undefined) { + warningsForRoot = []; + pendingLegacyContextWarning.set(strictRoot, warningsForRoot); + } -new Quaternion(); + warningsForRoot.push(fiber); + } + }; -new Vector3(0, 1, 0); -new Vector3(0, 0, 1); + ReactStrictModeWarnings.flushLegacyContextWarning = function () { + pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) { + if (fiberArray.length === 0) { + return; + } -class VRButton { - static createButton(renderer, sessionInit = {}) { - const button = document.createElement('button'); + var firstFiber = fiberArray[0]; + var uniqueNames = new Set(); + fiberArray.forEach(function (fiber) { + uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutLegacyContext.add(fiber.type); + }); + var sortedNames = setToSortedString(uniqueNames); - function - /*device*/ - showEnterVR() { - let currentSession = null; + try { + setCurrentFiber(firstFiber); - async function onSessionStarted(session) { - session.addEventListener('end', onSessionEnded); - await renderer.xr.setSession(session); - button.textContent = 'EXIT VR'; - currentSession = session; - } + error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames); + } finally { + resetCurrentFiber(); + } + }); + }; - function - /*event*/ - onSessionEnded() { - currentSession.removeEventListener('end', onSessionEnded); - button.textContent = 'ENTER VR'; - currentSession = null; - } // + ReactStrictModeWarnings.discardPendingWarnings = function () { + pendingComponentWillMountWarnings = []; + pendingUNSAFE_ComponentWillMountWarnings = []; + pendingComponentWillReceivePropsWarnings = []; + pendingUNSAFE_ComponentWillReceivePropsWarnings = []; + pendingComponentWillUpdateWarnings = []; + pendingUNSAFE_ComponentWillUpdateWarnings = []; + pendingLegacyContextWarning = new Map(); + }; + } + /* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ + // $FlowFixMe only called in DEV, so void return is not possible. + function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } + } // $FlowFixMe only called in DEV, so void return is not possible. - button.style.display = ''; - button.style.cursor = 'pointer'; - button.style.left = 'calc(50% - 50px)'; - button.style.width = '100px'; - button.textContent = 'ENTER VR'; - button.onmouseenter = () => { - button.style.opacity = '1.0'; - }; + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } - button.onmouseleave = () => { - button.style.opacity = '0.5'; - }; + function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); - button.onclick = () => { - if (currentSession === null) { - var _xr; - - // WebXR's requestReferenceSpace only works if the corresponding feature - // was requested at session creation time. For simplicity, just ask for - // the interesting ones as optional features, but be aware that the - // requestReferenceSpace call will fail if it turns out to be unavailable. - // ('local' is always available for immersive sessions and doesn't need to - // be requested separately.) - const optionalFeatures = [sessionInit.optionalFeatures, 'local-floor', 'bounded-floor', 'hand-tracking'].flat().filter(Boolean); - (_xr = navigator.xr) === null || _xr === void 0 ? void 0 : _xr.requestSession('immersive-vr', { ...sessionInit, - optionalFeatures - }).then(onSessionStarted); - } else { - currentSession.end(); - } - }; - } + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } + } + function checkPropStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); - function disableButton() { - button.style.display = ''; - button.style.cursor = 'auto'; - button.style.left = 'calc(50% - 75px)'; - button.style.width = '150px'; - button.onmouseenter = null; - button.onmouseleave = null; - button.onclick = null; - } + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } + } - function showWebXRNotFound() { - disableButton(); - button.textContent = 'VR NOT SUPPORTED'; - } + function resolveDefaultProps(Component, baseProps) { + if (Component && Component.defaultProps) { + // Resolve default props. Taken from ReactElement + var props = assign({}, baseProps); + var defaultProps = Component.defaultProps; - function stylizeElement(element) { - element.style.position = 'absolute'; - element.style.bottom = '20px'; - element.style.padding = '12px 6px'; - element.style.border = '1px solid #fff'; - element.style.borderRadius = '4px'; - element.style.background = 'rgba(0,0,0,0.1)'; - element.style.color = '#fff'; - element.style.font = 'normal 13px sans-serif'; - element.style.textAlign = 'center'; - element.style.opacity = '0.5'; - element.style.outline = 'none'; - element.style.zIndex = '999'; - } + for (var propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } - if ('xr' in navigator) { - stylizeElement(button); - button.id = 'VRButton'; - button.style.display = 'none' // Query for session mode - ; - navigator.xr.isSessionSupported('immersive-vr').then(supported => { - supported ? showEnterVR() : showWebXRNotFound(); + return props; + } - if (supported && VRButton.xrSessionIsGranted) { - button.click(); - } - }); - return button; - } else { - const message = document.createElement('a'); + return baseProps; + } - if (window.isSecureContext === false) { - message.href = document.location.href.replace(/^http:/, 'https:'); - message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message - } else { - message.href = 'https://immersiveweb.dev/'; - message.innerHTML = 'WEBXR NOT AVAILABLE'; - } + var valueCursor = createCursor(null); + var rendererSigil; - message.style.left = 'calc(50% - 90px)'; - message.style.width = '180px'; - message.style.textDecoration = 'none'; - stylizeElement(message); - return message; - } - } + { + // Use this to detect multiple renderers using the same context + rendererSigil = {}; + } - static registerSessionGrantedListener() { - if ('xr' in navigator) { - navigator.xr.addEventListener('sessiongranted', () => { - VRButton.xrSessionIsGranted = true; - }); - } - } + var currentlyRenderingFiber = null; + var lastContextDependency = null; + var lastFullyObservedContext = null; + var isDisallowedContextReadInDEV = false; + function resetContextDependencies() { + // This is called right before React yields execution, to ensure `readContext` + // cannot be called outside the render phase. + currentlyRenderingFiber = null; + lastContextDependency = null; + lastFullyObservedContext = null; -} + { + isDisallowedContextReadInDEV = false; + } + } + function enterDisallowedContextReadInDEV() { + { + isDisallowedContextReadInDEV = true; + } + } + function exitDisallowedContextReadInDEV() { + { + isDisallowedContextReadInDEV = false; + } + } + function pushProvider(providerFiber, context, nextValue) { + if (isPrimaryRenderer) { + push(valueCursor, context._currentValue, providerFiber); + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } -_defineProperty$1(VRButton, "xrSessionIsGranted", false); + context._currentRenderer = rendererSigil; + } + } else { + push(valueCursor, context._currentValue2, providerFiber); + context._currentValue2 = nextValue; -/** - * @webxr-input-profiles/motion-controllers 1.0.0 https://github.com/immersive-web/webxr-input-profiles - */ -const MotionControllerConstants = { - Handedness: Object.freeze({ - NONE: 'none', - LEFT: 'left', - RIGHT: 'right' - }), - ComponentState: Object.freeze({ - DEFAULT: 'default', - TOUCHED: 'touched', - PRESSED: 'pressed' - }), - ComponentProperty: Object.freeze({ - BUTTON: 'button', - X_AXIS: 'xAxis', - Y_AXIS: 'yAxis', - STATE: 'state' - }), - ComponentType: Object.freeze({ - TRIGGER: 'trigger', - SQUEEZE: 'squeeze', - TOUCHPAD: 'touchpad', - THUMBSTICK: 'thumbstick', - BUTTON: 'button' - }), - ButtonTouchThreshold: 0.05, - AxisTouchThreshold: 0.1, - VisualResponseProperty: Object.freeze({ - TRANSFORM: 'transform', - VISIBILITY: 'visibility' - }) -}; -/** @constant {Object} */ + { + if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + context._currentRenderer2 = rendererSigil; + } + } + } + function popProvider(context, providerFiber) { + var currentValue = valueCursor.current; + pop(valueCursor, providerFiber); -({ - xAxis: 0, - yAxis: 0, - button: 0, - state: MotionControllerConstants.ComponentState.DEFAULT -}); + if (isPrimaryRenderer) { + { + context._currentValue = currentValue; + } + } else { + { + context._currentValue2 = currentValue; + } + } + } + function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { + // Update the child lanes of all the ancestors, including the alternates. + var node = parent; -new Matrix4(); + while (node !== null) { + var alternate = node.alternate; -new Vector3(); + if (!isSubsetOfLanes(node.childLanes, renderLanes)) { + node.childLanes = mergeLanes(node.childLanes, renderLanes); -/** - * Experimenting of primitive geometry creation using Surface Parametric equations - */ + if (alternate !== null) { + alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); + } + } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) { + alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); + } -const ParametricGeometries = { - klein: function (v, u, target) { - u *= Math.PI; - v *= 2 * Math.PI; - u = u * 2; - let x, y, z; + if (node === propagationRoot) { + break; + } - if (u < Math.PI) { - x = 3 * Math.cos(u) * (1 + Math.sin(u)) + 2 * (1 - Math.cos(u) / 2) * Math.cos(u) * Math.cos(v); - z = -8 * Math.sin(u) - 2 * (1 - Math.cos(u) / 2) * Math.sin(u) * Math.cos(v); - } else { - x = 3 * Math.cos(u) * (1 + Math.sin(u)) + 2 * (1 - Math.cos(u) / 2) * Math.cos(v + Math.PI); - z = -8 * Math.sin(u); - } + node = node.return; + } - y = -2 * (1 - Math.cos(u) / 2) * Math.sin(v); - target.set(x, y, z); - }, - plane: function (width, height) { - return (u, v, target) => { - const x = u * width; - const y = 0; - const z = v * height; - target.set(x, y, z); - }; - }, - mobius: function (u, t, target) { - // flat mobius strip - // http://www.wolframalpha.com/input/?i=M%C3%B6bius+strip+parametric+equations&lk=1&a=ClashPrefs_*Surface.MoebiusStrip.SurfaceProperty.ParametricEquations- - u = u - 0.5; - const v = 2 * Math.PI * t; - let x, y, z; - const a = 2; - x = Math.cos(v) * (a + u * Math.cos(v / 2)); - y = Math.sin(v) * (a + u * Math.cos(v / 2)); - z = u * Math.sin(v / 2); - target.set(x, y, z); - }, - mobius3d: function (u, t, target) { - // volumetric mobius strip - u *= Math.PI; - t *= 2 * Math.PI; - u = u * 2; - const phi = u / 2; - const major = 2.25, - a = 0.125, - b = 0.65; - let x, y, z; - x = a * Math.cos(t) * Math.cos(phi) - b * Math.sin(t) * Math.sin(phi); - z = a * Math.cos(t) * Math.sin(phi) + b * Math.sin(t) * Math.cos(phi); - y = (major + x) * Math.sin(u); - x = (major + x) * Math.cos(u); - target.set(x, y, z); - } -}; -/********************************************* - * - * Parametric Replacement for TubeGeometry - * - *********************************************/ - -ParametricGeometries.TubeGeometry = function (path, segments, radius, segmentsRadius, closed) { - this.path = path; - this.segments = segments || 64; - this.radius = radius || 1; - this.segmentsRadius = segmentsRadius || 8; - this.closed = closed || false; - const scope = this, - numpoints = this.segments + 1; - const frames = path.computeFrenetFrames(segments, closed), - tangents = frames.tangents, - normals = frames.normals, - binormals = frames.binormals; // proxy internals - - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; - const position = new Vector3(); - - const ParametricTube = (u, v, target) => { - v *= 2 * Math.PI; - let i = u * (numpoints - 1); - i = Math.floor(i); - path.getPointAt(u, position); - const normal = normals[i]; - const binormal = binormals[i]; - const cx = -scope.radius * Math.cos(v); // TODO: Hack: Negating it so it faces outside. - - const cy = scope.radius * Math.sin(v); - position.x += cx * normal.x + cy * binormal.x; - position.y += cx * normal.y + cy * binormal.y; - position.z += cx * normal.z + cy * binormal.z; - target.copy(position); - }; + { + if (node !== propagationRoot) { + error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } + } + } + function propagateContextChange(workInProgress, context, renderLanes) { + { + propagateContextChange_eager(workInProgress, context, renderLanes); + } + } - ParametricGeometry.call(this, ParametricTube, segments, segmentsRadius); -}; + function propagateContextChange_eager(workInProgress, context, renderLanes) { -ParametricGeometries.TubeGeometry.prototype = Object.create(BufferGeometry.prototype); -ParametricGeometries.TubeGeometry.prototype.constructor = ParametricGeometries.TubeGeometry; -/********************************************* - * - * Parametric Replacement for TorusKnotGeometry - * - *********************************************/ + var fiber = workInProgress.child; -ParametricGeometries.TorusKnotGeometry = function (radius, tube, segmentsT, segmentsR, p, q) { - this.radius = radius || 200; - this.tube = tube || 40; - this.segmentsT = segmentsT || 64; - this.segmentsR = segmentsR || 8; - this.p = p || 2; - this.q = q || 3; + if (fiber !== null) { + // Set the return pointer of the child to the work-in-progress fiber. + fiber.return = workInProgress; + } - class TorusKnotCurve extends Curve { - constructor() { - super(); - } + while (fiber !== null) { + var nextFiber = void 0; // Visit this fiber. - getPoint(t, optionalTarget) { - const point = optionalTarget || new Vector3(); - t *= Math.PI * 2; - const r = 0.5; - const x = (1 + r * Math.cos(q * t)) * Math.cos(p * t); - const y = (1 + r * Math.cos(q * t)) * Math.sin(p * t); - const z = r * Math.sin(q * t); - return point.set(x, y, z).multiplyScalar(radius); - } + var list = fiber.dependencies; - } + if (list !== null) { + nextFiber = fiber.child; + var dependency = list.firstContext; - const segments = segmentsT; - const radiusSegments = segmentsR; - const extrudePath = new TorusKnotCurve(); - ParametricGeometries.TubeGeometry.call(this, extrudePath, segments, tube, radiusSegments, true, false); -}; + while (dependency !== null) { + // Check if the context matches. + if (dependency.context === context) { + // Match! Schedule an update on this fiber. + if (fiber.tag === ClassComponent) { + // Schedule a force update on the work-in-progress. + var lane = pickArbitraryLane(renderLanes); + var update = createUpdate(NoTimestamp, lane); + update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the + // update to the current fiber, too, which means it will persist even if + // this render is thrown away. Since it's a race condition, not sure it's + // worth fixing. + // Inlined `enqueueUpdate` to remove interleaved update check -ParametricGeometries.TorusKnotGeometry.prototype = Object.create(BufferGeometry.prototype); -ParametricGeometries.TorusKnotGeometry.prototype.constructor = ParametricGeometries.TorusKnotGeometry; -/********************************************* - * - * Parametric Replacement for SphereGeometry - * - *********************************************/ + var updateQueue = fiber.updateQueue; -ParametricGeometries.SphereGeometry = function (size, u, v) { - function sphere(u, v, target) { - u *= Math.PI; - v *= 2 * Math.PI; - const x = size * Math.sin(u) * Math.cos(v); - const y = size * Math.sin(u) * Math.sin(v); - const z = size * Math.cos(u); - target.set(x, y, z); - } + if (updateQueue === null) ; else { + var sharedQueue = updateQueue.shared; + var pending = sharedQueue.pending; - ParametricGeometry.call(this, sphere, u, v); -}; + if (pending === null) { + // This is the first update. Create a circular list. + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } -ParametricGeometries.SphereGeometry.prototype = Object.create(BufferGeometry.prototype); -ParametricGeometries.SphereGeometry.prototype.constructor = ParametricGeometries.SphereGeometry; -/********************************************* - * - * Parametric Replacement for PlaneGeometry - * - *********************************************/ + sharedQueue.pending = update; + } + } -ParametricGeometries.PlaneGeometry = function (width, depth, segmentsWidth, segmentsDepth) { - function plane(u, v, target) { - const x = u * width; - const y = 0; - const z = v * depth; - target.set(x, y, z); - } + fiber.lanes = mergeLanes(fiber.lanes, renderLanes); + var alternate = fiber.alternate; - ParametricGeometry.call(this, plane, segmentsWidth, segmentsDepth); -}; + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, renderLanes); + } -ParametricGeometries.PlaneGeometry.prototype = Object.create(BufferGeometry.prototype); -ParametricGeometries.PlaneGeometry.prototype.constructor = ParametricGeometries.PlaneGeometry; + scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too. -new Vector3(); + list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the + // dependency list. -const inverseProjectionMatrix = new Matrix4(); -class Frustum { - constructor(data) { - data = data || {}; - this.vertices = { - near: [new Vector3(), new Vector3(), new Vector3(), new Vector3()], - far: [new Vector3(), new Vector3(), new Vector3(), new Vector3()] - }; + break; + } - if (data.projectionMatrix !== undefined) { - this.setFromProjectionMatrix(data.projectionMatrix, data.maxFar || 10000); - } - } + dependency = dependency.next; + } + } else if (fiber.tag === ContextProvider) { + // Don't scan deeper if this is a matching provider + nextFiber = fiber.type === workInProgress.type ? null : fiber.child; + } else if ( fiber.tag === DehydratedFragment) { + // If a dehydrated suspense boundary is in this subtree, we don't know + // if it will have any context consumers in it. The best we can do is + // mark it as having updates. + var parentSuspense = fiber.return; - setFromProjectionMatrix(projectionMatrix, maxFar) { - const isOrthographic = projectionMatrix.elements[2 * 4 + 3] === 0; - inverseProjectionMatrix.copy(projectionMatrix).invert(); // 3 --- 0 vertices.near/far order - // | | - // 2 --- 1 - // clip space spans from [-1, 1] + if (parentSuspense === null) { + throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.'); + } - this.vertices.near[0].set(1, 1, -1); - this.vertices.near[1].set(1, -1, -1); - this.vertices.near[2].set(-1, -1, -1); - this.vertices.near[3].set(-1, 1, -1); - this.vertices.near.forEach(v => { - v.applyMatrix4(inverseProjectionMatrix); - }); - this.vertices.far[0].set(1, 1, 1); - this.vertices.far[1].set(1, -1, 1); - this.vertices.far[2].set(-1, -1, 1); - this.vertices.far[3].set(-1, 1, 1); - this.vertices.far.forEach(v => { - v.applyMatrix4(inverseProjectionMatrix); - const absZ = Math.abs(v.z); - - if (isOrthographic) { - v.z *= Math.min(maxFar / absZ, 1.0); - } else { - v.multiplyScalar(Math.min(maxFar / absZ, 1.0)); - } - }); - return this.vertices; - } + parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); + var _alternate = parentSuspense.alternate; - split(breaks, target) { - while (breaks.length > target.length) { - target.push(new Frustum()); - } + if (_alternate !== null) { + _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes); + } // This is intentionally passing this fiber as the parent + // because we want to schedule this fiber as having work + // on its children. We'll use the childLanes on + // this fiber to indicate that a context has changed. - target.length = breaks.length; - for (let i = 0; i < breaks.length; i++) { - const cascade = target[i]; + scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress); + nextFiber = fiber.sibling; + } else { + // Traverse down. + nextFiber = fiber.child; + } - if (i === 0) { - for (let j = 0; j < 4; j++) { - cascade.vertices.near[j].copy(this.vertices.near[j]); - } - } else { - for (let j = 0; j < 4; j++) { - cascade.vertices.near[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i - 1]); - } - } + if (nextFiber !== null) { + // Set the return pointer of the child to the work-in-progress fiber. + nextFiber.return = fiber; + } else { + // No child. Traverse to next sibling. + nextFiber = fiber; - if (i === breaks - 1) { - for (let j = 0; j < 4; j++) { - cascade.vertices.far[j].copy(this.vertices.far[j]); - } - } else { - for (let j = 0; j < 4; j++) { - cascade.vertices.far[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i]); - } - } - } - } + while (nextFiber !== null) { + if (nextFiber === workInProgress) { + // We're back to the root of this subtree. Exit. + nextFiber = null; + break; + } - toSpace(cameraMatrix, target) { - for (let i = 0; i < 4; i++) { - target.vertices.near[i].copy(this.vertices.near[i]).applyMatrix4(cameraMatrix); - target.vertices.far[i].copy(this.vertices.far[i]).applyMatrix4(cameraMatrix); - } - } + var sibling = nextFiber.sibling; -} + if (sibling !== null) { + // Set the return pointer of the sibling to the work-in-progress fiber. + sibling.return = nextFiber.return; + nextFiber = sibling; + break; + } // No more siblings. Traverse up. -({ - lights_fragment_begin: - /* glsl */ - ` -GeometricContext geometry; -geometry.position = - vViewPosition; -geometry.normal = normal; -geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + nextFiber = nextFiber.return; + } + } -#ifdef CLEARCOAT + fiber = nextFiber; + } + } + function prepareToReadContext(workInProgress, renderLanes) { + currentlyRenderingFiber = workInProgress; + lastContextDependency = null; + lastFullyObservedContext = null; + var dependencies = workInProgress.dependencies; - geometry.clearcoatNormal = clearcoatNormal; + if (dependencies !== null) { + { + var firstContext = dependencies.firstContext; -#endif + if (firstContext !== null) { + if (includesSomeLane(dependencies.lanes, renderLanes)) { + // Context list has a pending update. Mark that this fiber performed work. + markWorkInProgressReceivedUpdate(); + } // Reset the work-in-progress list -IncidentLight directLight; -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + dependencies.firstContext = null; + } + } + } + } + function readContext(context) { + { + // This warning would fire if you read context inside a Hook like useMemo. + // Unlike the class check below, it's not enforced in production for perf. + if (isDisallowedContextReadInDEV) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif + var value = isPrimaryRenderer ? context._currentValue : context._currentValue2; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + if (lastFullyObservedContext === context) ; else { + var contextItem = { + context: context, + memoizedValue: value, + next: null + }; - pointLight = pointLights[ i ]; + if (lastContextDependency === null) { + if (currentlyRenderingFiber === null) { + throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } // This is the first dependency for this component. Create a new list. - getPointLightInfo( pointLight, geometry, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif + lastContextDependency = contextItem; + currentlyRenderingFiber.dependencies = { + lanes: NoLanes, + firstContext: contextItem + }; + } else { + // Append a new context item. + lastContextDependency = lastContextDependency.next = contextItem; + } + } - RE_Direct( directLight, geometry, material, reflectedLight ); + return value; + } + // An array of all update queues that received updates during the current + // render. When this render exits, either because it finishes or because it is + // interrupted, the interleaved updates will be transferred onto the main part + // of the queue. + var interleavedQueues = null; + function pushInterleavedQueue(queue) { + if (interleavedQueues === null) { + interleavedQueues = [queue]; + } else { + interleavedQueues.push(queue); + } } - #pragma unroll_loop_end + function enqueueInterleavedUpdates() { + // Transfer the interleaved updates onto the main queue. Each queue has a + // `pending` field and an `interleaved` field. When they are not null, they + // point to the last node in a circular linked list. We need to append the + // interleaved list to the end of the pending list by joining them into a + // single, circular list. + if (interleavedQueues !== null) { + for (var i = 0; i < interleavedQueues.length; i++) { + var queue = interleavedQueues[i]; + var lastInterleavedUpdate = queue.interleaved; -#endif + if (lastInterleavedUpdate !== null) { + queue.interleaved = null; + var firstInterleavedUpdate = lastInterleavedUpdate.next; + var lastPendingUpdate = queue.pending; -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + if (lastPendingUpdate !== null) { + var firstPendingUpdate = lastPendingUpdate.next; + lastPendingUpdate.next = firstInterleavedUpdate; + lastInterleavedUpdate.next = firstPendingUpdate; + } - SpotLight spotLight; - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif + queue.pending = lastInterleavedUpdate; + } + } - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + interleavedQueues = null; + } + } - spotLight = spotLights[ i ]; + var UpdateState = 0; + var ReplaceState = 1; + var ForceUpdate = 2; + var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. + // It should only be read right after calling `processUpdateQueue`, via + // `checkHasForceUpdateAfterProcessing`. - getSpotLightInfo( spotLight, geometry, directLight ); + var hasForceUpdate = false; + var didWarnUpdateInsideUpdate; + var currentlyProcessingQueue; - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; - #endif + { + didWarnUpdateInsideUpdate = false; + currentlyProcessingQueue = null; + } - RE_Direct( directLight, geometry, material, reflectedLight ); + function initializeUpdateQueue(fiber) { + var queue = { + baseState: fiber.memoizedState, + firstBaseUpdate: null, + lastBaseUpdate: null, + shared: { + pending: null, + interleaved: null, + lanes: NoLanes + }, + effects: null + }; + fiber.updateQueue = queue; + } + function cloneUpdateQueue(current, workInProgress) { + // Clone the update queue from current. Unless it's already a clone. + var queue = workInProgress.updateQueue; + var currentQueue = current.updateQueue; + if (queue === currentQueue) { + var clone = { + baseState: currentQueue.baseState, + firstBaseUpdate: currentQueue.firstBaseUpdate, + lastBaseUpdate: currentQueue.lastBaseUpdate, + shared: currentQueue.shared, + effects: currentQueue.effects + }; + workInProgress.updateQueue = clone; + } } - #pragma unroll_loop_end + function createUpdate(eventTime, lane) { + var update = { + eventTime: eventTime, + lane: lane, + tag: UpdateState, + payload: null, + callback: null, + next: null + }; + return update; + } + function enqueueUpdate(fiber, update, lane) { + var updateQueue = fiber.updateQueue; -#endif + if (updateQueue === null) { + // Only occurs if the fiber has been unmounted. + return; + } -#if ( NUM_DIR_LIGHTS > 0) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES ) + var sharedQueue = updateQueue.shared; - DirectionalLight directionalLight; - float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear); - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif + if (isInterleavedUpdate(fiber)) { + var interleaved = sharedQueue.interleaved; - #if defined( USE_SHADOWMAP ) && defined( CSM_FADE ) - vec2 cascade; - float cascadeCenter; - float closestEdge; - float margin; - float csmx; - float csmy; + if (interleaved === null) { + // This is the first update. Create a circular list. + update.next = update; // At the end of the current render, this queue's interleaved updates will + // be transferred to the pending queue. - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + pushInterleavedQueue(sharedQueue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, geometry, directLight ); + sharedQueue.interleaved = update; + } else { + var pending = sharedQueue.pending; - // NOTE: Depth gets larger away from the camera. - // cascade.x is closer, cascade.y is further - cascade = CSM_cascades[ i ]; - cascadeCenter = ( cascade.x + cascade.y ) / 2.0; - closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; - margin = 0.25 * pow( closestEdge, 2.0 ); - csmx = cascade.x - margin / 2.0; - csmy = cascade.y + margin / 2.0; - if( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS && linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) { + if (pending === null) { + // This is the first update. Create a circular list. + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } - float dist = min( linearDepth - csmx, csmy - linearDepth ); - float ratio = clamp( dist / margin, 0.0, 1.0 ); - if( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) { + sharedQueue.pending = update; + } - vec3 prevColor = directLight.color; - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + { + if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) { + error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); - bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter; - directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); + didWarnUpdateInsideUpdate = true; + } + } + } + function entangleTransitions(root, fiber, lane) { + var updateQueue = fiber.updateQueue; - } + if (updateQueue === null) { + // Only occurs if the fiber has been unmounted. + return; + } - ReflectedLight prevLight = reflectedLight; - RE_Direct( directLight, geometry, material, reflectedLight ); + var sharedQueue = updateQueue.shared; - bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter; - float blendRatio = shouldBlend ? ratio : 1.0; + if (isTransitionLane(lane)) { + var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must + // have finished. We can remove them from the shared queue, which represents + // a superset of the actually pending lanes. In some cases we may entangle + // more than we need to, but that's OK. In fact it's worse if we *don't* + // entangle when we should. - reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); - reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio ); - reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio ); - reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio ); + queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. - } + var newQueueLanes = mergeLanes(queueLanes, lane); + sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if + // the lane finished since the last time we entangled it. So we need to + // entangle it again, just to be sure. + markRootEntangled(root, newQueueLanes); + } } - #pragma unroll_loop_end - #else - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, geometry, directLight ); - - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - - directionalLightShadow = directionalLightShadows[ i ]; - if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + function enqueueCapturedUpdate(workInProgress, capturedUpdate) { + // Captured updates are updates that are thrown by a child during the render + // phase. They should be discarded if the render is aborted. Therefore, + // we should only put them on the work-in-progress queue, not the current one. + var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone. - #endif + var current = workInProgress.alternate; - if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometry, material, reflectedLight ); + if (current !== null) { + var currentQueue = current.updateQueue; - } - #pragma unroll_loop_end + if (queue === currentQueue) { + // The work-in-progress queue is the same as current. This happens when + // we bail out on a parent fiber that then captures an error thrown by + // a child. Since we want to append the update only to the work-in + // -progress queue, we need to clone the updates. We usually clone during + // processUpdateQueue, but that didn't happen in this case because we + // skipped over the parent when we bailed out. + var newFirst = null; + var newLast = null; + var firstBaseUpdate = queue.firstBaseUpdate; - #endif + if (firstBaseUpdate !== null) { + // Loop through the updates and clone them. + var update = firstBaseUpdate; -#endif + do { + var clone = { + eventTime: update.eventTime, + lane: update.lane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; + if (newLast === null) { + newFirst = newLast = clone; + } else { + newLast.next = clone; + newLast = clone; + } -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES ) + update = update.next; + } while (update !== null); // Append the captured update the end of the cloned list. - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + if (newLast === null) { + newFirst = newLast = capturedUpdate; + } else { + newLast.next = capturedUpdate; + newLast = capturedUpdate; + } + } else { + // There are no base updates. + newFirst = newLast = capturedUpdate; + } - directionalLight = directionalLights[ i ]; + queue = { + baseState: currentQueue.baseState, + firstBaseUpdate: newFirst, + lastBaseUpdate: newLast, + shared: currentQueue.shared, + effects: currentQueue.effects + }; + workInProgress.updateQueue = queue; + return; + } + } // Append the update to the end of the list. - getDirectionalLightInfo( directionalLight, geometry, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif + var lastBaseUpdate = queue.lastBaseUpdate; - RE_Direct( directLight, geometry, material, reflectedLight ); + if (lastBaseUpdate === null) { + queue.firstBaseUpdate = capturedUpdate; + } else { + lastBaseUpdate.next = capturedUpdate; + } + queue.lastBaseUpdate = capturedUpdate; } - #pragma unroll_loop_end - -#endif -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) { + switch (update.tag) { + case ReplaceState: + { + var payload = update.payload; - RectAreaLight rectAreaLight; + if (typeof payload === 'function') { + // Updater function + { + enterDisallowedContextReadInDEV(); + } - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + var nextState = payload.call(instance, prevState, nextProps); - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight ); + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - } - #pragma unroll_loop_end + try { + payload.call(instance, prevState, nextProps); + } finally { + setIsStrictModeForDevtools(false); + } + } -#endif + exitDisallowedContextReadInDEV(); + } -#if defined( RE_IndirectDiffuse ) + return nextState; + } // State object - vec3 iblIrradiance = vec3( 0.0 ); - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + return payload; + } - irradiance += getLightProbeIrradiance( lightProbe, geometry.normal ); + case CaptureUpdate: + { + workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture; + } + // Intentional fallthrough - #if ( NUM_HEMI_LIGHTS > 0 ) + case UpdateState: + { + var _payload = update.payload; + var partialState; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + if (typeof _payload === 'function') { + // Updater function + { + enterDisallowedContextReadInDEV(); + } - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); + partialState = _payload.call(instance, prevState, nextProps); - } - #pragma unroll_loop_end + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - #endif + try { + _payload.call(instance, prevState, nextProps); + } finally { + setIsStrictModeForDevtools(false); + } + } -#endif + exitDisallowedContextReadInDEV(); + } + } else { + // Partial state object + partialState = _payload; + } -#if defined( RE_IndirectSpecular ) + if (partialState === null || partialState === undefined) { + // Null and undefined are treated as no-ops. + return prevState; + } // Merge the partial state and the previous state. - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); -#endif -`, - lights_pars_begin: - /* glsl */ - ` -#if defined( USE_CSM ) && defined( CSM_CASCADES ) -uniform vec2 CSM_cascades[CSM_CASCADES]; -uniform float cameraNear; -uniform float shadowFar; -#endif - ` + ShaderChunk.lights_pars_begin -}); + return assign({}, prevState, partialState); + } -new Matrix4(); + case ForceUpdate: + { + hasForceUpdate = true; + return prevState; + } + } -new Frustum(); + return prevState; + } -new Vector3(); + function processUpdateQueue(workInProgress, props, instance, renderLanes) { + // This is always non-null on a ClassComponent or HostRoot + var queue = workInProgress.updateQueue; + hasForceUpdate = false; -new Box3(); + { + currentlyProcessingQueue = queue.shared; + } -/** - * This is a class to check whether objects are in a selection area in 3D space - */ + var firstBaseUpdate = queue.firstBaseUpdate; + var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue. -(() => { - const frustum = new Frustum$1(); - const center = new Vector3(); - const tmpPoint = new Vector3(); - const vecNear = new Vector3(); - const vecTopLeft = new Vector3(); - const vecTopRight = new Vector3(); - const vecDownRight = new Vector3(); - const vecDownLeft = new Vector3(); - const vecFarTopLeft = new Vector3(); - const vecFarTopRight = new Vector3(); - const vecFarDownRight = new Vector3(); - const vecFarDownLeft = new Vector3(); - const vectemp1 = new Vector3(); - const vectemp2 = new Vector3(); - const vectemp3 = new Vector3(); - - class SelectionBox { - constructor(camera, scene, deep) { - this.camera = camera; - this.scene = scene; - this.startPoint = new Vector3(); - this.endPoint = new Vector3(); - this.collection = []; - this.deep = deep || Number.MAX_VALUE; - } + var pendingQueue = queue.shared.pending; - select(startPoint, endPoint) { - this.startPoint = startPoint || this.startPoint; - this.endPoint = endPoint || this.endPoint; - this.collection = []; - this.updateFrustum(this.startPoint, this.endPoint); - this.searchChildInFrustum(frustum, this.scene); - return this.collection; - } + if (pendingQueue !== null) { + queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first + // and last so that it's non-circular. - updateFrustum(startPoint, endPoint) { - startPoint = startPoint || this.startPoint; - endPoint = endPoint || this.endPoint; // Avoid invalid frustum + var lastPendingUpdate = pendingQueue; + var firstPendingUpdate = lastPendingUpdate.next; + lastPendingUpdate.next = null; // Append pending updates to base queue - if (startPoint.x === endPoint.x) { - endPoint.x += Number.EPSILON; - } + if (lastBaseUpdate === null) { + firstBaseUpdate = firstPendingUpdate; + } else { + lastBaseUpdate.next = firstPendingUpdate; + } - if (startPoint.y === endPoint.y) { - endPoint.y += Number.EPSILON; - } + lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then + // we need to transfer the updates to that queue, too. Because the base + // queue is a singly-linked list with no cycles, we can append to both + // lists and take advantage of structural sharing. + // TODO: Pass `current` as argument - this.camera.updateProjectionMatrix(); - this.camera.updateMatrixWorld(); - - if (this.camera.isPerspectiveCamera) { - tmpPoint.copy(startPoint); - tmpPoint.x = Math.min(startPoint.x, endPoint.x); - tmpPoint.y = Math.max(startPoint.y, endPoint.y); - endPoint.x = Math.max(startPoint.x, endPoint.x); - endPoint.y = Math.min(startPoint.y, endPoint.y); - vecNear.setFromMatrixPosition(this.camera.matrixWorld); - vecTopLeft.copy(tmpPoint); - vecTopRight.set(endPoint.x, tmpPoint.y, 0); - vecDownRight.copy(endPoint); - vecDownLeft.set(tmpPoint.x, endPoint.y, 0); - vecTopLeft.unproject(this.camera); - vecTopRight.unproject(this.camera); - vecDownRight.unproject(this.camera); - vecDownLeft.unproject(this.camera); - vectemp1.copy(vecTopLeft).sub(vecNear); - vectemp2.copy(vecTopRight).sub(vecNear); - vectemp3.copy(vecDownRight).sub(vecNear); - vectemp1.normalize(); - vectemp2.normalize(); - vectemp3.normalize(); - vectemp1.multiplyScalar(this.deep); - vectemp2.multiplyScalar(this.deep); - vectemp3.multiplyScalar(this.deep); - vectemp1.add(vecNear); - vectemp2.add(vecNear); - vectemp3.add(vecNear); - var planes = frustum.planes; - planes[0].setFromCoplanarPoints(vecNear, vecTopLeft, vecTopRight); - planes[1].setFromCoplanarPoints(vecNear, vecTopRight, vecDownRight); - planes[2].setFromCoplanarPoints(vecDownRight, vecDownLeft, vecNear); - planes[3].setFromCoplanarPoints(vecDownLeft, vecTopLeft, vecNear); - planes[4].setFromCoplanarPoints(vecTopRight, vecDownRight, vecDownLeft); - planes[5].setFromCoplanarPoints(vectemp3, vectemp2, vectemp1); - planes[5].normal.multiplyScalar(-1); - } else if (this.camera.isOrthographicCamera) { - const left = Math.min(startPoint.x, endPoint.x); - const top = Math.max(startPoint.y, endPoint.y); - const right = Math.max(startPoint.x, endPoint.x); - const down = Math.min(startPoint.y, endPoint.y); - vecTopLeft.set(left, top, -1); - vecTopRight.set(right, top, -1); - vecDownRight.set(right, down, -1); - vecDownLeft.set(left, down, -1); - vecFarTopLeft.set(left, top, 1); - vecFarTopRight.set(right, top, 1); - vecFarDownRight.set(right, down, 1); - vecFarDownLeft.set(left, down, 1); - vecTopLeft.unproject(this.camera); - vecTopRight.unproject(this.camera); - vecDownRight.unproject(this.camera); - vecDownLeft.unproject(this.camera); - vecFarTopLeft.unproject(this.camera); - vecFarTopRight.unproject(this.camera); - vecFarDownRight.unproject(this.camera); - vecFarDownLeft.unproject(this.camera); - var planes = frustum.planes; - planes[0].setFromCoplanarPoints(vecTopLeft, vecFarTopLeft, vecFarTopRight); - planes[1].setFromCoplanarPoints(vecTopRight, vecFarTopRight, vecFarDownRight); - planes[2].setFromCoplanarPoints(vecFarDownRight, vecFarDownLeft, vecDownLeft); - planes[3].setFromCoplanarPoints(vecFarDownLeft, vecFarTopLeft, vecTopLeft); - planes[4].setFromCoplanarPoints(vecTopRight, vecDownRight, vecDownLeft); - planes[5].setFromCoplanarPoints(vecFarDownRight, vecFarTopRight, vecFarTopLeft); - planes[5].normal.multiplyScalar(-1); - } else { - console.error('THREE.SelectionBox: Unsupported camera type.'); - } - } + var current = workInProgress.alternate; - searchChildInFrustum(frustum, object) { - if (object.isMesh || object.isLine || object.isPoints) { - if (object.material !== undefined) { - if (object.geometry.boundingSphere === null) object.geometry.computeBoundingSphere(); - center.copy(object.geometry.boundingSphere.center); - center.applyMatrix4(object.matrixWorld); + if (current !== null) { + // This is always non-null on a ClassComponent or HostRoot + var currentQueue = current.updateQueue; + var currentLastBaseUpdate = currentQueue.lastBaseUpdate; - if (frustum.containsPoint(center)) { - this.collection.push(object); - } - } - } + if (currentLastBaseUpdate !== lastBaseUpdate) { + if (currentLastBaseUpdate === null) { + currentQueue.firstBaseUpdate = firstPendingUpdate; + } else { + currentLastBaseUpdate.next = firstPendingUpdate; + } - if (object.children.length > 0) { - for (let x = 0; x < object.children.length; x++) { - this.searchChildInFrustum(frustum, object.children[x]); - } - } - } + currentQueue.lastBaseUpdate = lastPendingUpdate; + } + } + } // These values may change as we process the queue. - } - return SelectionBox; -})(); + if (firstBaseUpdate !== null) { + // Iterate through the list of updates to compute the result. + var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes + // from the original lanes. -new Euler(); -new Vector3(); // generate transformation from FBX transform data + var newLanes = NoLanes; + var newBaseState = null; + var newFirstBaseUpdate = null; + var newLastBaseUpdate = null; + var update = firstBaseUpdate; -class Font$1 { - constructor(data) { - _defineProperty$1(this, "data", void 0); + do { + var updateLane = update.lane; + var updateEventTime = update.eventTime; - this.data = data; - } + if (!isSubsetOfLanes(renderLanes, updateLane)) { + // Priority is insufficient. Skip this update. If this is the first + // skipped update, the previous update/state is the new base + // update/state. + var clone = { + eventTime: updateEventTime, + lane: updateLane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; - generateShapes(text, size = 100) { - const shapes = []; - const paths = createPaths(text, size, this.data); + if (newLastBaseUpdate === null) { + newFirstBaseUpdate = newLastBaseUpdate = clone; + newBaseState = newState; + } else { + newLastBaseUpdate = newLastBaseUpdate.next = clone; + } // Update the remaining priority in the queue. - for (let p = 0, pl = paths.length; p < pl; p++) { - Array.prototype.push.apply(shapes, paths[p].toShapes(false)); - } - return shapes; - } + newLanes = mergeLanes(newLanes, updateLane); + } else { + // This update does have sufficient priority. + if (newLastBaseUpdate !== null) { + var _clone = { + eventTime: updateEventTime, + // This update is going to be committed so we never want uncommit + // it. Using NoLane works because 0 is a subset of all bitmasks, so + // this will never be skipped by the check above. + lane: NoLane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; + newLastBaseUpdate = newLastBaseUpdate.next = _clone; + } // Process this update. -} -_defineProperty$1(Font$1, "isFont", void 0); + newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance); + var callback = update.callback; -_defineProperty$1(Font$1, "type", void 0); + if (callback !== null && // If the update was already committed, we should not queue its + // callback again. + update.lane !== NoLane) { + workInProgress.flags |= Callback; + var effects = queue.effects; -function createPaths(text, size, data) { - const chars = Array.from(text); - const scale = size / data.resolution; - const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale; - const paths = []; - let offsetX = 0, - offsetY = 0; + if (effects === null) { + queue.effects = [update]; + } else { + effects.push(update); + } + } + } - for (let i = 0; i < chars.length; i++) { - const char = chars[i]; + update = update.next; - if (char === '\n') { - offsetX = 0; - offsetY -= line_height; - } else { - const ret = createPath(char, scale, offsetX, offsetY, data); + if (update === null) { + pendingQueue = queue.shared.pending; - if (ret) { - offsetX += ret.offsetX; - paths.push(ret.path); - } - } - } + if (pendingQueue === null) { + break; + } else { + // An update was scheduled from inside a reducer. Add the new + // pending updates to the end of the list and keep processing. + var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we + // unravel them when transferring them to the base queue. - return paths; -} + var _firstPendingUpdate = _lastPendingUpdate.next; + _lastPendingUpdate.next = null; + update = _firstPendingUpdate; + queue.lastBaseUpdate = _lastPendingUpdate; + queue.shared.pending = null; + } + } + } while (true); -function createPath(char, scale, offsetX, offsetY, data) { - const glyph = data.glyphs[char] || data.glyphs['?']; + if (newLastBaseUpdate === null) { + newBaseState = newState; + } - if (!glyph) { - console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.'); - return; - } + queue.baseState = newBaseState; + queue.firstBaseUpdate = newFirstBaseUpdate; + queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to + // process them during this render, but we do need to track which lanes + // are remaining. - const path = new ShapePath(); - let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; + var lastInterleaved = queue.shared.interleaved; - if (glyph.o) { - const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' ')); + if (lastInterleaved !== null) { + var interleaved = lastInterleaved; - for (let i = 0, l = outline.length; i < l;) { - const action = outline[i++]; + do { + newLanes = mergeLanes(newLanes, interleaved.lane); + interleaved = interleaved.next; + } while (interleaved !== lastInterleaved); + } else if (firstBaseUpdate === null) { + // `queue.lanes` is used for entangling transitions. We can set it back to + // zero once the queue is empty. + queue.shared.lanes = NoLanes; + } // Set the remaining expiration time to be whatever is remaining in the queue. + // This should be fine because the only two other things that contribute to + // expiration time are props and context. We're already in the middle of the + // begin phase by the time we start processing the queue, so we've already + // dealt with the props. Context in components that specify + // shouldComponentUpdate is tricky; but we'll have to account for + // that regardless. - switch (action) { - case 'm': - // moveTo - x = parseInt(outline[i++]) * scale + offsetX; - y = parseInt(outline[i++]) * scale + offsetY; - path.moveTo(x, y); - break; - case 'l': - // lineTo - x = parseInt(outline[i++]) * scale + offsetX; - y = parseInt(outline[i++]) * scale + offsetY; - path.lineTo(x, y); - break; + markSkippedUpdateLanes(newLanes); + workInProgress.lanes = newLanes; + workInProgress.memoizedState = newState; + } - case 'q': - // quadraticCurveTo - cpx = parseInt(outline[i++]) * scale + offsetX; - cpy = parseInt(outline[i++]) * scale + offsetY; - cpx1 = parseInt(outline[i++]) * scale + offsetX; - cpy1 = parseInt(outline[i++]) * scale + offsetY; - path.quadraticCurveTo(cpx1, cpy1, cpx, cpy); - break; + { + currentlyProcessingQueue = null; + } + } - case 'b': - // bezierCurveTo - cpx = parseInt(outline[i++]) * scale + offsetX; - cpy = parseInt(outline[i++]) * scale + offsetY; - cpx1 = parseInt(outline[i++]) * scale + offsetX; - cpy1 = parseInt(outline[i++]) * scale + offsetY; - cpx2 = parseInt(outline[i++]) * scale + offsetX; - cpy2 = parseInt(outline[i++]) * scale + offsetY; - path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy); - break; - } - } - } + function callCallback(callback, context) { + if (typeof callback !== 'function') { + throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback)); + } - return { - offsetX: glyph.ha * scale, - path - }; -} + callback.call(context); + } -(function () { - var classCallCheck = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError('Cannot call a class as a function'); - } - }; + function resetHasForceUpdateBeforeProcessing() { + hasForceUpdate = false; + } + function checkHasForceUpdateAfterProcessing() { + return hasForceUpdate; + } + function commitUpdateQueue(finishedWork, finishedQueue, instance) { + // Commit the effects + var effects = finishedQueue.effects; + finishedQueue.effects = null; - var createClass = function () { - function defineProperties(target, props) { - for (let i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ('value' in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } + if (effects !== null) { + for (var i = 0; i < effects.length; i++) { + var effect = effects[i]; + var callback = effect.callback; - return function (Constructor, protoProps, staticProps) { - if (protoProps) defineProperties(Constructor.prototype, protoProps); - if (staticProps) defineProperties(Constructor, staticProps); - return Constructor; - }; - }(); - - var XboneInf = function XboneInf() { - classCallCheck(this, XboneInf); - this.boneName = ''; - this.BoneIndex = 0; - this.Indeces = []; - this.Weights = []; - this.initMatrix = null; - this.OffsetMatrix = null; - }; + if (callback !== null) { + effect.callback = null; + callCallback(callback, instance); + } + } + } + } - var XAnimationInfo = function XAnimationInfo() { - classCallCheck(this, XAnimationInfo); - this.animeName = ''; - this.boneName = ''; - this.targetBone = null; - this.keyType = 4; - this.frameStartLv = 0; - this.keyFrames = []; - this.InverseMx = null; - }; + var fakeInternalInstance = {}; // React.Component uses a shared frozen object by default. + // We'll use it to determine whether we need to initialize legacy refs. - var XAnimationObj = function () { - function XAnimationObj(_flags) { - classCallCheck(this, XAnimationObj); - this.fps = 30; - this.name = 'xanimation'; - this.length = 0; - this.hierarchy = []; - this.putFlags = _flags; - - if (this.putFlags.putPos === undefined) { - this.putFlags.putPos = true; - } + var emptyRefsObject = new React.Component().refs; + var didWarnAboutStateAssignmentForComponent; + var didWarnAboutUninitializedState; + var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; + var didWarnAboutLegacyLifecyclesAndDerivedState; + var didWarnAboutUndefinedDerivedState; + var warnOnUndefinedDerivedState; + var warnOnInvalidCallback; + var didWarnAboutDirectlyAssigningPropsToState; + var didWarnAboutContextTypeAndContextTypes; + var didWarnAboutInvalidateContextType; - if (this.putFlags.putRot === undefined) { - this.putFlags.putRot = true; - } + { + didWarnAboutStateAssignmentForComponent = new Set(); + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutContextTypeAndContextTypes = new Set(); + didWarnAboutInvalidateContextType = new Set(); + var didWarnOnInvalidCallback = new Set(); - if (this.putFlags.putScl === undefined) { - this.putFlags.putScl = true; - } - } + warnOnInvalidCallback = function (callback, callerName) { + if (callback === null || typeof callback === 'function') { + return; + } - createClass(XAnimationObj, [{ - key: 'make', - value: function make(XAnimationInfoArray) { - for (let i = 0; i < XAnimationInfoArray.length; i++) { - this.hierarchy.push(this.makeBonekeys(XAnimationInfoArray[i])); - } + var key = callerName + '_' + callback; - this.length = this.hierarchy[0].keys[this.hierarchy[0].keys.length - 1].time; - } - }, { - key: 'clone', - value: function clone() { - return Object.assign({}, this); - } - }, { - key: 'makeBonekeys', - value: function makeBonekeys(XAnimationInfo) { - var refObj = {}; - refObj.name = XAnimationInfo.boneName; - refObj.parent = ''; - refObj.keys = this.keyFrameRefactor(XAnimationInfo); - - refObj.copy = function () { - return Object.assign({}, this); - }; + if (!didWarnOnInvalidCallback.has(key)) { + didWarnOnInvalidCallback.add(key); - return refObj; - } - }, { - key: 'keyFrameRefactor', - value: function keyFrameRefactor(XAnimationInfo) { - var keys = []; + error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); + } + }; - for (let i = 0; i < XAnimationInfo.keyFrames.length; i++) { - var keyframe = {}; - keyframe.time = XAnimationInfo.keyFrames[i].time * this.fps; + warnOnUndefinedDerivedState = function (type, partialState) { + if (partialState === undefined) { + var componentName = getComponentNameFromType(type) || 'Component'; - if (XAnimationInfo.keyFrames[i].pos && this.putFlags.putPos) { - keyframe.pos = XAnimationInfo.keyFrames[i].pos; - } + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { + didWarnAboutUndefinedDerivedState.add(componentName); - if (XAnimationInfo.keyFrames[i].rot && this.putFlags.putRot) { - keyframe.rot = XAnimationInfo.keyFrames[i].rot; - } + error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); + } + } + }; // This is so gross but it's at least non-critical and can be removed if + // it causes problems. This is meant to give a nicer error message for + // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, + // ...)) which otherwise throws a "_processChildContext is not a function" + // exception. - if (XAnimationInfo.keyFrames[i].scl && this.putFlags.putScl) { - keyframe.scl = XAnimationInfo.keyFrames[i].scl; - } - if (XAnimationInfo.keyFrames[i].matrix) { - keyframe.matrix = XAnimationInfo.keyFrames[i].matrix; + Object.defineProperty(fakeInternalInstance, '_processChildContext', { + enumerable: false, + value: function () { + throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).'); + } + }); + Object.freeze(fakeInternalInstance); + } - if (this.putFlags.putPos) { - keyframe.pos = new Vector3().setFromMatrixPosition(keyframe.matrix); - } + function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) { + var prevState = workInProgress.memoizedState; + var partialState = getDerivedStateFromProps(nextProps, prevState); - if (this.putFlags.putRot) { - keyframe.rot = new Quaternion().setFromRotationMatrix(keyframe.matrix); - } + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - if (this.putFlags.putScl) { - keyframe.scl = new Vector3().setFromMatrixScale(keyframe.matrix); - } - } + try { + // Invoke the function an extra time to help detect side-effects. + partialState = getDerivedStateFromProps(nextProps, prevState); + } finally { + setIsStrictModeForDevtools(false); + } + } - keys.push(keyframe); - } + warnOnUndefinedDerivedState(ctor, partialState); + } // Merge the partial state and the previous state. - return keys; - } - }]); - return XAnimationObj; - }(); - - var XKeyFrameInfo = function XKeyFrameInfo() { - classCallCheck(this, XKeyFrameInfo); - this.index = 0; - this.Frame = 0; - this.time = 0.0; - this.matrix = null; - }; - var XLoader = function () { - function XLoader(manager) { - Loader.call(this, manager); - classCallCheck(this, XLoader); - this.debug = false; - this.texloader = new TextureLoader(this.manager); - this.url = ''; - this._putMatLength = 0; - this._nowMat = null; - this._nowFrameName = ''; - this.frameHierarchie = []; - this.Hierarchies = {}; - this.HieStack = []; - this._currentObject = {}; - this._currentFrame = {}; - this._data = null; - this.onLoad = null; - this.IsUvYReverse = true; - this.Meshes = []; - this.animations = []; - this.animTicksPerSecond = 30; - this._currentGeo = null; - this._currentAnime = null; - this._currentAnimeFrames = null; - } + var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); + workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the + // base state. - createClass(XLoader, [{ - key: '_setArgOption', - value: function _setArgOption(_arg) { - var _start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (workInProgress.lanes === NoLanes) { + // Queue is always non-null for classes + var updateQueue = workInProgress.updateQueue; + updateQueue.baseState = memoizedState; + } + } - if (!_arg) { - return; - } + var classComponentUpdater = { + isMounted: isMounted, + enqueueSetState: function (inst, payload, callback) { + var fiber = get(inst); + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + var update = createUpdate(eventTime, lane); + update.payload = payload; - for (let i = _start; i < _arg.length; i++) { - switch (i) { - case 0: - this.url = _arg[i]; - break; + if (callback !== undefined && callback !== null) { + { + warnOnInvalidCallback(callback, 'setState'); + } - case 1: - this.options = _arg[i]; - break; - } - } + update.callback = callback; + } - if (this.options === undefined) { - this.options = {}; - } - } - }, { - key: 'load', - value: function load(_arg, onLoad, onProgress, onError) { - var _this = this; + enqueueUpdate(fiber, update); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - this._setArgOption(_arg); + if (root !== null) { + entangleTransitions(root, fiber, lane); + } - var loader = new FileLoader(this.manager); - loader.setPath(this.path); - loader.setResponseType('arraybuffer'); - loader.setRequestHeader(this.requestHeader); - loader.setWithCredentials(this.withCredentials); - loader.load(this.url, function (response) { - try { - _this.parse(response, onLoad); - } catch (e) { - if (onError) { - onError(e); - } else { - console.error(e); - } + { + markStateUpdateScheduled(fiber, lane); + } + }, + enqueueReplaceState: function (inst, payload, callback) { + var fiber = get(inst); + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + var update = createUpdate(eventTime, lane); + update.tag = ReplaceState; + update.payload = payload; - _this.manager.itemError(_this.url); - } - }, onProgress, onError); - } - }, { - key: '_readLine', - value: function _readLine(line) { - var readed = 0; + if (callback !== undefined && callback !== null) { + { + warnOnInvalidCallback(callback, 'replaceState'); + } - while (true) { - var find = -1; - find = line.indexOf('//', readed); + update.callback = callback; + } - if (find === -1) { - find = line.indexOf('#', readed); - } + enqueueUpdate(fiber, update); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - if (find > -1 && find < 2) { - var foundNewLine = -1; - foundNewLine = line.indexOf('\r\n', readed); + if (root !== null) { + entangleTransitions(root, fiber, lane); + } - if (foundNewLine > 0) { - readed = foundNewLine + 2; - } else { - foundNewLine = line.indexOf('\r', readed); + { + markStateUpdateScheduled(fiber, lane); + } + }, + enqueueForceUpdate: function (inst, callback) { + var fiber = get(inst); + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + var update = createUpdate(eventTime, lane); + update.tag = ForceUpdate; - if (foundNewLine > 0) { - readed = foundNewLine + 1; - } else { - readed = line.indexOf('\n', readed) + 1; - } - } - } else { - break; - } - } + if (callback !== undefined && callback !== null) { + { + warnOnInvalidCallback(callback, 'forceUpdate'); + } - return line.substr(readed); - } - }, { - key: '_readLine', - value: function _readLine(line) { - var readed = 0; + update.callback = callback; + } - while (true) { - var find = -1; - find = line.indexOf('//', readed); + enqueueUpdate(fiber, update); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - if (find === -1) { - find = line.indexOf('#', readed); - } + if (root !== null) { + entangleTransitions(root, fiber, lane); + } - if (find > -1 && find < 2) { - var foundNewLine = -1; - foundNewLine = line.indexOf('\r\n', readed); + { + markForceUpdateScheduled(fiber, lane); + } + } + }; - if (foundNewLine > 0) { - readed = foundNewLine + 2; - } else { - foundNewLine = line.indexOf('\r', readed); + function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) { + var instance = workInProgress.stateNode; - if (foundNewLine > 0) { - readed = foundNewLine + 1; - } else { - readed = line.indexOf('\n', readed) + 1; - } - } - } else { - break; - } - } + if (typeof instance.shouldComponentUpdate === 'function') { + var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); - return line.substr(readed); - } - }, { - key: '_isBinary', - value: function _isBinary(binData) { - var reader = new DataView(binData); - var face_size = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8; - var n_faces = reader.getUint32(80, true); - var expect = 80 + 32 / 8 + n_faces * face_size; - - if (expect === reader.byteLength) { - return true; - } + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - var fileLength = reader.byteLength; + try { + // Invoke the function an extra time to help detect side-effects. + shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); + } finally { + setIsStrictModeForDevtools(false); + } + } - for (let index = 0; index < fileLength; index++) { - if (reader.getUint8(index, false) > 127) { - return true; - } - } + if (shouldUpdate === undefined) { + error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component'); + } + } - return false; - } - }, { - key: '_ensureBinary', - value: function _ensureBinary(buf) { - if (typeof buf === 'string') { - var array_buffer = new Uint8Array(buf.length); - - for (let i = 0; i < buf.length; i++) { - array_buffer[i] = buf.charCodeAt(i) & 0xff; - } + return shouldUpdate; + } - return array_buffer.buffer || array_buffer; - } else { - return buf; - } - } - }, { - key: '_ensureString', - value: function _ensureString(buf) { - if (typeof buf !== 'string') { - return LoaderUtils.decodeText(new Uint8Array(buf)); - } else { - return buf; - } - } - }, { - key: 'parse', - value: function _parse(data, onLoad) { - var binData = this._ensureBinary(data); - - this._data = this._ensureString(data); - this.onLoad = onLoad; - return this._isBinary(binData) ? this._parseBinary(binData) : this._parseASCII(); - } - }, { - key: '_parseBinary', - value: function _parseBinary(data) { - return this._parseASCII(LoaderUtils.decodeText(new Uint8Array(data))); - } - }, { - key: '_parseASCII', - value: function _parseASCII() { - var path; - - if (this.resourcePath !== '') { - path = this.resourcePath; - } else if (this.path !== '') { - path = this.path; - } else { - path = LoaderUtils.extractUrlBase(this.url); - } + if (ctor.prototype && ctor.prototype.isPureReactComponent) { + return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); + } - this.texloader.setPath(path).setCrossOrigin(this.crossOrigin); - var endRead = 16; - this.Hierarchies.children = []; + return true; + } - this._hierarchieParse(this.Hierarchies, endRead); + function checkClassInstance(workInProgress, ctor, newProps) { + var instance = workInProgress.stateNode; - this._changeRoot(); + { + var name = getComponentNameFromType(ctor) || 'Component'; + var renderPresent = instance.render; - this._currentObject = this.Hierarchies.children.shift(); + if (!renderPresent) { + if (ctor.prototype && typeof ctor.prototype.render === 'function') { + error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); + } else { + error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); + } + } - this._mainloop(); - } - }, { - key: '_hierarchieParse', - value: function _hierarchieParse(_parent, _end) { - var endRead = _end; + if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { + error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); + } - while (true) { - var find1 = this._data.indexOf('{', endRead) + 1; + if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { + error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); + } - var findEnd = this._data.indexOf('}', endRead); + if (instance.propTypes) { + error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); + } - var findNext = this._data.indexOf('{', find1) + 1; + if (instance.contextType) { + error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); + } - if (find1 > 0 && findEnd > find1) { - var _currentObject = {}; - _currentObject.children = []; + { + if (instance.contextTypes) { + error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); + } - var nameData = this._readLine(this._data.substr(endRead, find1 - endRead - 1)).trim(); + if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { + didWarnAboutContextTypeAndContextTypes.add(ctor); - var word = nameData.split(/ /g); + error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); + } + } - if (word.length > 0) { - _currentObject.type = word[0]; + if (typeof instance.componentShouldUpdate === 'function') { + error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); + } - if (word.length >= 2) { - _currentObject.name = word[1]; - } else { - _currentObject.name = word[0] + this.Hierarchies.children.length; - } - } else { - _currentObject.name = nameData; - _currentObject.type = ''; - } + if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { + error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); + } - if (_currentObject.type === 'Animation') { - _currentObject.data = this._data.substr(findNext, findEnd - findNext).trim(); + if (typeof instance.componentDidUnmount === 'function') { + error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); + } - var refs = this._hierarchieParse(_currentObject, findEnd + 1); + if (typeof instance.componentDidReceiveProps === 'function') { + error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); + } - endRead = refs.end; - _currentObject.children = refs.parent.children; - } else { - var DataEnder = this._data.lastIndexOf(';', findNext > 0 ? Math.min(findNext, findEnd) : findEnd); + if (typeof instance.componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); + } - _currentObject.data = this._data.substr(find1, DataEnder - find1).trim(); + if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); + } - if (findNext <= 0 || findEnd < findNext) { - endRead = findEnd + 1; - } else { - var nextStart = Math.max(DataEnder + 1, find1); + var hasMutatedProps = instance.props !== newProps; - var _refs = this._hierarchieParse(_currentObject, nextStart); + if (instance.props !== undefined && hasMutatedProps) { + error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); + } - endRead = _refs.end; - _currentObject.children = _refs.parent.children; - } - } + if (instance.defaultProps) { + error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); + } - _currentObject.parent = _parent; + if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - if (_currentObject.type != 'template') { - _parent.children.push(_currentObject); - } - } else { - endRead = find1 === -1 ? this._data.length : findEnd + 1; - break; - } - } + error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); + } - return { - parent: _parent, - end: endRead - }; - } - }, { - key: '_mainloop', - value: function _mainloop() { - var _this2 = this; + if (typeof instance.getDerivedStateFromProps === 'function') { + error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } - this._mainProc(); + if (typeof instance.getDerivedStateFromError === 'function') { + error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } - if (this._currentObject.parent || this._currentObject.children.length > 0 || !this._currentObject.worked) { - setTimeout(function () { - _this2._mainloop(); - }, 1); - } else { - setTimeout(function () { - _this2.onLoad({ - models: _this2.Meshes, - animations: _this2.animations - }); - }, 1); - } - } - }, { - key: '_mainProc', - value: function _mainProc() { - var breakFlag = false; - - while (true) { - if (!this._currentObject.worked) { - switch (this._currentObject.type) { - case 'template': - break; + if (typeof ctor.getSnapshotBeforeUpdate === 'function') { + error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); + } - case 'AnimTicksPerSecond': - this.animTicksPerSecond = parseInt(this._currentObject.data); - break; + var _state = instance.state; - case 'Frame': - this._setFrame(); + if (_state && (typeof _state !== 'object' || isArray(_state))) { + error('%s.state: must be set to an object or null', name); + } - break; + if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { + error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); + } + } + } - case 'FrameTransformMatrix': - this._setFrameTransformMatrix(); + function adoptClassInstance(workInProgress, instance) { + instance.updater = classComponentUpdater; + workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates - break; + set(instance, workInProgress); - case 'Mesh': - this._changeRoot(); - - this._currentGeo = {}; - this._currentGeo.name = this._currentObject.name.trim(); - this._currentGeo.parentName = this._getParentName(this._currentObject).trim(); - this._currentGeo.VertexSetedBoneCount = []; - this._currentGeo.GeometryData = { - vertices: [], - normals: [], - uvs: [], - skinIndices: [], - skinWeights: [], - indices: [], - materialIndices: [] - }; - this._currentGeo.Materials = []; - this._currentGeo.normalVectors = []; - this._currentGeo.BoneInfs = []; - this._currentGeo.baseFrame = this._currentFrame; - - this._makeBoneFrom_CurrentFrame(); - - this._readVertexDatas(); - - breakFlag = true; - break; + { + instance._reactInternalInstance = fakeInternalInstance; + } + } - case 'MeshNormals': - this._readVertexDatas(); + function constructClassInstance(workInProgress, ctor, props) { + var isLegacyContextConsumer = false; + var unmaskedContext = emptyContextObject; + var context = emptyContextObject; + var contextType = ctor.contextType; - break; + { + if ('contextType' in ctor) { + var isValid = // Allow null for conditional declaration + contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a - case 'MeshTextureCoords': - this._setMeshTextureCoords(); + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { + didWarnAboutInvalidateContextType.add(ctor); + var addendum = ''; - break; + if (contextType === undefined) { + addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; + } else if (typeof contextType !== 'object') { + addendum = ' However, it is set to a ' + typeof contextType + '.'; + } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { + addendum = ' Did you accidentally pass the Context.Provider instead?'; + } else if (contextType._context !== undefined) { + // + addendum = ' Did you accidentally pass the Context.Consumer instead?'; + } else { + addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; + } - case 'VertexDuplicationIndices': - break; + error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); + } + } + } - case 'MeshMaterialList': - this._setMeshMaterialList(); + if (typeof contextType === 'object' && contextType !== null) { + context = readContext(contextType); + } else { + unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); + var contextTypes = ctor.contextTypes; + isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined; + context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; + } - break; + var instance = new ctor(props, context); // Instantiate twice to help detect side-effects. - case 'Material': - this._setMaterial(); + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - break; + try { + instance = new ctor(props, context); // eslint-disable-line no-new + } finally { + setIsStrictModeForDevtools(false); + } + } + } - case 'SkinWeights': - this._setSkinWeights(); + var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null; + adoptClassInstance(workInProgress, instance); - break; + { + if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { + var componentName = getComponentNameFromType(ctor) || 'Component'; - case 'AnimationSet': - this._changeRoot(); + if (!didWarnAboutUninitializedState.has(componentName)) { + didWarnAboutUninitializedState.add(componentName); - this._currentAnime = {}; - this._currentAnime.name = this._currentObject.name.trim(); - this._currentAnime.AnimeFrames = []; - break; + error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); + } + } // If new component APIs are defined, "unsafe" lifecycles won't be called. + // Warn about these lifecycles if they are present. + // Don't warn about react-lifecycles-compat polyfilled methods though. - case 'Animation': - if (this._currentAnimeFrames) { - this._currentAnime.AnimeFrames.push(this._currentAnimeFrames); - } - this._currentAnimeFrames = new XAnimationInfo(); - this._currentAnimeFrames.boneName = this._currentObject.data.trim(); - break; + if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { + var foundWillMountName = null; + var foundWillReceivePropsName = null; + var foundWillUpdateName = null; - case 'AnimationKey': - this._readAnimationKey(); + if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { + foundWillMountName = 'componentWillMount'; + } else if (typeof instance.UNSAFE_componentWillMount === 'function') { + foundWillMountName = 'UNSAFE_componentWillMount'; + } - breakFlag = true; - break; - } + if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { + foundWillReceivePropsName = 'componentWillReceiveProps'; + } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { + foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; + } - this._currentObject.worked = true; - } + if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { + foundWillUpdateName = 'componentWillUpdate'; + } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { + foundWillUpdateName = 'UNSAFE_componentWillUpdate'; + } - if (this._currentObject.children.length > 0) { - this._currentObject = this._currentObject.children.shift(); + if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { + var _componentName = getComponentNameFromType(ctor) || 'Component'; - if (this.debug) { - console.log('processing ' + this._currentObject.name); - } + var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; - if (breakFlag) break; - } else { - if (this._currentObject.worked) { - if (this._currentObject.parent && !this._currentObject.parent.parent) { - this._changeRoot(); - } - } + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { + didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); - if (this._currentObject.parent) { - this._currentObject = this._currentObject.parent; - } else { - breakFlag = true; - } + error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); + } + } + } + } // Cache unmasked context so we can avoid recreating masked context unless necessary. + // ReactFiberContext usually updates this cache but can't for newly-created instances. - if (breakFlag) break; - } - } - return; - } - }, { - key: '_changeRoot', - value: function _changeRoot() { - if (this._currentGeo != null && this._currentGeo.name) { - this._makeOutputGeometry(); - } + if (isLegacyContextConsumer) { + cacheContext(workInProgress, unmaskedContext, context); + } - this._currentGeo = {}; + return instance; + } - if (this._currentAnime != null && this._currentAnime.name) { - if (this._currentAnimeFrames) { - this._currentAnime.AnimeFrames.push(this._currentAnimeFrames); + function callComponentWillMount(workInProgress, instance) { + var oldState = instance.state; - this._currentAnimeFrames = null; - } + if (typeof instance.componentWillMount === 'function') { + instance.componentWillMount(); + } - this._makeOutputAnimation(); - } + if (typeof instance.UNSAFE_componentWillMount === 'function') { + instance.UNSAFE_componentWillMount(); + } - this._currentAnime = {}; - } - }, { - key: '_getParentName', - value: function _getParentName(_obj) { - if (_obj.parent) { - if (_obj.parent.name) { - return _obj.parent.name; - } else { - return this._getParentName(_obj.parent); - } - } else { - return ''; - } - } - }, { - key: '_setFrame', - value: function _setFrame() { - this._nowFrameName = this._currentObject.name.trim(); - this._currentFrame = {}; - this._currentFrame.name = this._nowFrameName; - this._currentFrame.children = []; - - if (this._currentObject.parent && this._currentObject.parent.name) { - this._currentFrame.parentName = this._currentObject.parent.name; - } + if (oldState !== instance.state) { + { + error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component'); + } - this.frameHierarchie.push(this._nowFrameName); - this.HieStack[this._nowFrameName] = this._currentFrame; - } - }, { - key: '_setFrameTransformMatrix', - value: function _setFrameTransformMatrix() { - this._currentFrame.FrameTransformMatrix = new Matrix4(); + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } + } - var data = this._currentObject.data.split(','); + function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) { + var oldState = instance.state; - this._ParseMatrixData(this._currentFrame.FrameTransformMatrix, data); + if (typeof instance.componentWillReceiveProps === 'function') { + instance.componentWillReceiveProps(newProps, nextContext); + } - this._makeBoneFrom_CurrentFrame(); - } - }, { - key: '_makeBoneFrom_CurrentFrame', - value: function _makeBoneFrom_CurrentFrame() { - if (!this._currentFrame.FrameTransformMatrix) { - return; - } + if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { + instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); + } - var b = new Bone(); - b.name = this._currentFrame.name; - b.applyMatrix4(this._currentFrame.FrameTransformMatrix); - b.matrixWorld = b.matrix; - b.FrameTransformMatrix = this._currentFrame.FrameTransformMatrix; - this._currentFrame.putBone = b; - - if (this._currentFrame.parentName) { - for (let frame in this.HieStack) { - if (this.HieStack[frame].name === this._currentFrame.parentName) { - this.HieStack[frame].putBone.add(this._currentFrame.putBone); - } - } - } - } - }, { - key: '_readVertexDatas', - value: function _readVertexDatas() { - var endRead = 0; - var mode = 0; - var mode_local = 0; - var maxLength = 0; - - while (true) { - var changeMode = false; - - if (mode_local === 0) { - var refO = this._readInt1(endRead); - - endRead = refO.endRead; - mode_local = 1; - maxLength = this._currentObject.data.indexOf(';;', endRead) + 1; - - if (maxLength <= 0) { - maxLength = this._currentObject.data.length; - } - } else { - var find = 0; + if (instance.state !== oldState) { + { + var componentName = getComponentNameFromFiber(workInProgress) || 'Component'; - switch (mode) { - case 0: - find = this._currentObject.data.indexOf(',', endRead) + 1; - break; + if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { + didWarnAboutStateAssignmentForComponent.add(componentName); - case 1: - find = this._currentObject.data.indexOf(';,', endRead) + 1; - break; - } + error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName); + } + } - if (find === 0 || find > maxLength) { - find = maxLength; - mode_local = 0; - changeMode = true; - } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } + } // Invokes the mount life-cycles on a previously never rendered instance. - switch (this._currentObject.type) { - case 'Mesh': - switch (mode) { - case 0: - this._readVertex1(this._currentObject.data.substr(endRead, find - endRead)); - break; + function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { + { + checkClassInstance(workInProgress, ctor, newProps); + } - case 1: - this._readFace1(this._currentObject.data.substr(endRead, find - endRead)); + var instance = workInProgress.stateNode; + instance.props = newProps; + instance.state = workInProgress.memoizedState; + instance.refs = emptyRefsObject; + initializeUpdateQueue(workInProgress); + var contextType = ctor.contextType; - break; - } + if (typeof contextType === 'object' && contextType !== null) { + instance.context = readContext(contextType); + } else { + var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); + instance.context = getMaskedContext(workInProgress, unmaskedContext); + } - break; + { + if (instance.state === newProps) { + var componentName = getComponentNameFromType(ctor) || 'Component'; - case 'MeshNormals': - switch (mode) { - case 0: - this._readNormalVector1(this._currentObject.data.substr(endRead, find - endRead)); + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { + didWarnAboutDirectlyAssigningPropsToState.add(componentName); - break; - } + error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); + } + } - break; - } + if (workInProgress.mode & StrictLegacyMode) { + ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance); + } - endRead = find + 1; + { + ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance); + } + } - if (changeMode) { - mode++; - } - } + instance.state = workInProgress.memoizedState; + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - if (endRead >= this._currentObject.data.length) { - break; - } - } - } - }, { - key: '_readInt1', - value: function _readInt1(start) { - var find = this._currentObject.data.indexOf(';', start); + if (typeof getDerivedStateFromProps === 'function') { + applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); + instance.state = workInProgress.memoizedState; + } // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. - return { - refI: parseInt(this._currentObject.data.substr(start, find - start)), - endRead: find + 1 - }; - } - }, { - key: '_readVertex1', - value: function _readVertex1(line) { - var data = this._readLine(line.trim()).substr(0, line.length - 2).split(';'); - this._currentGeo.GeometryData.vertices.push(parseFloat(data[0]), parseFloat(data[1]), parseFloat(data[2])); + if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { + callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's + // process them now. - this._currentGeo.GeometryData.skinIndices.push(0, 0, 0, 0); + processUpdateQueue(workInProgress, newProps, instance, renderLanes); + instance.state = workInProgress.memoizedState; + } - this._currentGeo.GeometryData.skinWeights.push(1, 0, 0, 0); + if (typeof instance.componentDidMount === 'function') { + var fiberFlags = Update; - this._currentGeo.VertexSetedBoneCount.push(0); - } - }, { - key: '_readFace1', - value: function _readFace1(line) { - var data = this._readLine(line.trim()).substr(2, line.length - 4).split(','); + { + fiberFlags |= LayoutStatic; + } - this._currentGeo.GeometryData.indices.push(parseInt(data[0], 10), parseInt(data[1], 10), parseInt(data[2], 10)); - } - }, { - key: '_readNormalVector1', - value: function _readNormalVector1(line) { - var data = this._readLine(line.trim()).substr(0, line.length - 2).split(';'); + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } - this._currentGeo.GeometryData.normals.push(parseFloat(data[0]), parseFloat(data[1]), parseFloat(data[2])); - } - }, { - key: '_buildGeometry', - value: function _buildGeometry() { - var bufferGeometry = new BufferGeometry(); - var position = []; - var normals = []; - var uvs = []; - var skinIndices = []; - var skinWeights = []; // - - var data = this._currentGeo.GeometryData; - - for (let i = 0, l = data.indices.length; i < l; i++) { - var stride2 = data.indices[i] * 2; - var stride3 = data.indices[i] * 3; - var stride4 = data.indices[i] * 4; - position.push(data.vertices[stride3], data.vertices[stride3 + 1], data.vertices[stride3 + 2]); - normals.push(data.normals[stride3], data.normals[stride3 + 1], data.normals[stride3 + 2]); - skinIndices.push(data.skinIndices[stride4], data.skinIndices[stride4 + 1], data.skinIndices[stride4 + 2], data.skinIndices[stride4 + 3]); - skinWeights.push(data.skinWeights[stride4], data.skinWeights[stride4 + 1], data.skinWeights[stride4 + 2], data.skinWeights[stride4 + 3]); - uvs.push(data.uvs[stride2], data.uvs[stride2 + 1]); - } // - - - bufferGeometry.setAttribute('position', new Float32BufferAttribute(position, 3)); - bufferGeometry.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - bufferGeometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); - bufferGeometry.setAttribute('skinIndex', new Uint16BufferAttribute(skinIndices, 4)); - bufferGeometry.setAttribute('skinWeight', new Float32BufferAttribute(skinWeights, 4)); - - this._computeGroups(bufferGeometry, data.materialIndices); - - return bufferGeometry; - } - }, { - key: '_computeGroups', - value: function _computeGroups(bufferGeometry, materialIndices) { - var group; - var groups = []; - var materialIndex = undefined; - - for (let i = 0; i < materialIndices.length; i++) { - var currentMaterialIndex = materialIndices[i]; - - if (currentMaterialIndex !== materialIndex) { - materialIndex = currentMaterialIndex; - - if (group !== undefined) { - group.count = i * 3 - group.start; - groups.push(group); - } + workInProgress.flags |= fiberFlags; + } + } - group = { - start: i * 3, - materialIndex: materialIndex - }; - } - } + function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) { + var instance = workInProgress.stateNode; + var oldProps = workInProgress.memoizedProps; + instance.props = oldProps; + var oldContext = instance.context; + var contextType = ctor.contextType; + var nextContext = emptyContextObject; - if (group !== undefined) { - group.count = i * 3 - group.start; - groups.push(group); - } + if (typeof contextType === 'object' && contextType !== null) { + nextContext = readContext(contextType); + } else { + var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); + nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext); + } - bufferGeometry.groups = groups; - } - }, { - key: '_setMeshTextureCoords', - value: function _setMeshTextureCoords() { - var endRead = 0; - var mode = 0; - var mode_local = 0; - - while (true) { - switch (mode) { - case 0: - if (mode_local === 0) { - var refO = this._readInt1(0); - - endRead = refO.endRead; - mode_local = 1; - } else { - var find = this._currentObject.data.indexOf(',', endRead) + 1; + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what + // ever the previously attempted to render - not the "current". However, + // during componentDidUpdate we pass the "current" props. + // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. - if (find === 0) { - find = this._currentObject.data.length; - mode = 2; - mode_local = 0; - } + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { + if (oldProps !== newProps || oldContext !== nextContext) { + callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); + } + } - var line = this._currentObject.data.substr(endRead, find - endRead); + resetHasForceUpdateBeforeProcessing(); + var oldState = workInProgress.memoizedState; + var newState = instance.state = oldState; + processUpdateQueue(workInProgress, newProps, instance, renderLanes); + newState = workInProgress.memoizedState; - var data = this._readLine(line.trim()).split(';'); + if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { + // If an update was already in progress, we should schedule an Update + // effect even though we're bailing out, so that cWU/cDU are called. + if (typeof instance.componentDidMount === 'function') { + var fiberFlags = Update; - if (this.IsUvYReverse) { - this._currentGeo.GeometryData.uvs.push(parseFloat(data[0]), 1 - parseFloat(data[1])); - } else { - this._currentGeo.GeometryData.uvs.push(parseFloat(data[0]), parseFloat(data[1])); - } + { + fiberFlags |= LayoutStatic; + } - endRead = find + 1; - } + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } - break; - } + workInProgress.flags |= fiberFlags; + } - if (endRead >= this._currentObject.data.length) { - break; - } - } - } - }, { - key: '_setMeshMaterialList', - value: function _setMeshMaterialList() { - var endRead = 0; - var mode = 0; - var mode_local = 0; - - while (true) { - if (mode_local < 2) { - var refO = this._readInt1(endRead); - - endRead = refO.endRead; - mode_local++; - } else { - var find = this._currentObject.data.indexOf(';', endRead); + return false; + } - if (find === -1) { - find = this._currentObject.data.length; - mode = 3; - mode_local = 0; - } + if (typeof getDerivedStateFromProps === 'function') { + applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); + newState = workInProgress.memoizedState; + } - var line = this._currentObject.data.substr(endRead, find - endRead); + var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext); - var data = this._readLine(line.trim()).split(','); + if (shouldUpdate) { + // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { + if (typeof instance.componentWillMount === 'function') { + instance.componentWillMount(); + } - for (let i = 0; i < data.length; i++) { - this._currentGeo.GeometryData.materialIndices[i] = parseInt(data[i]); - } + if (typeof instance.UNSAFE_componentWillMount === 'function') { + instance.UNSAFE_componentWillMount(); + } + } - endRead = this._currentObject.data.length; - } + if (typeof instance.componentDidMount === 'function') { + var _fiberFlags = Update; - if (endRead >= this._currentObject.data.length || mode >= 3) { - break; - } - } - } - }, { - key: '_setMaterial', - value: function _setMaterial() { - var _nowMat = new MeshPhongMaterial({ - color: Math.random() * 0xffffff - }); + { + _fiberFlags |= LayoutStatic; + } - _nowMat.side = FrontSide; - _nowMat.name = this._currentObject.name; - var endRead = 0; + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + _fiberFlags |= MountLayoutDev; + } - var find = this._currentObject.data.indexOf(';;', endRead); + workInProgress.flags |= _fiberFlags; + } + } else { + // If an update was already in progress, we should schedule an Update + // effect even though we're bailing out, so that cWU/cDU are called. + if (typeof instance.componentDidMount === 'function') { + var _fiberFlags2 = Update; - var line = this._currentObject.data.substr(endRead, find - endRead); + { + _fiberFlags2 |= LayoutStatic; + } - var data = this._readLine(line.trim()).split(';'); + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + _fiberFlags2 |= MountLayoutDev; + } - _nowMat.color.r = parseFloat(data[0]); - _nowMat.color.g = parseFloat(data[1]); - _nowMat.color.b = parseFloat(data[2]); - endRead = find + 2; - find = this._currentObject.data.indexOf(';', endRead); - line = this._currentObject.data.substr(endRead, find - endRead); - _nowMat.shininess = parseFloat(this._readLine(line)); - endRead = find + 1; - find = this._currentObject.data.indexOf(';;', endRead); - line = this._currentObject.data.substr(endRead, find - endRead); + workInProgress.flags |= _fiberFlags2; + } // If shouldComponentUpdate returned false, we should still update the + // memoized state to indicate that this work can be reused. - var data2 = this._readLine(line.trim()).split(';'); - _nowMat.specular.r = parseFloat(data2[0]); - _nowMat.specular.g = parseFloat(data2[1]); - _nowMat.specular.b = parseFloat(data2[2]); - endRead = find + 2; - find = this._currentObject.data.indexOf(';;', endRead); + workInProgress.memoizedProps = newProps; + workInProgress.memoizedState = newState; + } // Update the existing instance's state, props, and context pointers even + // if shouldComponentUpdate returns false. - if (find === -1) { - find = this._currentObject.data.length; - } - line = this._currentObject.data.substr(endRead, find - endRead); + instance.props = newProps; + instance.state = newState; + instance.context = nextContext; + return shouldUpdate; + } // Invokes the update life-cycles and returns false if it shouldn't rerender. - var data3 = this._readLine(line.trim()).split(';'); - _nowMat.emissive.r = parseFloat(data3[0]); - _nowMat.emissive.g = parseFloat(data3[1]); - _nowMat.emissive.b = parseFloat(data3[2]); - var localObject = null; + function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) { + var instance = workInProgress.stateNode; + cloneUpdateQueue(current, workInProgress); + var unresolvedOldProps = workInProgress.memoizedProps; + var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps); + instance.props = oldProps; + var unresolvedNewProps = workInProgress.pendingProps; + var oldContext = instance.context; + var contextType = ctor.contextType; + var nextContext = emptyContextObject; - while (true) { - if (this._currentObject.children.length > 0) { - localObject = this._currentObject.children.shift(); + if (typeof contextType === 'object' && contextType !== null) { + nextContext = readContext(contextType); + } else { + var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); + nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); + } - if (this.debug) { - console.log('processing ' + localObject.name); - } + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what + // ever the previously attempted to render - not the "current". However, + // during componentDidUpdate we pass the "current" props. + // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. - var fileName = localObject.data.substr(1, localObject.data.length - 2); + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { + if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { + callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); + } + } - switch (localObject.type) { - case 'TextureFilename': - _nowMat.map = this.texloader.load(fileName); - break; + resetHasForceUpdateBeforeProcessing(); + var oldState = workInProgress.memoizedState; + var newState = instance.state = oldState; + processUpdateQueue(workInProgress, newProps, instance, renderLanes); + newState = workInProgress.memoizedState; - case 'BumpMapFilename': - _nowMat.bumpMap = this.texloader.load(fileName); - _nowMat.bumpScale = 0.05; - break; + if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation )) { + // If an update was already in progress, we should schedule an Update + // effect even though we're bailing out, so that cWU/cDU are called. + if (typeof instance.componentDidUpdate === 'function') { + if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { + workInProgress.flags |= Update; + } + } - case 'NormalMapFilename': - _nowMat.normalMap = this.texloader.load(fileName); - _nowMat.normalScale = new Vector2(2, 2); - break; + if (typeof instance.getSnapshotBeforeUpdate === 'function') { + if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { + workInProgress.flags |= Snapshot; + } + } - case 'EmissiveMapFilename': - _nowMat.emissiveMap = this.texloader.load(fileName); - break; + return false; + } - case 'LightMapFilename': - _nowMat.lightMap = this.texloader.load(fileName); - break; - } - } else { - break; - } - } + if (typeof getDerivedStateFromProps === 'function') { + applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); + newState = workInProgress.memoizedState; + } - this._currentGeo.Materials.push(_nowMat); - } - }, { - key: '_setSkinWeights', - value: function _setSkinWeights() { - var boneInf = new XboneInf(); - var endRead = 0; + var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice, + // both before and after `shouldComponentUpdate` has been called. Not ideal, + // but I'm loath to refactor this function. This only happens for memoized + // components so it's not that common. + enableLazyContextPropagation ; - var find = this._currentObject.data.indexOf(';', endRead); + if (shouldUpdate) { + // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) { + if (typeof instance.componentWillUpdate === 'function') { + instance.componentWillUpdate(newProps, newState, nextContext); + } - var line = this._currentObject.data.substr(endRead, find - endRead); + if (typeof instance.UNSAFE_componentWillUpdate === 'function') { + instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); + } + } - endRead = find + 1; - boneInf.boneName = line.substr(1, line.length - 2); - boneInf.BoneIndex = this._currentGeo.BoneInfs.length; - find = this._currentObject.data.indexOf(';', endRead); - endRead = find + 1; - find = this._currentObject.data.indexOf(';', endRead); - line = this._currentObject.data.substr(endRead, find - endRead); + if (typeof instance.componentDidUpdate === 'function') { + workInProgress.flags |= Update; + } - var data = this._readLine(line.trim()).split(','); + if (typeof instance.getSnapshotBeforeUpdate === 'function') { + workInProgress.flags |= Snapshot; + } + } else { + // If an update was already in progress, we should schedule an Update + // effect even though we're bailing out, so that cWU/cDU are called. + if (typeof instance.componentDidUpdate === 'function') { + if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { + workInProgress.flags |= Update; + } + } - for (let i = 0; i < data.length; i++) { - boneInf.Indeces.push(parseInt(data[i])); - } + if (typeof instance.getSnapshotBeforeUpdate === 'function') { + if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { + workInProgress.flags |= Snapshot; + } + } // If shouldComponentUpdate returned false, we should still update the + // memoized props/state to indicate that this work can be reused. - endRead = find + 1; - find = this._currentObject.data.indexOf(';', endRead); - line = this._currentObject.data.substr(endRead, find - endRead); - var data2 = this._readLine(line.trim()).split(','); + workInProgress.memoizedProps = newProps; + workInProgress.memoizedState = newState; + } // Update the existing instance's state, props, and context pointers even + // if shouldComponentUpdate returns false. - for (let _i = 0; _i < data2.length; _i++) { - boneInf.Weights.push(parseFloat(data2[_i])); - } - endRead = find + 1; - find = this._currentObject.data.indexOf(';', endRead); + instance.props = newProps; + instance.state = newState; + instance.context = nextContext; + return shouldUpdate; + } - if (find <= 0) { - find = this._currentObject.data.length; - } + // TODO: Use the unified fiber stack module instead of this local one? + // Intentionally not using it yet to derisk the initial implementation, because + // the way we push/pop these values is a bit unusual. If there's a mistake, I'd + // rather the ids be wrong than crash the whole reconciler. + var forkStack = []; + var forkStackIndex = 0; + var treeForkProvider = null; + var treeForkCount = 0; + var idStack = []; + var idStackIndex = 0; + var treeContextProvider = null; + var treeContextId = 1; + var treeContextOverflow = ''; + function isForkedChild(workInProgress) { + warnIfNotHydrating(); + return (workInProgress.flags & Forked) !== NoFlags; + } + function getForksAtLevel(workInProgress) { + warnIfNotHydrating(); + return treeForkCount; + } + function getTreeId() { + var overflow = treeContextOverflow; + var idWithLeadingBit = treeContextId; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; + } + function pushTreeFork(workInProgress, totalChildren) { + // This is called right after we reconcile an array (or iterator) of child + // fibers, because that's the only place where we know how many children in + // the whole set without doing extra work later, or storing addtional + // information on the fiber. + // + // That's why this function is separate from pushTreeId — it's called during + // the render phase of the fork parent, not the child, which is where we push + // the other context values. + // + // In the Fizz implementation this is much simpler because the child is + // rendered in the same callstack as the parent. + // + // It might be better to just add a `forks` field to the Fiber type. It would + // make this module simpler. + warnIfNotHydrating(); + forkStack[forkStackIndex++] = treeForkCount; + forkStack[forkStackIndex++] = treeForkProvider; + treeForkProvider = workInProgress; + treeForkCount = totalChildren; + } + function pushTreeId(workInProgress, totalChildren, index) { + warnIfNotHydrating(); + idStack[idStackIndex++] = treeContextId; + idStack[idStackIndex++] = treeContextOverflow; + idStack[idStackIndex++] = treeContextProvider; + treeContextProvider = workInProgress; + var baseIdWithLeadingBit = treeContextId; + var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part + // of the id; we use it to account for leading 0s. - line = this._currentObject.data.substr(endRead, find - endRead); + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index + 1; + var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into + // consideration the leading 1 we use to mark the end of the sequence. - var data3 = this._readLine(line.trim()).split(','); + if (length > 30) { + // We overflowed the bitwise-safe range. Fall back to slower algorithm. + // This branch assumes the length of the base id is greater than 5; it won't + // work for smaller ids, because you need 5 bits per character. + // + // We encode the id in multiple steps: first the base id, then the + // remaining digits. + // + // Each 5 bit sequence corresponds to a single base 32 character. So for + // example, if the current id is 23 bits long, we can convert 20 of those + // bits into a string of 4 characters, with 3 bits left over. + // + // First calculate how many bits in the base id represent a complete + // sequence of characters. + var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. - boneInf.OffsetMatrix = new Matrix4(); + var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. - this._ParseMatrixData(boneInf.OffsetMatrix, data3); + var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. - this._currentGeo.BoneInfs.push(boneInf); - } - }, { - key: '_makePutBoneList', - value: function _makePutBoneList(_RootName, _bones) { - var putting = false; - - for (let frame in this.HieStack) { - if (this.HieStack[frame].name === _RootName || putting) { - putting = true; - var b = new Bone(); - b.name = this.HieStack[frame].name; - b.applyMatrix4(this.HieStack[frame].FrameTransformMatrix); - b.matrixWorld = b.matrix; - b.FrameTransformMatrix = this.HieStack[frame].FrameTransformMatrix; - b.pos = new Vector3().setFromMatrixPosition(b.FrameTransformMatrix).toArray(); - b.rotq = new Quaternion().setFromRotationMatrix(b.FrameTransformMatrix).toArray(); - b.scl = new Vector3().setFromMatrixScale(b.FrameTransformMatrix).toArray(); - - if (this.HieStack[frame].parentName && this.HieStack[frame].parentName.length > 0) { - for (let i = 0; i < _bones.length; i++) { - if (this.HieStack[frame].parentName === _bones[i].name) { - _bones[i].add(b); - - b.parent = i; - break; - } - } - } + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because + // we made more room, this time it won't overflow. - _bones.push(b); - } - } - } - }, { - key: '_makeOutputGeometry', - value: function _makeOutputGeometry() { - var mesh = null; + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + treeContextId = 1 << restOfLength | id; + treeContextOverflow = overflow; + } else { + // Normal path + var newBits = slot << baseLength; - if (this._currentGeo.BoneInfs.length > 0) { - var putBones = []; + var _id = newBits | baseId; - this._makePutBoneList(this._currentGeo.baseFrame.parentName, putBones); + var _overflow = baseOverflow; + treeContextId = 1 << length | _id; + treeContextOverflow = _overflow; + } + } + function pushMaterializedTreeId(workInProgress) { + warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear + // in its children. - for (let bi = 0; bi < this._currentGeo.BoneInfs.length; bi++) { - var boneIndex = 0; + var returnFiber = workInProgress.return; - for (let bb = 0; bb < putBones.length; bb++) { - if (putBones[bb].name === this._currentGeo.BoneInfs[bi].boneName) { - boneIndex = bb; - putBones[bb].OffsetMatrix = new Matrix4(); - putBones[bb].OffsetMatrix.copy(this._currentGeo.BoneInfs[bi].OffsetMatrix); - break; - } - } + if (returnFiber !== null) { + var numberOfForks = 1; + var slotIndex = 0; + pushTreeFork(workInProgress, numberOfForks); + pushTreeId(workInProgress, numberOfForks, slotIndex); + } + } - for (let vi = 0; vi < this._currentGeo.BoneInfs[bi].Indeces.length; vi++) { - var nowVertexID = this._currentGeo.BoneInfs[bi].Indeces[vi]; - var nowVal = this._currentGeo.BoneInfs[bi].Weights[vi]; - var stride = nowVertexID * 4; - - switch (this._currentGeo.VertexSetedBoneCount[nowVertexID]) { - case 0: - this._currentGeo.GeometryData.skinIndices[stride] = boneIndex; - this._currentGeo.GeometryData.skinWeights[stride] = nowVal; - break; - - case 1: - this._currentGeo.GeometryData.skinIndices[stride + 1] = boneIndex; - this._currentGeo.GeometryData.skinWeights[stride + 1] = nowVal; - break; - - case 2: - this._currentGeo.GeometryData.skinIndices[stride + 2] = boneIndex; - this._currentGeo.GeometryData.skinWeights[stride + 2] = nowVal; - break; - - case 3: - this._currentGeo.GeometryData.skinIndices[stride + 3] = boneIndex; - this._currentGeo.GeometryData.skinWeights[stride + 3] = nowVal; - break; - } + function getBitLength(number) { + return 32 - clz32(number); + } - this._currentGeo.VertexSetedBoneCount[nowVertexID]++; + function getLeadingBit(id) { + return 1 << getBitLength(id) - 1; + } - if (this._currentGeo.VertexSetedBoneCount[nowVertexID] > 4) { - console.log('warn! over 4 bone weight! :' + nowVertexID); - } - } - } + function popTreeContext(workInProgress) { + // Restore the previous values. + // This is a bit more complicated than other context-like modules in Fiber + // because the same Fiber may appear on the stack multiple times and for + // different reasons. We have to keep popping until the work-in-progress is + // no longer at the top of the stack. + while (workInProgress === treeForkProvider) { + treeForkProvider = forkStack[--forkStackIndex]; + forkStack[forkStackIndex] = null; + treeForkCount = forkStack[--forkStackIndex]; + forkStack[forkStackIndex] = null; + } - for (let sk = 0; sk < this._currentGeo.Materials.length; sk++) { - this._currentGeo.Materials[sk].skinning = true; - } + while (workInProgress === treeContextProvider) { + treeContextProvider = idStack[--idStackIndex]; + idStack[idStackIndex] = null; + treeContextOverflow = idStack[--idStackIndex]; + idStack[idStackIndex] = null; + treeContextId = idStack[--idStackIndex]; + idStack[idStackIndex] = null; + } + } + function getSuspendedTreeContext() { + warnIfNotHydrating(); - var offsetList = []; + if (treeContextProvider !== null) { + return { + id: treeContextId, + overflow: treeContextOverflow + }; + } else { + return null; + } + } + function restoreSuspendedTreeContext(workInProgress, suspendedContext) { + warnIfNotHydrating(); + idStack[idStackIndex++] = treeContextId; + idStack[idStackIndex++] = treeContextOverflow; + idStack[idStackIndex++] = treeContextProvider; + treeContextId = suspendedContext.id; + treeContextOverflow = suspendedContext.overflow; + treeContextProvider = workInProgress; + } - for (let _bi = 0; _bi < putBones.length; _bi++) { - if (putBones[_bi].OffsetMatrix) { - offsetList.push(putBones[_bi].OffsetMatrix); - } else { - offsetList.push(new Matrix4()); - } - } + function warnIfNotHydrating() { + { + if (!getIsHydrating()) { + error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.'); + } + } + } - var bufferGeometry = this._buildGeometry(); + // This may have been an insertion or a hydration. - mesh = new SkinnedMesh(bufferGeometry, this._currentGeo.Materials.length === 1 ? this._currentGeo.Materials[0] : this._currentGeo.Materials); + var hydrationParentFiber = null; + var nextHydratableInstance = null; + var isHydrating = false; + var didSuspend = false; // Hydration errors that were thrown inside this boundary - this._initSkeleton(mesh, putBones, offsetList); - } else { - var _bufferGeometry = this._buildGeometry(); + var hydrationErrors = null; - mesh = new Mesh(_bufferGeometry, this._currentGeo.Materials.length === 1 ? this._currentGeo.Materials[0] : this._currentGeo.Materials); - } + function warnIfHydrating() { + { + if (isHydrating) { + error('We should not be hydrating here. This is a bug in React. Please file a bug.'); + } + } + } - mesh.name = this._currentGeo.name; - var worldBaseMx = new Matrix4(); - var currentMxFrame = this._currentGeo.baseFrame.putBone; + function markDidSuspendWhileHydratingDEV() { + { + didSuspend = true; + } + } - if (currentMxFrame && currentMxFrame.parent) { - while (true) { - currentMxFrame = currentMxFrame.parent; + function enterHydrationState(fiber) { + if (!supportsHydration) { + return false; + } - if (currentMxFrame) { - worldBaseMx.multiply(currentMxFrame.FrameTransformMatrix); - } else { - break; - } - } + var parentInstance = fiber.stateNode.containerInfo; + nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); + hydrationParentFiber = fiber; + isHydrating = true; + hydrationErrors = null; + didSuspend = false; + return true; + } - mesh.applyMatrix4(worldBaseMx); - } + function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) { + if (!supportsHydration) { + return false; + } - this.Meshes.push(mesh); - } - }, { - key: '_initSkeleton', - value: function _initSkeleton(mesh, boneList, boneInverses) { - var bones = [], - bone, - gbone; - var i, il; - - for (i = 0, il = boneList.length; i < il; i++) { - gbone = boneList[i]; - bone = new Bone(); - bones.push(bone); - bone.name = gbone.name; - bone.position.fromArray(gbone.pos); - bone.quaternion.fromArray(gbone.rotq); - if (gbone.scl !== undefined) bone.scale.fromArray(gbone.scl); - } + nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); + hydrationParentFiber = fiber; + isHydrating = true; + hydrationErrors = null; + didSuspend = false; - for (i = 0, il = boneList.length; i < il; i++) { - gbone = boneList[i]; + if (treeContext !== null) { + restoreSuspendedTreeContext(fiber, treeContext); + } - if (gbone.parent !== -1 && gbone.parent !== null && bones[gbone.parent] !== undefined) { - bones[gbone.parent].add(bones[i]); - } else { - mesh.add(bones[i]); - } - } + return true; + } - mesh.updateMatrixWorld(true); - var skeleton = new Skeleton(bones, boneInverses); - mesh.bind(skeleton, mesh.matrixWorld); - } - }, { - key: '_readAnimationKey', - value: function _readAnimationKey() { - var endRead = 0; - - var find = this._currentObject.data.indexOf(';', endRead); - - var line = this._currentObject.data.substr(endRead, find - endRead); - - endRead = find + 1; - var nowKeyType = parseInt(this._readLine(line)); - find = this._currentObject.data.indexOf(';', endRead); - endRead = find + 1; - line = this._currentObject.data.substr(endRead); - - var data = this._readLine(line.trim()).split(';;,'); - - for (let i = 0; i < data.length; i++) { - var data2 = data[i].split(';'); - var keyInfo = new XKeyFrameInfo(); - keyInfo.type = nowKeyType; - keyInfo.Frame = parseInt(data2[0]); - keyInfo.index = this._currentAnimeFrames.keyFrames.length; - keyInfo.time = keyInfo.Frame; - - if (nowKeyType != 4) { - var frameFound = false; - - for (let mm = 0; mm < this._currentAnimeFrames.keyFrames.length; mm++) { - if (this._currentAnimeFrames.keyFrames[mm].Frame === keyInfo.Frame) { - keyInfo = this._currentAnimeFrames.keyFrames[mm]; - frameFound = true; - break; - } - } + function warnUnhydratedInstance(returnFiber, instance) { + { + switch (returnFiber.tag) { + case HostRoot: + didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance); + break; - var frameValue = data2[2].split(','); + case HostComponent: + didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance); + break; - switch (nowKeyType) { - case 0: - keyInfo.rot = new Quaternion(parseFloat(frameValue[1]), parseFloat(frameValue[2]), parseFloat(frameValue[3]), parseFloat(frameValue[0]) * -1); - break; + case SuspenseComponent: + var suspenseState = returnFiber.memoizedState; + if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance); + break; + } + } + } - case 1: - keyInfo.scl = new Vector3(parseFloat(frameValue[0]), parseFloat(frameValue[1]), parseFloat(frameValue[2])); - break; + function deleteHydratableInstance(returnFiber, instance) { + warnUnhydratedInstance(returnFiber, instance); + var childToDelete = createFiberFromHostInstanceForDeletion(); + childToDelete.stateNode = instance; + childToDelete.return = returnFiber; + var deletions = returnFiber.deletions; - case 2: - keyInfo.pos = new Vector3(parseFloat(frameValue[0]), parseFloat(frameValue[1]), parseFloat(frameValue[2])); - break; - } + if (deletions === null) { + returnFiber.deletions = [childToDelete]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(childToDelete); + } + } - if (!frameFound) { - this._currentAnimeFrames.keyFrames.push(keyInfo); - } - } else { - keyInfo.matrix = new Matrix4(); + function warnNonhydratedInstance(returnFiber, fiber) { + { + if (didSuspend) { + // Inside a boundary that already suspended. We're currently rendering the + // siblings of a suspended node. The mismatch may be due to the missing + // data, so it's probably a false positive. + return; + } - this._ParseMatrixData(keyInfo.matrix, data2[2].split(',')); + switch (returnFiber.tag) { + case HostRoot: + { + var parentContainer = returnFiber.stateNode.containerInfo; - this._currentAnimeFrames.keyFrames.push(keyInfo); - } - } - } - }, { - key: '_makeOutputAnimation', - value: function _makeOutputAnimation() { - var animationObj = new XAnimationObj(this.options); - animationObj.fps = this.animTicksPerSecond; - animationObj.name = this._currentAnime.name; - animationObj.make(this._currentAnime.AnimeFrames); - this.animations.push(animationObj); - } - }, { - key: 'assignAnimation', - value: function assignAnimation(_model, _animation) { - var model = _model; - var animation = _animation; - - if (!model) { - model = this.Meshes[0]; - } + switch (fiber.tag) { + case HostComponent: + var type = fiber.type; + var props = fiber.pendingProps; + didNotFindHydratableInstanceWithinContainer(parentContainer, type, props); + break; - if (!animation) { - animation = this.animations[0]; - } + case HostText: + var text = fiber.pendingProps; + didNotFindHydratableTextInstanceWithinContainer(parentContainer, text); + break; - if (!model || !animation) { - return null; - } + case SuspenseComponent: + didNotFindHydratableSuspenseInstanceWithinContainer(parentContainer); + break; + } - var put = {}; - put.fps = animation.fps; - put.name = animation.name; - put.length = animation.length; - put.hierarchy = []; - - for (let b = 0; b < model.skeleton.bones.length; b++) { - var findAnimation = false; - - for (let i = 0; i < animation.hierarchy.length; i++) { - if (model.skeleton.bones[b].name === animation.hierarchy[i].name) { - findAnimation = true; - var c_key = animation.hierarchy[i].copy(); - c_key.parent = -1; - - if (model.skeleton.bones[b].parent && model.skeleton.bones[b].parent.type === 'Bone') { - for (let bb = 0; bb < put.hierarchy.length; bb++) { - if (put.hierarchy[bb].name === model.skeleton.bones[b].parent.name) { - c_key.parent = bb; - c_key.parentName = model.skeleton.bones[b].parent.name; - } - } - } + break; + } - put.hierarchy.push(c_key); - break; - } - } + case HostComponent: + { + var parentType = returnFiber.type; + var parentProps = returnFiber.memoizedProps; + var parentInstance = returnFiber.stateNode; - if (!findAnimation) { - var _c_key = animation.hierarchy[0].copy(); + switch (fiber.tag) { + case HostComponent: + var _type = fiber.type; + var _props = fiber.pendingProps; + didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props); + break; - _c_key.name = model.skeleton.bones[b].name; - _c_key.parent = -1; + case HostText: + var _text = fiber.pendingProps; + didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text); + break; - for (let k = 0; k < _c_key.keys.length; k++) { - if (_c_key.keys[k].pos) { - _c_key.keys[k].pos.set(0, 0, 0); - } + case SuspenseComponent: + didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance); + break; + } - if (_c_key.keys[k].scl) { - _c_key.keys[k].scl.set(1, 1, 1); - } + break; + } - if (_c_key.keys[k].rot) { - _c_key.keys[k].rot.set(0, 0, 0, 1); - } - } + case SuspenseComponent: + { + var suspenseState = returnFiber.memoizedState; + var _parentInstance = suspenseState.dehydrated; + if (_parentInstance !== null) switch (fiber.tag) { + case HostComponent: + var _type2 = fiber.type; + var _props2 = fiber.pendingProps; + didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2, _props2); + break; - put.hierarchy.push(_c_key); - } - } + case HostText: + var _text2 = fiber.pendingProps; + didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2); + break; - if (!model.geometry.animations) { - model.geometry.animations = []; - } + case SuspenseComponent: + didNotFindHydratableSuspenseInstanceWithinSuspenseInstance(_parentInstance); + break; + } + break; + } - model.geometry.animations.push(AnimationClip.parseAnimation(put, model.skeleton.bones)); + default: + return; + } + } + } - if (!model.animationMixer) { - model.animationMixer = new AnimationMixer(model); - } + function insertNonHydratedInstance(returnFiber, fiber) { + fiber.flags = fiber.flags & ~Hydrating | Placement; + warnNonhydratedInstance(returnFiber, fiber); + } - return put; - } - }, { - key: '_ParseMatrixData', - value: function _ParseMatrixData(targetMatrix, data) { - targetMatrix.set(parseFloat(data[0]), parseFloat(data[4]), parseFloat(data[8]), parseFloat(data[12]), parseFloat(data[1]), parseFloat(data[5]), parseFloat(data[9]), parseFloat(data[13]), parseFloat(data[2]), parseFloat(data[6]), parseFloat(data[10]), parseFloat(data[14]), parseFloat(data[3]), parseFloat(data[7]), parseFloat(data[11]), parseFloat(data[15])); - } - }]); - return XLoader; - }(); + function tryHydrate(fiber, nextInstance) { + switch (fiber.tag) { + case HostComponent: + { + var type = fiber.type; + var props = fiber.pendingProps; + var instance = canHydrateInstance(nextInstance, type, props); - return XLoader; -})(); + if (instance !== null) { + fiber.stateNode = instance; + hydrationParentFiber = fiber; + nextHydratableInstance = getFirstHydratableChild(instance); + return true; + } -var api$3 = {}; + return false; + } -var version = {}; + case HostText: + { + var text = fiber.pendingProps; + var textInstance = canHydrateTextInstance(nextInstance, text); -Object.defineProperty(version, "__esModule", { value: true }); -version.VERSION = void 0; -// needs a separate module as this is required inside chevrotain productive code -// and also in the entry point for webpack(api.ts). -// A separate file avoids cyclic dependencies and webpack errors. -version.VERSION = "10.1.2"; + if (textInstance !== null) { + fiber.stateNode = textInstance; + hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate. -var parser = {}; + nextHydratableInstance = null; + return true; + } -/** Used for built-in method references. */ + return false; + } -var objectProto$l = Object.prototype; + case SuspenseComponent: + { + { + var suspenseInstance = canHydrateSuspenseInstance(nextInstance); -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype$6(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$l; + if (suspenseInstance !== null) { + var suspenseState = { + dehydrated: suspenseInstance, + treeContext: getSuspendedTreeContext(), + retryLane: OffscreenLane + }; + fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. + // This simplifies the code for getHostSibling and deleting nodes, + // since it doesn't have to consider all Suspense boundaries and + // check if they're dehydrated ones or not. - return value === proto; -} + var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); + dehydratedFragment.return = fiber; + fiber.child = dehydratedFragment; + hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into + // it during the first pass. Instead, we'll reenter it later. -var _isPrototype = isPrototype$6; + nextHydratableInstance = null; + return true; + } + } -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ + return false; + } -function overArg$3(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} + default: + return false; + } + } -var _overArg = overArg$3; + function shouldClientRenderOnMismatch(fiber) { + return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags; + } -var overArg$2 = _overArg; + function throwOnHydrationMismatch(fiber) { + throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.'); + } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys$1 = overArg$2(Object.keys, Object); + function tryToClaimNextHydratableInstance(fiber) { + if (!isHydrating) { + return; + } -var _nativeKeys = nativeKeys$1; + var nextInstance = nextHydratableInstance; -var isPrototype$5 = _isPrototype, - nativeKeys = _nativeKeys; + if (!nextInstance) { + if (shouldClientRenderOnMismatch(fiber)) { + warnNonhydratedInstance(hydrationParentFiber, fiber); + throwOnHydrationMismatch(); + } // Nothing to hydrate. Make it an insertion. -/** Used for built-in method references. */ -var objectProto$k = Object.prototype; -/** Used to check objects for own properties. */ -var hasOwnProperty$i = objectProto$k.hasOwnProperty; + insertNonHydratedInstance(hydrationParentFiber, fiber); + isHydrating = false; + hydrationParentFiber = fiber; + return; + } -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys$2(object) { - if (!isPrototype$5(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$i.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; -} + var firstAttemptedInstance = nextInstance; -var _baseKeys = baseKeys$2; + if (!tryHydrate(fiber, nextInstance)) { + if (shouldClientRenderOnMismatch(fiber)) { + warnNonhydratedInstance(hydrationParentFiber, fiber); + throwOnHydrationMismatch(); + } // If we can't hydrate this instance let's try the next one. + // We use this as a heuristic. It's based on intuition and not data so it + // might be flawed or unnecessary. -/** Detect free variable `global` from Node.js. */ -var freeGlobal$3 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + nextInstance = getNextHydratableSibling(firstAttemptedInstance); + var prevHydrationParentFiber = hydrationParentFiber; -var _freeGlobal = freeGlobal$3; + if (!nextInstance || !tryHydrate(fiber, nextInstance)) { + // Nothing to hydrate. Make it an insertion. + insertNonHydratedInstance(hydrationParentFiber, fiber); + isHydrating = false; + hydrationParentFiber = fiber; + return; + } // We matched the next one, we'll now assume that the first one was + // superfluous and we'll delete it. Since we can't eagerly delete it + // we'll have to schedule a deletion. To do that, this node needs a dummy + // fiber associated with it. -var freeGlobal$2 = _freeGlobal; -/** Detect free variable `self`. */ -var freeSelf$2 = typeof self == 'object' && self && self.Object === Object && self; + deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); + } + } -/** Used as a reference to the global object. */ -var root$a = freeGlobal$2 || freeSelf$2 || Function('return this')(); + function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { + if (!supportsHydration) { + throw new Error('Expected prepareToHydrateHostInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -var _root = root$a; + var instance = fiber.stateNode; + var shouldWarnIfMismatchDev = !didSuspend; + var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component. -var root$9 = _root; + fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there + // is a new ref we mark this as an update. -/** Built-in value references. */ -var Symbol$9 = root$9.Symbol; + if (updatePayload !== null) { + return true; + } -var _Symbol = Symbol$9; + return false; + } -var Symbol$8 = _Symbol; + function prepareToHydrateHostTextInstance(fiber) { + if (!supportsHydration) { + throw new Error('Expected prepareToHydrateHostTextInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** Used for built-in method references. */ -var objectProto$j = Object.prototype; + var textInstance = fiber.stateNode; + var textContent = fiber.memoizedProps; + var shouldWarnIfMismatchDev = !didSuspend; + var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber, shouldWarnIfMismatchDev); -/** Used to check objects for own properties. */ -var hasOwnProperty$h = objectProto$j.hasOwnProperty; + if (shouldUpdate) { + // We assume that prepareToHydrateHostTextInstance is called in a context where the + // hydration parent is the parent host component of this host text. + var returnFiber = hydrationParentFiber; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$j.toString; + if (returnFiber !== null) { + var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; -/** Built-in value references. */ -var symToStringTag$1 = Symbol$8 ? Symbol$8.toStringTag : undefined; + switch (returnFiber.tag) { + case HostRoot: + { + var parentContainer = returnFiber.stateNode.containerInfo; + didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. + isConcurrentMode); + break; + } -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag$1(value) { - var isOwn = hasOwnProperty$h.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; + case HostComponent: + { + var parentType = returnFiber.type; + var parentProps = returnFiber.memoizedProps; + var parentInstance = returnFiber.stateNode; + didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. + isConcurrentMode); + break; + } + } + } + } - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString$1.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - return result; -} + return shouldUpdate; + } -var _getRawTag = getRawTag$1; + function prepareToHydrateHostSuspenseInstance(fiber) { + if (!supportsHydration) { + throw new Error('Expected prepareToHydrateHostSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** Used for built-in method references. */ + var suspenseState = fiber.memoizedState; + var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; -var objectProto$i = Object.prototype; + if (!suspenseInstance) { + throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto$i.toString; + hydrateSuspenseInstance(suspenseInstance, fiber); + } -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString$3(value) { - return nativeObjectToString.call(value); -} + function skipPastDehydratedSuspenseInstance(fiber) { + if (!supportsHydration) { + throw new Error('Expected skipPastDehydratedSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -var _objectToString = objectToString$3; + var suspenseState = fiber.memoizedState; + var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; -var Symbol$7 = _Symbol, - getRawTag = _getRawTag, - objectToString$2 = _objectToString; + if (!suspenseInstance) { + throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; + return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); + } -/** Built-in value references. */ -var symToStringTag = Symbol$7 ? Symbol$7.toStringTag : undefined; + function popToNextHostParent(fiber) { + var parent = fiber.return; -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag$7(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString$2(value); -} + while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) { + parent = parent.return; + } -var _baseGetTag = baseGetTag$7; + hydrationParentFiber = parent; + } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ + function popHydrationState(fiber) { + if (!supportsHydration) { + return false; + } -function isObject$b(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} + if (fiber !== hydrationParentFiber) { + // We're deeper than the current hydration context, inside an inserted + // tree. + return false; + } -var isObject_1 = isObject$b; + if (!isHydrating) { + // If we're not currently hydrating but we're in a hydration context, then + // we were an insertion and now need to pop up reenter hydration of our + // siblings. + popToNextHostParent(fiber); + isHydrating = true; + return false; + } // If we have any remaining hydratable nodes, we need to delete them now. + // We only do this deeper than head and body since they tend to have random + // other nodes in them. We also ignore components with pure text content in + // side of them. We also don't delete anything inside the root container. -var baseGetTag$6 = _baseGetTag, - isObject$a = isObject_1; -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]', - funcTag$4 = '[object Function]', - genTag$3 = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; + if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) { + var nextInstance = nextHydratableInstance; -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction$4(value) { - if (!isObject$a(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag$6(value); - return tag == funcTag$4 || tag == genTag$3 || tag == asyncTag || tag == proxyTag; -} + if (nextInstance) { + if (shouldClientRenderOnMismatch(fiber)) { + warnIfUnhydratedTailNodes(fiber); + throwOnHydrationMismatch(); + } else { + while (nextInstance) { + deleteHydratableInstance(fiber, nextInstance); + nextInstance = getNextHydratableSibling(nextInstance); + } + } + } + } -var isFunction_1 = isFunction$4; + popToNextHostParent(fiber); -var root$8 = _root; + if (fiber.tag === SuspenseComponent) { + nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); + } else { + nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; + } -/** Used to detect overreaching core-js shims. */ -var coreJsData$2 = root$8['__core-js_shared__']; + return true; + } -var _coreJsData = coreJsData$2; + function hasUnhydratedTailNodes() { + return isHydrating && nextHydratableInstance !== null; + } -var coreJsData$1 = _coreJsData; + function warnIfUnhydratedTailNodes(fiber) { + var nextInstance = nextHydratableInstance; -/** Used to detect methods masquerading as native. */ -var maskSrcKey$1 = (function() { - var uid = /[^.]+$/.exec(coreJsData$1 && coreJsData$1.keys && coreJsData$1.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); + while (nextInstance) { + warnUnhydratedInstance(fiber, nextInstance); + nextInstance = getNextHydratableSibling(nextInstance); + } + } -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked$2(func) { - return !!maskSrcKey$1 && (maskSrcKey$1 in func); -} + function resetHydrationState() { + if (!supportsHydration) { + return; + } -var _isMasked = isMasked$2; + hydrationParentFiber = null; + nextHydratableInstance = null; + isHydrating = false; + didSuspend = false; + } -/** Used for built-in method references. */ + function upgradeHydrationErrorsToRecoverable() { + if (hydrationErrors !== null) { + // Successfully completed a forced client render. The errors that occurred + // during the hydration attempt are now recovered. We will log them in + // commit phase, once the entire tree has finished. + queueRecoverableErrors(hydrationErrors); + hydrationErrors = null; + } + } -var funcProto$2 = Function.prototype; + function getIsHydrating() { + return isHydrating; + } -/** Used to resolve the decompiled source of functions. */ -var funcToString$2 = funcProto$2.toString; + function queueHydrationError(error) { + if (hydrationErrors === null) { + hydrationErrors = [error]; + } else { + hydrationErrors.push(error); + } + } -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ -function toSource$3(func) { - if (func != null) { - try { - return funcToString$2.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; -} + var didWarnAboutMaps; + var didWarnAboutGenerators; + var didWarnAboutStringRefs; + var ownerHasKeyUseWarning; + var ownerHasFunctionTypeWarning; -var _toSource = toSource$3; + var warnForMissingKey = function (child, returnFiber) {}; -var isFunction$3 = isFunction_1, - isMasked$1 = _isMasked, - isObject$9 = isObject_1, - toSource$2 = _toSource; + { + didWarnAboutMaps = false; + didWarnAboutGenerators = false; + didWarnAboutStringRefs = {}; + /** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g; + ownerHasKeyUseWarning = {}; + ownerHasFunctionTypeWarning = {}; -/** Used to detect host constructors (Safari). */ -var reIsHostCtor$1 = /^\[object .+?Constructor\]$/; + warnForMissingKey = function (child, returnFiber) { + if (child === null || typeof child !== 'object') { + return; + } -/** Used for built-in method references. */ -var funcProto$1 = Function.prototype, - objectProto$h = Object.prototype; + if (!child._store || child._store.validated || child.key != null) { + return; + } -/** Used to resolve the decompiled source of functions. */ -var funcToString$1 = funcProto$1.toString; + if (typeof child._store !== 'object') { + throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** Used to check objects for own properties. */ -var hasOwnProperty$g = objectProto$h.hasOwnProperty; + child._store.validated = true; + var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; -/** Used to detect if a method is native. */ -var reIsNative$1 = RegExp('^' + - funcToString$1.call(hasOwnProperty$g).replace(reRegExpChar$1, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); + if (ownerHasKeyUseWarning[componentName]) { + return; + } -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative$2(value) { - if (!isObject$9(value) || isMasked$1(value)) { - return false; - } - var pattern = isFunction$3(value) ? reIsNative$1 : reIsHostCtor$1; - return pattern.test(toSource$2(value)); -} + ownerHasKeyUseWarning[componentName] = true; -var _baseIsNative = baseIsNative$2; + error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.'); + }; + } -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ + function coerceRef(returnFiber, current, element) { + var mixedRef = element.ref; -function getValue$2(object, key) { - return object == null ? undefined : object[key]; -} + if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') { + { + // TODO: Clean this up once we turn on the string ref warning for + // everyone, because the strict mode case will no longer be relevant + if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs + // because these cannot be automatically converted to an arrow function + // using a codemod. Therefore, we don't have to warn about string refs again. + !(element._owner && element._self && element._owner.stateNode !== element._self)) { + var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; -var _getValue = getValue$2; + if (!didWarnAboutStringRefs[componentName]) { + { + error('A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', mixedRef); + } -var baseIsNative$1 = _baseIsNative, - getValue$1 = _getValue; + didWarnAboutStringRefs[componentName] = true; + } + } + } -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative$8(object, key) { - var value = getValue$1(object, key); - return baseIsNative$1(value) ? value : undefined; -} + if (element._owner) { + var owner = element._owner; + var inst; -var _getNative = getNative$8; + if (owner) { + var ownerFiber = owner; -var getNative$7 = _getNative, - root$7 = _root; + if (ownerFiber.tag !== ClassComponent) { + throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref'); + } -/* Built-in method references that are verified to be native. */ -var DataView$2 = getNative$7(root$7, 'DataView'); + inst = ownerFiber.stateNode; + } -var _DataView = DataView$2; + if (!inst) { + throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.'); + } // Assigning this to a const so Flow knows it won't change in the closure -var getNative$6 = _getNative, - root$6 = _root; -/* Built-in method references that are verified to be native. */ -var Map$5 = getNative$6(root$6, 'Map'); + var resolvedInst = inst; -var _Map = Map$5; + { + checkPropStringCoercion(mixedRef, 'ref'); + } -var getNative$5 = _getNative, - root$5 = _root; + var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref -/* Built-in method references that are verified to be native. */ -var Promise$2 = getNative$5(root$5, 'Promise'); + if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) { + return current.ref; + } -var _Promise = Promise$2; + var ref = function (value) { + var refs = resolvedInst.refs; -var getNative$4 = _getNative, - root$4 = _root; + if (refs === emptyRefsObject) { + // This is a lazy pooled frozen object, so we need to initialize. + refs = resolvedInst.refs = {}; + } -/* Built-in method references that are verified to be native. */ -var Set$3 = getNative$4(root$4, 'Set'); + if (value === null) { + delete refs[stringRef]; + } else { + refs[stringRef] = value; + } + }; -var _Set = Set$3; + ref._stringRef = stringRef; + return ref; + } else { + if (typeof mixedRef !== 'string') { + throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.'); + } -var getNative$3 = _getNative, - root$3 = _root; + if (!element._owner) { + throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.'); + } + } + } -/* Built-in method references that are verified to be native. */ -var WeakMap$2 = getNative$3(root$3, 'WeakMap'); + return mixedRef; + } -var _WeakMap = WeakMap$2; + function throwOnInvalidObjectType(returnFiber, newChild) { + var childString = Object.prototype.toString.call(newChild); + throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); + } -var DataView$1 = _DataView, - Map$4 = _Map, - Promise$1 = _Promise, - Set$2 = _Set, - WeakMap$1 = _WeakMap, - baseGetTag$5 = _baseGetTag, - toSource$1 = _toSource; + function warnOnFunctionType(returnFiber) { + { + var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; -/** `Object#toString` result references. */ -var mapTag$6 = '[object Map]', - objectTag$3 = '[object Object]', - promiseTag = '[object Promise]', - setTag$6 = '[object Set]', - weakMapTag$2 = '[object WeakMap]'; + if (ownerHasFunctionTypeWarning[componentName]) { + return; + } -var dataViewTag$4 = '[object DataView]'; + ownerHasFunctionTypeWarning[componentName] = true; -/** Used to detect maps, sets, and weakmaps. */ -var dataViewCtorString = toSource$1(DataView$1), - mapCtorString = toSource$1(Map$4), - promiseCtorString = toSource$1(Promise$1), - setCtorString = toSource$1(Set$2), - weakMapCtorString = toSource$1(WeakMap$1); + error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.'); + } + } -/** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -var getTag$6 = baseGetTag$5; - -// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. -if ((DataView$1 && getTag$6(new DataView$1(new ArrayBuffer(1))) != dataViewTag$4) || - (Map$4 && getTag$6(new Map$4) != mapTag$6) || - (Promise$1 && getTag$6(Promise$1.resolve()) != promiseTag) || - (Set$2 && getTag$6(new Set$2) != setTag$6) || - (WeakMap$1 && getTag$6(new WeakMap$1) != weakMapTag$2)) { - getTag$6 = function(value) { - var result = baseGetTag$5(value), - Ctor = result == objectTag$3 ? value.constructor : undefined, - ctorString = Ctor ? toSource$1(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$4; - case mapCtorString: return mapTag$6; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$6; - case weakMapCtorString: return weakMapTag$2; - } - } - return result; - }; -} + function resolveLazy(lazyType) { + var payload = lazyType._payload; + var init = lazyType._init; + return init(payload); + } // This wrapper function exists because I expect to clone the code in each path + // to be able to optimize each path individually by branching early. This needs + // a compiler or we can do it manually. Helpers that don't need this branching + // live outside of this function. -var _getTag = getTag$6; -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ + function ChildReconciler(shouldTrackSideEffects) { + function deleteChild(returnFiber, childToDelete) { + if (!shouldTrackSideEffects) { + // Noop. + return; + } -function isObjectLike$c(value) { - return value != null && typeof value == 'object'; -} + var deletions = returnFiber.deletions; -var isObjectLike_1 = isObjectLike$c; + if (deletions === null) { + returnFiber.deletions = [childToDelete]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(childToDelete); + } + } -var baseGetTag$4 = _baseGetTag, - isObjectLike$b = isObjectLike_1; + function deleteRemainingChildren(returnFiber, currentFirstChild) { + if (!shouldTrackSideEffects) { + // Noop. + return null; + } // TODO: For the shouldClone case, this could be micro-optimized a bit by + // assuming that after the first child we've already added everything. -/** `Object#toString` result references. */ -var argsTag$5 = '[object Arguments]'; -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments$1(value) { - return isObjectLike$b(value) && baseGetTag$4(value) == argsTag$5; -} + var childToDelete = currentFirstChild; -var _baseIsArguments = baseIsArguments$1; + while (childToDelete !== null) { + deleteChild(returnFiber, childToDelete); + childToDelete = childToDelete.sibling; + } -var baseIsArguments = _baseIsArguments, - isObjectLike$a = isObjectLike_1; + return null; + } -/** Used for built-in method references. */ -var objectProto$g = Object.prototype; + function mapRemainingChildren(returnFiber, currentFirstChild) { + // Add the remaining children to a temporary map so that we can find them by + // keys quickly. Implicit (null) keys get added to this set with their index + // instead. + var existingChildren = new Map(); + var existingChild = currentFirstChild; -/** Used to check objects for own properties. */ -var hasOwnProperty$f = objectProto$g.hasOwnProperty; + while (existingChild !== null) { + if (existingChild.key !== null) { + existingChildren.set(existingChild.key, existingChild); + } else { + existingChildren.set(existingChild.index, existingChild); + } -/** Built-in value references. */ -var propertyIsEnumerable$3 = objectProto$g.propertyIsEnumerable; + existingChild = existingChild.sibling; + } -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments$6 = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike$a(value) && hasOwnProperty$f.call(value, 'callee') && - !propertyIsEnumerable$3.call(value, 'callee'); -}; + return existingChildren; + } -var isArguments_1 = isArguments$6; + function useFiber(fiber, pendingProps) { + // We currently set sibling to null and index to 0 here because it is easy + // to forget to do before returning it. E.g. for the single child case. + var clone = createWorkInProgress(fiber, pendingProps); + clone.index = 0; + clone.sibling = null; + return clone; + } -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ + function placeChild(newFiber, lastPlacedIndex, newIndex) { + newFiber.index = newIndex; -var isArray$m = Array.isArray; + if (!shouldTrackSideEffects) { + // During hydration, the useId algorithm needs to know which fibers are + // part of a list of children (arrays, iterators). + newFiber.flags |= Forked; + return lastPlacedIndex; + } -var isArray_1$1 = isArray$m; + var current = newFiber.alternate; -/** Used as references for various `Number` constants. */ + if (current !== null) { + var oldIndex = current.index; -var MAX_SAFE_INTEGER$3 = 9007199254740991; + if (oldIndex < lastPlacedIndex) { + // This is a move. + newFiber.flags |= Placement; + return lastPlacedIndex; + } else { + // This item can stay in place. + return oldIndex; + } + } else { + // This is an insertion. + newFiber.flags |= Placement; + return lastPlacedIndex; + } + } -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength$5(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$3; -} + function placeSingleChild(newFiber) { + // This is simpler for the single child case. We only need to do a + // placement for inserting new children. + if (shouldTrackSideEffects && newFiber.alternate === null) { + newFiber.flags |= Placement; + } -var isLength_1 = isLength$5; + return newFiber; + } -var isFunction$2 = isFunction_1, - isLength$4 = isLength_1; + function updateTextNode(returnFiber, current, textContent, lanes) { + if (current === null || current.tag !== HostText) { + // Insert + var created = createFiberFromText(textContent, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } else { + // Update + var existing = useFiber(current, textContent); + existing.return = returnFiber; + return existing; + } + } -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike$c(value) { - return value != null && isLength$4(value.length) && !isFunction$2(value); -} + function updateElement(returnFiber, current, element, lanes) { + var elementType = element.type; -var isArrayLike_1 = isArrayLike$c; + if (elementType === REACT_FRAGMENT_TYPE) { + return updateFragment(returnFiber, current, element.props.children, lanes, element.key); + } -var isBuffer$4 = {exports: {}}; + if (current !== null) { + if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path: + isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type. + // We need to do this after the Hot Reloading check above, + // because hot reloading has different semantics than prod because + // it doesn't resuspend. So we can't let the call below suspend. + typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) { + // Move based on index + var existing = useFiber(current, element.props); + existing.ref = coerceRef(returnFiber, current, element); + existing.return = returnFiber; -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ + { + existing._debugSource = element._source; + existing._debugOwner = element._owner; + } -function stubFalse() { - return false; -} + return existing; + } + } // Insert -var stubFalse_1 = stubFalse; -(function (module, exports) { - var root = _root, - stubFalse = stubFalse_1; + var created = createFiberFromElement(element, returnFiber.mode, lanes); + created.ref = coerceRef(returnFiber, current, element); + created.return = returnFiber; + return created; + } - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; + function updatePortal(returnFiber, current, portal, lanes) { + if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) { + // Insert + var created = createFiberFromPortal(portal, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } else { + // Update + var existing = useFiber(current, portal.children || []); + existing.return = returnFiber; + return existing; + } + } - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + function updateFragment(returnFiber, current, fragment, lanes, key) { + if (current === null || current.tag !== Fragment) { + // Insert + var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key); + created.return = returnFiber; + return created; + } else { + // Update + var existing = useFiber(current, fragment); + existing.return = returnFiber; + return existing; + } + } - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + function createChild(returnFiber, newChild, lanes) { + if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { + // Text nodes don't have keys. If the previous node is implicitly keyed + // we can continue to replace it without aborting even if it is not a text + // node. + var created = createFiberFromText('' + newChild, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined; + if (typeof newChild === 'object' && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: + { + var _created = createFiberFromElement(newChild, returnFiber.mode, lanes); - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + _created.ref = coerceRef(returnFiber, null, newChild); + _created.return = returnFiber; + return _created; + } - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; + case REACT_PORTAL_TYPE: + { + var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes); - module.exports = isBuffer; -} (isBuffer$4, isBuffer$4.exports)); + _created2.return = returnFiber; + return _created2; + } -var baseGetTag$3 = _baseGetTag, - isLength$3 = isLength_1, - isObjectLike$9 = isObjectLike_1; + case REACT_LAZY_TYPE: + { + { + var payload = newChild._payload; + var init = newChild._init; + return createChild(returnFiber, init(payload), lanes); + } + } + } -/** `Object#toString` result references. */ -var argsTag$4 = '[object Arguments]', - arrayTag$2 = '[object Array]', - boolTag$3 = '[object Boolean]', - dateTag$3 = '[object Date]', - errorTag$2 = '[object Error]', - funcTag$3 = '[object Function]', - mapTag$5 = '[object Map]', - numberTag$3 = '[object Number]', - objectTag$2 = '[object Object]', - regexpTag$4 = '[object RegExp]', - setTag$5 = '[object Set]', - stringTag$4 = '[object String]', - weakMapTag$1 = '[object WeakMap]'; - -var arrayBufferTag$3 = '[object ArrayBuffer]', - dataViewTag$3 = '[object DataView]', - float32Tag$2 = '[object Float32Array]', - float64Tag$2 = '[object Float64Array]', - int8Tag$2 = '[object Int8Array]', - int16Tag$2 = '[object Int16Array]', - int32Tag$2 = '[object Int32Array]', - uint8Tag$2 = '[object Uint8Array]', - uint8ClampedTag$2 = '[object Uint8ClampedArray]', - uint16Tag$2 = '[object Uint16Array]', - uint32Tag$2 = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] = -typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] = -typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] = -typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] = -typedArrayTags[uint32Tag$2] = true; -typedArrayTags[argsTag$4] = typedArrayTags[arrayTag$2] = -typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$3] = -typedArrayTags[dataViewTag$3] = typedArrayTags[dateTag$3] = -typedArrayTags[errorTag$2] = typedArrayTags[funcTag$3] = -typedArrayTags[mapTag$5] = typedArrayTags[numberTag$3] = -typedArrayTags[objectTag$2] = typedArrayTags[regexpTag$4] = -typedArrayTags[setTag$5] = typedArrayTags[stringTag$4] = -typedArrayTags[weakMapTag$1] = false; + if (isArray(newChild) || getIteratorFn(newChild)) { + var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null); -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray$1(value) { - return isObjectLike$9(value) && - isLength$3(value.length) && !!typedArrayTags[baseGetTag$3(value)]; -} + _created3.return = returnFiber; + return _created3; + } -var _baseIsTypedArray = baseIsTypedArray$1; + throwOnInvalidObjectType(returnFiber, newChild); + } -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ + { + if (typeof newChild === 'function') { + warnOnFunctionType(returnFiber); + } + } -function baseUnary$6(func) { - return function(value) { - return func(value); - }; -} + return null; + } -var _baseUnary = baseUnary$6; + function updateSlot(returnFiber, oldFiber, newChild, lanes) { + // Update the fiber if the keys match, otherwise return null. + var key = oldFiber !== null ? oldFiber.key : null; -var _nodeUtil = {exports: {}}; + if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { + // Text nodes don't have keys. If the previous node is implicitly keyed + // we can continue to replace it without aborting even if it is not a text + // node. + if (key !== null) { + return null; + } -(function (module, exports) { - var freeGlobal = _freeGlobal; + return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes); + } - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; + if (typeof newChild === 'object' && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: + { + if (newChild.key === key) { + return updateElement(returnFiber, oldFiber, newChild, lanes); + } else { + return null; + } + } - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + case REACT_PORTAL_TYPE: + { + if (newChild.key === key) { + return updatePortal(returnFiber, oldFiber, newChild, lanes); + } else { + return null; + } + } - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + case REACT_LAZY_TYPE: + { + { + var payload = newChild._payload; + var init = newChild._init; + return updateSlot(returnFiber, oldFiber, init(payload), lanes); + } + } + } - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; + if (isArray(newChild) || getIteratorFn(newChild)) { + if (key !== null) { + return null; + } - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; + return updateFragment(returnFiber, oldFiber, newChild, lanes, null); + } - if (types) { - return types; + throwOnInvalidObjectType(returnFiber, newChild); } - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - module.exports = nodeUtil; -} (_nodeUtil, _nodeUtil.exports)); + { + if (typeof newChild === 'function') { + warnOnFunctionType(returnFiber); + } + } -var baseIsTypedArray = _baseIsTypedArray, - baseUnary$5 = _baseUnary, - nodeUtil$3 = _nodeUtil.exports; + return null; + } -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil$3 && nodeUtil$3.isTypedArray; + function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) { + if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { + // Text nodes don't have keys, so we neither have to check the old nor + // new node for the key. If both are text nodes, they match. + var matchedFiber = existingChildren.get(newIdx) || null; + return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes); + } -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray$3 = nodeIsTypedArray ? baseUnary$5(nodeIsTypedArray) : baseIsTypedArray; + if (typeof newChild === 'object' && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: + { + var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; -var isTypedArray_1 = isTypedArray$3; + return updateElement(returnFiber, _matchedFiber, newChild, lanes); + } -var baseKeys$1 = _baseKeys, - getTag$5 = _getTag, - isArguments$5 = isArguments_1, - isArray$l = isArray_1$1, - isArrayLike$b = isArrayLike_1, - isBuffer$3 = isBuffer$4.exports, - isPrototype$4 = _isPrototype, - isTypedArray$2 = isTypedArray_1; + case REACT_PORTAL_TYPE: + { + var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; -/** `Object#toString` result references. */ -var mapTag$4 = '[object Map]', - setTag$4 = '[object Set]'; + return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); + } -/** Used for built-in method references. */ -var objectProto$f = Object.prototype; + case REACT_LAZY_TYPE: + { + var payload = newChild._payload; + var init = newChild._init; + return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes); + } -/** Used to check objects for own properties. */ -var hasOwnProperty$e = objectProto$f.hasOwnProperty; + } -/** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ -function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike$b(value) && - (isArray$l(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer$3(value) || isTypedArray$2(value) || isArguments$5(value))) { - return !value.length; - } - var tag = getTag$5(value); - if (tag == mapTag$4 || tag == setTag$4) { - return !value.size; - } - if (isPrototype$4(value)) { - return !baseKeys$1(value).length; - } - for (var key in value) { - if (hasOwnProperty$e.call(value, key)) { - return false; - } - } - return true; -} + if (isArray(newChild) || getIteratorFn(newChild)) { + var _matchedFiber3 = existingChildren.get(newIdx) || null; -var isEmpty_1$1 = isEmpty; + return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null); + } -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ + throwOnInvalidObjectType(returnFiber, newChild); + } -function arrayMap$7(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); + { + if (typeof newChild === 'function') { + warnOnFunctionType(returnFiber); + } + } - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} + return null; + } + /** + * Warns if there is a duplicate or missing key + */ -var _arrayMap = arrayMap$7; -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ + function warnOnInvalidKey(child, knownKeys, returnFiber) { + { + if (typeof child !== 'object' || child === null) { + return knownKeys; + } -function listCacheClear$2() { - this.__data__ = []; - this.size = 0; -} + switch (child.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + warnForMissingKey(child, returnFiber); + var key = child.key; -var _listCacheClear = listCacheClear$2; + if (typeof key !== 'string') { + break; + } -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ + if (knownKeys === null) { + knownKeys = new Set(); + knownKeys.add(key); + break; + } -function eq$6(value, other) { - return value === other || (value !== value && other !== other); -} + if (!knownKeys.has(key)) { + knownKeys.add(key); + break; + } -var eq_1 = eq$6; + error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key); -var eq$5 = eq_1; + break; -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf$5(array, key) { - var length = array.length; - while (length--) { - if (eq$5(array[length][0], key)) { - return length; - } - } - return -1; -} + case REACT_LAZY_TYPE: + { + var payload = child._payload; + var init = child._init; + warnOnInvalidKey(init(payload), knownKeys, returnFiber); + break; + } + } + } -var _assocIndexOf = assocIndexOf$5; + return knownKeys; + } -var assocIndexOf$4 = _assocIndexOf; + function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) { + // This algorithm can't optimize by searching from both ends since we + // don't have backpointers on fibers. I'm trying to see how far we can get + // with that model. If it ends up not being worth the tradeoffs, we can + // add it later. + // Even with a two ended optimization, we'd want to optimize for the case + // where there are few changes and brute force the comparison instead of + // going for the Map. It'd like to explore hitting that path first in + // forward-only mode and only go for the Map once we notice that we need + // lots of look ahead. This doesn't handle reversal as well as two ended + // search but that's unusual. Besides, for the two ended optimization to + // work on Iterables, we'd need to copy the whole set. + // In this first iteration, we'll just live with hitting the bad case + // (adding everything to a Map) in for every insert/move. + // If you change this code, also update reconcileChildrenIterator() which + // uses the same algorithm. + { + // First, validate keys. + var knownKeys = null; -/** Used for built-in method references. */ -var arrayProto$1 = Array.prototype; + for (var i = 0; i < newChildren.length; i++) { + var child = newChildren[i]; + knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); + } + } -/** Built-in value references. */ -var splice$1 = arrayProto$1.splice; + var resultingFirstChild = null; + var previousNewFiber = null; + var oldFiber = currentFirstChild; + var lastPlacedIndex = 0; + var newIdx = 0; + var nextOldFiber = null; -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete$2(key) { - var data = this.__data__, - index = assocIndexOf$4(data, key); + for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { + if (oldFiber.index > newIdx) { + nextOldFiber = oldFiber; + oldFiber = null; + } else { + nextOldFiber = oldFiber.sibling; + } - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice$1.call(data, index, 1); - } - --this.size; - return true; -} + var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes); -var _listCacheDelete = listCacheDelete$2; + if (newFiber === null) { + // TODO: This breaks on empty slots like null children. That's + // unfortunate because it triggers the slow path all the time. We need + // a better way to communicate whether this was a miss or null, + // boolean, undefined, etc. + if (oldFiber === null) { + oldFiber = nextOldFiber; + } -var assocIndexOf$3 = _assocIndexOf; + break; + } -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet$2(key) { - var data = this.__data__, - index = assocIndexOf$3(data, key); + if (shouldTrackSideEffects) { + if (oldFiber && newFiber.alternate === null) { + // We matched the slot, but we didn't reuse the existing fiber, so we + // need to delete the existing child. + deleteChild(returnFiber, oldFiber); + } + } - return index < 0 ? undefined : data[index][1]; -} + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); -var _listCacheGet = listCacheGet$2; + if (previousNewFiber === null) { + // TODO: Move out of the loop. This only happens for the first run. + resultingFirstChild = newFiber; + } else { + // TODO: Defer siblings if we're not at the right index for this slot. + // I.e. if we had null values before, then we want to defer this + // for each null value. However, we also don't want to call updateSlot + // with the previous one. + previousNewFiber.sibling = newFiber; + } -var assocIndexOf$2 = _assocIndexOf; + previousNewFiber = newFiber; + oldFiber = nextOldFiber; + } -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas$2(key) { - return assocIndexOf$2(this.__data__, key) > -1; -} + if (newIdx === newChildren.length) { + // We've reached the end of the new children. We can delete the rest. + deleteRemainingChildren(returnFiber, oldFiber); -var _listCacheHas = listCacheHas$2; + if (getIsHydrating()) { + var numberOfForks = newIdx; + pushTreeFork(returnFiber, numberOfForks); + } -var assocIndexOf$1 = _assocIndexOf; + return resultingFirstChild; + } -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet$2(key, value) { - var data = this.__data__, - index = assocIndexOf$1(data, key); + if (oldFiber === null) { + // If we don't have any more existing children we can choose a fast path + // since the rest will all be insertions. + for (; newIdx < newChildren.length; newIdx++) { + var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes); - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} + if (_newFiber === null) { + continue; + } -var _listCacheSet = listCacheSet$2; + lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); -var listCacheClear$1 = _listCacheClear, - listCacheDelete$1 = _listCacheDelete, - listCacheGet$1 = _listCacheGet, - listCacheHas$1 = _listCacheHas, - listCacheSet$1 = _listCacheSet; + if (previousNewFiber === null) { + // TODO: Move out of the loop. This only happens for the first run. + resultingFirstChild = _newFiber; + } else { + previousNewFiber.sibling = _newFiber; + } -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache$5(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + previousNewFiber = _newFiber; + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + if (getIsHydrating()) { + var _numberOfForks = newIdx; + pushTreeFork(returnFiber, _numberOfForks); + } -// Add methods to `ListCache`. -ListCache$5.prototype.clear = listCacheClear$1; -ListCache$5.prototype['delete'] = listCacheDelete$1; -ListCache$5.prototype.get = listCacheGet$1; -ListCache$5.prototype.has = listCacheHas$1; -ListCache$5.prototype.set = listCacheSet$1; + return resultingFirstChild; + } // Add all children to a key map for quick lookups. -var _ListCache = ListCache$5; -var ListCache$4 = _ListCache; + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. -/** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ -function stackClear$1() { - this.__data__ = new ListCache$4; - this.size = 0; -} + for (; newIdx < newChildren.length; newIdx++) { + var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes); -var _stackClear = stackClear$1; + if (_newFiber2 !== null) { + if (shouldTrackSideEffects) { + if (_newFiber2.alternate !== null) { + // The new fiber is a work in progress, but if there exists a + // current, that means that we reused the fiber. We need to delete + // it from the child list so that we don't add it to the deletion + // list. + existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key); + } + } -/** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ + lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); -function stackDelete$1(key) { - var data = this.__data__, - result = data['delete'](key); + if (previousNewFiber === null) { + resultingFirstChild = _newFiber2; + } else { + previousNewFiber.sibling = _newFiber2; + } - this.size = data.size; - return result; -} + previousNewFiber = _newFiber2; + } + } -var _stackDelete = stackDelete$1; + if (shouldTrackSideEffects) { + // Any existing children that weren't consumed above were deleted. We need + // to add them to the deletion list. + existingChildren.forEach(function (child) { + return deleteChild(returnFiber, child); + }); + } -/** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ + if (getIsHydrating()) { + var _numberOfForks2 = newIdx; + pushTreeFork(returnFiber, _numberOfForks2); + } -function stackGet$1(key) { - return this.__data__.get(key); -} + return resultingFirstChild; + } -var _stackGet = stackGet$1; + function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) { + // This is the same implementation as reconcileChildrenArray(), + // but using the iterator instead. + var iteratorFn = getIteratorFn(newChildrenIterable); -/** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ + if (typeof iteratorFn !== 'function') { + throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.'); + } -function stackHas$1(key) { - return this.__data__.has(key); -} + { + // We don't support rendering Generators because it's a mutation. + // See https://github.com/facebook/react/issues/12995 + if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag + newChildrenIterable[Symbol.toStringTag] === 'Generator') { + if (!didWarnAboutGenerators) { + error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); + } -var _stackHas = stackHas$1; + didWarnAboutGenerators = true; + } // Warn about using Maps as children -var getNative$2 = _getNative; -/* Built-in method references that are verified to be native. */ -var nativeCreate$5 = getNative$2(Object, 'create'); + if (newChildrenIterable.entries === iteratorFn) { + if (!didWarnAboutMaps) { + error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); + } -var _nativeCreate = nativeCreate$5; + didWarnAboutMaps = true; + } // First, validate keys. + // We'll get a different iterator later for the main pass. -var nativeCreate$4 = _nativeCreate; -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear$2() { - this.__data__ = nativeCreate$4 ? nativeCreate$4(null) : {}; - this.size = 0; -} + var _newChildren = iteratorFn.call(newChildrenIterable); -var _hashClear = hashClear$2; + if (_newChildren) { + var knownKeys = null; -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ + var _step = _newChildren.next(); -function hashDelete$2(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; -} + for (; !_step.done; _step = _newChildren.next()) { + var child = _step.value; + knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); + } + } + } -var _hashDelete = hashDelete$2; + var newChildren = iteratorFn.call(newChildrenIterable); -var nativeCreate$3 = _nativeCreate; + if (newChildren == null) { + throw new Error('An iterable object provided no iterator.'); + } -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$3 = '__lodash_hash_undefined__'; + var resultingFirstChild = null; + var previousNewFiber = null; + var oldFiber = currentFirstChild; + var lastPlacedIndex = 0; + var newIdx = 0; + var nextOldFiber = null; + var step = newChildren.next(); -/** Used for built-in method references. */ -var objectProto$e = Object.prototype; + for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { + if (oldFiber.index > newIdx) { + nextOldFiber = oldFiber; + oldFiber = null; + } else { + nextOldFiber = oldFiber.sibling; + } -/** Used to check objects for own properties. */ -var hasOwnProperty$d = objectProto$e.hasOwnProperty; + var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet$2(key) { - var data = this.__data__; - if (nativeCreate$3) { - var result = data[key]; - return result === HASH_UNDEFINED$3 ? undefined : result; - } - return hasOwnProperty$d.call(data, key) ? data[key] : undefined; -} + if (newFiber === null) { + // TODO: This breaks on empty slots like null children. That's + // unfortunate because it triggers the slow path all the time. We need + // a better way to communicate whether this was a miss or null, + // boolean, undefined, etc. + if (oldFiber === null) { + oldFiber = nextOldFiber; + } -var _hashGet = hashGet$2; + break; + } -var nativeCreate$2 = _nativeCreate; + if (shouldTrackSideEffects) { + if (oldFiber && newFiber.alternate === null) { + // We matched the slot, but we didn't reuse the existing fiber, so we + // need to delete the existing child. + deleteChild(returnFiber, oldFiber); + } + } -/** Used for built-in method references. */ -var objectProto$d = Object.prototype; + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); -/** Used to check objects for own properties. */ -var hasOwnProperty$c = objectProto$d.hasOwnProperty; + if (previousNewFiber === null) { + // TODO: Move out of the loop. This only happens for the first run. + resultingFirstChild = newFiber; + } else { + // TODO: Defer siblings if we're not at the right index for this slot. + // I.e. if we had null values before, then we want to defer this + // for each null value. However, we also don't want to call updateSlot + // with the previous one. + previousNewFiber.sibling = newFiber; + } -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas$2(key) { - var data = this.__data__; - return nativeCreate$2 ? (data[key] !== undefined) : hasOwnProperty$c.call(data, key); -} + previousNewFiber = newFiber; + oldFiber = nextOldFiber; + } -var _hashHas = hashHas$2; + if (step.done) { + // We've reached the end of the new children. We can delete the rest. + deleteRemainingChildren(returnFiber, oldFiber); -var nativeCreate$1 = _nativeCreate; + if (getIsHydrating()) { + var numberOfForks = newIdx; + pushTreeFork(returnFiber, numberOfForks); + } -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + return resultingFirstChild; + } -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet$2(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate$1 && value === undefined) ? HASH_UNDEFINED$2 : value; - return this; -} + if (oldFiber === null) { + // If we don't have any more existing children we can choose a fast path + // since the rest will all be insertions. + for (; !step.done; newIdx++, step = newChildren.next()) { + var _newFiber3 = createChild(returnFiber, step.value, lanes); -var _hashSet = hashSet$2; + if (_newFiber3 === null) { + continue; + } -var hashClear$1 = _hashClear, - hashDelete$1 = _hashDelete, - hashGet$1 = _hashGet, - hashHas$1 = _hashHas, - hashSet$1 = _hashSet; + lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash$2(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + if (previousNewFiber === null) { + // TODO: Move out of the loop. This only happens for the first run. + resultingFirstChild = _newFiber3; + } else { + previousNewFiber.sibling = _newFiber3; + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + previousNewFiber = _newFiber3; + } + + if (getIsHydrating()) { + var _numberOfForks3 = newIdx; + pushTreeFork(returnFiber, _numberOfForks3); + } -// Add methods to `Hash`. -Hash$2.prototype.clear = hashClear$1; -Hash$2.prototype['delete'] = hashDelete$1; -Hash$2.prototype.get = hashGet$1; -Hash$2.prototype.has = hashHas$1; -Hash$2.prototype.set = hashSet$1; + return resultingFirstChild; + } // Add all children to a key map for quick lookups. -var _Hash = Hash$2; -var Hash$1 = _Hash, - ListCache$3 = _ListCache, - Map$3 = _Map; + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear$2() { - this.size = 0; - this.__data__ = { - 'hash': new Hash$1, - 'map': new (Map$3 || ListCache$3), - 'string': new Hash$1 - }; -} + for (; !step.done; newIdx++, step = newChildren.next()) { + var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes); -var _mapCacheClear = mapCacheClear$2; + if (_newFiber4 !== null) { + if (shouldTrackSideEffects) { + if (_newFiber4.alternate !== null) { + // The new fiber is a work in progress, but if there exists a + // current, that means that we reused the fiber. We need to delete + // it from the child list so that we don't add it to the deletion + // list. + existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key); + } + } -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ + lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); -function isKeyable$2(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); -} + if (previousNewFiber === null) { + resultingFirstChild = _newFiber4; + } else { + previousNewFiber.sibling = _newFiber4; + } -var _isKeyable = isKeyable$2; + previousNewFiber = _newFiber4; + } + } -var isKeyable$1 = _isKeyable; + if (shouldTrackSideEffects) { + // Any existing children that weren't consumed above were deleted. We need + // to add them to the deletion list. + existingChildren.forEach(function (child) { + return deleteChild(returnFiber, child); + }); + } -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData$5(map, key) { - var data = map.__data__; - return isKeyable$1(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} + if (getIsHydrating()) { + var _numberOfForks4 = newIdx; + pushTreeFork(returnFiber, _numberOfForks4); + } -var _getMapData = getMapData$5; + return resultingFirstChild; + } -var getMapData$4 = _getMapData; + function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) { + // There's no need to check for keys on text nodes since we don't have a + // way to define them. + if (currentFirstChild !== null && currentFirstChild.tag === HostText) { + // We already have an existing node so let's just update it and delete + // the rest. + deleteRemainingChildren(returnFiber, currentFirstChild.sibling); + var existing = useFiber(currentFirstChild, textContent); + existing.return = returnFiber; + return existing; + } // The existing first child is not a text node so we need to create one + // and delete the existing ones. -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete$2(key) { - var result = getMapData$4(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; -} -var _mapCacheDelete = mapCacheDelete$2; + deleteRemainingChildren(returnFiber, currentFirstChild); + var created = createFiberFromText(textContent, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } -var getMapData$3 = _getMapData; + function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) { + var key = element.key; + var child = currentFirstChild; -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet$2(key) { - return getMapData$3(this, key).get(key); -} + while (child !== null) { + // TODO: If key === null and child.key === null, then this only applies to + // the first item in the list. + if (child.key === key) { + var elementType = element.type; -var _mapCacheGet = mapCacheGet$2; + if (elementType === REACT_FRAGMENT_TYPE) { + if (child.tag === Fragment) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, element.props.children); + existing.return = returnFiber; -var getMapData$2 = _getMapData; + { + existing._debugSource = element._source; + existing._debugOwner = element._owner; + } -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas$2(key) { - return getMapData$2(this, key).has(key); -} + return existing; + } + } else { + if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path: + isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type. + // We need to do this after the Hot Reloading check above, + // because hot reloading has different semantics than prod because + // it doesn't resuspend. So we can't let the call below suspend. + typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) { + deleteRemainingChildren(returnFiber, child.sibling); -var _mapCacheHas = mapCacheHas$2; + var _existing = useFiber(child, element.props); -var getMapData$1 = _getMapData; + _existing.ref = coerceRef(returnFiber, child, element); + _existing.return = returnFiber; -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet$2(key, value) { - var data = getMapData$1(this, key), - size = data.size; + { + _existing._debugSource = element._source; + _existing._debugOwner = element._owner; + } - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; -} + return _existing; + } + } // Didn't match. -var _mapCacheSet = mapCacheSet$2; -var mapCacheClear$1 = _mapCacheClear, - mapCacheDelete$1 = _mapCacheDelete, - mapCacheGet$1 = _mapCacheGet, - mapCacheHas$1 = _mapCacheHas, - mapCacheSet$1 = _mapCacheSet; + deleteRemainingChildren(returnFiber, child); + break; + } else { + deleteChild(returnFiber, child); + } -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache$4(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + child = child.sibling; + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + if (element.type === REACT_FRAGMENT_TYPE) { + var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key); + created.return = returnFiber; + return created; + } else { + var _created4 = createFiberFromElement(element, returnFiber.mode, lanes); -// Add methods to `MapCache`. -MapCache$4.prototype.clear = mapCacheClear$1; -MapCache$4.prototype['delete'] = mapCacheDelete$1; -MapCache$4.prototype.get = mapCacheGet$1; -MapCache$4.prototype.has = mapCacheHas$1; -MapCache$4.prototype.set = mapCacheSet$1; + _created4.ref = coerceRef(returnFiber, currentFirstChild, element); + _created4.return = returnFiber; + return _created4; + } + } -var _MapCache = MapCache$4; + function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) { + var key = portal.key; + var child = currentFirstChild; -var ListCache$2 = _ListCache, - Map$2 = _Map, - MapCache$3 = _MapCache; + while (child !== null) { + // TODO: If key === null and child.key === null, then this only applies to + // the first item in the list. + if (child.key === key) { + if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, portal.children || []); + existing.return = returnFiber; + return existing; + } else { + deleteRemainingChildren(returnFiber, child); + break; + } + } else { + deleteChild(returnFiber, child); + } -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE$3 = 200; + child = child.sibling; + } -/** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ -function stackSet$1(key, value) { - var data = this.__data__; - if (data instanceof ListCache$2) { - var pairs = data.__data__; - if (!Map$2 || (pairs.length < LARGE_ARRAY_SIZE$3 - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache$3(pairs); - } - data.set(key, value); - this.size = data.size; - return this; -} + var created = createFiberFromPortal(portal, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } // This API will tag the children with the side-effect of the reconciliation + // itself. They will be added to the side-effect list as we pass through the + // children and the parent. -var _stackSet = stackSet$1; -var ListCache$1 = _ListCache, - stackClear = _stackClear, - stackDelete = _stackDelete, - stackGet = _stackGet, - stackHas = _stackHas, - stackSet = _stackSet; + function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) { + // This function is not recursive. + // If the top level item is an array, we treat it as a set of children, + // not as a fragment. Nested arrays on the other hand will be treated as + // fragment nodes. Recursion happens at the normal flow. + // Handle top level unkeyed fragments as if they were arrays. + // This leads to an ambiguity between <>{[...]} and <>.... + // We treat the ambiguous cases above the same. + var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; -/** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Stack$3(entries) { - var data = this.__data__ = new ListCache$1(entries); - this.size = data.size; -} + if (isUnkeyedTopLevelFragment) { + newChild = newChild.props.children; + } // Handle object types -// Add methods to `Stack`. -Stack$3.prototype.clear = stackClear; -Stack$3.prototype['delete'] = stackDelete; -Stack$3.prototype.get = stackGet; -Stack$3.prototype.has = stackHas; -Stack$3.prototype.set = stackSet; -var _Stack = Stack$3; + if (typeof newChild === 'object' && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: + return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes)); -/** Used to stand-in for `undefined` hash values. */ + case REACT_PORTAL_TYPE: + return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes)); -var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + case REACT_LAZY_TYPE: + { + var payload = newChild._payload; + var init = newChild._init; // TODO: This function is supposed to be non-recursive. -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd$2(value) { - this.__data__.set(value, HASH_UNDEFINED$1); - return this; -} + return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes); + } -var _setCacheAdd = setCacheAdd$2; + } -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ + if (isArray(newChild)) { + return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes); + } -function setCacheHas$2(value) { - return this.__data__.has(value); -} + if (getIteratorFn(newChild)) { + return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes); + } -var _setCacheHas = setCacheHas$2; + throwOnInvalidObjectType(returnFiber, newChild); + } -var MapCache$2 = _MapCache, - setCacheAdd$1 = _setCacheAdd, - setCacheHas$1 = _setCacheHas; + if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { + return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes)); + } -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache$4(values) { - var index = -1, - length = values == null ? 0 : values.length; + { + if (typeof newChild === 'function') { + warnOnFunctionType(returnFiber); + } + } // Remaining cases are all treated as empty. - this.__data__ = new MapCache$2; - while (++index < length) { - this.add(values[index]); - } -} -// Add methods to `SetCache`. -SetCache$4.prototype.add = SetCache$4.prototype.push = setCacheAdd$1; -SetCache$4.prototype.has = setCacheHas$1; + return deleteRemainingChildren(returnFiber, currentFirstChild); + } -var _SetCache = SetCache$4; + return reconcileChildFibers; + } -/** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ + var reconcileChildFibers = ChildReconciler(true); + var mountChildFibers = ChildReconciler(false); + function cloneChildFibers(current, workInProgress) { + if (current !== null && workInProgress.child !== current.child) { + throw new Error('Resuming work not yet implemented.'); + } -function arraySome$2(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; + if (workInProgress.child === null) { + return; + } - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; -} + var currentChild = workInProgress.child; + var newChild = createWorkInProgress(currentChild, currentChild.pendingProps); + workInProgress.child = newChild; + newChild.return = workInProgress; -var _arraySome = arraySome$2; + while (currentChild.sibling !== null) { + currentChild = currentChild.sibling; + newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps); + newChild.return = workInProgress; + } -/** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ + newChild.sibling = null; + } // Reset a workInProgress child set to prepare it for a second pass. -function cacheHas$4(cache, key) { - return cache.has(key); -} + function resetChildFibers(workInProgress, lanes) { + var child = workInProgress.child; -var _cacheHas = cacheHas$4; + while (child !== null) { + resetWorkInProgress(child, lanes); + child = child.sibling; + } + } -var SetCache$3 = _SetCache, - arraySome$1 = _arraySome, - cacheHas$3 = _cacheHas; + var NO_CONTEXT = {}; + var contextStackCursor$1 = createCursor(NO_CONTEXT); + var contextFiberStackCursor = createCursor(NO_CONTEXT); + var rootInstanceStackCursor = createCursor(NO_CONTEXT); -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; + function requiredContext(c) { + if (c === NO_CONTEXT) { + throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.'); + } -/** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ -function equalArrays$2(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5, - arrLength = array.length, - othLength = other.length; + return c; + } - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new SetCache$3 : undefined; + function getRootHostContainer() { + var rootInstance = requiredContext(rootInstanceStackCursor.current); + return rootInstance; + } - stack.set(array, other); - stack.set(other, array); + function pushHostContainer(fiber, nextRootInstance) { + // Push current root instance onto the stack; + // This allows us to reset root when portals are popped. + push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. + // This enables us to pop only Fibers that provide unique contexts. - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; + push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. + // However, we can't just call getRootHostContext() and push it because + // we'd have a different number of entries on the stack depending on + // whether getRootHostContext() throws somewhere in renderer code or not. + // So we push an empty value first. This lets us safely unwind on errors. - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome$1(other, function(othValue, othIndex) { - if (!cacheHas$3(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; -} + push(contextStackCursor$1, NO_CONTEXT, fiber); + var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. -var _equalArrays = equalArrays$2; + pop(contextStackCursor$1, fiber); + push(contextStackCursor$1, nextRootContext, fiber); + } -var root$2 = _root; + function popHostContainer(fiber) { + pop(contextStackCursor$1, fiber); + pop(contextFiberStackCursor, fiber); + pop(rootInstanceStackCursor, fiber); + } -/** Built-in value references. */ -var Uint8Array$3 = root$2.Uint8Array; + function getHostContext() { + var context = requiredContext(contextStackCursor$1.current); + return context; + } -var _Uint8Array = Uint8Array$3; + function pushHostContext(fiber) { + var rootInstance = requiredContext(rootInstanceStackCursor.current); + var context = requiredContext(contextStackCursor$1.current); + var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique. -/** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ + if (context === nextContext) { + return; + } // Track the context and the Fiber that provided it. + // This enables us to pop only Fibers that provide unique contexts. -function mapToArray$1(map) { - var index = -1, - result = Array(map.size); - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; -} + push(contextFiberStackCursor, fiber, fiber); + push(contextStackCursor$1, nextContext, fiber); + } -var _mapToArray = mapToArray$1; + function popHostContext(fiber) { + // Do not pop unless this Fiber provided the current context. + // pushHostContext() only pushes Fibers that provide unique contexts. + if (contextFiberStackCursor.current !== fiber) { + return; + } -/** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ + pop(contextStackCursor$1, fiber); + pop(contextFiberStackCursor, fiber); + } -function setToArray$3(set) { - var index = -1, - result = Array(set.size); + var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is + // inherited deeply down the subtree. The upper bits only affect + // this immediate suspense boundary and gets reset each new + // boundary or suspense list. - set.forEach(function(value) { - result[++index] = value; - }); - return result; -} + var SubtreeSuspenseContextMask = 1; // Subtree Flags: + // InvisibleParentSuspenseContext indicates that one of our parent Suspense + // boundaries is not currently showing visible main content. + // Either because it is already showing a fallback or is not mounted at all. + // We can use this to determine if it is desirable to trigger a fallback at + // the parent. If not, then we might need to trigger undesirable boundaries + // and/or suspend the commit to avoid hiding the parent content. -var _setToArray = setToArray$3; + var InvisibleParentSuspenseContext = 1; // Shallow Flags: + // ForceSuspenseFallback can be used by SuspenseList to force newly added + // items into their fallback state during one of the render passes. -var Symbol$6 = _Symbol, - Uint8Array$2 = _Uint8Array, - eq$4 = eq_1, - equalArrays$1 = _equalArrays, - mapToArray = _mapToArray, - setToArray$2 = _setToArray; + var ForceSuspenseFallback = 2; + var suspenseStackCursor = createCursor(DefaultSuspenseContext); + function hasSuspenseContext(parentContext, flag) { + return (parentContext & flag) !== 0; + } + function setDefaultShallowSuspenseContext(parentContext) { + return parentContext & SubtreeSuspenseContextMask; + } + function setShallowSuspenseContext(parentContext, shallowContext) { + return parentContext & SubtreeSuspenseContextMask | shallowContext; + } + function addSubtreeSuspenseContext(parentContext, subtreeContext) { + return parentContext | subtreeContext; + } + function pushSuspenseContext(fiber, newContext) { + push(suspenseStackCursor, newContext, fiber); + } + function popSuspenseContext(fiber) { + pop(suspenseStackCursor, fiber); + } -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; + function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { + // If it was the primary children that just suspended, capture and render the + // fallback. Otherwise, don't capture and bubble to the next boundary. + var nextState = workInProgress.memoizedState; -/** `Object#toString` result references. */ -var boolTag$2 = '[object Boolean]', - dateTag$2 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$3 = '[object Map]', - numberTag$2 = '[object Number]', - regexpTag$3 = '[object RegExp]', - setTag$3 = '[object Set]', - stringTag$3 = '[object String]', - symbolTag$5 = '[object Symbol]'; - -var arrayBufferTag$2 = '[object ArrayBuffer]', - dataViewTag$2 = '[object DataView]'; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto$2 = Symbol$6 ? Symbol$6.prototype : undefined, - symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; + if (nextState !== null) { + if (nextState.dehydrated !== null) { + // A dehydrated boundary always captures. + return true; + } -/** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalByTag$1(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$2: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; + return false; + } - case arrayBufferTag$2: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array$2(object), new Uint8Array$2(other))) { - return false; - } - return true; + workInProgress.memoizedProps; // Regular boundaries always capture. - case boolTag$2: - case dateTag$2: - case numberTag$2: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq$4(+object, +other); + { + return true; + } // If it's a boundary we should avoid, then we prefer to bubble up to the + } + function findFirstSuspended(row) { + var node = row; - case errorTag$1: - return object.name == other.name && object.message == other.message; + while (node !== null) { + if (node.tag === SuspenseComponent) { + var state = node.memoizedState; - case regexpTag$3: - case stringTag$3: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); + if (state !== null) { + var dehydrated = state.dehydrated; - case mapTag$3: - var convert = mapToArray; + if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) { + return node; + } + } + } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't + // keep track of whether it suspended or not. + node.memoizedProps.revealOrder !== undefined) { + var didSuspend = (node.flags & DidCapture) !== NoFlags; - case setTag$3: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4; - convert || (convert = setToArray$2); + if (didSuspend) { + return node; + } + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$2; + if (node === row) { + return null; + } - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays$1(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; + while (node.sibling === null) { + if (node.return === null || node.return === row) { + return null; + } - case symbolTag$5: - if (symbolValueOf$1) { - return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); - } - } - return false; -} + node = node.return; + } -var _equalByTag = equalByTag$1; + node.sibling.return = node.return; + node = node.sibling; + } -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ + return null; + } -function arrayPush$5(array, values) { - var index = -1, - length = values.length, - offset = array.length; + var NoFlags$1 = + /* */ + 0; // Represents whether effect should fire. - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} + var HasEffect = + /* */ + 1; // Represents the phase in which the effect (not the clean-up) fires. -var _arrayPush = arrayPush$5; + var Insertion = + /* */ + 2; + var Layout = + /* */ + 4; + var Passive$1 = + /* */ + 8; -var arrayPush$4 = _arrayPush, - isArray$k = isArray_1$1; + // and should be reset before starting a new render. + // This tracks which mutable sources need to be reset after a render. -/** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ -function baseGetAllKeys$3(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray$k(object) ? result : arrayPush$4(result, symbolsFunc(object)); -} + var workInProgressSources = []; + function resetWorkInProgressVersions() { + for (var i = 0; i < workInProgressSources.length; i++) { + var mutableSource = workInProgressSources[i]; -var _baseGetAllKeys = baseGetAllKeys$3; + if (isPrimaryRenderer) { + mutableSource._workInProgressVersionPrimary = null; + } else { + mutableSource._workInProgressVersionSecondary = null; + } + } -/** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ + workInProgressSources.length = 0; + } + // This ensures that the version used for server rendering matches the one + // that is eventually read during hydration. + // If they don't match there's a potential tear and a full deopt render is required. -function arrayFilter$3(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + function registerMutableSourceForHydration(root, mutableSource) { + var getVersion = mutableSource._getVersion; + var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished. + // Retaining it forever may interfere with GC. - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; -} + if (root.mutableSourceEagerHydrationData == null) { + root.mutableSourceEagerHydrationData = [mutableSource, version]; + } else { + root.mutableSourceEagerHydrationData.push(mutableSource, version); + } + } -var _arrayFilter = arrayFilter$3; + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, + ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; + var didWarnAboutMismatchedHooksForComponent; + var didWarnUncachedGetSnapshot; -/** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ + { + didWarnAboutMismatchedHooksForComponent = new Set(); + } -function stubArray$3() { - return []; -} + // These are set right before calling the component. + var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from + // the work-in-progress hook. -var stubArray_1 = stubArray$3; + var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The + // current hook list is the list that belongs to the current fiber. The + // work-in-progress hook list is a new list that will be added to the + // work-in-progress fiber. -var arrayFilter$2 = _arrayFilter, - stubArray$2 = stubArray_1; + var currentHook = null; + var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This + // does not get reset if we do another render pass; only when we're completely + // finished evaluating this component. This is an optimization so we know + // whether we need to clear render phase updates after a throw. -/** Used for built-in method references. */ -var objectProto$c = Object.prototype; + var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This + // gets reset after each attempt. + // TODO: Maybe there's some way to consolidate this with + // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`. -/** Built-in value references. */ -var propertyIsEnumerable$2 = objectProto$c.propertyIsEnumerable; + var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component. -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeGetSymbols$2 = Object.getOwnPropertySymbols; + var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during + // hydration). This counter is global, so client ids are not stable across + // render attempts. -/** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ -var getSymbols$4 = !nativeGetSymbols$2 ? stubArray$2 : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter$2(nativeGetSymbols$2(object), function(symbol) { - return propertyIsEnumerable$2.call(object, symbol); - }); -}; + var globalClientIdCounter = 0; + var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook -var _getSymbols = getSymbols$4; + var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. + // The list stores the order of hooks used during the initial render (mount). + // Subsequent renders (updates) reference this list. -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ + var hookTypesDev = null; + var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore + // the dependencies for Hooks that need them (e.g. useEffect or useMemo). + // When true, such Hooks will always be "remounted". Only used during hot reload. -function baseTimes$2(n, iteratee) { - var index = -1, - result = Array(n); + var ignorePreviousDependencies = false; - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} + function mountHookTypesDev() { + { + var hookName = currentHookNameInDev; -var _baseTimes = baseTimes$2; + if (hookTypesDev === null) { + hookTypesDev = [hookName]; + } else { + hookTypesDev.push(hookName); + } + } + } -/** Used as references for various `Number` constants. */ + function updateHookTypesDev() { + { + var hookName = currentHookNameInDev; -var MAX_SAFE_INTEGER$2 = 9007199254740991; + if (hookTypesDev !== null) { + hookTypesUpdateIndexDev++; -/** Used to detect unsigned integer values. */ -var reIsUint$1 = /^(?:0|[1-9]\d*)$/; + if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { + warnOnHookMismatchInDev(hookName); + } + } + } + } -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex$5(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$2 : length; + function checkDepsAreArrayDev(deps) { + { + if (deps !== undefined && deps !== null && !isArray(deps)) { + // Verify deps, but only on mount to avoid extra checks. + // It's unlikely their type would change as usually you define them inline. + error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps); + } + } + } - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint$1.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} + function warnOnHookMismatchInDev(currentHookName) { + { + var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1); -var _isIndex = isIndex$5; + if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { + didWarnAboutMismatchedHooksForComponent.add(componentName); -var baseTimes$1 = _baseTimes, - isArguments$4 = isArguments_1, - isArray$j = isArray_1$1, - isBuffer$2 = isBuffer$4.exports, - isIndex$4 = _isIndex, - isTypedArray$1 = isTypedArray_1; + if (hookTypesDev !== null) { + var table = ''; + var secondColumnStart = 30; -/** Used for built-in method references. */ -var objectProto$b = Object.prototype; + for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { + var oldHookName = hookTypesDev[i]; + var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; + var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up + // lol @ IE not supporting String#repeat -/** Used to check objects for own properties. */ -var hasOwnProperty$b = objectProto$b.hasOwnProperty; + while (row.length < secondColumnStart) { + row += ' '; + } -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys$3(value, inherited) { - var isArr = isArray$j(value), - isArg = !isArr && isArguments$4(value), - isBuff = !isArr && !isArg && isBuffer$2(value), - isType = !isArr && !isArg && !isBuff && isTypedArray$1(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes$1(value.length, String) : [], - length = result.length; + row += newHookName + '\n'; + table += row; + } - for (var key in value) { - if ((inherited || hasOwnProperty$b.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex$4(key, length) - ))) { - result.push(key); - } - } - return result; -} + error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table); + } + } + } + } -var _arrayLikeKeys = arrayLikeKeys$3; + function throwInvalidHookError() { + throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); + } -var arrayLikeKeys$2 = _arrayLikeKeys, - baseKeys = _baseKeys, - isArrayLike$a = isArrayLike_1; + function areHookInputsEqual(nextDeps, prevDeps) { + { + if (ignorePreviousDependencies) { + // Only true when this component is being hot reloaded. + return false; + } + } -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys$9(object) { - return isArrayLike$a(object) ? arrayLikeKeys$2(object) : baseKeys(object); -} + if (prevDeps === null) { + { + error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); + } -var keys_1 = keys$9; + return false; + } -var baseGetAllKeys$2 = _baseGetAllKeys, - getSymbols$3 = _getSymbols, - keys$8 = keys_1; + { + // Don't bother comparing lengths in prod because these arrays should be + // passed inline. + if (nextDeps.length !== prevDeps.length) { + error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]"); + } + } -/** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ -function getAllKeys$2(object) { - return baseGetAllKeys$2(object, keys$8, getSymbols$3); -} + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { + if (objectIs(nextDeps[i], prevDeps[i])) { + continue; + } -var _getAllKeys = getAllKeys$2; + return false; + } -var getAllKeys$1 = _getAllKeys; + return true; + } -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$3 = 1; + function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) { + renderLanes = nextRenderLanes; + currentlyRenderingFiber$1 = workInProgress; -/** Used for built-in method references. */ -var objectProto$a = Object.prototype; + { + hookTypesDev = current !== null ? current._debugHookTypes : null; + hookTypesUpdateIndexDev = -1; // Used for hot reloading: -/** Used to check objects for own properties. */ -var hasOwnProperty$a = objectProto$a.hasOwnProperty; + ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; + } -/** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalObjects$1(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3, - objProps = getAllKeys$1(object), - objLength = objProps.length, - othProps = getAllKeys$1(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) { - return false; - } - } - // Check that cyclic values are equal. - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; + workInProgress.memoizedState = null; + workInProgress.updateQueue = null; + workInProgress.lanes = NoLanes; // The following should have already been reset + // currentHook = null; + // workInProgressHook = null; + // didScheduleRenderPhaseUpdate = false; + // localIdCounter = 0; + // TODO Warn if no hooks are used at all during mount, then some are used during update. + // Currently we will identify the update render as a mount because memoizedState === null. + // This is tricky because it's valid for certain types of components (e.g. React.lazy) + // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used. + // Non-stateful hooks (e.g. context) don't get added to memoizedState, + // so memoizedState would be null during updates and mounts. - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; -} + { + if (current !== null && current.memoizedState !== null) { + ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; + } else if (hookTypesDev !== null) { + // This dispatcher handles an edge case where a component is updating, + // but no stateful hooks have been used. + // We want to match the production code behavior (which will use HooksDispatcherOnMount), + // but with the extra DEV validation to ensure hooks ordering hasn't changed. + // This dispatcher does that. + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; + } else { + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; + } + } -var _equalObjects = equalObjects$1; + var children = Component(props, secondArg); // Check if there was a render phase update -var Stack$2 = _Stack, - equalArrays = _equalArrays, - equalByTag = _equalByTag, - equalObjects = _equalObjects, - getTag$4 = _getTag, - isArray$i = isArray_1$1, - isBuffer$1 = isBuffer$4.exports, - isTypedArray = isTypedArray_1; + if (didScheduleRenderPhaseUpdateDuringThisPass) { + // Keep rendering in a loop for as long as render phase updates continue to + // be scheduled. Use a counter to prevent infinite loops. + var numberOfReRenders = 0; -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$2 = 1; + do { + didScheduleRenderPhaseUpdateDuringThisPass = false; + localIdCounter = 0; -/** `Object#toString` result references. */ -var argsTag$3 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$1 = '[object Object]'; + if (numberOfReRenders >= RE_RENDER_LIMIT) { + throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); + } -/** Used for built-in method references. */ -var objectProto$9 = Object.prototype; + numberOfReRenders += 1; -/** Used to check objects for own properties. */ -var hasOwnProperty$9 = objectProto$9.hasOwnProperty; + { + // Even when hot reloading, allow dependencies to stabilize + // after first render to prevent infinite render phase updates. + ignorePreviousDependencies = false; + } // Start over from the beginning of the list -/** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function baseIsEqualDeep$1(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray$i(object), - othIsArr = isArray$i(other), - objTag = objIsArr ? arrayTag$1 : getTag$4(object), - othTag = othIsArr ? arrayTag$1 : getTag$4(other); - objTag = objTag == argsTag$3 ? objectTag$1 : objTag; - othTag = othTag == argsTag$3 ? objectTag$1 : othTag; + currentHook = null; + workInProgressHook = null; + workInProgress.updateQueue = null; - var objIsObj = objTag == objectTag$1, - othIsObj = othTag == objectTag$1, - isSameTag = objTag == othTag; + { + // Also validate hook order for cascading updates. + hookTypesUpdateIndexDev = -1; + } - if (isSameTag && isBuffer$1(object)) { - if (!isBuffer$1(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack$2); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) { - var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); + ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ; + children = Component(props, secondArg); + } while (didScheduleRenderPhaseUpdateDuringThisPass); + } // We can assume the previous dispatcher is always this one, since we set it + // at the beginning of the render phase and there's no re-entrance. - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - stack || (stack = new Stack$2); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack$2); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); -} + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; -var _baseIsEqualDeep = baseIsEqualDeep$1; + { + workInProgress._debugHookTypes = hookTypesDev; + } // This check uses currentHook so that it works the same in DEV and prod bundles. + // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. -var baseIsEqualDeep = _baseIsEqualDeep, - isObjectLike$8 = isObjectLike_1; -/** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ -function baseIsEqual$2(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike$8(value) && !isObjectLike$8(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual$2, stack); -} + var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; + renderLanes = NoLanes; + currentlyRenderingFiber$1 = null; + currentHook = null; + workInProgressHook = null; -var _baseIsEqual = baseIsEqual$2; + { + currentHookNameInDev = null; + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last + // render. If this fires, it suggests that we incorrectly reset the static + // flags in some other part of the codebase. This has happened before, for + // example, in the SuspenseList implementation. -var Stack$1 = _Stack, - baseIsEqual$1 = _baseIsEqual; + if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird + // and creates false positives. To make this work in legacy mode, we'd + // need to mark fibers that commit in an incomplete state, somehow. For + // now I'll disable the warning that most of the bugs that would trigger + // it are either exclusive to concurrent mode or exist in both. + (current.mode & ConcurrentMode) !== NoMode) { + error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.'); + } + } -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; + didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook + // localIdCounter = 0; -/** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ -function baseIsMatch$1(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; + if (didRenderTooFewHooks) { + throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.'); + } - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; + return children; + } + function checkDidRenderIdHook() { + // This should be called immediately after every renderWithHooks call. + // Conceptually, it's part of the return value of renderWithHooks; it's only a + // separate function to avoid using an array tuple. + var didRenderIdHook = localIdCounter !== 0; + localIdCounter = 0; + return didRenderIdHook; + } + function bailoutHooks(current, workInProgress, lanes) { + workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the + // complete phase (bubbleProperties). - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack$1; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual$1(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack) - : result - )) { - return false; - } - } - } - return true; -} + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update); + } else { + workInProgress.flags &= ~(Passive | Update); + } -var _baseIsMatch = baseIsMatch$1; + current.lanes = removeLanes(current.lanes, lanes); + } + function resetHooksAfterThrow() { + // We can assume the previous dispatcher is always this one, since we set it + // at the beginning of the render phase and there's no re-entrance. + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; -var isObject$8 = isObject_1; + if (didScheduleRenderPhaseUpdate) { + // There were render phase updates. These are only valid for this render + // phase, which we are now aborting. Remove the updates from the queues so + // they do not persist to the next render. Do not remove updates from hooks + // that weren't processed. + // + // Only reset the updates from the queue if it has a clone. If it does + // not have a clone, that means it wasn't processed, and the updates were + // scheduled before we entered the render phase. + var hook = currentlyRenderingFiber$1.memoizedState; -/** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ -function isStrictComparable$2(value) { - return value === value && !isObject$8(value); -} + while (hook !== null) { + var queue = hook.queue; -var _isStrictComparable = isStrictComparable$2; + if (queue !== null) { + queue.pending = null; + } -var isStrictComparable$1 = _isStrictComparable, - keys$7 = keys_1; + hook = hook.next; + } -/** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ -function getMatchData$1(object) { - var result = keys$7(object), - length = result.length; + didScheduleRenderPhaseUpdate = false; + } - while (length--) { - var key = result[length], - value = object[key]; + renderLanes = NoLanes; + currentlyRenderingFiber$1 = null; + currentHook = null; + workInProgressHook = null; - result[length] = [key, value, isStrictComparable$1(value)]; - } - return result; -} + { + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; + currentHookNameInDev = null; + isUpdatingOpaqueValueInRenderPhase = false; + } -var _getMatchData = getMatchData$1; + didScheduleRenderPhaseUpdateDuringThisPass = false; + localIdCounter = 0; + } -/** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ + function mountWorkInProgressHook() { + var hook = { + memoizedState: null, + baseState: null, + baseQueue: null, + queue: null, + next: null + }; -function matchesStrictComparable$2(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; -} + if (workInProgressHook === null) { + // This is the first hook in the list + currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook; + } else { + // Append to the end of the list + workInProgressHook = workInProgressHook.next = hook; + } -var _matchesStrictComparable = matchesStrictComparable$2; + return workInProgressHook; + } -var baseIsMatch = _baseIsMatch, - getMatchData = _getMatchData, - matchesStrictComparable$1 = _matchesStrictComparable; + function updateWorkInProgressHook() { + // This function is used both for updates and for re-renders triggered by a + // render phase update. It assumes there is either a current hook we can + // clone, or a work-in-progress hook from a previous render pass that we can + // use as a base. When we reach the end of the base list, we must switch to + // the dispatcher used for mounts. + var nextCurrentHook; -/** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ -function baseMatches$1(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable$1(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; -} + if (currentHook === null) { + var current = currentlyRenderingFiber$1.alternate; -var _baseMatches = baseMatches$1; + if (current !== null) { + nextCurrentHook = current.memoizedState; + } else { + nextCurrentHook = null; + } + } else { + nextCurrentHook = currentHook.next; + } -var baseGetTag$2 = _baseGetTag, - isObjectLike$7 = isObjectLike_1; + var nextWorkInProgressHook; -/** `Object#toString` result references. */ -var symbolTag$4 = '[object Symbol]'; + if (workInProgressHook === null) { + nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState; + } else { + nextWorkInProgressHook = workInProgressHook.next; + } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol$6(value) { - return typeof value == 'symbol' || - (isObjectLike$7(value) && baseGetTag$2(value) == symbolTag$4); -} + if (nextWorkInProgressHook !== null) { + // There's already a work-in-progress. Reuse it. + workInProgressHook = nextWorkInProgressHook; + nextWorkInProgressHook = workInProgressHook.next; + currentHook = nextCurrentHook; + } else { + // Clone from the current hook. + if (nextCurrentHook === null) { + throw new Error('Rendered more hooks than during the previous render.'); + } -var isSymbol_1 = isSymbol$6; + currentHook = nextCurrentHook; + var newHook = { + memoizedState: currentHook.memoizedState, + baseState: currentHook.baseState, + baseQueue: currentHook.baseQueue, + queue: currentHook.queue, + next: null + }; -var isArray$h = isArray_1$1, - isSymbol$5 = isSymbol_1; + if (workInProgressHook === null) { + // This is the first hook in the list. + currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook; + } else { + // Append to the end of the list. + workInProgressHook = workInProgressHook.next = newHook; + } + } -/** Used to match property names within property paths. */ -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; + return workInProgressHook; + } -/** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ -function isKey$3(value, object) { - if (isArray$h(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol$5(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); -} + function createFunctionComponentUpdateQueue() { + return { + lastEffect: null, + stores: null + }; + } -var _isKey = isKey$3; + function basicStateReducer(state, action) { + // $FlowFixMe: Flow doesn't like mixed types + return typeof action === 'function' ? action(state) : action; + } -var MapCache$1 = _MapCache; + function mountReducer(reducer, initialArg, init) { + var hook = mountWorkInProgressHook(); + var initialState; -/** Error message constants. */ -var FUNC_ERROR_TEXT$1 = 'Expected a function'; + if (init !== undefined) { + initialState = init(initialArg); + } else { + initialState = initialArg; + } -/** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ -function memoize$1(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT$1); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; + hook.memoizedState = hook.baseState = initialState; + var queue = { + pending: null, + interleaved: null, + lanes: NoLanes, + dispatch: null, + lastRenderedReducer: reducer, + lastRenderedState: initialState + }; + hook.queue = queue; + var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue); + return [hook.memoizedState, dispatch]; + } - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize$1.Cache || MapCache$1); - return memoized; -} + function updateReducer(reducer, initialArg, init) { + var hook = updateWorkInProgressHook(); + var queue = hook.queue; -// Expose `MapCache`. -memoize$1.Cache = MapCache$1; + if (queue === null) { + throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); + } -var memoize_1 = memoize$1; + queue.lastRenderedReducer = reducer; + var current = currentHook; // The last rebase update that is NOT part of the base state. -var memoize = memoize_1; + var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet. -/** Used as the maximum memoize cache size. */ -var MAX_MEMOIZE_SIZE = 500; + var pendingQueue = queue.pending; -/** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ -function memoizeCapped$1(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); + if (pendingQueue !== null) { + // We have new updates that haven't been processed yet. + // We'll add them to the base queue. + if (baseQueue !== null) { + // Merge the pending queue and the base queue. + var baseFirst = baseQueue.next; + var pendingFirst = pendingQueue.next; + baseQueue.next = pendingFirst; + pendingQueue.next = baseFirst; + } - var cache = result.cache; - return result; -} + { + if (current.baseQueue !== baseQueue) { + // Internal invariant that should never happen, but feasibly could in + // the future if we implement resuming, or some form of that. + error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.'); + } + } -var _memoizeCapped = memoizeCapped$1; + current.baseQueue = baseQueue = pendingQueue; + queue.pending = null; + } -var memoizeCapped = _memoizeCapped; + if (baseQueue !== null) { + // We have a queue to process. + var first = baseQueue.next; + var newState = current.baseState; + var newBaseState = null; + var newBaseQueueFirst = null; + var newBaseQueueLast = null; + var update = first; -/** Used to match property names within property paths. */ -var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + do { + var updateLane = update.lane; -/** Used to match backslashes in property paths. */ -var reEscapeChar = /\\(\\)?/g; + if (!isSubsetOfLanes(renderLanes, updateLane)) { + // Priority is insufficient. Skip this update. If this is the first + // skipped update, the previous update/state is the new base + // update/state. + var clone = { + lane: updateLane, + action: update.action, + hasEagerState: update.hasEagerState, + eagerState: update.eagerState, + next: null + }; -/** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ -var stringToPath$1 = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; -}); + if (newBaseQueueLast === null) { + newBaseQueueFirst = newBaseQueueLast = clone; + newBaseState = newState; + } else { + newBaseQueueLast = newBaseQueueLast.next = clone; + } // Update the remaining priority in the queue. + // TODO: Don't need to accumulate this. Instead, we can remove + // renderLanes from the original lanes. -var _stringToPath = stringToPath$1; -var Symbol$5 = _Symbol, - arrayMap$6 = _arrayMap, - isArray$g = isArray_1$1, - isSymbol$4 = isSymbol_1; + currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane); + markSkippedUpdateLanes(updateLane); + } else { + // This update does have sufficient priority. + if (newBaseQueueLast !== null) { + var _clone = { + // This update is going to be committed so we never want uncommit + // it. Using NoLane works because 0 is a subset of all bitmasks, so + // this will never be skipped by the check above. + lane: NoLane, + action: update.action, + hasEagerState: update.hasEagerState, + eagerState: update.eagerState, + next: null + }; + newBaseQueueLast = newBaseQueueLast.next = _clone; + } // Process this update. -/** Used as references for various `Number` constants. */ -var INFINITY$5 = 1 / 0; -/** Used to convert symbols to primitives and strings. */ -var symbolProto$1 = Symbol$5 ? Symbol$5.prototype : undefined, - symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; + if (update.hasEagerState) { + // If this update is a state update (not a reducer) and was processed eagerly, + // we can use the eagerly computed state + newState = update.eagerState; + } else { + var action = update.action; + newState = reducer(newState, action); + } + } -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString$1(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray$g(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap$6(value, baseToString$1) + ''; - } - if (isSymbol$4(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$5) ? '-0' : result; -} + update = update.next; + } while (update !== null && update !== first); -var _baseToString = baseToString$1; + if (newBaseQueueLast === null) { + newBaseState = newState; + } else { + newBaseQueueLast.next = newBaseQueueFirst; + } // Mark that the fiber performed work, but only if the new state is + // different from the current state. -var baseToString = _baseToString; -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString$2(value) { - return value == null ? '' : baseToString(value); -} + if (!objectIs(newState, hook.memoizedState)) { + markWorkInProgressReceivedUpdate(); + } -var toString_1 = toString$2; + hook.memoizedState = newState; + hook.baseState = newBaseState; + hook.baseQueue = newBaseQueueLast; + queue.lastRenderedState = newState; + } // Interleaved updates are stored on a separate queue. We aren't going to + // process them during this render, but we do need to track which lanes + // are remaining. -var isArray$f = isArray_1$1, - isKey$2 = _isKey, - stringToPath = _stringToPath, - toString$1 = toString_1; -/** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ -function castPath$4(value, object) { - if (isArray$f(value)) { - return value; - } - return isKey$2(value, object) ? [value] : stringToPath(toString$1(value)); -} + var lastInterleaved = queue.interleaved; -var _castPath = castPath$4; + if (lastInterleaved !== null) { + var interleaved = lastInterleaved; -var isSymbol$3 = isSymbol_1; + do { + var interleavedLane = interleaved.lane; + currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane); + markSkippedUpdateLanes(interleavedLane); + interleaved = interleaved.next; + } while (interleaved !== lastInterleaved); + } else if (baseQueue === null) { + // `queue.lanes` is used for entangling transitions. We can set it back to + // zero once the queue is empty. + queue.lanes = NoLanes; + } -/** Used as references for various `Number` constants. */ -var INFINITY$4 = 1 / 0; + var dispatch = queue.dispatch; + return [hook.memoizedState, dispatch]; + } -/** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ -function toKey$7(value) { - if (typeof value == 'string' || isSymbol$3(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$4) ? '-0' : result; -} + function rerenderReducer(reducer, initialArg, init) { + var hook = updateWorkInProgressHook(); + var queue = hook.queue; -var _toKey = toKey$7; + if (queue === null) { + throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); + } -var castPath$3 = _castPath, - toKey$6 = _toKey; + queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous + // work-in-progress hook. -/** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ -function baseGet$3(object, path) { - path = castPath$3(path, object); + var dispatch = queue.dispatch; + var lastRenderPhaseUpdate = queue.pending; + var newState = hook.memoizedState; - var index = 0, - length = path.length; + if (lastRenderPhaseUpdate !== null) { + // The queue doesn't persist past this render pass. + queue.pending = null; + var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; + var update = firstRenderPhaseUpdate; - while (object != null && index < length) { - object = object[toKey$6(path[index++])]; - } - return (index && index == length) ? object : undefined; -} + do { + // Process this render phase update. We don't have to check the + // priority because it will always be the same as the current + // render's. + var action = update.action; + newState = reducer(newState, action); + update = update.next; + } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is + // different from the current state. -var _baseGet = baseGet$3; -var baseGet$2 = _baseGet; + if (!objectIs(newState, hook.memoizedState)) { + markWorkInProgressReceivedUpdate(); + } -/** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ -function get$1(object, path, defaultValue) { - var result = object == null ? undefined : baseGet$2(object, path); - return result === undefined ? defaultValue : result; -} + hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to + // the base state unless the queue is empty. + // TODO: Not sure if this is the desired semantics, but it's what we + // do for gDSFP. I can't remember why. -var get_1 = get$1; + if (hook.baseQueue === null) { + hook.baseState = newState; + } -/** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ + queue.lastRenderedState = newState; + } -function baseHasIn$1(object, key) { - return object != null && key in Object(object); -} + return [newState, dispatch]; + } -var _baseHasIn = baseHasIn$1; + function mountMutableSource(source, getSnapshot, subscribe) { + { + return undefined; + } + } -var castPath$2 = _castPath, - isArguments$3 = isArguments_1, - isArray$e = isArray_1$1, - isIndex$3 = _isIndex, - isLength$2 = isLength_1, - toKey$5 = _toKey; + function updateMutableSource(source, getSnapshot, subscribe) { + { + return undefined; + } + } -/** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ -function hasPath$2(object, path, hasFunc) { - path = castPath$2(path, object); + function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var fiber = currentlyRenderingFiber$1; + var hook = mountWorkInProgressHook(); + var nextSnapshot; + var isHydrating = getIsHydrating(); - var index = -1, - length = path.length, - result = false; + if (isHydrating) { + if (getServerSnapshot === undefined) { + throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); + } - while (++index < length) { - var key = toKey$5(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength$2(length) && isIndex$3(key, length) && - (isArray$e(object) || isArguments$3(object)); -} + nextSnapshot = getServerSnapshot(); -var _hasPath = hasPath$2; + { + if (!didWarnUncachedGetSnapshot) { + if (nextSnapshot !== getServerSnapshot()) { + error('The result of getServerSnapshot should be cached to avoid an infinite loop'); -var baseHasIn = _baseHasIn, - hasPath$1 = _hasPath; + didWarnUncachedGetSnapshot = true; + } + } + } + } else { + nextSnapshot = getSnapshot(); -/** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ -function hasIn$1(object, path) { - return object != null && hasPath$1(object, path, baseHasIn); -} + { + if (!didWarnUncachedGetSnapshot) { + var cachedSnapshot = getSnapshot(); -var hasIn_1 = hasIn$1; + if (!objectIs(nextSnapshot, cachedSnapshot)) { + error('The result of getSnapshot should be cached to avoid an infinite loop'); -var baseIsEqual = _baseIsEqual, - get = get_1, - hasIn = hasIn_1, - isKey$1 = _isKey, - isStrictComparable = _isStrictComparable, - matchesStrictComparable = _matchesStrictComparable, - toKey$4 = _toKey; + didWarnUncachedGetSnapshot = true; + } + } + } // Unless we're rendering a blocking lane, schedule a consistency check. + // Right before committing, we will walk the tree and check if any of the + // stores were mutated. + // + // We won't do this if we're hydrating server-rendered content, because if + // the content is stale, it's already visible anyway. Instead we'll patch + // it up in a passive effect. -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; -/** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ -function baseMatchesProperty$1(path, srcValue) { - if (isKey$1(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey$4(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; -} + var root = getWorkInProgressRoot(); -var _baseMatchesProperty = baseMatchesProperty$1; + if (root === null) { + throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); + } -/** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ + if (!includesBlockingLane(root, renderLanes)) { + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); + } + } // Read the current snapshot from the store on every render. This breaks the + // normal rules of React, and only works because store updates are + // always synchronous. -function identity$4(value) { - return value; -} -var identity_1 = identity$4; + hook.memoizedState = nextSnapshot; + var inst = { + value: nextSnapshot, + getSnapshot: getSnapshot + }; + hook.queue = inst; // Schedule an effect to subscribe to the store. -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ + mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update + // this whenever subscribe, getSnapshot, or value changes. Because there's no + // clean-up function, and we track the deps correctly, we can call pushEffect + // directly, without storing any additional state. For the same reason, we + // don't need to set a static flag, either. + // TODO: We can move this to the passive phase once we add a pre-commit + // consistency check. See the next comment. -function baseProperty$1(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; -} + fiber.flags |= Passive; + pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); + return nextSnapshot; + } -var _baseProperty = baseProperty$1; + function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var fiber = currentlyRenderingFiber$1; + var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the + // normal rules of React, and only works because store updates are + // always synchronous. -var baseGet$1 = _baseGet; + var nextSnapshot = getSnapshot(); -/** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function basePropertyDeep$1(path) { - return function(object) { - return baseGet$1(object, path); - }; -} + { + if (!didWarnUncachedGetSnapshot) { + var cachedSnapshot = getSnapshot(); -var _basePropertyDeep = basePropertyDeep$1; + if (!objectIs(nextSnapshot, cachedSnapshot)) { + error('The result of getSnapshot should be cached to avoid an infinite loop'); -var baseProperty = _baseProperty, - basePropertyDeep = _basePropertyDeep, - isKey = _isKey, - toKey$3 = _toKey; + didWarnUncachedGetSnapshot = true; + } + } + } -/** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ -function property$1(path) { - return isKey(path) ? baseProperty(toKey$3(path)) : basePropertyDeep(path); -} + var prevSnapshot = hook.memoizedState; + var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot); -var property_1 = property$1; + if (snapshotChanged) { + hook.memoizedState = nextSnapshot; + markWorkInProgressReceivedUpdate(); + } -var baseMatches = _baseMatches, - baseMatchesProperty = _baseMatchesProperty, - identity$3 = identity_1, - isArray$d = isArray_1$1, - property = property_1; + var inst = hook.queue; + updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the + // commit phase if there was an interleaved mutation. In concurrent mode + // this can happen all the time, but even in synchronous mode, an earlier + // effect may have mutated the store. -/** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ -function baseIteratee$a(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity$3; - } - if (typeof value == 'object') { - return isArray$d(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); -} + if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by + // checking whether we scheduled a subscription effect above. + workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) { + fiber.flags |= Passive; + pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check. + // Right before committing, we will walk the tree and check if any of the + // stores were mutated. -var _baseIteratee = baseIteratee$a; + var root = getWorkInProgressRoot(); -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ + if (root === null) { + throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); + } -function createBaseFor$1(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; + if (!includesBlockingLane(root, renderLanes)) { + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); + } + } - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; -} + return nextSnapshot; + } -var _createBaseFor = createBaseFor$1; + function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) { + fiber.flags |= StoreConsistency; + var check = { + getSnapshot: getSnapshot, + value: renderedSnapshot + }; + var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; -var createBaseFor = _createBaseFor; + if (componentUpdateQueue === null) { + componentUpdateQueue = createFunctionComponentUpdateQueue(); + currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; + componentUpdateQueue.stores = [check]; + } else { + var stores = componentUpdateQueue.stores; -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor$1 = createBaseFor(); + if (stores === null) { + componentUpdateQueue.stores = [check]; + } else { + stores.push(check); + } + } + } -var _baseFor = baseFor$1; + function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) { + // These are updated in the passive phase + inst.value = nextSnapshot; + inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could + // have been in an event that fired before the passive effects, or it could + // have been in a layout effect. In that case, we would have used the old + // snapsho and getSnapshot values to bail out. We need to check one more time. -var baseFor = _baseFor, - keys$6 = keys_1; + if (checkIfSnapshotChanged(inst)) { + // Force a re-render. + forceStoreRerender(fiber); + } + } -/** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn$1(object, iteratee) { - return object && baseFor(object, iteratee, keys$6); -} + function subscribeToStore(fiber, inst, subscribe) { + var handleStoreChange = function () { + // The store changed. Check if the snapshot changed since the last time we + // read from the store. + if (checkIfSnapshotChanged(inst)) { + // Force a re-render. + forceStoreRerender(fiber); + } + }; // Subscribe to the store and return a clean-up function. -var _baseForOwn = baseForOwn$1; -var isArrayLike$9 = isArrayLike_1; + return subscribe(handleStoreChange); + } -/** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseEach$1(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike$9(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); + function checkIfSnapshotChanged(inst) { + var latestGetSnapshot = inst.getSnapshot; + var prevValue = inst.value; - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; -} + try { + var nextValue = latestGetSnapshot(); + return !objectIs(prevValue, nextValue); + } catch (error) { + return true; + } + } -var _createBaseEach = createBaseEach$1; + function forceStoreRerender(fiber) { + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } -var baseForOwn = _baseForOwn, - createBaseEach = _createBaseEach; + function mountState(initialState) { + var hook = mountWorkInProgressHook(); -/** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ -var baseEach$7 = createBaseEach(baseForOwn); + if (typeof initialState === 'function') { + // $FlowFixMe: Flow doesn't like mixed types + initialState = initialState(); + } -var _baseEach = baseEach$7; + hook.memoizedState = hook.baseState = initialState; + var queue = { + pending: null, + interleaved: null, + lanes: NoLanes, + dispatch: null, + lastRenderedReducer: basicStateReducer, + lastRenderedState: initialState + }; + hook.queue = queue; + var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue); + return [hook.memoizedState, dispatch]; + } -var baseEach$6 = _baseEach, - isArrayLike$8 = isArrayLike_1; + function updateState(initialState) { + return updateReducer(basicStateReducer); + } -/** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function baseMap$1(collection, iteratee) { - var index = -1, - result = isArrayLike$8(collection) ? Array(collection.length) : []; + function rerenderState(initialState) { + return rerenderReducer(basicStateReducer); + } - baseEach$6(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; -} + function pushEffect(tag, create, destroy, deps) { + var effect = { + tag: tag, + create: create, + destroy: destroy, + deps: deps, + // Circular + next: null + }; + var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; -var _baseMap = baseMap$1; + if (componentUpdateQueue === null) { + componentUpdateQueue = createFunctionComponentUpdateQueue(); + currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; + componentUpdateQueue.lastEffect = effect.next = effect; + } else { + var lastEffect = componentUpdateQueue.lastEffect; -var arrayMap$5 = _arrayMap, - baseIteratee$9 = _baseIteratee, - baseMap = _baseMap, - isArray$c = isArray_1$1; + if (lastEffect === null) { + componentUpdateQueue.lastEffect = effect.next = effect; + } else { + var firstEffect = lastEffect.next; + lastEffect.next = effect; + effect.next = firstEffect; + componentUpdateQueue.lastEffect = effect; + } + } -/** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ -function map$1(collection, iteratee) { - var func = isArray$c(collection) ? arrayMap$5 : baseMap; - return func(collection, baseIteratee$9(iteratee)); -} + return effect; + } -var map_1$4 = map$1; + function mountRef(initialValue) { + var hook = mountWorkInProgressHook(); -/** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ + { + var _ref2 = { + current: initialValue + }; + hook.memoizedState = _ref2; + return _ref2; + } + } -function arrayEach$2(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; + function updateRef(initialValue) { + var hook = updateWorkInProgressHook(); + return hook.memoizedState; + } - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; -} + function mountEffectImpl(fiberFlags, hookFlags, create, deps) { + var hook = mountWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + currentlyRenderingFiber$1.flags |= fiberFlags; + hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps); + } -var _arrayEach = arrayEach$2; + function updateEffectImpl(fiberFlags, hookFlags, create, deps) { + var hook = updateWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + var destroy = undefined; -var identity$2 = identity_1; + if (currentHook !== null) { + var prevEffect = currentHook.memoizedState; + destroy = prevEffect.destroy; -/** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ -function castFunction$1(value) { - return typeof value == 'function' ? value : identity$2; -} + if (nextDeps !== null) { + var prevDeps = prevEffect.deps; -var _castFunction = castFunction$1; + if (areHookInputsEqual(nextDeps, prevDeps)) { + hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps); + return; + } + } + } -var arrayEach$1 = _arrayEach, - baseEach$5 = _baseEach, - castFunction = _castFunction, - isArray$b = isArray_1$1; + currentlyRenderingFiber$1.flags |= fiberFlags; + hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps); + } -/** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. - * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ -function forEach(collection, iteratee) { - var func = isArray$b(collection) ? arrayEach$1 : baseEach$5; - return func(collection, castFunction(iteratee)); -} + function mountEffect(create, deps) { + if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { + return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps); + } else { + return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps); + } + } -var forEach_1$4 = forEach; + function updateEffect(create, deps) { + return updateEffectImpl(Passive, Passive$1, create, deps); + } -var arrayMap$4 = _arrayMap; + function mountInsertionEffect(create, deps) { + return mountEffectImpl(Update, Insertion, create, deps); + } -/** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ -function baseValues$1(object, props) { - return arrayMap$4(props, function(key) { - return object[key]; - }); -} + function updateInsertionEffect(create, deps) { + return updateEffectImpl(Update, Insertion, create, deps); + } -var _baseValues = baseValues$1; + function mountLayoutEffect(create, deps) { + var fiberFlags = Update; -var baseValues = _baseValues, - keys$5 = keys_1; + { + fiberFlags |= LayoutStatic; + } -/** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ -function values$1(object) { - return object == null ? [] : baseValues(object, keys$5(object)); -} + if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } -var values_1$1 = values$1; + return mountEffectImpl(fiberFlags, Layout, create, deps); + } -/** Used for built-in method references. */ + function updateLayoutEffect(create, deps) { + return updateEffectImpl(Update, Layout, create, deps); + } -var objectProto$8 = Object.prototype; + function imperativeHandleEffect(create, ref) { + if (typeof ref === 'function') { + var refCallback = ref; -/** Used to check objects for own properties. */ -var hasOwnProperty$8 = objectProto$8.hasOwnProperty; + var _inst = create(); -/** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ -function baseHas$1(object, key) { - return object != null && hasOwnProperty$8.call(object, key); -} + refCallback(_inst); + return function () { + refCallback(null); + }; + } else if (ref !== null && ref !== undefined) { + var refObject = ref; -var _baseHas = baseHas$1; + { + if (!refObject.hasOwnProperty('current')) { + error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}'); + } + } -var baseHas = _baseHas, - hasPath = _hasPath; + var _inst2 = create(); -/** - * Checks if `path` is a direct property of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true - * - * _.has(other, 'a'); - * // => false - */ -function has$1(object, path) { - return object != null && hasPath(object, path, baseHas); -} + refObject.current = _inst2; + return function () { + refObject.current = null; + }; + } + } -var has_1 = has$1; + function mountImperativeHandle(ref, create, deps) { + { + if (typeof create !== 'function') { + error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); + } + } // TODO: If deps are provided, should we skip comparing the ref itself? -var getNative$1 = _getNative; -var defineProperty$2 = (function() { - try { - var func = getNative$1(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} -}()); + var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; + var fiberFlags = Update; -var _defineProperty = defineProperty$2; + { + fiberFlags |= LayoutStatic; + } -var defineProperty$1 = _defineProperty; + if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } -/** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function baseAssignValue$3(object, key, value) { - if (key == '__proto__' && defineProperty$1) { - defineProperty$1(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } -} + return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); + } -var _baseAssignValue = baseAssignValue$3; + function updateImperativeHandle(ref, create, deps) { + { + if (typeof create !== 'function') { + error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); + } + } // TODO: If deps are provided, should we skip comparing the ref itself? -var baseAssignValue$2 = _baseAssignValue, - eq$3 = eq_1; -/** Used for built-in method references. */ -var objectProto$7 = Object.prototype; + var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; + return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); + } -/** Used to check objects for own properties. */ -var hasOwnProperty$7 = objectProto$7.hasOwnProperty; + function mountDebugValue(value, formatterFn) {// This hook is normally a no-op. + // The react-debug-hooks package injects its own implementation + // so that e.g. DevTools can display custom hook values. + } -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue$4(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$7.call(object, key) && eq$3(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue$2(object, key, value); - } -} + var updateDebugValue = mountDebugValue; -var _assignValue = assignValue$4; + function mountCallback(callback, deps) { + var hook = mountWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + hook.memoizedState = [callback, nextDeps]; + return callback; + } -var assignValue$3 = _assignValue, - baseAssignValue$1 = _baseAssignValue; + function updateCallback(callback, deps) { + var hook = updateWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + var prevState = hook.memoizedState; -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ -function copyObject$5(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; - var index = -1, - length = props.length; + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } - while (++index < length) { - var key = props[index]; + hook.memoizedState = [callback, nextDeps]; + return callback; + } - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + function mountMemo(nextCreate, deps) { + var hook = mountWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + var nextValue = nextCreate(); + hook.memoizedState = [nextValue, nextDeps]; + return nextValue; + } - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue$1(object, key, newValue); - } else { - assignValue$3(object, key, newValue); - } - } - return object; -} + function updateMemo(nextCreate, deps) { + var hook = updateWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + var prevState = hook.memoizedState; -var _copyObject = copyObject$5; + if (prevState !== null) { + // Assume these are defined. If they're not, areHookInputsEqual will warn. + if (nextDeps !== null) { + var prevDeps = prevState[1]; -var copyObject$4 = _copyObject, - keys$4 = keys_1; + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } -/** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ -function baseAssign$1(object, source) { - return object && copyObject$4(source, keys$4(source), object); -} + var nextValue = nextCreate(); + hook.memoizedState = [nextValue, nextDeps]; + return nextValue; + } -var _baseAssign = baseAssign$1; + function mountDeferredValue(value) { + var _mountState = mountState(value), + prevValue = _mountState[0], + setValue = _mountState[1]; -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ + mountEffect(function () { + var prevTransition = ReactCurrentBatchConfig$1.transition; + ReactCurrentBatchConfig$1.transition = {}; -function nativeKeysIn$2(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; -} + try { + setValue(value); + } finally { + ReactCurrentBatchConfig$1.transition = prevTransition; + } + }, [value]); + return prevValue; + } -var _nativeKeysIn = nativeKeysIn$2; + function updateDeferredValue(value) { + var _updateState = updateState(), + prevValue = _updateState[0], + setValue = _updateState[1]; -var isObject$7 = isObject_1, - isPrototype$3 = _isPrototype, - nativeKeysIn$1 = _nativeKeysIn; + updateEffect(function () { + var prevTransition = ReactCurrentBatchConfig$1.transition; + ReactCurrentBatchConfig$1.transition = {}; -/** Used for built-in method references. */ -var objectProto$6 = Object.prototype; + try { + setValue(value); + } finally { + ReactCurrentBatchConfig$1.transition = prevTransition; + } + }, [value]); + return prevValue; + } -/** Used to check objects for own properties. */ -var hasOwnProperty$6 = objectProto$6.hasOwnProperty; + function rerenderDeferredValue(value) { + var _rerenderState = rerenderState(), + prevValue = _rerenderState[0], + setValue = _rerenderState[1]; -/** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeysIn$2(object) { - if (!isObject$7(object)) { - return nativeKeysIn$1(object); - } - var isProto = isPrototype$3(object), - result = []; + updateEffect(function () { + var prevTransition = ReactCurrentBatchConfig$1.transition; + ReactCurrentBatchConfig$1.transition = {}; - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$6.call(object, key)))) { - result.push(key); - } - } - return result; -} + try { + setValue(value); + } finally { + ReactCurrentBatchConfig$1.transition = prevTransition; + } + }, [value]); + return prevValue; + } -var _baseKeysIn = baseKeysIn$2; + function startTransition(setPending, callback, options) { + var previousPriority = getCurrentUpdatePriority(); + setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); + setPending(true); + var prevTransition = ReactCurrentBatchConfig$1.transition; + ReactCurrentBatchConfig$1.transition = {}; + var currentTransition = ReactCurrentBatchConfig$1.transition; -var arrayLikeKeys$1 = _arrayLikeKeys, - baseKeysIn$1 = _baseKeysIn, - isArrayLike$7 = isArrayLike_1; + { + ReactCurrentBatchConfig$1.transition._updatedFibers = new Set(); + } -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn$5(object) { - return isArrayLike$7(object) ? arrayLikeKeys$1(object, true) : baseKeysIn$1(object); -} + try { + setPending(false); + callback(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$1.transition = prevTransition; -var keysIn_1 = keysIn$5; + { + if (prevTransition === null && currentTransition._updatedFibers) { + var updatedFibersCount = currentTransition._updatedFibers.size; -var copyObject$3 = _copyObject, - keysIn$4 = keysIn_1; + if (updatedFibersCount > 10) { + warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); + } -/** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ -function baseAssignIn$1(object, source) { - return object && copyObject$3(source, keysIn$4(source), object); -} + currentTransition._updatedFibers.clear(); + } + } + } + } -var _baseAssignIn = baseAssignIn$1; + function mountTransition() { + var _mountState2 = mountState(false), + isPending = _mountState2[0], + setPending = _mountState2[1]; // The `start` method never changes. -var _cloneBuffer = {exports: {}}; -(function (module, exports) { - var root = _root; + var start = startTransition.bind(null, setPending); + var hook = mountWorkInProgressHook(); + hook.memoizedState = start; + return [isPending, start]; + } - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; + function updateTransition() { + var _updateState2 = updateState(), + isPending = _updateState2[0]; - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + var hook = updateWorkInProgressHook(); + var start = hook.memoizedState; + return [isPending, start]; + } - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + function rerenderTransition() { + var _rerenderState2 = rerenderState(), + isPending = _rerenderState2[0]; - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; + var hook = updateWorkInProgressHook(); + var start = hook.memoizedState; + return [isPending, start]; + } - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); + var isUpdatingOpaqueValueInRenderPhase = false; + function getIsUpdatingOpaqueValueInRenderPhaseInDEV() { + { + return isUpdatingOpaqueValueInRenderPhase; } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; } - module.exports = cloneBuffer; -} (_cloneBuffer, _cloneBuffer.exports)); - -/** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ + function mountId() { + var hook = mountWorkInProgressHook(); + var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we + // should do this in Fiber, too? Deferring this decision for now because + // there's no other place to store the prefix except for an internal field on + // the public createRoot object, which the fiber tree does not currently have + // a reference to. -function copyArray$1(source, array) { - var index = -1, - length = source.length; + var identifierPrefix = root.identifierPrefix; + var id; - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; -} + if (getIsHydrating()) { + var treeId = getTreeId(); // Use a captial R prefix for server-generated ids. -var _copyArray = copyArray$1; + id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end + // that represents the position of this useId hook among all the useId + // hooks for this fiber. -var copyObject$2 = _copyObject, - getSymbols$2 = _getSymbols; + var localId = localIdCounter++; -/** - * Copies own symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ -function copySymbols$1(source, object) { - return copyObject$2(source, getSymbols$2(source), object); -} + if (localId > 0) { + id += 'H' + localId.toString(32); + } -var _copySymbols = copySymbols$1; + id += ':'; + } else { + // Use a lowercase r prefix for client-generated ids. + var globalClientId = globalClientIdCounter++; + id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':'; + } -var overArg$1 = _overArg; + hook.memoizedState = id; + return id; + } -/** Built-in value references. */ -var getPrototype$3 = overArg$1(Object.getPrototypeOf, Object); + function updateId() { + var hook = updateWorkInProgressHook(); + var id = hook.memoizedState; + return id; + } -var _getPrototype = getPrototype$3; + function dispatchReducerAction(fiber, queue, action) { + { + if (typeof arguments[3] === 'function') { + error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); + } + } -var arrayPush$3 = _arrayPush, - getPrototype$2 = _getPrototype, - getSymbols$1 = _getSymbols, - stubArray$1 = stubArray_1; + var lane = requestUpdateLane(fiber); + var update = { + lane: lane, + action: action, + hasEagerState: false, + eagerState: null, + next: null + }; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + if (isRenderPhaseUpdate(fiber)) { + enqueueRenderPhaseUpdate(queue, update); + } else { + enqueueUpdate$1(fiber, queue, update); + var eventTime = requestEventTime(); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); -/** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ -var getSymbolsIn$3 = !nativeGetSymbols$1 ? stubArray$1 : function(object) { - var result = []; - while (object) { - arrayPush$3(result, getSymbols$1(object)); - object = getPrototype$2(object); - } - return result; -}; + if (root !== null) { + entangleTransitionUpdate(root, queue, lane); + } + } -var _getSymbolsIn = getSymbolsIn$3; + markUpdateInDevTools(fiber, lane); + } -var copyObject$1 = _copyObject, - getSymbolsIn$2 = _getSymbolsIn; + function dispatchSetState(fiber, queue, action) { + { + if (typeof arguments[3] === 'function') { + error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); + } + } -/** - * Copies own and inherited symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ -function copySymbolsIn$1(source, object) { - return copyObject$1(source, getSymbolsIn$2(source), object); -} + var lane = requestUpdateLane(fiber); + var update = { + lane: lane, + action: action, + hasEagerState: false, + eagerState: null, + next: null + }; -var _copySymbolsIn = copySymbolsIn$1; + if (isRenderPhaseUpdate(fiber)) { + enqueueRenderPhaseUpdate(queue, update); + } else { + enqueueUpdate$1(fiber, queue, update); + var alternate = fiber.alternate; -var baseGetAllKeys$1 = _baseGetAllKeys, - getSymbolsIn$1 = _getSymbolsIn, - keysIn$3 = keysIn_1; + if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) { + // The queue is currently empty, which means we can eagerly compute the + // next state before entering the render phase. If the new state is the + // same as the current state, we may be able to bail out entirely. + var lastRenderedReducer = queue.lastRenderedReducer; -/** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ -function getAllKeysIn$3(object) { - return baseGetAllKeys$1(object, keysIn$3, getSymbolsIn$1); -} + if (lastRenderedReducer !== null) { + var prevDispatcher; -var _getAllKeysIn = getAllKeysIn$3; + { + prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + } -/** Used for built-in method references. */ + try { + var currentState = queue.lastRenderedState; + var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute + // it, on the update object. If the reducer hasn't changed by the + // time we enter the render phase, then the eager state can be used + // without calling the reducer again. -var objectProto$5 = Object.prototype; + update.hasEagerState = true; + update.eagerState = eagerState; -/** Used to check objects for own properties. */ -var hasOwnProperty$5 = objectProto$5.hasOwnProperty; + if (objectIs(eagerState, currentState)) { + // Fast path. We can bail out without scheduling React to re-render. + // It's still possible that we'll need to rebase this update later, + // if the component re-renders for a different reason and by that + // time the reducer has changed. + return; + } + } catch (error) {// Suppress the error. It will throw again in the render phase. + } finally { + { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + } + } + } -/** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ -function initCloneArray$1(array) { - var length = array.length, - result = new array.constructor(length); + var eventTime = requestEventTime(); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty$5.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; -} + if (root !== null) { + entangleTransitionUpdate(root, queue, lane); + } + } -var _initCloneArray = initCloneArray$1; + markUpdateInDevTools(fiber, lane); + } -var Uint8Array$1 = _Uint8Array; + function isRenderPhaseUpdate(fiber) { + var alternate = fiber.alternate; + return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1; + } -/** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ -function cloneArrayBuffer$3(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); - return result; -} + function enqueueRenderPhaseUpdate(queue, update) { + // This is a render phase update. Stash it in a lazily-created map of + // queue -> linked list of updates. After this render pass, we'll restart + // and apply the stashed updates on top of the work-in-progress hook. + didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; + var pending = queue.pending; -var _cloneArrayBuffer = cloneArrayBuffer$3; + if (pending === null) { + // This is the first update. Create a circular list. + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } -var cloneArrayBuffer$2 = _cloneArrayBuffer; + queue.pending = update; + } -/** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ -function cloneDataView$1(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer$2(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); -} + function enqueueUpdate$1(fiber, queue, update, lane) { + if (isInterleavedUpdate(fiber)) { + var interleaved = queue.interleaved; -var _cloneDataView = cloneDataView$1; + if (interleaved === null) { + // This is the first update. Create a circular list. + update.next = update; // At the end of the current render, this queue's interleaved updates will + // be transferred to the pending queue. -/** Used to match `RegExp` flags from their coerced string values. */ + pushInterleavedQueue(queue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } -var reFlags = /\w*$/; + queue.interleaved = update; + } else { + var pending = queue.pending; -/** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ -function cloneRegExp$1(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; -} + if (pending === null) { + // This is the first update. Create a circular list. + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } + + queue.pending = update; + } + } -var _cloneRegExp = cloneRegExp$1; + function entangleTransitionUpdate(root, queue, lane) { + if (isTransitionLane(lane)) { + var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they + // must have finished. We can remove them from the shared queue, which + // represents a superset of the actually pending lanes. In some cases we + // may entangle more than we need to, but that's OK. In fact it's worse if + // we *don't* entangle when we should. -var Symbol$4 = _Symbol; + queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$4 ? Symbol$4.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + var newQueueLanes = mergeLanes(queueLanes, lane); + queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if + // the lane finished since the last time we entangled it. So we need to + // entangle it again, just to be sure. -/** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ -function cloneSymbol$1(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; -} + markRootEntangled(root, newQueueLanes); + } + } -var _cloneSymbol = cloneSymbol$1; + function markUpdateInDevTools(fiber, lane, action) { -var cloneArrayBuffer$1 = _cloneArrayBuffer; + { + markStateUpdateScheduled(fiber, lane); + } + } -/** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ -function cloneTypedArray$1(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer$1(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); -} + var ContextOnlyDispatcher = { + readContext: readContext, + useCallback: throwInvalidHookError, + useContext: throwInvalidHookError, + useEffect: throwInvalidHookError, + useImperativeHandle: throwInvalidHookError, + useInsertionEffect: throwInvalidHookError, + useLayoutEffect: throwInvalidHookError, + useMemo: throwInvalidHookError, + useReducer: throwInvalidHookError, + useRef: throwInvalidHookError, + useState: throwInvalidHookError, + useDebugValue: throwInvalidHookError, + useDeferredValue: throwInvalidHookError, + useTransition: throwInvalidHookError, + useMutableSource: throwInvalidHookError, + useSyncExternalStore: throwInvalidHookError, + useId: throwInvalidHookError, + unstable_isNewReconciler: enableNewReconciler + }; -var _cloneTypedArray = cloneTypedArray$1; + var HooksDispatcherOnMountInDEV = null; + var HooksDispatcherOnMountWithHookTypesInDEV = null; + var HooksDispatcherOnUpdateInDEV = null; + var HooksDispatcherOnRerenderInDEV = null; + var InvalidNestedHooksDispatcherOnMountInDEV = null; + var InvalidNestedHooksDispatcherOnUpdateInDEV = null; + var InvalidNestedHooksDispatcherOnRerenderInDEV = null; -var cloneArrayBuffer = _cloneArrayBuffer, - cloneDataView = _cloneDataView, - cloneRegExp = _cloneRegExp, - cloneSymbol = _cloneSymbol, - cloneTypedArray = _cloneTypedArray; + { + var warnInvalidContextAccess = function () { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + }; -/** `Object#toString` result references. */ -var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - mapTag$2 = '[object Map]', - numberTag$1 = '[object Number]', - regexpTag$2 = '[object RegExp]', - setTag$2 = '[object Set]', - stringTag$2 = '[object String]', - symbolTag$3 = '[object Symbol]'; - -var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$1 = '[object DataView]', - float32Tag$1 = '[object Float32Array]', - float64Tag$1 = '[object Float64Array]', - int8Tag$1 = '[object Int8Array]', - int16Tag$1 = '[object Int16Array]', - int32Tag$1 = '[object Int32Array]', - uint8Tag$1 = '[object Uint8Array]', - uint8ClampedTag$1 = '[object Uint8ClampedArray]', - uint16Tag$1 = '[object Uint16Array]', - uint32Tag$1 = '[object Uint32Array]'; + var warnInvalidHookAccess = function () { + error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); + }; -/** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ -function initCloneByTag$1(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag$1: - return cloneArrayBuffer(object); + HooksDispatcherOnMountInDEV = { + readContext: function (context) { + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + mountHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case boolTag$1: - case dateTag$1: - return new Ctor(+object); + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case dataViewTag$1: - return cloneDataView(object, isDeep); + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + mountHookTypesDev(); + return mountRef(initialValue); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case float32Tag$1: case float64Tag$1: - case int8Tag$1: case int16Tag$1: case int32Tag$1: - case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: - return cloneTypedArray(object, isDeep); + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + mountHookTypesDev(); + return mountDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + mountHookTypesDev(); + return mountDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + mountHookTypesDev(); + return mountTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + mountHookTypesDev(); + return mountMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + mountHookTypesDev(); + return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + mountHookTypesDev(); + return mountId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; - case mapTag$2: - return new Ctor; + HooksDispatcherOnMountWithHookTypesInDEV = { + readContext: function (context) { + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + updateHookTypesDev(); + return mountCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + updateHookTypesDev(); + return mountEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + updateHookTypesDev(); + return mountImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + updateHookTypesDev(); + return mountInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + updateHookTypesDev(); + return mountLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case numberTag$1: - case stringTag$2: - return new Ctor(object); + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case regexpTag$2: - return cloneRegExp(object); + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + updateHookTypesDev(); + return mountRef(initialValue); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case setTag$2: - return new Ctor; + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + updateHookTypesDev(); + return mountDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + updateHookTypesDev(); + return mountDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + updateHookTypesDev(); + return mountTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + updateHookTypesDev(); + return mountMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + updateHookTypesDev(); + return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + updateHookTypesDev(); + return mountId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; - case symbolTag$3: - return cloneSymbol(object); - } -} + HooksDispatcherOnUpdateInDEV = { + readContext: function (context) { + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -var _initCloneByTag = initCloneByTag$1; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -var isObject$6 = isObject_1; + try { + return updateReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + updateHookTypesDev(); + return updateRef(); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/** Built-in value references. */ -var objectCreate = Object.create; + try { + return updateState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + updateHookTypesDev(); + return updateDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + updateHookTypesDev(); + return updateTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; -/** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ -var baseCreate$1 = (function() { - function object() {} - return function(proto) { - if (!isObject$6(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; -}()); + HooksDispatcherOnRerenderInDEV = { + readContext: function (context) { + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; -var _baseCreate = baseCreate$1; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; -var baseCreate = _baseCreate, - getPrototype$1 = _getPrototype, - isPrototype$2 = _isPrototype; + try { + return rerenderReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + updateHookTypesDev(); + return updateRef(); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; -/** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ -function initCloneObject$1(object) { - return (typeof object.constructor == 'function' && !isPrototype$2(object)) - ? baseCreate(getPrototype$1(object)) - : {}; -} + try { + return rerenderState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + updateHookTypesDev(); + return rerenderDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + updateHookTypesDev(); + return rerenderTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; -var _initCloneObject = initCloneObject$1; + InvalidNestedHooksDispatcherOnMountInDEV = { + readContext: function (context) { + warnInvalidContextAccess(); + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + warnInvalidHookAccess(); + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; -var getTag$3 = _getTag, - isObjectLike$6 = isObjectLike_1; + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + warnInvalidHookAccess(); + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; -/** `Object#toString` result references. */ -var mapTag$1 = '[object Map]'; + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountRef(initialValue); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + warnInvalidHookAccess(); + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; -/** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ -function baseIsMap$1(value) { - return isObjectLike$6(value) && getTag$3(value) == mapTag$1; -} + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; -var _baseIsMap = baseIsMap$1; + InvalidNestedHooksDispatcherOnUpdateInDEV = { + readContext: function (context) { + warnInvalidContextAccess(); + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -var baseIsMap = _baseIsMap, - baseUnary$4 = _baseUnary, - nodeUtil$2 = _nodeUtil.exports; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/* Node.js helper references. */ -var nodeIsMap = nodeUtil$2 && nodeUtil$2.isMap; + try { + return updateReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateRef(); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/** - * Checks if `value` is classified as a `Map` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - * @example - * - * _.isMap(new Map); - * // => true - * - * _.isMap(new WeakMap); - * // => false - */ -var isMap$1 = nodeIsMap ? baseUnary$4(nodeIsMap) : baseIsMap; + try { + return updateState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; -var isMap_1 = isMap$1; + InvalidNestedHooksDispatcherOnRerenderInDEV = { + readContext: function (context) { + warnInvalidContextAccess(); + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -var getTag$2 = _getTag, - isObjectLike$5 = isObjectLike_1; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/** `Object#toString` result references. */ -var setTag$1 = '[object Set]'; + try { + return rerenderReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateRef(); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ -function baseIsSet$1(value) { - return isObjectLike$5(value) && getTag$2(value) == setTag$1; -} + try { + return rerenderState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return rerenderDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return rerenderTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; + } -var _baseIsSet = baseIsSet$1; + var now$2 = Scheduler.unstable_now; + var commitTime = 0; + var layoutEffectStartTime = -1; + var profilerStartTime = -1; + var passiveEffectStartTime = -1; + /** + * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect). + * + * The overall sequence is: + * 1. render + * 2. commit (and call `onRender`, `onCommit`) + * 3. check for nested updates + * 4. flush passive effects (and call `onPostCommit`) + * + * Nested updates are identified in step 3 above, + * but step 4 still applies to the work that was just committed. + * We use two flags to track nested updates then: + * one tracks whether the upcoming update is a nested update, + * and the other tracks whether the current update was a nested update. + * The first value gets synced to the second at the start of the render phase. + */ -var baseIsSet = _baseIsSet, - baseUnary$3 = _baseUnary, - nodeUtil$1 = _nodeUtil.exports; + var currentUpdateIsNested = false; + var nestedUpdateScheduled = false; -/* Node.js helper references. */ -var nodeIsSet = nodeUtil$1 && nodeUtil$1.isSet; + function isCurrentUpdateNested() { + return currentUpdateIsNested; + } -/** - * Checks if `value` is classified as a `Set` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - * @example - * - * _.isSet(new Set); - * // => true - * - * _.isSet(new WeakSet); - * // => false - */ -var isSet$1 = nodeIsSet ? baseUnary$3(nodeIsSet) : baseIsSet; - -var isSet_1 = isSet$1; - -var Stack = _Stack, - arrayEach = _arrayEach, - assignValue$2 = _assignValue, - baseAssign = _baseAssign, - baseAssignIn = _baseAssignIn, - cloneBuffer = _cloneBuffer.exports, - copyArray = _copyArray, - copySymbols = _copySymbols, - copySymbolsIn = _copySymbolsIn, - getAllKeys = _getAllKeys, - getAllKeysIn$2 = _getAllKeysIn, - getTag$1 = _getTag, - initCloneArray = _initCloneArray, - initCloneByTag = _initCloneByTag, - initCloneObject = _initCloneObject, - isArray$a = isArray_1$1, - isBuffer = isBuffer$4.exports, - isMap = isMap_1, - isObject$5 = isObject_1, - isSet = isSet_1, - keys$3 = keys_1, - keysIn$2 = keysIn_1; - -/** Used to compose bitmasks for cloning. */ -var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG$1 = 4; + function markNestedUpdateScheduled() { + { + nestedUpdateScheduled = true; + } + } -/** `Object#toString` result references. */ -var argsTag$2 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag$2 = '[object Function]', - genTag$2 = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag$1 = '[object RegExp]', - setTag = '[object Set]', - stringTag$1 = '[object String]', - symbolTag$2 = '[object Symbol]', - weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values supported by `_.clone`. */ -var cloneableTags = {}; -cloneableTags[argsTag$2] = cloneableTags[arrayTag] = -cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = -cloneableTags[boolTag] = cloneableTags[dateTag] = -cloneableTags[float32Tag] = cloneableTags[float64Tag] = -cloneableTags[int8Tag] = cloneableTags[int16Tag] = -cloneableTags[int32Tag] = cloneableTags[mapTag] = -cloneableTags[numberTag] = cloneableTags[objectTag] = -cloneableTags[regexpTag$1] = cloneableTags[setTag] = -cloneableTags[stringTag$1] = cloneableTags[symbolTag$2] = -cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = -cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; -cloneableTags[errorTag] = cloneableTags[funcTag$2] = -cloneableTags[weakMapTag] = false; + function resetNestedUpdateFlag() { + { + currentUpdateIsNested = false; + nestedUpdateScheduled = false; + } + } -/** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} bitmask The bitmask flags. - * 1 - Deep clone - * 2 - Flatten inherited properties - * 4 - Clone symbols - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ -function baseClone$1(value, bitmask, customizer, key, object, stack) { - var result, - isDeep = bitmask & CLONE_DEEP_FLAG, - isFlat = bitmask & CLONE_FLAT_FLAG, - isFull = bitmask & CLONE_SYMBOLS_FLAG$1; + function syncNestedUpdateFlag() { + { + currentUpdateIsNested = nestedUpdateScheduled; + nestedUpdateScheduled = false; + } + } - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject$5(value)) { - return value; - } - var isArr = isArray$a(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag$1(value), - isFunc = tag == funcTag$2 || tag == genTag$2; + function getCommitTime() { + return commitTime; + } - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag$2 || (isFunc && !object)) { - result = (isFlat || isFunc) ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat - ? copySymbolsIn(value, baseAssignIn(result, value)) - : copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); + function recordCommitTime() { - if (isSet(value)) { - value.forEach(function(subValue) { - result.add(baseClone$1(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key) { - result.set(key, baseClone$1(subValue, bitmask, customizer, key, value, stack)); - }); - } + commitTime = now$2(); + } - var keysFunc = isFull - ? (isFlat ? getAllKeysIn$2 : getAllKeys) - : (isFlat ? keysIn$2 : keys$3); + function startProfilerTimer(fiber) { - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue$2(result, key, baseClone$1(subValue, bitmask, customizer, key, value, stack)); - }); - return result; -} + profilerStartTime = now$2(); -var _baseClone = baseClone$1; + if (fiber.actualStartTime < 0) { + fiber.actualStartTime = now$2(); + } + } -var baseClone = _baseClone; + function stopProfilerTimerIfRunning(fiber) { -/** Used to compose bitmasks for cloning. */ -var CLONE_SYMBOLS_FLAG = 4; + profilerStartTime = -1; + } -/** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ -function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); -} + function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { -var clone_1$1 = clone; + if (profilerStartTime >= 0) { + var elapsedTime = now$2() - profilerStartTime; + fiber.actualDuration += elapsedTime; -var api$2 = {}; + if (overrideBaseTime) { + fiber.selfBaseDuration = elapsedTime; + } -var print = {}; + profilerStartTime = -1; + } + } -Object.defineProperty(print, "__esModule", { value: true }); -print.PRINT_WARNING = print.PRINT_ERROR = void 0; -function PRINT_ERROR(msg) { - /* istanbul ignore else - can't override global.console in node.js */ - if (console && console.error) { - console.error("Error: ".concat(msg)); - } -} -print.PRINT_ERROR = PRINT_ERROR; -function PRINT_WARNING(msg) { - /* istanbul ignore else - can't override global.console in node.js*/ - if (console && console.warn) { - // TODO: modify docs accordingly - console.warn("Warning: ".concat(msg)); - } -} -print.PRINT_WARNING = PRINT_WARNING; - -var timer$1 = {}; - -Object.defineProperty(timer$1, "__esModule", { value: true }); -timer$1.timer = void 0; -function timer(func) { - var start = new Date().getTime(); - var val = func(); - var end = new Date().getTime(); - var total = end - start; - return { time: total, value: val }; -} -timer$1.timer = timer; - -var toFastProperties$1 = {}; - -Object.defineProperty(toFastProperties$1, "__esModule", { value: true }); -toFastProperties$1.toFastProperties = void 0; -// based on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216 -function toFastProperties(toBecomeFast) { - function FakeConstructor() { } - // If our object is used as a constructor it would receive - FakeConstructor.prototype = toBecomeFast; - var fakeInstance = new FakeConstructor(); - function fakeAccess() { - return typeof fakeInstance.bar; - } - // help V8 understand this is a "real" prototype by actually using - // the fake instance. - fakeAccess(); - fakeAccess(); - return toBecomeFast; -} -toFastProperties$1.toFastProperties = toFastProperties; - -(function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.toFastProperties = exports.timer = exports.PRINT_ERROR = exports.PRINT_WARNING = void 0; - var print_1 = print; - Object.defineProperty(exports, "PRINT_WARNING", { enumerable: true, get: function () { return print_1.PRINT_WARNING; } }); - Object.defineProperty(exports, "PRINT_ERROR", { enumerable: true, get: function () { return print_1.PRINT_ERROR; } }); - var timer_1 = timer$1; - Object.defineProperty(exports, "timer", { enumerable: true, get: function () { return timer_1.timer; } }); - var to_fast_properties_1 = toFastProperties$1; - Object.defineProperty(exports, "toFastProperties", { enumerable: true, get: function () { return to_fast_properties_1.toFastProperties; } }); - -} (api$2)); - -var follow = {}; - -var rest = {}; + function recordLayoutEffectDuration(fiber) { -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ + if (layoutEffectStartTime >= 0) { + var elapsedTime = now$2() - layoutEffectStartTime; + layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor + // Or the root (for the DevTools Profiler to read) -function baseSlice$3(array, start, end) { - var index = -1, - length = array.length; + var parentFiber = fiber.return; - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + root.effectDuration += elapsedTime; + return; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.effectDuration += elapsedTime; + return; + } + + parentFiber = parentFiber.return; + } + } + } -var _baseSlice = baseSlice$3; + function recordPassiveEffectDuration(fiber) { -/** Used to match a single whitespace character. */ + if (passiveEffectStartTime >= 0) { + var elapsedTime = now$2() - passiveEffectStartTime; + passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor + // Or the root (for the DevTools Profiler to read) -var reWhitespace = /\s/; + var parentFiber = fiber.return; -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ -function trimmedEndIndex$1(string) { - var index = string.length; + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; - while (index-- && reWhitespace.test(string.charAt(index))) {} - return index; -} + if (root !== null) { + root.passiveEffectDuration += elapsedTime; + } -var _trimmedEndIndex = trimmedEndIndex$1; + return; -var trimmedEndIndex = _trimmedEndIndex; + case Profiler: + var parentStateNode = parentFiber.stateNode; -/** Used to match leading whitespace. */ -var reTrimStart = /^\s+/; + if (parentStateNode !== null) { + // Detached fibers have their state node cleared out. + // In this case, the return pointer is also cleared out, + // so we won't be able to report the time spent in this Profiler's subtree. + parentStateNode.passiveEffectDuration += elapsedTime; + } -/** - * The base implementation of `_.trim`. - * - * @private - * @param {string} string The string to trim. - * @returns {string} Returns the trimmed string. - */ -function baseTrim$1(string) { - return string - ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') - : string; -} + return; + } -var _baseTrim = baseTrim$1; + parentFiber = parentFiber.return; + } + } + } -var baseTrim = _baseTrim, - isObject$4 = isObject_1, - isSymbol$2 = isSymbol_1; + function startLayoutEffectTimer() { -/** Used as references for various `Number` constants. */ -var NAN = 0 / 0; + layoutEffectStartTime = now$2(); + } + + function startPassiveEffectTimer() { -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + passiveEffectStartTime = now$2(); + } -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + function transferActualDuration(fiber) { + // Transfer time spent rendering these children so we don't lose it + // after we rerender. This is used as a helper in special cases + // where we should count the work of multiple passes. + var child = fiber.child; -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; + while (child) { + fiber.actualDuration += child.actualDuration; + child = child.sibling; + } + } -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; + function createCapturedValue(value, source) { + // If the value is an error, call this function immediately after it is thrown + // so the stack is accurate. + return { + value: value, + source: source, + stack: getStackByFiberInDevAndProd(source) + }; + } -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber$1(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol$2(value)) { - return NAN; - } - if (isObject$4(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject$4(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); -} + // This module is forked in different environments. + // By default, return `true` to log errors to the console. + // Forks can return `false` if this isn't desirable. + function showErrorDialog(boundary, errorInfo) { + return true; + } -var toNumber_1 = toNumber$1; + function logCapturedError(boundary, errorInfo) { + try { + var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging. + // This enables renderers like ReactNative to better manage redbox behavior. -var toNumber = toNumber_1; + if (logError === false) { + return; + } -/** Used as references for various `Number` constants. */ -var INFINITY$3 = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308; + var error = errorInfo.value; -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite$1(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY$3 || value === -INFINITY$3) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; -} + if (true) { + var source = errorInfo.source; + var stack = errorInfo.stack; + var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling + // `preventDefault()` in window `error` handler. + // We record this information as an expando on the error. -var toFinite_1 = toFinite$1; + if (error != null && error._suppressLogging) { + if (boundary.tag === ClassComponent) { + // The error is recoverable and was silenced. + // Ignore it and don't print the stack addendum. + // This is handy for testing error boundaries without noise. + return; + } // The error is fatal. Since the silencing might have + // been accidental, we'll surface it anyway. + // However, the browser would have silenced the original error + // so we'll print it first, and then print the stack addendum. -var toFinite = toFinite_1; -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger$5(value) { - var result = toFinite(value), - remainder = result % 1; + console['error'](error); // Don't transform to our wrapper + // For a more detailed description of this block, see: + // https://github.com/facebook/react/pull/13384 + } - return result === result ? (remainder ? result - remainder : result) : 0; -} + var componentName = source ? getComponentNameFromFiber(source) : null; + var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:'; + var errorBoundaryMessage; -var toInteger_1 = toInteger$5; + if (boundary.tag === HostRoot) { + errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.'; + } else { + var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous'; + errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + "."); + } -var baseSlice$2 = _baseSlice, - toInteger$4 = toInteger_1; + var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. + // We don't include the original error message and JS stack because the browser + // has already printed it. Even if the application swallows the error, it is still + // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. -/** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ -function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger$4(n); - return baseSlice$2(array, n < 0 ? 0 : n, length); -} + console['error'](combinedMessage); // Don't transform to our wrapper + } + } catch (e) { + // This method must not throw, or React internal state will get messed up. + // If console.error is overridden, or logCapturedError() shows a dialog that throws, + // we want to report this error outside of the normal stack as a last resort. + // https://github.com/facebook/react/issues/13188 + setTimeout(function () { + throw e; + }); + } + } -var drop_1$2 = drop; + var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map; -var api$1 = {}; + function createRootErrorUpdate(fiber, errorInfo, lane) { + var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null. -var model$1 = {}; + update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property + // being called "element". -var baseGetTag$1 = _baseGetTag, - isArray$9 = isArray_1$1, - isObjectLike$4 = isObjectLike_1; + update.payload = { + element: null + }; + var error = errorInfo.value; -/** `Object#toString` result references. */ -var stringTag = '[object String]'; + update.callback = function () { + onUncaughtError(error); + logCapturedError(fiber, errorInfo); + }; -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString$1(value) { - return typeof value == 'string' || - (!isArray$9(value) && isObjectLike$4(value) && baseGetTag$1(value) == stringTag); -} + return update; + } -var isString_1$1 = isString$1; + function createClassErrorUpdate(fiber, errorInfo, lane) { + var update = createUpdate(NoTimestamp, lane); + update.tag = CaptureUpdate; + var getDerivedStateFromError = fiber.type.getDerivedStateFromError; -var baseGetTag = _baseGetTag, - isObjectLike$3 = isObjectLike_1; + if (typeof getDerivedStateFromError === 'function') { + var error$1 = errorInfo.value; -/** `Object#toString` result references. */ -var regexpTag = '[object RegExp]'; + update.payload = function () { + return getDerivedStateFromError(error$1); + }; -/** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ -function baseIsRegExp$1(value) { - return isObjectLike$3(value) && baseGetTag(value) == regexpTag; -} + update.callback = function () { + { + markFailedErrorBoundaryForHotReloading(fiber); + } -var _baseIsRegExp = baseIsRegExp$1; + logCapturedError(fiber, errorInfo); + }; + } -var baseIsRegExp = _baseIsRegExp, - baseUnary$2 = _baseUnary, - nodeUtil = _nodeUtil.exports; + var inst = fiber.stateNode; -/* Node.js helper references. */ -var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; + if (inst !== null && typeof inst.componentDidCatch === 'function') { + update.callback = function callback() { + { + markFailedErrorBoundaryForHotReloading(fiber); + } -/** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ -var isRegExp = nodeIsRegExp ? baseUnary$2(nodeIsRegExp) : baseIsRegExp; + logCapturedError(fiber, errorInfo); -var isRegExp_1$1 = isRegExp; + if (typeof getDerivedStateFromError !== 'function') { + // To preserve the preexisting retry behavior of error boundaries, + // we keep track of which ones already failed during this batch. + // This gets reset before we yield back to the browser. + // TODO: Warn in strict mode if getDerivedStateFromError is + // not defined. + markLegacyErrorBoundaryAsFailed(this); + } -var assignValue$1 = _assignValue, - castPath$1 = _castPath, - isIndex$2 = _isIndex, - isObject$3 = isObject_1, - toKey$2 = _toKey; + var error$1 = errorInfo.value; + var stack = errorInfo.stack; + this.componentDidCatch(error$1, { + componentStack: stack !== null ? stack : '' + }); -/** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ -function baseSet$1(object, path, value, customizer) { - if (!isObject$3(object)) { - return object; - } - path = castPath$1(path, object); + { + if (typeof getDerivedStateFromError !== 'function') { + // If componentDidCatch is the only error boundary method defined, + // then it needs to call setState to recover from errors. + // If no state update is scheduled then the boundary will swallow the error. + if (!includesSomeLane(fiber.lanes, SyncLane)) { + error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown'); + } + } + } + }; + } - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; + return update; + } - while (nested != null && ++index < length) { - var key = toKey$2(path[index]), - newValue = value; + function attachPingListener(root, wakeable, lanes) { + // Attach a ping listener + // + // The data might resolve before we have a chance to commit the fallback. Or, + // in the case of a refresh, we'll never commit a fallback. So we need to + // attach a listener now. When it resolves ("pings"), we can decide whether to + // try rendering the tree again. + // + // Only attach a listener if one does not already exist for the lanes + // we're currently rendering (which acts like a "thread ID" here). + // + // We only need to do this in concurrent mode. Legacy Suspense always + // commits fallbacks synchronously, so there are no pings. + var pingCache = root.pingCache; + var threadIDs; - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } + if (pingCache === null) { + pingCache = root.pingCache = new PossiblyWeakMap$1(); + threadIDs = new Set(); + pingCache.set(wakeable, threadIDs); + } else { + threadIDs = pingCache.get(wakeable); - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject$3(objValue) - ? objValue - : (isIndex$2(path[index + 1]) ? [] : {}); - } - } - assignValue$1(nested, key, newValue); - nested = nested[key]; - } - return object; -} + if (threadIDs === undefined) { + threadIDs = new Set(); + pingCache.set(wakeable, threadIDs); + } + } -var _baseSet = baseSet$1; + if (!threadIDs.has(lanes)) { + // Memoize using the thread ID to prevent redundant listeners. + threadIDs.add(lanes); + var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes); -var baseGet = _baseGet, - baseSet = _baseSet, - castPath = _castPath; + { + if (isDevToolsPresent) { + // If we have pending work still, restore the original updaters + restorePendingUpdaters(root, lanes); + } + } -/** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ -function basePickBy$3(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; + wakeable.then(ping, ping); + } + } - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); + function attachRetryListener(suspenseBoundary, root, wakeable, lanes) { + // Retry listener + // + // If the fallback does commit, we need to attach a different type of + // listener. This one schedules an update on the Suspense boundary to turn + // the fallback state off. + // + // Stash the wakeable on the boundary fiber so we can access it in the + // commit phase. + // + // When the wakeable resolves, we'll attempt to render the boundary + // again ("retry"). + var wakeables = suspenseBoundary.updateQueue; - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; -} + if (wakeables === null) { + var updateQueue = new Set(); + updateQueue.add(wakeable); + suspenseBoundary.updateQueue = updateQueue; + } else { + wakeables.add(wakeable); + } + } -var _basePickBy = basePickBy$3; + function resetSuspendedComponent(sourceFiber, rootRenderLanes) { + // A legacy mode Suspense quirk, only relevant to hook components. -var arrayMap$3 = _arrayMap, - baseIteratee$8 = _baseIteratee, - basePickBy$2 = _basePickBy, - getAllKeysIn$1 = _getAllKeysIn; -/** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ -function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap$3(getAllKeysIn$1(object), function(prop) { - return [prop]; - }); - predicate = baseIteratee$8(predicate); - return basePickBy$2(object, props, function(value, path) { - return predicate(value, path[0]); - }); -} + var tag = sourceFiber.tag; -var pickBy_1$1 = pickBy; + if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) { + var currentSource = sourceFiber.alternate; -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ + if (currentSource) { + sourceFiber.updateQueue = currentSource.updateQueue; + sourceFiber.memoizedState = currentSource.memoizedState; + sourceFiber.lanes = currentSource.lanes; + } else { + sourceFiber.updateQueue = null; + sourceFiber.memoizedState = null; + } + } + } -function apply$3(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} + function getNearestSuspenseBoundaryToCapture(returnFiber) { + var node = returnFiber; -var _apply = apply$3; + do { + if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) { + return node; + } // This boundary already captured during this render. Continue to the next + // boundary. -var apply$2 = _apply; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax$5 = Math.max; + node = node.return; + } while (node !== null); -/** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ -function overRest$1(func, start, transform) { - start = nativeMax$5(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax$5(args.length - start, 0), - array = Array(length); + return null; + } - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply$2(func, this, otherArgs); - }; -} + function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) { + // This marks a Suspense boundary so that when we're unwinding the stack, + // it captures the suspended "exception" and does a second (fallback) pass. + if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { + // Legacy Mode Suspense + // + // If the boundary is in legacy mode, we should *not* + // suspend the commit. Pretend as if the suspended component rendered + // null and keep rendering. When the Suspense boundary completes, + // we'll do a second pass to render the fallback. + if (suspenseBoundary === returnFiber) { + // Special case where we suspended while reconciling the children of + // a Suspense boundary's inner Offscreen wrapper fiber. This happens + // when a React.lazy component is a direct child of a + // Suspense boundary. + // + // Suspense boundaries are implemented as multiple fibers, but they + // are a single conceptual unit. The legacy mode behavior where we + // pretend the suspended fiber committed as `null` won't work, + // because in this case the "suspended" fiber is the inner + // Offscreen wrapper. + // + // Because the contents of the boundary haven't started rendering + // yet (i.e. nothing in the tree has partially rendered) we can + // switch to the regular, concurrent mode behavior: mark the + // boundary with ShouldCapture and enter the unwind phase. + suspenseBoundary.flags |= ShouldCapture; + } else { + suspenseBoundary.flags |= DidCapture; + sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete. + // But we shouldn't call any lifecycle methods or callbacks. Remove + // all lifecycle effect tags. -var _overRest = overRest$1; + sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ + if (supportsPersistence && enablePersistentOffscreenHostContainer) { + // Another legacy Suspense quirk. In persistent mode, if this is the + // initial mount, override the props of the host container to hide + // its contents. + var currentSuspenseBoundary = suspenseBoundary.alternate; -function constant$2(value) { - return function() { - return value; - }; -} + if (currentSuspenseBoundary === null) { + var offscreenFiber = suspenseBoundary.child; + var offscreenContainer = offscreenFiber.child; -var constant_1 = constant$2; + if (offscreenContainer !== null) { + var children = offscreenContainer.memoizedProps.children; + var containerProps = getOffscreenContainerProps('hidden', children); + offscreenContainer.pendingProps = containerProps; + offscreenContainer.memoizedProps = containerProps; + } + } + } -var constant$1 = constant_1, - defineProperty = _defineProperty, - identity$1 = identity_1; + if (sourceFiber.tag === ClassComponent) { + var currentSourceFiber = sourceFiber.alternate; -/** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var baseSetToString$1 = !defineProperty ? identity$1 : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant$1(string), - 'writable': true - }); -}; + if (currentSourceFiber === null) { + // This is a new mount. Change the tag so it's not mistaken for a + // completed class component. For example, we should not call + // componentWillUnmount if it is deleted. + sourceFiber.tag = IncompleteClassComponent; + } else { + // When we try rendering again, we should not reuse the current fiber, + // since it's known to be in an inconsistent state. Use a force update to + // prevent a bail out. + var update = createUpdate(NoTimestamp, SyncLane); + update.tag = ForceUpdate; + enqueueUpdate(sourceFiber, update); + } + } // The source fiber did not complete. Mark it with Sync priority to + // indicate that it still has pending work. -var _baseSetToString = baseSetToString$1; -/** Used to detect hot functions by number of calls within a span of milliseconds. */ + sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); + } -var HOT_COUNT = 800, - HOT_SPAN = 16; + return suspenseBoundary; + } // Confirmed that the boundary is in a concurrent mode tree. Continue + // with the normal suspend path. + // + // After this we'll use a set of heuristics to determine whether this + // render pass will run to completion or restart or "suspend" the commit. + // The actual logic for this is spread out in different places. + // + // This first principle is that if we're going to suspend when we complete + // a root, then we should also restart if we get an update or ping that + // might unsuspend it, and vice versa. The only reason to suspend is + // because you think you might want to restart before committing. However, + // it doesn't make sense to restart only while in the period we're suspended. + // + // Restarting too aggressively is also not good because it starves out any + // intermediate loading state. So we use heuristics to determine when. + // Suspense Heuristics + // + // If nothing threw a Promise or all the same fallbacks are already showing, + // then don't suspend/restart. + // + // If this is an initial render of a new tree of Suspense boundaries and + // those trigger a fallback, then don't suspend/restart. We want to ensure + // that we can show the initial loading state as quickly as possible. + // + // If we hit a "Delayed" case, such as when we'd switch from content back into + // a fallback, then we should always suspend/restart. Transitions apply + // to this case. If none is defined, JND is used instead. + // + // If we're already showing a fallback and it gets "retried", allowing us to show + // another level, but there's still an inner boundary that would show a fallback, + // then we suspend/restart for 500ms since the last time we showed a fallback + // anywhere in the tree. This effectively throttles progressive loading into a + // consistent train of commits. This also gives us an opportunity to restart to + // get to the completed state slightly earlier. + // + // If there's ambiguity due to batching it's resolved in preference of: + // 1) "delayed", 2) "initial render", 3) "retry". + // + // We want to ensure that a "busy" state doesn't get force committed. We want to + // ensure that new initial loading states can commit as soon as possible. -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeNow = Date.now; -/** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ -function shortOut$1(func) { - var count = 0, - lastCalled = 0; + suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in + // the begin phase to prevent an early bailout. - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); + suspenseBoundary.lanes = rootRenderLanes; + return suspenseBoundary; + } - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; -} + function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) { + // The source fiber did not complete. + sourceFiber.flags |= Incomplete; -var _shortOut = shortOut$1; + { + if (isDevToolsPresent) { + // If we have pending work still, restore the original updaters + restorePendingUpdaters(root, rootRenderLanes); + } + } -var baseSetToString = _baseSetToString, - shortOut = _shortOut; + if (value !== null && typeof value === 'object' && typeof value.then === 'function') { + // This is a wakeable. The component suspended. + var wakeable = value; + resetSuspendedComponent(sourceFiber); -/** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var setToString$1 = shortOut(baseSetToString); -var _setToString = setToString$1; + var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); -var identity = identity_1, - overRest = _overRest, - setToString = _setToString; + if (suspenseBoundary !== null) { + suspenseBoundary.flags &= ~ForceClientRender; + markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always + // commits fallbacks synchronously, so there are no pings. -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest$5(func, start) { - return setToString(overRest(func, start, identity), func + ''); -} + if (suspenseBoundary.mode & ConcurrentMode) { + attachPingListener(root, wakeable, rootRenderLanes); + } -var _baseRest = baseRest$5; + attachRetryListener(suspenseBoundary, root, wakeable); + return; + } else { + // No boundary was found. Unless this is a sync update, this is OK. + // We can suspend and wait for more data to arrive. + if (!includesSyncLane(rootRenderLanes)) { + // This is not a sync update. Suspend. Since we're not activating a + // Suspense boundary, this will unwind all the way to the root without + // performing a second pass to render a fallback. (This is arguably how + // refresh transitions should work, too, since we're not going to commit + // the fallbacks anyway.) + // + // This case also applies to initial hydration. + attachPingListener(root, wakeable, rootRenderLanes); + renderDidSuspendDelayIfPossible(); + return; + } // This is a sync/discrete update. We treat this case like an error + // because discrete renders are expected to produce a complete tree + // synchronously to maintain consistency with external state. -var eq$2 = eq_1, - isArrayLike$6 = isArrayLike_1, - isIndex$1 = _isIndex, - isObject$2 = isObject_1; -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall$4(value, index, object) { - if (!isObject$2(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike$6(object) && isIndex$1(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq$2(object[index], value); - } - return false; -} + var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path. + // The error will be caught by the nearest suspense boundary. -var _isIterateeCall = isIterateeCall$4; + value = uncaughtSuspenseError; + } + } else { + // This is a regular error, not a Suspense wakeable. + if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { + markDidSuspendWhileHydratingDEV(); -var baseRest$4 = _baseRest, - isIterateeCall$3 = _isIterateeCall; + var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by + // discarding the dehydrated content and switching to a client render. + // Instead of surfacing the error, find the nearest Suspense boundary + // and render it again without hydration. -/** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ -function createAssigner$1(assigner) { - return baseRest$4(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall$3(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); -} -var _createAssigner = createAssigner$1; + if (_suspenseBoundary !== null) { + if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) { + // Set a flag to indicate that we should try rendering the normal + // children again, not the fallback. + _suspenseBoundary.flags |= ForceClientRender; + } -var assignValue = _assignValue, - copyObject = _copyObject, - createAssigner = _createAssigner, - isArrayLike$5 = isArrayLike_1, - isPrototype$1 = _isPrototype, - keys$2 = keys_1; + markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should + // still log it so it can be fixed. -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; + queueHydrationError(value); + return; + } + } + } // We didn't find a boundary that could handle this type of exception. Start + // over and traverse parent path again, this time treating the exception + // as an error. -/** Used to check objects for own properties. */ -var hasOwnProperty$4 = objectProto$4.hasOwnProperty; -/** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } - */ -var assign$2 = createAssigner(function(object, source) { - if (isPrototype$1(source) || isArrayLike$5(source)) { - copyObject(source, keys$2(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty$4.call(source, key)) { - assignValue(object, key, source[key]); - } - } -}); + renderDidError(value); + value = createCapturedValue(value, sourceFiber); + var workInProgress = returnFiber; -var assign_1$3 = assign$2; + do { + switch (workInProgress.tag) { + case HostRoot: + { + var _errorInfo = value; + workInProgress.flags |= ShouldCapture; + var lane = pickArbitraryLane(rootRenderLanes); + workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); + var update = createRootErrorUpdate(workInProgress, _errorInfo, lane); + enqueueCapturedUpdate(workInProgress, update); + return; + } -var __extends$4 = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$9 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(model$1, "__esModule", { value: true }); -model$1.serializeProduction = model$1.serializeGrammar = model$1.Terminal = model$1.Alternation = model$1.RepetitionWithSeparator = model$1.Repetition = model$1.RepetitionMandatoryWithSeparator = model$1.RepetitionMandatory = model$1.Option = model$1.Alternative = model$1.Rule = model$1.NonTerminal = model$1.AbstractProduction = void 0; -var map_1$3 = __importDefault$9(map_1$4); -var forEach_1$3 = __importDefault$9(forEach_1$4); -var isString_1 = __importDefault$9(isString_1$1); -var isRegExp_1 = __importDefault$9(isRegExp_1$1); -var pickBy_1 = __importDefault$9(pickBy_1$1); -var assign_1$2 = __importDefault$9(assign_1$3); -// TODO: duplicated code to avoid extracting another sub-package -- how to avoid? -function tokenLabel(tokType) { - if (hasTokenLabel(tokType)) { - return tokType.LABEL; - } - else { - return tokType.name; - } -} -// TODO: duplicated code to avoid extracting another sub-package -- how to avoid? -function hasTokenLabel(obj) { - return (0, isString_1.default)(obj.LABEL) && obj.LABEL !== ""; -} -var AbstractProduction = /** @class */ (function () { - function AbstractProduction(_definition) { - this._definition = _definition; - } - Object.defineProperty(AbstractProduction.prototype, "definition", { - get: function () { - return this._definition; - }, - set: function (value) { - this._definition = value; - }, - enumerable: false, - configurable: true - }); - AbstractProduction.prototype.accept = function (visitor) { - visitor.visit(this); - (0, forEach_1$3.default)(this.definition, function (prod) { - prod.accept(visitor); - }); - }; - return AbstractProduction; -}()); -model$1.AbstractProduction = AbstractProduction; -var NonTerminal = /** @class */ (function (_super) { - __extends$4(NonTerminal, _super); - function NonTerminal(options) { - var _this = _super.call(this, []) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - Object.defineProperty(NonTerminal.prototype, "definition", { - get: function () { - if (this.referencedRule !== undefined) { - return this.referencedRule.definition; - } - return []; - }, - set: function (definition) { - // immutable - }, - enumerable: false, - configurable: true - }); - NonTerminal.prototype.accept = function (visitor) { - visitor.visit(this); - // don't visit children of a reference, we will get cyclic infinite loops if we do so - }; - return NonTerminal; -}(AbstractProduction)); -model$1.NonTerminal = NonTerminal; -var Rule = /** @class */ (function (_super) { - __extends$4(Rule, _super); - function Rule(options) { - var _this = _super.call(this, options.definition) || this; - _this.orgText = ""; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return Rule; -}(AbstractProduction)); -model$1.Rule = Rule; -var Alternative = /** @class */ (function (_super) { - __extends$4(Alternative, _super); - function Alternative(options) { - var _this = _super.call(this, options.definition) || this; - _this.ignoreAmbiguities = false; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return Alternative; -}(AbstractProduction)); -model$1.Alternative = Alternative; -var Option = /** @class */ (function (_super) { - __extends$4(Option, _super); - function Option(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return Option; -}(AbstractProduction)); -model$1.Option = Option; -var RepetitionMandatory = /** @class */ (function (_super) { - __extends$4(RepetitionMandatory, _super); - function RepetitionMandatory(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionMandatory; -}(AbstractProduction)); -model$1.RepetitionMandatory = RepetitionMandatory; -var RepetitionMandatoryWithSeparator = /** @class */ (function (_super) { - __extends$4(RepetitionMandatoryWithSeparator, _super); - function RepetitionMandatoryWithSeparator(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionMandatoryWithSeparator; -}(AbstractProduction)); -model$1.RepetitionMandatoryWithSeparator = RepetitionMandatoryWithSeparator; -var Repetition = /** @class */ (function (_super) { - __extends$4(Repetition, _super); - function Repetition(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return Repetition; -}(AbstractProduction)); -model$1.Repetition = Repetition; -var RepetitionWithSeparator = /** @class */ (function (_super) { - __extends$4(RepetitionWithSeparator, _super); - function RepetitionWithSeparator(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionWithSeparator; -}(AbstractProduction)); -model$1.RepetitionWithSeparator = RepetitionWithSeparator; -var Alternation = /** @class */ (function (_super) { - __extends$4(Alternation, _super); - function Alternation(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - _this.ignoreAmbiguities = false; - _this.hasPredicates = false; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - Object.defineProperty(Alternation.prototype, "definition", { - get: function () { - return this._definition; - }, - set: function (value) { - this._definition = value; - }, - enumerable: false, - configurable: true - }); - return Alternation; -}(AbstractProduction)); -model$1.Alternation = Alternation; -var Terminal = /** @class */ (function () { - function Terminal(options) { - this.idx = 1; - (0, assign_1$2.default)(this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - } - Terminal.prototype.accept = function (visitor) { - visitor.visit(this); - }; - return Terminal; -}()); -model$1.Terminal = Terminal; -function serializeGrammar(topRules) { - return (0, map_1$3.default)(topRules, serializeProduction); -} -model$1.serializeGrammar = serializeGrammar; -function serializeProduction(node) { - function convertDefinition(definition) { - return (0, map_1$3.default)(definition, serializeProduction); - } - /* istanbul ignore else */ - if (node instanceof NonTerminal) { - var serializedNonTerminal = { - type: "NonTerminal", - name: node.nonTerminalName, - idx: node.idx - }; - if ((0, isString_1.default)(node.label)) { - serializedNonTerminal.label = node.label; - } - return serializedNonTerminal; - } - else if (node instanceof Alternative) { - return { - type: "Alternative", - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Option) { - return { - type: "Option", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof RepetitionMandatory) { - return { - type: "RepetitionMandatory", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof RepetitionMandatoryWithSeparator) { - return { - type: "RepetitionMandatoryWithSeparator", - idx: node.idx, - separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof RepetitionWithSeparator) { - return { - type: "RepetitionWithSeparator", - idx: node.idx, - separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Repetition) { - return { - type: "Repetition", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Alternation) { - return { - type: "Alternation", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Terminal) { - var serializedTerminal = { - type: "Terminal", - name: node.terminalType.name, - label: tokenLabel(node.terminalType), - idx: node.idx - }; - if ((0, isString_1.default)(node.label)) { - serializedTerminal.terminalLabel = node.label; - } - var pattern = node.terminalType.PATTERN; - if (node.terminalType.PATTERN) { - serializedTerminal.pattern = (0, isRegExp_1.default)(pattern) - ? pattern.source - : pattern; - } - return serializedTerminal; - } - else if (node instanceof Rule) { - return { - type: "Rule", - name: node.name, - orgText: node.orgText, - definition: convertDefinition(node.definition) - }; - } - else { - throw Error("non exhaustive match"); - } -} -model$1.serializeProduction = serializeProduction; + case ClassComponent: + // Capture and retry + var errorInfo = value; + var ctor = workInProgress.type; + var instance = workInProgress.stateNode; -var visitor = {}; + if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) { + workInProgress.flags |= ShouldCapture; -Object.defineProperty(visitor, "__esModule", { value: true }); -visitor.GAstVisitor = void 0; -var model_1$2 = model$1; -var GAstVisitor = /** @class */ (function () { - function GAstVisitor() { - } - GAstVisitor.prototype.visit = function (node) { - var nodeAny = node; - switch (nodeAny.constructor) { - case model_1$2.NonTerminal: - return this.visitNonTerminal(nodeAny); - case model_1$2.Alternative: - return this.visitAlternative(nodeAny); - case model_1$2.Option: - return this.visitOption(nodeAny); - case model_1$2.RepetitionMandatory: - return this.visitRepetitionMandatory(nodeAny); - case model_1$2.RepetitionMandatoryWithSeparator: - return this.visitRepetitionMandatoryWithSeparator(nodeAny); - case model_1$2.RepetitionWithSeparator: - return this.visitRepetitionWithSeparator(nodeAny); - case model_1$2.Repetition: - return this.visitRepetition(nodeAny); - case model_1$2.Alternation: - return this.visitAlternation(nodeAny); - case model_1$2.Terminal: - return this.visitTerminal(nodeAny); - case model_1$2.Rule: - return this.visitRule(nodeAny); - /* istanbul ignore next */ - default: - throw Error("non exhaustive match"); - } - }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitNonTerminal = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitAlternative = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitOption = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRepetition = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRepetitionMandatory = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitAlternation = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitTerminal = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRule = function (node) { }; - return GAstVisitor; -}()); -visitor.GAstVisitor = GAstVisitor; + var _lane = pickArbitraryLane(rootRenderLanes); -var helpers = {}; + workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state -var baseEach$4 = _baseEach; + var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane); -/** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ -function baseSome$1(collection, predicate) { - var result; + enqueueCapturedUpdate(workInProgress, _update); + return; + } - baseEach$4(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; -} + break; + } -var _baseSome = baseSome$1; + workInProgress = workInProgress.return; + } while (workInProgress !== null); + } -var arraySome = _arraySome, - baseIteratee$7 = _baseIteratee, - baseSome = _baseSome, - isArray$8 = isArray_1$1, - isIterateeCall$2 = _isIterateeCall; + function getSuspendedCache() { + { + return null; + } // This function is called when a Suspense boundary suspends. It returns the + } -/** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ -function some(collection, predicate, guard) { - var func = isArray$8(collection) ? arraySome : baseSome; - if (guard && isIterateeCall$2(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, baseIteratee$7(predicate)); -} + function markUpdate(workInProgress) { + // Tag the fiber with an update effect. This turns a Placement into + // a PlacementAndUpdate. + workInProgress.flags |= Update; + } -var some_1$2 = some; + function markRef(workInProgress) { + workInProgress.flags |= Ref; -/** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ + { + workInProgress.flags |= RefStatic; + } + } -function arrayEvery$1(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; + function hadNoMutationsEffects(current, completedWork) { + var didBailout = current !== null && current.child === completedWork.child; - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; -} + if (didBailout) { + return true; + } -var _arrayEvery = arrayEvery$1; + if ((completedWork.flags & ChildDeletion) !== NoFlags) { + return false; + } // TODO: If we move the `hadNoMutationsEffects` call after `bubbleProperties` + // then we only have to check the `completedWork.subtreeFlags`. -var baseEach$3 = _baseEach; -/** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ -function baseEvery$1(collection, predicate) { - var result = true; - baseEach$3(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; -} + var child = completedWork.child; -var _baseEvery = baseEvery$1; + while (child !== null) { + if ((child.flags & MutationMask) !== NoFlags || (child.subtreeFlags & MutationMask) !== NoFlags) { + return false; + } -var arrayEvery = _arrayEvery, - baseEvery = _baseEvery, - baseIteratee$6 = _baseIteratee, - isArray$7 = isArray_1$1, - isIterateeCall$1 = _isIterateeCall; + child = child.sibling; + } -/** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false - */ -function every(collection, predicate, guard) { - var func = isArray$7(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall$1(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, baseIteratee$6(predicate)); -} + return true; + } -var every_1$1 = every; + var appendAllChildren; + var updateHostContainer; + var updateHostComponent; + var updateHostText; -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ + if (supportsMutation) { + // Mutation mode + appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { + // We only have the top Fiber that was created but we need recurse down its + // children to find all the terminal nodes. + var node = workInProgress.child; -function baseFindIndex$3(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); + while (node !== null) { + if (node.tag === HostComponent || node.tag === HostText) { + appendInitialChild(parent, node.stateNode); + } else if (node.tag === HostPortal) ; else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} + if (node === workInProgress) { + return; + } -var _baseFindIndex = baseFindIndex$3; + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress) { + return; + } -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ + node = node.return; + } -function baseIsNaN$2(value) { - return value !== value; -} + node.sibling.return = node.return; + node = node.sibling; + } + }; -var _baseIsNaN = baseIsNaN$2; + updateHostContainer = function (current, workInProgress) {// Noop + }; -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ + updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) { + // If we have an alternate, that means this is an update and we need to + // schedule a side-effect to do the updates. + var oldProps = current.memoizedProps; -function strictIndexOf$1(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; + if (oldProps === newProps) { + // In mutation mode, this is sufficient for a bailout because + // we won't touch this node even if children changed. + return; + } // If we get updated because one of our children updated, we don't + // have newProps so we'll have to reuse them. + // TODO: Split the update API as separate for the props vs. children. + // Even better would be if children weren't special cased at all tho. - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} -var _strictIndexOf = strictIndexOf$1; + var instance = workInProgress.stateNode; + var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host + // component is hitting the resume path. Figure out why. Possibly + // related to `hidden`. -var baseFindIndex$2 = _baseFindIndex, - baseIsNaN$1 = _baseIsNaN, - strictIndexOf = _strictIndexOf; + var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component. -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf$4(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex$2(array, baseIsNaN$1, fromIndex); -} + workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there + // is a new ref we mark this as an update. All the work is done in commitWork. -var _baseIndexOf = baseIndexOf$4; + if (updatePayload) { + markUpdate(workInProgress); + } + }; -var baseIndexOf$3 = _baseIndexOf, - isArrayLike$4 = isArrayLike_1, - isString = isString_1$1, - toInteger$3 = toInteger_1, - values = values_1$1; + updateHostText = function (current, workInProgress, oldText, newText) { + // If the text differs, mark it as an update. All the work in done in commitWork. + if (oldText !== newText) { + markUpdate(workInProgress); + } + }; + } else if (supportsPersistence) { + // Persistent host tree mode + appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { + // We only have the top Fiber that was created but we need recurse down its + // children to find all the terminal nodes. + var node = workInProgress.child; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax$4 = Math.max; + while (node !== null) { + // eslint-disable-next-line no-labels + if (node.tag === HostComponent) { + var instance = node.stateNode; -/** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ -function includes(collection, value, fromIndex, guard) { - collection = isArrayLike$4(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger$3(fromIndex) : 0; + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. + var props = node.memoizedProps; + var type = node.type; + instance = cloneHiddenInstance(instance, type, props, node); + } - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax$4(length + fromIndex, 0); - } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf$3(collection, value, fromIndex) > -1); -} + appendInitialChild(parent, instance); + } else if (node.tag === HostText) { + var _instance = node.stateNode; -var includes_1$2 = includes; + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. + var text = node.memoizedProps; + _instance = cloneHiddenTextInstance(_instance, text, node); + } -var __importDefault$8 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(helpers, "__esModule", { value: true }); -helpers.getProductionDslName = helpers.isBranchingProd = helpers.isOptionalProd = helpers.isSequenceProd = void 0; -var some_1$1 = __importDefault$8(some_1$2); -var every_1 = __importDefault$8(every_1$1); -var includes_1$1 = __importDefault$8(includes_1$2); -var model_1$1 = model$1; -function isSequenceProd(prod) { - return (prod instanceof model_1$1.Alternative || - prod instanceof model_1$1.Option || - prod instanceof model_1$1.Repetition || - prod instanceof model_1$1.RepetitionMandatory || - prod instanceof model_1$1.RepetitionMandatoryWithSeparator || - prod instanceof model_1$1.RepetitionWithSeparator || - prod instanceof model_1$1.Terminal || - prod instanceof model_1$1.Rule); -} -helpers.isSequenceProd = isSequenceProd; -function isOptionalProd(prod, alreadyVisited) { - if (alreadyVisited === void 0) { alreadyVisited = []; } - var isDirectlyOptional = prod instanceof model_1$1.Option || - prod instanceof model_1$1.Repetition || - prod instanceof model_1$1.RepetitionWithSeparator; - if (isDirectlyOptional) { - return true; - } - // note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another - // empty optional top rule - // may be indirectly optional ((A?B?C?) | (D?E?F?)) - if (prod instanceof model_1$1.Alternation) { - // for OR its enough for just one of the alternatives to be optional - return (0, some_1$1.default)(prod.definition, function (subProd) { - return isOptionalProd(subProd, alreadyVisited); - }); - } - else if (prod instanceof model_1$1.NonTerminal && (0, includes_1$1.default)(alreadyVisited, prod)) { - // avoiding stack overflow due to infinite recursion - return false; - } - else if (prod instanceof model_1$1.AbstractProduction) { - if (prod instanceof model_1$1.NonTerminal) { - alreadyVisited.push(prod); - } - return (0, every_1.default)(prod.definition, function (subProd) { - return isOptionalProd(subProd, alreadyVisited); - }); - } - else { - return false; - } -} -helpers.isOptionalProd = isOptionalProd; -function isBranchingProd(prod) { - return prod instanceof model_1$1.Alternation; -} -helpers.isBranchingProd = isBranchingProd; -function getProductionDslName(prod) { - /* istanbul ignore else */ - if (prod instanceof model_1$1.NonTerminal) { - return "SUBRULE"; - } - else if (prod instanceof model_1$1.Option) { - return "OPTION"; - } - else if (prod instanceof model_1$1.Alternation) { - return "OR"; - } - else if (prod instanceof model_1$1.RepetitionMandatory) { - return "AT_LEAST_ONE"; - } - else if (prod instanceof model_1$1.RepetitionMandatoryWithSeparator) { - return "AT_LEAST_ONE_SEP"; - } - else if (prod instanceof model_1$1.RepetitionWithSeparator) { - return "MANY_SEP"; - } - else if (prod instanceof model_1$1.Repetition) { - return "MANY"; - } - else if (prod instanceof model_1$1.Terminal) { - return "CONSUME"; - } - else { - throw Error("non exhaustive match"); - } -} -helpers.getProductionDslName = getProductionDslName; - -(function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isSequenceProd = exports.isBranchingProd = exports.isOptionalProd = exports.getProductionDslName = exports.GAstVisitor = exports.serializeProduction = exports.serializeGrammar = exports.Alternative = exports.Alternation = exports.RepetitionWithSeparator = exports.RepetitionMandatoryWithSeparator = exports.RepetitionMandatory = exports.Repetition = exports.Option = exports.NonTerminal = exports.Terminal = exports.Rule = void 0; - var model_1 = model$1; - Object.defineProperty(exports, "Rule", { enumerable: true, get: function () { return model_1.Rule; } }); - Object.defineProperty(exports, "Terminal", { enumerable: true, get: function () { return model_1.Terminal; } }); - Object.defineProperty(exports, "NonTerminal", { enumerable: true, get: function () { return model_1.NonTerminal; } }); - Object.defineProperty(exports, "Option", { enumerable: true, get: function () { return model_1.Option; } }); - Object.defineProperty(exports, "Repetition", { enumerable: true, get: function () { return model_1.Repetition; } }); - Object.defineProperty(exports, "RepetitionMandatory", { enumerable: true, get: function () { return model_1.RepetitionMandatory; } }); - Object.defineProperty(exports, "RepetitionMandatoryWithSeparator", { enumerable: true, get: function () { return model_1.RepetitionMandatoryWithSeparator; } }); - Object.defineProperty(exports, "RepetitionWithSeparator", { enumerable: true, get: function () { return model_1.RepetitionWithSeparator; } }); - Object.defineProperty(exports, "Alternation", { enumerable: true, get: function () { return model_1.Alternation; } }); - Object.defineProperty(exports, "Alternative", { enumerable: true, get: function () { return model_1.Alternative; } }); - Object.defineProperty(exports, "serializeGrammar", { enumerable: true, get: function () { return model_1.serializeGrammar; } }); - Object.defineProperty(exports, "serializeProduction", { enumerable: true, get: function () { return model_1.serializeProduction; } }); - var visitor_1 = visitor; - Object.defineProperty(exports, "GAstVisitor", { enumerable: true, get: function () { return visitor_1.GAstVisitor; } }); - var helpers_1 = helpers; - Object.defineProperty(exports, "getProductionDslName", { enumerable: true, get: function () { return helpers_1.getProductionDslName; } }); - Object.defineProperty(exports, "isOptionalProd", { enumerable: true, get: function () { return helpers_1.isOptionalProd; } }); - Object.defineProperty(exports, "isBranchingProd", { enumerable: true, get: function () { return helpers_1.isBranchingProd; } }); - Object.defineProperty(exports, "isSequenceProd", { enumerable: true, get: function () { return helpers_1.isSequenceProd; } }); - -} (api$1)); - -var __importDefault$7 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(rest, "__esModule", { value: true }); -rest.RestWalker = void 0; -var drop_1$1 = __importDefault$7(drop_1$2); -var forEach_1$2 = __importDefault$7(forEach_1$4); -var gast_1$4 = api$1; -/** - * A Grammar Walker that computes the "remaining" grammar "after" a productions in the grammar. - */ -var RestWalker = /** @class */ (function () { - function RestWalker() { - } - RestWalker.prototype.walk = function (prod, prevRest) { - var _this = this; - if (prevRest === void 0) { prevRest = []; } - (0, forEach_1$2.default)(prod.definition, function (subProd, index) { - var currRest = (0, drop_1$1.default)(prod.definition, index + 1); - /* istanbul ignore else */ - if (subProd instanceof gast_1$4.NonTerminal) { - _this.walkProdRef(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Terminal) { - _this.walkTerminal(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Alternative) { - _this.walkFlat(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Option) { - _this.walkOption(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.RepetitionMandatory) { - _this.walkAtLeastOne(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.RepetitionMandatoryWithSeparator) { - _this.walkAtLeastOneSep(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.RepetitionWithSeparator) { - _this.walkManySep(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Repetition) { - _this.walkMany(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Alternation) { - _this.walkOr(subProd, currRest, prevRest); - } - else { - throw Error("non exhaustive match"); - } - }); - }; - RestWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { }; - RestWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { }; - RestWalker.prototype.walkFlat = function (flatProd, currRest, prevRest) { - // ABCDEF => after the D the rest is EF - var fullOrRest = currRest.concat(prevRest); - this.walk(flatProd, fullOrRest); - }; - RestWalker.prototype.walkOption = function (optionProd, currRest, prevRest) { - // ABC(DE)?F => after the (DE)? the rest is F - var fullOrRest = currRest.concat(prevRest); - this.walk(optionProd, fullOrRest); - }; - RestWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { - // ABC(DE)+F => after the (DE)+ the rest is (DE)?F - var fullAtLeastOneRest = [ - new gast_1$4.Option({ definition: atLeastOneProd.definition }) - ].concat(currRest, prevRest); - this.walk(atLeastOneProd, fullAtLeastOneRest); - }; - RestWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) { - // ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F - var fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest); - this.walk(atLeastOneSepProd, fullAtLeastOneSepRest); - }; - RestWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { - // ABC(DE)*F => after the (DE)* the rest is (DE)?F - var fullManyRest = [ - new gast_1$4.Option({ definition: manyProd.definition }) - ].concat(currRest, prevRest); - this.walk(manyProd, fullManyRest); - }; - RestWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { - // ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F - var fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest); - this.walk(manySepProd, fullManySepRest); - }; - RestWalker.prototype.walkOr = function (orProd, currRest, prevRest) { - var _this = this; - // ABC(D|E|F)G => when finding the (D|E|F) the rest is G - var fullOrRest = currRest.concat(prevRest); - // walk all different alternatives - (0, forEach_1$2.default)(orProd.definition, function (alt) { - // wrapping each alternative in a single definition wrapper - // to avoid errors in computing the rest of that alternative in the invocation to computeInProdFollows - // (otherwise for OR([alt1,alt2]) alt2 will be considered in 'rest' of alt1 - var prodWrapper = new gast_1$4.Alternative({ definition: [alt] }); - _this.walk(prodWrapper, fullOrRest); - }); - }; - return RestWalker; -}()); -rest.RestWalker = RestWalker; -function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) { - var repSepRest = [ - new gast_1$4.Option({ - definition: [ - new gast_1$4.Terminal({ terminalType: repSepProd.separator }) - ].concat(repSepProd.definition) - }) - ]; - var fullRepSepRest = repSepRest.concat(currRest, prevRest); - return fullRepSepRest; -} + appendInitialChild(parent, _instance); + } else if (node.tag === HostPortal) ; else if (node.tag === OffscreenComponent && node.memoizedState !== null) { + // The children in this boundary are hidden. Toggle their visibility + // before appending. + var child = node.child; -var first$2 = {}; + if (child !== null) { + child.return = node; + } -var Symbol$3 = _Symbol, - isArguments$2 = isArguments_1, - isArray$6 = isArray_1$1; + { + appendAllChildren(parent, node, true, true); + } + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } // $FlowFixMe This is correct but Flow is confused by the labeled break. -/** Built-in value references. */ -var spreadableSymbol$2 = Symbol$3 ? Symbol$3.isConcatSpreadable : undefined; -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable$3(value) { - return isArray$6(value) || isArguments$2(value) || - !!(spreadableSymbol$2 && value && value[spreadableSymbol$2]); -} + node = node; -var _isFlattenable = isFlattenable$3; + if (node === workInProgress) { + return; + } -var arrayPush$2 = _arrayPush, - isFlattenable$2 = _isFlattenable; + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress) { + return; + } -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten$5(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; + node = node.return; + } - predicate || (predicate = isFlattenable$2); - result || (result = []); + node.sibling.return = node.return; + node = node.sibling; + } + }; // An unfortunate fork of appendAllChildren because we have two different parent types. - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten$5(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush$2(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; -} -var _baseFlatten = baseFlatten$5; + var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) { + // We only have the top Fiber that was created but we need recurse down its + // children to find all the terminal nodes. + var node = workInProgress.child; -var baseFlatten$4 = _baseFlatten; + while (node !== null) { + // eslint-disable-next-line no-labels + if (node.tag === HostComponent) { + var instance = node.stateNode; -/** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ -function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten$4(array, 1) : []; -} + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. + var props = node.memoizedProps; + var type = node.type; + instance = cloneHiddenInstance(instance, type, props, node); + } -var flatten_1$3 = flatten; + appendChildToContainerChildSet(containerChildSet, instance); + } else if (node.tag === HostText) { + var _instance2 = node.stateNode; -var baseIndexOf$2 = _baseIndexOf; + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. + var text = node.memoizedProps; + _instance2 = cloneHiddenTextInstance(_instance2, text, node); + } -/** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludes$3(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf$2(array, value, 0) > -1; -} + appendChildToContainerChildSet(containerChildSet, _instance2); + } else if (node.tag === HostPortal) ; else if (node.tag === OffscreenComponent && node.memoizedState !== null) { + // The children in this boundary are hidden. Toggle their visibility + // before appending. + var child = node.child; -var _arrayIncludes = arrayIncludes$3; + if (child !== null) { + child.return = node; + } -/** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ + { + appendAllChildrenToContainer(containerChildSet, node, true, true); + } + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } // $FlowFixMe This is correct but Flow is confused by the labeled break. -function arrayIncludesWith$3(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; -} + node = node; -var _arrayIncludesWith = arrayIncludesWith$3; + if (node === workInProgress) { + return; + } -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress) { + return; + } -function noop$1() { - // No operation performed. -} + node = node.return; + } -var noop_1 = noop$1; + node.sibling.return = node.return; + node = node.sibling; + } + }; -var Set$1 = _Set, - noop = noop_1, - setToArray$1 = _setToArray; + updateHostContainer = function (current, workInProgress) { + var portalOrRoot = workInProgress.stateNode; + var childrenUnchanged = hadNoMutationsEffects(current, workInProgress); -/** Used as references for various `Number` constants. */ -var INFINITY$2 = 1 / 0; + if (childrenUnchanged) ; else { + var container = portalOrRoot.containerInfo; + var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set. -/** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ -var createSet$1 = !(Set$1 && (1 / setToArray$1(new Set$1([,-0]))[1]) == INFINITY$2) ? noop : function(values) { - return new Set$1(values); -}; + appendAllChildrenToContainer(newChildSet, workInProgress, false, false); + portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container. -var _createSet = createSet$1; + markUpdate(workInProgress); + finalizeContainerChildren(container, newChildSet); + } + }; -var SetCache$2 = _SetCache, - arrayIncludes$2 = _arrayIncludes, - arrayIncludesWith$2 = _arrayIncludesWith, - cacheHas$2 = _cacheHas, - createSet = _createSet, - setToArray = _setToArray; + updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) { + var currentInstance = current.stateNode; + var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates. + // This guarantees that we can reuse all of them. -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE$2 = 200; + var childrenUnchanged = hadNoMutationsEffects(current, workInProgress); -/** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ -function baseUniq$1(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes$2, - length = array.length, - isCommon = true, - result = [], - seen = result; + if (childrenUnchanged && oldProps === newProps) { + // No changes, just reuse the existing instance. + // Note that this might release a previous clone. + workInProgress.stateNode = currentInstance; + return; + } - if (comparator) { - isCommon = false; - includes = arrayIncludesWith$2; - } - else if (length >= LARGE_ARRAY_SIZE$2) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas$2; - seen = new SetCache$2; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + var recyclableInstance = workInProgress.stateNode; + var currentHostContext = getHostContext(); + var updatePayload = null; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; -} + if (oldProps !== newProps) { + updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext); + } -var _baseUniq = baseUniq$1; + if (childrenUnchanged && updatePayload === null) { + // No changes, just reuse the existing instance. + // Note that this might release a previous clone. + workInProgress.stateNode = currentInstance; + return; + } -var baseUniq = _baseUniq; + var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance); -/** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ -function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; -} + if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) { + markUpdate(workInProgress); + } -var uniq_1$2 = uniq; + workInProgress.stateNode = newInstance; -var __importDefault$6 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(first$2, "__esModule", { value: true }); -first$2.firstForTerminal = first$2.firstForBranching = first$2.firstForSequence = first$2.first = void 0; -var flatten_1$2 = __importDefault$6(flatten_1$3); -var uniq_1$1 = __importDefault$6(uniq_1$2); -var map_1$2 = __importDefault$6(map_1$4); -var gast_1$3 = api$1; -var gast_2 = api$1; -function first$1(prod) { - /* istanbul ignore else */ - if (prod instanceof gast_1$3.NonTerminal) { - // this could in theory cause infinite loops if - // (1) prod A refs prod B. - // (2) prod B refs prod A - // (3) AB can match the empty set - // in other words a cycle where everything is optional so the first will keep - // looking ahead for the next optional part and will never exit - // currently there is no safeguard for this unique edge case because - // (1) not sure a grammar in which this can happen is useful for anything (productive) - return first$1(prod.referencedRule); - } - else if (prod instanceof gast_1$3.Terminal) { - return firstForTerminal(prod); - } - else if ((0, gast_2.isSequenceProd)(prod)) { - return firstForSequence(prod); - } - else if ((0, gast_2.isBranchingProd)(prod)) { - return firstForBranching(prod); - } - else { - throw Error("non exhaustive match"); - } -} -first$2.first = first$1; -function firstForSequence(prod) { - var firstSet = []; - var seq = prod.definition; - var nextSubProdIdx = 0; - var hasInnerProdsRemaining = seq.length > nextSubProdIdx; - var currSubProd; - // so we enter the loop at least once (if the definition is not empty - var isLastInnerProdOptional = true; - // scan a sequence until it's end or until we have found a NONE optional production in it - while (hasInnerProdsRemaining && isLastInnerProdOptional) { - currSubProd = seq[nextSubProdIdx]; - isLastInnerProdOptional = (0, gast_2.isOptionalProd)(currSubProd); - firstSet = firstSet.concat(first$1(currSubProd)); - nextSubProdIdx = nextSubProdIdx + 1; - hasInnerProdsRemaining = seq.length > nextSubProdIdx; - } - return (0, uniq_1$1.default)(firstSet); -} -first$2.firstForSequence = firstForSequence; -function firstForBranching(prod) { - var allAlternativesFirsts = (0, map_1$2.default)(prod.definition, function (innerProd) { - return first$1(innerProd); - }); - return (0, uniq_1$1.default)((0, flatten_1$2.default)(allAlternativesFirsts)); -} -first$2.firstForBranching = firstForBranching; -function firstForTerminal(terminal) { - return [terminal.terminalType]; -} -first$2.firstForTerminal = firstForTerminal; + if (childrenUnchanged) { + // If there are no other effects in this tree, we need to flag this node as having one. + // Even though we're not going to use it for anything. + // Otherwise parents won't know that there are new children to propagate upwards. + markUpdate(workInProgress); + } else { + // If children might have changed, we have to add them all to the set. + appendAllChildren(newInstance, workInProgress, false, false); + } + }; -var constants = {}; + updateHostText = function (current, workInProgress, oldText, newText) { + if (oldText !== newText) { + // If the text content differs, we'll create a new text instance for it. + var rootContainerInstance = getRootHostContainer(); + var currentHostContext = getHostContext(); + workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress); // We'll have to mark it as having an effect, even though we won't use the effect for anything. + // This lets the parents know that at least one of their children has changed. -Object.defineProperty(constants, "__esModule", { value: true }); -constants.IN = void 0; -// TODO: can this be removed? where is it used? -constants.IN = "_~IN~_"; + markUpdate(workInProgress); + } else { + workInProgress.stateNode = current.stateNode; + } + }; + } else { + // No host operations + updateHostContainer = function (current, workInProgress) {// Noop + }; -var __extends$3 = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$5 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(follow, "__esModule", { value: true }); -follow.buildInProdFollowPrefix = follow.buildBetweenProdsFollowPrefix = follow.computeAllProdsFollows = follow.ResyncFollowsWalker = void 0; -var rest_1$1 = rest; -var first_1$2 = first$2; -var forEach_1$1 = __importDefault$5(forEach_1$4); -var assign_1$1 = __importDefault$5(assign_1$3); -var constants_1 = constants; -var gast_1$2 = api$1; -// This ResyncFollowsWalker computes all of the follows required for RESYNC -// (skipping reference production). -var ResyncFollowsWalker = /** @class */ (function (_super) { - __extends$3(ResyncFollowsWalker, _super); - function ResyncFollowsWalker(topProd) { - var _this = _super.call(this) || this; - _this.topProd = topProd; - _this.follows = {}; - return _this; - } - ResyncFollowsWalker.prototype.startWalking = function () { - this.walk(this.topProd); - return this.follows; - }; - ResyncFollowsWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { - // do nothing! just like in the public sector after 13:00 - }; - ResyncFollowsWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { - var followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) + - this.topProd.name; - var fullRest = currRest.concat(prevRest); - var restProd = new gast_1$2.Alternative({ definition: fullRest }); - var t_in_topProd_follows = (0, first_1$2.first)(restProd); - this.follows[followName] = t_in_topProd_follows; - }; - return ResyncFollowsWalker; -}(rest_1$1.RestWalker)); -follow.ResyncFollowsWalker = ResyncFollowsWalker; -function computeAllProdsFollows(topProductions) { - var reSyncFollows = {}; - (0, forEach_1$1.default)(topProductions, function (topProd) { - var currRefsFollow = new ResyncFollowsWalker(topProd).startWalking(); - (0, assign_1$1.default)(reSyncFollows, currRefsFollow); - }); - return reSyncFollows; -} -follow.computeAllProdsFollows = computeAllProdsFollows; -function buildBetweenProdsFollowPrefix(inner, occurenceInParent) { - return inner.name + occurenceInParent + constants_1.IN; -} -follow.buildBetweenProdsFollowPrefix = buildBetweenProdsFollowPrefix; -function buildInProdFollowPrefix(terminal) { - var terminalName = terminal.terminalType.name; - return terminalName + terminal.idx + constants_1.IN; -} -follow.buildInProdFollowPrefix = buildInProdFollowPrefix; + updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) {// Noop + }; -var tokens_public = {}; + updateHostText = function (current, workInProgress, oldText, newText) {// Noop + }; + } -/** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ + function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { + if (getIsHydrating()) { + // If we're hydrating, we should consume as many items as we can + // so we don't leave any behind. + return; + } -function isUndefined(value) { - return value === undefined; -} + switch (renderState.tailMode) { + case 'hidden': + { + // Any insertions at the end of the tail list after this point + // should be invisible. If there are already mounted boundaries + // anything before them are not considered for collapsing. + // Therefore we need to go through the whole tail to find if + // there are any. + var tailNode = renderState.tail; + var lastTailNode = null; -var isUndefined_1$1 = isUndefined; + while (tailNode !== null) { + if (tailNode.alternate !== null) { + lastTailNode = tailNode; + } -var lexer_public = {}; + tailNode = tailNode.sibling; + } // Next we're simply going to delete all insertions after the + // last rendered item. -var lexer = {}; -var regexpToAst = {exports: {}}; + if (lastTailNode === null) { + // All remaining items in the tail are insertions. + renderState.tail = null; + } else { + // Detach the insertion after the last node that was already + // inserted. + lastTailNode.sibling = null; + } -(function (module) { -(function(root, factory) { - // istanbul ignore next - if (module.exports) { - module.exports = factory(); - } else { - // istanbul ignore next - root.regexpToAst = factory(); - } - })( - typeof self !== "undefined" - ? // istanbul ignore next - self - : commonjsGlobal, - function() { - // references - // https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983 - // https://www.ecma-international.org/ecma-262/8.0/index.html#prod-Pattern - function RegExpParser() {} - - RegExpParser.prototype.saveState = function() { - return { - idx: this.idx, - input: this.input, - groupIdx: this.groupIdx - } - }; + break; + } - RegExpParser.prototype.restoreState = function(newState) { - this.idx = newState.idx; - this.input = newState.input; - this.groupIdx = newState.groupIdx; - }; + case 'collapsed': + { + // Any insertions at the end of the tail list after this point + // should be invisible. If there are already mounted boundaries + // anything before them are not considered for collapsing. + // Therefore we need to go through the whole tail to find if + // there are any. + var _tailNode = renderState.tail; + var _lastTailNode = null; - RegExpParser.prototype.pattern = function(input) { - // parser state - this.idx = 0; - this.input = input; - this.groupIdx = 0; - - this.consumeChar("/"); - var value = this.disjunction(); - this.consumeChar("/"); - - var flags = { - type: "Flags", - loc: { begin: this.idx, end: input.length }, - global: false, - ignoreCase: false, - multiLine: false, - unicode: false, - sticky: false - }; + while (_tailNode !== null) { + if (_tailNode.alternate !== null) { + _lastTailNode = _tailNode; + } - while (this.isRegExpFlag()) { - switch (this.popChar()) { - case "g": - addFlag(flags, "global"); - break - case "i": - addFlag(flags, "ignoreCase"); - break - case "m": - addFlag(flags, "multiLine"); - break - case "u": - addFlag(flags, "unicode"); - break - case "y": - addFlag(flags, "sticky"); - break - } - } + _tailNode = _tailNode.sibling; + } // Next we're simply going to delete all insertions after the + // last rendered item. - if (this.idx !== this.input.length) { - throw Error( - "Redundant input: " + this.input.substring(this.idx) - ) - } - return { - type: "Pattern", - flags: flags, - value: value, - loc: this.loc(0) - } - }; - RegExpParser.prototype.disjunction = function() { - var alts = []; - var begin = this.idx; + if (_lastTailNode === null) { + // All remaining items in the tail are insertions. + if (!hasRenderedATailFallback && renderState.tail !== null) { + // We suspended during the head. We want to show at least one + // row at the tail. So we'll keep on and cut off the rest. + renderState.tail.sibling = null; + } else { + renderState.tail = null; + } + } else { + // Detach the insertion after the last node that was already + // inserted. + _lastTailNode.sibling = null; + } - alts.push(this.alternative()); + break; + } + } + } - while (this.peekChar() === "|") { - this.consumeChar("|"); - alts.push(this.alternative()); - } + function bubbleProperties(completedWork) { + var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child; + var newChildLanes = NoLanes; + var subtreeFlags = NoFlags; - return { type: "Disjunction", value: alts, loc: this.loc(begin) } - }; + if (!didBailout) { + // Bubble up the earliest expiration time. + if ( (completedWork.mode & ProfileMode) !== NoMode) { + // In profiling mode, resetChildExpirationTime is also used to reset + // profiler durations. + var actualDuration = completedWork.actualDuration; + var treeBaseDuration = completedWork.selfBaseDuration; + var child = completedWork.child; - RegExpParser.prototype.alternative = function() { - var terms = []; - var begin = this.idx; + while (child !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes)); + subtreeFlags |= child.subtreeFlags; + subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will + // only be updated if work is done on the fiber (i.e. it doesn't bailout). + // When work is done, it should bubble to the parent's actualDuration. If + // the fiber has not been cloned though, (meaning no work was done), then + // this value will reflect the amount of time spent working on a previous + // render. In that case it should not bubble. We determine whether it was + // cloned by comparing the child pointer. - while (this.isTerm()) { - terms.push(this.term()); - } + actualDuration += child.actualDuration; + treeBaseDuration += child.treeBaseDuration; + child = child.sibling; + } - return { type: "Alternative", value: terms, loc: this.loc(begin) } - }; + completedWork.actualDuration = actualDuration; + completedWork.treeBaseDuration = treeBaseDuration; + } else { + var _child = completedWork.child; - RegExpParser.prototype.term = function() { - if (this.isAssertion()) { - return this.assertion() - } else { - return this.atom() - } - }; + while (_child !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes)); + subtreeFlags |= _child.subtreeFlags; + subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code + // smell because it assumes the commit phase is never concurrent with + // the render phase. Will address during refactor to alternate model. - RegExpParser.prototype.assertion = function() { - var begin = this.idx; - switch (this.popChar()) { - case "^": - return { - type: "StartAnchor", - loc: this.loc(begin) - } - case "$": - return { type: "EndAnchor", loc: this.loc(begin) } - // '\b' or '\B' - case "\\": - switch (this.popChar()) { - case "b": - return { - type: "WordBoundary", - loc: this.loc(begin) - } - case "B": - return { - type: "NonWordBoundary", - loc: this.loc(begin) - } - } - // istanbul ignore next - throw Error("Invalid Assertion Escape") - // '(?=' or '(?!' - case "(": - this.consumeChar("?"); - - var type; - switch (this.popChar()) { - case "=": - type = "Lookahead"; - break - case "!": - type = "NegativeLookahead"; - break - } - ASSERT_EXISTS(type); + _child.return = completedWork; + _child = _child.sibling; + } + } - var disjunction = this.disjunction(); + completedWork.subtreeFlags |= subtreeFlags; + } else { + // Bubble up the earliest expiration time. + if ( (completedWork.mode & ProfileMode) !== NoMode) { + // In profiling mode, resetChildExpirationTime is also used to reset + // profiler durations. + var _treeBaseDuration = completedWork.selfBaseDuration; + var _child2 = completedWork.child; - this.consumeChar(")"); + while (_child2 !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, + // so we should bubble those up even during a bailout. All the other + // flags have a lifetime only of a single render + commit, so we should + // ignore them. - return { - type: type, - value: disjunction, - loc: this.loc(begin) - } - } - // istanbul ignore next - ASSERT_NEVER_REACH_HERE(); - }; + subtreeFlags |= _child2.subtreeFlags & StaticMask; + subtreeFlags |= _child2.flags & StaticMask; + _treeBaseDuration += _child2.treeBaseDuration; + _child2 = _child2.sibling; + } - RegExpParser.prototype.quantifier = function(isBacktracking) { - var range; - var begin = this.idx; - switch (this.popChar()) { - case "*": - range = { - atLeast: 0, - atMost: Infinity - }; - break - case "+": - range = { - atLeast: 1, - atMost: Infinity - }; - break - case "?": - range = { - atLeast: 0, - atMost: 1 - }; - break - case "{": - var atLeast = this.integerIncludingZero(); - switch (this.popChar()) { - case "}": - range = { - atLeast: atLeast, - atMost: atLeast - }; - break - case ",": - var atMost; - if (this.isDigit()) { - atMost = this.integerIncludingZero(); - range = { - atLeast: atLeast, - atMost: atMost - }; - } else { - range = { - atLeast: atLeast, - atMost: Infinity - }; - } - this.consumeChar("}"); - break - } - // throwing exceptions from "ASSERT_EXISTS" during backtracking - // causes severe performance degradations - if (isBacktracking === true && range === undefined) { - return undefined - } - ASSERT_EXISTS(range); - break - } + completedWork.treeBaseDuration = _treeBaseDuration; + } else { + var _child3 = completedWork.child; - // throwing exceptions from "ASSERT_EXISTS" during backtracking - // causes severe performance degradations - if (isBacktracking === true && range === undefined) { - return undefined - } + while (_child3 !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, + // so we should bubble those up even during a bailout. All the other + // flags have a lifetime only of a single render + commit, so we should + // ignore them. - ASSERT_EXISTS(range); + subtreeFlags |= _child3.subtreeFlags & StaticMask; + subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code + // smell because it assumes the commit phase is never concurrent with + // the render phase. Will address during refactor to alternate model. - if (this.peekChar(0) === "?") { - this.consumeChar("?"); - range.greedy = false; - } else { - range.greedy = true; - } + _child3.return = completedWork; + _child3 = _child3.sibling; + } + } - range.type = "Quantifier"; - range.loc = this.loc(begin); - return range - }; + completedWork.subtreeFlags |= subtreeFlags; + } - RegExpParser.prototype.atom = function() { - var atom; - var begin = this.idx; - switch (this.peekChar()) { - case ".": - atom = this.dotAll(); - break - case "\\": - atom = this.atomEscape(); - break - case "[": - atom = this.characterClass(); - break - case "(": - atom = this.group(); - break - } + completedWork.childLanes = newChildLanes; + return didBailout; + } - if (atom === undefined && this.isPatternCharacter()) { - atom = this.patternCharacter(); - } + function completeWork(current, workInProgress, renderLanes) { + var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing + // to the current tree provider fiber is just as fast and less error-prone. + // Ideally we would have a special version of the work loop only + // for hydration. - ASSERT_EXISTS(atom); + popTreeContext(workInProgress); - atom.loc = this.loc(begin); + switch (workInProgress.tag) { + case IndeterminateComponent: + case LazyComponent: + case SimpleMemoComponent: + case FunctionComponent: + case ForwardRef: + case Fragment: + case Mode: + case Profiler: + case ContextConsumer: + case MemoComponent: + bubbleProperties(workInProgress); + return null; - if (this.isQuantifier()) { - atom.quantifier = this.quantifier(); - } + case ClassComponent: + { + var Component = workInProgress.type; - return atom - }; + if (isContextProvider(Component)) { + popContext(workInProgress); + } - RegExpParser.prototype.dotAll = function() { - this.consumeChar("."); - return { - type: "Set", - complement: true, - value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")] - } - }; + bubbleProperties(workInProgress); + return null; + } - RegExpParser.prototype.atomEscape = function() { - this.consumeChar("\\"); - - switch (this.peekChar()) { - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - return this.decimalEscapeAtom() - case "d": - case "D": - case "s": - case "S": - case "w": - case "W": - return this.characterClassEscape() - case "f": - case "n": - case "r": - case "t": - case "v": - return this.controlEscapeAtom() - case "c": - return this.controlLetterEscapeAtom() - case "0": - return this.nulCharacterAtom() - case "x": - return this.hexEscapeSequenceAtom() - case "u": - return this.regExpUnicodeEscapeSequenceAtom() - default: - return this.identityEscapeAtom() - } - }; + case HostRoot: + { + var fiberRoot = workInProgress.stateNode; - RegExpParser.prototype.decimalEscapeAtom = function() { - var value = this.positiveInteger(); + popHostContainer(workInProgress); + popTopLevelContextObject(workInProgress); + resetWorkInProgressVersions(); - return { type: "GroupBackReference", value: value } - }; + if (fiberRoot.pendingContext) { + fiberRoot.context = fiberRoot.pendingContext; + fiberRoot.pendingContext = null; + } - RegExpParser.prototype.characterClassEscape = function() { - var set; - var complement = false; - switch (this.popChar()) { - case "d": - set = digitsCharCodes; - break - case "D": - set = digitsCharCodes; - complement = true; - break - case "s": - set = whitespaceCodes; - break - case "S": - set = whitespaceCodes; - complement = true; - break - case "w": - set = wordCharCodes; - break - case "W": - set = wordCharCodes; - complement = true; - break - } + if (current === null || current.child === null) { + // If we hydrated, pop so that we can delete any remaining children + // that weren't hydrated. + var wasHydrated = popHydrationState(workInProgress); - ASSERT_EXISTS(set); + if (wasHydrated) { + // If we hydrated, then we'll need to schedule an update for + // the commit side-effects on the root. + markUpdate(workInProgress); + } else { + if (current !== null) { + var prevState = current.memoizedState; - return { type: "Set", value: set, complement: complement } - }; + if ( // Check if this is a client root + !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error) + (workInProgress.flags & ForceClientRender) !== NoFlags) { + // Schedule an effect to clear this container at the start of the + // next commit. This handles the case of React rendering into a + // container with previous children. It's also safe to do for + // updates too, because current.child would only be null if the + // previous render was null (so the container would already + // be empty). + workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been + // recoverable errors during first hydration attempt. If so, add + // them to a queue so we can log them in the commit phase. - RegExpParser.prototype.controlEscapeAtom = function() { - var escapeCode; - switch (this.popChar()) { - case "f": - escapeCode = cc("\f"); - break - case "n": - escapeCode = cc("\n"); - break - case "r": - escapeCode = cc("\r"); - break - case "t": - escapeCode = cc("\t"); - break - case "v": - escapeCode = cc("\v"); - break + upgradeHydrationErrorsToRecoverable(); + } } - ASSERT_EXISTS(escapeCode); + } + } - return { type: "Character", value: escapeCode } - }; + updateHostContainer(current, workInProgress); + bubbleProperties(workInProgress); + return null; + } - RegExpParser.prototype.controlLetterEscapeAtom = function() { - this.consumeChar("c"); - var letter = this.popChar(); - if (/[a-zA-Z]/.test(letter) === false) { - throw Error("Invalid ") - } + case HostComponent: + { + popHostContext(workInProgress); + var rootContainerInstance = getRootHostContainer(); + var type = workInProgress.type; - var letterCode = letter.toUpperCase().charCodeAt(0) - 64; - return { type: "Character", value: letterCode } - }; + if (current !== null && workInProgress.stateNode != null) { + updateHostComponent(current, workInProgress, type, newProps, rootContainerInstance); - RegExpParser.prototype.nulCharacterAtom = function() { - // TODO implement '[lookahead ∉ DecimalDigit]' - // TODO: for the deprecated octal escape sequence - this.consumeChar("0"); - return { type: "Character", value: cc("\0") } - }; + if (current.ref !== workInProgress.ref) { + markRef(workInProgress); + } + } else { + if (!newProps) { + if (workInProgress.stateNode === null) { + throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); + } // This can happen when we abort work. - RegExpParser.prototype.hexEscapeSequenceAtom = function() { - this.consumeChar("x"); - return this.parseHexDigits(2) - }; - RegExpParser.prototype.regExpUnicodeEscapeSequenceAtom = function() { - this.consumeChar("u"); - return this.parseHexDigits(4) - }; + bubbleProperties(workInProgress); + return null; + } - RegExpParser.prototype.identityEscapeAtom = function() { - // TODO: implement "SourceCharacter but not UnicodeIDContinue" - // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments - var escapedChar = this.popChar(); - return { type: "Character", value: cc(escapedChar) } - }; + var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context + // "stack" as the parent. Then append children as we go in beginWork + // or completeWork depending on whether we want to add them top->down or + // bottom->up. Top->down is faster in IE11. - RegExpParser.prototype.classPatternCharacterAtom = function() { - switch (this.peekChar()) { - // istanbul ignore next - case "\n": - // istanbul ignore next - case "\r": - // istanbul ignore next - case "\u2028": - // istanbul ignore next - case "\u2029": - // istanbul ignore next - case "\\": - // istanbul ignore next - case "]": - throw Error("TBD") - default: - var nextChar = this.popChar(); - return { type: "Character", value: cc(nextChar) } - } - }; + var _wasHydrated = popHydrationState(workInProgress); - RegExpParser.prototype.characterClass = function() { - var set = []; - var complement = false; - this.consumeChar("["); - if (this.peekChar(0) === "^") { - this.consumeChar("^"); - complement = true; + if (_wasHydrated) { + // TODO: Move this and createInstance step into the beginPhase + // to consolidate. + if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) { + // If changes to the hydrated node need to be applied at the + // commit-phase we mark this as such. + markUpdate(workInProgress); } + } else { + var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress); + appendAllChildren(instance, workInProgress, false, false); + workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount. + // (eg DOM renderer supports auto-focus for certain elements). + // Make sure such renderers get scheduled for later work. - while (this.isClassAtom()) { - var from = this.classAtom(); - var isFromSingleChar = from.type === "Character"; - if (isFromSingleChar && this.isRangeDash()) { - this.consumeChar("-"); - var to = this.classAtom(); - var isToSingleChar = to.type === "Character"; - - // a range can only be used when both sides are single characters - if (isToSingleChar) { - if (to.value < from.value) { - throw Error("Range out of order in character class") - } - set.push({ from: from.value, to: to.value }); - } else { - // literal dash - insertToSet(from.value, set); - set.push(cc("-")); - insertToSet(to.value, set); - } - } else { - insertToSet(from.value, set); - } + if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) { + markUpdate(workInProgress); } + } - this.consumeChar("]"); + if (workInProgress.ref !== null) { + // If there is a ref on a host node we need to schedule a callback + markRef(workInProgress); + } + } - return { type: "Set", complement: complement, value: set } - }; + bubbleProperties(workInProgress); + return null; + } - RegExpParser.prototype.classAtom = function() { - switch (this.peekChar()) { - // istanbul ignore next - case "]": - // istanbul ignore next - case "\n": - // istanbul ignore next - case "\r": - // istanbul ignore next - case "\u2028": - // istanbul ignore next - case "\u2029": - throw Error("TBD") - case "\\": - return this.classEscape() - default: - return this.classPatternCharacterAtom() - } - }; + case HostText: + { + var newText = newProps; - RegExpParser.prototype.classEscape = function() { - this.consumeChar("\\"); - switch (this.peekChar()) { - // Matches a backspace. - // (Not to be confused with \b word boundary outside characterClass) - case "b": - this.consumeChar("b"); - return { type: "Character", value: cc("\u0008") } - case "d": - case "D": - case "s": - case "S": - case "w": - case "W": - return this.characterClassEscape() - case "f": - case "n": - case "r": - case "t": - case "v": - return this.controlEscapeAtom() - case "c": - return this.controlLetterEscapeAtom() - case "0": - return this.nulCharacterAtom() - case "x": - return this.hexEscapeSequenceAtom() - case "u": - return this.regExpUnicodeEscapeSequenceAtom() - default: - return this.identityEscapeAtom() - } - }; + if (current && workInProgress.stateNode != null) { + var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need + // to schedule a side-effect to do the updates. - RegExpParser.prototype.group = function() { - var capturing = true; - this.consumeChar("("); - switch (this.peekChar(0)) { - case "?": - this.consumeChar("?"); - this.consumeChar(":"); - capturing = false; - break - default: - this.groupIdx++; - break - } - var value = this.disjunction(); - this.consumeChar(")"); + updateHostText(current, workInProgress, oldText, newText); + } else { + if (typeof newText !== 'string') { + if (workInProgress.stateNode === null) { + throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); + } // This can happen when we abort work. - var groupAst = { - type: "Group", - capturing: capturing, - value: value - }; + } - if (capturing) { - groupAst.idx = this.groupIdx; - } + var _rootContainerInstance = getRootHostContainer(); - return groupAst - }; + var _currentHostContext = getHostContext(); - RegExpParser.prototype.positiveInteger = function() { - var number = this.popChar(); + var _wasHydrated2 = popHydrationState(workInProgress); - // istanbul ignore next - can't ever get here due to previous lookahead checks - // still implementing this error checking in case this ever changes. - if (decimalPatternNoZero.test(number) === false) { - throw Error("Expecting a positive integer") + if (_wasHydrated2) { + if (prepareToHydrateHostTextInstance(workInProgress)) { + markUpdate(workInProgress); } + } else { + workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress); + } + } - while (decimalPattern.test(this.peekChar(0))) { - number += this.popChar(); - } + bubbleProperties(workInProgress); + return null; + } - return parseInt(number, 10) - }; + case SuspenseComponent: + { + popSuspenseContext(workInProgress); + var nextState = workInProgress.memoizedState; - RegExpParser.prototype.integerIncludingZero = function() { - var number = this.popChar(); - if (decimalPattern.test(number) === false) { - throw Error("Expecting an integer") - } + { + if ( hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) { + warnIfUnhydratedTailNodes(workInProgress); + resetHydrationState(); + workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture; + return workInProgress; + } - while (decimalPattern.test(this.peekChar(0))) { - number += this.popChar(); - } + if (nextState !== null && nextState.dehydrated !== null) { + // We might be inside a hydration state the first time we're picking up this + // Suspense boundary, and also after we've reentered it for further hydration. + var _wasHydrated3 = popHydrationState(workInProgress); - return parseInt(number, 10) - }; + if (current === null) { + if (!_wasHydrated3) { + throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.'); + } - RegExpParser.prototype.patternCharacter = function() { - var nextChar = this.popChar(); - switch (nextChar) { - // istanbul ignore next - case "\n": - // istanbul ignore next - case "\r": - // istanbul ignore next - case "\u2028": - // istanbul ignore next - case "\u2029": - // istanbul ignore next - case "^": - // istanbul ignore next - case "$": - // istanbul ignore next - case "\\": - // istanbul ignore next - case ".": - // istanbul ignore next - case "*": - // istanbul ignore next - case "+": - // istanbul ignore next - case "?": - // istanbul ignore next - case "(": - // istanbul ignore next - case ")": - // istanbul ignore next - case "[": - // istanbul ignore next - case "|": - // istanbul ignore next - throw Error("TBD") - default: - return { type: "Character", value: cc(nextChar) } - } - }; - RegExpParser.prototype.isRegExpFlag = function() { - switch (this.peekChar(0)) { - case "g": - case "i": - case "m": - case "u": - case "y": - return true - default: - return false - } - }; + prepareToHydrateHostSuspenseInstance(workInProgress); + bubbleProperties(workInProgress); - RegExpParser.prototype.isRangeDash = function() { - return this.peekChar() === "-" && this.isClassAtom(1) - }; + { + if ((workInProgress.mode & ProfileMode) !== NoMode) { + var isTimedOutSuspense = nextState !== null; - RegExpParser.prototype.isDigit = function() { - return decimalPattern.test(this.peekChar(0)) - }; + if (isTimedOutSuspense) { + // Don't count time spent in a timed out Suspense subtree as part of the base duration. + var primaryChildFragment = workInProgress.child; - RegExpParser.prototype.isClassAtom = function(howMuch) { - if (howMuch === undefined) { - howMuch = 0; - } + if (primaryChildFragment !== null) { + // $FlowFixMe Flow doesn't support type casting in combination with the -= operator + workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration; + } + } + } + } - switch (this.peekChar(howMuch)) { - case "]": - case "\n": - case "\r": - case "\u2028": - case "\u2029": - return false - default: - return true - } - }; + return null; + } else { + // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration + // state since we're now exiting out of it. popHydrationState doesn't do that for us. + resetHydrationState(); - RegExpParser.prototype.isTerm = function() { - return this.isAtom() || this.isAssertion() - }; + if ((workInProgress.flags & DidCapture) === NoFlags) { + // This boundary did not suspend so it's now hydrated and unsuspended. + workInProgress.memoizedState = null; + } // If nothing suspended, we need to schedule an effect to mark this boundary + // as having hydrated so events know that they're free to be invoked. + // It's also a signal to replay events and the suspense callback. + // If something suspended, schedule an effect to attach retry listeners. + // So we might as well always mark this. - RegExpParser.prototype.isAtom = function() { - if (this.isPatternCharacter()) { - return true - } - switch (this.peekChar(0)) { - case ".": - case "\\": // atomEscape - case "[": // characterClass - // TODO: isAtom must be called before isAssertion - disambiguate - case "(": // group - return true - default: - return false - } - }; + workInProgress.flags |= Update; + bubbleProperties(workInProgress); + + { + if ((workInProgress.mode & ProfileMode) !== NoMode) { + var _isTimedOutSuspense = nextState !== null; + + if (_isTimedOutSuspense) { + // Don't count time spent in a timed out Suspense subtree as part of the base duration. + var _primaryChildFragment = workInProgress.child; - RegExpParser.prototype.isAssertion = function() { - switch (this.peekChar(0)) { - case "^": - case "$": - return true - // '\b' or '\B' - case "\\": - switch (this.peekChar(1)) { - case "b": - case "B": - return true - default: - return false + if (_primaryChildFragment !== null) { + // $FlowFixMe Flow doesn't support type casting in combination with the -= operator + workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration; } - // '(?=' or '(?!' - case "(": - return ( - this.peekChar(1) === "?" && - (this.peekChar(2) === "=" || this.peekChar(2) === "!") - ) - default: - return false - } - }; + } + } + } - RegExpParser.prototype.isQuantifier = function() { - var prevState = this.saveState(); - try { - return this.quantifier(true) !== undefined - } catch (e) { - return false - } finally { - this.restoreState(prevState); + return null; } - }; + } // Successfully completed this tree. If this was a forced client render, + // there may have been recoverable errors during first hydration + // attempt. If so, add them to a queue so we can log them in the + // commit phase. - RegExpParser.prototype.isPatternCharacter = function() { - switch (this.peekChar()) { - case "^": - case "$": - case "\\": - case ".": - case "*": - case "+": - case "?": - case "(": - case ")": - case "[": - case "|": - case "/": - case "\n": - case "\r": - case "\u2028": - case "\u2029": - return false - default: - return true - } - }; - RegExpParser.prototype.parseHexDigits = function(howMany) { - var hexString = ""; - for (var i = 0; i < howMany; i++) { - var hexChar = this.popChar(); - if (hexDigitPattern.test(hexChar) === false) { - throw Error("Expecting a HexDecimal digits") - } - hexString += hexChar; - } - var charCode = parseInt(hexString, 16); - return { type: "Character", value: charCode } - }; + upgradeHydrationErrorsToRecoverable(); + } - RegExpParser.prototype.peekChar = function(howMuch) { - if (howMuch === undefined) { - howMuch = 0; - } - return this.input[this.idx + howMuch] - }; + if ((workInProgress.flags & DidCapture) !== NoFlags) { + // Something suspended. Re-render with the fallback children. + workInProgress.lanes = renderLanes; // Do not reset the effect list. - RegExpParser.prototype.popChar = function() { - var nextChar = this.peekChar(0); - this.consumeChar(); - return nextChar - }; + if ( (workInProgress.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress); + } // Don't bubble properties in this case. - RegExpParser.prototype.consumeChar = function(char) { - if (char !== undefined && this.input[this.idx] !== char) { - throw Error( - "Expected: '" + - char + - "' but found: '" + - this.input[this.idx] + - "' at offset: " + - this.idx - ) - } - if (this.idx >= this.input.length) { - throw Error("Unexpected end of input") - } - this.idx++; - }; + return workInProgress; + } + + var nextDidTimeout = nextState !== null; + var prevDidTimeout = false; + + if (current === null) { + popHydrationState(workInProgress); + } else { + var _prevState = current.memoizedState; + prevDidTimeout = _prevState !== null; + } + // an effect to toggle the subtree's visibility. When we switch from + // fallback -> primary, the inner Offscreen fiber schedules this effect + // as part of its normal complete phase. But when we switch from + // primary -> fallback, the inner Offscreen fiber does not have a complete + // phase. So we need to schedule its effect here. + // + // We also use this flag to connect/disconnect the effects, but the same + // logic applies: when re-connecting, the Offscreen fiber's complete + // phase will handle scheduling the effect. It's only when the fallback + // is active that we have to do anything special. - RegExpParser.prototype.loc = function(begin) { - return { begin: begin, end: this.idx } - }; - // consts and utilities - var hexDigitPattern = /[0-9a-fA-F]/; - var decimalPattern = /[0-9]/; - var decimalPatternNoZero = /[1-9]/; + if (nextDidTimeout && !prevDidTimeout) { + var _offscreenFiber = workInProgress.child; + _offscreenFiber.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything + // in the concurrent tree already suspended during this render. + // This is a known bug. - function cc(char) { - return char.charCodeAt(0) - } + if ((workInProgress.mode & ConcurrentMode) !== NoMode) { + // TODO: Move this back to throwException because this is too late + // if this is a large tree which is common for initial loads. We + // don't know if we should restart a render or not until we get + // this marker, and this is too late. + // If this render already had a ping or lower pri updates, + // and this is the first time we know we're going to suspend we + // should be able to immediately restart from within throwException. + var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback); - function insertToSet(item, set) { - if (item.length !== undefined) { - item.forEach(function(subItem) { - set.push(subItem); - }); + if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) { + // If this was in an invisible tree or a new render, then showing + // this boundary is ok. + renderDidSuspend(); } else { - set.push(item); + // Otherwise, we're going to have to hide content so we should + // suspend for longer if possible. + renderDidSuspendDelayIfPossible(); } + } } - function addFlag(flagObj, flagKey) { - if (flagObj[flagKey] === true) { - throw "duplicate flag " + flagKey - } - - flagObj[flagKey] = true; - } + var wakeables = workInProgress.updateQueue; - function ASSERT_EXISTS(obj) { - // istanbul ignore next - if (obj === undefined) { - throw Error("Internal Error - Should never get here!") - } + if (wakeables !== null) { + // Schedule an effect to attach a retry listener to the promise. + // TODO: Move to passive phase + workInProgress.flags |= Update; } - // istanbul ignore next - function ASSERT_NEVER_REACH_HERE() { - throw Error("Internal Error - Should never get here!") - } + bubbleProperties(workInProgress); - var i; - var digitsCharCodes = []; - for (i = cc("0"); i <= cc("9"); i++) { - digitsCharCodes.push(i); - } + { + if ((workInProgress.mode & ProfileMode) !== NoMode) { + if (nextDidTimeout) { + // Don't count time spent in a timed out Suspense subtree as part of the base duration. + var _primaryChildFragment2 = workInProgress.child; - var wordCharCodes = [cc("_")].concat(digitsCharCodes); - for (i = cc("a"); i <= cc("z"); i++) { - wordCharCodes.push(i); + if (_primaryChildFragment2 !== null) { + // $FlowFixMe Flow doesn't support type casting in combination with the -= operator + workInProgress.treeBaseDuration -= _primaryChildFragment2.treeBaseDuration; + } + } + } } - for (i = cc("A"); i <= cc("Z"); i++) { - wordCharCodes.push(i); - } + return null; + } - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes - var whitespaceCodes = [ - cc(" "), - cc("\f"), - cc("\n"), - cc("\r"), - cc("\t"), - cc("\v"), - cc("\t"), - cc("\u00a0"), - cc("\u1680"), - cc("\u2000"), - cc("\u2001"), - cc("\u2002"), - cc("\u2003"), - cc("\u2004"), - cc("\u2005"), - cc("\u2006"), - cc("\u2007"), - cc("\u2008"), - cc("\u2009"), - cc("\u200a"), - cc("\u2028"), - cc("\u2029"), - cc("\u202f"), - cc("\u205f"), - cc("\u3000"), - cc("\ufeff") - ]; - - function BaseRegExpVisitor() {} - - BaseRegExpVisitor.prototype.visitChildren = function(node) { - for (var key in node) { - var child = node[key]; - /* istanbul ignore else */ - if (node.hasOwnProperty(key)) { - if (child.type !== undefined) { - this.visit(child); - } else if (Array.isArray(child)) { - child.forEach(function(subChild) { - this.visit(subChild); - }, this); - } - } - } - }; + case HostPortal: + popHostContainer(workInProgress); + updateHostContainer(current, workInProgress); - BaseRegExpVisitor.prototype.visit = function(node) { - switch (node.type) { - case "Pattern": - this.visitPattern(node); - break - case "Flags": - this.visitFlags(node); - break - case "Disjunction": - this.visitDisjunction(node); - break - case "Alternative": - this.visitAlternative(node); - break - case "StartAnchor": - this.visitStartAnchor(node); - break - case "EndAnchor": - this.visitEndAnchor(node); - break - case "WordBoundary": - this.visitWordBoundary(node); - break - case "NonWordBoundary": - this.visitNonWordBoundary(node); - break - case "Lookahead": - this.visitLookahead(node); - break - case "NegativeLookahead": - this.visitNegativeLookahead(node); - break - case "Character": - this.visitCharacter(node); - break - case "Set": - this.visitSet(node); - break - case "Group": - this.visitGroup(node); - break - case "GroupBackReference": - this.visitGroupBackReference(node); - break - case "Quantifier": - this.visitQuantifier(node); - break - } + if (current === null) { + preparePortalMount(workInProgress.stateNode.containerInfo); + } - this.visitChildren(node); - }; + bubbleProperties(workInProgress); + return null; - BaseRegExpVisitor.prototype.visitPattern = function(node) {}; + case ContextProvider: + // Pop provider fiber + var context = workInProgress.type._context; + popProvider(context, workInProgress); + bubbleProperties(workInProgress); + return null; - BaseRegExpVisitor.prototype.visitFlags = function(node) {}; + case IncompleteClassComponent: + { + // Same as class component case. I put it down here so that the tags are + // sequential to ensure this switch is compiled to a jump table. + var _Component = workInProgress.type; - BaseRegExpVisitor.prototype.visitDisjunction = function(node) {}; + if (isContextProvider(_Component)) { + popContext(workInProgress); + } - BaseRegExpVisitor.prototype.visitAlternative = function(node) {}; + bubbleProperties(workInProgress); + return null; + } - // Assertion - BaseRegExpVisitor.prototype.visitStartAnchor = function(node) {}; + case SuspenseListComponent: + { + popSuspenseContext(workInProgress); + var renderState = workInProgress.memoizedState; - BaseRegExpVisitor.prototype.visitEndAnchor = function(node) {}; + if (renderState === null) { + // We're running in the default, "independent" mode. + // We don't do anything in this mode. + bubbleProperties(workInProgress); + return null; + } - BaseRegExpVisitor.prototype.visitWordBoundary = function(node) {}; + var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags; + var renderedTail = renderState.rendering; - BaseRegExpVisitor.prototype.visitNonWordBoundary = function(node) {}; + if (renderedTail === null) { + // We just rendered the head. + if (!didSuspendAlready) { + // This is the first pass. We need to figure out if anything is still + // suspended in the rendered set. + // If new content unsuspended, but there's still some content that + // didn't. Then we need to do a second pass that forces everything + // to keep showing their fallbacks. + // We might be suspended if something in this render pass suspended, or + // something in the previous committed pass suspended. Otherwise, + // there's no chance so we can skip the expensive call to + // findFirstSuspended. + var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags); - BaseRegExpVisitor.prototype.visitLookahead = function(node) {}; + if (!cannotBeSuspended) { + var row = workInProgress.child; - BaseRegExpVisitor.prototype.visitNegativeLookahead = function(node) {}; + while (row !== null) { + var suspended = findFirstSuspended(row); - // atoms - BaseRegExpVisitor.prototype.visitCharacter = function(node) {}; + if (suspended !== null) { + didSuspendAlready = true; + workInProgress.flags |= DidCapture; + cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as + // part of the second pass. In that case nothing will subscribe to + // its thenables. Instead, we'll transfer its thenables to the + // SuspenseList so that it can retry if they resolve. + // There might be multiple of these in the list but since we're + // going to wait for all of them anyway, it doesn't really matter + // which ones gets to ping. In theory we could get clever and keep + // track of how many dependencies remain but it gets tricky because + // in the meantime, we can add/remove/change items and dependencies. + // We might bail out of the loop before finding any but that + // doesn't matter since that means that the other boundaries that + // we did find already has their listeners attached. - BaseRegExpVisitor.prototype.visitSet = function(node) {}; + var newThenables = suspended.updateQueue; - BaseRegExpVisitor.prototype.visitGroup = function(node) {}; + if (newThenables !== null) { + workInProgress.updateQueue = newThenables; + workInProgress.flags |= Update; + } // Rerender the whole list, but this time, we'll force fallbacks + // to stay in place. + // Reset the effect flags before doing the second pass since that's now invalid. + // Reset the child fibers to their original state. - BaseRegExpVisitor.prototype.visitGroupBackReference = function(node) {}; - BaseRegExpVisitor.prototype.visitQuantifier = function(node) {}; + workInProgress.subtreeFlags = NoFlags; + resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately + // rerender the children. - return { - RegExpParser: RegExpParser, - BaseRegExpVisitor: BaseRegExpVisitor, - VERSION: "0.5.0" - } - } - ); -} (regexpToAst)); + pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case. -var first = {exports: {}}; + return workInProgress.child; + } -/** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ + row = row.sibling; + } + } -function head$1(array) { - return (array && array.length) ? array[0] : undefined; -} + if (renderState.tail !== null && now$1() > getRenderTargetTime()) { + // We have already passed our CPU deadline but we still have rows + // left in the tail. We'll just give up further attempts to render + // the main content and only render fallbacks. + workInProgress.flags |= DidCapture; + didSuspendAlready = true; + cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this + // to get it started back up to attempt the next item. While in terms + // of priority this work has the same priority as this current render, + // it's not part of the same transition once the transition has + // committed. If it's sync, we still want to yield so that it can be + // painted. Conceptually, this is really the same as pinging. + // We can use any RetryLane even if it's the one currently rendering + // since we're leaving it behind on this node. -var head_1 = head$1; + workInProgress.lanes = SomeRetryLane; + } + } else { + cutOffTailIfNeeded(renderState, false); + } // Next we're going to render the tail. -(function (module) { - module.exports = head_1; -} (first)); + } else { + // Append the rendered row to the child list. + if (!didSuspendAlready) { + var _suspended = findFirstSuspended(renderedTail); -/** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ + if (_suspended !== null) { + workInProgress.flags |= DidCapture; + didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't + // get lost if this row ends up dropped during a second pass. -function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + var _newThenables = _suspended.updateQueue; - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } - } - return result; -} + if (_newThenables !== null) { + workInProgress.updateQueue = _newThenables; + workInProgress.flags |= Update; + } -var compact_1 = compact; + cutOffTailIfNeeded(renderState, true); // This might have been modified. -var baseEach$2 = _baseEach; + if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating. + ) { + // We're done. + bubbleProperties(workInProgress); + return null; + } + } else if ( // The time it took to render last row is greater than the remaining + // time we have to render. So rendering one more row would likely + // exceed it. + now$1() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) { + // We have now passed our CPU deadline and we'll just give up further + // attempts to render the main content and only render fallbacks. + // The assumption is that this is usually faster. + workInProgress.flags |= DidCapture; + didSuspendAlready = true; + cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this + // to get it started back up to attempt the next item. While in terms + // of priority this work has the same priority as this current render, + // it's not part of the same transition once the transition has + // committed. If it's sync, we still want to yield so that it can be + // painted. Conceptually, this is really the same as pinging. + // We can use any RetryLane even if it's the one currently rendering + // since we're leaving it behind on this node. -/** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ -function baseFilter$2(collection, predicate) { - var result = []; - baseEach$2(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; -} + workInProgress.lanes = SomeRetryLane; + } + } -var _baseFilter = baseFilter$2; + if (renderState.isBackwards) { + // The effect list of the backwards tail will have been added + // to the end. This breaks the guarantee that life-cycles fire in + // sibling order but that isn't a strong guarantee promised by React. + // Especially since these might also just pop in during future commits. + // Append to the beginning of the list. + renderedTail.sibling = workInProgress.child; + workInProgress.child = renderedTail; + } else { + var previousSibling = renderState.last; -/** Error message constants. */ + if (previousSibling !== null) { + previousSibling.sibling = renderedTail; + } else { + workInProgress.child = renderedTail; + } -var FUNC_ERROR_TEXT = 'Expected a function'; + renderState.last = renderedTail; + } + } -/** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ -function negate$1(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; -} + if (renderState.tail !== null) { + // We still have tail rows to render. + // Pop a row. + var next = renderState.tail; + renderState.rendering = next; + renderState.tail = next.sibling; + renderState.renderingStartTime = now$1(); + next.sibling = null; // Restore the context. + // TODO: We can probably just avoid popping it instead and only + // setting it the first time we go from not suspended to suspended. -var negate_1 = negate$1; + var suspenseContext = suspenseStackCursor.current; -var arrayFilter$1 = _arrayFilter, - baseFilter$1 = _baseFilter, - baseIteratee$5 = _baseIteratee, - isArray$5 = isArray_1$1, - negate = negate_1; + if (didSuspendAlready) { + suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); + } else { + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + } -/** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] - */ -function reject(collection, predicate) { - var func = isArray$5(collection) ? arrayFilter$1 : baseFilter$1; - return func(collection, negate(baseIteratee$5(predicate))); -} + pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. + // Don't bubble properties in this case. -var reject_1 = reject; + return next; + } -var SetCache$1 = _SetCache, - arrayIncludes$1 = _arrayIncludes, - arrayIncludesWith$1 = _arrayIncludesWith, - arrayMap$2 = _arrayMap, - baseUnary$1 = _baseUnary, - cacheHas$1 = _cacheHas; + bubbleProperties(workInProgress); + return null; + } -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE$1 = 200; + case ScopeComponent: + { -/** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ -function baseDifference$2(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes$1, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; + break; + } - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap$2(values, baseUnary$1(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith$1; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE$1) { - includes = cacheHas$1; - isCommon = false; - values = new SetCache$1(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); + case OffscreenComponent: + case LegacyHiddenComponent: + { + popRenderLanes(workInProgress); + var _nextState = workInProgress.memoizedState; + var nextIsHidden = _nextState !== null; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; -} + if (current !== null) { + var _prevState2 = current.memoizedState; + var prevIsHidden = _prevState2 !== null; -var _baseDifference = baseDifference$2; + if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding — it only pre-renders. + !enableLegacyHidden )) { + workInProgress.flags |= Visibility; + } + } -var isArrayLike$3 = isArrayLike_1, - isObjectLike$2 = isObjectLike_1; + if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) { + bubbleProperties(workInProgress); + } else { + // Don't bubble properties for hidden children unless we're rendering + // at offscreen priority. + if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) { + bubbleProperties(workInProgress); -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject$3(value) { - return isObjectLike$2(value) && isArrayLike$3(value); -} + if (supportsMutation) { + // Check if there was an insertion or update in the hidden subtree. + // If so, we need to hide those nodes in the commit phase, so + // schedule a visibility effect. + if ( workInProgress.subtreeFlags & (Placement | Update)) { + workInProgress.flags |= Visibility; + } + } + } + } -var isArrayLikeObject_1 = isArrayLikeObject$3; + return null; + } -var baseDifference$1 = _baseDifference, - baseFlatten$3 = _baseFlatten, - baseRest$3 = _baseRest, - isArrayLikeObject$2 = isArrayLikeObject_1; + case CacheComponent: + { -/** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ -var difference = baseRest$3(function(array, values) { - return isArrayLikeObject$2(array) - ? baseDifference$1(array, baseFlatten$3(values, 1, isArrayLikeObject$2, true)) - : []; -}); + return null; + } -var difference_1 = difference; + case TracingMarkerComponent: + { -var baseIndexOf$1 = _baseIndexOf, - toInteger$2 = toInteger_1; + return null; + } + } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax$3 = Math.max; + throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); + } -/** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ -function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger$2(fromIndex); - if (index < 0) { - index = nativeMax$3(length + index, 0); - } - return baseIndexOf$1(array, value, index); -} + var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; + var didReceiveUpdate = false; + var didWarnAboutBadClass; + var didWarnAboutModulePatternComponent; + var didWarnAboutContextTypeOnFunctionComponent; + var didWarnAboutGetDerivedStateOnFunctionComponent; + var didWarnAboutFunctionRefs; + var didWarnAboutReassigningProps; + var didWarnAboutRevealOrder; + var didWarnAboutTailOptions; -var indexOf_1 = indexOf; + { + didWarnAboutBadClass = {}; + didWarnAboutModulePatternComponent = {}; + didWarnAboutContextTypeOnFunctionComponent = {}; + didWarnAboutGetDerivedStateOnFunctionComponent = {}; + didWarnAboutFunctionRefs = {}; + didWarnAboutReassigningProps = false; + didWarnAboutRevealOrder = {}; + didWarnAboutTailOptions = {}; + } -var baseIteratee$4 = _baseIteratee, - isArrayLike$2 = isArrayLike_1, - keys$1 = keys_1; + function reconcileChildren(current, workInProgress, nextChildren, renderLanes) { + if (current === null) { + // If this is a fresh new component that hasn't been rendered yet, we + // won't update its child set by applying minimal side-effects. Instead, + // we will add them all to the child before it gets rendered. That means + // we can optimize this reconciliation pass by not tracking side-effects. + workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); + } else { + // If the current child is the same as the work in progress, it means that + // we haven't yet started any work on these children. Therefore, we use + // the clone algorithm to create a copy of all the current children. + // If we had any progressed work already, that is invalid at this point so + // let's throw it out. + workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes); + } + } -/** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ -function createFind$1(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike$2(collection)) { - var iteratee = baseIteratee$4(predicate); - collection = keys$1(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; -} + function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) { + // This function is fork of reconcileChildren. It's used in cases where we + // want to reconcile without matching against the existing set. This has the + // effect of all current children being unmounted; even if the type and key + // are the same, the old child is unmounted and a new child is created. + // + // To do this, we're going to go through the reconcile algorithm twice. In + // the first pass, we schedule a deletion for all the current children by + // passing null. + workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we + // pass null in place of where we usually pass the current child set. This has + // the effect of remounting all children regardless of whether their + // identities match. -var _createFind = createFind$1; + workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); + } -var baseFindIndex$1 = _baseFindIndex, - baseIteratee$3 = _baseIteratee, - toInteger$1 = toInteger_1; + function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) { + // TODO: current can be non-null here even if the component + // hasn't yet mounted. This happens after the first render suspends. + // We'll need to figure out if this is fine or can cause issues. + { + if (workInProgress.type !== workInProgress.elementType) { + // Lazy component props can't be validated in createElement + // because they're only guaranteed to be resolved here. + var innerPropTypes = Component.propTypes; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax$2 = Math.max; + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(Component)); + } + } + } -/** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ -function findIndex$1(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger$1(fromIndex); - if (index < 0) { - index = nativeMax$2(length + index, 0); - } - return baseFindIndex$1(array, baseIteratee$3(predicate), index); -} + var render = Component.render; + var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent -var findIndex_1 = findIndex$1; + var nextChildren; + var hasId; + prepareToReadContext(workInProgress, renderLanes); -var createFind = _createFind, - findIndex = findIndex_1; + { + markComponentRenderStarted(workInProgress); + } -/** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ -var find = createFind(findIndex); + { + ReactCurrentOwner$1.current = workInProgress; + setIsRendering(true); + nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); + hasId = checkDidRenderIdHook(); -var find_1 = find; + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); -var arrayFilter = _arrayFilter, - baseFilter = _baseFilter, - baseIteratee$2 = _baseIteratee, - isArray$4 = isArray_1$1; + try { + nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } -/** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] - */ -function filter(collection, predicate) { - var func = isArray$4(collection) ? arrayFilter : baseFilter; - return func(collection, baseIteratee$2(predicate)); -} + setIsRendering(false); + } -var filter_1 = filter; + { + markComponentRenderStopped(); + } -var baseRest$2 = _baseRest, - eq$1 = eq_1, - isIterateeCall = _isIterateeCall, - keysIn$1 = keysIn_1; + if (current !== null && !didReceiveUpdate) { + bailoutHooks(current, workInProgress, renderLanes); + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress); + } // React DevTools reads this flag. -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$3.hasOwnProperty; -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var defaults = baseRest$2(function(object, sources) { - object = Object(object); + workInProgress.flags |= PerformedWork; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; + function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { + if (current === null) { + var type = Component.type; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } + if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. + Component.defaultProps === undefined) { + var resolvedType = type; - while (++index < length) { - var source = sources[index]; - var props = keysIn$1(source); - var propsIndex = -1; - var propsLength = props.length; - - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - - if (value === undefined || - (eq$1(value, objectProto$3[key]) && !hasOwnProperty$3.call(object, key))) { - object[key] = source[key]; - } - } - } + { + resolvedType = resolveFunctionForHotReloading(type); + } // If this is a plain function component without default props, + // and with only the default shallow comparison, we upgrade it + // to a SimpleMemoComponent to allow fast path updates. - return object; -}); -var defaults_1 = defaults; + workInProgress.tag = SimpleMemoComponent; + workInProgress.type = resolvedType; -/** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ + { + validateFunctionComponentInDev(workInProgress, type); + } -function arrayReduce$1(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; + return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes); + } - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; -} + { + var innerPropTypes = type.propTypes; -var _arrayReduce = arrayReduce$1; + if (innerPropTypes) { + // Inner memo component props aren't currently validated in createElement. + // We could move it there, but we'd still need this for lazy code path. + checkPropTypes(innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(type)); + } + } -/** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ + var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes); + child.ref = workInProgress.ref; + child.return = workInProgress; + workInProgress.child = child; + return child; + } -function baseReduce$1(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; -} + { + var _type = Component.type; + var _innerPropTypes = _type.propTypes; -var _baseReduce = baseReduce$1; + if (_innerPropTypes) { + // Inner memo component props aren't currently validated in createElement. + // We could move it there, but we'd still need this for lazy code path. + checkPropTypes(_innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(_type)); + } + } -var arrayReduce = _arrayReduce, - baseEach$1 = _baseEach, - baseIteratee$1 = _baseIteratee, - baseReduce = _baseReduce, - isArray$3 = isArray_1$1; + var currentChild = current.child; // This is always exactly one child -/** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ -function reduce(collection, iteratee, accumulator) { - var func = isArray$3(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; + var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); - return func(collection, baseIteratee$1(iteratee), accumulator, initAccum, baseEach$1); -} + if (!hasScheduledUpdateOrContext) { + // This will be the props with resolved defaultProps, + // unlike current.memoizedProps which will be the unresolved ones. + var prevProps = currentChild.memoizedProps; // Default to shallow comparison -var reduce_1$1 = reduce; + var compare = Component.compare; + compare = compare !== null ? compare : shallowEqual; -var reg_exp = {}; + if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) { + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } + } // React DevTools reads this flag. -var reg_exp_parser = {}; -Object.defineProperty(reg_exp_parser, "__esModule", { value: true }); -reg_exp_parser.clearRegExpParserCache = reg_exp_parser.getRegExpAst = void 0; -var regexp_to_ast_1 = regexpToAst.exports; -var regExpAstCache = {}; -var regExpParser = new regexp_to_ast_1.RegExpParser(); -function getRegExpAst(regExp) { - var regExpStr = regExp.toString(); - if (regExpAstCache.hasOwnProperty(regExpStr)) { - return regExpAstCache[regExpStr]; - } - else { - var regExpAst = regExpParser.pattern(regExpStr); - regExpAstCache[regExpStr] = regExpAst; - return regExpAst; - } -} -reg_exp_parser.getRegExpAst = getRegExpAst; -function clearRegExpParserCache() { - regExpAstCache = {}; -} -reg_exp_parser.clearRegExpParserCache = clearRegExpParserCache; + workInProgress.flags |= PerformedWork; + var newChild = createWorkInProgress(currentChild, nextProps); + newChild.ref = workInProgress.ref; + newChild.return = workInProgress; + workInProgress.child = newChild; + return newChild; + } -var hasRequiredReg_exp; + function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { + // TODO: current can be non-null here even if the component + // hasn't yet mounted. This happens when the inner render suspends. + // We'll need to figure out if this is fine or can cause issues. + { + if (workInProgress.type !== workInProgress.elementType) { + // Lazy component props can't be validated in createElement + // because they're only guaranteed to be resolved here. + var outerMemoType = workInProgress.elementType; -function requireReg_exp () { - if (hasRequiredReg_exp) return reg_exp; - hasRequiredReg_exp = 1; - (function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.canMatchCharCode = exports.firstCharOptimizedIndices = exports.getOptimizedStartCodesIndices = exports.failedOptimizationPrefixMsg = void 0; - var regexp_to_ast_1 = regexpToAst.exports; - var isArray_1 = __importDefault(isArray_1$1); - var every_1 = __importDefault(every_1$1); - var forEach_1 = __importDefault(forEach_1$4); - var find_1$1 = __importDefault(find_1); - var values_1 = __importDefault(values_1$1); - var includes_1 = __importDefault(includes_1$2); - var utils_1 = api$2; - var reg_exp_parser_1 = reg_exp_parser; - var lexer_1 = requireLexer(); - var complementErrorMessage = "Complement Sets are not supported for first char optimization"; - exports.failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n'; - function getOptimizedStartCodesIndices(regExp, ensureOptimizations) { - if (ensureOptimizations === void 0) { ensureOptimizations = false; } - try { - var ast = (0, reg_exp_parser_1.getRegExpAst)(regExp); - var firstChars = firstCharOptimizedIndices(ast.value, {}, ast.flags.ignoreCase); - return firstChars; - } - catch (e) { - /* istanbul ignore next */ - // Testing this relies on the regexp-to-ast library having a bug... */ - // TODO: only the else branch needs to be ignored, try to fix with newer prettier / tsc - if (e.message === complementErrorMessage) { - if (ensureOptimizations) { - (0, utils_1.PRINT_WARNING)("".concat(exports.failedOptimizationPrefixMsg) + - "\tUnable to optimize: < ".concat(regExp.toString(), " >\n") + - "\tComplement Sets cannot be automatically optimized.\n" + - "\tThis will disable the lexer's first char optimizations.\n" + - "\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details."); - } - } - else { - var msgSuffix = ""; - if (ensureOptimizations) { - msgSuffix = - "\n\tThis will disable the lexer's first char optimizations.\n" + - "\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details."; - } - (0, utils_1.PRINT_ERROR)("".concat(exports.failedOptimizationPrefixMsg, "\n") + - "\tFailed parsing: < ".concat(regExp.toString(), " >\n") + - "\tUsing the regexp-to-ast library version: ".concat(regexp_to_ast_1.VERSION, "\n") + - "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" + - msgSuffix); - } - } - return []; - } - exports.getOptimizedStartCodesIndices = getOptimizedStartCodesIndices; - function firstCharOptimizedIndices(ast, result, ignoreCase) { - switch (ast.type) { - case "Disjunction": - for (var i = 0; i < ast.value.length; i++) { - firstCharOptimizedIndices(ast.value[i], result, ignoreCase); - } - break; - case "Alternative": - var terms = ast.value; - for (var i = 0; i < terms.length; i++) { - var term = terms[i]; - // skip terms that cannot effect the first char results - switch (term.type) { - case "EndAnchor": - // A group back reference cannot affect potential starting char. - // because if a back reference is the first production than automatically - // the group being referenced has had to come BEFORE so its codes have already been added - case "GroupBackReference": - // assertions do not affect potential starting codes - case "Lookahead": - case "NegativeLookahead": - case "StartAnchor": - case "WordBoundary": - case "NonWordBoundary": - continue; - } - var atom = term; - switch (atom.type) { - case "Character": - addOptimizedIdxToResult(atom.value, result, ignoreCase); - break; - case "Set": - if (atom.complement === true) { - throw Error(complementErrorMessage); - } - (0, forEach_1.default)(atom.value, function (code) { - if (typeof code === "number") { - addOptimizedIdxToResult(code, result, ignoreCase); - } - else { - // range - var range = code; - // cannot optimize when ignoreCase is - if (ignoreCase === true) { - for (var rangeCode = range.from; rangeCode <= range.to; rangeCode++) { - addOptimizedIdxToResult(rangeCode, result, ignoreCase); - } - } - // Optimization (2 orders of magnitude less work for very large ranges) - else { - // handle unoptimized values - for (var rangeCode = range.from; rangeCode <= range.to && rangeCode < lexer_1.minOptimizationVal; rangeCode++) { - addOptimizedIdxToResult(rangeCode, result, ignoreCase); - } - // Less common charCode where we optimize for faster init time, by using larger "buckets" - if (range.to >= lexer_1.minOptimizationVal) { - var minUnOptVal = range.from >= lexer_1.minOptimizationVal - ? range.from - : lexer_1.minOptimizationVal; - var maxUnOptVal = range.to; - var minOptIdx = (0, lexer_1.charCodeToOptimizedIndex)(minUnOptVal); - var maxOptIdx = (0, lexer_1.charCodeToOptimizedIndex)(maxUnOptVal); - for (var currOptIdx = minOptIdx; currOptIdx <= maxOptIdx; currOptIdx++) { - result[currOptIdx] = currOptIdx; - } - } - } - } - }); - break; - case "Group": - firstCharOptimizedIndices(atom.value, result, ignoreCase); - break; - /* istanbul ignore next */ - default: - throw Error("Non Exhaustive Match"); - } - // reached a mandatory production, no more **start** codes can be found on this alternative - var isOptionalQuantifier = atom.quantifier !== undefined && atom.quantifier.atLeast === 0; - if ( - // A group may be optional due to empty contents /(?:)/ - // or if everything inside it is optional /((a)?)/ - (atom.type === "Group" && isWholeOptional(atom) === false) || - // If this term is not a group it may only be optional if it has an optional quantifier - (atom.type !== "Group" && isOptionalQuantifier === false)) { - break; - } - } - break; - /* istanbul ignore next */ - default: - throw Error("non exhaustive match!"); - } - // console.log(Object.keys(result).length) - return (0, values_1.default)(result); - } - exports.firstCharOptimizedIndices = firstCharOptimizedIndices; - function addOptimizedIdxToResult(code, result, ignoreCase) { - var optimizedCharIdx = (0, lexer_1.charCodeToOptimizedIndex)(code); - result[optimizedCharIdx] = optimizedCharIdx; - if (ignoreCase === true) { - handleIgnoreCase(code, result); - } - } - function handleIgnoreCase(code, result) { - var char = String.fromCharCode(code); - var upperChar = char.toUpperCase(); - /* istanbul ignore else */ - if (upperChar !== char) { - var optimizedCharIdx = (0, lexer_1.charCodeToOptimizedIndex)(upperChar.charCodeAt(0)); - result[optimizedCharIdx] = optimizedCharIdx; - } - else { - var lowerChar = char.toLowerCase(); - if (lowerChar !== char) { - var optimizedCharIdx = (0, lexer_1.charCodeToOptimizedIndex)(lowerChar.charCodeAt(0)); - result[optimizedCharIdx] = optimizedCharIdx; - } - } - } - function findCode(setNode, targetCharCodes) { - return (0, find_1$1.default)(setNode.value, function (codeOrRange) { - if (typeof codeOrRange === "number") { - return (0, includes_1.default)(targetCharCodes, codeOrRange); - } - else { - // range - var range_1 = codeOrRange; - return ((0, find_1$1.default)(targetCharCodes, function (targetCode) { return range_1.from <= targetCode && targetCode <= range_1.to; }) !== undefined); - } - }); - } - function isWholeOptional(ast) { - var quantifier = ast.quantifier; - if (quantifier && quantifier.atLeast === 0) { - return true; - } - if (!ast.value) { - return false; - } - return (0, isArray_1.default)(ast.value) - ? (0, every_1.default)(ast.value, isWholeOptional) - : isWholeOptional(ast.value); - } - var CharCodeFinder = /** @class */ (function (_super) { - __extends(CharCodeFinder, _super); - function CharCodeFinder(targetCharCodes) { - var _this = _super.call(this) || this; - _this.targetCharCodes = targetCharCodes; - _this.found = false; - return _this; - } - CharCodeFinder.prototype.visitChildren = function (node) { - // No need to keep looking... - if (this.found === true) { - return; - } - // switch lookaheads as they do not actually consume any characters thus - // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match. - switch (node.type) { - case "Lookahead": - this.visitLookahead(node); - return; - case "NegativeLookahead": - this.visitNegativeLookahead(node); - return; - } - _super.prototype.visitChildren.call(this, node); - }; - CharCodeFinder.prototype.visitCharacter = function (node) { - if ((0, includes_1.default)(this.targetCharCodes, node.value)) { - this.found = true; - } - }; - CharCodeFinder.prototype.visitSet = function (node) { - if (node.complement) { - if (findCode(node, this.targetCharCodes) === undefined) { - this.found = true; - } - } - else { - if (findCode(node, this.targetCharCodes) !== undefined) { - this.found = true; - } - } - }; - return CharCodeFinder; - }(regexp_to_ast_1.BaseRegExpVisitor)); - function canMatchCharCode(charCodes, pattern) { - if (pattern instanceof RegExp) { - var ast = (0, reg_exp_parser_1.getRegExpAst)(pattern); - var charCodeFinder = new CharCodeFinder(charCodes); - charCodeFinder.visit(ast); - return charCodeFinder.found; - } - else { - return ((0, find_1$1.default)(pattern, function (char) { - return (0, includes_1.default)(charCodes, char.charCodeAt(0)); - }) !== undefined); - } - } - exports.canMatchCharCode = canMatchCharCode; - -} (reg_exp)); - return reg_exp; -} + if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { + // We warn when you define propTypes on lazy() + // so let's just skip over it to find memo() outer wrapper. + // Inner props for memo are validated later. + var lazyComponent = outerMemoType; + var payload = lazyComponent._payload; + var init = lazyComponent._init; -var hasRequiredLexer; + try { + outerMemoType = init(payload); + } catch (x) { + outerMemoType = null; + } // Inner propTypes will be validated in the function component path. -function requireLexer () { - if (hasRequiredLexer) return lexer; - hasRequiredLexer = 1; - (function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.charCodeToOptimizedIndex = exports.minOptimizationVal = exports.buildLineBreakIssueMessage = exports.LineTerminatorOptimizedTester = exports.isShortPattern = exports.isCustomPattern = exports.cloneEmptyGroups = exports.performWarningRuntimeChecks = exports.performRuntimeChecks = exports.addStickyFlag = exports.addStartOfInput = exports.findUnreachablePatterns = exports.findModesThatDoNotExist = exports.findInvalidGroupType = exports.findDuplicatePatterns = exports.findUnsupportedFlags = exports.findStartOfInputAnchor = exports.findEmptyMatchRegExps = exports.findEndOfInputAnchor = exports.findInvalidPatterns = exports.findMissingPatterns = exports.validatePatterns = exports.analyzeTokenTypes = exports.enableSticky = exports.disableSticky = exports.SUPPORT_STICKY = exports.MODES = exports.DEFAULT_MODE = void 0; - var regexp_to_ast_1 = regexpToAst.exports; - var lexer_public_1 = requireLexer_public(); - var first_1 = __importDefault(first.exports); - var isEmpty_1 = __importDefault(isEmpty_1$1); - var compact_1$1 = __importDefault(compact_1); - var isArray_1 = __importDefault(isArray_1$1); - var values_1 = __importDefault(values_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var reject_1$1 = __importDefault(reject_1); - var difference_1$1 = __importDefault(difference_1); - var indexOf_1$1 = __importDefault(indexOf_1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var isString_1 = __importDefault(isString_1$1); - var isFunction_1$1 = __importDefault(isFunction_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var find_1$1 = __importDefault(find_1); - var has_1$1 = __importDefault(has_1); - var keys_1$1 = __importDefault(keys_1); - var isRegExp_1 = __importDefault(isRegExp_1$1); - var filter_1$1 = __importDefault(filter_1); - var defaults_1$1 = __importDefault(defaults_1); - var reduce_1 = __importDefault(reduce_1$1); - var includes_1 = __importDefault(includes_1$2); - var utils_1 = api$2; - var reg_exp_1 = requireReg_exp(); - var reg_exp_parser_1 = reg_exp_parser; - var PATTERN = "PATTERN"; - exports.DEFAULT_MODE = "defaultMode"; - exports.MODES = "modes"; - exports.SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean"; - function disableSticky() { - exports.SUPPORT_STICKY = false; - } - exports.disableSticky = disableSticky; - function enableSticky() { - exports.SUPPORT_STICKY = true; - } - exports.enableSticky = enableSticky; - function analyzeTokenTypes(tokenTypes, options) { - options = (0, defaults_1$1.default)(options, { - useSticky: exports.SUPPORT_STICKY, - debug: false, - safeMode: false, - positionTracking: "full", - lineTerminatorCharacters: ["\r", "\n"], - tracer: function (msg, action) { return action(); } - }); - var tracer = options.tracer; - tracer("initCharCodeToOptimizedIndexMap", function () { - initCharCodeToOptimizedIndexMap(); - }); - var onlyRelevantTypes; - tracer("Reject Lexer.NA", function () { - onlyRelevantTypes = (0, reject_1$1.default)(tokenTypes, function (currType) { - return currType[PATTERN] === lexer_public_1.Lexer.NA; - }); - }); - var hasCustom = false; - var allTransformedPatterns; - tracer("Transform Patterns", function () { - hasCustom = false; - allTransformedPatterns = (0, map_1.default)(onlyRelevantTypes, function (currType) { - var currPattern = currType[PATTERN]; - /* istanbul ignore else */ - if ((0, isRegExp_1.default)(currPattern)) { - var regExpSource = currPattern.source; - if (regExpSource.length === 1 && - // only these regExp meta characters which can appear in a length one regExp - regExpSource !== "^" && - regExpSource !== "$" && - regExpSource !== "." && - !currPattern.ignoreCase) { - return regExpSource; - } - else if (regExpSource.length === 2 && - regExpSource[0] === "\\" && - // not a meta character - !(0, includes_1.default)([ - "d", - "D", - "s", - "S", - "t", - "r", - "n", - "t", - "0", - "c", - "b", - "B", - "f", - "v", - "w", - "W" - ], regExpSource[1])) { - // escaped meta Characters: /\+/ /\[/ - // or redundant escaping: /\a/ - // without the escaping "\" - return regExpSource[1]; - } - else { - return options.useSticky - ? addStickyFlag(currPattern) - : addStartOfInput(currPattern); - } - } - else if ((0, isFunction_1$1.default)(currPattern)) { - hasCustom = true; - // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object - return { exec: currPattern }; - } - else if (typeof currPattern === "object") { - hasCustom = true; - // ICustomPattern - return currPattern; - } - else if (typeof currPattern === "string") { - if (currPattern.length === 1) { - return currPattern; - } - else { - var escapedRegExpString = currPattern.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); - var wrappedRegExp = new RegExp(escapedRegExpString); - return options.useSticky - ? addStickyFlag(wrappedRegExp) - : addStartOfInput(wrappedRegExp); - } - } - else { - throw Error("non exhaustive match"); - } - }); - }); - var patternIdxToType; - var patternIdxToGroup; - var patternIdxToLongerAltIdxArr; - var patternIdxToPushMode; - var patternIdxToPopMode; - tracer("misc mapping", function () { - patternIdxToType = (0, map_1.default)(onlyRelevantTypes, function (currType) { return currType.tokenTypeIdx; }); - patternIdxToGroup = (0, map_1.default)(onlyRelevantTypes, function (clazz) { - var groupName = clazz.GROUP; - /* istanbul ignore next */ - if (groupName === lexer_public_1.Lexer.SKIPPED) { - return undefined; - } - else if ((0, isString_1.default)(groupName)) { - return groupName; - } - else if ((0, isUndefined_1.default)(groupName)) { - return false; - } - else { - throw Error("non exhaustive match"); - } - }); - patternIdxToLongerAltIdxArr = (0, map_1.default)(onlyRelevantTypes, function (clazz) { - var longerAltType = clazz.LONGER_ALT; - if (longerAltType) { - var longerAltIdxArr = (0, isArray_1.default)(longerAltType) - ? (0, map_1.default)(longerAltType, function (type) { return (0, indexOf_1$1.default)(onlyRelevantTypes, type); }) - : [(0, indexOf_1$1.default)(onlyRelevantTypes, longerAltType)]; - return longerAltIdxArr; - } - }); - patternIdxToPushMode = (0, map_1.default)(onlyRelevantTypes, function (clazz) { return clazz.PUSH_MODE; }); - patternIdxToPopMode = (0, map_1.default)(onlyRelevantTypes, function (clazz) { - return (0, has_1$1.default)(clazz, "POP_MODE"); - }); - }); - var patternIdxToCanLineTerminator; - tracer("Line Terminator Handling", function () { - var lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters); - patternIdxToCanLineTerminator = (0, map_1.default)(onlyRelevantTypes, function (tokType) { return false; }); - if (options.positionTracking !== "onlyOffset") { - patternIdxToCanLineTerminator = (0, map_1.default)(onlyRelevantTypes, function (tokType) { - if ((0, has_1$1.default)(tokType, "LINE_BREAKS")) { - return !!tokType.LINE_BREAKS; - } - else { - return (checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false && - (0, reg_exp_1.canMatchCharCode)(lineTerminatorCharCodes, tokType.PATTERN)); - } - }); - } - }); - var patternIdxToIsCustom; - var patternIdxToShort; - var emptyGroups; - var patternIdxToConfig; - tracer("Misc Mapping #2", function () { - patternIdxToIsCustom = (0, map_1.default)(onlyRelevantTypes, isCustomPattern); - patternIdxToShort = (0, map_1.default)(allTransformedPatterns, isShortPattern); - emptyGroups = (0, reduce_1.default)(onlyRelevantTypes, function (acc, clazz) { - var groupName = clazz.GROUP; - if ((0, isString_1.default)(groupName) && !(groupName === lexer_public_1.Lexer.SKIPPED)) { - acc[groupName] = []; - } - return acc; - }, {}); - patternIdxToConfig = (0, map_1.default)(allTransformedPatterns, function (x, idx) { - return { - pattern: allTransformedPatterns[idx], - longerAlt: patternIdxToLongerAltIdxArr[idx], - canLineTerminator: patternIdxToCanLineTerminator[idx], - isCustom: patternIdxToIsCustom[idx], - short: patternIdxToShort[idx], - group: patternIdxToGroup[idx], - push: patternIdxToPushMode[idx], - pop: patternIdxToPopMode[idx], - tokenTypeIdx: patternIdxToType[idx], - tokenType: onlyRelevantTypes[idx] - }; - }); - }); - var canBeOptimized = true; - var charCodeToPatternIdxToConfig = []; - if (!options.safeMode) { - tracer("First Char Optimization", function () { - charCodeToPatternIdxToConfig = (0, reduce_1.default)(onlyRelevantTypes, function (result, currTokType, idx) { - if (typeof currTokType.PATTERN === "string") { - var charCode = currTokType.PATTERN.charCodeAt(0); - var optimizedIdx = charCodeToOptimizedIndex(charCode); - addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]); - } - else if ((0, isArray_1.default)(currTokType.START_CHARS_HINT)) { - var lastOptimizedIdx_1; - (0, forEach_1.default)(currTokType.START_CHARS_HINT, function (charOrInt) { - var charCode = typeof charOrInt === "string" - ? charOrInt.charCodeAt(0) - : charOrInt; - var currOptimizedIdx = charCodeToOptimizedIndex(charCode); - // Avoid adding the config multiple times - /* istanbul ignore else */ - // - Difficult to check this scenario effects as it is only a performance - // optimization that does not change correctness - if (lastOptimizedIdx_1 !== currOptimizedIdx) { - lastOptimizedIdx_1 = currOptimizedIdx; - addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]); - } - }); - } - else if ((0, isRegExp_1.default)(currTokType.PATTERN)) { - if (currTokType.PATTERN.unicode) { - canBeOptimized = false; - if (options.ensureOptimizations) { - (0, utils_1.PRINT_ERROR)("".concat(reg_exp_1.failedOptimizationPrefixMsg) + - "\tUnable to analyze < ".concat(currTokType.PATTERN.toString(), " > pattern.\n") + - "\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\n" + - "\tThis will disable the lexer's first char optimizations.\n" + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE"); - } - } - else { - var optimizedCodes = (0, reg_exp_1.getOptimizedStartCodesIndices)(currTokType.PATTERN, options.ensureOptimizations); - /* istanbul ignore if */ - // start code will only be empty given an empty regExp or failure of regexp-to-ast library - // the first should be a different validation and the second cannot be tested. - if ((0, isEmpty_1.default)(optimizedCodes)) { - // we cannot understand what codes may start possible matches - // The optimization correctness requires knowing start codes for ALL patterns. - // Not actually sure this is an error, no debug message - canBeOptimized = false; - } - (0, forEach_1.default)(optimizedCodes, function (code) { - addToMapOfArrays(result, code, patternIdxToConfig[idx]); - }); - } - } - else { - if (options.ensureOptimizations) { - (0, utils_1.PRINT_ERROR)("".concat(reg_exp_1.failedOptimizationPrefixMsg) + - "\tTokenType: <".concat(currTokType.name, "> is using a custom token pattern without providing parameter.\n") + - "\tThis will disable the lexer's first char optimizations.\n" + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE"); - } - canBeOptimized = false; - } - return result; - }, []); - }); - } - return { - emptyGroups: emptyGroups, - patternIdxToConfig: patternIdxToConfig, - charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig, - hasCustom: hasCustom, - canBeOptimized: canBeOptimized - }; - } - exports.analyzeTokenTypes = analyzeTokenTypes; - function validatePatterns(tokenTypes, validModesNames) { - var errors = []; - var missingResult = findMissingPatterns(tokenTypes); - errors = errors.concat(missingResult.errors); - var invalidResult = findInvalidPatterns(missingResult.valid); - var validTokenTypes = invalidResult.valid; - errors = errors.concat(invalidResult.errors); - errors = errors.concat(validateRegExpPattern(validTokenTypes)); - errors = errors.concat(findInvalidGroupType(validTokenTypes)); - errors = errors.concat(findModesThatDoNotExist(validTokenTypes, validModesNames)); - errors = errors.concat(findUnreachablePatterns(validTokenTypes)); - return errors; - } - exports.validatePatterns = validatePatterns; - function validateRegExpPattern(tokenTypes) { - var errors = []; - var withRegExpPatterns = (0, filter_1$1.default)(tokenTypes, function (currTokType) { - return (0, isRegExp_1.default)(currTokType[PATTERN]); - }); - errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns)); - errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns)); - errors = errors.concat(findUnsupportedFlags(withRegExpPatterns)); - errors = errors.concat(findDuplicatePatterns(withRegExpPatterns)); - errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns)); - return errors; - } - function findMissingPatterns(tokenTypes) { - var tokenTypesWithMissingPattern = (0, filter_1$1.default)(tokenTypes, function (currType) { - return !(0, has_1$1.default)(currType, PATTERN); - }); - var errors = (0, map_1.default)(tokenTypesWithMissingPattern, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- missing static 'PATTERN' property", - type: lexer_public_1.LexerDefinitionErrorType.MISSING_PATTERN, - tokenTypes: [currType] - }; - }); - var valid = (0, difference_1$1.default)(tokenTypes, tokenTypesWithMissingPattern); - return { errors: errors, valid: valid }; - } - exports.findMissingPatterns = findMissingPatterns; - function findInvalidPatterns(tokenTypes) { - var tokenTypesWithInvalidPattern = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return (!(0, isRegExp_1.default)(pattern) && - !(0, isFunction_1$1.default)(pattern) && - !(0, has_1$1.default)(pattern, "exec") && - !(0, isString_1.default)(pattern)); - }); - var errors = (0, map_1.default)(tokenTypesWithInvalidPattern, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' can only be a RegExp, a" + - " Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", - type: lexer_public_1.LexerDefinitionErrorType.INVALID_PATTERN, - tokenTypes: [currType] - }; - }); - var valid = (0, difference_1$1.default)(tokenTypes, tokenTypesWithInvalidPattern); - return { errors: errors, valid: valid }; - } - exports.findInvalidPatterns = findInvalidPatterns; - var end_of_input = /[^\\][$]/; - function findEndOfInputAnchor(tokenTypes) { - var EndAnchorFinder = /** @class */ (function (_super) { - __extends(EndAnchorFinder, _super); - function EndAnchorFinder() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.found = false; - return _this; - } - EndAnchorFinder.prototype.visitEndAnchor = function (node) { - this.found = true; - }; - return EndAnchorFinder; - }(regexp_to_ast_1.BaseRegExpVisitor)); - var invalidRegex = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType.PATTERN; - try { - var regexpAst = (0, reg_exp_parser_1.getRegExpAst)(pattern); - var endAnchorVisitor = new EndAnchorFinder(); - endAnchorVisitor.visit(regexpAst); - return endAnchorVisitor.found; - } - catch (e) { - // old behavior in case of runtime exceptions with regexp-to-ast. - /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ - return end_of_input.test(pattern.source); - } - }); - var errors = (0, map_1.default)(invalidRegex, function (currType) { - return { - message: "Unexpected RegExp Anchor Error:\n" + - "\tToken Type: ->" + - currType.name + - "<- static 'PATTERN' cannot contain end of input anchor '$'\n" + - "\tSee chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS" + - "\tfor details.", - type: lexer_public_1.LexerDefinitionErrorType.EOI_ANCHOR_FOUND, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findEndOfInputAnchor = findEndOfInputAnchor; - function findEmptyMatchRegExps(tokenTypes) { - var matchesEmptyString = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType.PATTERN; - return pattern.test(""); - }); - var errors = (0, map_1.default)(matchesEmptyString, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' must not match an empty string", - type: lexer_public_1.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findEmptyMatchRegExps = findEmptyMatchRegExps; - var start_of_input = /[^\\[][\^]|^\^/; - function findStartOfInputAnchor(tokenTypes) { - var StartAnchorFinder = /** @class */ (function (_super) { - __extends(StartAnchorFinder, _super); - function StartAnchorFinder() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.found = false; - return _this; - } - StartAnchorFinder.prototype.visitStartAnchor = function (node) { - this.found = true; - }; - return StartAnchorFinder; - }(regexp_to_ast_1.BaseRegExpVisitor)); - var invalidRegex = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType.PATTERN; - try { - var regexpAst = (0, reg_exp_parser_1.getRegExpAst)(pattern); - var startAnchorVisitor = new StartAnchorFinder(); - startAnchorVisitor.visit(regexpAst); - return startAnchorVisitor.found; - } - catch (e) { - // old behavior in case of runtime exceptions with regexp-to-ast. - /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ - return start_of_input.test(pattern.source); - } - }); - var errors = (0, map_1.default)(invalidRegex, function (currType) { - return { - message: "Unexpected RegExp Anchor Error:\n" + - "\tToken Type: ->" + - currType.name + - "<- static 'PATTERN' cannot contain start of input anchor '^'\n" + - "\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS" + - "\tfor details.", - type: lexer_public_1.LexerDefinitionErrorType.SOI_ANCHOR_FOUND, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findStartOfInputAnchor = findStartOfInputAnchor; - function findUnsupportedFlags(tokenTypes) { - var invalidFlags = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return pattern instanceof RegExp && (pattern.multiline || pattern.global); - }); - var errors = (0, map_1.default)(invalidFlags, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", - type: lexer_public_1.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findUnsupportedFlags = findUnsupportedFlags; - // This can only test for identical duplicate RegExps, not semantically equivalent ones. - function findDuplicatePatterns(tokenTypes) { - var found = []; - var identicalPatterns = (0, map_1.default)(tokenTypes, function (outerType) { - return (0, reduce_1.default)(tokenTypes, function (result, innerType) { - if (outerType.PATTERN.source === innerType.PATTERN.source && - !(0, includes_1.default)(found, innerType) && - innerType.PATTERN !== lexer_public_1.Lexer.NA) { - // this avoids duplicates in the result, each Token Type may only appear in one "set" - // in essence we are creating Equivalence classes on equality relation. - found.push(innerType); - result.push(innerType); - return result; - } - return result; - }, []); - }); - identicalPatterns = (0, compact_1$1.default)(identicalPatterns); - var duplicatePatterns = (0, filter_1$1.default)(identicalPatterns, function (currIdenticalSet) { - return currIdenticalSet.length > 1; - }); - var errors = (0, map_1.default)(duplicatePatterns, function (setOfIdentical) { - var tokenTypeNames = (0, map_1.default)(setOfIdentical, function (currType) { - return currType.name; - }); - var dupPatternSrc = (0, first_1.default)(setOfIdentical).PATTERN; - return { - message: "The same RegExp pattern ->".concat(dupPatternSrc, "<-") + - "has been used in all of the following Token Types: ".concat(tokenTypeNames.join(", "), " <-"), - type: lexer_public_1.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, - tokenTypes: setOfIdentical - }; - }); - return errors; - } - exports.findDuplicatePatterns = findDuplicatePatterns; - function findInvalidGroupType(tokenTypes) { - var invalidTypes = (0, filter_1$1.default)(tokenTypes, function (clazz) { - if (!(0, has_1$1.default)(clazz, "GROUP")) { - return false; - } - var group = clazz.GROUP; - return group !== lexer_public_1.Lexer.SKIPPED && group !== lexer_public_1.Lexer.NA && !(0, isString_1.default)(group); - }); - var errors = (0, map_1.default)(invalidTypes, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", - type: lexer_public_1.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findInvalidGroupType = findInvalidGroupType; - function findModesThatDoNotExist(tokenTypes, validModes) { - var invalidModes = (0, filter_1$1.default)(tokenTypes, function (clazz) { - return (clazz.PUSH_MODE !== undefined && !(0, includes_1.default)(validModes, clazz.PUSH_MODE)); - }); - var errors = (0, map_1.default)(invalidModes, function (tokType) { - var msg = "Token Type: ->".concat(tokType.name, "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->").concat(tokType.PUSH_MODE, "<-") + - "which does not exist"; - return { - message: msg, - type: lexer_public_1.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, - tokenTypes: [tokType] - }; - }); - return errors; - } - exports.findModesThatDoNotExist = findModesThatDoNotExist; - function findUnreachablePatterns(tokenTypes) { - var errors = []; - var canBeTested = (0, reduce_1.default)(tokenTypes, function (result, tokType, idx) { - var pattern = tokType.PATTERN; - if (pattern === lexer_public_1.Lexer.NA) { - return result; - } - // a more comprehensive validation for all forms of regExps would require - // deeper regExp analysis capabilities - if ((0, isString_1.default)(pattern)) { - result.push({ str: pattern, idx: idx, tokenType: tokType }); - } - else if ((0, isRegExp_1.default)(pattern) && noMetaChar(pattern)) { - result.push({ str: pattern.source, idx: idx, tokenType: tokType }); - } - return result; - }, []); - (0, forEach_1.default)(tokenTypes, function (tokType, testIdx) { - (0, forEach_1.default)(canBeTested, function (_a) { - var str = _a.str, idx = _a.idx, tokenType = _a.tokenType; - if (testIdx < idx && testTokenType(str, tokType.PATTERN)) { - var msg = "Token: ->".concat(tokenType.name, "<- can never be matched.\n") + - "Because it appears AFTER the Token Type ->".concat(tokType.name, "<-") + - "in the lexer's definition.\n" + - "See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE"; - errors.push({ - message: msg, - type: lexer_public_1.LexerDefinitionErrorType.UNREACHABLE_PATTERN, - tokenTypes: [tokType, tokenType] - }); - } - }); - }); - return errors; - } - exports.findUnreachablePatterns = findUnreachablePatterns; - function testTokenType(str, pattern) { - /* istanbul ignore else */ - if ((0, isRegExp_1.default)(pattern)) { - var regExpArray = pattern.exec(str); - return regExpArray !== null && regExpArray.index === 0; - } - else if ((0, isFunction_1$1.default)(pattern)) { - // maintain the API of custom patterns - return pattern(str, 0, [], {}); - } - else if ((0, has_1$1.default)(pattern, "exec")) { - // maintain the API of custom patterns - return pattern.exec(str, 0, [], {}); - } - else if (typeof pattern === "string") { - return pattern === str; - } - else { - throw Error("non exhaustive match"); - } - } - function noMetaChar(regExp) { - //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp - var metaChars = [ - ".", - "\\", - "[", - "]", - "|", - "^", - "$", - "(", - ")", - "?", - "*", - "+", - "{" - ]; - return ((0, find_1$1.default)(metaChars, function (char) { return regExp.source.indexOf(char) !== -1; }) === undefined); - } - function addStartOfInput(pattern) { - var flags = pattern.ignoreCase ? "i" : ""; - // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. - // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) - return new RegExp("^(?:".concat(pattern.source, ")"), flags); - } - exports.addStartOfInput = addStartOfInput; - function addStickyFlag(pattern) { - var flags = pattern.ignoreCase ? "iy" : "y"; - // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. - // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) - return new RegExp("".concat(pattern.source), flags); - } - exports.addStickyFlag = addStickyFlag; - function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { - var errors = []; - // some run time checks to help the end users. - if (!(0, has_1$1.default)(lexerDefinition, exports.DEFAULT_MODE)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized without a <" + - exports.DEFAULT_MODE + - "> property in its definition\n", - type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE - }); - } - if (!(0, has_1$1.default)(lexerDefinition, exports.MODES)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized without a <" + - exports.MODES + - "> property in its definition\n", - type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY - }); - } - if ((0, has_1$1.default)(lexerDefinition, exports.MODES) && - (0, has_1$1.default)(lexerDefinition, exports.DEFAULT_MODE) && - !(0, has_1$1.default)(lexerDefinition.modes, lexerDefinition.defaultMode)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized with a ".concat(exports.DEFAULT_MODE, ": <").concat(lexerDefinition.defaultMode, ">") + - "which does not exist\n", - type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST - }); - } - if ((0, has_1$1.default)(lexerDefinition, exports.MODES)) { - (0, forEach_1.default)(lexerDefinition.modes, function (currModeValue, currModeName) { - (0, forEach_1.default)(currModeValue, function (currTokType, currIdx) { - if ((0, isUndefined_1.default)(currTokType)) { - errors.push({ - message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" + - "<".concat(currModeName, "> at index: <").concat(currIdx, ">\n"), - type: lexer_public_1.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED - }); - } - }); - }); - } - return errors; - } - exports.performRuntimeChecks = performRuntimeChecks; - function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { - var warnings = []; - var hasAnyLineBreak = false; - var allTokenTypes = (0, compact_1$1.default)((0, flatten_1.default)((0, values_1.default)(lexerDefinition.modes))); - var concreteTokenTypes = (0, reject_1$1.default)(allTokenTypes, function (currType) { return currType[PATTERN] === lexer_public_1.Lexer.NA; }); - var terminatorCharCodes = getCharCodes(lineTerminatorCharacters); - if (trackLines) { - (0, forEach_1.default)(concreteTokenTypes, function (tokType) { - var currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes); - if (currIssue !== false) { - var message = buildLineBreakIssueMessage(tokType, currIssue); - var warningDescriptor = { - message: message, - type: currIssue.issue, - tokenType: tokType - }; - warnings.push(warningDescriptor); - } - else { - // we don't want to attempt to scan if the user explicitly specified the line_breaks option. - if ((0, has_1$1.default)(tokType, "LINE_BREAKS")) { - if (tokType.LINE_BREAKS === true) { - hasAnyLineBreak = true; - } - } - else { - if ((0, reg_exp_1.canMatchCharCode)(terminatorCharCodes, tokType.PATTERN)) { - hasAnyLineBreak = true; - } - } - } - }); - } - if (trackLines && !hasAnyLineBreak) { - warnings.push({ - message: "Warning: No LINE_BREAKS Found.\n" + - "\tThis Lexer has been defined to track line and column information,\n" + - "\tBut none of the Token Types can be identified as matching a line terminator.\n" + - "\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n" + - "\tfor details.", - type: lexer_public_1.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS - }); - } - return warnings; - } - exports.performWarningRuntimeChecks = performWarningRuntimeChecks; - function cloneEmptyGroups(emptyGroups) { - var clonedResult = {}; - var groupKeys = (0, keys_1$1.default)(emptyGroups); - (0, forEach_1.default)(groupKeys, function (currKey) { - var currGroupValue = emptyGroups[currKey]; - /* istanbul ignore else */ - if ((0, isArray_1.default)(currGroupValue)) { - clonedResult[currKey] = []; - } - else { - throw Error("non exhaustive match"); - } - }); - return clonedResult; - } - exports.cloneEmptyGroups = cloneEmptyGroups; - // TODO: refactor to avoid duplication - function isCustomPattern(tokenType) { - var pattern = tokenType.PATTERN; - /* istanbul ignore else */ - if ((0, isRegExp_1.default)(pattern)) { - return false; - } - else if ((0, isFunction_1$1.default)(pattern)) { - // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object - return true; - } - else if ((0, has_1$1.default)(pattern, "exec")) { - // ICustomPattern - return true; - } - else if ((0, isString_1.default)(pattern)) { - return false; - } - else { - throw Error("non exhaustive match"); - } - } - exports.isCustomPattern = isCustomPattern; - function isShortPattern(pattern) { - if ((0, isString_1.default)(pattern) && pattern.length === 1) { - return pattern.charCodeAt(0); - } - else { - return false; - } - } - exports.isShortPattern = isShortPattern; - /** - * Faster than using a RegExp for default newline detection during lexing. - */ - exports.LineTerminatorOptimizedTester = { - // implements /\n|\r\n?/g.test - test: function (text) { - var len = text.length; - for (var i = this.lastIndex; i < len; i++) { - var c = text.charCodeAt(i); - if (c === 10) { - this.lastIndex = i + 1; - return true; - } - else if (c === 13) { - if (text.charCodeAt(i + 1) === 10) { - this.lastIndex = i + 2; - } - else { - this.lastIndex = i + 1; - } - return true; - } - } - return false; - }, - lastIndex: 0 - }; - function checkLineBreaksIssues(tokType, lineTerminatorCharCodes) { - if ((0, has_1$1.default)(tokType, "LINE_BREAKS")) { - // if the user explicitly declared the line_breaks option we will respect their choice - // and assume it is correct. - return false; - } - else { - /* istanbul ignore else */ - if ((0, isRegExp_1.default)(tokType.PATTERN)) { - try { - // TODO: why is the casting suddenly needed? - (0, reg_exp_1.canMatchCharCode)(lineTerminatorCharCodes, tokType.PATTERN); - } - catch (e) { - /* istanbul ignore next - to test this we would have to mock to throw an error */ - return { - issue: lexer_public_1.LexerDefinitionErrorType.IDENTIFY_TERMINATOR, - errMsg: e.message - }; - } - return false; - } - else if ((0, isString_1.default)(tokType.PATTERN)) { - // string literal patterns can always be analyzed to detect line terminator usage - return false; - } - else if (isCustomPattern(tokType)) { - // custom token types - return { issue: lexer_public_1.LexerDefinitionErrorType.CUSTOM_LINE_BREAK }; - } - else { - throw Error("non exhaustive match"); - } - } - } - function buildLineBreakIssueMessage(tokType, details) { - /* istanbul ignore else */ - if (details.issue === lexer_public_1.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) { - return ("Warning: unable to identify line terminator usage in pattern.\n" + - "\tThe problem is in the <".concat(tokType.name, "> Token Type\n") + - "\t Root cause: ".concat(details.errMsg, ".\n") + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR"); - } - else if (details.issue === lexer_public_1.LexerDefinitionErrorType.CUSTOM_LINE_BREAK) { - return ("Warning: A Custom Token Pattern should specify the option.\n" + - "\tThe problem is in the <".concat(tokType.name, "> Token Type\n") + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK"); - } - else { - throw Error("non exhaustive match"); - } - } - exports.buildLineBreakIssueMessage = buildLineBreakIssueMessage; - function getCharCodes(charsOrCodes) { - var charCodes = (0, map_1.default)(charsOrCodes, function (numOrString) { - if ((0, isString_1.default)(numOrString)) { - return numOrString.charCodeAt(0); - } - else { - return numOrString; - } - }); - return charCodes; - } - function addToMapOfArrays(map, key, value) { - if (map[key] === undefined) { - map[key] = [value]; - } - else { - map[key].push(value); - } - } - exports.minOptimizationVal = 256; - /** - * We are mapping charCode above ASCI (256) into buckets each in the size of 256. - * This is because ASCI are the most common start chars so each one of those will get its own - * possible token configs vector. - * - * Tokens starting with charCodes "above" ASCI are uncommon, so we can "afford" - * to place these into buckets of possible token configs, What we gain from - * this is avoiding the case of creating an optimization 'charCodeToPatternIdxToConfig' - * which would contain 10,000+ arrays of small size (e.g unicode Identifiers scenario). - * Our 'charCodeToPatternIdxToConfig' max size will now be: - * 256 + (2^16 / 2^8) - 1 === 511 - * - * note the hack for fast division integer part extraction - * See: https://stackoverflow.com/a/4228528 - */ - var charCodeToOptimizedIdxMap = []; - function charCodeToOptimizedIndex(charCode) { - return charCode < exports.minOptimizationVal - ? charCode - : charCodeToOptimizedIdxMap[charCode]; - } - exports.charCodeToOptimizedIndex = charCodeToOptimizedIndex; - /** - * This is a compromise between cold start / hot running performance - * Creating this array takes ~3ms on a modern machine, - * But if we perform the computation at runtime as needed the CSS Lexer benchmark - * performance degrades by ~10% - * - * TODO: Perhaps it should be lazy initialized only if a charCode > 255 is used. - */ - function initCharCodeToOptimizedIndexMap() { - if ((0, isEmpty_1.default)(charCodeToOptimizedIdxMap)) { - charCodeToOptimizedIdxMap = new Array(65536); - for (var i = 0; i < 65536; i++) { - charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i; - } - } - } - -} (lexer)); - return lexer; -} -/** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ + var outerPropTypes = outerMemoType && outerMemoType.propTypes; -function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; -} + if (outerPropTypes) { + checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps) + 'prop', getComponentNameFromType(outerMemoType)); + } + } + } + } -var last_1$1 = last; + if (current !== null) { + var prevProps = current.memoizedProps; -var tokens = {}; + if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload. + workInProgress.type === current.type )) { + didReceiveUpdate = false; -(function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isTokenType = exports.hasExtendingTokensTypesMapProperty = exports.hasExtendingTokensTypesProperty = exports.hasCategoriesProperty = exports.hasShortKeyProperty = exports.singleAssignCategoriesToksMap = exports.assignCategoriesMapProp = exports.assignCategoriesTokensProp = exports.assignTokenDefaultProps = exports.expandCategories = exports.augmentTokenTypes = exports.tokenIdxToClass = exports.tokenShortNameIdx = exports.tokenStructuredMatcherNoCategories = exports.tokenStructuredMatcher = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var compact_1$1 = __importDefault(compact_1); - var isArray_1 = __importDefault(isArray_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var difference_1$1 = __importDefault(difference_1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var has_1$1 = __importDefault(has_1); - var includes_1 = __importDefault(includes_1$2); - var clone_1 = __importDefault(clone_1$1); - function tokenStructuredMatcher(tokInstance, tokConstructor) { - var instanceType = tokInstance.tokenTypeIdx; - if (instanceType === tokConstructor.tokenTypeIdx) { - return true; - } - else { - return (tokConstructor.isParent === true && - tokConstructor.categoryMatchesMap[instanceType] === true); - } - } - exports.tokenStructuredMatcher = tokenStructuredMatcher; - // Optimized tokenMatcher in case our grammar does not use token categories - // Being so tiny it is much more likely to be in-lined and this avoid the function call overhead - function tokenStructuredMatcherNoCategories(token, tokType) { - return token.tokenTypeIdx === tokType.tokenTypeIdx; - } - exports.tokenStructuredMatcherNoCategories = tokenStructuredMatcherNoCategories; - exports.tokenShortNameIdx = 1; - exports.tokenIdxToClass = {}; - function augmentTokenTypes(tokenTypes) { - // collect the parent Token Types as well. - var tokenTypesAndParents = expandCategories(tokenTypes); - // add required tokenType and categoryMatches properties - assignTokenDefaultProps(tokenTypesAndParents); - // fill up the categoryMatches - assignCategoriesMapProp(tokenTypesAndParents); - assignCategoriesTokensProp(tokenTypesAndParents); - (0, forEach_1.default)(tokenTypesAndParents, function (tokType) { - tokType.isParent = tokType.categoryMatches.length > 0; - }); - } - exports.augmentTokenTypes = augmentTokenTypes; - function expandCategories(tokenTypes) { - var result = (0, clone_1.default)(tokenTypes); - var categories = tokenTypes; - var searching = true; - while (searching) { - categories = (0, compact_1$1.default)((0, flatten_1.default)((0, map_1.default)(categories, function (currTokType) { return currTokType.CATEGORIES; }))); - var newCategories = (0, difference_1$1.default)(categories, result); - result = result.concat(newCategories); - if ((0, isEmpty_1.default)(newCategories)) { - searching = false; - } - else { - categories = newCategories; - } + if (!checkScheduledUpdateOrContext(current, renderLanes)) { + // The pending lanes were cleared at the beginning of beginWork. We're + // about to bail out, but there might be other lanes that weren't + // included in the current render. Usually, the priority level of the + // remaining updates is accumulated during the evaluation of the + // component (i.e. when processing the update queue). But since since + // we're bailing out early *without* evaluating the component, we need + // to account for it here, too. Reset to the value of the current fiber. + // NOTE: This only applies to SimpleMemoComponent, not MemoComponent, + // because a MemoComponent fiber does not have hooks or an update queue; + // rather, it wraps around an inner component, which may or may not + // contains hooks. + // TODO: Move the reset at in beginWork out of the common path so that + // this is no longer necessary. + workInProgress.lanes = current.lanes; + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { + // This is a special case that only exists for legacy mode. + // See https://github.com/facebook/react/pull/19216. + didReceiveUpdate = true; + } } - return result; - } - exports.expandCategories = expandCategories; - function assignTokenDefaultProps(tokenTypes) { - (0, forEach_1.default)(tokenTypes, function (currTokType) { - if (!hasShortKeyProperty(currTokType)) { - exports.tokenIdxToClass[exports.tokenShortNameIdx] = currTokType; - currTokType.tokenTypeIdx = exports.tokenShortNameIdx++; - } - // CATEGORIES? : TokenType | TokenType[] - if (hasCategoriesProperty(currTokType) && - !(0, isArray_1.default)(currTokType.CATEGORIES) - // && - // !isUndefined(currTokType.CATEGORIES.PATTERN) - ) { - currTokType.CATEGORIES = [currTokType.CATEGORIES]; - } - if (!hasCategoriesProperty(currTokType)) { - currTokType.CATEGORIES = []; - } - if (!hasExtendingTokensTypesProperty(currTokType)) { - currTokType.categoryMatches = []; - } - if (!hasExtendingTokensTypesMapProperty(currTokType)) { - currTokType.categoryMatchesMap = {}; - } - }); - } - exports.assignTokenDefaultProps = assignTokenDefaultProps; - function assignCategoriesTokensProp(tokenTypes) { - (0, forEach_1.default)(tokenTypes, function (currTokType) { - // avoid duplications - currTokType.categoryMatches = []; - (0, forEach_1.default)(currTokType.categoryMatchesMap, function (val, key) { - currTokType.categoryMatches.push(exports.tokenIdxToClass[key].tokenTypeIdx); - }); - }); - } - exports.assignCategoriesTokensProp = assignCategoriesTokensProp; - function assignCategoriesMapProp(tokenTypes) { - (0, forEach_1.default)(tokenTypes, function (currTokType) { - singleAssignCategoriesToksMap([], currTokType); - }); - } - exports.assignCategoriesMapProp = assignCategoriesMapProp; - function singleAssignCategoriesToksMap(path, nextNode) { - (0, forEach_1.default)(path, function (pathNode) { - nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true; - }); - (0, forEach_1.default)(nextNode.CATEGORIES, function (nextCategory) { - var newPath = path.concat(nextNode); - // avoids infinite loops due to cyclic categories. - if (!(0, includes_1.default)(newPath, nextCategory)) { - singleAssignCategoriesToksMap(newPath, nextCategory); - } - }); - } - exports.singleAssignCategoriesToksMap = singleAssignCategoriesToksMap; - function hasShortKeyProperty(tokType) { - return (0, has_1$1.default)(tokType, "tokenTypeIdx"); - } - exports.hasShortKeyProperty = hasShortKeyProperty; - function hasCategoriesProperty(tokType) { - return (0, has_1$1.default)(tokType, "CATEGORIES"); - } - exports.hasCategoriesProperty = hasCategoriesProperty; - function hasExtendingTokensTypesProperty(tokType) { - return (0, has_1$1.default)(tokType, "categoryMatches"); - } - exports.hasExtendingTokensTypesProperty = hasExtendingTokensTypesProperty; - function hasExtendingTokensTypesMapProperty(tokType) { - return (0, has_1$1.default)(tokType, "categoryMatchesMap"); - } - exports.hasExtendingTokensTypesMapProperty = hasExtendingTokensTypesMapProperty; - function isTokenType(tokType) { - return (0, has_1$1.default)(tokType, "tokenTypeIdx"); + } + + return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes); } - exports.isTokenType = isTokenType; - -} (tokens)); -var lexer_errors_public = {}; + function updateOffscreenComponent(current, workInProgress, renderLanes) { + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; + var prevState = current !== null ? current.memoizedState : null; -Object.defineProperty(lexer_errors_public, "__esModule", { value: true }); -lexer_errors_public.defaultLexerErrorProvider = void 0; -lexer_errors_public.defaultLexerErrorProvider = { - buildUnableToPopLexerModeMessage: function (token) { - return "Unable to pop Lexer Mode after encountering Token ->".concat(token.image, "<- The Mode Stack is empty"); - }, - buildUnexpectedCharactersMessage: function (fullText, startOffset, length, line, column) { - return ("unexpected character: ->".concat(fullText.charAt(startOffset), "<- at offset: ").concat(startOffset, ",") + " skipped ".concat(length, " characters.")); - } -}; + if (nextProps.mode === 'hidden' || enableLegacyHidden ) { + // Rendering a hidden tree. + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + // In legacy sync mode, don't defer the subtree. Render it now. + var nextState = { + baseLanes: NoLanes, + cachePool: null + }; + workInProgress.memoizedState = nextState; -var hasRequiredLexer_public; + pushRenderLanes(workInProgress, renderLanes); + } else if (!includesSomeLane(renderLanes, OffscreenLane)) { + var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out + // and resume this tree later. -function requireLexer_public () { - if (hasRequiredLexer_public) return lexer_public; - hasRequiredLexer_public = 1; - (function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Lexer = exports.LexerDefinitionErrorType = void 0; - var lexer_1 = requireLexer(); - var noop_1$1 = __importDefault(noop_1); - var isEmpty_1 = __importDefault(isEmpty_1$1); - var isArray_1 = __importDefault(isArray_1$1); - var last_1 = __importDefault(last_1$1); - var reject_1$1 = __importDefault(reject_1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var keys_1$1 = __importDefault(keys_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var identity_1$1 = __importDefault(identity_1); - var assign_1 = __importDefault(assign_1$3); - var reduce_1 = __importDefault(reduce_1$1); - var clone_1 = __importDefault(clone_1$1); - var utils_1 = api$2; - var tokens_1 = tokens; - var lexer_errors_public_1 = lexer_errors_public; - var reg_exp_parser_1 = reg_exp_parser; - (function (LexerDefinitionErrorType) { - LexerDefinitionErrorType[LexerDefinitionErrorType["MISSING_PATTERN"] = 0] = "MISSING_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_PATTERN"] = 1] = "INVALID_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["EOI_ANCHOR_FOUND"] = 2] = "EOI_ANCHOR_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["UNSUPPORTED_FLAGS_FOUND"] = 3] = "UNSUPPORTED_FLAGS_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["DUPLICATE_PATTERNS_FOUND"] = 4] = "DUPLICATE_PATTERNS_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_GROUP_TYPE_FOUND"] = 5] = "INVALID_GROUP_TYPE_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["PUSH_MODE_DOES_NOT_EXIST"] = 6] = "PUSH_MODE_DOES_NOT_EXIST"; - LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"] = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"; - LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"] = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"; - LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"] = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"; - LexerDefinitionErrorType[LexerDefinitionErrorType["LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"] = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"; - LexerDefinitionErrorType[LexerDefinitionErrorType["SOI_ANCHOR_FOUND"] = 11] = "SOI_ANCHOR_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["EMPTY_MATCH_PATTERN"] = 12] = "EMPTY_MATCH_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["NO_LINE_BREAKS_FLAGS"] = 13] = "NO_LINE_BREAKS_FLAGS"; - LexerDefinitionErrorType[LexerDefinitionErrorType["UNREACHABLE_PATTERN"] = 14] = "UNREACHABLE_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["IDENTIFY_TERMINATOR"] = 15] = "IDENTIFY_TERMINATOR"; - LexerDefinitionErrorType[LexerDefinitionErrorType["CUSTOM_LINE_BREAK"] = 16] = "CUSTOM_LINE_BREAK"; - })(exports.LexerDefinitionErrorType || (exports.LexerDefinitionErrorType = {})); - var DEFAULT_LEXER_CONFIG = { - deferDefinitionErrorsHandling: false, - positionTracking: "full", - lineTerminatorsPattern: /\n|\r\n?/g, - lineTerminatorCharacters: ["\n", "\r"], - ensureOptimizations: false, - safeMode: false, - errorMessageProvider: lexer_errors_public_1.defaultLexerErrorProvider, - traceInitPerf: false, - skipValidations: false - }; - Object.freeze(DEFAULT_LEXER_CONFIG); - var Lexer = /** @class */ (function () { - function Lexer(lexerDefinition, config) { - if (config === void 0) { config = DEFAULT_LEXER_CONFIG; } - var _this = this; - this.lexerDefinition = lexerDefinition; - this.lexerDefinitionErrors = []; - this.lexerDefinitionWarning = []; - this.patternIdxToConfig = {}; - this.charCodeToPatternIdxToConfig = {}; - this.modes = []; - this.emptyGroups = {}; - this.trackStartLines = true; - this.trackEndLines = true; - this.hasCustom = false; - this.canModeBeOptimized = {}; - // Duplicated from the parser's perf trace trait to allow future extraction - // of the lexer to a separate package. - this.TRACE_INIT = function (phaseDesc, phaseImpl) { - // No need to optimize this using NOOP pattern because - // It is not called in a hot spot... - if (_this.traceInitPerf === true) { - _this.traceInitIndent++; - var indent = new Array(_this.traceInitIndent + 1).join("\t"); - if (_this.traceInitIndent < _this.traceInitMaxIdent) { - console.log("".concat(indent, "--> <").concat(phaseDesc, ">")); - } - var _a = (0, utils_1.timer)(phaseImpl), time = _a.time, value = _a.value; - /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */ - var traceMethod = time > 10 ? console.warn : console.log; - if (_this.traceInitIndent < _this.traceInitMaxIdent) { - traceMethod("".concat(indent, "<-- <").concat(phaseDesc, "> time: ").concat(time, "ms")); - } - _this.traceInitIndent--; - return value; - } - else { - return phaseImpl(); - } - }; - if (typeof config === "boolean") { - throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\n" + - "a boolean 2nd argument is no longer supported"); - } - // todo: defaults func? - this.config = (0, assign_1.default)({}, DEFAULT_LEXER_CONFIG, config); - var traceInitVal = this.config.traceInitPerf; - if (traceInitVal === true) { - this.traceInitMaxIdent = Infinity; - this.traceInitPerf = true; - } - else if (typeof traceInitVal === "number") { - this.traceInitMaxIdent = traceInitVal; - this.traceInitPerf = true; - } - this.traceInitIndent = -1; - this.TRACE_INIT("Lexer Constructor", function () { - var actualDefinition; - var hasOnlySingleMode = true; - _this.TRACE_INIT("Lexer Config handling", function () { - if (_this.config.lineTerminatorsPattern === - DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) { - // optimized built-in implementation for the defaults definition of lineTerminators - _this.config.lineTerminatorsPattern = lexer_1.LineTerminatorOptimizedTester; - } - else { - if (_this.config.lineTerminatorCharacters === - DEFAULT_LEXER_CONFIG.lineTerminatorCharacters) { - throw Error("Error: Missing property on the Lexer config.\n" + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS"); - } - } - if (config.safeMode && config.ensureOptimizations) { - throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.'); - } - _this.trackStartLines = /full|onlyStart/i.test(_this.config.positionTracking); - _this.trackEndLines = /full/i.test(_this.config.positionTracking); - // Convert SingleModeLexerDefinition into a IMultiModeLexerDefinition. - if ((0, isArray_1.default)(lexerDefinition)) { - actualDefinition = { - modes: { defaultMode: (0, clone_1.default)(lexerDefinition) }, - defaultMode: lexer_1.DEFAULT_MODE - }; - } - else { - // no conversion needed, input should already be a IMultiModeLexerDefinition - hasOnlySingleMode = false; - actualDefinition = (0, clone_1.default)(lexerDefinition); - } - }); - if (_this.config.skipValidations === false) { - _this.TRACE_INIT("performRuntimeChecks", function () { - _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat((0, lexer_1.performRuntimeChecks)(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters)); - }); - _this.TRACE_INIT("performWarningRuntimeChecks", function () { - _this.lexerDefinitionWarning = _this.lexerDefinitionWarning.concat((0, lexer_1.performWarningRuntimeChecks)(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters)); - }); - } - // for extra robustness to avoid throwing an none informative error message - actualDefinition.modes = actualDefinition.modes - ? actualDefinition.modes - : {}; - // an error of undefined TokenTypes will be detected in "performRuntimeChecks" above. - // this transformation is to increase robustness in the case of partially invalid lexer definition. - (0, forEach_1.default)(actualDefinition.modes, function (currModeValue, currModeName) { - actualDefinition.modes[currModeName] = (0, reject_1$1.default)(currModeValue, function (currTokType) { return (0, isUndefined_1.default)(currTokType); }); - }); - var allModeNames = (0, keys_1$1.default)(actualDefinition.modes); - (0, forEach_1.default)(actualDefinition.modes, function (currModDef, currModName) { - _this.TRACE_INIT("Mode: <".concat(currModName, "> processing"), function () { - _this.modes.push(currModName); - if (_this.config.skipValidations === false) { - _this.TRACE_INIT("validatePatterns", function () { - _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat((0, lexer_1.validatePatterns)(currModDef, allModeNames)); - }); - } - // If definition errors were encountered, the analysis phase may fail unexpectedly/ - // Considering a lexer with definition errors may never be used, there is no point - // to performing the analysis anyhow... - if ((0, isEmpty_1.default)(_this.lexerDefinitionErrors)) { - (0, tokens_1.augmentTokenTypes)(currModDef); - var currAnalyzeResult_1; - _this.TRACE_INIT("analyzeTokenTypes", function () { - currAnalyzeResult_1 = (0, lexer_1.analyzeTokenTypes)(currModDef, { - lineTerminatorCharacters: _this.config.lineTerminatorCharacters, - positionTracking: config.positionTracking, - ensureOptimizations: config.ensureOptimizations, - safeMode: config.safeMode, - tracer: _this.TRACE_INIT - }); - }); - _this.patternIdxToConfig[currModName] = - currAnalyzeResult_1.patternIdxToConfig; - _this.charCodeToPatternIdxToConfig[currModName] = - currAnalyzeResult_1.charCodeToPatternIdxToConfig; - _this.emptyGroups = (0, assign_1.default)({}, _this.emptyGroups, currAnalyzeResult_1.emptyGroups); - _this.hasCustom = currAnalyzeResult_1.hasCustom || _this.hasCustom; - _this.canModeBeOptimized[currModName] = - currAnalyzeResult_1.canBeOptimized; - } - }); - }); - _this.defaultMode = actualDefinition.defaultMode; - if (!(0, isEmpty_1.default)(_this.lexerDefinitionErrors) && - !_this.config.deferDefinitionErrorsHandling) { - var allErrMessages = (0, map_1.default)(_this.lexerDefinitionErrors, function (error) { - return error.message; - }); - var allErrMessagesString = allErrMessages.join("-----------------------\n"); - throw new Error("Errors detected in definition of Lexer:\n" + allErrMessagesString); - } - // Only print warning if there are no errors, This will avoid pl - (0, forEach_1.default)(_this.lexerDefinitionWarning, function (warningDescriptor) { - (0, utils_1.PRINT_WARNING)(warningDescriptor.message); - }); - _this.TRACE_INIT("Choosing sub-methods implementations", function () { - // Choose the relevant internal implementations for this specific parser. - // These implementations should be in-lined by the JavaScript engine - // to provide optimal performance in each scenario. - if (lexer_1.SUPPORT_STICKY) { - _this.chopInput = identity_1$1.default; - _this.match = _this.matchWithTest; - } - else { - _this.updateLastIndex = noop_1$1.default; - _this.match = _this.matchWithExec; - } - if (hasOnlySingleMode) { - _this.handleModes = noop_1$1.default; - } - if (_this.trackStartLines === false) { - _this.computeNewColumn = identity_1$1.default; - } - if (_this.trackEndLines === false) { - _this.updateTokenEndLineColumnLocation = noop_1$1.default; - } - if (/full/i.test(_this.config.positionTracking)) { - _this.createTokenInstance = _this.createFullToken; - } - else if (/onlyStart/i.test(_this.config.positionTracking)) { - _this.createTokenInstance = _this.createStartOnlyToken; - } - else if (/onlyOffset/i.test(_this.config.positionTracking)) { - _this.createTokenInstance = _this.createOffsetOnlyToken; - } - else { - throw Error("Invalid config option: \"".concat(_this.config.positionTracking, "\"")); - } - if (_this.hasCustom) { - _this.addToken = _this.addTokenUsingPush; - _this.handlePayload = _this.handlePayloadWithCustom; - } - else { - _this.addToken = _this.addTokenUsingMemberAccess; - _this.handlePayload = _this.handlePayloadNoCustom; - } - }); - _this.TRACE_INIT("Failed Optimization Warnings", function () { - var unOptimizedModes = (0, reduce_1.default)(_this.canModeBeOptimized, function (cannotBeOptimized, canBeOptimized, modeName) { - if (canBeOptimized === false) { - cannotBeOptimized.push(modeName); - } - return cannotBeOptimized; - }, []); - if (config.ensureOptimizations && !(0, isEmpty_1.default)(unOptimizedModes)) { - throw Error("Lexer Modes: < ".concat(unOptimizedModes.join(", "), " > cannot be optimized.\n") + - '\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n' + - "\t Or inspect the console log for details on how to resolve these issues."); - } - }); - _this.TRACE_INIT("clearRegExpParserCache", function () { - (0, reg_exp_parser_1.clearRegExpParserCache)(); - }); - _this.TRACE_INIT("toFastProperties", function () { - (0, utils_1.toFastProperties)(_this); - }); - }); - } - Lexer.prototype.tokenize = function (text, initialMode) { - if (initialMode === void 0) { initialMode = this.defaultMode; } - if (!(0, isEmpty_1.default)(this.lexerDefinitionErrors)) { - var allErrMessages = (0, map_1.default)(this.lexerDefinitionErrors, function (error) { - return error.message; - }); - var allErrMessagesString = allErrMessages.join("-----------------------\n"); - throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" + - allErrMessagesString); - } - return this.tokenizeInternal(text, initialMode); - }; - // There is quite a bit of duplication between this and "tokenizeInternalLazy" - // This is intentional due to performance considerations. - // this method also used quite a bit of `!` none null assertions because it is too optimized - // for `tsc` to always understand it is "safe" - Lexer.prototype.tokenizeInternal = function (text, initialMode) { - var _this = this; - var i, j, k, matchAltImage, longerAlt, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, msg, match; - var orgText = text; - var orgLength = orgText.length; - var offset = 0; - var matchedTokensIndex = 0; - // initializing the tokensArray to the "guessed" size. - // guessing too little will still reduce the number of array re-sizes on pushes. - // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory - // but would still have a faster runtime by avoiding (All but one) array resizing. - var guessedNumberOfTokens = this.hasCustom - ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements. - : Math.floor(text.length / 10); - var matchedTokens = new Array(guessedNumberOfTokens); - var errors = []; - var line = this.trackStartLines ? 1 : undefined; - var column = this.trackStartLines ? 1 : undefined; - var groups = (0, lexer_1.cloneEmptyGroups)(this.emptyGroups); - var trackLines = this.trackStartLines; - var lineTerminatorPattern = this.config.lineTerminatorsPattern; - var currModePatternsLength = 0; - var patternIdxToConfig = []; - var currCharCodeToPatternIdxToConfig = []; - var modeStack = []; - var emptyArray = []; - Object.freeze(emptyArray); - var getPossiblePatterns; - function getPossiblePatternsSlow() { - return patternIdxToConfig; - } - function getPossiblePatternsOptimized(charCode) { - var optimizedCharIdx = (0, lexer_1.charCodeToOptimizedIndex)(charCode); - var possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx]; - if (possiblePatterns === undefined) { - return emptyArray; - } - else { - return possiblePatterns; - } - } - var pop_mode = function (popToken) { - // TODO: perhaps avoid this error in the edge case there is no more input? - if (modeStack.length === 1 && - // if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition" - // So no error should occur. - popToken.tokenType.PUSH_MODE === undefined) { - // if we try to pop the last mode there lexer will no longer have ANY mode. - // thus the pop is ignored, an error will be created and the lexer will continue parsing in the previous mode. - var msg_1 = _this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken); - errors.push({ - offset: popToken.startOffset, - line: popToken.startLine, - column: popToken.startColumn, - length: popToken.image.length, - message: msg_1 - }); - } - else { - modeStack.pop(); - var newMode = (0, last_1.default)(modeStack); - patternIdxToConfig = _this.patternIdxToConfig[newMode]; - currCharCodeToPatternIdxToConfig = - _this.charCodeToPatternIdxToConfig[newMode]; - currModePatternsLength = patternIdxToConfig.length; - var modeCanBeOptimized = _this.canModeBeOptimized[newMode] && _this.config.safeMode === false; - if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { - getPossiblePatterns = getPossiblePatternsOptimized; - } - else { - getPossiblePatterns = getPossiblePatternsSlow; - } - } - }; - function push_mode(newMode) { - modeStack.push(newMode); - currCharCodeToPatternIdxToConfig = - this.charCodeToPatternIdxToConfig[newMode]; - patternIdxToConfig = this.patternIdxToConfig[newMode]; - currModePatternsLength = patternIdxToConfig.length; - currModePatternsLength = patternIdxToConfig.length; - var modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false; - if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { - getPossiblePatterns = getPossiblePatternsOptimized; - } - else { - getPossiblePatterns = getPossiblePatternsSlow; - } - } - // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not - // seem to matter performance wise. - push_mode.call(this, initialMode); - var currConfig; - while (offset < orgLength) { - matchedImage = null; - var nextCharCode = orgText.charCodeAt(offset); - var chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode); - var chosenPatternsLength = chosenPatternIdxToConfig.length; - for (i = 0; i < chosenPatternsLength; i++) { - currConfig = chosenPatternIdxToConfig[i]; - var currPattern = currConfig.pattern; - payload = null; - // manually in-lined because > 600 chars won't be in-lined in V8 - var singleCharCode = currConfig.short; - if (singleCharCode !== false) { - if (nextCharCode === singleCharCode) { - // single character string - matchedImage = currPattern; - } - } - else if (currConfig.isCustom === true) { - match = currPattern.exec(orgText, offset, matchedTokens, groups); - if (match !== null) { - matchedImage = match[0]; - if (match.payload !== undefined) { - payload = match.payload; - } - } - else { - matchedImage = null; - } - } - else { - this.updateLastIndex(currPattern, offset); - matchedImage = this.match(currPattern, text, offset); - } - if (matchedImage !== null) { - // even though this pattern matched we must try a another longer alternative. - // this can be used to prioritize keywords over identifiers - longerAlt = currConfig.longerAlt; - if (longerAlt !== undefined) { - // TODO: micro optimize, avoid extra prop access - // by saving/linking longerAlt on the original config? - var longerAltLength = longerAlt.length; - for (k = 0; k < longerAltLength; k++) { - var longerAltConfig = patternIdxToConfig[longerAlt[k]]; - var longerAltPattern = longerAltConfig.pattern; - altPayload = null; - // single Char can never be a longer alt so no need to test it. - // manually in-lined because > 600 chars won't be in-lined in V8 - if (longerAltConfig.isCustom === true) { - match = longerAltPattern.exec(orgText, offset, matchedTokens, groups); - if (match !== null) { - matchAltImage = match[0]; - if (match.payload !== undefined) { - altPayload = match.payload; - } - } - else { - matchAltImage = null; - } - } - else { - this.updateLastIndex(longerAltPattern, offset); - matchAltImage = this.match(longerAltPattern, text, offset); - } - if (matchAltImage && matchAltImage.length > matchedImage.length) { - matchedImage = matchAltImage; - payload = altPayload; - currConfig = longerAltConfig; - // Exit the loop early after matching one of the longer alternatives - // The first matched alternative takes precedence - break; - } - } - } - break; - } - } - // successful match - if (matchedImage !== null) { - imageLength = matchedImage.length; - group = currConfig.group; - if (group !== undefined) { - tokType = currConfig.tokenTypeIdx; - // TODO: "offset + imageLength" and the new column may be computed twice in case of "full" location information inside - // createFullToken method - newToken = this.createTokenInstance(matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength); - this.handlePayload(newToken, payload); - // TODO: optimize NOOP in case there are no special groups? - if (group === false) { - matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken); - } - else { - groups[group].push(newToken); - } - } - text = this.chopInput(text, imageLength); - offset = offset + imageLength; - // TODO: with newlines the column may be assigned twice - column = this.computeNewColumn(column, imageLength); - if (trackLines === true && currConfig.canLineTerminator === true) { - var numOfLTsInMatch = 0; - var foundTerminator = void 0; - var lastLTEndOffset = void 0; - lineTerminatorPattern.lastIndex = 0; - do { - foundTerminator = lineTerminatorPattern.test(matchedImage); - if (foundTerminator === true) { - lastLTEndOffset = lineTerminatorPattern.lastIndex - 1; - numOfLTsInMatch++; - } - } while (foundTerminator === true); - if (numOfLTsInMatch !== 0) { - line = line + numOfLTsInMatch; - column = imageLength - lastLTEndOffset; - this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength); - } - } - // will be NOOP if no modes present - this.handleModes(currConfig, pop_mode, push_mode, newToken); - } - else { - // error recovery, drop characters until we identify a valid token's start point - var errorStartOffset = offset; - var errorLine = line; - var errorColumn = column; - var foundResyncPoint = false; - while (!foundResyncPoint && offset < orgLength) { - // drop chars until we succeed in matching something - orgText.charCodeAt(offset); - // Identity Func (when sticky flag is enabled) - text = this.chopInput(text, 1); - offset++; - for (j = 0; j < currModePatternsLength; j++) { - var currConfig_1 = patternIdxToConfig[j]; - var currPattern = currConfig_1.pattern; - // manually in-lined because > 600 chars won't be in-lined in V8 - var singleCharCode = currConfig_1.short; - if (singleCharCode !== false) { - if (orgText.charCodeAt(offset) === singleCharCode) { - // single character string - foundResyncPoint = true; - } - } - else if (currConfig_1.isCustom === true) { - foundResyncPoint = - currPattern.exec(orgText, offset, matchedTokens, groups) !== null; - } - else { - this.updateLastIndex(currPattern, offset); - foundResyncPoint = currPattern.exec(text) !== null; - } - if (foundResyncPoint === true) { - break; - } - } - } - errLength = offset - errorStartOffset; - // at this point we either re-synced or reached the end of the input text - msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText, errorStartOffset, errLength, errorLine, errorColumn); - errors.push({ - offset: errorStartOffset, - line: errorLine, - column: errorColumn, - length: errLength, - message: msg - }); - } - } - // if we do have custom patterns which push directly into the - // TODO: custom tokens should not push directly?? - if (!this.hasCustom) { - // if we guessed a too large size for the tokens array this will shrink it to the right size. - matchedTokens.length = matchedTokensIndex; - } - return { - tokens: matchedTokens, - groups: groups, - errors: errors - }; - }; - Lexer.prototype.handleModes = function (config, pop_mode, push_mode, newToken) { - if (config.pop === true) { - // need to save the PUSH_MODE property as if the mode is popped - // patternIdxToPopMode is updated to reflect the new mode after popping the stack - var pushMode = config.push; - pop_mode(newToken); - if (pushMode !== undefined) { - push_mode.call(this, pushMode); - } - } - else if (config.push !== undefined) { - push_mode.call(this, config.push); - } - }; - Lexer.prototype.chopInput = function (text, length) { - return text.substring(length); - }; - Lexer.prototype.updateLastIndex = function (regExp, newLastIndex) { - regExp.lastIndex = newLastIndex; - }; - // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler - Lexer.prototype.updateTokenEndLineColumnLocation = function (newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) { - var lastCharIsLT, fixForEndingInLT; - if (group !== undefined) { - // a none skipped multi line Token, need to update endLine/endColumn - lastCharIsLT = lastLTIdx === imageLength - 1; - fixForEndingInLT = lastCharIsLT ? -1 : 0; - if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) { - // if a token ends in a LT that last LT only affects the line numbering of following Tokens - newToken.endLine = line + fixForEndingInLT; - // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd) - // inclusive to exclusive range. - newToken.endColumn = column - 1 + -fixForEndingInLT; - } - // else single LT in the last character of a token, no need to modify the endLine/EndColumn - } - }; - Lexer.prototype.computeNewColumn = function (oldColumn, imageLength) { - return oldColumn + imageLength; - }; - Lexer.prototype.createOffsetOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType) { - return { - image: image, - startOffset: startOffset, - tokenTypeIdx: tokenTypeIdx, - tokenType: tokenType - }; - }; - Lexer.prototype.createStartOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) { - return { - image: image, - startOffset: startOffset, - startLine: startLine, - startColumn: startColumn, - tokenTypeIdx: tokenTypeIdx, - tokenType: tokenType - }; - }; - Lexer.prototype.createFullToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) { - return { - image: image, - startOffset: startOffset, - endOffset: startOffset + imageLength - 1, - startLine: startLine, - endLine: startLine, - startColumn: startColumn, - endColumn: startColumn + imageLength - 1, - tokenTypeIdx: tokenTypeIdx, - tokenType: tokenType - }; - }; - Lexer.prototype.addTokenUsingPush = function (tokenVector, index, tokenToAdd) { - tokenVector.push(tokenToAdd); - return index; - }; - Lexer.prototype.addTokenUsingMemberAccess = function (tokenVector, index, tokenToAdd) { - tokenVector[index] = tokenToAdd; - index++; - return index; - }; - Lexer.prototype.handlePayloadNoCustom = function (token, payload) { }; - Lexer.prototype.handlePayloadWithCustom = function (token, payload) { - if (payload !== null) { - token.payload = payload; - } - }; - Lexer.prototype.matchWithTest = function (pattern, text, offset) { - var found = pattern.test(text); - if (found === true) { - return text.substring(offset, pattern.lastIndex); - } - return null; - }; - Lexer.prototype.matchWithExec = function (pattern, text) { - var regExpArray = pattern.exec(text); - return regExpArray !== null ? regExpArray[0] : null; - }; - Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will" + - "be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace."; - Lexer.NA = /NOT_APPLICABLE/; - return Lexer; - }()); - exports.Lexer = Lexer; - -} (lexer_public)); - return lexer_public; -} - -(function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.tokenMatcher = exports.createTokenInstance = exports.EOF = exports.createToken = exports.hasTokenLabel = exports.tokenName = exports.tokenLabel = void 0; - var isString_1 = __importDefault(isString_1$1); - var has_1$1 = __importDefault(has_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var lexer_public_1 = requireLexer_public(); - var tokens_1 = tokens; - function tokenLabel(tokType) { - if (hasTokenLabel(tokType)) { - return tokType.LABEL; - } - else { - return tokType.name; - } - } - exports.tokenLabel = tokenLabel; - function tokenName(tokType) { - return tokType.name; - } - exports.tokenName = tokenName; - function hasTokenLabel(obj) { - return (0, isString_1.default)(obj.LABEL) && obj.LABEL !== ""; - } - exports.hasTokenLabel = hasTokenLabel; - var PARENT = "parent"; - var CATEGORIES = "categories"; - var LABEL = "label"; - var GROUP = "group"; - var PUSH_MODE = "push_mode"; - var POP_MODE = "pop_mode"; - var LONGER_ALT = "longer_alt"; - var LINE_BREAKS = "line_breaks"; - var START_CHARS_HINT = "start_chars_hint"; - function createToken(config) { - return createTokenInternal(config); - } - exports.createToken = createToken; - function createTokenInternal(config) { - var pattern = config.pattern; - var tokenType = {}; - tokenType.name = config.name; - if (!(0, isUndefined_1.default)(pattern)) { - tokenType.PATTERN = pattern; - } - if ((0, has_1$1.default)(config, PARENT)) { - throw ("The parent property is no longer supported.\n" + - "See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details."); - } - if ((0, has_1$1.default)(config, CATEGORIES)) { - // casting to ANY as this will be fixed inside `augmentTokenTypes`` - tokenType.CATEGORIES = config[CATEGORIES]; - } - (0, tokens_1.augmentTokenTypes)([tokenType]); - if ((0, has_1$1.default)(config, LABEL)) { - tokenType.LABEL = config[LABEL]; - } - if ((0, has_1$1.default)(config, GROUP)) { - tokenType.GROUP = config[GROUP]; - } - if ((0, has_1$1.default)(config, POP_MODE)) { - tokenType.POP_MODE = config[POP_MODE]; - } - if ((0, has_1$1.default)(config, PUSH_MODE)) { - tokenType.PUSH_MODE = config[PUSH_MODE]; - } - if ((0, has_1$1.default)(config, LONGER_ALT)) { - tokenType.LONGER_ALT = config[LONGER_ALT]; - } - if ((0, has_1$1.default)(config, LINE_BREAKS)) { - tokenType.LINE_BREAKS = config[LINE_BREAKS]; - } - if ((0, has_1$1.default)(config, START_CHARS_HINT)) { - tokenType.START_CHARS_HINT = config[START_CHARS_HINT]; - } - return tokenType; - } - exports.EOF = createToken({ name: "EOF", pattern: lexer_public_1.Lexer.NA }); - (0, tokens_1.augmentTokenTypes)([exports.EOF]); - function createTokenInstance(tokType, image, startOffset, endOffset, startLine, endLine, startColumn, endColumn) { - return { - image: image, - startOffset: startOffset, - endOffset: endOffset, - startLine: startLine, - endLine: endLine, - startColumn: startColumn, - endColumn: endColumn, - tokenTypeIdx: tokType.tokenTypeIdx, - tokenType: tokType - }; - } - exports.createTokenInstance = createTokenInstance; - function tokenMatcher(token, tokType) { - return (0, tokens_1.tokenStructuredMatcher)(token, tokType); - } - exports.tokenMatcher = tokenMatcher; - -} (tokens_public)); + var nextBaseLanes; -var errors_public = {}; + if (prevState !== null) { + var prevBaseLanes = prevState.baseLanes; + nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes); + } else { + nextBaseLanes = renderLanes; + } // Schedule this fiber to re-render at offscreen priority. Then bailout. -(function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.defaultGrammarValidatorErrorProvider = exports.defaultGrammarResolverErrorProvider = exports.defaultParserErrorProvider = void 0; - var tokens_public_1 = tokens_public; - var first_1 = __importDefault(first.exports); - var map_1 = __importDefault(map_1$4); - var reduce_1 = __importDefault(reduce_1$1); - var gast_1 = api$1; - var gast_2 = api$1; - exports.defaultParserErrorProvider = { - buildMismatchTokenMessage: function (_a) { - var expected = _a.expected, actual = _a.actual; _a.previous; _a.ruleName; - var hasLabel = (0, tokens_public_1.hasTokenLabel)(expected); - var expectedMsg = hasLabel - ? "--> ".concat((0, tokens_public_1.tokenLabel)(expected), " <--") - : "token of type --> ".concat(expected.name, " <--"); - var msg = "Expecting ".concat(expectedMsg, " but found --> '").concat(actual.image, "' <--"); - return msg; - }, - buildNotAllInputParsedMessage: function (_a) { - var firstRedundant = _a.firstRedundant; _a.ruleName; - return "Redundant input, expecting EOF but found: " + firstRedundant.image; - }, - buildNoViableAltMessage: function (_a) { - var expectedPathsPerAlt = _a.expectedPathsPerAlt, actual = _a.actual; _a.previous; var customUserDescription = _a.customUserDescription; _a.ruleName; - var errPrefix = "Expecting: "; - // TODO: issue: No Viable Alternative Error may have incomplete details. #502 - var actualText = (0, first_1.default)(actual).image; - var errSuffix = "\nbut found: '" + actualText + "'"; - if (customUserDescription) { - return errPrefix + customUserDescription + errSuffix; - } - else { - var allLookAheadPaths = (0, reduce_1.default)(expectedPathsPerAlt, function (result, currAltPaths) { return result.concat(currAltPaths); }, []); - var nextValidTokenSequences = (0, map_1.default)(allLookAheadPaths, function (currPath) { - return "[".concat((0, map_1.default)(currPath, function (currTokenType) { return (0, tokens_public_1.tokenLabel)(currTokenType); }).join(", "), "]"); - }); - var nextValidSequenceItems = (0, map_1.default)(nextValidTokenSequences, function (itemMsg, idx) { return " ".concat(idx + 1, ". ").concat(itemMsg); }); - var calculatedDescription = "one of these possible Token sequences:\n".concat(nextValidSequenceItems.join("\n")); - return errPrefix + calculatedDescription + errSuffix; - } - }, - buildEarlyExitMessage: function (_a) { - var expectedIterationPaths = _a.expectedIterationPaths, actual = _a.actual, customUserDescription = _a.customUserDescription; _a.ruleName; - var errPrefix = "Expecting: "; - // TODO: issue: No Viable Alternative Error may have incomplete details. #502 - var actualText = (0, first_1.default)(actual).image; - var errSuffix = "\nbut found: '" + actualText + "'"; - if (customUserDescription) { - return errPrefix + customUserDescription + errSuffix; - } - else { - var nextValidTokenSequences = (0, map_1.default)(expectedIterationPaths, function (currPath) { - return "[".concat((0, map_1.default)(currPath, function (currTokenType) { return (0, tokens_public_1.tokenLabel)(currTokenType); }).join(","), "]"); - }); - var calculatedDescription = "expecting at least one iteration which starts with one of these possible Token sequences::\n " + - "<".concat(nextValidTokenSequences.join(" ,"), ">"); - return errPrefix + calculatedDescription + errSuffix; - } - } - }; - Object.freeze(exports.defaultParserErrorProvider); - exports.defaultGrammarResolverErrorProvider = { - buildRuleNotFoundError: function (topLevelRule, undefinedRule) { - var msg = "Invalid grammar, reference to a rule which is not defined: ->" + - undefinedRule.nonTerminalName + - "<-\n" + - "inside top level rule: ->" + - topLevelRule.name + - "<-"; - return msg; - } - }; - exports.defaultGrammarValidatorErrorProvider = { - buildDuplicateFoundError: function (topLevelRule, duplicateProds) { - function getExtraProductionArgument(prod) { - if (prod instanceof gast_1.Terminal) { - return prod.terminalType.name; - } - else if (prod instanceof gast_1.NonTerminal) { - return prod.nonTerminalName; - } - else { - return ""; - } - } - var topLevelName = topLevelRule.name; - var duplicateProd = (0, first_1.default)(duplicateProds); - var index = duplicateProd.idx; - var dslName = (0, gast_2.getProductionDslName)(duplicateProd); - var extraArgument = getExtraProductionArgument(duplicateProd); - var hasExplicitIndex = index > 0; - var msg = "->".concat(dslName).concat(hasExplicitIndex ? index : "", "<- ").concat(extraArgument ? "with argument: ->".concat(extraArgument, "<-") : "", "\n appears more than once (").concat(duplicateProds.length, " times) in the top level rule: ->").concat(topLevelName, "<-. \n For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES \n "); - // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings... - msg = msg.replace(/[ \t]+/g, " "); - msg = msg.replace(/\s\s+/g, "\n"); - return msg; - }, - buildNamespaceConflictError: function (rule) { - var errMsg = "Namespace conflict found in grammar.\n" + - "The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <".concat(rule.name, ">.\n") + - "To resolve this make sure each Terminal and Non-Terminal names are unique\n" + - "This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\n" + - "and Non-Terminal names start with a lower case letter."; - return errMsg; - }, - buildAlternationPrefixAmbiguityError: function (options) { - var pathMsg = (0, map_1.default)(options.prefixPath, function (currTok) { - return (0, tokens_public_1.tokenLabel)(currTok); - }).join(", "); - var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; - var errMsg = "Ambiguous alternatives: <".concat(options.ambiguityIndices.join(" ,"), "> due to common lookahead prefix\n") + - "in inside <").concat(options.topLevelRule.name, "> Rule,\n") + - "<".concat(pathMsg, "> may appears as a prefix path in all these alternatives.\n") + - "See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\n" + - "For Further details."; - return errMsg; - }, - buildAlternationAmbiguityError: function (options) { - var pathMsg = (0, map_1.default)(options.prefixPath, function (currtok) { - return (0, tokens_public_1.tokenLabel)(currtok); - }).join(", "); - var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; - var currMessage = "Ambiguous Alternatives Detected: <".concat(options.ambiguityIndices.join(" ,"), "> in ") + - " inside <".concat(options.topLevelRule.name, "> Rule,\n") + - "<".concat(pathMsg, "> may appears as a prefix path in all these alternatives.\n"); - currMessage = - currMessage + - "See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\n" + - "For Further details."; - return currMessage; - }, - buildEmptyRepetitionError: function (options) { - var dslName = (0, gast_2.getProductionDslName)(options.repetition); - if (options.repetition.idx !== 0) { - dslName += options.repetition.idx; - } - var errMsg = "The repetition <".concat(dslName, "> within Rule <").concat(options.topLevelRule.name, "> can never consume any tokens.\n") + - "This could lead to an infinite loop."; - return errMsg; - }, - // TODO: remove - `errors_public` from nyc.config.js exclude - // once this method is fully removed from this file - buildTokenNameError: function (options) { - /* istanbul ignore next */ - return "deprecated"; - }, - buildEmptyAlternationError: function (options) { - var errMsg = "Ambiguous empty alternative: <".concat(options.emptyChoiceIdx + 1, ">") + - " in inside <").concat(options.topLevelRule.name, "> Rule.\n") + - "Only the last alternative may be an empty alternative."; - return errMsg; - }, - buildTooManyAlternativesError: function (options) { - var errMsg = "An Alternation cannot have more than 256 alternatives:\n" + - " inside <").concat(options.topLevelRule.name, "> Rule.\n has ").concat(options.alternation.definition.length + 1, " alternatives."); - return errMsg; - }, - buildLeftRecursionError: function (options) { - var ruleName = options.topLevelRule.name; - var pathNames = (0, map_1.default)(options.leftRecursionPath, function (currRule) { return currRule.name; }); - var leftRecursivePath = "".concat(ruleName, " --> ").concat(pathNames - .concat([ruleName]) - .join(" --> ")); - var errMsg = "Left Recursion found in grammar.\n" + - "rule: <".concat(ruleName, "> can be invoked from itself (directly or indirectly)\n") + - "without consuming any Tokens. The grammar path that causes this is: \n ".concat(leftRecursivePath, "\n") + - " To fix this refactor your grammar to remove the left recursion.\n" + - "see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring."; - return errMsg; - }, - // TODO: remove - `errors_public` from nyc.config.js exclude - // once this method is fully removed from this file - buildInvalidRuleNameError: function (options) { - /* istanbul ignore next */ - return "deprecated"; - }, - buildDuplicateRuleNameError: function (options) { - var ruleName; - if (options.topLevelRule instanceof gast_1.Rule) { - ruleName = options.topLevelRule.name; - } - else { - ruleName = options.topLevelRule; - } - var errMsg = "Duplicate definition, rule: ->".concat(ruleName, "<- is already defined in the grammar: ->").concat(options.grammarName, "<-"); - return errMsg; - } - }; - -} (errors_public)); -var gast_resolver_public = {}; + workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane); + var _nextState = { + baseLanes: nextBaseLanes, + cachePool: spawnedCachePool + }; + workInProgress.memoizedState = _nextState; + workInProgress.updateQueue = null; + // to avoid a push/pop misalignment. + -var resolver = {}; + pushRenderLanes(workInProgress, nextBaseLanes); -var hasRequiredResolver; + return null; + } else { + // This is the second render. The surrounding visible content has already + // committed. Now we resume rendering the hidden tree. + // Rendering at offscreen, so we can clear the base lanes. + var _nextState2 = { + baseLanes: NoLanes, + cachePool: null + }; + workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out. -function requireResolver () { - if (hasRequiredResolver) return resolver; - hasRequiredResolver = 1; - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(resolver, "__esModule", { value: true }); - resolver.GastRefResolverVisitor = resolver.resolveGrammar = void 0; - var parser_1 = requireParser(); - var forEach_1 = __importDefault(forEach_1$4); - var values_1 = __importDefault(values_1$1); - var gast_1 = api$1; - function resolveGrammar(topLevels, errMsgProvider) { - var refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider); - refResolver.resolveRefs(); - return refResolver.errors; - } - resolver.resolveGrammar = resolveGrammar; - var GastRefResolverVisitor = /** @class */ (function (_super) { - __extends(GastRefResolverVisitor, _super); - function GastRefResolverVisitor(nameToTopRule, errMsgProvider) { - var _this = _super.call(this) || this; - _this.nameToTopRule = nameToTopRule; - _this.errMsgProvider = errMsgProvider; - _this.errors = []; - return _this; - } - GastRefResolverVisitor.prototype.resolveRefs = function () { - var _this = this; - (0, forEach_1.default)((0, values_1.default)(this.nameToTopRule), function (prod) { - _this.currTopLevel = prod; - prod.accept(_this); - }); - }; - GastRefResolverVisitor.prototype.visitNonTerminal = function (node) { - var ref = this.nameToTopRule[node.nonTerminalName]; - if (!ref) { - var msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node); - this.errors.push({ - message: msg, - type: parser_1.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, - ruleName: this.currTopLevel.name, - unresolvedRefName: node.nonTerminalName - }); - } - else { - node.referencedRule = ref; - } - }; - return GastRefResolverVisitor; - }(gast_1.GAstVisitor)); - resolver.GastRefResolverVisitor = GastRefResolverVisitor; - - return resolver; -} + var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes; -var checks = {}; + pushRenderLanes(workInProgress, subtreeRenderLanes); + } + } else { + // Rendering a visible tree. + var _subtreeRenderLanes; -/** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ + if (prevState !== null) { + // We're going from hidden -> visible. + _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes); -function arrayAggregator$1(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; -} + workInProgress.memoizedState = null; + } else { + // We weren't previously hidden, and we still aren't, so there's nothing + // special to do. Need to push to the stack regardless, though, to avoid + // a push/pop misalignment. + _subtreeRenderLanes = renderLanes; + } -var _arrayAggregator = arrayAggregator$1; + pushRenderLanes(workInProgress, _subtreeRenderLanes); + } -var baseEach = _baseEach; + { + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } + } -/** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ -function baseAggregator$1(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; -} + function updateFragment(current, workInProgress, renderLanes) { + var nextChildren = workInProgress.pendingProps; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } -var _baseAggregator = baseAggregator$1; + function updateMode(current, workInProgress, renderLanes) { + var nextChildren = workInProgress.pendingProps.children; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } -var arrayAggregator = _arrayAggregator, - baseAggregator = _baseAggregator, - baseIteratee = _baseIteratee, - isArray$2 = isArray_1$1; + function updateProfiler(current, workInProgress, renderLanes) { + { + workInProgress.flags |= Update; -/** - * Creates a function like `_.groupBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ -function createAggregator$1(setter, initializer) { - return function(collection, iteratee) { - var func = isArray$2(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; + { + // Reset effect durations for the next eventual effect phase. + // These are reset during render to allow the DevTools commit hook a chance to read them, + var stateNode = workInProgress.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + } - return func(collection, setter, baseIteratee(iteratee), accumulator); - }; -} + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } -var _createAggregator = createAggregator$1; + function markRef$1(current, workInProgress) { + var ref = workInProgress.ref; -var baseAssignValue = _baseAssignValue, - createAggregator = _createAggregator; + if (current === null && ref !== null || current !== null && current.ref !== ref) { + // Schedule a Ref effect + workInProgress.flags |= Ref; -/** Used for built-in method references. */ -var objectProto$2 = Object.prototype; + { + workInProgress.flags |= RefStatic; + } + } + } -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$2.hasOwnProperty; + function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) { + { + if (workInProgress.type !== workInProgress.elementType) { + // Lazy component props can't be validated in createElement + // because they're only guaranteed to be resolved here. + var innerPropTypes = Component.propTypes; -/** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } - * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ -var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty$2.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); - } -}); + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(Component)); + } + } + } -var groupBy_1$1 = groupBy; + var context; -var baseFlatten$2 = _baseFlatten, - map = map_1$4; + { + var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); + context = getMaskedContext(workInProgress, unmaskedContext); + } -/** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ -function flatMap(collection, iteratee) { - return baseFlatten$2(map(collection, iteratee), 1); -} + var nextChildren; + var hasId; + prepareToReadContext(workInProgress, renderLanes); -var flatMap_1 = flatMap; + { + markComponentRenderStarted(workInProgress); + } -var lookahead = {}; + { + ReactCurrentOwner$1.current = workInProgress; + setIsRendering(true); + nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); + hasId = checkDidRenderIdHook(); -var interpreter = {}; + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); -var baseSlice$1 = _baseSlice, - toInteger = toInteger_1; + try { + nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } -/** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] - * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ -function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice$1(array, 0, n < 0 ? 0 : n); -} + setIsRendering(false); + } -var dropRight_1$1 = dropRight; + { + markComponentRenderStopped(); + } -/* istanbul ignore next */ var __extends$2 = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$4 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(interpreter, "__esModule", { value: true }); -interpreter.nextPossibleTokensAfter = interpreter.possiblePathsFrom = interpreter.NextTerminalAfterAtLeastOneSepWalker = interpreter.NextTerminalAfterAtLeastOneWalker = interpreter.NextTerminalAfterManySepWalker = interpreter.NextTerminalAfterManyWalker = interpreter.AbstractNextTerminalAfterProductionWalker = interpreter.NextAfterTokenWalker = interpreter.AbstractNextPossibleTokensWalker = void 0; -var rest_1 = rest; -var first_1$1 = __importDefault$4(first.exports); -var isEmpty_1 = __importDefault$4(isEmpty_1$1); -var dropRight_1 = __importDefault$4(dropRight_1$1); -var drop_1 = __importDefault$4(drop_1$2); -var last_1 = __importDefault$4(last_1$1); -var forEach_1 = __importDefault$4(forEach_1$4); -var clone_1 = __importDefault$4(clone_1$1); -var first_2 = first$2; -var gast_1$1 = api$1; -var AbstractNextPossibleTokensWalker = /** @class */ (function (_super) { - __extends$2(AbstractNextPossibleTokensWalker, _super); - function AbstractNextPossibleTokensWalker(topProd, path) { - var _this = _super.call(this) /* istanbul ignore next */ || this; - _this.topProd = topProd; - _this.path = path; - _this.possibleTokTypes = []; - _this.nextProductionName = ""; - _this.nextProductionOccurrence = 0; - _this.found = false; - _this.isAtEndOfPath = false; - return _this; - } - AbstractNextPossibleTokensWalker.prototype.startWalking = function () { - this.found = false; - if (this.path.ruleStack[0] !== this.topProd.name) { - throw Error("The path does not start with the walker's top Rule!"); - } - // immutable for the win - this.ruleStack = (0, clone_1.default)(this.path.ruleStack).reverse(); // intelij bug requires assertion - this.occurrenceStack = (0, clone_1.default)(this.path.occurrenceStack).reverse(); // intelij bug requires assertion - // already verified that the first production is valid, we now seek the 2nd production - this.ruleStack.pop(); - this.occurrenceStack.pop(); - this.updateExpectedNext(); - this.walk(this.topProd); - return this.possibleTokTypes; - }; - AbstractNextPossibleTokensWalker.prototype.walk = function (prod, prevRest) { - if (prevRest === void 0) { prevRest = []; } - // stop scanning once we found the path - if (!this.found) { - _super.prototype.walk.call(this, prod, prevRest); - } - }; - AbstractNextPossibleTokensWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { - // found the next production, need to keep walking in it - if (refProd.referencedRule.name === this.nextProductionName && - refProd.idx === this.nextProductionOccurrence) { - var fullRest = currRest.concat(prevRest); - this.updateExpectedNext(); - this.walk(refProd.referencedRule, fullRest); - } - }; - AbstractNextPossibleTokensWalker.prototype.updateExpectedNext = function () { - // need to consume the Terminal - if ((0, isEmpty_1.default)(this.ruleStack)) { - // must reset nextProductionXXX to avoid walking down another Top Level production while what we are - // really seeking is the last Terminal... - this.nextProductionName = ""; - this.nextProductionOccurrence = 0; - this.isAtEndOfPath = true; - } - else { - this.nextProductionName = this.ruleStack.pop(); - this.nextProductionOccurrence = this.occurrenceStack.pop(); - } - }; - return AbstractNextPossibleTokensWalker; -}(rest_1.RestWalker)); -interpreter.AbstractNextPossibleTokensWalker = AbstractNextPossibleTokensWalker; -var NextAfterTokenWalker = /** @class */ (function (_super) { - __extends$2(NextAfterTokenWalker, _super); - function NextAfterTokenWalker(topProd, path) { - var _this = _super.call(this, topProd, path) /* istanbul ignore next */ || this; - _this.path = path; - _this.nextTerminalName = ""; - _this.nextTerminalOccurrence = 0; - _this.nextTerminalName = _this.path.lastTok.name; - _this.nextTerminalOccurrence = _this.path.lastTokOccurrence; - return _this; - } - NextAfterTokenWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { - if (this.isAtEndOfPath && - terminal.terminalType.name === this.nextTerminalName && - terminal.idx === this.nextTerminalOccurrence && - !this.found) { - var fullRest = currRest.concat(prevRest); - var restProd = new gast_1$1.Alternative({ definition: fullRest }); - this.possibleTokTypes = (0, first_2.first)(restProd); - this.found = true; - } - }; - return NextAfterTokenWalker; -}(AbstractNextPossibleTokensWalker)); -interpreter.NextAfterTokenWalker = NextAfterTokenWalker; -/** - * This walker only "walks" a single "TOP" level in the Grammar Ast, this means - * it never "follows" production refs - */ -var AbstractNextTerminalAfterProductionWalker = /** @class */ (function (_super) { - __extends$2(AbstractNextTerminalAfterProductionWalker, _super); - function AbstractNextTerminalAfterProductionWalker(topRule, occurrence) { - var _this = _super.call(this) /* istanbul ignore next */ || this; - _this.topRule = topRule; - _this.occurrence = occurrence; - _this.result = { - token: undefined, - occurrence: undefined, - isEndOfRule: undefined - }; - return _this; - } - AbstractNextTerminalAfterProductionWalker.prototype.startWalking = function () { - this.walk(this.topRule); - return this.result; - }; - return AbstractNextTerminalAfterProductionWalker; -}(rest_1.RestWalker)); -interpreter.AbstractNextTerminalAfterProductionWalker = AbstractNextTerminalAfterProductionWalker; -var NextTerminalAfterManyWalker = /** @class */ (function (_super) { - __extends$2(NextTerminalAfterManyWalker, _super); - function NextTerminalAfterManyWalker() { - return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this; - } - NextTerminalAfterManyWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { - if (manyProd.idx === this.occurrence) { - var firstAfterMany = (0, first_1$1.default)(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterMany === undefined; - if (firstAfterMany instanceof gast_1$1.Terminal) { - this.result.token = firstAfterMany.terminalType; - this.result.occurrence = firstAfterMany.idx; - } - } - else { - _super.prototype.walkMany.call(this, manyProd, currRest, prevRest); - } - }; - return NextTerminalAfterManyWalker; -}(AbstractNextTerminalAfterProductionWalker)); -interpreter.NextTerminalAfterManyWalker = NextTerminalAfterManyWalker; -var NextTerminalAfterManySepWalker = /** @class */ (function (_super) { - __extends$2(NextTerminalAfterManySepWalker, _super); - function NextTerminalAfterManySepWalker() { - return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this; - } - NextTerminalAfterManySepWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { - if (manySepProd.idx === this.occurrence) { - var firstAfterManySep = (0, first_1$1.default)(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterManySep === undefined; - if (firstAfterManySep instanceof gast_1$1.Terminal) { - this.result.token = firstAfterManySep.terminalType; - this.result.occurrence = firstAfterManySep.idx; - } - } - else { - _super.prototype.walkManySep.call(this, manySepProd, currRest, prevRest); - } - }; - return NextTerminalAfterManySepWalker; -}(AbstractNextTerminalAfterProductionWalker)); -interpreter.NextTerminalAfterManySepWalker = NextTerminalAfterManySepWalker; -var NextTerminalAfterAtLeastOneWalker = /** @class */ (function (_super) { - __extends$2(NextTerminalAfterAtLeastOneWalker, _super); - function NextTerminalAfterAtLeastOneWalker() { - return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this; - } - NextTerminalAfterAtLeastOneWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { - if (atLeastOneProd.idx === this.occurrence) { - var firstAfterAtLeastOne = (0, first_1$1.default)(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterAtLeastOne === undefined; - if (firstAfterAtLeastOne instanceof gast_1$1.Terminal) { - this.result.token = firstAfterAtLeastOne.terminalType; - this.result.occurrence = firstAfterAtLeastOne.idx; - } - } - else { - _super.prototype.walkAtLeastOne.call(this, atLeastOneProd, currRest, prevRest); - } - }; - return NextTerminalAfterAtLeastOneWalker; -}(AbstractNextTerminalAfterProductionWalker)); -interpreter.NextTerminalAfterAtLeastOneWalker = NextTerminalAfterAtLeastOneWalker; -// TODO: reduce code duplication in the AfterWalkers -var NextTerminalAfterAtLeastOneSepWalker = /** @class */ (function (_super) { - __extends$2(NextTerminalAfterAtLeastOneSepWalker, _super); - function NextTerminalAfterAtLeastOneSepWalker() { - return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this; - } - NextTerminalAfterAtLeastOneSepWalker.prototype.walkAtLeastOneSep = function (atleastOneSepProd, currRest, prevRest) { - if (atleastOneSepProd.idx === this.occurrence) { - var firstAfterfirstAfterAtLeastOneSep = (0, first_1$1.default)(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === undefined; - if (firstAfterfirstAfterAtLeastOneSep instanceof gast_1$1.Terminal) { - this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType; - this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx; - } - } - else { - _super.prototype.walkAtLeastOneSep.call(this, atleastOneSepProd, currRest, prevRest); - } - }; - return NextTerminalAfterAtLeastOneSepWalker; -}(AbstractNextTerminalAfterProductionWalker)); -interpreter.NextTerminalAfterAtLeastOneSepWalker = NextTerminalAfterAtLeastOneSepWalker; -function possiblePathsFrom(targetDef, maxLength, currPath) { - if (currPath === void 0) { currPath = []; } - // avoid side effects - currPath = (0, clone_1.default)(currPath); - var result = []; - var i = 0; - // TODO: avoid inner funcs - function remainingPathWith(nextDef) { - return nextDef.concat((0, drop_1.default)(targetDef, i + 1)); - } - // TODO: avoid inner funcs - function getAlternativesForProd(definition) { - var alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath); - return result.concat(alternatives); - } - /** - * Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the - * following (rest) of the targetDef. - * - * For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the - * the optional production. - */ - while (currPath.length < maxLength && i < targetDef.length) { - var prod = targetDef[i]; - /* istanbul ignore else */ - if (prod instanceof gast_1$1.Alternative) { - return getAlternativesForProd(prod.definition); - } - else if (prod instanceof gast_1$1.NonTerminal) { - return getAlternativesForProd(prod.definition); - } - else if (prod instanceof gast_1$1.Option) { - result = getAlternativesForProd(prod.definition); - } - else if (prod instanceof gast_1$1.RepetitionMandatory) { - var newDef = prod.definition.concat([ - new gast_1$1.Repetition({ - definition: prod.definition - }) - ]); - return getAlternativesForProd(newDef); - } - else if (prod instanceof gast_1$1.RepetitionMandatoryWithSeparator) { - var newDef = [ - new gast_1$1.Alternative({ definition: prod.definition }), - new gast_1$1.Repetition({ - definition: [new gast_1$1.Terminal({ terminalType: prod.separator })].concat(prod.definition) - }) - ]; - return getAlternativesForProd(newDef); - } - else if (prod instanceof gast_1$1.RepetitionWithSeparator) { - var newDef = prod.definition.concat([ - new gast_1$1.Repetition({ - definition: [new gast_1$1.Terminal({ terminalType: prod.separator })].concat(prod.definition) - }) - ]); - result = getAlternativesForProd(newDef); - } - else if (prod instanceof gast_1$1.Repetition) { - var newDef = prod.definition.concat([ - new gast_1$1.Repetition({ - definition: prod.definition - }) - ]); - result = getAlternativesForProd(newDef); - } - else if (prod instanceof gast_1$1.Alternation) { - (0, forEach_1.default)(prod.definition, function (currAlt) { - // TODO: this is a limited check for empty alternatives - // It would prevent a common case of infinite loops during parser initialization. - // However **in-directly** empty alternatives may still cause issues. - if ((0, isEmpty_1.default)(currAlt.definition) === false) { - result = getAlternativesForProd(currAlt.definition); - } - }); - return result; - } - else if (prod instanceof gast_1$1.Terminal) { - currPath.push(prod.terminalType); - } - else { - throw Error("non exhaustive match"); - } - i++; - } - result.push({ - partialPath: currPath, - suffixDef: (0, drop_1.default)(targetDef, i) - }); - return result; -} -interpreter.possiblePathsFrom = possiblePathsFrom; -function nextPossibleTokensAfter(initialDef, tokenVector, tokMatcher, maxLookAhead) { - var EXIT_NON_TERMINAL = "EXIT_NONE_TERMINAL"; - // to avoid creating a new Array each time. - var EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL]; - var EXIT_ALTERNATIVE = "EXIT_ALTERNATIVE"; - var foundCompletePath = false; - var tokenVectorLength = tokenVector.length; - var minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1; - var result = []; - var possiblePaths = []; - possiblePaths.push({ - idx: -1, - def: initialDef, - ruleStack: [], - occurrenceStack: [] - }); - while (!(0, isEmpty_1.default)(possiblePaths)) { - var currPath = possiblePaths.pop(); - // skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead) - if (currPath === EXIT_ALTERNATIVE) { - if (foundCompletePath && - (0, last_1.default)(possiblePaths).idx <= minimalAlternativesIndex) { - // remove irrelevant alternative - possiblePaths.pop(); - } - continue; - } - var currDef = currPath.def; - var currIdx = currPath.idx; - var currRuleStack = currPath.ruleStack; - var currOccurrenceStack = currPath.occurrenceStack; - // For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT - if ((0, isEmpty_1.default)(currDef)) { - continue; - } - var prod = currDef[0]; - /* istanbul ignore else */ - if (prod === EXIT_NON_TERMINAL) { - var nextPath = { - idx: currIdx, - def: (0, drop_1.default)(currDef), - ruleStack: (0, dropRight_1.default)(currRuleStack), - occurrenceStack: (0, dropRight_1.default)(currOccurrenceStack) - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_1$1.Terminal) { - /* istanbul ignore else */ - if (currIdx < tokenVectorLength - 1) { - var nextIdx = currIdx + 1; - var actualToken = tokenVector[nextIdx]; - if (tokMatcher(actualToken, prod.terminalType)) { - var nextPath = { - idx: nextIdx, - def: (0, drop_1.default)(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - // end of the line - } - else if (currIdx === tokenVectorLength - 1) { - // IGNORE ABOVE ELSE - result.push({ - nextTokenType: prod.terminalType, - nextTokenOccurrence: prod.idx, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }); - foundCompletePath = true; - } - else { - throw Error("non exhaustive match"); - } - } - else if (prod instanceof gast_1$1.NonTerminal) { - var newRuleStack = (0, clone_1.default)(currRuleStack); - newRuleStack.push(prod.nonTerminalName); - var newOccurrenceStack = (0, clone_1.default)(currOccurrenceStack); - newOccurrenceStack.push(prod.idx); - var nextPath = { - idx: currIdx, - def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, (0, drop_1.default)(currDef)), - ruleStack: newRuleStack, - occurrenceStack: newOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_1$1.Option) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: (0, drop_1.default)(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWithout); - // required marker to avoid backtracking paths whose higher priority alternatives already matched - possiblePaths.push(EXIT_ALTERNATIVE); - var nextPathWith = { - idx: currIdx, - def: prod.definition.concat((0, drop_1.default)(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof gast_1$1.RepetitionMandatory) { - // TODO:(THE NEW operators here take a while...) (convert once?) - var secondIteration = new gast_1$1.Repetition({ - definition: prod.definition, - idx: prod.idx - }); - var nextDef = prod.definition.concat([secondIteration], (0, drop_1.default)(currDef)); - var nextPath = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_1$1.RepetitionMandatoryWithSeparator) { - // TODO:(THE NEW operators here take a while...) (convert once?) - var separatorGast = new gast_1$1.Terminal({ - terminalType: prod.separator - }); - var secondIteration = new gast_1$1.Repetition({ - definition: [separatorGast].concat(prod.definition), - idx: prod.idx - }); - var nextDef = prod.definition.concat([secondIteration], (0, drop_1.default)(currDef)); - var nextPath = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_1$1.RepetitionWithSeparator) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: (0, drop_1.default)(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWithout); - // required marker to avoid backtracking paths whose higher priority alternatives already matched - possiblePaths.push(EXIT_ALTERNATIVE); - var separatorGast = new gast_1$1.Terminal({ - terminalType: prod.separator - }); - var nthRepetition = new gast_1$1.Repetition({ - definition: [separatorGast].concat(prod.definition), - idx: prod.idx - }); - var nextDef = prod.definition.concat([nthRepetition], (0, drop_1.default)(currDef)); - var nextPathWith = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof gast_1$1.Repetition) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: (0, drop_1.default)(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWithout); - // required marker to avoid backtracking paths whose higher priority alternatives already matched - possiblePaths.push(EXIT_ALTERNATIVE); - // TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis? - var nthRepetition = new gast_1$1.Repetition({ - definition: prod.definition, - idx: prod.idx - }); - var nextDef = prod.definition.concat([nthRepetition], (0, drop_1.default)(currDef)); - var nextPathWith = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof gast_1$1.Alternation) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - for (var i = prod.definition.length - 1; i >= 0; i--) { - var currAlt = prod.definition[i]; - var currAltPath = { - idx: currIdx, - def: currAlt.definition.concat((0, drop_1.default)(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(currAltPath); - possiblePaths.push(EXIT_ALTERNATIVE); - } - } - else if (prod instanceof gast_1$1.Alternative) { - possiblePaths.push({ - idx: currIdx, - def: prod.definition.concat((0, drop_1.default)(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }); - } - else if (prod instanceof gast_1$1.Rule) { - // last because we should only encounter at most a single one of these per invocation. - possiblePaths.push(expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack)); - } - else { - throw Error("non exhaustive match"); - } - } - return result; -} -interpreter.nextPossibleTokensAfter = nextPossibleTokensAfter; -function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) { - var newRuleStack = (0, clone_1.default)(currRuleStack); - newRuleStack.push(topRule.name); - var newCurrOccurrenceStack = (0, clone_1.default)(currOccurrenceStack); - // top rule is always assumed to have been called with occurrence index 1 - newCurrOccurrenceStack.push(1); - return { - idx: currIdx, - def: topRule.definition, - ruleStack: newRuleStack, - occurrenceStack: newCurrOccurrenceStack - }; -} + if (current !== null && !didReceiveUpdate) { + bailoutHooks(current, workInProgress, renderLanes); + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } -(function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.areTokenCategoriesNotUsed = exports.isStrictPrefixOfPath = exports.containsPath = exports.getLookaheadPathsForOptionalProd = exports.getLookaheadPathsForOr = exports.lookAheadSequenceFromAlternatives = exports.buildSingleAlternativeLookaheadFunction = exports.buildAlternativesLookAheadFunc = exports.buildLookaheadFuncForOptionalProd = exports.buildLookaheadFuncForOr = exports.getProdType = exports.PROD_TYPE = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var every_1 = __importDefault(every_1$1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var has_1$1 = __importDefault(has_1); - var reduce_1 = __importDefault(reduce_1$1); - var interpreter_1 = interpreter; - var rest_1 = rest; - var tokens_1 = tokens; - var gast_1 = api$1; - var gast_2 = api$1; - var PROD_TYPE; - (function (PROD_TYPE) { - PROD_TYPE[PROD_TYPE["OPTION"] = 0] = "OPTION"; - PROD_TYPE[PROD_TYPE["REPETITION"] = 1] = "REPETITION"; - PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY"] = 2] = "REPETITION_MANDATORY"; - PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY_WITH_SEPARATOR"] = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR"; - PROD_TYPE[PROD_TYPE["REPETITION_WITH_SEPARATOR"] = 4] = "REPETITION_WITH_SEPARATOR"; - PROD_TYPE[PROD_TYPE["ALTERNATION"] = 5] = "ALTERNATION"; - })(PROD_TYPE = exports.PROD_TYPE || (exports.PROD_TYPE = {})); - function getProdType(prod) { - /* istanbul ignore else */ - if (prod instanceof gast_1.Option) { - return PROD_TYPE.OPTION; - } - else if (prod instanceof gast_1.Repetition) { - return PROD_TYPE.REPETITION; - } - else if (prod instanceof gast_1.RepetitionMandatory) { - return PROD_TYPE.REPETITION_MANDATORY; - } - else if (prod instanceof gast_1.RepetitionMandatoryWithSeparator) { - return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR; - } - else if (prod instanceof gast_1.RepetitionWithSeparator) { - return PROD_TYPE.REPETITION_WITH_SEPARATOR; - } - else if (prod instanceof gast_1.Alternation) { - return PROD_TYPE.ALTERNATION; - } - else { - throw Error("non exhaustive match"); - } - } - exports.getProdType = getProdType; - function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) { - var lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead); - var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths) - ? tokens_1.tokenStructuredMatcherNoCategories - : tokens_1.tokenStructuredMatcher; - return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher, dynamicTokensEnabled); - } - exports.buildLookaheadFuncForOr = buildLookaheadFuncForOr; - /** - * When dealing with an Optional production (OPTION/MANY/2nd iteration of AT_LEAST_ONE/...) we need to compare - * the lookahead "inside" the production and the lookahead immediately "after" it in the same top level rule (context free). - * - * Example: given a production: - * ABC(DE)?DF - * - * The optional '(DE)?' should only be entered if we see 'DE'. a single Token 'D' is not sufficient to distinguish between the two - * alternatives. - * - * @returns A Lookahead function which will return true IFF the parser should parse the Optional production. - */ - function buildLookaheadFuncForOptionalProd(occurrence, ruleGrammar, k, dynamicTokensEnabled, prodType, lookaheadBuilder) { - var lookAheadPaths = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k); - var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths) - ? tokens_1.tokenStructuredMatcherNoCategories - : tokens_1.tokenStructuredMatcher; - return lookaheadBuilder(lookAheadPaths[0], tokenMatcher, dynamicTokensEnabled); - } - exports.buildLookaheadFuncForOptionalProd = buildLookaheadFuncForOptionalProd; - function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { - var numOfAlts = alts.length; - var areAllOneTokenLookahead = (0, every_1.default)(alts, function (currAlt) { - return (0, every_1.default)(currAlt, function (currPath) { - return currPath.length === 1; - }); - }); - // This version takes into account the predicates as well. - if (hasPredicates) { - /** - * @returns {number} - The chosen alternative index - */ - return function (orAlts) { - // unfortunately the predicates must be extracted every single time - // as they cannot be cached due to references to parameters(vars) which are no longer valid. - // note that in the common case of no predicates, no cpu time will be wasted on this (see else block) - var predicates = (0, map_1.default)(orAlts, function (currAlt) { return currAlt.GATE; }); - for (var t = 0; t < numOfAlts; t++) { - var currAlt = alts[t]; - var currNumOfPaths = currAlt.length; - var currPredicate = predicates[t]; - if (currPredicate !== undefined && currPredicate.call(this) === false) { - // if the predicate does not match there is no point in checking the paths - continue; - } - nextPath: for (var j = 0; j < currNumOfPaths; j++) { - var currPath = currAlt[j]; - var currPathLength = currPath.length; - for (var i = 0; i < currPathLength; i++) { - var nextToken = this.LA(i + 1); - if (tokenMatcher(nextToken, currPath[i]) === false) { - // mismatch in current path - // try the next pth - continue nextPath; - } - } - // found a full path that matches. - // this will also work for an empty ALT as the loop will be skipped - return t; - } - // none of the paths for the current alternative matched - // try the next alternative - } - // none of the alternatives could be matched - return undefined; - }; - } - else if (areAllOneTokenLookahead && !dynamicTokensEnabled) { - // optimized (common) case of all the lookaheads paths requiring only - // a single token lookahead. These Optimizations cannot work if dynamically defined Tokens are used. - var singleTokenAlts = (0, map_1.default)(alts, function (currAlt) { - return (0, flatten_1.default)(currAlt); - }); - var choiceToAlt_1 = (0, reduce_1.default)(singleTokenAlts, function (result, currAlt, idx) { - (0, forEach_1.default)(currAlt, function (currTokType) { - if (!(0, has_1$1.default)(result, currTokType.tokenTypeIdx)) { - result[currTokType.tokenTypeIdx] = idx; - } - (0, forEach_1.default)(currTokType.categoryMatches, function (currExtendingType) { - if (!(0, has_1$1.default)(result, currExtendingType)) { - result[currExtendingType] = idx; - } - }); - }); - return result; - }, {}); - /** - * @returns {number} - The chosen alternative index - */ - return function () { - var nextToken = this.LA(1); - return choiceToAlt_1[nextToken.tokenTypeIdx]; - }; - } - else { - // optimized lookahead without needing to check the predicates at all. - // this causes code duplication which is intentional to improve performance. - /** - * @returns {number} - The chosen alternative index - */ - return function () { - for (var t = 0; t < numOfAlts; t++) { - var currAlt = alts[t]; - var currNumOfPaths = currAlt.length; - nextPath: for (var j = 0; j < currNumOfPaths; j++) { - var currPath = currAlt[j]; - var currPathLength = currPath.length; - for (var i = 0; i < currPathLength; i++) { - var nextToken = this.LA(i + 1); - if (tokenMatcher(nextToken, currPath[i]) === false) { - // mismatch in current path - // try the next pth - continue nextPath; - } - } - // found a full path that matches. - // this will also work for an empty ALT as the loop will be skipped - return t; - } - // none of the paths for the current alternative matched - // try the next alternative - } - // none of the alternatives could be matched - return undefined; - }; - } - } - exports.buildAlternativesLookAheadFunc = buildAlternativesLookAheadFunc; - function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled) { - var areAllOneTokenLookahead = (0, every_1.default)(alt, function (currPath) { - return currPath.length === 1; - }); - var numOfPaths = alt.length; - // optimized (common) case of all the lookaheads paths requiring only - // a single token lookahead. - if (areAllOneTokenLookahead && !dynamicTokensEnabled) { - var singleTokensTypes = (0, flatten_1.default)(alt); - if (singleTokensTypes.length === 1 && - (0, isEmpty_1.default)(singleTokensTypes[0].categoryMatches)) { - var expectedTokenType = singleTokensTypes[0]; - var expectedTokenUniqueKey_1 = expectedTokenType.tokenTypeIdx; - return function () { - return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey_1; - }; - } - else { - var choiceToAlt_2 = (0, reduce_1.default)(singleTokensTypes, function (result, currTokType, idx) { - result[currTokType.tokenTypeIdx] = true; - (0, forEach_1.default)(currTokType.categoryMatches, function (currExtendingType) { - result[currExtendingType] = true; - }); - return result; - }, []); - return function () { - var nextToken = this.LA(1); - return choiceToAlt_2[nextToken.tokenTypeIdx] === true; - }; - } - } - else { - return function () { - nextPath: for (var j = 0; j < numOfPaths; j++) { - var currPath = alt[j]; - var currPathLength = currPath.length; - for (var i = 0; i < currPathLength; i++) { - var nextToken = this.LA(i + 1); - if (tokenMatcher(nextToken, currPath[i]) === false) { - // mismatch in current path - // try the next pth - continue nextPath; - } - } - // found a full path that matches. - return true; - } - // none of the paths matched - return false; - }; - } - } - exports.buildSingleAlternativeLookaheadFunction = buildSingleAlternativeLookaheadFunction; - var RestDefinitionFinderWalker = /** @class */ (function (_super) { - __extends(RestDefinitionFinderWalker, _super); - function RestDefinitionFinderWalker(topProd, targetOccurrence, targetProdType) { - var _this = _super.call(this) || this; - _this.topProd = topProd; - _this.targetOccurrence = targetOccurrence; - _this.targetProdType = targetProdType; - return _this; - } - RestDefinitionFinderWalker.prototype.startWalking = function () { - this.walk(this.topProd); - return this.restDef; - }; - RestDefinitionFinderWalker.prototype.checkIsTarget = function (node, expectedProdType, currRest, prevRest) { - if (node.idx === this.targetOccurrence && - this.targetProdType === expectedProdType) { - this.restDef = currRest.concat(prevRest); - return true; - } - // performance optimization, do not iterate over the entire Grammar ast after we have found the target - return false; - }; - RestDefinitionFinderWalker.prototype.walkOption = function (optionProd, currRest, prevRest) { - if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) { - _super.prototype.walkOption.call(this, optionProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { - if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) { - _super.prototype.walkOption.call(this, atLeastOneProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) { - if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) { - _super.prototype.walkOption.call(this, atLeastOneSepProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { - if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) { - _super.prototype.walkOption.call(this, manyProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { - if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) { - _super.prototype.walkOption.call(this, manySepProd, currRest, prevRest); - } - }; - return RestDefinitionFinderWalker; - }(rest_1.RestWalker)); - /** - * Returns the definition of a target production in a top level level rule. - */ - var InsideDefinitionFinderVisitor = /** @class */ (function (_super) { - __extends(InsideDefinitionFinderVisitor, _super); - function InsideDefinitionFinderVisitor(targetOccurrence, targetProdType, targetRef) { - var _this = _super.call(this) || this; - _this.targetOccurrence = targetOccurrence; - _this.targetProdType = targetProdType; - _this.targetRef = targetRef; - _this.result = []; - return _this; - } - InsideDefinitionFinderVisitor.prototype.checkIsTarget = function (node, expectedProdName) { - if (node.idx === this.targetOccurrence && - this.targetProdType === expectedProdName && - (this.targetRef === undefined || node === this.targetRef)) { - this.result = node.definition; - } - }; - InsideDefinitionFinderVisitor.prototype.visitOption = function (node) { - this.checkIsTarget(node, PROD_TYPE.OPTION); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetition = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatory = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetitionWithSeparator = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR); - }; - InsideDefinitionFinderVisitor.prototype.visitAlternation = function (node) { - this.checkIsTarget(node, PROD_TYPE.ALTERNATION); - }; - return InsideDefinitionFinderVisitor; - }(gast_2.GAstVisitor)); - function initializeArrayOfArrays(size) { - var result = new Array(size); - for (var i = 0; i < size; i++) { - result[i] = []; - } - return result; - } - /** - * A sort of hash function between a Path in the grammar and a string. - * Note that this returns multiple "hashes" to support the scenario of token categories. - * - A single path with categories may match multiple **actual** paths. - */ - function pathToHashKeys(path) { - var keys = [""]; - for (var i = 0; i < path.length; i++) { - var tokType = path[i]; - var longerKeys = []; - for (var j = 0; j < keys.length; j++) { - var currShorterKey = keys[j]; - longerKeys.push(currShorterKey + "_" + tokType.tokenTypeIdx); - for (var t = 0; t < tokType.categoryMatches.length; t++) { - var categoriesKeySuffix = "_" + tokType.categoryMatches[t]; - longerKeys.push(currShorterKey + categoriesKeySuffix); - } - } - keys = longerKeys; - } - return keys; - } - /** - * Imperative style due to being called from a hot spot - */ - function isUniquePrefixHash(altKnownPathsKeys, searchPathKeys, idx) { - for (var currAltIdx = 0; currAltIdx < altKnownPathsKeys.length; currAltIdx++) { - // We only want to test vs the other alternatives - if (currAltIdx === idx) { - continue; - } - var otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx]; - for (var searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) { - var searchKey = searchPathKeys[searchIdx]; - if (otherAltKnownPathsKeys[searchKey] === true) { - return false; - } - } - } - // None of the SearchPathKeys were found in any of the other alternatives - return true; - } - function lookAheadSequenceFromAlternatives(altsDefs, k) { - var partialAlts = (0, map_1.default)(altsDefs, function (currAlt) { - return (0, interpreter_1.possiblePathsFrom)([currAlt], 1); - }); - var finalResult = initializeArrayOfArrays(partialAlts.length); - var altsHashes = (0, map_1.default)(partialAlts, function (currAltPaths) { - var dict = {}; - (0, forEach_1.default)(currAltPaths, function (item) { - var keys = pathToHashKeys(item.partialPath); - (0, forEach_1.default)(keys, function (currKey) { - dict[currKey] = true; - }); - }); - return dict; - }); - var newData = partialAlts; - // maxLookahead loop - for (var pathLength = 1; pathLength <= k; pathLength++) { - var currDataset = newData; - newData = initializeArrayOfArrays(currDataset.length); - var _loop_1 = function (altIdx) { - var currAltPathsAndSuffixes = currDataset[altIdx]; - // paths in current alternative loop - for (var currPathIdx = 0; currPathIdx < currAltPathsAndSuffixes.length; currPathIdx++) { - var currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath; - var suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef; - var prefixKeys = pathToHashKeys(currPathPrefix); - var isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx); - // End of the line for this path. - if (isUnique || (0, isEmpty_1.default)(suffixDef) || currPathPrefix.length === k) { - var currAltResult = finalResult[altIdx]; - // TODO: Can we implement a containsPath using Maps/Dictionaries? - if (containsPath(currAltResult, currPathPrefix) === false) { - currAltResult.push(currPathPrefix); - // Update all new keys for the current path. - for (var j = 0; j < prefixKeys.length; j++) { - var currKey = prefixKeys[j]; - altsHashes[altIdx][currKey] = true; - } - } - } - // Expand longer paths - else { - var newPartialPathsAndSuffixes = (0, interpreter_1.possiblePathsFrom)(suffixDef, pathLength + 1, currPathPrefix); - newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes); - // Update keys for new known paths - (0, forEach_1.default)(newPartialPathsAndSuffixes, function (item) { - var prefixKeys = pathToHashKeys(item.partialPath); - (0, forEach_1.default)(prefixKeys, function (key) { - altsHashes[altIdx][key] = true; - }); - }); - } - } - }; - // alternatives loop - for (var altIdx = 0; altIdx < currDataset.length; altIdx++) { - _loop_1(altIdx); - } - } - return finalResult; - } - exports.lookAheadSequenceFromAlternatives = lookAheadSequenceFromAlternatives; - function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) { - var visitor = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd); - ruleGrammar.accept(visitor); - return lookAheadSequenceFromAlternatives(visitor.result, k); - } - exports.getLookaheadPathsForOr = getLookaheadPathsForOr; - function getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k) { - var insideDefVisitor = new InsideDefinitionFinderVisitor(occurrence, prodType); - ruleGrammar.accept(insideDefVisitor); - var insideDef = insideDefVisitor.result; - var afterDefWalker = new RestDefinitionFinderWalker(ruleGrammar, occurrence, prodType); - var afterDef = afterDefWalker.startWalking(); - var insideFlat = new gast_1.Alternative({ definition: insideDef }); - var afterFlat = new gast_1.Alternative({ definition: afterDef }); - return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k); - } - exports.getLookaheadPathsForOptionalProd = getLookaheadPathsForOptionalProd; - function containsPath(alternative, searchPath) { - compareOtherPath: for (var i = 0; i < alternative.length; i++) { - var otherPath = alternative[i]; - if (otherPath.length !== searchPath.length) { - continue; - } - for (var j = 0; j < otherPath.length; j++) { - var searchTok = searchPath[j]; - var otherTok = otherPath[j]; - var matchingTokens = searchTok === otherTok || - otherTok.categoryMatchesMap[searchTok.tokenTypeIdx] !== undefined; - if (matchingTokens === false) { - continue compareOtherPath; - } - } - return true; - } - return false; - } - exports.containsPath = containsPath; - function isStrictPrefixOfPath(prefix, other) { - return (prefix.length < other.length && - (0, every_1.default)(prefix, function (tokType, idx) { - var otherTokType = other[idx]; - return (tokType === otherTokType || - otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]); - })); - } - exports.isStrictPrefixOfPath = isStrictPrefixOfPath; - function areTokenCategoriesNotUsed(lookAheadPaths) { - return (0, every_1.default)(lookAheadPaths, function (singleAltPaths) { - return (0, every_1.default)(singleAltPaths, function (singlePath) { - return (0, every_1.default)(singlePath, function (token) { return (0, isEmpty_1.default)(token.categoryMatches); }); - }); - }); - } - exports.areTokenCategoriesNotUsed = areTokenCategoriesNotUsed; - -} (lookahead)); - -var hasRequiredChecks; - -function requireChecks () { - if (hasRequiredChecks) return checks; - hasRequiredChecks = 1; - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(checks, "__esModule", { value: true }); - checks.checkPrefixAlternativesAmbiguities = checks.validateSomeNonEmptyLookaheadPath = checks.validateTooManyAlts = checks.RepetitionCollector = checks.validateAmbiguousAlternationAlternatives = checks.validateEmptyOrAlternative = checks.getFirstNoneTerminal = checks.validateNoLeftRecursion = checks.validateRuleIsOverridden = checks.validateRuleDoesNotAlreadyExist = checks.OccurrenceValidationCollector = checks.identifyProductionForDuplicates = checks.validateGrammar = void 0; - var first_1 = __importDefault(first.exports); - var isEmpty_1 = __importDefault(isEmpty_1$1); - var drop_1 = __importDefault(drop_1$2); - var flatten_1 = __importDefault(flatten_1$3); - var filter_1$1 = __importDefault(filter_1); - var reject_1$1 = __importDefault(reject_1); - var difference_1$1 = __importDefault(difference_1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var groupBy_1 = __importDefault(groupBy_1$1); - var reduce_1 = __importDefault(reduce_1$1); - var pickBy_1 = __importDefault(pickBy_1$1); - var values_1 = __importDefault(values_1$1); - var includes_1 = __importDefault(includes_1$2); - var flatMap_1$1 = __importDefault(flatMap_1); - var clone_1 = __importDefault(clone_1$1); - var parser_1 = requireParser(); - var gast_1 = api$1; - var lookahead_1 = lookahead; - var interpreter_1 = interpreter; - var gast_2 = api$1; - var gast_3 = api$1; - var dropRight_1 = __importDefault(dropRight_1$1); - var compact_1$1 = __importDefault(compact_1); - var tokens_1 = tokens; - function validateGrammar(topLevels, globalMaxLookahead, tokenTypes, errMsgProvider, grammarName) { - var duplicateErrors = (0, flatMap_1$1.default)(topLevels, function (currTopLevel) { - return validateDuplicateProductions(currTopLevel, errMsgProvider); - }); - var leftRecursionErrors = (0, flatMap_1$1.default)(topLevels, function (currTopRule) { - return validateNoLeftRecursion(currTopRule, currTopRule, errMsgProvider); - }); - var emptyAltErrors = []; - var ambiguousAltsErrors = []; - var emptyRepetitionErrors = []; - // left recursion could cause infinite loops in the following validations. - // It is safest to first have the user fix the left recursion errors first and only then examine Further issues. - if ((0, isEmpty_1.default)(leftRecursionErrors)) { - emptyAltErrors = (0, flatMap_1$1.default)(topLevels, function (currTopRule) { - return validateEmptyOrAlternative(currTopRule, errMsgProvider); - }); - ambiguousAltsErrors = (0, flatMap_1$1.default)(topLevels, function (currTopRule) { - return validateAmbiguousAlternationAlternatives(currTopRule, globalMaxLookahead, errMsgProvider); - }); - emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(topLevels, globalMaxLookahead, errMsgProvider); - } - var termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider); - var tooManyAltsErrors = (0, flatMap_1$1.default)(topLevels, function (curRule) { - return validateTooManyAlts(curRule, errMsgProvider); - }); - var duplicateRulesError = (0, flatMap_1$1.default)(topLevels, function (curRule) { - return validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider); - }); - return duplicateErrors.concat(emptyRepetitionErrors, leftRecursionErrors, emptyAltErrors, ambiguousAltsErrors, termsNamespaceConflictErrors, tooManyAltsErrors, duplicateRulesError); - } - checks.validateGrammar = validateGrammar; - function validateDuplicateProductions(topLevelRule, errMsgProvider) { - var collectorVisitor = new OccurrenceValidationCollector(); - topLevelRule.accept(collectorVisitor); - var allRuleProductions = collectorVisitor.allProductions; - var productionGroups = (0, groupBy_1.default)(allRuleProductions, identifyProductionForDuplicates); - var duplicates = (0, pickBy_1.default)(productionGroups, function (currGroup) { - return currGroup.length > 1; - }); - var errors = (0, map_1.default)((0, values_1.default)(duplicates), function (currDuplicates) { - var firstProd = (0, first_1.default)(currDuplicates); - var msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates); - var dslName = (0, gast_1.getProductionDslName)(firstProd); - var defError = { - message: msg, - type: parser_1.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, - ruleName: topLevelRule.name, - dslName: dslName, - occurrence: firstProd.idx - }; - var param = getExtraProductionArgument(firstProd); - if (param) { - defError.parameter = param; - } - return defError; - }); - return errors; - } - function identifyProductionForDuplicates(prod) { - return "".concat((0, gast_1.getProductionDslName)(prod), "_#_").concat(prod.idx, "_#_").concat(getExtraProductionArgument(prod)); - } - checks.identifyProductionForDuplicates = identifyProductionForDuplicates; - function getExtraProductionArgument(prod) { - if (prod instanceof gast_2.Terminal) { - return prod.terminalType.name; - } - else if (prod instanceof gast_2.NonTerminal) { - return prod.nonTerminalName; - } - else { - return ""; - } - } - var OccurrenceValidationCollector = /** @class */ (function (_super) { - __extends(OccurrenceValidationCollector, _super); - function OccurrenceValidationCollector() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.allProductions = []; - return _this; - } - OccurrenceValidationCollector.prototype.visitNonTerminal = function (subrule) { - this.allProductions.push(subrule); - }; - OccurrenceValidationCollector.prototype.visitOption = function (option) { - this.allProductions.push(option); - }; - OccurrenceValidationCollector.prototype.visitRepetitionWithSeparator = function (manySep) { - this.allProductions.push(manySep); - }; - OccurrenceValidationCollector.prototype.visitRepetitionMandatory = function (atLeastOne) { - this.allProductions.push(atLeastOne); - }; - OccurrenceValidationCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { - this.allProductions.push(atLeastOneSep); - }; - OccurrenceValidationCollector.prototype.visitRepetition = function (many) { - this.allProductions.push(many); - }; - OccurrenceValidationCollector.prototype.visitAlternation = function (or) { - this.allProductions.push(or); - }; - OccurrenceValidationCollector.prototype.visitTerminal = function (terminal) { - this.allProductions.push(terminal); - }; - return OccurrenceValidationCollector; - }(gast_3.GAstVisitor)); - checks.OccurrenceValidationCollector = OccurrenceValidationCollector; - function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) { - var errors = []; - var occurrences = (0, reduce_1.default)(allRules, function (result, curRule) { - if (curRule.name === rule.name) { - return result + 1; - } - return result; - }, 0); - if (occurrences > 1) { - var errMsg = errMsgProvider.buildDuplicateRuleNameError({ - topLevelRule: rule, - grammarName: className - }); - errors.push({ - message: errMsg, - type: parser_1.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, - ruleName: rule.name - }); - } - return errors; - } - checks.validateRuleDoesNotAlreadyExist = validateRuleDoesNotAlreadyExist; - // TODO: is there anyway to get only the rule names of rules inherited from the super grammars? - // This is not part of the IGrammarErrorProvider because the validation cannot be performed on - // The grammar structure, only at runtime. - function validateRuleIsOverridden(ruleName, definedRulesNames, className) { - var errors = []; - var errMsg; - if (!(0, includes_1.default)(definedRulesNames, ruleName)) { - errMsg = - "Invalid rule override, rule: ->".concat(ruleName, "<- cannot be overridden in the grammar: ->").concat(className, "<-") + - "as it is not defined in any of the super grammars "; - errors.push({ - message: errMsg, - type: parser_1.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE, - ruleName: ruleName - }); - } - return errors; - } - checks.validateRuleIsOverridden = validateRuleIsOverridden; - function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path) { - if (path === void 0) { path = []; } - var errors = []; - var nextNonTerminals = getFirstNoneTerminal(currRule.definition); - if ((0, isEmpty_1.default)(nextNonTerminals)) { - return []; - } - else { - var ruleName = topRule.name; - var foundLeftRecursion = (0, includes_1.default)(nextNonTerminals, topRule); - if (foundLeftRecursion) { - errors.push({ - message: errMsgProvider.buildLeftRecursionError({ - topLevelRule: topRule, - leftRecursionPath: path - }), - type: parser_1.ParserDefinitionErrorType.LEFT_RECURSION, - ruleName: ruleName - }); - } - // we are only looking for cyclic paths leading back to the specific topRule - // other cyclic paths are ignored, we still need this difference to avoid infinite loops... - var validNextSteps = (0, difference_1$1.default)(nextNonTerminals, path.concat([topRule])); - var errorsFromNextSteps = (0, flatMap_1$1.default)(validNextSteps, function (currRefRule) { - var newPath = (0, clone_1.default)(path); - newPath.push(currRefRule); - return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath); - }); - return errors.concat(errorsFromNextSteps); - } - } - checks.validateNoLeftRecursion = validateNoLeftRecursion; - function getFirstNoneTerminal(definition) { - var result = []; - if ((0, isEmpty_1.default)(definition)) { - return result; - } - var firstProd = (0, first_1.default)(definition); - /* istanbul ignore else */ - if (firstProd instanceof gast_2.NonTerminal) { - result.push(firstProd.referencedRule); - } - else if (firstProd instanceof gast_2.Alternative || - firstProd instanceof gast_2.Option || - firstProd instanceof gast_2.RepetitionMandatory || - firstProd instanceof gast_2.RepetitionMandatoryWithSeparator || - firstProd instanceof gast_2.RepetitionWithSeparator || - firstProd instanceof gast_2.Repetition) { - result = result.concat(getFirstNoneTerminal(firstProd.definition)); - } - else if (firstProd instanceof gast_2.Alternation) { - // each sub definition in alternation is a FLAT - result = (0, flatten_1.default)((0, map_1.default)(firstProd.definition, function (currSubDef) { - return getFirstNoneTerminal(currSubDef.definition); - })); - } - else if (firstProd instanceof gast_2.Terminal) ; - else { - throw Error("non exhaustive match"); - } - var isFirstOptional = (0, gast_1.isOptionalProd)(firstProd); - var hasMore = definition.length > 1; - if (isFirstOptional && hasMore) { - var rest = (0, drop_1.default)(definition); - return result.concat(getFirstNoneTerminal(rest)); - } - else { - return result; - } - } - checks.getFirstNoneTerminal = getFirstNoneTerminal; - var OrCollector = /** @class */ (function (_super) { - __extends(OrCollector, _super); - function OrCollector() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.alternations = []; - return _this; - } - OrCollector.prototype.visitAlternation = function (node) { - this.alternations.push(node); - }; - return OrCollector; - }(gast_3.GAstVisitor)); - function validateEmptyOrAlternative(topLevelRule, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - var errors = (0, flatMap_1$1.default)(ors, function (currOr) { - var exceptLast = (0, dropRight_1.default)(currOr.definition); - return (0, flatMap_1$1.default)(exceptLast, function (currAlternative, currAltIdx) { - var possibleFirstInAlt = (0, interpreter_1.nextPossibleTokensAfter)([currAlternative], [], tokens_1.tokenStructuredMatcher, 1); - if ((0, isEmpty_1.default)(possibleFirstInAlt)) { - return [ - { - message: errMsgProvider.buildEmptyAlternationError({ - topLevelRule: topLevelRule, - alternation: currOr, - emptyChoiceIdx: currAltIdx - }), - type: parser_1.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, - ruleName: topLevelRule.name, - occurrence: currOr.idx, - alternative: currAltIdx + 1 - } - ]; - } - else { - return []; - } - }); - }); - return errors; - } - checks.validateEmptyOrAlternative = validateEmptyOrAlternative; - function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - // New Handling of ignoring ambiguities - // - https://github.com/chevrotain/chevrotain/issues/869 - ors = (0, reject_1$1.default)(ors, function (currOr) { return currOr.ignoreAmbiguities === true; }); - var errors = (0, flatMap_1$1.default)(ors, function (currOr) { - var currOccurrence = currOr.idx; - var actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead; - var alternatives = (0, lookahead_1.getLookaheadPathsForOr)(currOccurrence, topLevelRule, actualMaxLookahead, currOr); - var altsAmbiguityErrors = checkAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); - var altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); - return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors); - }); - return errors; - } - checks.validateAmbiguousAlternationAlternatives = validateAmbiguousAlternationAlternatives; - var RepetitionCollector = /** @class */ (function (_super) { - __extends(RepetitionCollector, _super); - function RepetitionCollector() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.allProductions = []; - return _this; - } - RepetitionCollector.prototype.visitRepetitionWithSeparator = function (manySep) { - this.allProductions.push(manySep); - }; - RepetitionCollector.prototype.visitRepetitionMandatory = function (atLeastOne) { - this.allProductions.push(atLeastOne); - }; - RepetitionCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { - this.allProductions.push(atLeastOneSep); - }; - RepetitionCollector.prototype.visitRepetition = function (many) { - this.allProductions.push(many); - }; - return RepetitionCollector; - }(gast_3.GAstVisitor)); - checks.RepetitionCollector = RepetitionCollector; - function validateTooManyAlts(topLevelRule, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - var errors = (0, flatMap_1$1.default)(ors, function (currOr) { - if (currOr.definition.length > 255) { - return [ - { - message: errMsgProvider.buildTooManyAlternativesError({ - topLevelRule: topLevelRule, - alternation: currOr - }), - type: parser_1.ParserDefinitionErrorType.TOO_MANY_ALTS, - ruleName: topLevelRule.name, - occurrence: currOr.idx - } - ]; - } - else { - return []; - } - }); - return errors; - } - checks.validateTooManyAlts = validateTooManyAlts; - function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) { - var errors = []; - (0, forEach_1.default)(topLevelRules, function (currTopRule) { - var collectorVisitor = new RepetitionCollector(); - currTopRule.accept(collectorVisitor); - var allRuleProductions = collectorVisitor.allProductions; - (0, forEach_1.default)(allRuleProductions, function (currProd) { - var prodType = (0, lookahead_1.getProdType)(currProd); - var actualMaxLookahead = currProd.maxLookahead || maxLookahead; - var currOccurrence = currProd.idx; - var paths = (0, lookahead_1.getLookaheadPathsForOptionalProd)(currOccurrence, currTopRule, prodType, actualMaxLookahead); - var pathsInsideProduction = paths[0]; - if ((0, isEmpty_1.default)((0, flatten_1.default)(pathsInsideProduction))) { - var errMsg = errMsgProvider.buildEmptyRepetitionError({ - topLevelRule: currTopRule, - repetition: currProd - }); - errors.push({ - message: errMsg, - type: parser_1.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, - ruleName: currTopRule.name - }); - } - }); - }); - return errors; - } - checks.validateSomeNonEmptyLookaheadPath = validateSomeNonEmptyLookaheadPath; - function checkAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { - var foundAmbiguousPaths = []; - var identicalAmbiguities = (0, reduce_1.default)(alternatives, function (result, currAlt, currAltIdx) { - // ignore (skip) ambiguities with this alternative - if (alternation.definition[currAltIdx].ignoreAmbiguities === true) { - return result; - } - (0, forEach_1.default)(currAlt, function (currPath) { - var altsCurrPathAppearsIn = [currAltIdx]; - (0, forEach_1.default)(alternatives, function (currOtherAlt, currOtherAltIdx) { - if (currAltIdx !== currOtherAltIdx && - (0, lookahead_1.containsPath)(currOtherAlt, currPath) && - // ignore (skip) ambiguities with this "other" alternative - alternation.definition[currOtherAltIdx].ignoreAmbiguities !== true) { - altsCurrPathAppearsIn.push(currOtherAltIdx); - } - }); - if (altsCurrPathAppearsIn.length > 1 && - !(0, lookahead_1.containsPath)(foundAmbiguousPaths, currPath)) { - foundAmbiguousPaths.push(currPath); - result.push({ - alts: altsCurrPathAppearsIn, - path: currPath - }); - } - }); - return result; - }, []); - var currErrors = (0, map_1.default)(identicalAmbiguities, function (currAmbDescriptor) { - var ambgIndices = (0, map_1.default)(currAmbDescriptor.alts, function (currAltIdx) { return currAltIdx + 1; }); - var currMessage = errMsgProvider.buildAlternationAmbiguityError({ - topLevelRule: rule, - alternation: alternation, - ambiguityIndices: ambgIndices, - prefixPath: currAmbDescriptor.path - }); - return { - message: currMessage, - type: parser_1.ParserDefinitionErrorType.AMBIGUOUS_ALTS, - ruleName: rule.name, - occurrence: alternation.idx, - alternatives: currAmbDescriptor.alts - }; - }); - return currErrors; + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress); + } // React DevTools reads this flag. + + + workInProgress.flags |= PerformedWork; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; } - function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { - // flatten - var pathsAndIndices = (0, reduce_1.default)(alternatives, function (result, currAlt, idx) { - var currPathsAndIdx = (0, map_1.default)(currAlt, function (currPath) { - return { idx: idx, path: currPath }; - }); - return result.concat(currPathsAndIdx); - }, []); - var errors = (0, compact_1$1.default)((0, flatMap_1$1.default)(pathsAndIndices, function (currPathAndIdx) { - var alternativeGast = alternation.definition[currPathAndIdx.idx]; - // ignore (skip) ambiguities with this alternative - if (alternativeGast.ignoreAmbiguities === true) { - return []; + + function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) { + { + // This is used by DevTools to force a boundary to error. + switch (shouldError(workInProgress)) { + case false: + { + var _instance = workInProgress.stateNode; + var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack. + // Is there a better way to do this? + + var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context); + var state = tempInstance.state; + + _instance.updater.enqueueSetState(_instance, state, null); + + break; } - var targetIdx = currPathAndIdx.idx; - var targetPath = currPathAndIdx.path; - var prefixAmbiguitiesPathsAndIndices = (0, filter_1$1.default)(pathsAndIndices, function (searchPathAndIdx) { - // prefix ambiguity can only be created from lower idx (higher priority) path - return ( - // ignore (skip) ambiguities with this "other" alternative - alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities !== - true && - searchPathAndIdx.idx < targetIdx && - // checking for strict prefix because identical lookaheads - // will be be detected using a different validation. - (0, lookahead_1.isStrictPrefixOfPath)(searchPathAndIdx.path, targetPath)); - }); - var currPathPrefixErrors = (0, map_1.default)(prefixAmbiguitiesPathsAndIndices, function (currAmbPathAndIdx) { - var ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1]; - var occurrence = alternation.idx === 0 ? "" : alternation.idx; - var message = errMsgProvider.buildAlternationPrefixAmbiguityError({ - topLevelRule: rule, - alternation: alternation, - ambiguityIndices: ambgIndices, - prefixPath: currAmbPathAndIdx.path - }); - return { - message: message, - type: parser_1.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, - ruleName: rule.name, - occurrence: occurrence, - alternatives: ambgIndices - }; - }); - return currPathPrefixErrors; - })); - return errors; - } - checks.checkPrefixAlternativesAmbiguities = checkPrefixAlternativesAmbiguities; - function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) { - var errors = []; - var tokenNames = (0, map_1.default)(tokenTypes, function (currToken) { return currToken.name; }); - (0, forEach_1.default)(topLevels, function (currRule) { - var currRuleName = currRule.name; - if ((0, includes_1.default)(tokenNames, currRuleName)) { - var errMsg = errMsgProvider.buildNamespaceConflictError(currRule); - errors.push({ - message: errMsg, - type: parser_1.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, - ruleName: currRuleName - }); + + case true: + { + workInProgress.flags |= DidCapture; + workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes + + var error$1 = new Error('Simulated error coming from DevTools'); + var lane = pickArbitraryLane(renderLanes); + workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state + + var update = createClassErrorUpdate(workInProgress, createCapturedValue(error$1, workInProgress), lane); + enqueueCapturedUpdate(workInProgress, update); + break; } - }); - return errors; - } - - return checks; -} + } -var hasRequiredGast_resolver_public; + if (workInProgress.type !== workInProgress.elementType) { + // Lazy component props can't be validated in createElement + // because they're only guaranteed to be resolved here. + var innerPropTypes = Component.propTypes; -function requireGast_resolver_public () { - if (hasRequiredGast_resolver_public) return gast_resolver_public; - hasRequiredGast_resolver_public = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(gast_resolver_public, "__esModule", { value: true }); - gast_resolver_public.validateGrammar = gast_resolver_public.resolveGrammar = void 0; - var forEach_1 = __importDefault(forEach_1$4); - var defaults_1$1 = __importDefault(defaults_1); - var resolver_1 = requireResolver(); - var checks_1 = requireChecks(); - var errors_public_1 = errors_public; - function resolveGrammar(options) { - var actualOptions = (0, defaults_1$1.default)(options, { - errMsgProvider: errors_public_1.defaultGrammarResolverErrorProvider - }); - var topRulesTable = {}; - (0, forEach_1.default)(options.rules, function (rule) { - topRulesTable[rule.name] = rule; - }); - return (0, resolver_1.resolveGrammar)(topRulesTable, actualOptions.errMsgProvider); - } - gast_resolver_public.resolveGrammar = resolveGrammar; - function validateGrammar(options) { - options = (0, defaults_1$1.default)(options, { - errMsgProvider: errors_public_1.defaultGrammarValidatorErrorProvider - }); - return (0, checks_1.validateGrammar)(options.rules, options.maxLookahead, options.tokenTypes, options.errMsgProvider, options.grammarName); - } - gast_resolver_public.validateGrammar = validateGrammar; - - return gast_resolver_public; -} + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(Component)); + } + } + } // Push context providers early to prevent context stack mismatches. + // During mounting we don't know the child context yet as the instance doesn't exist. + // We will invalidate the child context in finishClassComponent() right after rendering. -var recoverable = {}; -var exceptions_public = {}; + var hasContext; -/* istanbul ignore next */ var __extends$1 = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$3 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exceptions_public, "__esModule", { value: true }); -exceptions_public.EarlyExitException = exceptions_public.NotAllInputParsedException = exceptions_public.NoViableAltException = exceptions_public.MismatchedTokenException = exceptions_public.isRecognitionException = void 0; -var includes_1 = __importDefault$3(includes_1$2); -var MISMATCHED_TOKEN_EXCEPTION = "MismatchedTokenException"; -var NO_VIABLE_ALT_EXCEPTION = "NoViableAltException"; -var EARLY_EXIT_EXCEPTION = "EarlyExitException"; -var NOT_ALL_INPUT_PARSED_EXCEPTION = "NotAllInputParsedException"; -var RECOGNITION_EXCEPTION_NAMES = [ - MISMATCHED_TOKEN_EXCEPTION, - NO_VIABLE_ALT_EXCEPTION, - EARLY_EXIT_EXCEPTION, - NOT_ALL_INPUT_PARSED_EXCEPTION -]; -Object.freeze(RECOGNITION_EXCEPTION_NAMES); -// hacks to bypass no support for custom Errors in javascript/typescript -function isRecognitionException(error) { - // can't do instanceof on hacked custom js exceptions - return (0, includes_1.default)(RECOGNITION_EXCEPTION_NAMES, error.name); -} -exceptions_public.isRecognitionException = isRecognitionException; -var RecognitionException = /** @class */ (function (_super) { - __extends$1(RecognitionException, _super); - function RecognitionException(message, token) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) /* istanbul ignore next */ || this; - _this.token = token; - _this.resyncedTokens = []; - // fix prototype chain when typescript target is ES5 - Object.setPrototypeOf(_this, _newTarget.prototype); - /* istanbul ignore next - V8 workaround to remove constructor from stacktrace when typescript target is ES5 */ - if (Error.captureStackTrace) { - Error.captureStackTrace(_this, _this.constructor); - } - return _this; - } - return RecognitionException; -}(Error)); -var MismatchedTokenException = /** @class */ (function (_super) { - __extends$1(MismatchedTokenException, _super); - function MismatchedTokenException(message, token, previousToken) { - var _this = _super.call(this, message, token) /* istanbul ignore next */ || this; - _this.previousToken = previousToken; - _this.name = MISMATCHED_TOKEN_EXCEPTION; - return _this; - } - return MismatchedTokenException; -}(RecognitionException)); -exceptions_public.MismatchedTokenException = MismatchedTokenException; -var NoViableAltException = /** @class */ (function (_super) { - __extends$1(NoViableAltException, _super); - function NoViableAltException(message, token, previousToken) { - var _this = _super.call(this, message, token) /* istanbul ignore next */ || this; - _this.previousToken = previousToken; - _this.name = NO_VIABLE_ALT_EXCEPTION; - return _this; - } - return NoViableAltException; -}(RecognitionException)); -exceptions_public.NoViableAltException = NoViableAltException; -var NotAllInputParsedException = /** @class */ (function (_super) { - __extends$1(NotAllInputParsedException, _super); - function NotAllInputParsedException(message, token) { - var _this = _super.call(this, message, token) /* istanbul ignore next */ || this; - _this.name = NOT_ALL_INPUT_PARSED_EXCEPTION; - return _this; - } - return NotAllInputParsedException; -}(RecognitionException)); -exceptions_public.NotAllInputParsedException = NotAllInputParsedException; -var EarlyExitException = /** @class */ (function (_super) { - __extends$1(EarlyExitException, _super); - function EarlyExitException(message, token, previousToken) { - var _this = _super.call(this, message, token) /* istanbul ignore next */ || this; - _this.previousToken = previousToken; - _this.name = EARLY_EXIT_EXCEPTION; - return _this; - } - return EarlyExitException; -}(RecognitionException)); -exceptions_public.EarlyExitException = EarlyExitException; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress); + } else { + hasContext = false; + } -var hasRequiredRecoverable; + prepareToReadContext(workInProgress, renderLanes); + var instance = workInProgress.stateNode; + var shouldUpdate; -function requireRecoverable () { - if (hasRequiredRecoverable) return recoverable; - hasRequiredRecoverable = 1; - (function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.attemptInRepetitionRecovery = exports.Recoverable = exports.InRuleRecoveryException = exports.IN_RULE_RECOVERY_EXCEPTION = exports.EOF_FOLLOW_KEY = void 0; - var tokens_public_1 = tokens_public; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var dropRight_1 = __importDefault(dropRight_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var map_1 = __importDefault(map_1$4); - var find_1$1 = __importDefault(find_1); - var has_1$1 = __importDefault(has_1); - var includes_1 = __importDefault(includes_1$2); - var clone_1 = __importDefault(clone_1$1); - var exceptions_public_1 = exceptions_public; - var constants_1 = constants; - var parser_1 = requireParser(); - exports.EOF_FOLLOW_KEY = {}; - exports.IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException"; - var InRuleRecoveryException = /** @class */ (function (_super) { - __extends(InRuleRecoveryException, _super); - function InRuleRecoveryException(message) { - var _this = _super.call(this, message) || this; - _this.name = exports.IN_RULE_RECOVERY_EXCEPTION; - return _this; - } - return InRuleRecoveryException; - }(Error)); - exports.InRuleRecoveryException = InRuleRecoveryException; - /** - * This trait is responsible for the error recovery and fault tolerant logic - */ - var Recoverable = /** @class */ (function () { - function Recoverable() { - } - Recoverable.prototype.initRecoverable = function (config) { - this.firstAfterRepMap = {}; - this.resyncFollows = {}; - this.recoveryEnabled = (0, has_1$1.default)(config, "recoveryEnabled") - ? config.recoveryEnabled // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.recoveryEnabled; - // performance optimization, NOOP will be inlined which - // effectively means that this optional feature does not exist - // when not used. - if (this.recoveryEnabled) { - this.attemptInRepetitionRecovery = attemptInRepetitionRecovery; - } - }; - Recoverable.prototype.getTokenToInsert = function (tokType) { - var tokToInsert = (0, tokens_public_1.createTokenInstance)(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN); - tokToInsert.isInsertedInRecovery = true; - return tokToInsert; - }; - Recoverable.prototype.canTokenTypeBeInsertedInRecovery = function (tokType) { - return true; - }; - Recoverable.prototype.canTokenTypeBeDeletedInRecovery = function (tokType) { - return true; - }; - Recoverable.prototype.tryInRepetitionRecovery = function (grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) { - var _this = this; - // TODO: can the resyncTokenType be cached? - var reSyncTokType = this.findReSyncTokenType(); - var savedLexerState = this.exportLexerState(); - var resyncedTokens = []; - var passedResyncPoint = false; - var nextTokenWithoutResync = this.LA(1); - var currToken = this.LA(1); - var generateErrorMessage = function () { - var previousToken = _this.LA(0); - // we are preemptively re-syncing before an error has been detected, therefor we must reproduce - // the error that would have been thrown - var msg = _this.errorMessageProvider.buildMismatchTokenMessage({ - expected: expectedTokType, - actual: nextTokenWithoutResync, - previous: previousToken, - ruleName: _this.getCurrRuleFullName() - }); - var error = new exceptions_public_1.MismatchedTokenException(msg, nextTokenWithoutResync, _this.LA(0)); - // the first token here will be the original cause of the error, this is not part of the resyncedTokens property. - error.resyncedTokens = (0, dropRight_1.default)(resyncedTokens); - _this.SAVE_ERROR(error); - }; - while (!passedResyncPoint) { - // re-synced to a point where we can safely exit the repetition/ - if (this.tokenMatcher(currToken, expectedTokType)) { - generateErrorMessage(); - return; // must return here to avoid reverting the inputIdx - } - else if (lookAheadFunc.call(this)) { - // we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule - generateErrorMessage(); - // recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule - grammarRule.apply(this, grammarRuleArgs); - return; // must return here to avoid reverting the inputIdx - } - else if (this.tokenMatcher(currToken, reSyncTokType)) { - passedResyncPoint = true; - } - else { - currToken = this.SKIP_TOKEN(); - this.addToResyncTokens(currToken, resyncedTokens); - } - } - // we were unable to find a CLOSER point to resync inside the Repetition, reset the state. - // The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by - // "between rules" resync recovery later in the flow. - this.importLexerState(savedLexerState); - }; - Recoverable.prototype.shouldInRepetitionRecoveryBeTried = function (expectTokAfterLastMatch, nextTokIdx, notStuck) { - // Edge case of arriving from a MANY repetition which is stuck - // Attempting recovery in this case could cause an infinite loop - if (notStuck === false) { - return false; - } - // no need to recover, next token is what we expect... - if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) { - return false; - } - // error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path - // and prefer some backtracking path that includes recovered errors. - if (this.isBackTracking()) { - return false; - } - // if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm - // because if it works, it makes the least amount of changes to the input stream (greedy algorithm) - //noinspection RedundantIfStatementJS - if (this.canPerformInRuleRecovery(expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx))) { - return false; - } - return true; - }; - // Error Recovery functionality - Recoverable.prototype.getFollowsForInRuleRecovery = function (tokType, tokIdxInRule) { - var grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule); - var follows = this.getNextPossibleTokenTypes(grammarPath); - return follows; - }; - Recoverable.prototype.tryInRuleRecovery = function (expectedTokType, follows) { - if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) { - var tokToInsert = this.getTokenToInsert(expectedTokType); - return tokToInsert; - } - if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) { - var nextTok = this.SKIP_TOKEN(); - this.consumeToken(); - return nextTok; - } - throw new InRuleRecoveryException("sad sad panda"); - }; - Recoverable.prototype.canPerformInRuleRecovery = function (expectedToken, follows) { - return (this.canRecoverWithSingleTokenInsertion(expectedToken, follows) || - this.canRecoverWithSingleTokenDeletion(expectedToken)); - }; - Recoverable.prototype.canRecoverWithSingleTokenInsertion = function (expectedTokType, follows) { - var _this = this; - if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) { - return false; - } - // must know the possible following tokens to perform single token insertion - if ((0, isEmpty_1.default)(follows)) { - return false; - } - var mismatchedTok = this.LA(1); - var isMisMatchedTokInFollows = (0, find_1$1.default)(follows, function (possibleFollowsTokType) { - return _this.tokenMatcher(mismatchedTok, possibleFollowsTokType); - }) !== undefined; - return isMisMatchedTokInFollows; - }; - Recoverable.prototype.canRecoverWithSingleTokenDeletion = function (expectedTokType) { - if (!this.canTokenTypeBeDeletedInRecovery(expectedTokType)) { - return false; - } - var isNextTokenWhatIsExpected = this.tokenMatcher(this.LA(2), expectedTokType); - return isNextTokenWhatIsExpected; - }; - Recoverable.prototype.isInCurrentRuleReSyncSet = function (tokenTypeIdx) { - var followKey = this.getCurrFollowKey(); - var currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey); - return (0, includes_1.default)(currentRuleReSyncSet, tokenTypeIdx); - }; - Recoverable.prototype.findReSyncTokenType = function () { - var allPossibleReSyncTokTypes = this.flattenFollowSet(); - // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input - var nextToken = this.LA(1); - var k = 2; - while (true) { - var foundMatch = (0, find_1$1.default)(allPossibleReSyncTokTypes, function (resyncTokType) { - var canMatch = (0, tokens_public_1.tokenMatcher)(nextToken, resyncTokType); - return canMatch; - }); - if (foundMatch !== undefined) { - return foundMatch; - } - nextToken = this.LA(k); - k++; - } - }; - Recoverable.prototype.getCurrFollowKey = function () { - // the length is at least one as we always add the ruleName to the stack before invoking the rule. - if (this.RULE_STACK.length === 1) { - return exports.EOF_FOLLOW_KEY; - } - var currRuleShortName = this.getLastExplicitRuleShortName(); - var currRuleIdx = this.getLastExplicitRuleOccurrenceIndex(); - var prevRuleShortName = this.getPreviousExplicitRuleShortName(); - return { - ruleName: this.shortRuleNameToFullName(currRuleShortName), - idxInCallingRule: currRuleIdx, - inRule: this.shortRuleNameToFullName(prevRuleShortName) - }; - }; - Recoverable.prototype.buildFullFollowKeyStack = function () { - var _this = this; - var explicitRuleStack = this.RULE_STACK; - var explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK; - return (0, map_1.default)(explicitRuleStack, function (ruleName, idx) { - if (idx === 0) { - return exports.EOF_FOLLOW_KEY; - } - return { - ruleName: _this.shortRuleNameToFullName(ruleName), - idxInCallingRule: explicitOccurrenceStack[idx], - inRule: _this.shortRuleNameToFullName(explicitRuleStack[idx - 1]) - }; - }); - }; - Recoverable.prototype.flattenFollowSet = function () { - var _this = this; - var followStack = (0, map_1.default)(this.buildFullFollowKeyStack(), function (currKey) { - return _this.getFollowSetFromFollowKey(currKey); - }); - return (0, flatten_1.default)(followStack); - }; - Recoverable.prototype.getFollowSetFromFollowKey = function (followKey) { - if (followKey === exports.EOF_FOLLOW_KEY) { - return [tokens_public_1.EOF]; - } - var followName = followKey.ruleName + followKey.idxInCallingRule + constants_1.IN + followKey.inRule; - return this.resyncFollows[followName]; - }; - // It does not make any sense to include a virtual EOF token in the list of resynced tokens - // as EOF does not really exist and thus does not contain any useful information (line/column numbers) - Recoverable.prototype.addToResyncTokens = function (token, resyncTokens) { - if (!this.tokenMatcher(token, tokens_public_1.EOF)) { - resyncTokens.push(token); - } - return resyncTokens; - }; - Recoverable.prototype.reSyncTo = function (tokType) { - var resyncedTokens = []; - var nextTok = this.LA(1); - while (this.tokenMatcher(nextTok, tokType) === false) { - nextTok = this.SKIP_TOKEN(); - this.addToResyncTokens(nextTok, resyncedTokens); - } - // the last token is not part of the error. - return (0, dropRight_1.default)(resyncedTokens); - }; - Recoverable.prototype.attemptInRepetitionRecovery = function (prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { - // by default this is a NO-OP - // The actual implementation is with the function(not method) below - }; - Recoverable.prototype.getCurrentGrammarPath = function (tokType, tokIdxInRule) { - var pathRuleStack = this.getHumanReadableRuleStack(); - var pathOccurrenceStack = (0, clone_1.default)(this.RULE_OCCURRENCE_STACK); - var grammarPath = { - ruleStack: pathRuleStack, - occurrenceStack: pathOccurrenceStack, - lastTok: tokType, - lastTokOccurrence: tokIdxInRule - }; - return grammarPath; - }; - Recoverable.prototype.getHumanReadableRuleStack = function () { - var _this = this; - return (0, map_1.default)(this.RULE_STACK, function (currShortName) { - return _this.shortRuleNameToFullName(currShortName); - }); - }; - return Recoverable; - }()); - exports.Recoverable = Recoverable; - function attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { - var key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence); - var firstAfterRepInfo = this.firstAfterRepMap[key]; - if (firstAfterRepInfo === undefined) { - var currRuleName = this.getCurrRuleFullName(); - var ruleGrammar = this.getGAstProductions()[currRuleName]; - var walker = new nextToksWalker(ruleGrammar, prodOccurrence); - firstAfterRepInfo = walker.startWalking(); - this.firstAfterRepMap[key] = firstAfterRepInfo; - } - var expectTokAfterLastMatch = firstAfterRepInfo.token; - var nextTokIdx = firstAfterRepInfo.occurrence; - var isEndOfRule = firstAfterRepInfo.isEndOfRule; - // special edge case of a TOP most repetition after which the input should END. - // this will force an attempt for inRule recovery in that scenario. - if (this.RULE_STACK.length === 1 && - isEndOfRule && - expectTokAfterLastMatch === undefined) { - expectTokAfterLastMatch = tokens_public_1.EOF; - nextTokIdx = 1; - } - // We don't have anything to re-sync to... - // this condition was extracted from `shouldInRepetitionRecoveryBeTried` to act as a type-guard - if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) { - return; - } - if (this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck)) { - // TODO: performance optimization: instead of passing the original args here, we modify - // the args param (or create a new one) and make sure the lookahead func is explicitly provided - // to avoid searching the cache for it once more. - this.tryInRepetitionRecovery(prodFunc, args, lookaheadFunc, expectTokAfterLastMatch); - } - } - exports.attemptInRepetitionRecovery = attemptInRepetitionRecovery; - -} (recoverable)); - return recoverable; -} - -var looksahead = {}; - -var keys = {}; - -(function (exports) { - // Lookahead keys are 32Bit integers in the form - // TTTTTTTT-ZZZZZZZZZZZZ-YYYY-XXXXXXXX - // XXXX -> Occurrence Index bitmap. - // YYYY -> DSL Method Type bitmap. - // ZZZZZZZZZZZZZZZ -> Rule short Index bitmap. - // TTTTTTTTT -> alternation alternative index bitmap - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getKeyForAutomaticLookahead = exports.AT_LEAST_ONE_SEP_IDX = exports.MANY_SEP_IDX = exports.AT_LEAST_ONE_IDX = exports.MANY_IDX = exports.OPTION_IDX = exports.OR_IDX = exports.BITS_FOR_ALT_IDX = exports.BITS_FOR_RULE_IDX = exports.BITS_FOR_OCCURRENCE_IDX = exports.BITS_FOR_METHOD_TYPE = void 0; - exports.BITS_FOR_METHOD_TYPE = 4; - exports.BITS_FOR_OCCURRENCE_IDX = 8; - exports.BITS_FOR_RULE_IDX = 12; - // TODO: validation, this means that there may at most 2^8 --> 256 alternatives for an alternation. - exports.BITS_FOR_ALT_IDX = 8; - // short string used as part of mapping keys. - // being short improves the performance when composing KEYS for maps out of these - // The 5 - 8 bits (16 possible values, are reserved for the DSL method indices) - exports.OR_IDX = 1 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.OPTION_IDX = 2 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.MANY_IDX = 3 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.AT_LEAST_ONE_IDX = 4 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.MANY_SEP_IDX = 5 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.AT_LEAST_ONE_SEP_IDX = 6 << exports.BITS_FOR_OCCURRENCE_IDX; - // this actually returns a number, but it is always used as a string (object prop key) - function getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) { - return occurrence | dslMethodIdx | ruleIdx; - } - exports.getKeyForAutomaticLookahead = getKeyForAutomaticLookahead; - 32 - exports.BITS_FOR_ALT_IDX; - -} (keys)); - -var hasRequiredLooksahead; - -function requireLooksahead () { - if (hasRequiredLooksahead) return looksahead; - hasRequiredLooksahead = 1; - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(looksahead, "__esModule", { value: true }); - looksahead.collectMethods = looksahead.LooksAhead = void 0; - var lookahead_1 = lookahead; - var forEach_1 = __importDefault(forEach_1$4); - var has_1$1 = __importDefault(has_1); - var parser_1 = requireParser(); - var keys_1 = keys; - var gast_1 = api$1; - var gast_2 = api$1; - /** - * Trait responsible for the lookahead related utilities and optimizations. - */ - var LooksAhead = /** @class */ (function () { - function LooksAhead() { - } - LooksAhead.prototype.initLooksAhead = function (config) { - this.dynamicTokensEnabled = (0, has_1$1.default)(config, "dynamicTokensEnabled") - ? config.dynamicTokensEnabled // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled; - this.maxLookahead = (0, has_1$1.default)(config, "maxLookahead") - ? config.maxLookahead // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.maxLookahead; - this.lookAheadFuncsCache = new Map(); - }; - LooksAhead.prototype.preComputeLookaheadFunctions = function (rules) { - var _this = this; - (0, forEach_1.default)(rules, function (currRule) { - _this.TRACE_INIT("".concat(currRule.name, " Rule Lookahead"), function () { - var _a = collectMethods(currRule), alternation = _a.alternation, repetition = _a.repetition, option = _a.option, repetitionMandatory = _a.repetitionMandatory, repetitionMandatoryWithSeparator = _a.repetitionMandatoryWithSeparator, repetitionWithSeparator = _a.repetitionWithSeparator; - (0, forEach_1.default)(alternation, function (currProd) { - var prodIdx = currProd.idx === 0 ? "" : currProd.idx; - _this.TRACE_INIT("".concat((0, gast_2.getProductionDslName)(currProd)).concat(prodIdx), function () { - var laFunc = (0, lookahead_1.buildLookaheadFuncForOr)(currProd.idx, currRule, currProd.maxLookahead || _this.maxLookahead, currProd.hasPredicates, _this.dynamicTokensEnabled, _this.lookAheadBuilderForAlternatives); - var key = (0, keys_1.getKeyForAutomaticLookahead)(_this.fullRuleNameToShort[currRule.name], keys_1.OR_IDX, currProd.idx); - _this.setLaFuncCache(key, laFunc); - }); - }); - (0, forEach_1.default)(repetition, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.MANY_IDX, lookahead_1.PROD_TYPE.REPETITION, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - (0, forEach_1.default)(option, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.OPTION_IDX, lookahead_1.PROD_TYPE.OPTION, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - (0, forEach_1.default)(repetitionMandatory, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.AT_LEAST_ONE_IDX, lookahead_1.PROD_TYPE.REPETITION_MANDATORY, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - (0, forEach_1.default)(repetitionMandatoryWithSeparator, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.AT_LEAST_ONE_SEP_IDX, lookahead_1.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - (0, forEach_1.default)(repetitionWithSeparator, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.MANY_SEP_IDX, lookahead_1.PROD_TYPE.REPETITION_WITH_SEPARATOR, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - }); - }); - }; - LooksAhead.prototype.computeLookaheadFunc = function (rule, prodOccurrence, prodKey, prodType, prodMaxLookahead, dslMethodName) { - var _this = this; - this.TRACE_INIT("".concat(dslMethodName).concat(prodOccurrence === 0 ? "" : prodOccurrence), function () { - var laFunc = (0, lookahead_1.buildLookaheadFuncForOptionalProd)(prodOccurrence, rule, prodMaxLookahead || _this.maxLookahead, _this.dynamicTokensEnabled, prodType, _this.lookAheadBuilderForOptional); - var key = (0, keys_1.getKeyForAutomaticLookahead)(_this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence); - _this.setLaFuncCache(key, laFunc); - }); - }; - LooksAhead.prototype.lookAheadBuilderForOptional = function (alt, tokenMatcher, dynamicTokensEnabled) { - return (0, lookahead_1.buildSingleAlternativeLookaheadFunction)(alt, tokenMatcher, dynamicTokensEnabled); - }; - LooksAhead.prototype.lookAheadBuilderForAlternatives = function (alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { - return (0, lookahead_1.buildAlternativesLookAheadFunc)(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled); - }; - // this actually returns a number, but it is always used as a string (object prop key) - LooksAhead.prototype.getKeyForAutomaticLookahead = function (dslMethodIdx, occurrence) { - var currRuleShortName = this.getLastExplicitRuleShortName(); - return (0, keys_1.getKeyForAutomaticLookahead)(currRuleShortName, dslMethodIdx, occurrence); - }; - LooksAhead.prototype.getLaFuncFromCache = function (key) { - return this.lookAheadFuncsCache.get(key); - }; - /* istanbul ignore next */ - LooksAhead.prototype.setLaFuncCache = function (key, value) { - this.lookAheadFuncsCache.set(key, value); - }; - return LooksAhead; - }()); - looksahead.LooksAhead = LooksAhead; - var DslMethodsCollectorVisitor = /** @class */ (function (_super) { - __extends(DslMethodsCollectorVisitor, _super); - function DslMethodsCollectorVisitor() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.dslMethods = { - option: [], - alternation: [], - repetition: [], - repetitionWithSeparator: [], - repetitionMandatory: [], - repetitionMandatoryWithSeparator: [] - }; - return _this; - } - DslMethodsCollectorVisitor.prototype.reset = function () { - this.dslMethods = { - option: [], - alternation: [], - repetition: [], - repetitionWithSeparator: [], - repetitionMandatory: [], - repetitionMandatoryWithSeparator: [] - }; - }; - DslMethodsCollectorVisitor.prototype.visitOption = function (option) { - this.dslMethods.option.push(option); - }; - DslMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (manySep) { - this.dslMethods.repetitionWithSeparator.push(manySep); - }; - DslMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (atLeastOne) { - this.dslMethods.repetitionMandatory.push(atLeastOne); - }; - DslMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { - this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep); - }; - DslMethodsCollectorVisitor.prototype.visitRepetition = function (many) { - this.dslMethods.repetition.push(many); - }; - DslMethodsCollectorVisitor.prototype.visitAlternation = function (or) { - this.dslMethods.alternation.push(or); - }; - return DslMethodsCollectorVisitor; - }(gast_1.GAstVisitor)); - var collectorVisitor = new DslMethodsCollectorVisitor(); - function collectMethods(rule) { - collectorVisitor.reset(); - rule.accept(collectorVisitor); - var dslMethods = collectorVisitor.dslMethods; - // avoid uncleaned references - collectorVisitor.reset(); - return dslMethods; - } - looksahead.collectMethods = collectMethods; - - return looksahead; -} + if (instance === null) { + if (current !== null) { + // A class component without an instance only mounts if it suspended + // inside a non-concurrent tree, in an inconsistent state. We want to + // treat it like a new mount, even though an empty version of it already + // committed. Disconnect the alternate pointers. + current.alternate = null; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect -var tree_builder = {}; + workInProgress.flags |= Placement; + } // In the initial pass we might need to construct the instance. -var cst = {}; -Object.defineProperty(cst, "__esModule", { value: true }); -cst.addNoneTerminalToCst = cst.addTerminalToCst = cst.setNodeLocationFull = cst.setNodeLocationOnlyOffset = void 0; -/** - * This nodeLocation tracking is not efficient and should only be used - * when error recovery is enabled or the Token Vector contains virtual Tokens - * (e.g, Python Indent/Outdent) - * As it executes the calculation for every single terminal/nonTerminal - * and does not rely on the fact the token vector is **sorted** - */ -function setNodeLocationOnlyOffset(currNodeLocation, newLocationInfo) { - // First (valid) update for this cst node - if (isNaN(currNodeLocation.startOffset) === true) { - // assumption1: Token location information is either NaN or a valid number - // assumption2: Token location information is fully valid if it exist - // (both start/end offsets exist and are numbers). - currNodeLocation.startOffset = newLocationInfo.startOffset; - currNodeLocation.endOffset = newLocationInfo.endOffset; - } - // Once the startOffset has been updated with a valid number it should never receive - // any farther updates as the Token vector is sorted. - // We still have to check this this condition for every new possible location info - // because with error recovery enabled we may encounter invalid tokens (NaN location props) - else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { - currNodeLocation.endOffset = newLocationInfo.endOffset; - } -} -cst.setNodeLocationOnlyOffset = setNodeLocationOnlyOffset; -/** - * This nodeLocation tracking is not efficient and should only be used - * when error recovery is enabled or the Token Vector contains virtual Tokens - * (e.g, Python Indent/Outdent) - * As it executes the calculation for every single terminal/nonTerminal - * and does not rely on the fact the token vector is **sorted** - */ -function setNodeLocationFull(currNodeLocation, newLocationInfo) { - // First (valid) update for this cst node - if (isNaN(currNodeLocation.startOffset) === true) { - // assumption1: Token location information is either NaN or a valid number - // assumption2: Token location information is fully valid if it exist - // (all start/end props exist and are numbers). - currNodeLocation.startOffset = newLocationInfo.startOffset; - currNodeLocation.startColumn = newLocationInfo.startColumn; - currNodeLocation.startLine = newLocationInfo.startLine; - currNodeLocation.endOffset = newLocationInfo.endOffset; - currNodeLocation.endColumn = newLocationInfo.endColumn; - currNodeLocation.endLine = newLocationInfo.endLine; - } - // Once the start props has been updated with a valid number it should never receive - // any farther updates as the Token vector is sorted. - // We still have to check this this condition for every new possible location info - // because with error recovery enabled we may encounter invalid tokens (NaN location props) - else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { - currNodeLocation.endOffset = newLocationInfo.endOffset; - currNodeLocation.endColumn = newLocationInfo.endColumn; - currNodeLocation.endLine = newLocationInfo.endLine; - } -} -cst.setNodeLocationFull = setNodeLocationFull; -function addTerminalToCst(node, token, tokenTypeName) { - if (node.children[tokenTypeName] === undefined) { - node.children[tokenTypeName] = [token]; - } - else { - node.children[tokenTypeName].push(token); - } -} -cst.addTerminalToCst = addTerminalToCst; -function addNoneTerminalToCst(node, ruleName, ruleResult) { - if (node.children[ruleName] === undefined) { - node.children[ruleName] = [ruleResult]; - } - else { - node.children[ruleName].push(ruleResult); - } -} -cst.addNoneTerminalToCst = addNoneTerminalToCst; + constructClassInstance(workInProgress, Component, nextProps); + mountClassInstance(workInProgress, Component, nextProps, renderLanes); + shouldUpdate = true; + } else if (current === null) { + // In a resume, we'll already have an instance we can reuse. + shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes); + } else { + shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes); + } -var cst_visitor = {}; + var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes); -var lang_extensions = {}; + { + var inst = workInProgress.stateNode; -Object.defineProperty(lang_extensions, "__esModule", { value: true }); -lang_extensions.defineNameProp = void 0; -var NAME = "name"; -function defineNameProp(obj, nameValue) { - Object.defineProperty(obj, NAME, { - enumerable: false, - configurable: true, - writable: false, - value: nameValue - }); -} -lang_extensions.defineNameProp = defineNameProp; + if (shouldUpdate && inst.props !== nextProps) { + if (!didWarnAboutReassigningProps) { + error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component'); + } -(function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateRedundantMethods = exports.validateMissingCstMethods = exports.validateVisitor = exports.CstVisitorDefinitionError = exports.createBaseVisitorConstructorWithDefaults = exports.createBaseSemanticVisitorConstructor = exports.defaultVisit = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var compact_1$1 = __importDefault(compact_1); - var isArray_1 = __importDefault(isArray_1$1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var filter_1$1 = __importDefault(filter_1); - var keys_1$1 = __importDefault(keys_1); - var isFunction_1$1 = __importDefault(isFunction_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var includes_1 = __importDefault(includes_1$2); - var lang_extensions_1 = lang_extensions; - function defaultVisit(ctx, param) { - var childrenNames = (0, keys_1$1.default)(ctx); - var childrenNamesLength = childrenNames.length; - for (var i = 0; i < childrenNamesLength; i++) { - var currChildName = childrenNames[i]; - var currChildArray = ctx[currChildName]; - var currChildArrayLength = currChildArray.length; - for (var j = 0; j < currChildArrayLength; j++) { - var currChild = currChildArray[j]; - // distinction between Tokens Children and CstNode children - if (currChild.tokenTypeIdx === undefined) { - this[currChild.name](currChild.children, param); - } - } - } - // defaultVisit does not support generic out param - } - exports.defaultVisit = defaultVisit; - function createBaseSemanticVisitorConstructor(grammarName, ruleNames) { - var derivedConstructor = function () { }; - // can be overwritten according to: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/ - // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname - (0, lang_extensions_1.defineNameProp)(derivedConstructor, grammarName + "BaseSemantics"); - var semanticProto = { - visit: function (cstNode, param) { - // enables writing more concise visitor methods when CstNode has only a single child - if ((0, isArray_1.default)(cstNode)) { - // A CST Node's children dictionary can never have empty arrays as values - // If a key is defined there will be at least one element in the corresponding value array. - cstNode = cstNode[0]; - } - // enables passing optional CstNodes concisely. - if ((0, isUndefined_1.default)(cstNode)) { - return undefined; - } - return this[cstNode.name](cstNode.children, param); - }, - validateVisitor: function () { - var semanticDefinitionErrors = validateVisitor(this, ruleNames); - if (!(0, isEmpty_1.default)(semanticDefinitionErrors)) { - var errorMessages = (0, map_1.default)(semanticDefinitionErrors, function (currDefError) { return currDefError.msg; }); - throw Error("Errors Detected in CST Visitor <".concat(this.constructor.name, ">:\n\t") + - "".concat(errorMessages.join("\n\n").replace(/\n/g, "\n\t"))); - } - } - }; - derivedConstructor.prototype = semanticProto; - derivedConstructor.prototype.constructor = derivedConstructor; - derivedConstructor._RULE_NAMES = ruleNames; - return derivedConstructor; - } - exports.createBaseSemanticVisitorConstructor = createBaseSemanticVisitorConstructor; - function createBaseVisitorConstructorWithDefaults(grammarName, ruleNames, baseConstructor) { - var derivedConstructor = function () { }; - // can be overwritten according to: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/ - // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname - (0, lang_extensions_1.defineNameProp)(derivedConstructor, grammarName + "BaseSemanticsWithDefaults"); - var withDefaultsProto = Object.create(baseConstructor.prototype); - (0, forEach_1.default)(ruleNames, function (ruleName) { - withDefaultsProto[ruleName] = defaultVisit; - }); - derivedConstructor.prototype = withDefaultsProto; - derivedConstructor.prototype.constructor = derivedConstructor; - return derivedConstructor; - } - exports.createBaseVisitorConstructorWithDefaults = createBaseVisitorConstructorWithDefaults; - var CstVisitorDefinitionError; - (function (CstVisitorDefinitionError) { - CstVisitorDefinitionError[CstVisitorDefinitionError["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD"; - CstVisitorDefinitionError[CstVisitorDefinitionError["MISSING_METHOD"] = 1] = "MISSING_METHOD"; - })(CstVisitorDefinitionError = exports.CstVisitorDefinitionError || (exports.CstVisitorDefinitionError = {})); - function validateVisitor(visitorInstance, ruleNames) { - var missingErrors = validateMissingCstMethods(visitorInstance, ruleNames); - var redundantErrors = validateRedundantMethods(visitorInstance, ruleNames); - return missingErrors.concat(redundantErrors); - } - exports.validateVisitor = validateVisitor; - function validateMissingCstMethods(visitorInstance, ruleNames) { - var missingRuleNames = (0, filter_1$1.default)(ruleNames, function (currRuleName) { - return (0, isFunction_1$1.default)(visitorInstance[currRuleName]) === false; - }); - var errors = (0, map_1.default)(missingRuleNames, function (currRuleName) { - return { - msg: "Missing visitor method: <".concat(currRuleName, "> on ").concat((visitorInstance.constructor.name), " CST Visitor."), - type: CstVisitorDefinitionError.MISSING_METHOD, - methodName: currRuleName - }; - }); - return (0, compact_1$1.default)(errors); - } - exports.validateMissingCstMethods = validateMissingCstMethods; - var VALID_PROP_NAMES = ["constructor", "visit", "validateVisitor"]; - function validateRedundantMethods(visitorInstance, ruleNames) { - var errors = []; - for (var prop in visitorInstance) { - if ((0, isFunction_1$1.default)(visitorInstance[prop]) && - !(0, includes_1.default)(VALID_PROP_NAMES, prop) && - !(0, includes_1.default)(ruleNames, prop)) { - errors.push({ - msg: "Redundant visitor method: <".concat(prop, "> on ").concat((visitorInstance.constructor.name), " CST Visitor\n") + - "There is no Grammar Rule corresponding to this method's name.\n", - type: CstVisitorDefinitionError.REDUNDANT_METHOD, - methodName: prop - }); - } + didWarnAboutReassigningProps = true; } - return errors; - } - exports.validateRedundantMethods = validateRedundantMethods; - -} (cst_visitor)); + } -var hasRequiredTree_builder; + return nextUnitOfWork; + } -function requireTree_builder () { - if (hasRequiredTree_builder) return tree_builder; - hasRequiredTree_builder = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(tree_builder, "__esModule", { value: true }); - tree_builder.TreeBuilder = void 0; - var cst_1 = cst; - var noop_1$1 = __importDefault(noop_1); - var has_1$1 = __importDefault(has_1); - var keys_1$1 = __importDefault(keys_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var cst_visitor_1 = cst_visitor; - var parser_1 = requireParser(); - /** - * This trait is responsible for the CST building logic. - */ - var TreeBuilder = /** @class */ (function () { - function TreeBuilder() { - } - TreeBuilder.prototype.initTreeBuilder = function (config) { - this.CST_STACK = []; - // outputCst is no longer exposed/defined in the pubic API - this.outputCst = config.outputCst; - this.nodeLocationTracking = (0, has_1$1.default)(config, "nodeLocationTracking") - ? config.nodeLocationTracking // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.nodeLocationTracking; - if (!this.outputCst) { - this.cstInvocationStateUpdate = noop_1$1.default; - this.cstFinallyStateUpdate = noop_1$1.default; - this.cstPostTerminal = noop_1$1.default; - this.cstPostNonTerminal = noop_1$1.default; - this.cstPostRule = noop_1$1.default; - } - else { - if (/full/i.test(this.nodeLocationTracking)) { - if (this.recoveryEnabled) { - this.setNodeLocationFromToken = cst_1.setNodeLocationFull; - this.setNodeLocationFromNode = cst_1.setNodeLocationFull; - this.cstPostRule = noop_1$1.default; - this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery; - } - else { - this.setNodeLocationFromToken = noop_1$1.default; - this.setNodeLocationFromNode = noop_1$1.default; - this.cstPostRule = this.cstPostRuleFull; - this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular; - } - } - else if (/onlyOffset/i.test(this.nodeLocationTracking)) { - if (this.recoveryEnabled) { - this.setNodeLocationFromToken = cst_1.setNodeLocationOnlyOffset; - this.setNodeLocationFromNode = cst_1.setNodeLocationOnlyOffset; - this.cstPostRule = noop_1$1.default; - this.setInitialNodeLocation = - this.setInitialNodeLocationOnlyOffsetRecovery; - } - else { - this.setNodeLocationFromToken = noop_1$1.default; - this.setNodeLocationFromNode = noop_1$1.default; - this.cstPostRule = this.cstPostRuleOnlyOffset; - this.setInitialNodeLocation = - this.setInitialNodeLocationOnlyOffsetRegular; - } - } - else if (/none/i.test(this.nodeLocationTracking)) { - this.setNodeLocationFromToken = noop_1$1.default; - this.setNodeLocationFromNode = noop_1$1.default; - this.cstPostRule = noop_1$1.default; - this.setInitialNodeLocation = noop_1$1.default; - } - else { - throw Error("Invalid config option: \"".concat(config.nodeLocationTracking, "\"")); - } - } - }; - TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRecovery = function (cstNode) { - cstNode.location = { - startOffset: NaN, - endOffset: NaN - }; - }; - TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRegular = function (cstNode) { - cstNode.location = { - // without error recovery the starting Location of a new CstNode is guaranteed - // To be the next Token's startOffset (for valid inputs). - // For invalid inputs there won't be any CSTOutput so this potential - // inaccuracy does not matter - startOffset: this.LA(1).startOffset, - endOffset: NaN - }; - }; - TreeBuilder.prototype.setInitialNodeLocationFullRecovery = function (cstNode) { - cstNode.location = { - startOffset: NaN, - startLine: NaN, - startColumn: NaN, - endOffset: NaN, - endLine: NaN, - endColumn: NaN - }; - }; - /** - * @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work - - * @param cstNode - */ - TreeBuilder.prototype.setInitialNodeLocationFullRegular = function (cstNode) { - var nextToken = this.LA(1); - cstNode.location = { - startOffset: nextToken.startOffset, - startLine: nextToken.startLine, - startColumn: nextToken.startColumn, - endOffset: NaN, - endLine: NaN, - endColumn: NaN - }; - }; - TreeBuilder.prototype.cstInvocationStateUpdate = function (fullRuleName) { - var cstNode = { - name: fullRuleName, - children: Object.create(null) - }; - this.setInitialNodeLocation(cstNode); - this.CST_STACK.push(cstNode); - }; - TreeBuilder.prototype.cstFinallyStateUpdate = function () { - this.CST_STACK.pop(); - }; - TreeBuilder.prototype.cstPostRuleFull = function (ruleCstNode) { - // casts to `required` are safe because `cstPostRuleFull` should only be invoked when full location is enabled - var prevToken = this.LA(0); - var loc = ruleCstNode.location; - // If this condition is true it means we consumed at least one Token - // In this CstNode. - if (loc.startOffset <= prevToken.startOffset === true) { - loc.endOffset = prevToken.endOffset; - loc.endLine = prevToken.endLine; - loc.endColumn = prevToken.endColumn; - } - // "empty" CstNode edge case - else { - loc.startOffset = NaN; - loc.startLine = NaN; - loc.startColumn = NaN; - } - }; - TreeBuilder.prototype.cstPostRuleOnlyOffset = function (ruleCstNode) { - var prevToken = this.LA(0); - // `location' is not null because `cstPostRuleOnlyOffset` will only be invoked when location tracking is enabled. - var loc = ruleCstNode.location; - // If this condition is true it means we consumed at least one Token - // In this CstNode. - if (loc.startOffset <= prevToken.startOffset === true) { - loc.endOffset = prevToken.endOffset; - } - // "empty" CstNode edge case - else { - loc.startOffset = NaN; - } - }; - TreeBuilder.prototype.cstPostTerminal = function (key, consumedToken) { - var rootCst = this.CST_STACK[this.CST_STACK.length - 1]; - (0, cst_1.addTerminalToCst)(rootCst, consumedToken, key); - // This is only used when **both** error recovery and CST Output are enabled. - this.setNodeLocationFromToken(rootCst.location, consumedToken); - }; - TreeBuilder.prototype.cstPostNonTerminal = function (ruleCstResult, ruleName) { - var preCstNode = this.CST_STACK[this.CST_STACK.length - 1]; - (0, cst_1.addNoneTerminalToCst)(preCstNode, ruleName, ruleCstResult); - // This is only used when **both** error recovery and CST Output are enabled. - this.setNodeLocationFromNode(preCstNode.location, ruleCstResult.location); - }; - TreeBuilder.prototype.getBaseCstVisitorConstructor = function () { - if ((0, isUndefined_1.default)(this.baseCstVisitorConstructor)) { - var newBaseCstVisitorConstructor = (0, cst_visitor_1.createBaseSemanticVisitorConstructor)(this.className, (0, keys_1$1.default)(this.gastProductionsCache)); - this.baseCstVisitorConstructor = newBaseCstVisitorConstructor; - return newBaseCstVisitorConstructor; - } - return this.baseCstVisitorConstructor; - }; - TreeBuilder.prototype.getBaseCstVisitorConstructorWithDefaults = function () { - if ((0, isUndefined_1.default)(this.baseCstVisitorWithDefaultsConstructor)) { - var newConstructor = (0, cst_visitor_1.createBaseVisitorConstructorWithDefaults)(this.className, (0, keys_1$1.default)(this.gastProductionsCache), this.getBaseCstVisitorConstructor()); - this.baseCstVisitorWithDefaultsConstructor = newConstructor; - return newConstructor; - } - return this.baseCstVisitorWithDefaultsConstructor; - }; - TreeBuilder.prototype.getLastExplicitRuleShortName = function () { - var ruleStack = this.RULE_STACK; - return ruleStack[ruleStack.length - 1]; - }; - TreeBuilder.prototype.getPreviousExplicitRuleShortName = function () { - var ruleStack = this.RULE_STACK; - return ruleStack[ruleStack.length - 2]; - }; - TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndex = function () { - var occurrenceStack = this.RULE_OCCURRENCE_STACK; - return occurrenceStack[occurrenceStack.length - 1]; - }; - return TreeBuilder; - }()); - tree_builder.TreeBuilder = TreeBuilder; - - return tree_builder; -} + function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) { + // Refs should update even if shouldComponentUpdate returns false + markRef$1(current, workInProgress); + var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags; -var lexer_adapter = {}; + if (!shouldUpdate && !didCaptureError) { + // Context providers should defer to sCU for rendering + if (hasContext) { + invalidateContextProvider(workInProgress, Component, false); + } -var hasRequiredLexer_adapter; + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } -function requireLexer_adapter () { - if (hasRequiredLexer_adapter) return lexer_adapter; - hasRequiredLexer_adapter = 1; - Object.defineProperty(lexer_adapter, "__esModule", { value: true }); - lexer_adapter.LexerAdapter = void 0; - var parser_1 = requireParser(); - /** - * Trait responsible abstracting over the interaction with Lexer output (Token vector). - * - * This could be generalized to support other kinds of lexers, e.g. - * - Just in Time Lexing / Lexer-Less parsing. - * - Streaming Lexer. - */ - var LexerAdapter = /** @class */ (function () { - function LexerAdapter() { - } - LexerAdapter.prototype.initLexerAdapter = function () { - this.tokVector = []; - this.tokVectorLength = 0; - this.currIdx = -1; - }; - Object.defineProperty(LexerAdapter.prototype, "input", { - get: function () { - return this.tokVector; - }, - set: function (newInput) { - // @ts-ignore - `this parameter` not supported in setters/getters - // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters - if (this.selfAnalysisDone !== true) { - throw Error("Missing invocation at the end of the Parser's constructor."); - } - // @ts-ignore - `this parameter` not supported in setters/getters - // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters - this.reset(); - this.tokVector = newInput; - this.tokVectorLength = newInput.length; - }, - enumerable: false, - configurable: true - }); - // skips a token and returns the next token - LexerAdapter.prototype.SKIP_TOKEN = function () { - if (this.currIdx <= this.tokVector.length - 2) { - this.consumeToken(); - return this.LA(1); - } - else { - return parser_1.END_OF_FILE; - } - }; - // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers - // or lexers dependent on parser context. - LexerAdapter.prototype.LA = function (howMuch) { - var soughtIdx = this.currIdx + howMuch; - if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) { - return parser_1.END_OF_FILE; - } - else { - return this.tokVector[soughtIdx]; - } - }; - LexerAdapter.prototype.consumeToken = function () { - this.currIdx++; - }; - LexerAdapter.prototype.exportLexerState = function () { - return this.currIdx; - }; - LexerAdapter.prototype.importLexerState = function (newState) { - this.currIdx = newState; - }; - LexerAdapter.prototype.resetLexerState = function () { - this.currIdx = -1; - }; - LexerAdapter.prototype.moveToTerminatedState = function () { - this.currIdx = this.tokVector.length - 1; - }; - LexerAdapter.prototype.getLexerPosition = function () { - return this.exportLexerState(); - }; - return LexerAdapter; - }()); - lexer_adapter.LexerAdapter = LexerAdapter; - - return lexer_adapter; -} + var instance = workInProgress.stateNode; // Rerender -var recognizer_api = {}; + ReactCurrentOwner$1.current = workInProgress; + var nextChildren; -var hasRequiredRecognizer_api; + if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') { + // If we captured an error, but getDerivedStateFromError is not defined, + // unmount all the children. componentDidCatch will schedule an update to + // re-render a fallback. This is temporary until we migrate everyone to + // the new API. + // TODO: Warn in a future release. + nextChildren = null; -function requireRecognizer_api () { - if (hasRequiredRecognizer_api) return recognizer_api; - hasRequiredRecognizer_api = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(recognizer_api, "__esModule", { value: true }); - recognizer_api.RecognizerApi = void 0; - var values_1 = __importDefault(values_1$1); - var includes_1 = __importDefault(includes_1$2); - var exceptions_public_1 = exceptions_public; - var parser_1 = requireParser(); - var errors_public_1 = errors_public; - var checks_1 = requireChecks(); - var gast_1 = api$1; - /** - * This trait is responsible for implementing the public API - * for defining Chevrotain parsers, i.e: - * - CONSUME - * - RULE - * - OPTION - * - ... - */ - var RecognizerApi = /** @class */ (function () { - function RecognizerApi() { + { + stopProfilerTimerIfRunning(); + } + } else { + { + markComponentRenderStarted(workInProgress); } - RecognizerApi.prototype.ACTION = function (impl) { - return impl.call(this); - }; - RecognizerApi.prototype.consume = function (idx, tokType, options) { - return this.consumeInternal(tokType, idx, options); - }; - RecognizerApi.prototype.subrule = function (idx, ruleToCall, options) { - return this.subruleInternal(ruleToCall, idx, options); - }; - RecognizerApi.prototype.option = function (idx, actionORMethodDef) { - return this.optionInternal(actionORMethodDef, idx); - }; - RecognizerApi.prototype.or = function (idx, altsOrOpts) { - return this.orInternal(altsOrOpts, idx); - }; - RecognizerApi.prototype.many = function (idx, actionORMethodDef) { - return this.manyInternal(idx, actionORMethodDef); - }; - RecognizerApi.prototype.atLeastOne = function (idx, actionORMethodDef) { - return this.atLeastOneInternal(idx, actionORMethodDef); - }; - RecognizerApi.prototype.CONSUME = function (tokType, options) { - return this.consumeInternal(tokType, 0, options); - }; - RecognizerApi.prototype.CONSUME1 = function (tokType, options) { - return this.consumeInternal(tokType, 1, options); - }; - RecognizerApi.prototype.CONSUME2 = function (tokType, options) { - return this.consumeInternal(tokType, 2, options); - }; - RecognizerApi.prototype.CONSUME3 = function (tokType, options) { - return this.consumeInternal(tokType, 3, options); - }; - RecognizerApi.prototype.CONSUME4 = function (tokType, options) { - return this.consumeInternal(tokType, 4, options); - }; - RecognizerApi.prototype.CONSUME5 = function (tokType, options) { - return this.consumeInternal(tokType, 5, options); - }; - RecognizerApi.prototype.CONSUME6 = function (tokType, options) { - return this.consumeInternal(tokType, 6, options); - }; - RecognizerApi.prototype.CONSUME7 = function (tokType, options) { - return this.consumeInternal(tokType, 7, options); - }; - RecognizerApi.prototype.CONSUME8 = function (tokType, options) { - return this.consumeInternal(tokType, 8, options); - }; - RecognizerApi.prototype.CONSUME9 = function (tokType, options) { - return this.consumeInternal(tokType, 9, options); - }; - RecognizerApi.prototype.SUBRULE = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 0, options); - }; - RecognizerApi.prototype.SUBRULE1 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 1, options); - }; - RecognizerApi.prototype.SUBRULE2 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 2, options); - }; - RecognizerApi.prototype.SUBRULE3 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 3, options); - }; - RecognizerApi.prototype.SUBRULE4 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 4, options); - }; - RecognizerApi.prototype.SUBRULE5 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 5, options); - }; - RecognizerApi.prototype.SUBRULE6 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 6, options); - }; - RecognizerApi.prototype.SUBRULE7 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 7, options); - }; - RecognizerApi.prototype.SUBRULE8 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 8, options); - }; - RecognizerApi.prototype.SUBRULE9 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 9, options); - }; - RecognizerApi.prototype.OPTION = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 0); - }; - RecognizerApi.prototype.OPTION1 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 1); - }; - RecognizerApi.prototype.OPTION2 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 2); - }; - RecognizerApi.prototype.OPTION3 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 3); - }; - RecognizerApi.prototype.OPTION4 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 4); - }; - RecognizerApi.prototype.OPTION5 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 5); - }; - RecognizerApi.prototype.OPTION6 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 6); - }; - RecognizerApi.prototype.OPTION7 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 7); - }; - RecognizerApi.prototype.OPTION8 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 8); - }; - RecognizerApi.prototype.OPTION9 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 9); - }; - RecognizerApi.prototype.OR = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 0); - }; - RecognizerApi.prototype.OR1 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 1); - }; - RecognizerApi.prototype.OR2 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 2); - }; - RecognizerApi.prototype.OR3 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 3); - }; - RecognizerApi.prototype.OR4 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 4); - }; - RecognizerApi.prototype.OR5 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 5); - }; - RecognizerApi.prototype.OR6 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 6); - }; - RecognizerApi.prototype.OR7 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 7); - }; - RecognizerApi.prototype.OR8 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 8); - }; - RecognizerApi.prototype.OR9 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 9); - }; - RecognizerApi.prototype.MANY = function (actionORMethodDef) { - this.manyInternal(0, actionORMethodDef); - }; - RecognizerApi.prototype.MANY1 = function (actionORMethodDef) { - this.manyInternal(1, actionORMethodDef); - }; - RecognizerApi.prototype.MANY2 = function (actionORMethodDef) { - this.manyInternal(2, actionORMethodDef); - }; - RecognizerApi.prototype.MANY3 = function (actionORMethodDef) { - this.manyInternal(3, actionORMethodDef); - }; - RecognizerApi.prototype.MANY4 = function (actionORMethodDef) { - this.manyInternal(4, actionORMethodDef); - }; - RecognizerApi.prototype.MANY5 = function (actionORMethodDef) { - this.manyInternal(5, actionORMethodDef); - }; - RecognizerApi.prototype.MANY6 = function (actionORMethodDef) { - this.manyInternal(6, actionORMethodDef); - }; - RecognizerApi.prototype.MANY7 = function (actionORMethodDef) { - this.manyInternal(7, actionORMethodDef); - }; - RecognizerApi.prototype.MANY8 = function (actionORMethodDef) { - this.manyInternal(8, actionORMethodDef); - }; - RecognizerApi.prototype.MANY9 = function (actionORMethodDef) { - this.manyInternal(9, actionORMethodDef); - }; - RecognizerApi.prototype.MANY_SEP = function (options) { - this.manySepFirstInternal(0, options); - }; - RecognizerApi.prototype.MANY_SEP1 = function (options) { - this.manySepFirstInternal(1, options); - }; - RecognizerApi.prototype.MANY_SEP2 = function (options) { - this.manySepFirstInternal(2, options); - }; - RecognizerApi.prototype.MANY_SEP3 = function (options) { - this.manySepFirstInternal(3, options); - }; - RecognizerApi.prototype.MANY_SEP4 = function (options) { - this.manySepFirstInternal(4, options); - }; - RecognizerApi.prototype.MANY_SEP5 = function (options) { - this.manySepFirstInternal(5, options); - }; - RecognizerApi.prototype.MANY_SEP6 = function (options) { - this.manySepFirstInternal(6, options); - }; - RecognizerApi.prototype.MANY_SEP7 = function (options) { - this.manySepFirstInternal(7, options); - }; - RecognizerApi.prototype.MANY_SEP8 = function (options) { - this.manySepFirstInternal(8, options); - }; - RecognizerApi.prototype.MANY_SEP9 = function (options) { - this.manySepFirstInternal(9, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE = function (actionORMethodDef) { - this.atLeastOneInternal(0, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE1 = function (actionORMethodDef) { - return this.atLeastOneInternal(1, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE2 = function (actionORMethodDef) { - this.atLeastOneInternal(2, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE3 = function (actionORMethodDef) { - this.atLeastOneInternal(3, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE4 = function (actionORMethodDef) { - this.atLeastOneInternal(4, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE5 = function (actionORMethodDef) { - this.atLeastOneInternal(5, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE6 = function (actionORMethodDef) { - this.atLeastOneInternal(6, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE7 = function (actionORMethodDef) { - this.atLeastOneInternal(7, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE8 = function (actionORMethodDef) { - this.atLeastOneInternal(8, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE9 = function (actionORMethodDef) { - this.atLeastOneInternal(9, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP = function (options) { - this.atLeastOneSepFirstInternal(0, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP1 = function (options) { - this.atLeastOneSepFirstInternal(1, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP2 = function (options) { - this.atLeastOneSepFirstInternal(2, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP3 = function (options) { - this.atLeastOneSepFirstInternal(3, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP4 = function (options) { - this.atLeastOneSepFirstInternal(4, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP5 = function (options) { - this.atLeastOneSepFirstInternal(5, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP6 = function (options) { - this.atLeastOneSepFirstInternal(6, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP7 = function (options) { - this.atLeastOneSepFirstInternal(7, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP8 = function (options) { - this.atLeastOneSepFirstInternal(8, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP9 = function (options) { - this.atLeastOneSepFirstInternal(9, options); - }; - RecognizerApi.prototype.RULE = function (name, implementation, config) { - if (config === void 0) { config = parser_1.DEFAULT_RULE_CONFIG; } - if ((0, includes_1.default)(this.definedRulesNames, name)) { - var errMsg = errors_public_1.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ - topLevelRule: name, - grammarName: this.className - }); - var error = { - message: errMsg, - type: parser_1.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, - ruleName: name - }; - this.definitionErrors.push(error); - } - this.definedRulesNames.push(name); - var ruleImplementation = this.defineRule(name, implementation, config); - this[name] = ruleImplementation; - return ruleImplementation; - }; - RecognizerApi.prototype.OVERRIDE_RULE = function (name, impl, config) { - if (config === void 0) { config = parser_1.DEFAULT_RULE_CONFIG; } - var ruleErrors = (0, checks_1.validateRuleIsOverridden)(name, this.definedRulesNames, this.className); - this.definitionErrors = this.definitionErrors.concat(ruleErrors); - var ruleImplementation = this.defineRule(name, impl, config); - this[name] = ruleImplementation; - return ruleImplementation; - }; - RecognizerApi.prototype.BACKTRACK = function (grammarRule, args) { - return function () { - // save org state - this.isBackTrackingStack.push(1); - var orgState = this.saveRecogState(); - try { - grammarRule.apply(this, args); - // if no exception was thrown we have succeed parsing the rule. - return true; - } - catch (e) { - if ((0, exceptions_public_1.isRecognitionException)(e)) { - return false; - } - else { - throw e; - } - } - finally { - this.reloadRecogState(orgState); - this.isBackTrackingStack.pop(); - } - }; - }; - // GAST export APIs - RecognizerApi.prototype.getGAstProductions = function () { - return this.gastProductionsCache; - }; - RecognizerApi.prototype.getSerializedGastProductions = function () { - return (0, gast_1.serializeGrammar)((0, values_1.default)(this.gastProductionsCache)); - }; - return RecognizerApi; - }()); - recognizer_api.RecognizerApi = RecognizerApi; - - return recognizer_api; -} -var recognizer_engine = {}; + { + setIsRendering(true); + nextChildren = instance.render(); -var hasRequiredRecognizer_engine; + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); -function requireRecognizer_engine () { - if (hasRequiredRecognizer_engine) return recognizer_engine; - hasRequiredRecognizer_engine = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(recognizer_engine, "__esModule", { value: true }); - recognizer_engine.RecognizerEngine = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var isArray_1 = __importDefault(isArray_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var every_1 = __importDefault(every_1$1); - var uniq_1 = __importDefault(uniq_1$2); - var isObject_1$1 = __importDefault(isObject_1); - var has_1$1 = __importDefault(has_1); - var values_1 = __importDefault(values_1$1); - var reduce_1 = __importDefault(reduce_1$1); - var clone_1 = __importDefault(clone_1$1); - var keys_1 = keys; - var exceptions_public_1 = exceptions_public; - var lookahead_1 = lookahead; - var interpreter_1 = interpreter; - var parser_1 = requireParser(); - var recoverable_1 = requireRecoverable(); - var tokens_public_1 = tokens_public; - var tokens_1 = tokens; - /** - * This trait is responsible for the runtime parsing engine - * Used by the official API (recognizer_api.ts) - */ - var RecognizerEngine = /** @class */ (function () { - function RecognizerEngine() { - } - RecognizerEngine.prototype.initRecognizerEngine = function (tokenVocabulary, config) { - this.className = this.constructor.name; - // TODO: would using an ES6 Map or plain object be faster (CST building scenario) - this.shortRuleNameToFull = {}; - this.fullRuleNameToShort = {}; - this.ruleShortNameIdx = 256; - this.tokenMatcher = tokens_1.tokenStructuredMatcherNoCategories; - this.subruleIdx = 0; - this.definedRulesNames = []; - this.tokensMap = {}; - this.isBackTrackingStack = []; - this.RULE_STACK = []; - this.RULE_OCCURRENCE_STACK = []; - this.gastProductionsCache = {}; - if ((0, has_1$1.default)(config, "serializedGrammar")) { - throw Error("The Parser's configuration can no longer contain a property.\n" + - "\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\n" + - "\tFor Further details."); - } - if ((0, isArray_1.default)(tokenVocabulary)) { - // This only checks for Token vocabularies provided as arrays. - // That is good enough because the main objective is to detect users of pre-V4.0 APIs - // rather than all edge cases of empty Token vocabularies. - if ((0, isEmpty_1.default)(tokenVocabulary)) { - throw Error("A Token Vocabulary cannot be empty.\n" + - "\tNote that the first argument for the parser constructor\n" + - "\tis no longer a Token vector (since v4.0)."); - } - if (typeof tokenVocabulary[0].startOffset === "number") { - throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n" + - "\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0\n" + - "\tFor Further details."); - } - } - if ((0, isArray_1.default)(tokenVocabulary)) { - this.tokensMap = (0, reduce_1.default)(tokenVocabulary, function (acc, tokType) { - acc[tokType.name] = tokType; - return acc; - }, {}); - } - else if ((0, has_1$1.default)(tokenVocabulary, "modes") && - (0, every_1.default)((0, flatten_1.default)((0, values_1.default)(tokenVocabulary.modes)), tokens_1.isTokenType)) { - var allTokenTypes_1 = (0, flatten_1.default)((0, values_1.default)(tokenVocabulary.modes)); - var uniqueTokens = (0, uniq_1.default)(allTokenTypes_1); - this.tokensMap = (0, reduce_1.default)(uniqueTokens, function (acc, tokType) { - acc[tokType.name] = tokType; - return acc; - }, {}); - } - else if ((0, isObject_1$1.default)(tokenVocabulary)) { - this.tokensMap = (0, clone_1.default)(tokenVocabulary); - } - else { - throw new Error(" argument must be An Array of Token constructors," + - " A dictionary of Token constructors or an IMultiModeLexerDefinition"); - } - // always add EOF to the tokenNames -> constructors map. it is useful to assure all the input has been - // parsed with a clear error message ("expecting EOF but found ...") - this.tokensMap["EOF"] = tokens_public_1.EOF; - var allTokenTypes = (0, has_1$1.default)(tokenVocabulary, "modes") - ? (0, flatten_1.default)((0, values_1.default)(tokenVocabulary.modes)) - : (0, values_1.default)(tokenVocabulary); - var noTokenCategoriesUsed = (0, every_1.default)(allTokenTypes, function (tokenConstructor) { - return (0, isEmpty_1.default)(tokenConstructor.categoryMatches); - }); - this.tokenMatcher = noTokenCategoriesUsed - ? tokens_1.tokenStructuredMatcherNoCategories - : tokens_1.tokenStructuredMatcher; - // Because ES2015+ syntax should be supported for creating Token classes - // We cannot assume that the Token classes were created using the "extendToken" utilities - // Therefore we must augment the Token classes both on Lexer initialization and on Parser initialization - (0, tokens_1.augmentTokenTypes)((0, values_1.default)(this.tokensMap)); - }; - RecognizerEngine.prototype.defineRule = function (ruleName, impl, config) { - if (this.selfAnalysisDone) { - throw Error("Grammar rule <".concat(ruleName, "> may not be defined after the 'performSelfAnalysis' method has been called'\n") + - "Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called."); - } - var resyncEnabled = (0, has_1$1.default)(config, "resyncEnabled") - ? config.resyncEnabled // assumes end user provides the correct config value/type - : parser_1.DEFAULT_RULE_CONFIG.resyncEnabled; - var recoveryValueFunc = (0, has_1$1.default)(config, "recoveryValueFunc") - ? config.recoveryValueFunc // assumes end user provides the correct config value/type - : parser_1.DEFAULT_RULE_CONFIG.recoveryValueFunc; - // performance optimization: Use small integers as keys for the longer human readable "full" rule names. - // this greatly improves Map access time (as much as 8% for some performance benchmarks). - var shortName = this.ruleShortNameIdx << (keys_1.BITS_FOR_METHOD_TYPE + keys_1.BITS_FOR_OCCURRENCE_IDX); - this.ruleShortNameIdx++; - this.shortRuleNameToFull[shortName] = ruleName; - this.fullRuleNameToShort[ruleName] = shortName; - var invokeRuleWithTry; - // Micro optimization, only check the condition **once** on rule definition - // instead of **every single** rule invocation. - if (this.outputCst === true) { - invokeRuleWithTry = function invokeRuleWithTry() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - try { - this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx); - impl.apply(this, args); - var cst = this.CST_STACK[this.CST_STACK.length - 1]; - this.cstPostRule(cst); - return cst; - } - catch (e) { - return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc); - } - finally { - this.ruleFinallyStateUpdate(); - } - }; - } - else { - invokeRuleWithTry = function invokeRuleWithTryCst() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - try { - this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx); - return impl.apply(this, args); - } - catch (e) { - return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc); - } - finally { - this.ruleFinallyStateUpdate(); - } - }; - } - var wrappedGrammarRule = Object.assign(invokeRuleWithTry, { ruleName: ruleName, originalGrammarAction: impl }); - return wrappedGrammarRule; - }; - RecognizerEngine.prototype.invokeRuleCatch = function (e, resyncEnabledConfig, recoveryValueFunc) { - var isFirstInvokedRule = this.RULE_STACK.length === 1; - // note the reSync is always enabled for the first rule invocation, because we must always be able to - // reSync with EOF and just output some INVALID ParseTree - // during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking - // path is really the most valid one - var reSyncEnabled = resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled; - if ((0, exceptions_public_1.isRecognitionException)(e)) { - var recogError = e; - if (reSyncEnabled) { - var reSyncTokType = this.findReSyncTokenType(); - if (this.isInCurrentRuleReSyncSet(reSyncTokType)) { - recogError.resyncedTokens = this.reSyncTo(reSyncTokType); - if (this.outputCst) { - var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; - partialCstResult.recoveredNode = true; - return partialCstResult; - } - else { - return recoveryValueFunc(); - } - } - else { - if (this.outputCst) { - var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; - partialCstResult.recoveredNode = true; - recogError.partialCstResult = partialCstResult; - } - // to be handled Further up the call stack - throw recogError; - } - } - else if (isFirstInvokedRule) { - // otherwise a Redundant input error will be created as well and we cannot guarantee that this is indeed the case - this.moveToTerminatedState(); - // the parser should never throw one of its own errors outside its flow. - // even if error recovery is disabled - return recoveryValueFunc(); - } - else { - // to be recovered Further up the call stack - throw recogError; - } - } - else { - // some other Error type which we don't know how to handle (for example a built in JavaScript Error) - throw e; - } - }; - // Implementation of parsing DSL - RecognizerEngine.prototype.optionInternal = function (actionORMethodDef, occurrence) { - var key = this.getKeyForAutomaticLookahead(keys_1.OPTION_IDX, occurrence); - return this.optionInternalLogic(actionORMethodDef, occurrence, key); - }; - RecognizerEngine.prototype.optionInternalLogic = function (actionORMethodDef, occurrence, key) { - var _this = this; - var lookAheadFunc = this.getLaFuncFromCache(key); - var action; - if (typeof actionORMethodDef !== "function") { - action = actionORMethodDef.DEF; - var predicate_1 = actionORMethodDef.GATE; - // predicate present - if (predicate_1 !== undefined) { - var orgLookaheadFunction_1 = lookAheadFunc; - lookAheadFunc = function () { - return predicate_1.call(_this) && orgLookaheadFunction_1.call(_this); - }; - } - } - else { - action = actionORMethodDef; - } - if (lookAheadFunc.call(this) === true) { - return action.call(this); - } - return undefined; - }; - RecognizerEngine.prototype.atLeastOneInternal = function (prodOccurrence, actionORMethodDef) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_IDX, prodOccurrence); - return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey); - }; - RecognizerEngine.prototype.atLeastOneInternalLogic = function (prodOccurrence, actionORMethodDef, key) { - var _this = this; - var lookAheadFunc = this.getLaFuncFromCache(key); - var action; - if (typeof actionORMethodDef !== "function") { - action = actionORMethodDef.DEF; - var predicate_2 = actionORMethodDef.GATE; - // predicate present - if (predicate_2 !== undefined) { - var orgLookaheadFunction_2 = lookAheadFunc; - lookAheadFunc = function () { - return predicate_2.call(_this) && orgLookaheadFunction_2.call(_this); - }; - } - } - else { - action = actionORMethodDef; - } - if (lookAheadFunc.call(this) === true) { - var notStuck = this.doSingleRepetition(action); - while (lookAheadFunc.call(this) === true && - notStuck === true) { - notStuck = this.doSingleRepetition(action); - } - } - else { - throw this.raiseEarlyExitException(prodOccurrence, lookahead_1.PROD_TYPE.REPETITION_MANDATORY, actionORMethodDef.ERR_MSG); - } - // note that while it may seem that this can cause an error because by using a recursive call to - // AT_LEAST_ONE we change the grammar to AT_LEAST_TWO, AT_LEAST_THREE ... , the possible recursive call - // from the tryInRepetitionRecovery(...) will only happen IFF there really are TWO/THREE/.... items. - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.atLeastOneInternal, [prodOccurrence, actionORMethodDef], lookAheadFunc, keys_1.AT_LEAST_ONE_IDX, prodOccurrence, interpreter_1.NextTerminalAfterAtLeastOneWalker); - }; - RecognizerEngine.prototype.atLeastOneSepFirstInternal = function (prodOccurrence, options) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence); - this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey); - }; - RecognizerEngine.prototype.atLeastOneSepFirstInternalLogic = function (prodOccurrence, options, key) { - var _this = this; - var action = options.DEF; - var separator = options.SEP; - var firstIterationLookaheadFunc = this.getLaFuncFromCache(key); - // 1st iteration - if (firstIterationLookaheadFunc.call(this) === true) { - action.call(this); - // TODO: Optimization can move this function construction into "attemptInRepetitionRecovery" - // because it is only needed in error recovery scenarios. - var separatorLookAheadFunc = function () { - return _this.tokenMatcher(_this.LA(1), separator); - }; - // 2nd..nth iterations - while (this.tokenMatcher(this.LA(1), separator) === true) { - // note that this CONSUME will never enter recovery because - // the separatorLookAheadFunc checks that the separator really does exist. - this.CONSUME(separator); - action.call(this); - } - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ - prodOccurrence, - separator, - separatorLookAheadFunc, - action, - interpreter_1.NextTerminalAfterAtLeastOneSepWalker - ], separatorLookAheadFunc, keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence, interpreter_1.NextTerminalAfterAtLeastOneSepWalker); - } - else { - throw this.raiseEarlyExitException(prodOccurrence, lookahead_1.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG); - } - }; - RecognizerEngine.prototype.manyInternal = function (prodOccurrence, actionORMethodDef) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_IDX, prodOccurrence); - return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey); - }; - RecognizerEngine.prototype.manyInternalLogic = function (prodOccurrence, actionORMethodDef, key) { - var _this = this; - var lookaheadFunction = this.getLaFuncFromCache(key); - var action; - if (typeof actionORMethodDef !== "function") { - action = actionORMethodDef.DEF; - var predicate_3 = actionORMethodDef.GATE; - // predicate present - if (predicate_3 !== undefined) { - var orgLookaheadFunction_3 = lookaheadFunction; - lookaheadFunction = function () { - return predicate_3.call(_this) && orgLookaheadFunction_3.call(_this); - }; - } - } - else { - action = actionORMethodDef; - } - var notStuck = true; - while (lookaheadFunction.call(this) === true && notStuck === true) { - notStuck = this.doSingleRepetition(action); - } - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.manyInternal, [prodOccurrence, actionORMethodDef], lookaheadFunction, keys_1.MANY_IDX, prodOccurrence, interpreter_1.NextTerminalAfterManyWalker, - // The notStuck parameter is only relevant when "attemptInRepetitionRecovery" - // is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP] - // An infinite loop cannot occur as: - // - Either the lookahead is guaranteed to consume something (Single Token Separator) - // - AT_LEAST_ONE by definition is guaranteed to consume something (or error out). - notStuck); - }; - RecognizerEngine.prototype.manySepFirstInternal = function (prodOccurrence, options) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_SEP_IDX, prodOccurrence); - this.manySepFirstInternalLogic(prodOccurrence, options, laKey); - }; - RecognizerEngine.prototype.manySepFirstInternalLogic = function (prodOccurrence, options, key) { - var _this = this; - var action = options.DEF; - var separator = options.SEP; - var firstIterationLaFunc = this.getLaFuncFromCache(key); - // 1st iteration - if (firstIterationLaFunc.call(this) === true) { - action.call(this); - var separatorLookAheadFunc = function () { - return _this.tokenMatcher(_this.LA(1), separator); - }; - // 2nd..nth iterations - while (this.tokenMatcher(this.LA(1), separator) === true) { - // note that this CONSUME will never enter recovery because - // the separatorLookAheadFunc checks that the separator really does exist. - this.CONSUME(separator); - // No need for checking infinite loop here due to consuming the separator. - action.call(this); - } - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ - prodOccurrence, - separator, - separatorLookAheadFunc, - action, - interpreter_1.NextTerminalAfterManySepWalker - ], separatorLookAheadFunc, keys_1.MANY_SEP_IDX, prodOccurrence, interpreter_1.NextTerminalAfterManySepWalker); - } - }; - RecognizerEngine.prototype.repetitionSepSecondInternal = function (prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker) { - while (separatorLookAheadFunc()) { - // note that this CONSUME will never enter recovery because - // the separatorLookAheadFunc checks that the separator really does exist. - this.CONSUME(separator); - action.call(this); - } - // we can only arrive to this function after an error - // has occurred (hence the name 'second') so the following - // IF will always be entered, its possible to remove it... - // however it is kept to avoid confusion and be consistent. - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - /* istanbul ignore else */ - this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ - prodOccurrence, - separator, - separatorLookAheadFunc, - action, - nextTerminalAfterWalker - ], separatorLookAheadFunc, keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker); - }; - RecognizerEngine.prototype.doSingleRepetition = function (action) { - var beforeIteration = this.getLexerPosition(); - action.call(this); - var afterIteration = this.getLexerPosition(); - // This boolean will indicate if this repetition progressed - // or if we are "stuck" (potential infinite loop in the repetition). - return afterIteration > beforeIteration; - }; - RecognizerEngine.prototype.orInternal = function (altsOrOpts, occurrence) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.OR_IDX, occurrence); - var alts = (0, isArray_1.default)(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF; - var laFunc = this.getLaFuncFromCache(laKey); - var altIdxToTake = laFunc.call(this, alts); - if (altIdxToTake !== undefined) { - var chosenAlternative = alts[altIdxToTake]; - return chosenAlternative.ALT.call(this); - } - this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG); - }; - RecognizerEngine.prototype.ruleFinallyStateUpdate = function () { - this.RULE_STACK.pop(); - this.RULE_OCCURRENCE_STACK.pop(); - // NOOP when cst is disabled - this.cstFinallyStateUpdate(); - if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) { - var firstRedundantTok = this.LA(1); - var errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({ - firstRedundant: firstRedundantTok, - ruleName: this.getCurrRuleFullName() - }); - this.SAVE_ERROR(new exceptions_public_1.NotAllInputParsedException(errMsg, firstRedundantTok)); - } - }; - RecognizerEngine.prototype.subruleInternal = function (ruleToCall, idx, options) { - var ruleResult; - try { - var args = options !== undefined ? options.ARGS : undefined; - this.subruleIdx = idx; - ruleResult = ruleToCall.apply(this, args); - this.cstPostNonTerminal(ruleResult, options !== undefined && options.LABEL !== undefined - ? options.LABEL - : ruleToCall.ruleName); - return ruleResult; - } - catch (e) { - throw this.subruleInternalError(e, options, ruleToCall.ruleName); - } - }; - RecognizerEngine.prototype.subruleInternalError = function (e, options, ruleName) { - if ((0, exceptions_public_1.isRecognitionException)(e) && e.partialCstResult !== undefined) { - this.cstPostNonTerminal(e.partialCstResult, options !== undefined && options.LABEL !== undefined - ? options.LABEL - : ruleName); - delete e.partialCstResult; - } - throw e; - }; - RecognizerEngine.prototype.consumeInternal = function (tokType, idx, options) { - var consumedToken; try { - var nextToken = this.LA(1); - if (this.tokenMatcher(nextToken, tokType) === true) { - this.consumeToken(); - consumedToken = nextToken; - } - else { - this.consumeInternalError(tokType, nextToken, options); - } - } - catch (eFromConsumption) { - consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption); - } - this.cstPostTerminal(options !== undefined && options.LABEL !== undefined - ? options.LABEL - : tokType.name, consumedToken); - return consumedToken; - }; - RecognizerEngine.prototype.consumeInternalError = function (tokType, nextToken, options) { - var msg; - var previousToken = this.LA(0); - if (options !== undefined && options.ERR_MSG) { - msg = options.ERR_MSG; - } - else { - msg = this.errorMessageProvider.buildMismatchTokenMessage({ - expected: tokType, - actual: nextToken, - previous: previousToken, - ruleName: this.getCurrRuleFullName() - }); - } - throw this.SAVE_ERROR(new exceptions_public_1.MismatchedTokenException(msg, nextToken, previousToken)); - }; - RecognizerEngine.prototype.consumeInternalRecovery = function (tokType, idx, eFromConsumption) { - // no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it - // but the original syntax could have been parsed successfully without any backtracking + recovery - if (this.recoveryEnabled && - // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions? - eFromConsumption.name === "MismatchedTokenException" && - !this.isBackTracking()) { - var follows = this.getFollowsForInRuleRecovery(tokType, idx); - try { - return this.tryInRuleRecovery(tokType, follows); - } - catch (eFromInRuleRecovery) { - if (eFromInRuleRecovery.name === recoverable_1.IN_RULE_RECOVERY_EXCEPTION) { - // failed in RuleRecovery. - // throw the original error in order to trigger reSync error recovery - throw eFromConsumption; - } - else { - throw eFromInRuleRecovery; - } - } - } - else { - throw eFromConsumption; + instance.render(); + } finally { + setIsStrictModeForDevtools(false); } - }; - RecognizerEngine.prototype.saveRecogState = function () { - // errors is a getter which will clone the errors array - var savedErrors = this.errors; - var savedRuleStack = (0, clone_1.default)(this.RULE_STACK); - return { - errors: savedErrors, - lexerState: this.exportLexerState(), - RULE_STACK: savedRuleStack, - CST_STACK: this.CST_STACK - }; - }; - RecognizerEngine.prototype.reloadRecogState = function (newState) { - this.errors = newState.errors; - this.importLexerState(newState.lexerState); - this.RULE_STACK = newState.RULE_STACK; - }; - RecognizerEngine.prototype.ruleInvocationStateUpdate = function (shortName, fullName, idxInCallingRule) { - this.RULE_OCCURRENCE_STACK.push(idxInCallingRule); - this.RULE_STACK.push(shortName); - // NOOP when cst is disabled - this.cstInvocationStateUpdate(fullName); - }; - RecognizerEngine.prototype.isBackTracking = function () { - return this.isBackTrackingStack.length !== 0; - }; - RecognizerEngine.prototype.getCurrRuleFullName = function () { - var shortName = this.getLastExplicitRuleShortName(); - return this.shortRuleNameToFull[shortName]; - }; - RecognizerEngine.prototype.shortRuleNameToFullName = function (shortName) { - return this.shortRuleNameToFull[shortName]; - }; - RecognizerEngine.prototype.isAtEndOfInput = function () { - return this.tokenMatcher(this.LA(1), tokens_public_1.EOF); - }; - RecognizerEngine.prototype.reset = function () { - this.resetLexerState(); - this.subruleIdx = 0; - this.isBackTrackingStack = []; - this.errors = []; - this.RULE_STACK = []; - // TODO: extract a specific reset for TreeBuilder trait - this.CST_STACK = []; - this.RULE_OCCURRENCE_STACK = []; - }; - return RecognizerEngine; - }()); - recognizer_engine.RecognizerEngine = RecognizerEngine; - - return recognizer_engine; -} + } + + setIsRendering(false); + } -var error_handler = {}; + { + markComponentRenderStopped(); + } + } // React DevTools reads this flag. -var hasRequiredError_handler; -function requireError_handler () { - if (hasRequiredError_handler) return error_handler; - hasRequiredError_handler = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(error_handler, "__esModule", { value: true }); - error_handler.ErrorHandler = void 0; - var exceptions_public_1 = exceptions_public; - var has_1$1 = __importDefault(has_1); - var clone_1 = __importDefault(clone_1$1); - var lookahead_1 = lookahead; - var parser_1 = requireParser(); - /** - * Trait responsible for runtime parsing errors. - */ - var ErrorHandler = /** @class */ (function () { - function ErrorHandler() { - } - ErrorHandler.prototype.initErrorHandler = function (config) { - this._errors = []; - this.errorMessageProvider = (0, has_1$1.default)(config, "errorMessageProvider") - ? config.errorMessageProvider // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.errorMessageProvider; - }; - ErrorHandler.prototype.SAVE_ERROR = function (error) { - if ((0, exceptions_public_1.isRecognitionException)(error)) { - error.context = { - ruleStack: this.getHumanReadableRuleStack(), - ruleOccurrenceStack: (0, clone_1.default)(this.RULE_OCCURRENCE_STACK) - }; - this._errors.push(error); - return error; - } - else { - throw Error("Trying to save an Error which is not a RecognitionException"); - } - }; - Object.defineProperty(ErrorHandler.prototype, "errors", { - get: function () { - return (0, clone_1.default)(this._errors); - }, - set: function (newErrors) { - this._errors = newErrors; - }, - enumerable: false, - configurable: true - }); - // TODO: consider caching the error message computed information - ErrorHandler.prototype.raiseEarlyExitException = function (occurrence, prodType, userDefinedErrMsg) { - var ruleName = this.getCurrRuleFullName(); - var ruleGrammar = this.getGAstProductions()[ruleName]; - var lookAheadPathsPerAlternative = (0, lookahead_1.getLookaheadPathsForOptionalProd)(occurrence, ruleGrammar, prodType, this.maxLookahead); - var insideProdPaths = lookAheadPathsPerAlternative[0]; - var actualTokens = []; - for (var i = 1; i <= this.maxLookahead; i++) { - actualTokens.push(this.LA(i)); - } - var msg = this.errorMessageProvider.buildEarlyExitMessage({ - expectedIterationPaths: insideProdPaths, - actual: actualTokens, - previous: this.LA(0), - customUserDescription: userDefinedErrMsg, - ruleName: ruleName - }); - throw this.SAVE_ERROR(new exceptions_public_1.EarlyExitException(msg, this.LA(1), this.LA(0))); - }; - // TODO: consider caching the error message computed information - ErrorHandler.prototype.raiseNoAltException = function (occurrence, errMsgTypes) { - var ruleName = this.getCurrRuleFullName(); - var ruleGrammar = this.getGAstProductions()[ruleName]; - // TODO: getLookaheadPathsForOr can be slow for large enough maxLookahead and certain grammars, consider caching ? - var lookAheadPathsPerAlternative = (0, lookahead_1.getLookaheadPathsForOr)(occurrence, ruleGrammar, this.maxLookahead); - var actualTokens = []; - for (var i = 1; i <= this.maxLookahead; i++) { - actualTokens.push(this.LA(i)); - } - var previousToken = this.LA(0); - var errMsg = this.errorMessageProvider.buildNoViableAltMessage({ - expectedPathsPerAlt: lookAheadPathsPerAlternative, - actual: actualTokens, - previous: previousToken, - customUserDescription: errMsgTypes, - ruleName: this.getCurrRuleFullName() - }); - throw this.SAVE_ERROR(new exceptions_public_1.NoViableAltException(errMsg, this.LA(1), previousToken)); + workInProgress.flags |= PerformedWork; + + if (current !== null && didCaptureError) { + // If we're recovering from an error, reconcile without reusing any of + // the existing children. Conceptually, the normal children and the children + // that are shown on error are two different sets, so we shouldn't reuse + // normal children even if their identities match. + forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes); + } else { + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + } // Memoize state using the values we just used to render. + // TODO: Restructure so we never read values from the instance. + + + workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. + + if (hasContext) { + invalidateContextProvider(workInProgress, Component, true); + } + + return workInProgress.child; + } + + function pushHostRootContext(workInProgress) { + var root = workInProgress.stateNode; + + if (root.pendingContext) { + pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context); + } else if (root.context) { + // Should always be set + pushTopLevelContextObject(workInProgress, root.context, false); + } + + pushHostContainer(workInProgress, root.containerInfo); + } + + function updateHostRoot(current, workInProgress, renderLanes) { + pushHostRootContext(workInProgress); + + if (current === null) { + throw new Error('Should have a current fiber. This is a bug in React.'); + } + + var nextProps = workInProgress.pendingProps; + var prevState = workInProgress.memoizedState; + var prevChildren = prevState.element; + cloneUpdateQueue(current, workInProgress); + processUpdateQueue(workInProgress, nextProps, null, renderLanes); + var nextState = workInProgress.memoizedState; + workInProgress.stateNode; + // being called "element". + + + var nextChildren = nextState.element; + + if (supportsHydration && prevState.isDehydrated) { + // This is a hydration root whose shell has not yet hydrated. We should + // attempt to hydrate. + // Flip isDehydrated to false to indicate that when this render + // finishes, the root will no longer be dehydrated. + var overrideState = { + element: nextChildren, + isDehydrated: false, + cache: nextState.cache, + transitions: nextState.transitions }; - return ErrorHandler; - }()); - error_handler.ErrorHandler = ErrorHandler; - - return error_handler; -} + var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't + // have reducer functions so it doesn't need rebasing. -var context_assist = {}; + updateQueue.baseState = overrideState; + workInProgress.memoizedState = overrideState; -var __importDefault$2 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(context_assist, "__esModule", { value: true }); -context_assist.ContentAssist = void 0; -var interpreter_1 = interpreter; -var first_1 = __importDefault$2(first.exports); -var isUndefined_1 = __importDefault$2(isUndefined_1$1); -var ContentAssist = /** @class */ (function () { - function ContentAssist() { - } - ContentAssist.prototype.initContentAssist = function () { }; - ContentAssist.prototype.computeContentAssist = function (startRuleName, precedingInput) { - var startRuleGast = this.gastProductionsCache[startRuleName]; - if ((0, isUndefined_1.default)(startRuleGast)) { - throw Error("Rule ->".concat(startRuleName, "<- does not exist in this grammar.")); - } - return (0, interpreter_1.nextPossibleTokensAfter)([startRuleGast], precedingInput, this.tokenMatcher, this.maxLookahead); - }; - // TODO: should this be a member method or a utility? it does not have any state or usage of 'this'... - // TODO: should this be more explicitly part of the public API? - ContentAssist.prototype.getNextPossibleTokenTypes = function (grammarPath) { - var topRuleName = (0, first_1.default)(grammarPath.ruleStack); - var gastProductions = this.getGAstProductions(); - var topProduction = gastProductions[topRuleName]; - var nextPossibleTokenTypes = new interpreter_1.NextAfterTokenWalker(topProduction, grammarPath).startWalking(); - return nextPossibleTokenTypes; - }; - return ContentAssist; -}()); -context_assist.ContentAssist = ContentAssist; + if (workInProgress.flags & ForceClientRender) { + // Something errored during a previous attempt to hydrate the shell, so we + // forced a client render. + var recoverableError = new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'); + return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError); + } else if (nextChildren !== prevChildren) { + var _recoverableError = new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'); -var gast_recorder = {}; + return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError); + } else { + // The outermost shell has not hydrated yet. Start hydrating. + enterHydrationState(workInProgress); -var hasRequiredGast_recorder; + var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); + workInProgress.child = child; + var node = child; -function requireGast_recorder () { - if (hasRequiredGast_recorder) return gast_recorder; - hasRequiredGast_recorder = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(gast_recorder, "__esModule", { value: true }); - gast_recorder.GastRecorder = void 0; - var last_1 = __importDefault(last_1$1); - var isArray_1 = __importDefault(isArray_1$1); - var some_1 = __importDefault(some_1$2); - var forEach_1 = __importDefault(forEach_1$4); - var isFunction_1$1 = __importDefault(isFunction_1); - var has_1$1 = __importDefault(has_1); - var gast_1 = api$1; - var lexer_public_1 = requireLexer_public(); - var tokens_1 = tokens; - var tokens_public_1 = tokens_public; - var parser_1 = requireParser(); - var keys_1 = keys; - var RECORDING_NULL_OBJECT = { - description: "This Object indicates the Parser is during Recording Phase" - }; - Object.freeze(RECORDING_NULL_OBJECT); - var HANDLE_SEPARATOR = true; - var MAX_METHOD_IDX = Math.pow(2, keys_1.BITS_FOR_OCCURRENCE_IDX) - 1; - var RFT = (0, tokens_public_1.createToken)({ name: "RECORDING_PHASE_TOKEN", pattern: lexer_public_1.Lexer.NA }); - (0, tokens_1.augmentTokenTypes)([RFT]); - var RECORDING_PHASE_TOKEN = (0, tokens_public_1.createTokenInstance)(RFT, "This IToken indicates the Parser is in Recording Phase\n\t" + - "" + - "See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details", - // Using "-1" instead of NaN (as in EOF) because an actual number is less likely to - // cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase. - -1, -1, -1, -1, -1, -1); - Object.freeze(RECORDING_PHASE_TOKEN); - var RECORDING_PHASE_CSTNODE = { - name: "This CSTNode indicates the Parser is in Recording Phase\n\t" + - "See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details", - children: {} - }; - /** - * This trait handles the creation of the GAST structure for Chevrotain Grammars - */ - var GastRecorder = /** @class */ (function () { - function GastRecorder() { + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.flags = node.flags & ~Placement | Hydrating; + node = node.sibling; + } } - GastRecorder.prototype.initGastRecorder = function (config) { - this.recordingProdStack = []; - this.RECORDING_PHASE = false; - }; - GastRecorder.prototype.enableRecording = function () { - var _this = this; - this.RECORDING_PHASE = true; - this.TRACE_INIT("Enable Recording", function () { - var _loop_1 = function (i) { - var idx = i > 0 ? i : ""; - _this["CONSUME".concat(idx)] = function (arg1, arg2) { - return this.consumeInternalRecord(arg1, i, arg2); - }; - _this["SUBRULE".concat(idx)] = function (arg1, arg2) { - return this.subruleInternalRecord(arg1, i, arg2); - }; - _this["OPTION".concat(idx)] = function (arg1) { - return this.optionInternalRecord(arg1, i); - }; - _this["OR".concat(idx)] = function (arg1) { - return this.orInternalRecord(arg1, i); - }; - _this["MANY".concat(idx)] = function (arg1) { - this.manyInternalRecord(i, arg1); - }; - _this["MANY_SEP".concat(idx)] = function (arg1) { - this.manySepFirstInternalRecord(i, arg1); - }; - _this["AT_LEAST_ONE".concat(idx)] = function (arg1) { - this.atLeastOneInternalRecord(i, arg1); - }; - _this["AT_LEAST_ONE_SEP".concat(idx)] = function (arg1) { - this.atLeastOneSepFirstInternalRecord(i, arg1); - }; - }; - /** - * Warning Dark Voodoo Magic upcoming! - * We are "replacing" the public parsing DSL methods API - * With **new** alternative implementations on the Parser **instance** - * - * So far this is the only way I've found to avoid performance regressions during parsing time. - * - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the "internal" - * implementations directly instead. - */ - for (var i = 0; i < 10; i++) { - _loop_1(i); - } - // DSL methods with the idx(suffix) as an argument - _this["consume"] = function (idx, arg1, arg2) { - return this.consumeInternalRecord(arg1, idx, arg2); - }; - _this["subrule"] = function (idx, arg1, arg2) { - return this.subruleInternalRecord(arg1, idx, arg2); - }; - _this["option"] = function (idx, arg1) { - return this.optionInternalRecord(arg1, idx); - }; - _this["or"] = function (idx, arg1) { - return this.orInternalRecord(arg1, idx); - }; - _this["many"] = function (idx, arg1) { - this.manyInternalRecord(idx, arg1); - }; - _this["atLeastOne"] = function (idx, arg1) { - this.atLeastOneInternalRecord(idx, arg1); - }; - _this.ACTION = _this.ACTION_RECORD; - _this.BACKTRACK = _this.BACKTRACK_RECORD; - _this.LA = _this.LA_RECORD; - }); - }; - GastRecorder.prototype.disableRecording = function () { - var _this = this; - this.RECORDING_PHASE = false; - // By deleting these **instance** properties, any future invocation - // will be deferred to the original methods on the **prototype** object - // This seems to get rid of any incorrect optimizations that V8 may - // do during the recording phase. - this.TRACE_INIT("Deleting Recording methods", function () { - var that = _this; - for (var i = 0; i < 10; i++) { - var idx = i > 0 ? i : ""; - delete that["CONSUME".concat(idx)]; - delete that["SUBRULE".concat(idx)]; - delete that["OPTION".concat(idx)]; - delete that["OR".concat(idx)]; - delete that["MANY".concat(idx)]; - delete that["MANY_SEP".concat(idx)]; - delete that["AT_LEAST_ONE".concat(idx)]; - delete that["AT_LEAST_ONE_SEP".concat(idx)]; - } - delete that["consume"]; - delete that["subrule"]; - delete that["option"]; - delete that["or"]; - delete that["many"]; - delete that["atLeastOne"]; - delete that.ACTION; - delete that.BACKTRACK; - delete that.LA; - }); - }; - // Parser methods are called inside an ACTION? - // Maybe try/catch/finally on ACTIONS while disabling the recorders state changes? - // @ts-expect-error -- noop place holder - GastRecorder.prototype.ACTION_RECORD = function (impl) { - // NO-OP during recording - }; - // Executing backtracking logic will break our recording logic assumptions - GastRecorder.prototype.BACKTRACK_RECORD = function (grammarRule, args) { - return function () { return true; }; - }; - // LA is part of the official API and may be used for custom lookahead logic - // by end users who may forget to wrap it in ACTION or inside a GATE - GastRecorder.prototype.LA_RECORD = function (howMuch) { - // We cannot use the RECORD_PHASE_TOKEN here because someone may depend - // On LA return EOF at the end of the input so an infinite loop may occur. - return parser_1.END_OF_FILE; - }; - GastRecorder.prototype.topLevelRuleRecord = function (name, def) { - try { - var newTopLevelRule = new gast_1.Rule({ definition: [], name: name }); - newTopLevelRule.name = name; - this.recordingProdStack.push(newTopLevelRule); - def.call(this); - this.recordingProdStack.pop(); - return newTopLevelRule; - } - catch (originalError) { - if (originalError.KNOWN_RECORDER_ERROR !== true) { - try { - originalError.message = - originalError.message + - '\n\t This error was thrown during the "grammar recording phase" For more info see:\n\t' + - "https://chevrotain.io/docs/guide/internals.html#grammar-recording"; - } - catch (mutabilityError) { - // We may not be able to modify the original error object - throw originalError; - } - } - throw originalError; - } - }; - // Implementation of parsing DSL - GastRecorder.prototype.optionInternalRecord = function (actionORMethodDef, occurrence) { - return recordProd.call(this, gast_1.Option, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.atLeastOneInternalRecord = function (occurrence, actionORMethodDef) { - recordProd.call(this, gast_1.RepetitionMandatory, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.atLeastOneSepFirstInternalRecord = function (occurrence, options) { - recordProd.call(this, gast_1.RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR); - }; - GastRecorder.prototype.manyInternalRecord = function (occurrence, actionORMethodDef) { - recordProd.call(this, gast_1.Repetition, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.manySepFirstInternalRecord = function (occurrence, options) { - recordProd.call(this, gast_1.RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR); - }; - GastRecorder.prototype.orInternalRecord = function (altsOrOpts, occurrence) { - return recordOrProd.call(this, altsOrOpts, occurrence); - }; - GastRecorder.prototype.subruleInternalRecord = function (ruleToCall, occurrence, options) { - assertMethodIdxIsValid(occurrence); - if (!ruleToCall || (0, has_1$1.default)(ruleToCall, "ruleName") === false) { - var error = new Error(" argument is invalid") + - " expecting a Parser method reference but got: <".concat(JSON.stringify(ruleToCall), ">") + - "\n inside top level rule: <".concat(this.recordingProdStack[0].name, ">")); - error.KNOWN_RECORDER_ERROR = true; - throw error; - } - var prevProd = (0, last_1.default)(this.recordingProdStack); - var ruleName = ruleToCall.ruleName; - var newNoneTerminal = new gast_1.NonTerminal({ - idx: occurrence, - nonTerminalName: ruleName, - label: options === null || options === void 0 ? void 0 : options.LABEL, - // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created - referencedRule: undefined - }); - prevProd.definition.push(newNoneTerminal); - return this.outputCst ? RECORDING_PHASE_CSTNODE : RECORDING_NULL_OBJECT; - }; - GastRecorder.prototype.consumeInternalRecord = function (tokType, occurrence, options) { - assertMethodIdxIsValid(occurrence); - if (!(0, tokens_1.hasShortKeyProperty)(tokType)) { - var error = new Error(" argument is invalid") + - " expecting a TokenType reference but got: <".concat(JSON.stringify(tokType), ">") + - "\n inside top level rule: <".concat(this.recordingProdStack[0].name, ">")); - error.KNOWN_RECORDER_ERROR = true; - throw error; - } - var prevProd = (0, last_1.default)(this.recordingProdStack); - var newNoneTerminal = new gast_1.Terminal({ - idx: occurrence, - terminalType: tokType, - label: options === null || options === void 0 ? void 0 : options.LABEL - }); - prevProd.definition.push(newNoneTerminal); - return RECORDING_PHASE_TOKEN; - }; - return GastRecorder; - }()); - gast_recorder.GastRecorder = GastRecorder; - function recordProd(prodConstructor, mainProdArg, occurrence, handleSep) { - if (handleSep === void 0) { handleSep = false; } - assertMethodIdxIsValid(occurrence); - var prevProd = (0, last_1.default)(this.recordingProdStack); - var grammarAction = (0, isFunction_1$1.default)(mainProdArg) ? mainProdArg : mainProdArg.DEF; - var newProd = new prodConstructor({ definition: [], idx: occurrence }); - if (handleSep) { - newProd.separator = mainProdArg.SEP; - } - if ((0, has_1$1.default)(mainProdArg, "MAX_LOOKAHEAD")) { - newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; - } - this.recordingProdStack.push(newProd); - grammarAction.call(this); - prevProd.definition.push(newProd); - this.recordingProdStack.pop(); - return RECORDING_NULL_OBJECT; - } - function recordOrProd(mainProdArg, occurrence) { - var _this = this; - assertMethodIdxIsValid(occurrence); - var prevProd = (0, last_1.default)(this.recordingProdStack); - // Only an array of alternatives - var hasOptions = (0, isArray_1.default)(mainProdArg) === false; - var alts = hasOptions === false ? mainProdArg : mainProdArg.DEF; - var newOrProd = new gast_1.Alternation({ - definition: [], - idx: occurrence, - ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true - }); - if ((0, has_1$1.default)(mainProdArg, "MAX_LOOKAHEAD")) { - newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; - } - var hasPredicates = (0, some_1.default)(alts, function (currAlt) { return (0, isFunction_1$1.default)(currAlt.GATE); }); - newOrProd.hasPredicates = hasPredicates; - prevProd.definition.push(newOrProd); - (0, forEach_1.default)(alts, function (currAlt) { - var currAltFlat = new gast_1.Alternative({ definition: [] }); - newOrProd.definition.push(currAltFlat); - if ((0, has_1$1.default)(currAlt, "IGNORE_AMBIGUITIES")) { - currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES; // assumes end user provides the correct config value/type - } - // **implicit** ignoreAmbiguities due to usage of gate - else if ((0, has_1$1.default)(currAlt, "GATE")) { - currAltFlat.ignoreAmbiguities = true; - } - _this.recordingProdStack.push(currAltFlat); - currAlt.ALT.call(_this); - _this.recordingProdStack.pop(); - }); - return RECORDING_NULL_OBJECT; + } else { + // Root is not dehydrated. Either this is a client-only root, or it + // already hydrated. + resetHydrationState(); + + if (nextChildren === prevChildren) { + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } + + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + } + + return workInProgress.child; } - function getIdxSuffix(idx) { - return idx === 0 ? "" : "".concat(idx); + + function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) { + // Revert to client rendering. + resetHydrationState(); + queueHydrationError(recoverableError); + workInProgress.flags |= ForceClientRender; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; } - function assertMethodIdxIsValid(idx) { - if (idx < 0 || idx > MAX_METHOD_IDX) { - var error = new Error( - // The stack trace will contain all the needed details - "Invalid DSL Method idx value: <".concat(idx, ">\n\t") + - "Idx value must be a none negative value smaller than ".concat(MAX_METHOD_IDX + 1)); - error.KNOWN_RECORDER_ERROR = true; - throw error; - } + + function updateHostComponent$1(current, workInProgress, renderLanes) { + pushHostContext(workInProgress); + + if (current === null) { + tryToClaimNextHydratableInstance(workInProgress); + } + + var type = workInProgress.type; + var nextProps = workInProgress.pendingProps; + var prevProps = current !== null ? current.memoizedProps : null; + var nextChildren = nextProps.children; + var isDirectTextChild = shouldSetTextContent(type, nextProps); + + if (isDirectTextChild) { + // We special case a direct text child of a host node. This is a common + // case. We won't handle it as a reified child. We will instead handle + // this in the host environment that also has access to this prop. That + // avoids allocating another HostText fiber and traversing it. + nextChildren = null; + } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { + // If we're switching from a direct text child to a normal child, or to + // empty, we need to schedule the text content to be reset. + workInProgress.flags |= ContentReset; + } + + markRef$1(current, workInProgress); + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; } - - return gast_recorder; -} -var perf_tracer = {}; + function updateHostText$1(current, workInProgress) { + if (current === null) { + tryToClaimNextHydratableInstance(workInProgress); + } // Nothing to do here. This is terminal. We'll do the completion step + // immediately after. -var hasRequiredPerf_tracer; -function requirePerf_tracer () { - if (hasRequiredPerf_tracer) return perf_tracer; - hasRequiredPerf_tracer = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(perf_tracer, "__esModule", { value: true }); - perf_tracer.PerformanceTracer = void 0; - var has_1$1 = __importDefault(has_1); - var utils_1 = api$2; - var parser_1 = requireParser(); - /** - * Trait responsible for runtime parsing errors. - */ - var PerformanceTracer = /** @class */ (function () { - function PerformanceTracer() { - } - PerformanceTracer.prototype.initPerformanceTracer = function (config) { - if ((0, has_1$1.default)(config, "traceInitPerf")) { - var userTraceInitPerf = config.traceInitPerf; - var traceIsNumber = typeof userTraceInitPerf === "number"; - this.traceInitMaxIdent = traceIsNumber - ? userTraceInitPerf - : Infinity; - this.traceInitPerf = traceIsNumber - ? userTraceInitPerf > 0 - : userTraceInitPerf; // assumes end user provides the correct config value/type + return null; + } + + function mountLazyComponent(_current, workInProgress, elementType, renderLanes) { + if (_current !== null) { + // A lazy component only mounts if it suspended inside a non- + // concurrent tree, in an inconsistent state. We want to treat it like + // a new mount, even though an empty version of it already committed. + // Disconnect the alternate pointers. + _current.alternate = null; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + + workInProgress.flags |= Placement; + } + + var props = workInProgress.pendingProps; + var lazyComponent = elementType; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + var Component = init(payload); // Store the unwrapped component in the type. + + workInProgress.type = Component; + var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component); + var resolvedProps = resolveDefaultProps(Component, props); + var child; + + switch (resolvedTag) { + case FunctionComponent: + { + { + validateFunctionComponentInDev(workInProgress, Component); + workInProgress.type = Component = resolveFunctionForHotReloading(Component); } - else { - this.traceInitMaxIdent = 0; - this.traceInitPerf = parser_1.DEFAULT_PARSER_CONFIG.traceInitPerf; + + child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes); + return child; + } + + case ClassComponent: + { + { + workInProgress.type = Component = resolveClassForHotReloading(Component); } - this.traceInitIndent = -1; - }; - PerformanceTracer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) { - // No need to optimize this using NOOP pattern because - // It is not called in a hot spot... - if (this.traceInitPerf === true) { - this.traceInitIndent++; - var indent = new Array(this.traceInitIndent + 1).join("\t"); - if (this.traceInitIndent < this.traceInitMaxIdent) { - console.log("".concat(indent, "--> <").concat(phaseDesc, ">")); - } - var _a = (0, utils_1.timer)(phaseImpl), time = _a.time, value = _a.value; - /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */ - var traceMethod = time > 10 ? console.warn : console.log; - if (this.traceInitIndent < this.traceInitMaxIdent) { - traceMethod("".concat(indent, "<-- <").concat(phaseDesc, "> time: ").concat(time, "ms")); - } - this.traceInitIndent--; - return value; + + child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes); + return child; + } + + case ForwardRef: + { + { + workInProgress.type = Component = resolveForwardRefForHotReloading(Component); } - else { - return phaseImpl(); + + child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes); + return child; + } + + case MemoComponent: + { + { + if (workInProgress.type !== workInProgress.elementType) { + var outerPropTypes = Component.propTypes; + + if (outerPropTypes) { + checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only + 'prop', getComponentNameFromType(Component)); + } + } } - }; - return PerformanceTracer; - }()); - perf_tracer.PerformanceTracer = PerformanceTracer; - - return perf_tracer; -} - -var apply_mixins = {}; - -Object.defineProperty(apply_mixins, "__esModule", { value: true }); -apply_mixins.applyMixins = void 0; -function applyMixins(derivedCtor, baseCtors) { - baseCtors.forEach(function (baseCtor) { - var baseProto = baseCtor.prototype; - Object.getOwnPropertyNames(baseProto).forEach(function (propName) { - if (propName === "constructor") { - return; - } - var basePropDescriptor = Object.getOwnPropertyDescriptor(baseProto, propName); - // Handle Accessors - if (basePropDescriptor && - (basePropDescriptor.get || basePropDescriptor.set)) { - Object.defineProperty(derivedCtor.prototype, propName, basePropDescriptor); - } - else { - derivedCtor.prototype[propName] = baseCtor.prototype[propName]; - } - }); - }); -} -apply_mixins.applyMixins = applyMixins; -var hasRequiredParser; + child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too + renderLanes); + return child; + } + } -function requireParser () { - if (hasRequiredParser) return parser; - hasRequiredParser = 1; - (function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EmbeddedActionsParser = exports.CstParser = exports.Parser = exports.EMPTY_ALT = exports.ParserDefinitionErrorType = exports.DEFAULT_RULE_CONFIG = exports.DEFAULT_PARSER_CONFIG = exports.END_OF_FILE = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var values_1 = __importDefault(values_1$1); - var has_1$1 = __importDefault(has_1); - var clone_1 = __importDefault(clone_1$1); - var utils_1 = api$2; - var follow_1 = follow; - var tokens_public_1 = tokens_public; - var errors_public_1 = errors_public; - var gast_resolver_public_1 = requireGast_resolver_public(); - var recoverable_1 = requireRecoverable(); - var looksahead_1 = requireLooksahead(); - var tree_builder_1 = requireTree_builder(); - var lexer_adapter_1 = requireLexer_adapter(); - var recognizer_api_1 = requireRecognizer_api(); - var recognizer_engine_1 = requireRecognizer_engine(); - var error_handler_1 = requireError_handler(); - var context_assist_1 = context_assist; - var gast_recorder_1 = requireGast_recorder(); - var perf_tracer_1 = requirePerf_tracer(); - var apply_mixins_1 = apply_mixins; - exports.END_OF_FILE = (0, tokens_public_1.createTokenInstance)(tokens_public_1.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN); - Object.freeze(exports.END_OF_FILE); - exports.DEFAULT_PARSER_CONFIG = Object.freeze({ - recoveryEnabled: false, - maxLookahead: 3, - dynamicTokensEnabled: false, - outputCst: true, - errorMessageProvider: errors_public_1.defaultParserErrorProvider, - nodeLocationTracking: "none", - traceInitPerf: false, - skipValidations: false - }); - exports.DEFAULT_RULE_CONFIG = Object.freeze({ - recoveryValueFunc: function () { return undefined; }, - resyncEnabled: true - }); - (function (ParserDefinitionErrorType) { - ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME"; - ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME"; - ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE"; - ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF"; - ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"] = 5] = "LEFT_RECURSION"; - ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT"; - ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE"; - ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME"; - ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"] = 10] = "NO_NON_EMPTY_LOOKAHEAD"; - ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 11] = "AMBIGUOUS_PREFIX_ALTS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 12] = "TOO_MANY_ALTS"; - })(exports.ParserDefinitionErrorType || (exports.ParserDefinitionErrorType = {})); - function EMPTY_ALT(value) { - if (value === void 0) { value = undefined; } - return function () { - return value; - }; - } - exports.EMPTY_ALT = EMPTY_ALT; - var Parser = /** @class */ (function () { - function Parser(tokenVocabulary, config) { - this.definitionErrors = []; - this.selfAnalysisDone = false; - var that = this; - that.initErrorHandler(config); - that.initLexerAdapter(); - that.initLooksAhead(config); - that.initRecognizerEngine(tokenVocabulary, config); - that.initRecoverable(config); - that.initTreeBuilder(config); - that.initContentAssist(); - that.initGastRecorder(config); - that.initPerformanceTracer(config); - if ((0, has_1$1.default)(config, "ignoredIssues")) { - throw new Error("The IParserConfig property has been deprecated.\n\t" + - "Please use the flag on the relevant DSL method instead.\n\t" + - "See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n\t" + - "For further details."); - } - this.skipValidations = (0, has_1$1.default)(config, "skipValidations") - ? config.skipValidations // casting assumes the end user passing the correct type - : exports.DEFAULT_PARSER_CONFIG.skipValidations; - } - /** - * @deprecated use the **instance** method with the same name instead - */ - Parser.performSelfAnalysis = function (parserInstance) { - throw Error("The **static** `performSelfAnalysis` method has been deprecated." + - "\t\nUse the **instance** method with the same name instead."); - }; - Parser.prototype.performSelfAnalysis = function () { - var _this = this; - this.TRACE_INIT("performSelfAnalysis", function () { - var defErrorsMsgs; - _this.selfAnalysisDone = true; - var className = _this.className; - _this.TRACE_INIT("toFastProps", function () { - // Without this voodoo magic the parser would be x3-x4 slower - // It seems it is better to invoke `toFastProperties` **before** - // Any manipulations of the `this` object done during the recording phase. - (0, utils_1.toFastProperties)(_this); - }); - _this.TRACE_INIT("Grammar Recording", function () { - try { - _this.enableRecording(); - // Building the GAST - (0, forEach_1.default)(_this.definedRulesNames, function (currRuleName) { - var wrappedRule = _this[currRuleName]; - var originalGrammarAction = wrappedRule["originalGrammarAction"]; - var recordedRuleGast; - _this.TRACE_INIT("".concat(currRuleName, " Rule"), function () { - recordedRuleGast = _this.topLevelRuleRecord(currRuleName, originalGrammarAction); - }); - _this.gastProductionsCache[currRuleName] = recordedRuleGast; - }); - } - finally { - _this.disableRecording(); - } - }); - var resolverErrors = []; - _this.TRACE_INIT("Grammar Resolving", function () { - resolverErrors = (0, gast_resolver_public_1.resolveGrammar)({ - rules: (0, values_1.default)(_this.gastProductionsCache) - }); - _this.definitionErrors = _this.definitionErrors.concat(resolverErrors); - }); - _this.TRACE_INIT("Grammar Validations", function () { - // only perform additional grammar validations IFF no resolving errors have occurred. - // as unresolved grammar may lead to unhandled runtime exceptions in the follow up validations. - if ((0, isEmpty_1.default)(resolverErrors) && _this.skipValidations === false) { - var validationErrors = (0, gast_resolver_public_1.validateGrammar)({ - rules: (0, values_1.default)(_this.gastProductionsCache), - maxLookahead: _this.maxLookahead, - tokenTypes: (0, values_1.default)(_this.tokensMap), - errMsgProvider: errors_public_1.defaultGrammarValidatorErrorProvider, - grammarName: className - }); - _this.definitionErrors = _this.definitionErrors.concat(validationErrors); - } - }); - // this analysis may fail if the grammar is not perfectly valid - if ((0, isEmpty_1.default)(_this.definitionErrors)) { - // The results of these computations are not needed unless error recovery is enabled. - if (_this.recoveryEnabled) { - _this.TRACE_INIT("computeAllProdsFollows", function () { - var allFollows = (0, follow_1.computeAllProdsFollows)((0, values_1.default)(_this.gastProductionsCache)); - _this.resyncFollows = allFollows; - }); - } - _this.TRACE_INIT("ComputeLookaheadFunctions", function () { - _this.preComputeLookaheadFunctions((0, values_1.default)(_this.gastProductionsCache)); - }); - } - if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING && - !(0, isEmpty_1.default)(_this.definitionErrors)) { - defErrorsMsgs = (0, map_1.default)(_this.definitionErrors, function (defError) { return defError.message; }); - throw new Error("Parser Definition Errors detected:\n ".concat(defErrorsMsgs.join("\n-------------------------------\n"))); - } - }); - }; - // Set this flag to true if you don't want the Parser to throw error when problems in it's definition are detected. - // (normally during the parser's constructor). - // This is a design time flag, it will not affect the runtime error handling of the parser, just design time errors, - // for example: duplicate rule names, referencing an unresolved subrule, ect... - // This flag should not be enabled during normal usage, it is used in special situations, for example when - // needing to display the parser definition errors in some GUI(online playground). - Parser.DEFER_DEFINITION_ERRORS_HANDLING = false; - return Parser; - }()); - exports.Parser = Parser; - (0, apply_mixins_1.applyMixins)(Parser, [ - recoverable_1.Recoverable, - looksahead_1.LooksAhead, - tree_builder_1.TreeBuilder, - lexer_adapter_1.LexerAdapter, - recognizer_engine_1.RecognizerEngine, - recognizer_api_1.RecognizerApi, - error_handler_1.ErrorHandler, - context_assist_1.ContentAssist, - gast_recorder_1.GastRecorder, - perf_tracer_1.PerformanceTracer - ]); - var CstParser = /** @class */ (function (_super) { - __extends(CstParser, _super); - function CstParser(tokenVocabulary, config) { - if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; } - var configClone = (0, clone_1.default)(config); - configClone.outputCst = true; - return _super.call(this, tokenVocabulary, configClone) || this; - } - return CstParser; - }(Parser)); - exports.CstParser = CstParser; - var EmbeddedActionsParser = /** @class */ (function (_super) { - __extends(EmbeddedActionsParser, _super); - function EmbeddedActionsParser(tokenVocabulary, config) { - if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; } - var configClone = (0, clone_1.default)(config); - configClone.outputCst = false; - return _super.call(this, tokenVocabulary, configClone) || this; - } - return EmbeddedActionsParser; - }(Parser)); - exports.EmbeddedActionsParser = EmbeddedActionsParser; - -} (parser)); - return parser; -} + var hint = ''; + + { + if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) { + hint = ' Did you wrap a component in React.lazy() more than once?'; + } + } // This message intentionally doesn't mention ForwardRef or MemoComponent + // because the fact that it's a separate type of work is an + // implementation detail. -var api = {}; -var model = {}; + throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint)); + } -var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(model, "__esModule", { value: true }); -model.buildModel = void 0; -var gast_1 = api$1; -var map_1$1 = __importDefault$1(map_1$4); -var flatten_1$1 = __importDefault$1(flatten_1$3); -var values_1 = __importDefault$1(values_1$1); -var some_1 = __importDefault$1(some_1$2); -var groupBy_1 = __importDefault$1(groupBy_1$1); -var assign_1 = __importDefault$1(assign_1$3); -function buildModel(productions) { - var generator = new CstNodeDefinitionGenerator(); - var allRules = (0, values_1.default)(productions); - return (0, map_1$1.default)(allRules, function (rule) { return generator.visitRule(rule); }); -} -model.buildModel = buildModel; -var CstNodeDefinitionGenerator = /** @class */ (function (_super) { - __extends(CstNodeDefinitionGenerator, _super); - function CstNodeDefinitionGenerator() { - return _super !== null && _super.apply(this, arguments) || this; - } - CstNodeDefinitionGenerator.prototype.visitRule = function (node) { - var rawElements = this.visitEach(node.definition); - var grouped = (0, groupBy_1.default)(rawElements, function (el) { return el.propertyName; }); - var properties = (0, map_1$1.default)(grouped, function (group, propertyName) { - var allNullable = !(0, some_1.default)(group, function (el) { return !el.canBeNull; }); - // In an alternation with a label a property name can have - // multiple types. - var propertyType = group[0].type; - if (group.length > 1) { - propertyType = (0, map_1$1.default)(group, function (g) { return g.type; }); - } - return { - name: propertyName, - type: propertyType, - optional: allNullable - }; - }); - return { - name: node.name, - properties: properties - }; - }; - CstNodeDefinitionGenerator.prototype.visitAlternative = function (node) { - return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); - }; - CstNodeDefinitionGenerator.prototype.visitOption = function (node) { - return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); - }; - CstNodeDefinitionGenerator.prototype.visitRepetition = function (node) { - return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); - }; - CstNodeDefinitionGenerator.prototype.visitRepetitionMandatory = function (node) { - return this.visitEach(node.definition); - }; - CstNodeDefinitionGenerator.prototype.visitRepetitionMandatoryWithSeparator = function (node) { - return this.visitEach(node.definition).concat({ - propertyName: node.separator.name, - canBeNull: true, - type: getType(node.separator) - }); - }; - CstNodeDefinitionGenerator.prototype.visitRepetitionWithSeparator = function (node) { - return this.visitEachAndOverrideWith(node.definition, { - canBeNull: true - }).concat({ - propertyName: node.separator.name, - canBeNull: true, - type: getType(node.separator) - }); - }; - CstNodeDefinitionGenerator.prototype.visitAlternation = function (node) { - return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); - }; - CstNodeDefinitionGenerator.prototype.visitTerminal = function (node) { - return [ - { - propertyName: node.label || node.terminalType.name, - canBeNull: false, - type: getType(node) - } - ]; - }; - CstNodeDefinitionGenerator.prototype.visitNonTerminal = function (node) { - return [ - { - propertyName: node.label || node.nonTerminalName, - canBeNull: false, - type: getType(node) - } - ]; - }; - CstNodeDefinitionGenerator.prototype.visitEachAndOverrideWith = function (definition, override) { - return (0, map_1$1.default)(this.visitEach(definition), function (definition) { return (0, assign_1.default)({}, definition, override); }); - }; - CstNodeDefinitionGenerator.prototype.visitEach = function (definition) { - var _this = this; - return (0, flatten_1$1.default)((0, map_1$1.default)(definition, function (definition) { return _this.visit(definition); })); - }; - return CstNodeDefinitionGenerator; -}(gast_1.GAstVisitor)); -function getType(production) { - if (production instanceof gast_1.NonTerminal) { - return { - kind: "rule", - name: production.referencedRule.name - }; - } - return { kind: "token" }; -} + function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) { + if (_current !== null) { + // An incomplete component only mounts if it suspended inside a non- + // concurrent tree, in an inconsistent state. We want to treat it like + // a new mount, even though an empty version of it already committed. + // Disconnect the alternate pointers. + _current.alternate = null; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect -var generate = {}; + workInProgress.flags |= Placement; + } // Promote the fiber to a class and try rendering again. -var baseSlice = _baseSlice; -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice$1(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} + workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` + // Push context providers early to prevent context stack mismatches. + // During mounting we don't know the child context yet as the instance doesn't exist. + // We will invalidate the child context in finishClassComponent() right after rendering. -var _castSlice = castSlice$1; + var hasContext; -/** Used to compose unicode character classes. */ + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress); + } else { + hasContext = false; + } -var rsAstralRange$1 = '\\ud800-\\udfff', - rsComboMarksRange$1 = '\\u0300-\\u036f', - reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', - rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, - rsVarRange$1 = '\\ufe0e\\ufe0f'; + prepareToReadContext(workInProgress, renderLanes); + constructClassInstance(workInProgress, Component, nextProps); + mountClassInstance(workInProgress, Component, nextProps, renderLanes); + return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); + } -/** Used to compose unicode capture groups. */ -var rsZWJ$1 = '\\u200d'; + function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) { + if (_current !== null) { + // An indeterminate component only mounts if it suspended inside a non- + // concurrent tree, in an inconsistent state. We want to treat it like + // a new mount, even though an empty version of it already committed. + // Disconnect the alternate pointers. + _current.alternate = null; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ$1 + rsAstralRange$1 + rsComboRange$1 + rsVarRange$1 + ']'); + workInProgress.flags |= Placement; + } -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode$2(string) { - return reHasUnicode.test(string); -} + var props = workInProgress.pendingProps; + var context; -var _hasUnicode = hasUnicode$2; + { + var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); + context = getMaskedContext(workInProgress, unmaskedContext); + } -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ + prepareToReadContext(workInProgress, renderLanes); + var value; + var hasId; -function asciiToArray$1(string) { - return string.split(''); -} + { + markComponentRenderStarted(workInProgress); + } -var _asciiToArray = asciiToArray$1; + { + if (Component.prototype && typeof Component.prototype.render === 'function') { + var componentName = getComponentNameFromType(Component) || 'Unknown'; -/** Used to compose unicode character classes. */ + if (!didWarnAboutBadClass[componentName]) { + error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); -var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsVarRange = '\\ufe0e\\ufe0f'; + didWarnAboutBadClass[componentName] = true; + } + } -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsZWJ = '\\u200d'; + if (workInProgress.mode & StrictLegacyMode) { + ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null); + } -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + setIsRendering(true); + ReactCurrentOwner$1.current = workInProgress; + value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); + hasId = checkDidRenderIdHook(); + setIsRendering(false); + } -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + { + markComponentRenderStopped(); + } // React DevTools reads this flag. -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray$1(string) { - return string.match(reUnicode) || []; -} -var _unicodeToArray = unicodeToArray$1; + workInProgress.flags |= PerformedWork; -var asciiToArray = _asciiToArray, - hasUnicode$1 = _hasUnicode, - unicodeToArray = _unicodeToArray; + { + // Support for module components is deprecated and is removed behind a flag. + // Whether or not it would crash later, we want to show a good message in DEV first. + if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + var _componentName = getComponentNameFromType(Component) || 'Unknown'; -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray$1(string) { - return hasUnicode$1(string) - ? unicodeToArray(string) - : asciiToArray(string); -} + if (!didWarnAboutModulePatternComponent[_componentName]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); -var _stringToArray = stringToArray$1; + didWarnAboutModulePatternComponent[_componentName] = true; + } + } + } -var castSlice = _castSlice, - hasUnicode = _hasUnicode, - stringToArray = _stringToArray, - toString = toString_1; + if ( // Run these checks in production only if the flag is off. + // Eventually we'll delete this branch altogether. + typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + { + var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; -/** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ -function createCaseFirst$1(methodName) { - return function(string) { - string = toString(string); + if (!didWarnAboutModulePatternComponent[_componentName2]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; + didWarnAboutModulePatternComponent[_componentName2] = true; + } + } // Proceed under the assumption that this is a class instance - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); + workInProgress.tag = ClassComponent; // Throw out any hooks that were used. - return chr[methodName]() + trailing; - }; -} + workInProgress.memoizedState = null; + workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches. + // During mounting we don't know the child context yet as the instance doesn't exist. + // We will invalidate the child context in finishClassComponent() right after rendering. -var _createCaseFirst = createCaseFirst$1; + var hasContext = false; -var createCaseFirst = _createCaseFirst; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress); + } else { + hasContext = false; + } -/** - * Converts the first character of `string` to upper case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.upperFirst('fred'); - * // => 'Fred' - * - * _.upperFirst('FRED'); - * // => 'FRED' - */ -var upperFirst = createCaseFirst('toUpperCase'); + workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; + initializeUpdateQueue(workInProgress); + adoptClassInstance(workInProgress, value); + mountClassInstance(workInProgress, Component, props, renderLanes); + return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); + } else { + // Proceed under the assumption that this is a function component + workInProgress.tag = FunctionComponent; -var upperFirst_1$1 = upperFirst; + { -var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(generate, "__esModule", { value: true }); -generate.genDts = void 0; -var flatten_1 = __importDefault(flatten_1$3); -var isArray_1 = __importDefault(isArray_1$1); -var map_1 = __importDefault(map_1$4); -var reduce_1 = __importDefault(reduce_1$1); -var uniq_1 = __importDefault(uniq_1$2); -var upperFirst_1 = __importDefault(upperFirst_1$1); -function genDts(model, options) { - var contentParts = []; - contentParts = contentParts.concat("import type { CstNode, ICstVisitor, IToken } from \"chevrotain\";"); - contentParts = contentParts.concat((0, flatten_1.default)((0, map_1.default)(model, function (node) { return genCstNodeTypes(node); }))); - if (options.includeVisitorInterface) { - contentParts = contentParts.concat(genVisitor(options.visitorInterfaceName, model)); - } - return contentParts.join("\n\n") + "\n"; -} -generate.genDts = genDts; -function genCstNodeTypes(node) { - var nodeCstInterface = genNodeInterface(node); - var nodeChildrenInterface = genNodeChildrenType(node); - return [nodeCstInterface, nodeChildrenInterface]; -} -function genNodeInterface(node) { - var nodeInterfaceName = getNodeInterfaceName(node.name); - var childrenTypeName = getNodeChildrenTypeName(node.name); - return "export interface ".concat(nodeInterfaceName, " extends CstNode {\n name: \"").concat(node.name, "\";\n children: ").concat(childrenTypeName, ";\n}"); -} -function genNodeChildrenType(node) { - var typeName = getNodeChildrenTypeName(node.name); - return "export type ".concat(typeName, " = {\n ").concat((0, map_1.default)(node.properties, function (property) { return genChildProperty(property); }).join("\n "), "\n};"); -} -function genChildProperty(prop) { - var typeName = buildTypeString(prop.type); - return "".concat(prop.name).concat(prop.optional ? "?" : "", ": ").concat(typeName, "[];"); -} -function genVisitor(name, nodes) { - return "export interface ".concat(name, " extends ICstVisitor {\n ").concat((0, map_1.default)(nodes, function (node) { return genVisitorFunction(node); }).join("\n "), "\n}"); -} -function genVisitorFunction(node) { - var childrenTypeName = getNodeChildrenTypeName(node.name); - return "".concat(node.name, "(children: ").concat(childrenTypeName, ", param?: IN): OUT;"); -} -function buildTypeString(type) { - if ((0, isArray_1.default)(type)) { - var typeNames = (0, uniq_1.default)((0, map_1.default)(type, function (t) { return getTypeString(t); })); - var typeString = (0, reduce_1.default)(typeNames, function (sum, t) { return sum + " | " + t; }); - return "(" + typeString + ")"; - } - else { - return getTypeString(type); - } -} -function getTypeString(type) { - if (type.kind === "token") { - return "IToken"; - } - return getNodeInterfaceName(type.name); -} -function getNodeInterfaceName(ruleName) { - return (0, upperFirst_1.default)(ruleName) + "CstNode"; -} -function getNodeChildrenTypeName(ruleName) { - return (0, upperFirst_1.default)(ruleName) + "CstChildren"; -} + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); -var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -Object.defineProperty(api, "__esModule", { value: true }); -api.generateCstDts = void 0; -var model_1 = model; -var generate_1 = generate; -var defaultOptions = { - includeVisitorInterface: true, - visitorInterfaceName: "ICstNodeVisitor" -}; -function generateCstDts(productions, options) { - var effectiveOptions = __assign(__assign({}, defaultOptions), options); - var model = (0, model_1.buildModel)(productions); - return (0, generate_1.genDts)(model, effectiveOptions); -} -api.generateCstDts = generateCstDts; - -var render_public = {}; - -Object.defineProperty(render_public, "__esModule", { value: true }); -render_public.createSyntaxDiagramsCode = void 0; -var version_1 = version; -function createSyntaxDiagramsCode(grammar, _a) { - var _b = _a === void 0 ? {} : _a, _c = _b.resourceBase, resourceBase = _c === void 0 ? "https://unpkg.com/chevrotain@".concat(version_1.VERSION, "/diagrams/") : _c, _d = _b.css, css = _d === void 0 ? "https://unpkg.com/chevrotain@".concat(version_1.VERSION, "/diagrams/diagrams.css") : _d; - var header = "\n\n\n\n\n\n"; - var cssHtml = "\n\n"); - var scripts = "\n\n\n\n\n"); - var diagramsDiv = "\n
\n"; - var serializedGrammar = "\n\n"); - var initLogic = "\n\n"; - return (header + cssHtml + scripts + diagramsDiv + serializedGrammar + initLogic); -} -render_public.createSyntaxDiagramsCode = createSyntaxDiagramsCode; - -(function (exports) { - /* istanbul ignore file - tricky to import some things from this module during testing */ - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Parser = exports.createSyntaxDiagramsCode = exports.clearCache = exports.generateCstDts = exports.GAstVisitor = exports.serializeProduction = exports.serializeGrammar = exports.Terminal = exports.Rule = exports.RepetitionWithSeparator = exports.RepetitionMandatoryWithSeparator = exports.RepetitionMandatory = exports.Repetition = exports.Option = exports.NonTerminal = exports.Alternative = exports.Alternation = exports.defaultLexerErrorProvider = exports.NoViableAltException = exports.NotAllInputParsedException = exports.MismatchedTokenException = exports.isRecognitionException = exports.EarlyExitException = exports.defaultParserErrorProvider = exports.tokenName = exports.tokenMatcher = exports.tokenLabel = exports.EOF = exports.createTokenInstance = exports.createToken = exports.LexerDefinitionErrorType = exports.Lexer = exports.EMPTY_ALT = exports.ParserDefinitionErrorType = exports.EmbeddedActionsParser = exports.CstParser = exports.VERSION = void 0; - // semantic version - var version_1 = version; - Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return version_1.VERSION; } }); - var parser_1 = requireParser(); - Object.defineProperty(exports, "CstParser", { enumerable: true, get: function () { return parser_1.CstParser; } }); - Object.defineProperty(exports, "EmbeddedActionsParser", { enumerable: true, get: function () { return parser_1.EmbeddedActionsParser; } }); - Object.defineProperty(exports, "ParserDefinitionErrorType", { enumerable: true, get: function () { return parser_1.ParserDefinitionErrorType; } }); - Object.defineProperty(exports, "EMPTY_ALT", { enumerable: true, get: function () { return parser_1.EMPTY_ALT; } }); - var lexer_public_1 = requireLexer_public(); - Object.defineProperty(exports, "Lexer", { enumerable: true, get: function () { return lexer_public_1.Lexer; } }); - Object.defineProperty(exports, "LexerDefinitionErrorType", { enumerable: true, get: function () { return lexer_public_1.LexerDefinitionErrorType; } }); - // Tokens utilities - var tokens_public_1 = tokens_public; - Object.defineProperty(exports, "createToken", { enumerable: true, get: function () { return tokens_public_1.createToken; } }); - Object.defineProperty(exports, "createTokenInstance", { enumerable: true, get: function () { return tokens_public_1.createTokenInstance; } }); - Object.defineProperty(exports, "EOF", { enumerable: true, get: function () { return tokens_public_1.EOF; } }); - Object.defineProperty(exports, "tokenLabel", { enumerable: true, get: function () { return tokens_public_1.tokenLabel; } }); - Object.defineProperty(exports, "tokenMatcher", { enumerable: true, get: function () { return tokens_public_1.tokenMatcher; } }); - Object.defineProperty(exports, "tokenName", { enumerable: true, get: function () { return tokens_public_1.tokenName; } }); - // Other Utilities - var errors_public_1 = errors_public; - Object.defineProperty(exports, "defaultParserErrorProvider", { enumerable: true, get: function () { return errors_public_1.defaultParserErrorProvider; } }); - var exceptions_public_1 = exceptions_public; - Object.defineProperty(exports, "EarlyExitException", { enumerable: true, get: function () { return exceptions_public_1.EarlyExitException; } }); - Object.defineProperty(exports, "isRecognitionException", { enumerable: true, get: function () { return exceptions_public_1.isRecognitionException; } }); - Object.defineProperty(exports, "MismatchedTokenException", { enumerable: true, get: function () { return exceptions_public_1.MismatchedTokenException; } }); - Object.defineProperty(exports, "NotAllInputParsedException", { enumerable: true, get: function () { return exceptions_public_1.NotAllInputParsedException; } }); - Object.defineProperty(exports, "NoViableAltException", { enumerable: true, get: function () { return exceptions_public_1.NoViableAltException; } }); - var lexer_errors_public_1 = lexer_errors_public; - Object.defineProperty(exports, "defaultLexerErrorProvider", { enumerable: true, get: function () { return lexer_errors_public_1.defaultLexerErrorProvider; } }); - // grammar reflection API - var gast_1 = api$1; - Object.defineProperty(exports, "Alternation", { enumerable: true, get: function () { return gast_1.Alternation; } }); - Object.defineProperty(exports, "Alternative", { enumerable: true, get: function () { return gast_1.Alternative; } }); - Object.defineProperty(exports, "NonTerminal", { enumerable: true, get: function () { return gast_1.NonTerminal; } }); - Object.defineProperty(exports, "Option", { enumerable: true, get: function () { return gast_1.Option; } }); - Object.defineProperty(exports, "Repetition", { enumerable: true, get: function () { return gast_1.Repetition; } }); - Object.defineProperty(exports, "RepetitionMandatory", { enumerable: true, get: function () { return gast_1.RepetitionMandatory; } }); - Object.defineProperty(exports, "RepetitionMandatoryWithSeparator", { enumerable: true, get: function () { return gast_1.RepetitionMandatoryWithSeparator; } }); - Object.defineProperty(exports, "RepetitionWithSeparator", { enumerable: true, get: function () { return gast_1.RepetitionWithSeparator; } }); - Object.defineProperty(exports, "Rule", { enumerable: true, get: function () { return gast_1.Rule; } }); - Object.defineProperty(exports, "Terminal", { enumerable: true, get: function () { return gast_1.Terminal; } }); - // GAST Utilities - var gast_2 = api$1; - Object.defineProperty(exports, "serializeGrammar", { enumerable: true, get: function () { return gast_2.serializeGrammar; } }); - Object.defineProperty(exports, "serializeProduction", { enumerable: true, get: function () { return gast_2.serializeProduction; } }); - Object.defineProperty(exports, "GAstVisitor", { enumerable: true, get: function () { return gast_2.GAstVisitor; } }); - var cst_dts_gen_1 = api; - Object.defineProperty(exports, "generateCstDts", { enumerable: true, get: function () { return cst_dts_gen_1.generateCstDts; } }); - /* istanbul ignore next */ - function clearCache() { - console.warn("The clearCache function was 'soft' removed from the Chevrotain API." + - "\n\t It performs no action other than printing this message." + - "\n\t Please avoid using it as it will be completely removed in the future"); - } - exports.clearCache = clearCache; - var render_public_1 = render_public; - Object.defineProperty(exports, "createSyntaxDiagramsCode", { enumerable: true, get: function () { return render_public_1.createSyntaxDiagramsCode; } }); - var Parser = /** @class */ (function () { - function Parser() { - throw new Error("The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead.\t\n" + - "See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0"); - } - return Parser; - }()); - exports.Parser = Parser; - -} (api$3)); - -var mod = /*@__PURE__*/getDefaultExportFromCjs(api$3); - -mod.Alternation; -mod.Alternative; -mod.CstParser; -mod.EMPTY_ALT; -mod.EOF; -mod.EarlyExitException; -mod.EmbeddedActionsParser; -mod.GAstVisitor; -mod.Lexer; -mod.LexerDefinitionErrorType; -mod.MismatchedTokenException; -mod.NoViableAltException; -mod.NonTerminal; -mod.NotAllInputParsedException; -mod.Option; -mod.Parser; -mod.ParserDefinitionErrorType; -mod.Repetition; -mod.RepetitionMandatory; -mod.RepetitionMandatoryWithSeparator; -mod.RepetitionWithSeparator; -mod.Rule; -mod.Terminal; -mod.VERSION; -mod.clearCache; -mod.createSyntaxDiagramsCode; -mod.createToken; -mod.createTokenInstance; -mod.defaultLexerErrorProvider; -mod.defaultParserErrorProvider; -mod.generateCstDts; -mod.isRecognitionException; -mod.serializeGrammar; -mod.serializeProduction; -mod.tokenLabel; -mod.tokenMatcher; -mod.tokenName; + try { + value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } + } -/** - * Loader for Basis Universal GPU Texture Codec. - * - * Basis Universal is a "supercompressed" GPU texture and texture video - * compression system that outputs a highly compressed intermediate file format - * (.basis) that can be quickly transcoded to a wide variety of GPU texture - * compression formats. - * - * This loader parallelizes the transcoding process across a configurable number - * of web workers, before transferring the transcoded compressed texture back - * to the main thread. - */ + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress); + } -const _taskCache = new WeakMap(); + reconcileChildren(null, workInProgress, value, renderLanes); -class BasisTextureLoader extends Loader { - constructor(manager) { - super(manager); - this.transcoderPath = ''; - this.transcoderBinary = null; - this.transcoderPending = null; - this.workerLimit = 4; - this.workerPool = []; - this.workerNextTaskID = 1; - this.workerSourceURL = ''; - this.workerConfig = null; - } + { + validateFunctionComponentInDev(workInProgress, Component); + } - setTranscoderPath(path) { - this.transcoderPath = path; - return this; - } + return workInProgress.child; + } + } - setWorkerLimit(workerLimit) { - this.workerLimit = workerLimit; - return this; - } + function validateFunctionComponentInDev(workInProgress, Component) { + { + if (Component) { + if (Component.childContextTypes) { + error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); + } + } - detectSupport(renderer) { - this.workerConfig = { - astcSupported: renderer.extensions.has('WEBGL_compressed_texture_astc'), - etc1Supported: renderer.extensions.has('WEBGL_compressed_texture_etc1'), - etc2Supported: renderer.extensions.has('WEBGL_compressed_texture_etc'), - dxtSupported: renderer.extensions.has('WEBGL_compressed_texture_s3tc'), - bptcSupported: renderer.extensions.has('EXT_texture_compression_bptc'), - pvrtcSupported: renderer.extensions.has('WEBGL_compressed_texture_pvrtc') || renderer.extensions.has('WEBKIT_WEBGL_compressed_texture_pvrtc') - }; - return this; - } + if (workInProgress.ref !== null) { + var info = ''; + var ownerName = getCurrentFiberOwnerNameInDevOrNull(); - load(url, onLoad, onProgress, onError) { - const loader = new FileLoader(this.manager); - loader.setResponseType('arraybuffer'); - loader.setWithCredentials(this.withCredentials); - const texture = new CompressedTexture(); - loader.load(url, buffer => { - // Check for an existing task using this buffer. A transferred buffer cannot be transferred - // again from this thread. - if (_taskCache.has(buffer)) { - const cachedTask = _taskCache.get(buffer); + if (ownerName) { + info += '\n\nCheck the render method of `' + ownerName + '`.'; + } - return cachedTask.promise.then(onLoad).catch(onError); - } + var warningKey = ownerName || ''; + var debugSource = workInProgress._debugSource; - this._createTexture([buffer]).then(function (_texture) { - texture.copy(_texture); - texture.needsUpdate = true; - if (onLoad) onLoad(texture); - }).catch(onError); - }, onProgress, onError); - return texture; - } - /** Low-level transcoding API, exposed for use by KTX2Loader. */ + if (debugSource) { + warningKey = debugSource.fileName + ':' + debugSource.lineNumber; + } + if (!didWarnAboutFunctionRefs[warningKey]) { + didWarnAboutFunctionRefs[warningKey] = true; - parseInternalAsync(options) { - const { - levels - } = options; - const buffers = new Set(); + error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info); + } + } - for (let i = 0; i < levels.length; i++) { - buffers.add(levels[i].data.buffer); - } + if (typeof Component.getDerivedStateFromProps === 'function') { + var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; - return this._createTexture(Array.from(buffers), { ...options, - lowLevel: true - }); - } - /** - * @param {ArrayBuffer[]} buffers - * @param {object?} config - * @return {Promise} - */ + if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { + error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); + didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; + } + } - _createTexture(buffers, config = {}) { - let worker; - let taskID; - const taskConfig = config; - let taskCost = 0; + if (typeof Component.contextType === 'object' && Component.contextType !== null) { + var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; - for (let i = 0; i < buffers.length; i++) { - taskCost += buffers[i].byteLength; - } + if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { + error('%s: Function components do not support contextType.', _componentName4); - const texturePending = this._allocateWorker(taskCost).then(_worker => { - worker = _worker; - taskID = this.workerNextTaskID++; - return new Promise((resolve, reject) => { - worker._callbacks[taskID] = { - resolve, - reject - }; - worker.postMessage({ - type: 'transcode', - id: taskID, - buffers: buffers, - taskConfig: taskConfig - }, buffers); - }); - }).then(message => { - const { - mipmaps, - width, - height, - format - } = message; - const texture = new CompressedTexture(mipmaps, width, height, format, UnsignedByteType); - texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; - texture.magFilter = LinearFilter; - texture.generateMipmaps = false; - texture.needsUpdate = true; - return texture; - }); // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416) - - - texturePending.catch(() => true).then(() => { - if (worker && taskID) { - worker._taskLoad -= taskCost; - delete worker._callbacks[taskID]; - } - }); // Cache the task result. + didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; + } + } + } + } - _taskCache.set(buffers[0], { - promise: texturePending - }); + var SUSPENDED_MARKER = { + dehydrated: null, + treeContext: null, + retryLane: NoLane + }; - return texturePending; - } - - _initTranscoder() { - if (!this.transcoderPending) { - // Load transcoder wrapper. - const jsLoader = new FileLoader(this.manager); - jsLoader.setPath(this.transcoderPath); - jsLoader.setWithCredentials(this.withCredentials); - const jsContent = new Promise((resolve, reject) => { - jsLoader.load('basis_transcoder.js', resolve, undefined, reject); - }); // Load transcoder WASM binary. - - const binaryLoader = new FileLoader(this.manager); - binaryLoader.setPath(this.transcoderPath); - binaryLoader.setResponseType('arraybuffer'); - binaryLoader.setWithCredentials(this.withCredentials); - const binaryContent = new Promise((resolve, reject) => { - binaryLoader.load('basis_transcoder.wasm', resolve, undefined, reject); - }); - this.transcoderPending = Promise.all([jsContent, binaryContent]).then(([jsContent, binaryContent]) => { - const fn = BasisTextureLoader.BasisWorker.toString(); - const body = ['/* constants */', 'let _EngineFormat = ' + JSON.stringify(BasisTextureLoader.EngineFormat), 'let _TranscoderFormat = ' + JSON.stringify(BasisTextureLoader.TranscoderFormat), 'let _BasisFormat = ' + JSON.stringify(BasisTextureLoader.BasisFormat), '/* basis_transcoder.js */', jsContent, '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n'); - this.workerSourceURL = URL.createObjectURL(new Blob([body])); - this.transcoderBinary = binaryContent; - }); - } + function mountSuspenseOffscreenState(renderLanes) { + return { + baseLanes: renderLanes, + cachePool: getSuspendedCache() + }; + } - return this.transcoderPending; - } + function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) { + var cachePool = null; - _allocateWorker(taskCost) { - return this._initTranscoder().then(() => { - if (this.workerPool.length < this.workerLimit) { - const worker = new Worker(this.workerSourceURL); - worker._callbacks = {}; - worker._taskLoad = 0; - worker.postMessage({ - type: 'init', - config: this.workerConfig, - transcoderBinary: this.transcoderBinary - }); + return { + baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes), + cachePool: cachePool + }; + } // TODO: Probably should inline this back - worker.onmessage = function (e) { - const message = e.data; - switch (message.type) { - case 'transcode': - worker._callbacks[message.id].resolve(message); + function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) { + // If we're already showing a fallback, there are cases where we need to + // remain on that fallback regardless of whether the content has resolved. + // For example, SuspenseList coordinates when nested content appears. + if (current !== null) { + var suspenseState = current.memoizedState; - break; + if (suspenseState === null) { + // Currently showing content. Don't hide it, even if ForceSuspenseFallback + // is true. More precise name might be "ForceRemainSuspenseFallback". + // Note: This is a factoring smell. Can't remain on a fallback if there's + // no fallback to remain on. + return false; + } + } // Not currently showing content. Consult the Suspense context. - case 'error': - worker._callbacks[message.id].reject(message); - break; + return hasSuspenseContext(suspenseContext, ForceSuspenseFallback); + } - default: - console.error('THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"'); - } - }; + function getRemainingWorkInPrimaryTree(current, renderLanes) { + // TODO: Should not remove render lanes that were pinged during this render + return removeLanes(current.childLanes, renderLanes); + } - this.workerPool.push(worker); - } else { - this.workerPool.sort(function (a, b) { - return a._taskLoad > b._taskLoad ? -1 : 1; - }); - } + function updateSuspenseComponent(current, workInProgress, renderLanes) { + var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. - const worker = this.workerPool[this.workerPool.length - 1]; - worker._taskLoad += taskCost; - return worker; - }); - } + { + if (shouldSuspend(workInProgress)) { + workInProgress.flags |= DidCapture; + } + } - dispose() { - for (let i = 0; i < this.workerPool.length; i++) { - this.workerPool[i].terminate(); - } + var suspenseContext = suspenseStackCursor.current; + var showFallback = false; + var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags; - this.workerPool.length = 0; - return this; - } + if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) { + // Something in this boundary's subtree already suspended. Switch to + // rendering the fallback children. + showFallback = true; + workInProgress.flags &= ~DidCapture; + } else { + // Attempting the main content + if (current === null || current.memoizedState !== null) { + // This is a new mount or this boundary is already showing a fallback state. + // Mark this subtree context as having at least one invisible parent that could + // handle the fallback state. + // Avoided boundaries are not considered since they cannot handle preferred fallback states. + { + suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext); + } + } + } -} -/* CONSTANTS */ + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense + // boundary's children. This involves some custom reconciliation logic. Two + // main reasons this is so complicated. + // + // First, Legacy Mode has different semantics for backwards compatibility. The + // primary tree will commit in an inconsistent state, so when we do the + // second pass to render the fallback, we do some exceedingly, uh, clever + // hacks to make that not totally break. Like transferring effects and + // deletions from hidden tree. In Concurrent Mode, it's much simpler, + // because we bailout on the primary tree completely and leave it in its old + // state, no effects. Same as what we do for Offscreen (except that + // Offscreen doesn't have the first render pass). + // + // Second is hydration. During hydration, the Suspense fiber has a slightly + // different layout, where the child points to a dehydrated fragment, which + // contains the DOM rendered by the server. + // + // Third, even if you set all that aside, Suspense is like error boundaries in + // that we first we try to render one tree, and if that fails, we render again + // and switch to a different tree. Like a try/catch block. So we have to track + // which branch we're currently rendering. Ideally we would model this using + // a stack. + if (current === null) { + // Initial mount + // If we're currently hydrating, try to hydrate this boundary. + tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. -BasisTextureLoader.BasisFormat = { - ETC1S: 0, - UASTC_4x4: 1 -}; -BasisTextureLoader.TranscoderFormat = { - ETC1: 0, - ETC2: 1, - BC1: 2, - BC3: 3, - BC4: 4, - BC5: 5, - BC7_M6_OPAQUE_ONLY: 6, - BC7_M5: 7, - PVRTC1_4_RGB: 8, - PVRTC1_4_RGBA: 9, - ASTC_4x4: 10, - ATC_RGB: 11, - ATC_RGBA_INTERPOLATED_ALPHA: 12, - RGBA32: 13, - RGB565: 14, - BGR565: 15, - RGBA4444: 16 -}; -BasisTextureLoader.EngineFormat = { - RGBAFormat: RGBAFormat, - RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format, - RGBA_BPTC_Format: RGBA_BPTC_Format, - RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format, - RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format, - RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format, - RGB_ETC1_Format: RGB_ETC1_Format, - RGB_ETC2_Format: RGB_ETC2_Format, - RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format, - RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format -}; -/* WEB WORKER */ + { + var suspenseState = workInProgress.memoizedState; -BasisTextureLoader.BasisWorker = function () { - let config; - let transcoderPending; - let BasisModule; - const EngineFormat = _EngineFormat; // eslint-disable-line no-undef + if (suspenseState !== null) { + var dehydrated = suspenseState.dehydrated; - const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef + if (dehydrated !== null) { + return mountDehydratedSuspenseComponent(workInProgress, dehydrated); + } + } + } - const BasisFormat = _BasisFormat; // eslint-disable-line no-undef + var nextPrimaryChildren = nextProps.children; + var nextFallbackChildren = nextProps.fallback; - onmessage = function (e) { - const message = e.data; + if (showFallback) { + var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes); + var primaryChildFragment = workInProgress.child; + primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes); + workInProgress.memoizedState = SUSPENDED_MARKER; + return fallbackFragment; + } else { + return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren); + } + } else { + // This is an update. + // If the current fiber has a SuspenseState, that means it's already showing + // a fallback. + var prevState = current.memoizedState; - switch (message.type) { - case 'init': - config = message.config; - init(message.transcoderBinary); - break; + if (prevState !== null) { + // The current tree is already showing a fallback + // Special path for hydration + { + var _dehydrated = prevState.dehydrated; - case 'transcode': - transcoderPending.then(() => { - try { - const { - width, - height, - hasAlpha, - mipmaps, - format - } = message.taskConfig.lowLevel ? transcodeLowLevel(message.taskConfig) : transcode(message.buffers[0]); - const buffers = []; - - for (let i = 0; i < mipmaps.length; ++i) { - buffers.push(mipmaps[i].data.buffer); - } + if (_dehydrated !== null) { + if (!didSuspend) { + return updateDehydratedSuspenseComponent(current, workInProgress, _dehydrated, prevState, renderLanes); + } else if (workInProgress.flags & ForceClientRender) { + // Something errored during hydration. Try again without hydrating. + workInProgress.flags &= ~ForceClientRender; + return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.')); + } else if (workInProgress.memoizedState !== null) { + // Something suspended and we should still be in dehydrated mode. + // Leave the existing child in place. + workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there + // but the normal suspense pass doesn't. - self.postMessage({ - type: 'transcode', - id: message.id, - width, - height, - hasAlpha, - mipmaps, - format - }, buffers); - } catch (error) { - console.error(error); - self.postMessage({ - type: 'error', - id: message.id, - error: error.message - }); - } - }); - break; - } - }; + workInProgress.flags |= DidCapture; + return null; + } else { + // Suspended but we should no longer be in dehydrated mode. + // Therefore we now have to render the fallback. + var _nextPrimaryChildren = nextProps.children; + var _nextFallbackChildren = nextProps.fallback; + var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes); + var _primaryChildFragment2 = workInProgress.child; + _primaryChildFragment2.memoizedState = mountSuspenseOffscreenState(renderLanes); + workInProgress.memoizedState = SUSPENDED_MARKER; + return fallbackChildFragment; + } + } + } - function init(wasmBinary) { - transcoderPending = new Promise(resolve => { - BasisModule = { - wasmBinary, - onRuntimeInitialized: resolve - }; - BASIS(BasisModule); // eslint-disable-line no-undef - }).then(() => { - BasisModule.initializeBasis(); - }); - } + if (showFallback) { + var _nextFallbackChildren2 = nextProps.fallback; + var _nextPrimaryChildren2 = nextProps.children; - function transcodeLowLevel(taskConfig) { - const { - basisFormat, - width, - height, - hasAlpha - } = taskConfig; - const { - transcoderFormat, - engineFormat - } = getTranscoderFormat(basisFormat, width, height, hasAlpha); - const blockByteLength = BasisModule.getBytesPerBlockOrPixel(transcoderFormat); - assert(BasisModule.isFormatSupported(transcoderFormat), 'THREE.BasisTextureLoader: Unsupported format.'); - const mipmaps = []; - - if (basisFormat === BasisFormat.ETC1S) { - const transcoder = new BasisModule.LowLevelETC1SImageTranscoder(); - const { - endpointCount, - endpointsData, - selectorCount, - selectorsData, - tablesData - } = taskConfig.globalData; + var _fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren2, _nextFallbackChildren2, renderLanes); - try { - let ok; - ok = transcoder.decodePalettes(endpointCount, endpointsData, selectorCount, selectorsData); - assert(ok, 'THREE.BasisTextureLoader: decodePalettes() failed.'); - ok = transcoder.decodeTables(tablesData); - assert(ok, 'THREE.BasisTextureLoader: decodeTables() failed.'); - - for (let i = 0; i < taskConfig.levels.length; i++) { - const level = taskConfig.levels[i]; - const imageDesc = taskConfig.globalData.imageDescs[i]; - const dstByteLength = getTranscodedImageByteLength(transcoderFormat, level.width, level.height); - const dst = new Uint8Array(dstByteLength); - ok = transcoder.transcodeImage(transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks(transcoderFormat, level.width), getHeightInBlocks(transcoderFormat, level.height), level.width, level.height, level.index, imageDesc.rgbSliceByteOffset, imageDesc.rgbSliceByteLength, imageDesc.alphaSliceByteOffset, imageDesc.alphaSliceByteLength, imageDesc.imageFlags, hasAlpha, false, 0, 0); - assert(ok, 'THREE.BasisTextureLoader: transcodeImage() failed for level ' + level.index + '.'); - mipmaps.push({ - data: dst, - width: level.width, - height: level.height - }); - } - } finally { - transcoder.delete(); - } - } else { - for (let i = 0; i < taskConfig.levels.length; i++) { - const level = taskConfig.levels[i]; - const dstByteLength = getTranscodedImageByteLength(transcoderFormat, level.width, level.height); - const dst = new Uint8Array(dstByteLength); - const ok = BasisModule.transcodeUASTCImage(transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks(transcoderFormat, level.width), getHeightInBlocks(transcoderFormat, level.height), level.width, level.height, level.index, 0, level.data.byteLength, 0, hasAlpha, false, 0, 0, -1, -1); - assert(ok, 'THREE.BasisTextureLoader: transcodeUASTCImage() failed for level ' + level.index + '.'); - mipmaps.push({ - data: dst, - width: level.width, - height: level.height - }); - } - } + var _primaryChildFragment3 = workInProgress.child; + var prevOffscreenState = current.child.memoizedState; + _primaryChildFragment3.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes); + _primaryChildFragment3.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); + workInProgress.memoizedState = SUSPENDED_MARKER; + return _fallbackChildFragment; + } else { + var _nextPrimaryChildren3 = nextProps.children; - return { - width, - height, - hasAlpha, - mipmaps, - format: engineFormat - }; - } + var _primaryChildFragment4 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren3, renderLanes); - function transcode(buffer) { - const basisFile = new BasisModule.BasisFile(new Uint8Array(buffer)); - const basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; - const width = basisFile.getImageWidth(0, 0); - const height = basisFile.getImageHeight(0, 0); - const levels = basisFile.getNumLevels(0); - const hasAlpha = basisFile.getHasAlpha(); + workInProgress.memoizedState = null; + return _primaryChildFragment4; + } + } else { + // The current tree is not already showing a fallback. + if (showFallback) { + // Timed out. + var _nextFallbackChildren3 = nextProps.fallback; + var _nextPrimaryChildren4 = nextProps.children; - function cleanup() { - basisFile.close(); - basisFile.delete(); - } + var _fallbackChildFragment2 = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren4, _nextFallbackChildren3, renderLanes); - const { - transcoderFormat, - engineFormat - } = getTranscoderFormat(basisFormat, width, height, hasAlpha); + var _primaryChildFragment5 = workInProgress.child; + var _prevOffscreenState = current.child.memoizedState; + _primaryChildFragment5.memoizedState = _prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(_prevOffscreenState, renderLanes); + _primaryChildFragment5.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); // Skip the primary children, and continue working on the + // fallback children. - if (!width || !height || !levels) { - cleanup(); - throw new Error('THREE.BasisTextureLoader: Invalid texture'); - } + workInProgress.memoizedState = SUSPENDED_MARKER; + return _fallbackChildFragment2; + } else { + // Still haven't timed out. Continue rendering the children, like we + // normally do. + var _nextPrimaryChildren5 = nextProps.children; - if (!basisFile.startTranscoding()) { - cleanup(); - throw new Error('THREE.BasisTextureLoader: .startTranscoding failed'); - } + var _primaryChildFragment6 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren5, renderLanes); - const mipmaps = []; + workInProgress.memoizedState = null; + return _primaryChildFragment6; + } + } + } + } - for (let mip = 0; mip < levels; mip++) { - const mipWidth = basisFile.getImageWidth(0, mip); - const mipHeight = basisFile.getImageHeight(0, mip); - const dst = new Uint8Array(basisFile.getImageTranscodedSizeInBytes(0, mip, transcoderFormat)); - const status = basisFile.transcodeImage(dst, 0, mip, transcoderFormat, 0, hasAlpha); + function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) { + var mode = workInProgress.mode; + var primaryChildProps = { + mode: 'visible', + children: primaryChildren + }; + var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); + primaryChildFragment.return = workInProgress; + workInProgress.child = primaryChildFragment; + return primaryChildFragment; + } - if (!status) { - cleanup(); - throw new Error('THREE.BasisTextureLoader: .transcodeImage failed.'); - } + function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) { + var mode = workInProgress.mode; + var progressedPrimaryFragment = workInProgress.child; + var primaryChildProps = { + mode: 'hidden', + children: primaryChildren + }; + var primaryChildFragment; + var fallbackChildFragment; - mipmaps.push({ - data: dst, - width: mipWidth, - height: mipHeight - }); - } + if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) { + // In legacy mode, we commit the primary tree as if it successfully + // completed, even though it's in an inconsistent state. + primaryChildFragment = progressedPrimaryFragment; + primaryChildFragment.childLanes = NoLanes; + primaryChildFragment.pendingProps = primaryChildProps; - cleanup(); - return { - width, - height, - hasAlpha, - mipmaps, - format: engineFormat - }; - } // - // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC), - // device capabilities, and texture dimensions. The list below ranks the formats separately - // for ETC1S and UASTC. - // - // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at - // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently - // chooses RGBA32 only as a last resort and does not expose that option to the caller. - - - const FORMAT_OPTIONS = [{ - if: 'astcSupported', - basisFormat: [BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4], - engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format], - priorityETC1S: Infinity, - priorityUASTC: 1, - needsPowerOfTwo: false - }, { - if: 'bptcSupported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5], - engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format], - priorityETC1S: 3, - priorityUASTC: 2, - needsPowerOfTwo: false - }, { - if: 'dxtSupported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3], - engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format], - priorityETC1S: 4, - priorityUASTC: 5, - needsPowerOfTwo: false - }, { - if: 'etc2Supported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2], - engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format], - priorityETC1S: 1, - priorityUASTC: 3, - needsPowerOfTwo: false - }, { - if: 'etc1Supported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC1], - engineFormat: [EngineFormat.RGB_ETC1_Format, EngineFormat.RGB_ETC1_Format], - priorityETC1S: 2, - priorityUASTC: 4, - needsPowerOfTwo: false - }, { - if: 'pvrtcSupported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA], - engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format], - priorityETC1S: 5, - priorityUASTC: 6, - needsPowerOfTwo: true - }]; - const ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) { - return a.priorityETC1S - b.priorityETC1S; - }); - const UASTC_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) { - return a.priorityUASTC - b.priorityUASTC; - }); + if ( workInProgress.mode & ProfileMode) { + // Reset the durations from the first pass so they aren't included in the + // final amounts. This seems counterintuitive, since we're intentionally + // not measuring part of the render phase, but this makes it match what we + // do in Concurrent Mode. + primaryChildFragment.actualDuration = 0; + primaryChildFragment.actualStartTime = -1; + primaryChildFragment.selfBaseDuration = 0; + primaryChildFragment.treeBaseDuration = 0; + } - function getTranscoderFormat(basisFormat, width, height, hasAlpha) { - let transcoderFormat; - let engineFormat; - const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; - - for (let i = 0; i < options.length; i++) { - const opt = options[i]; - if (!config[opt.if]) continue; - if (!opt.basisFormat.includes(basisFormat)) continue; - if (opt.needsPowerOfTwo && !(isPowerOfTwo(width) && isPowerOfTwo(height))) continue; - transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0]; - engineFormat = opt.engineFormat[hasAlpha ? 1 : 0]; - return { - transcoderFormat, - engineFormat - }; - } + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); + } else { + primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); + } - console.warn('THREE.BasisTextureLoader: No suitable compressed texture format found. Decoding to RGBA32.'); - transcoderFormat = TranscoderFormat.RGBA32; - engineFormat = EngineFormat.RGBAFormat; - return { - transcoderFormat, - engineFormat - }; - } + primaryChildFragment.return = workInProgress; + fallbackChildFragment.return = workInProgress; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress.child = primaryChildFragment; + return fallbackChildFragment; + } - function assert(ok, message) { - if (!ok) throw new Error(message); - } + function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) { + // The props argument to `createFiberFromOffscreen` is `any` typed, so we use + // this wrapper function to constrain it. + return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); + } - function getWidthInBlocks(transcoderFormat, width) { - return Math.ceil(width / BasisModule.getFormatBlockWidth(transcoderFormat)); - } + function updateWorkInProgressOffscreenFiber(current, offscreenProps) { + // The props argument to `createWorkInProgress` is `any` typed, so we use this + // wrapper function to constrain it. + return createWorkInProgress(current, offscreenProps); + } - function getHeightInBlocks(transcoderFormat, height) { - return Math.ceil(height / BasisModule.getFormatBlockHeight(transcoderFormat)); - } + function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) { + var currentPrimaryChildFragment = current.child; + var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, { + mode: 'visible', + children: primaryChildren + }); - function getTranscodedImageByteLength(transcoderFormat, width, height) { - const blockByteLength = BasisModule.getBytesPerBlockOrPixel(transcoderFormat); + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + primaryChildFragment.lanes = renderLanes; + } - if (BasisModule.formatIsUncompressed(transcoderFormat)) { - return width * height * blockByteLength; - } + primaryChildFragment.return = workInProgress; + primaryChildFragment.sibling = null; - if (transcoderFormat === TranscoderFormat.PVRTC1_4_RGB || transcoderFormat === TranscoderFormat.PVRTC1_4_RGBA) { - // GL requires extra padding for very small textures: - // https://www.khronos.org/registry/OpenGL/extensions/IMG/IMG_texture_compression_pvrtc.txt - const paddedWidth = width + 3 & ~3; - const paddedHeight = height + 3 & ~3; - return (Math.max(8, paddedWidth) * Math.max(8, paddedHeight) * 4 + 7) / 8; - } + if (currentFallbackChildFragment !== null) { + // Delete the fallback child fragment + var deletions = workInProgress.deletions; - return getWidthInBlocks(transcoderFormat, width) * getHeightInBlocks(transcoderFormat, height) * blockByteLength; - } + if (deletions === null) { + workInProgress.deletions = [currentFallbackChildFragment]; + workInProgress.flags |= ChildDeletion; + } else { + deletions.push(currentFallbackChildFragment); + } + } - function isPowerOfTwo(value) { - if (value <= 2) return true; - return (value & value - 1) === 0 && value !== 0; - } -}; + workInProgress.child = primaryChildFragment; + return primaryChildFragment; + } -var n$2,i$2,s$1,a$1,r$1,o$1,l$1,f$1;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB";}(n$2||(n$2={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT";}(i$2||(i$2={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC";}(s$1||(s$1={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB";}(a$1||(a$1={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2";}(r$1||(r$1={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED";}(o$1||(o$1={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA";}(l$1||(l$1={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG";}(f$1||(f$1={})); + function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { + var mode = workInProgress.mode; + var currentPrimaryChildFragment = current.child; + var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + var primaryChildProps = { + mode: 'hidden', + children: primaryChildren + }; + var primaryChildFragment; -/** - * https://opentype.js.org v1.3.4 | (c) Frederik De Bleser and other contributors | MIT License | Uses tiny-inflate by Devon Govett and string.prototype.codepointat polyfill by Mathias Bynens - */ + if ( // In legacy mode, we commit the primary tree as if it successfully + // completed, even though it's in an inconsistent state. + (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was + // already cloned. In legacy mode, the only case where this isn't true is + // when DevTools forces us to display a fallback; we skip the first render + // pass entirely and go straight to rendering the fallback. (In Concurrent + // Mode, SuspenseList can also trigger this scenario, but this is a legacy- + // only codepath.) + workInProgress.child !== currentPrimaryChildFragment) { + var progressedPrimaryFragment = workInProgress.child; + primaryChildFragment = progressedPrimaryFragment; + primaryChildFragment.childLanes = NoLanes; + primaryChildFragment.pendingProps = primaryChildProps; -/*! https://mths.be/codepointat v0.2.0 by @mathias */ -if (!String.prototype.codePointAt) { - (function() { - var defineProperty = (function() { - // IE 8 only supports `Object.defineProperty` on DOM elements - try { - var object = {}; - var $defineProperty = Object.defineProperty; - var result = $defineProperty(object, object, object) && $defineProperty; - } catch(error) {} - return result; - }()); - var codePointAt = function(position) { - if (this == null) { - throw TypeError(); - } - var string = String(this); - var size = string.length; - // `ToInteger` - var index = position ? Number(position) : 0; - if (index != index) { // better `isNaN` - index = 0; - } - // Account for out-of-bounds indices: - if (index < 0 || index >= size) { - return undefined; - } - // Get the first code unit - var first = string.charCodeAt(index); - var second; - if ( // check if it’s the start of a surrogate pair - first >= 0xD800 && first <= 0xDBFF && // high surrogate - size > index + 1 // there is a next code unit - ) { - second = string.charCodeAt(index + 1); - if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - } - } - return first; - }; - if (defineProperty) { - defineProperty(String.prototype, 'codePointAt', { - 'value': codePointAt, - 'configurable': true, - 'writable': true - }); - } else { - String.prototype.codePointAt = codePointAt; - } - }()); -} + if ( workInProgress.mode & ProfileMode) { + // Reset the durations from the first pass so they aren't included in the + // final amounts. This seems counterintuitive, since we're intentionally + // not measuring part of the render phase, but this makes it match what we + // do in Concurrent Mode. + primaryChildFragment.actualDuration = 0; + primaryChildFragment.actualStartTime = -1; + primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; + primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; + } + // However, since we're going to remain on the fallback, we no longer want + // to delete it. -function Tree$1() { - this.table = new Uint16Array(16); /* table of code length counts */ - this.trans = new Uint16Array(288); /* code -> symbol translation table */ -} -/* --------------------------------------------------- * - * -- uninitialized global data (static structures) -- * - * --------------------------------------------------- */ + workInProgress.deletions = null; + } else { + primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); + // (We don't do this in legacy mode, because in legacy mode we don't re-use + // the current tree; see previous branch.) + -var sltree = new Tree$1(); -var sdtree = new Tree$1(); + primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; + } -/* extra bits and base tables for length codes */ -var length_bits = new Uint8Array(30); -var length_base = new Uint16Array(30); + var fallbackChildFragment; -/* extra bits and base tables for distance codes */ -var dist_bits = new Uint8Array(30); -var dist_base = new Uint16Array(30); + if (currentFallbackChildFragment !== null) { + fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren); + } else { + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already + // mounted but this is a new fiber. -/* used by tinf_decode_trees, avoids allocations every call */ -new Tree$1(); + fallbackChildFragment.flags |= Placement; + } -/* ----------------------- * - * -- utility functions -- * - * ----------------------- */ + fallbackChildFragment.return = workInProgress; + primaryChildFragment.return = workInProgress; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress.child = primaryChildFragment; + return fallbackChildFragment; + } -/* build extra bits and base tables */ -function tinf_build_bits_base(bits, base, delta, first) { - var i, sum; + function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) { + // Falling back to client rendering. Because this has performance + // implications, it's considered a recoverable error, even though the user + // likely won't observe anything wrong with the UI. + // + // The error is passed in as an argument to enforce that every caller provide + // a custom message, or explicitly opt out (currently the only path that opts + // out is legacy mode; every concurrent path provides an error). + if (recoverableError !== null) { + queueHydrationError(recoverableError); + } // This will add the old fiber to the deletion list - /* build bits table */ - for (i = 0; i < delta; ++i) { bits[i] = 0; } - for (i = 0; i < 30 - delta; ++i) { bits[i + delta] = i / delta | 0; } - /* build base table */ - for (sum = first, i = 0; i < 30; ++i) { - base[i] = sum; - sum += 1 << bits[i]; - } -} + reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated. -/* build the fixed huffman trees */ -function tinf_build_fixed_trees(lt, dt) { - var i; + var nextProps = workInProgress.pendingProps; + var primaryChildren = nextProps.children; + var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already + // mounted but this is a new fiber. - /* build fixed length tree */ - for (i = 0; i < 7; ++i) { lt.table[i] = 0; } + primaryChildFragment.flags |= Placement; + workInProgress.memoizedState = null; + return primaryChildFragment; + } - lt.table[7] = 24; - lt.table[8] = 152; - lt.table[9] = 112; + function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { + var fiberMode = workInProgress.mode; + var primaryChildProps = { + mode: 'visible', + children: primaryChildren + }; + var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode); + var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense + // boundary) already mounted but this is a new fiber. - for (i = 0; i < 24; ++i) { lt.trans[i] = 256 + i; } - for (i = 0; i < 144; ++i) { lt.trans[24 + i] = i; } - for (i = 0; i < 8; ++i) { lt.trans[24 + 144 + i] = 280 + i; } - for (i = 0; i < 112; ++i) { lt.trans[24 + 144 + 8 + i] = 144 + i; } + fallbackChildFragment.flags |= Placement; + primaryChildFragment.return = workInProgress; + fallbackChildFragment.return = workInProgress; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress.child = primaryChildFragment; - /* build fixed distance tree */ - for (i = 0; i < 5; ++i) { dt.table[i] = 0; } + if ((workInProgress.mode & ConcurrentMode) !== NoMode) { + // We will have dropped the effect list which contains the + // deletion. We need to reconcile to delete the current child. + reconcileChildFibers(workInProgress, current.child, null, renderLanes); + } - dt.table[5] = 32; + return fallbackChildFragment; + } - for (i = 0; i < 32; ++i) { dt.trans[i] = i; } -} + function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) { + // During the first pass, we'll bail out and not drill into the children. + // Instead, we'll leave the content in place and try to hydrate it later. + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + { + error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, )' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.'); + } -/* -------------------- * - * -- initialization -- * - * -------------------- */ + workInProgress.lanes = laneToLanes(SyncLane); + } else if (isSuspenseInstanceFallback(suspenseInstance)) { + // This is a client-only boundary. Since we won't get any content from the server + // for this, we need to schedule that at a higher priority based on when it would + // have timed out. In theory we could render it in this pass but it would have the + // wrong priority associated with it and will prevent hydration of parent path. + // Instead, we'll leave work left on it to render it in a separate commit. + // TODO This time should be the time at which the server rendered response that is + // a parent to this boundary was displayed. However, since we currently don't have + // a protocol to transfer that time, we'll just estimate it by using the current + // time. This will mean that Suspense timeouts are slightly shifted to later than + // they should be. + // Schedule a normal pri update to render this content. + workInProgress.lanes = laneToLanes(DefaultHydrationLane); + } else { + // We'll continue hydrating the rest at offscreen priority since we'll already + // be showing the right content coming from the server, it is no rush. + workInProgress.lanes = laneToLanes(OffscreenLane); + } -/* build fixed huffman trees */ -tinf_build_fixed_trees(sltree, sdtree); + return null; + } -/* build extra bits and base tables */ -tinf_build_bits_base(length_bits, length_base, 4, 3); -tinf_build_bits_base(dist_bits, dist_base, 2, 1); + function updateDehydratedSuspenseComponent(current, workInProgress, suspenseInstance, suspenseState, renderLanes) { + // We should never be hydrating at this point because it is the first pass, + // but after we've already committed once. + warnIfHydrating(); -/* fix a special case */ -length_bits[28] = 0; -length_base[28] = 258; + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument + // required — every concurrent mode path that causes hydration to + // de-opt to client rendering should have an error message. + null); + } -// The Bounding Box object + if (isSuspenseInstanceFallback(suspenseInstance)) { + // This boundary is in a permanent fallback state. In this case, we'll never + // get an update and we'll never be able to hydrate the final content. Let's just try the + // client side render instead. + return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: The server should serialize the error message so we can log it + // here on the client. Or, in production, a hash/id that corresponds to + // the error. + new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.')); + } + // any context has changed, we need to treat is as if the input might have changed. -function derive(v0, v1, v2, v3, t) { - return Math.pow(1 - t, 3) * v0 + - 3 * Math.pow(1 - t, 2) * t * v1 + - 3 * (1 - t) * Math.pow(t, 2) * v2 + - Math.pow(t, 3) * v3; -} -/** - * A bounding box is an enclosing box that describes the smallest measure within which all the points lie. - * It is used to calculate the bounding box of a glyph or text path. - * - * On initialization, x1/y1/x2/y2 will be NaN. Check if the bounding box is empty using `isEmpty()`. - * - * @exports opentype.BoundingBox - * @class - * @constructor - */ -function BoundingBox() { - this.x1 = Number.NaN; - this.y1 = Number.NaN; - this.x2 = Number.NaN; - this.y2 = Number.NaN; -} -/** - * Returns true if the bounding box is empty, that is, no points have been added to the box yet. - */ -BoundingBox.prototype.isEmpty = function() { - return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2); -}; + var hasContextChanged = includesSomeLane(renderLanes, current.childLanes); -/** - * Add the point to the bounding box. - * The x1/y1/x2/y2 coordinates of the bounding box will now encompass the given point. - * @param {number} x - The X coordinate of the point. - * @param {number} y - The Y coordinate of the point. - */ -BoundingBox.prototype.addPoint = function(x, y) { - if (typeof x === 'number') { - if (isNaN(this.x1) || isNaN(this.x2)) { - this.x1 = x; - this.x2 = x; - } - if (x < this.x1) { - this.x1 = x; - } - if (x > this.x2) { - this.x2 = x; - } - } - if (typeof y === 'number') { - if (isNaN(this.y1) || isNaN(this.y2)) { - this.y1 = y; - this.y2 = y; - } - if (y < this.y1) { - this.y1 = y; - } - if (y > this.y2) { - this.y2 = y; - } - } -}; + if (didReceiveUpdate || hasContextChanged) { + // This boundary has changed since the first render. This means that we are now unable to + // hydrate it. We might still be able to hydrate it using a higher priority lane. + var root = getWorkInProgressRoot(); -/** - * Add a X coordinate to the bounding box. - * This extends the bounding box to include the X coordinate. - * This function is used internally inside of addBezier. - * @param {number} x - The X coordinate of the point. - */ -BoundingBox.prototype.addX = function(x) { - this.addPoint(x, null); -}; + if (root !== null) { + var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes); -/** - * Add a Y coordinate to the bounding box. - * This extends the bounding box to include the Y coordinate. - * This function is used internally inside of addBezier. - * @param {number} y - The Y coordinate of the point. - */ -BoundingBox.prototype.addY = function(y) { - this.addPoint(null, y); -}; + if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) { + // Intentionally mutating since this render will get interrupted. This + // is one of the very rare times where we mutate the current tree + // during the render phase. + suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render -/** - * Add a Bézier curve to the bounding box. - * This extends the bounding box to include the entire Bézier. - * @param {number} x0 - The starting X coordinate. - * @param {number} y0 - The starting Y coordinate. - * @param {number} x1 - The X coordinate of the first control point. - * @param {number} y1 - The Y coordinate of the first control point. - * @param {number} x2 - The X coordinate of the second control point. - * @param {number} y2 - The Y coordinate of the second control point. - * @param {number} x - The ending X coordinate. - * @param {number} y - The ending Y coordinate. - */ -BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x, y) { - // This code is based on http://nishiohirokazu.blogspot.com/2009/06/how-to-calculate-bezier-curves-bounding.html - // and https://github.com/icons8/svg-path-bounding-box - - var p0 = [x0, y0]; - var p1 = [x1, y1]; - var p2 = [x2, y2]; - var p3 = [x, y]; - - this.addPoint(x0, y0); - this.addPoint(x, y); - - for (var i = 0; i <= 1; i++) { - var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; - var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; - var c = 3 * p1[i] - 3 * p0[i]; - - if (a === 0) { - if (b === 0) { continue; } - var t = -c / b; - if (0 < t && t < 1) { - if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t)); } - if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t)); } - } - continue; - } + var eventTime = NoTimestamp; + scheduleUpdateOnFiber(current, attemptHydrationAtLane, eventTime); + } + } // If we have scheduled higher pri work above, this will probably just abort the render + // since we now have higher priority work, but in case it doesn't, we need to prepare to + // render something, if we time out. Even if that requires us to delete everything and + // skip hydration. + // Delay having to do this as long as the suspense timeout allows us. - var b2ac = Math.pow(b, 2) - 4 * c * a; - if (b2ac < 0) { continue; } - var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); - if (0 < t1 && t1 < 1) { - if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); } - if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); } - } - var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); - if (0 < t2 && t2 < 1) { - if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); } - if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); } - } - } -}; -/** - * Add a quadratic curve to the bounding box. - * This extends the bounding box to include the entire quadratic curve. - * @param {number} x0 - The starting X coordinate. - * @param {number} y0 - The starting Y coordinate. - * @param {number} x1 - The X coordinate of the control point. - * @param {number} y1 - The Y coordinate of the control point. - * @param {number} x - The ending X coordinate. - * @param {number} y - The ending Y coordinate. - */ -BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x, y) { - var cp1x = x0 + 2 / 3 * (x1 - x0); - var cp1y = y0 + 2 / 3 * (y1 - y0); - var cp2x = cp1x + 1 / 3 * (x - x0); - var cp2y = cp1y + 1 / 3 * (y - y0); - this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y); -}; + renderDidSuspendDelayIfPossible(); + return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.')); + } else if (isSuspenseInstancePending(suspenseInstance)) { + // This component is still pending more data from the server, so we can't hydrate its + // content. We treat it as if this component suspended itself. It might seem as if + // we could just try to render it client-side instead. However, this will perform a + // lot of unnecessary work and is unlikely to complete since it often will suspend + // on missing data anyway. Additionally, the server might be able to render more + // than we can on the client yet. In that case we'd end up with more fallback states + // on the client than if we just leave it alone. If the server times out or errors + // these should update this boundary to the permanent Fallback state instead. + // Mark it as having captured (i.e. suspended). + workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. -// Geometric objects + workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result. -/** - * A bézier path containing a set of path commands similar to a SVG path. - * Paths can be drawn on a context using `draw`. - * @exports opentype.Path - * @class - * @constructor - */ -function Path() { - this.commands = []; - this.fill = 'black'; - this.stroke = null; - this.strokeWidth = 1; -} + var retry = retryDehydratedSuspenseBoundary.bind(null, current); + registerSuspenseInstanceRetry(suspenseInstance, retry); + return null; + } else { + // This is the first attempt. + reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext); + var nextProps = workInProgress.pendingProps; + var primaryChildren = nextProps.children; + var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. -/** - * @param {number} x - * @param {number} y - */ -Path.prototype.moveTo = function(x, y) { - this.commands.push({ - type: 'M', - x: x, - y: y - }); -}; + primaryChildFragment.flags |= Hydrating; + return primaryChildFragment; + } + } -/** - * @param {number} x - * @param {number} y - */ -Path.prototype.lineTo = function(x, y) { - this.commands.push({ - type: 'L', - x: x, - y: y - }); -}; + function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) { + fiber.lanes = mergeLanes(fiber.lanes, renderLanes); + var alternate = fiber.alternate; -/** - * Draws cubic curve - * @function - * curveTo - * @memberof opentype.Path.prototype - * @param {number} x1 - x of control 1 - * @param {number} y1 - y of control 1 - * @param {number} x2 - x of control 2 - * @param {number} y2 - y of control 2 - * @param {number} x - x of path point - * @param {number} y - y of path point - */ + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, renderLanes); + } -/** - * Draws cubic curve - * @function - * bezierCurveTo - * @memberof opentype.Path.prototype - * @param {number} x1 - x of control 1 - * @param {number} y1 - y of control 1 - * @param {number} x2 - x of control 2 - * @param {number} y2 - y of control 2 - * @param {number} x - x of path point - * @param {number} y - y of path point - * @see curveTo - */ -Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) { - this.commands.push({ - type: 'C', - x1: x1, - y1: y1, - x2: x2, - y2: y2, - x: x, - y: y - }); -}; + scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot); + } -/** - * Draws quadratic curve - * @function - * quadraticCurveTo - * @memberof opentype.Path.prototype - * @param {number} x1 - x of control - * @param {number} y1 - y of control - * @param {number} x - x of path point - * @param {number} y - y of path point - */ + function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) { + // Mark any Suspense boundaries with fallbacks as having work to do. + // If they were previously forced into fallbacks, they may now be able + // to unblock. + var node = firstChild; -/** - * Draws quadratic curve - * @function - * quadTo - * @memberof opentype.Path.prototype - * @param {number} x1 - x of control - * @param {number} y1 - y of control - * @param {number} x - x of path point - * @param {number} y - y of path point - */ -Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) { - this.commands.push({ - type: 'Q', - x1: x1, - y1: y1, - x: x, - y: y - }); -}; + while (node !== null) { + if (node.tag === SuspenseComponent) { + var state = node.memoizedState; -/** - * Closes the path - * @function closePath - * @memberof opentype.Path.prototype - */ + if (state !== null) { + scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); + } + } else if (node.tag === SuspenseListComponent) { + // If the tail is hidden there might not be an Suspense boundaries + // to schedule work on. In this case we have to schedule it on the + // list itself. + // We don't have to traverse to the children of the list since + // the list will propagate the change when it rerenders. + scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } -/** - * Close the path - * @function close - * @memberof opentype.Path.prototype - */ -Path.prototype.close = Path.prototype.closePath = function() { - this.commands.push({ - type: 'Z' - }); -}; + if (node === workInProgress) { + return; + } -/** - * Add the given path or list of commands to the commands of this path. - * @param {Array} pathOrCommands - another opentype.Path, an opentype.BoundingBox, or an array of commands. - */ -Path.prototype.extend = function(pathOrCommands) { - if (pathOrCommands.commands) { - pathOrCommands = pathOrCommands.commands; - } else if (pathOrCommands instanceof BoundingBox) { - var box = pathOrCommands; - this.moveTo(box.x1, box.y1); - this.lineTo(box.x2, box.y1); - this.lineTo(box.x2, box.y2); - this.lineTo(box.x1, box.y2); - this.close(); - return; - } + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress) { + return; + } - Array.prototype.push.apply(this.commands, pathOrCommands); -}; + node = node.return; + } -/** - * Calculate the bounding box of the path. - * @returns {opentype.BoundingBox} - */ -Path.prototype.getBoundingBox = function() { - var box = new BoundingBox(); - - var startX = 0; - var startY = 0; - var prevX = 0; - var prevY = 0; - for (var i = 0; i < this.commands.length; i++) { - var cmd = this.commands[i]; - switch (cmd.type) { - case 'M': - box.addPoint(cmd.x, cmd.y); - startX = prevX = cmd.x; - startY = prevY = cmd.y; - break; - case 'L': - box.addPoint(cmd.x, cmd.y); - prevX = cmd.x; - prevY = cmd.y; - break; - case 'Q': - box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y); - prevX = cmd.x; - prevY = cmd.y; - break; - case 'C': - box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); - prevX = cmd.x; - prevY = cmd.y; - break; - case 'Z': - prevX = startX; - prevY = startY; - break; - default: - throw new Error('Unexpected path command ' + cmd.type); - } - } - if (box.isEmpty()) { - box.addPoint(0, 0); - } - return box; -}; + node.sibling.return = node.return; + node = node.sibling; + } + } -/** - * Draw the path to a 2D context. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context. - */ -Path.prototype.draw = function(ctx) { - ctx.beginPath(); - for (var i = 0; i < this.commands.length; i += 1) { - var cmd = this.commands[i]; - if (cmd.type === 'M') { - ctx.moveTo(cmd.x, cmd.y); - } else if (cmd.type === 'L') { - ctx.lineTo(cmd.x, cmd.y); - } else if (cmd.type === 'C') { - ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); - } else if (cmd.type === 'Q') { - ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); - } else if (cmd.type === 'Z') { - ctx.closePath(); - } - } + function findLastContentRow(firstChild) { + // This is going to find the last row among these children that is already + // showing content on the screen, as opposed to being in fallback state or + // new. If a row has multiple Suspense boundaries, any of them being in the + // fallback state, counts as the whole row being in a fallback state. + // Note that the "rows" will be workInProgress, but any nested children + // will still be current since we haven't rendered them yet. The mounted + // order may not be the same as the new order. We use the new order. + var row = firstChild; + var lastContentRow = null; - if (this.fill) { - ctx.fillStyle = this.fill; - ctx.fill(); - } + while (row !== null) { + var currentRow = row.alternate; // New rows can't be content rows. - if (this.stroke) { - ctx.strokeStyle = this.stroke; - ctx.lineWidth = this.strokeWidth; - ctx.stroke(); - } -}; + if (currentRow !== null && findFirstSuspended(currentRow) === null) { + lastContentRow = row; + } -/** - * Convert the Path to a string of path data instructions - * See http://www.w3.org/TR/SVG/paths.html#PathData - * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values - * @return {string} - */ -Path.prototype.toPathData = function(decimalPlaces) { - decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; + row = row.sibling; + } - function floatToString(v) { - if (Math.round(v) === v) { - return '' + Math.round(v); - } else { - return v.toFixed(decimalPlaces); - } - } + return lastContentRow; + } - function packValues() { - var arguments$1 = arguments; + function validateRevealOrder(revealOrder) { + { + if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) { + didWarnAboutRevealOrder[revealOrder] = true; - var s = ''; - for (var i = 0; i < arguments.length; i += 1) { - var v = arguments$1[i]; - if (v >= 0 && i > 0) { - s += ' '; - } + if (typeof revealOrder === 'string') { + switch (revealOrder.toLowerCase()) { + case 'together': + case 'forwards': + case 'backwards': + { + error('"%s" is not a valid value for revealOrder on . ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase()); - s += floatToString(v); - } + break; + } - return s; - } + case 'forward': + case 'backward': + { + error('"%s" is not a valid value for revealOrder on . ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase()); - var d = ''; - for (var i = 0; i < this.commands.length; i += 1) { - var cmd = this.commands[i]; - if (cmd.type === 'M') { - d += 'M' + packValues(cmd.x, cmd.y); - } else if (cmd.type === 'L') { - d += 'L' + packValues(cmd.x, cmd.y); - } else if (cmd.type === 'C') { - d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); - } else if (cmd.type === 'Q') { - d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); - } else if (cmd.type === 'Z') { - d += 'Z'; - } - } + break; + } - return d; -}; + default: + error('"%s" is not a supported revealOrder on . ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); -/** - * Convert the path to an SVG element, as a string. - * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values - * @return {string} - */ -Path.prototype.toSVG = function(decimalPlaces) { - var svg = '. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); + } + } + } + } - if (this.stroke) { - svg += ' stroke="' + this.stroke + '" stroke-width="' + this.strokeWidth + '"'; - } + function validateTailOptions(tailMode, revealOrder) { + { + if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) { + if (tailMode !== 'collapsed' && tailMode !== 'hidden') { + didWarnAboutTailOptions[tailMode] = true; - svg += '/>'; - return svg; -}; + error('"%s" is not a supported value for tail on . ' + 'Did you mean "collapsed" or "hidden"?', tailMode); + } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') { + didWarnAboutTailOptions[tailMode] = true; -/** - * Convert the path to a DOM element. - * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values - * @return {SVGPathElement} - */ -Path.prototype.toDOMElement = function(decimalPlaces) { - var temporaryPath = this.toPathData(decimalPlaces); - var newPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + error(' is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode); + } + } + } + } - newPath.setAttribute('d', temporaryPath); + function validateSuspenseListNestedChild(childSlot, index) { + { + var isAnArray = isArray(childSlot); + var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function'; - return newPath; -}; + if (isAnArray || isIterable) { + var type = isAnArray ? 'array' : 'iterable'; -// Run-time checking of preconditions. + error('A nested %s was passed to row #%s in . Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + ' ... ' + '{%s} ... ' + '', type, index, type); -function fail(message) { - throw new Error(message); -} + return false; + } + } -// Precondition function that checks if the given predicate is true. -// If not, it will throw an error. -function argument(predicate, message) { - if (!predicate) { - fail(message); - } -} -var check = { fail: fail, argument: argument, assert: argument }; + return true; + } -// Data types used in the OpenType font file. + function validateSuspenseListChildren(children, revealOrder) { + { + if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) { + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + if (!validateSuspenseListNestedChild(children[i], i)) { + return; + } + } + } else { + var iteratorFn = getIteratorFn(children); -var LIMIT16 = 32768; // The limit at which a 16-bit number switches signs == 2^15 -var LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31 + if (typeof iteratorFn === 'function') { + var childrenIterator = iteratorFn.call(children); -/** - * @exports opentype.decode - * @class - */ -var decode = {}; -/** - * @exports opentype.encode - * @class - */ -var encode = {}; -/** - * @exports opentype.sizeOf - * @class - */ -var sizeOf = {}; + if (childrenIterator) { + var step = childrenIterator.next(); + var _i = 0; -// Return a function that always returns the same value. -function constant(v) { - return function() { - return v; - }; -} + for (; !step.done; step = childrenIterator.next()) { + if (!validateSuspenseListNestedChild(step.value, _i)) { + return; + } -// OpenType data types ////////////////////////////////////////////////////// + _i++; + } + } + } else { + error('A single row was passed to a . ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder); + } + } + } + } + } -/** - * Convert an 8-bit unsigned integer to a list of 1 byte. - * @param {number} - * @returns {Array} - */ -encode.BYTE = function(v) { - check.argument(v >= 0 && v <= 255, 'Byte value should be between 0 and 255.'); - return [v]; -}; -/** - * @constant - * @type {number} - */ -sizeOf.BYTE = constant(1); + function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) { + var renderState = workInProgress.memoizedState; -/** - * Convert a 8-bit signed integer to a list of 1 byte. - * @param {string} - * @returns {Array} - */ -encode.CHAR = function(v) { - return [v.charCodeAt(0)]; -}; + if (renderState === null) { + workInProgress.memoizedState = { + isBackwards: isBackwards, + rendering: null, + renderingStartTime: 0, + last: lastContentRow, + tail: tail, + tailMode: tailMode + }; + } else { + // We can reuse the existing object from previous renders. + renderState.isBackwards = isBackwards; + renderState.rendering = null; + renderState.renderingStartTime = 0; + renderState.last = lastContentRow; + renderState.tail = tail; + renderState.tailMode = tailMode; + } + } // This can end up rendering this component multiple passes. + // The first pass splits the children fibers into two sets. A head and tail. + // We first render the head. If anything is in fallback state, we do another + // pass through beginWork to rerender all children (including the tail) with + // the force suspend context. If the first render didn't have anything in + // in fallback state. Then we render each row in the tail one-by-one. + // That happens in the completeWork phase without going back to beginWork. -/** - * @constant - * @type {number} - */ -sizeOf.CHAR = constant(1); -/** - * Convert an ASCII string to a list of bytes. - * @param {string} - * @returns {Array} - */ -encode.CHARARRAY = function(v) { - if (typeof v === 'undefined') { - v = ''; - console.warn('Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name.'); - } - var b = []; - for (var i = 0; i < v.length; i += 1) { - b[i] = v.charCodeAt(i); - } + function updateSuspenseListComponent(current, workInProgress, renderLanes) { + var nextProps = workInProgress.pendingProps; + var revealOrder = nextProps.revealOrder; + var tailMode = nextProps.tail; + var newChildren = nextProps.children; + validateRevealOrder(revealOrder); + validateTailOptions(tailMode, revealOrder); + validateSuspenseListChildren(newChildren, revealOrder); + reconcileChildren(current, workInProgress, newChildren, renderLanes); + var suspenseContext = suspenseStackCursor.current; + var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback); - return b; -}; + if (shouldForceFallback) { + suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); + workInProgress.flags |= DidCapture; + } else { + var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags; -/** - * @param {Array} - * @returns {number} - */ -sizeOf.CHARARRAY = function(v) { - if (typeof v === 'undefined') { - return 0; - } - return v.length; -}; + if (didSuspendBefore) { + // If we previously forced a fallback, we need to schedule work + // on any nested boundaries to let them know to try to render + // again. This is the same as context updating. + propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes); + } -/** - * Convert a 16-bit unsigned integer to a list of 2 bytes. - * @param {number} - * @returns {Array} - */ -encode.USHORT = function(v) { - return [(v >> 8) & 0xFF, v & 0xFF]; -}; + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + } -/** - * @constant - * @type {number} - */ -sizeOf.USHORT = constant(2); + pushSuspenseContext(workInProgress, suspenseContext); -/** - * Convert a 16-bit signed integer to a list of 2 bytes. - * @param {number} - * @returns {Array} - */ -encode.SHORT = function(v) { - // Two's complement - if (v >= LIMIT16) { - v = -(2 * LIMIT16 - v); - } + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + // In legacy mode, SuspenseList doesn't work so we just + // use make it a noop by treating it as the default revealOrder. + workInProgress.memoizedState = null; + } else { + switch (revealOrder) { + case 'forwards': + { + var lastContentRow = findLastContentRow(workInProgress.child); + var tail; - return [(v >> 8) & 0xFF, v & 0xFF]; -}; + if (lastContentRow === null) { + // The whole list is part of the tail. + // TODO: We could fast path by just rendering the tail now. + tail = workInProgress.child; + workInProgress.child = null; + } else { + // Disconnect the tail rows after the content row. + // We're going to render them separately later. + tail = lastContentRow.sibling; + lastContentRow.sibling = null; + } -/** - * @constant - * @type {number} - */ -sizeOf.SHORT = constant(2); + initSuspenseListRenderState(workInProgress, false, // isBackwards + tail, lastContentRow, tailMode); + break; + } -/** - * Convert a 24-bit unsigned integer to a list of 3 bytes. - * @param {number} - * @returns {Array} - */ -encode.UINT24 = function(v) { - return [(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + case 'backwards': + { + // We're going to find the first row that has existing content. + // At the same time we're going to reverse the list of everything + // we pass in the meantime. That's going to be our tail in reverse + // order. + var _tail = null; + var row = workInProgress.child; + workInProgress.child = null; -/** - * @constant - * @type {number} - */ -sizeOf.UINT24 = constant(3); + while (row !== null) { + var currentRow = row.alternate; // New rows can't be content rows. -/** - * Convert a 32-bit unsigned integer to a list of 4 bytes. - * @param {number} - * @returns {Array} - */ -encode.ULONG = function(v) { - return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + if (currentRow !== null && findFirstSuspended(currentRow) === null) { + // This is the beginning of the main content. + workInProgress.child = row; + break; + } -/** - * @constant - * @type {number} - */ -sizeOf.ULONG = constant(4); + var nextRow = row.sibling; + row.sibling = _tail; + _tail = row; + row = nextRow; + } // TODO: If workInProgress.child is null, we can continue on the tail immediately. -/** - * Convert a 32-bit unsigned integer to a list of 4 bytes. - * @param {number} - * @returns {Array} - */ -encode.LONG = function(v) { - // Two's complement - if (v >= LIMIT32) { - v = -(2 * LIMIT32 - v); - } - return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + initSuspenseListRenderState(workInProgress, true, // isBackwards + _tail, null, // last + tailMode); + break; + } -/** - * @constant - * @type {number} - */ -sizeOf.LONG = constant(4); + case 'together': + { + initSuspenseListRenderState(workInProgress, false, // isBackwards + null, // tail + null, // last + undefined); + break; + } -encode.FIXED = encode.ULONG; -sizeOf.FIXED = sizeOf.ULONG; + default: + { + // The default reveal order is the same as not having + // a boundary. + workInProgress.memoizedState = null; + } + } + } -encode.FWORD = encode.SHORT; -sizeOf.FWORD = sizeOf.SHORT; + return workInProgress.child; + } -encode.UFWORD = encode.USHORT; -sizeOf.UFWORD = sizeOf.USHORT; + function updatePortalComponent(current, workInProgress, renderLanes) { + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + var nextChildren = workInProgress.pendingProps; -/** - * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp. - * @param {number} - * @returns {Array} - */ -encode.LONGDATETIME = function(v) { - return [0, 0, 0, 0, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + if (current === null) { + // Portals are special because we don't append the children during mount + // but at commit. Therefore we need to track insertions which the normal + // flow doesn't do during mount. This doesn't happen at the root because + // the root always starts with a "current" with a null child. + // TODO: Consider unifying this with how the root works. + workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); + } else { + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + } -/** - * @constant - * @type {number} - */ -sizeOf.LONGDATETIME = constant(8); + return workInProgress.child; + } -/** - * Convert a 4-char tag to a list of 4 bytes. - * @param {string} - * @returns {Array} - */ -encode.TAG = function(v) { - check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.'); - return [v.charCodeAt(0), - v.charCodeAt(1), - v.charCodeAt(2), - v.charCodeAt(3)]; -}; + var hasWarnedAboutUsingNoValuePropOnContextProvider = false; -/** - * @constant - * @type {number} - */ -sizeOf.TAG = constant(4); + function updateContextProvider(current, workInProgress, renderLanes) { + var providerType = workInProgress.type; + var context = providerType._context; + var newProps = workInProgress.pendingProps; + var oldProps = workInProgress.memoizedProps; + var newValue = newProps.value; -// CFF data types /////////////////////////////////////////////////////////// + { + if (!('value' in newProps)) { + if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { + hasWarnedAboutUsingNoValuePropOnContextProvider = true; -encode.Card8 = encode.BYTE; -sizeOf.Card8 = sizeOf.BYTE; + error('The `value` prop is required for the ``. Did you misspell it or forget to pass it?'); + } + } -encode.Card16 = encode.USHORT; -sizeOf.Card16 = sizeOf.USHORT; + var providerPropTypes = workInProgress.type.propTypes; -encode.OffSize = encode.BYTE; -sizeOf.OffSize = sizeOf.BYTE; + if (providerPropTypes) { + checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider'); + } + } -encode.SID = encode.USHORT; -sizeOf.SID = sizeOf.USHORT; + pushProvider(workInProgress, context, newValue); -// Convert a numeric operand or charstring number to a variable-size list of bytes. -/** - * Convert a numeric operand or charstring number to a variable-size list of bytes. - * @param {number} - * @returns {Array} - */ -encode.NUMBER = function(v) { - if (v >= -107 && v <= 107) { - return [v + 139]; - } else if (v >= 108 && v <= 1131) { - v = v - 108; - return [(v >> 8) + 247, v & 0xFF]; - } else if (v >= -1131 && v <= -108) { - v = -v - 108; - return [(v >> 8) + 251, v & 0xFF]; - } else if (v >= -32768 && v <= 32767) { - return encode.NUMBER16(v); - } else { - return encode.NUMBER32(v); - } -}; + { + if (oldProps !== null) { + var oldValue = oldProps.value; -/** - * @param {number} - * @returns {number} - */ -sizeOf.NUMBER = function(v) { - return encode.NUMBER(v).length; -}; + if (objectIs(oldValue, newValue)) { + // No change. Bailout early if children are the same. + if (oldProps.children === newProps.children && !hasContextChanged()) { + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } + } else { + // The context value changed. Search for matching consumers and schedule + // them to update. + propagateContextChange(workInProgress, context, renderLanes); + } + } + } -/** - * Convert a signed number between -32768 and +32767 to a three-byte value. - * This ensures we always use three bytes, but is not the most compact format. - * @param {number} - * @returns {Array} - */ -encode.NUMBER16 = function(v) { - return [28, (v >> 8) & 0xFF, v & 0xFF]; -}; + var newChildren = newProps.children; + reconcileChildren(current, workInProgress, newChildren, renderLanes); + return workInProgress.child; + } -/** - * @constant - * @type {number} - */ -sizeOf.NUMBER16 = constant(3); + var hasWarnedAboutUsingContextAsConsumer = false; -/** - * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value. - * This is useful if you want to be sure you always use four bytes, - * at the expense of wasting a few bytes for smaller numbers. - * @param {number} - * @returns {Array} - */ -encode.NUMBER32 = function(v) { - return [29, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + function updateContextConsumer(current, workInProgress, renderLanes) { + var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In + // DEV mode, we create a separate object for Context.Consumer that acts + // like a proxy to Context. This proxy object adds unnecessary code in PROD + // so we use the old behaviour (Context.Consumer references Context) to + // reduce size and overhead. The separate object references context via + // a property called "_context", which also gives us the ability to check + // in DEV mode if this property exists or not and warn if it does not. -/** - * @constant - * @type {number} - */ -sizeOf.NUMBER32 = constant(5); + { + if (context._context === undefined) { + // This may be because it's a Context (rather than a Consumer). + // Or it may be because it's older React where they're the same thing. + // We only want to warn if we're sure it's a new React. + if (context !== context.Consumer) { + if (!hasWarnedAboutUsingContextAsConsumer) { + hasWarnedAboutUsingContextAsConsumer = true; -/** - * @param {number} - * @returns {Array} - */ -encode.REAL = function(v) { - var value = v.toString(); - - // Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7) - // This code converts it back to a number without the epsilon. - var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); - if (m) { - var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length)); - value = (Math.round(v * epsilon) / epsilon).toString(); - } + error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + } + } else { + context = context._context; + } + } - var nibbles = ''; - for (var i = 0, ii = value.length; i < ii; i += 1) { - var c = value[i]; - if (c === 'e') { - nibbles += value[++i] === '-' ? 'c' : 'b'; - } else if (c === '.') { - nibbles += 'a'; - } else if (c === '-') { - nibbles += 'e'; - } else { - nibbles += c; - } - } + var newProps = workInProgress.pendingProps; + var render = newProps.children; - nibbles += (nibbles.length & 1) ? 'f' : 'ff'; - var out = [30]; - for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) { - out.push(parseInt(nibbles.substr(i$1, 2), 16)); - } + { + if (typeof render !== 'function') { + error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); + } + } - return out; -}; + prepareToReadContext(workInProgress, renderLanes); + var newValue = readContext(context); -/** - * @param {number} - * @returns {number} - */ -sizeOf.REAL = function(v) { - return encode.REAL(v).length; -}; + { + markComponentRenderStarted(workInProgress); + } -encode.NAME = encode.CHARARRAY; -sizeOf.NAME = sizeOf.CHARARRAY; + var newChildren; -encode.STRING = encode.CHARARRAY; -sizeOf.STRING = sizeOf.CHARARRAY; + { + ReactCurrentOwner$1.current = workInProgress; + setIsRendering(true); + newChildren = render(newValue); + setIsRendering(false); + } -/** - * @param {DataView} data - * @param {number} offset - * @param {number} numBytes - * @returns {string} - */ -decode.UTF8 = function(data, offset, numBytes) { - var codePoints = []; - var numChars = numBytes; - for (var j = 0; j < numChars; j++, offset += 1) { - codePoints[j] = data.getUint8(offset); - } + { + markComponentRenderStopped(); + } // React DevTools reads this flag. - return String.fromCharCode.apply(null, codePoints); -}; -/** - * @param {DataView} data - * @param {number} offset - * @param {number} numBytes - * @returns {string} - */ -decode.UTF16 = function(data, offset, numBytes) { - var codePoints = []; - var numChars = numBytes / 2; - for (var j = 0; j < numChars; j++, offset += 2) { - codePoints[j] = data.getUint16(offset); - } + workInProgress.flags |= PerformedWork; + reconcileChildren(current, workInProgress, newChildren, renderLanes); + return workInProgress.child; + } - return String.fromCharCode.apply(null, codePoints); -}; + function markWorkInProgressReceivedUpdate() { + didReceiveUpdate = true; + } -/** - * Convert a JavaScript string to UTF16-BE. - * @param {string} - * @returns {Array} - */ -encode.UTF16 = function(v) { - var b = []; - for (var i = 0; i < v.length; i += 1) { - var codepoint = v.charCodeAt(i); - b[b.length] = (codepoint >> 8) & 0xFF; - b[b.length] = codepoint & 0xFF; - } + function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) { + if (current !== null) { + // Reuse previous dependencies + workInProgress.dependencies = current.dependencies; + } - return b; -}; + { + // Don't update "base" render times for bailouts. + stopProfilerTimerIfRunning(); + } -/** - * @param {string} - * @returns {number} - */ -sizeOf.UTF16 = function(v) { - return v.length * 2; -}; + markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work. -// Data for converting old eight-bit Macintosh encodings to Unicode. -// This representation is optimized for decoding; encoding is slower -// and needs more memory. The assumption is that all opentype.js users -// want to open fonts, but saving a font will be comparatively rare -// so it can be more expensive. Keyed by IANA character set name. -// -// Python script for generating these strings: -// -// s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)]) -// print(s.encode('utf-8')) -/** - * @private - */ -var eightBitMacEncodings = { - 'x-mac-croatian': // Python: 'mac_croatian' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' + - '¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ', - 'x-mac-cyrillic': // Python: 'mac_cyrillic' - 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' + - 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю', - 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' + - 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ', - 'x-mac-greek': // Python: 'mac_greek' - 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' + - 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD', - 'x-mac-icelandic': // Python: 'mac_iceland' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + - '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', - 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT - 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' + - 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł', - 'x-mac-ce': // Python: 'mac_latin2' - 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' + - 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ', - macintosh: // Python: 'mac_roman' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + - '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', - 'x-mac-romanian': // Python: 'mac_romanian' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' + - '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', - 'x-mac-turkish': // Python: 'mac_turkish' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + - '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ' -}; + if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { + // The children don't have any work either. We can skip them. + // TODO: Once we add back resuming, we should check if the children are + // a work-in-progress set. If so, we need to transfer their effects. + { + return null; + } + } // This fiber doesn't have work, but its subtree does. Clone the child + // fibers and continue. -/** - * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript - * string, or 'undefined' if the encoding is unsupported. For example, we do - * not support Chinese, Japanese or Korean because these would need large - * mapping tables. - * @param {DataView} dataView - * @param {number} offset - * @param {number} dataLength - * @param {string} encoding - * @returns {string} - */ -decode.MACSTRING = function(dataView, offset, dataLength, encoding) { - var table = eightBitMacEncodings[encoding]; - if (table === undefined) { - return undefined; - } - var result = ''; - for (var i = 0; i < dataLength; i++) { - var c = dataView.getUint8(offset + i); - // In all eight-bit Mac encodings, the characters 0x00..0x7F are - // mapped to U+0000..U+007F; we only need to look up the others. - if (c <= 0x7F) { - result += String.fromCharCode(c); - } else { - result += table[c & 0x7F]; - } - } + cloneChildFibers(current, workInProgress); + return workInProgress.child; + } - return result; -}; + function remountFiber(current, oldWorkInProgress, newWorkInProgress) { + { + var returnFiber = oldWorkInProgress.return; -// Helper function for encode.MACSTRING. Returns a dictionary for mapping -// Unicode character codes to their 8-bit MacOS equivalent. This table -// is not exactly a super cheap data structure, but we do not care because -// encoding Macintosh strings is only rarely needed in typical applications. -var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap(); -var macEncodingCacheKeys; -var getMacEncodingTable = function (encoding) { - // Since we use encoding as a cache key for WeakMap, it has to be - // a String object and not a literal. And at least on NodeJS 2.10.1, - // WeakMap requires that the same String instance is passed for cache hits. - if (!macEncodingCacheKeys) { - macEncodingCacheKeys = {}; - for (var e in eightBitMacEncodings) { - /*jshint -W053 */ // Suppress "Do not use String as a constructor." - macEncodingCacheKeys[e] = new String(e); - } - } + if (returnFiber === null) { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('Cannot swap the root fiber.'); + } // Disconnect from the old current. + // It will get deleted. - var cacheKey = macEncodingCacheKeys[encoding]; - if (cacheKey === undefined) { - return undefined; - } - // We can't do "if (cache.has(key)) {return cache.get(key)}" here: - // since garbage collection may run at any time, it could also kick in - // between the calls to cache.has() and cache.get(). In that case, - // we would return 'undefined' even though we do support the encoding. - if (macEncodingTableCache) { - var cachedTable = macEncodingTableCache.get(cacheKey); - if (cachedTable !== undefined) { - return cachedTable; - } - } + current.alternate = null; + oldWorkInProgress.alternate = null; // Connect to the new tree. - var decodingTable = eightBitMacEncodings[encoding]; - if (decodingTable === undefined) { - return undefined; - } + newWorkInProgress.index = oldWorkInProgress.index; + newWorkInProgress.sibling = oldWorkInProgress.sibling; + newWorkInProgress.return = oldWorkInProgress.return; + newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. - var encodingTable = {}; - for (var i = 0; i < decodingTable.length; i++) { - encodingTable[decodingTable.charCodeAt(i)] = i + 0x80; - } + if (oldWorkInProgress === returnFiber.child) { + returnFiber.child = newWorkInProgress; + } else { + var prevSibling = returnFiber.child; - if (macEncodingTableCache) { - macEncodingTableCache.set(cacheKey, encodingTable); - } + if (prevSibling === null) { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('Expected parent to have a child.'); + } - return encodingTable; -}; + while (prevSibling.sibling !== oldWorkInProgress) { + prevSibling = prevSibling.sibling; -/** - * Encodes an old-style Macintosh string. Returns a byte array upon success. - * If the requested encoding is unsupported, or if the input string contains - * a character that cannot be expressed in the encoding, the function returns - * 'undefined'. - * @param {string} str - * @param {string} encoding - * @returns {Array} - */ -encode.MACSTRING = function(str, encoding) { - var table = getMacEncodingTable(encoding); - if (table === undefined) { - return undefined; - } + if (prevSibling === null) { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('Expected to find the previous sibling.'); + } + } - var result = []; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - - // In all eight-bit Mac encodings, the characters 0x00..0x7F are - // mapped to U+0000..U+007F; we only need to look up the others. - if (c >= 0x80) { - c = table[c]; - if (c === undefined) { - // str contains a Unicode character that cannot be encoded - // in the requested encoding. - return undefined; - } - } - result[i] = c; - // result.push(c); - } + prevSibling.sibling = newWorkInProgress; + } // Delete the old fiber and place the new one. + // Since the old fiber is disconnected, we have to schedule it manually. - return result; -}; -/** - * @param {string} str - * @param {string} encoding - * @returns {number} - */ -sizeOf.MACSTRING = function(str, encoding) { - var b = encode.MACSTRING(str, encoding); - if (b !== undefined) { - return b.length; - } else { - return 0; - } -}; + var deletions = returnFiber.deletions; -// Helper for encode.VARDELTAS -function isByteEncodable(value) { - return value >= -128 && value <= 127; -} + if (deletions === null) { + returnFiber.deletions = [current]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(current); + } -// Helper for encode.VARDELTAS -function encodeVarDeltaRunAsZeroes(deltas, pos, result) { - var runLength = 0; - var numDeltas = deltas.length; - while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) { - ++pos; - ++runLength; - } - result.push(0x80 | (runLength - 1)); - return pos; -} - -// Helper for encode.VARDELTAS -function encodeVarDeltaRunAsBytes(deltas, offset, result) { - var runLength = 0; - var numDeltas = deltas.length; - var pos = offset; - while (pos < numDeltas && runLength < 64) { - var value = deltas[pos]; - if (!isByteEncodable(value)) { - break; - } + newWorkInProgress.flags |= Placement; // Restart work from the new fiber. - // Within a byte-encoded run of deltas, a single zero is best - // stored literally as 0x00 value. However, if we have two or - // more zeroes in a sequence, it is better to start a new run. - // Fore example, the sequence of deltas [15, 15, 0, 15, 15] - // becomes 6 bytes (04 0F 0F 00 0F 0F) when storing the zero - // within the current run, but 7 bytes (01 0F 0F 80 01 0F 0F) - // when starting a new run. - if (value === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) { - break; - } + return newWorkInProgress; + } + } - ++pos; - ++runLength; - } - result.push(runLength - 1); - for (var i = offset; i < pos; ++i) { - result.push((deltas[i] + 256) & 0xff); - } - return pos; -} - -// Helper for encode.VARDELTAS -function encodeVarDeltaRunAsWords(deltas, offset, result) { - var runLength = 0; - var numDeltas = deltas.length; - var pos = offset; - while (pos < numDeltas && runLength < 64) { - var value = deltas[pos]; - - // Within a word-encoded run of deltas, it is easiest to start - // a new run (with a different encoding) whenever we encounter - // a zero value. For example, the sequence [0x6666, 0, 0x7777] - // needs 7 bytes when storing the zero inside the current run - // (42 66 66 00 00 77 77), and equally 7 bytes when starting a - // new run (40 66 66 80 40 77 77). - if (value === 0) { - break; - } + function checkScheduledUpdateOrContext(current, renderLanes) { + // Before performing an early bailout, we must check if there are pending + // updates or context. + var updateLanes = current.lanes; - // Within a word-encoded run of deltas, a single value in the - // range (-128..127) should be encoded within the current run - // because it is more compact. For example, the sequence - // [0x6666, 2, 0x7777] becomes 7 bytes when storing the value - // literally (42 66 66 00 02 77 77), but 8 bytes when starting - // a new run (40 66 66 00 02 40 77 77). - if (isByteEncodable(value) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) { - break; - } + if (includesSomeLane(updateLanes, renderLanes)) { + return true; + } // No pending update, but because context is propagated lazily, we need - ++pos; - ++runLength; - } - result.push(0x40 | (runLength - 1)); - for (var i = offset; i < pos; ++i) { - var val = deltas[i]; - result.push(((val + 0x10000) >> 8) & 0xff, (val + 0x100) & 0xff); - } - return pos; -} + return false; + } -/** - * Encode a list of variation adjustment deltas. - * - * Variation adjustment deltas are used in ‘gvar’ and ‘cvar’ tables. - * They indicate how points (in ‘gvar’) or values (in ‘cvar’) get adjusted - * when generating instances of variation fonts. - * - * @see https://www.microsoft.com/typography/otspec/gvar.htm - * @see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html - * @param {Array} - * @return {Array} - */ -encode.VARDELTAS = function(deltas) { - var pos = 0; - var result = []; - while (pos < deltas.length) { - var value = deltas[pos]; - if (value === 0) { - pos = encodeVarDeltaRunAsZeroes(deltas, pos, result); - } else if (value >= -128 && value <= 127) { - pos = encodeVarDeltaRunAsBytes(deltas, pos, result); - } else { - pos = encodeVarDeltaRunAsWords(deltas, pos, result); - } - } - return result; -}; + function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) { + // This fiber does not have any pending work. Bailout without entering + // the begin phase. There's still some bookkeeping we that needs to be done + // in this optimized path, mostly pushing stuff onto the stack. + switch (workInProgress.tag) { + case HostRoot: + pushHostRootContext(workInProgress); + workInProgress.stateNode; -// Convert a list of values to a CFF INDEX structure. -// The values should be objects containing name / type / value. -/** - * @param {Array} l - * @returns {Array} - */ -encode.INDEX = function(l) { - //var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data, - // i, v; - // Because we have to know which data type to use to encode the offsets, - // we have to go through the values twice: once to encode the data and - // calculate the offsets, then again to encode the offsets using the fitting data type. - var offset = 1; // First offset is always 1. - var offsets = [offset]; - var data = []; - for (var i = 0; i < l.length; i += 1) { - var v = encode.OBJECT(l[i]); - Array.prototype.push.apply(data, v); - offset += v.length; - offsets.push(offset); - } + resetHydrationState(); + break; - if (data.length === 0) { - return [0, 0]; - } + case HostComponent: + pushHostContext(workInProgress); + break; - var encodedOffsets = []; - var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0; - var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize]; - for (var i$1 = 0; i$1 < offsets.length; i$1 += 1) { - var encodedOffset = offsetEncoder(offsets[i$1]); - Array.prototype.push.apply(encodedOffsets, encodedOffset); - } + case ClassComponent: + { + var Component = workInProgress.type; - return Array.prototype.concat(encode.Card16(l.length), - encode.OffSize(offSize), - encodedOffsets, - data); -}; + if (isContextProvider(Component)) { + pushContextProvider(workInProgress); + } -/** - * @param {Array} - * @returns {number} - */ -sizeOf.INDEX = function(v) { - return encode.INDEX(v).length; -}; + break; + } -/** - * Convert an object to a CFF DICT structure. - * The keys should be numeric. - * The values should be objects containing name / type / value. - * @param {Object} m - * @returns {Array} - */ -encode.DICT = function(m) { - var d = []; - var keys = Object.keys(m); - var length = keys.length; - - for (var i = 0; i < length; i += 1) { - // Object.keys() return string keys, but our keys are always numeric. - var k = parseInt(keys[i], 0); - var v = m[k]; - // Value comes before the key. - d = d.concat(encode.OPERAND(v.value, v.type)); - d = d.concat(encode.OPERATOR(k)); - } + case HostPortal: + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + break; - return d; -}; + case ContextProvider: + { + var newValue = workInProgress.memoizedProps.value; + var context = workInProgress.type._context; + pushProvider(workInProgress, context, newValue); + break; + } -/** - * @param {Object} - * @returns {number} - */ -sizeOf.DICT = function(m) { - return encode.DICT(m).length; -}; + case Profiler: + { + // Profiler should only call onRender when one of its descendants actually rendered. + var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); -/** - * @param {number} - * @returns {Array} - */ -encode.OPERATOR = function(v) { - if (v < 1200) { - return [v]; - } else { - return [12, v - 1200]; - } -}; + if (hasChildWork) { + workInProgress.flags |= Update; + } -/** - * @param {Array} v - * @param {string} - * @returns {Array} - */ -encode.OPERAND = function(v, type) { - var d = []; - if (Array.isArray(type)) { - for (var i = 0; i < type.length; i += 1) { - check.argument(v.length === type.length, 'Not enough arguments given for type' + type); - d = d.concat(encode.OPERAND(v[i], type[i])); - } - } else { - if (type === 'SID') { - d = d.concat(encode.NUMBER(v)); - } else if (type === 'offset') { - // We make it easy for ourselves and always encode offsets as - // 4 bytes. This makes offset calculation for the top dict easier. - d = d.concat(encode.NUMBER32(v)); - } else if (type === 'number') { - d = d.concat(encode.NUMBER(v)); - } else if (type === 'real') { - d = d.concat(encode.REAL(v)); - } else { - throw new Error('Unknown operand type ' + type); - // FIXME Add support for booleans - } - } + { + // Reset effect durations for the next eventual effect phase. + // These are reset during render to allow the DevTools commit hook a chance to read them, + var stateNode = workInProgress.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + } - return d; -}; + break; -encode.OP = encode.BYTE; -sizeOf.OP = sizeOf.BYTE; + case SuspenseComponent: + { + var state = workInProgress.memoizedState; -// memoize charstring encoding using WeakMap if available -var wmm = typeof WeakMap === 'function' && new WeakMap(); + if (state !== null) { + { + if (state.dehydrated !== null) { + pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has + // been unsuspended it has committed as a resolved Suspense component. + // If it needs to be retried, it should have work scheduled on it. -/** - * Convert a list of CharString operations to bytes. - * @param {Array} - * @returns {Array} - */ -encode.CHARSTRING = function(ops) { - // See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))". - if (wmm) { - var cachedValue = wmm.get(ops); - if (cachedValue !== undefined) { - return cachedValue; - } - } + workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we + // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork. - var d = []; - var length = ops.length; + return null; + } + } // If this boundary is currently timed out, we need to decide + // whether to retry the primary children, or to skip over it and + // go straight to the fallback. Check the priority of the primary + // child fragment. - for (var i = 0; i < length; i += 1) { - var op = ops[i]; - d = d.concat(encode[op.type](op.value)); - } - if (wmm) { - wmm.set(ops, d); - } + var primaryChildFragment = workInProgress.child; + var primaryChildLanes = primaryChildFragment.childLanes; - return d; -}; + if (includesSomeLane(renderLanes, primaryChildLanes)) { + // The primary children have pending work. Use the normal path + // to attempt to render the primary children again. + return updateSuspenseComponent(current, workInProgress, renderLanes); + } else { + // The primary child fragment does not have pending work marked + // on it + pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient + // priority. Bailout. -/** - * @param {Array} - * @returns {number} - */ -sizeOf.CHARSTRING = function(ops) { - return encode.CHARSTRING(ops).length; -}; + var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); -// Utility functions //////////////////////////////////////////////////////// + if (child !== null) { + // The fallback children have pending work. Skip over the + // primary children and work on the fallback. + return child.sibling; + } else { + // Note: We can return `null` here because we already checked + // whether there were nested context consumers, via the call to + // `bailoutOnAlreadyFinishedWork` above. + return null; + } + } + } else { + pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); + } -/** - * Convert an object containing name / type / value to bytes. - * @param {Object} - * @returns {Array} - */ -encode.OBJECT = function(v) { - var encodingFunction = encode[v.type]; - check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type); - return encodingFunction(v.value); -}; + break; + } -/** - * @param {Object} - * @returns {number} - */ -sizeOf.OBJECT = function(v) { - var sizeOfFunction = sizeOf[v.type]; - check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type); - return sizeOfFunction(v.value); -}; + case SuspenseListComponent: + { + var didSuspendBefore = (current.flags & DidCapture) !== NoFlags; -/** - * Convert a table object to bytes. - * A table contains a list of fields containing the metadata (name, type and default value). - * The table itself has the field values set as attributes. - * @param {opentype.Table} - * @returns {Array} - */ -encode.TABLE = function(table) { - var d = []; - var length = table.fields.length; - var subtables = []; - var subtableOffsets = []; - - for (var i = 0; i < length; i += 1) { - var field = table.fields[i]; - var encodingFunction = encode[field.type]; - check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')'); - var value = table[field.name]; - if (value === undefined) { - value = field.value; - } + var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); - var bytes = encodingFunction(value); + if (didSuspendBefore) { + if (_hasChildWork) { + // If something was in fallback state last time, and we have all the + // same children then we're still in progressive loading state. + // Something might get unblocked by state updates or retries in the + // tree which will affect the tail. So we need to use the normal + // path to compute the correct tail. + return updateSuspenseListComponent(current, workInProgress, renderLanes); + } // If none of the children had any work, that means that none of + // them got retried so they'll still be blocked in the same way + // as before. We can fast bail out. - if (field.type === 'TABLE') { - subtableOffsets.push(d.length); - d = d.concat([0, 0]); - subtables.push(bytes); - } else { - d = d.concat(bytes); - } - } - for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) { - var o = subtableOffsets[i$1]; - var offset = d.length; - check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.'); - d[o] = offset >> 8; - d[o + 1] = offset & 0xff; - d = d.concat(subtables[i$1]); - } + workInProgress.flags |= DidCapture; + } // If nothing suspended before and we're rendering the same children, + // then the tail doesn't matter. Anything new that suspends will work + // in the "together" mode, so we can continue from the state we had. - return d; -}; -/** - * @param {opentype.Table} - * @returns {number} - */ -sizeOf.TABLE = function(table) { - var numBytes = 0; - var length = table.fields.length; - - for (var i = 0; i < length; i += 1) { - var field = table.fields[i]; - var sizeOfFunction = sizeOf[field.type]; - check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')'); - var value = table[field.name]; - if (value === undefined) { - value = field.value; - } + var renderState = workInProgress.memoizedState; - numBytes += sizeOfFunction(value); + if (renderState !== null) { + // Reset to the "together" mode in case we've started a different + // update in the past but didn't complete it. + renderState.rendering = null; + renderState.tail = null; + renderState.lastEffect = null; + } - // Subtables take 2 more bytes for offsets. - if (field.type === 'TABLE') { - numBytes += 2; - } - } + pushSuspenseContext(workInProgress, suspenseStackCursor.current); - return numBytes; -}; + if (_hasChildWork) { + break; + } else { + // If none of the children had any work, that means that none of + // them got retried so they'll still be blocked in the same way + // as before. We can fast bail out. + return null; + } + } -encode.RECORD = encode.TABLE; -sizeOf.RECORD = sizeOf.TABLE; + case OffscreenComponent: + case LegacyHiddenComponent: + { + // Need to check if the tree still needs to be deferred. This is + // almost identical to the logic used in the normal update path, + // so we'll just enter that. The only difference is we'll bail out + // at the next level instead of this one, because the child props + // have not changed. Which is fine. + // TODO: Probably should refactor `beginWork` to split the bailout + // path from the normal path. I'm tempted to do a labeled break here + // but I won't :) + workInProgress.lanes = NoLanes; + return updateOffscreenComponent(current, workInProgress, renderLanes); + } + } -// Merge in a list of bytes. -encode.LITERAL = function(v) { - return v; -}; + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } -sizeOf.LITERAL = function(v) { - return v.length; -}; + function beginWork(current, workInProgress, renderLanes) { + { + if (workInProgress._debugNeedsRemount && current !== null) { + // This will restart the begin phase with a new fiber. + return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes)); + } + } -// Table metadata + if (current !== null) { + var oldProps = current.memoizedProps; + var newProps = workInProgress.pendingProps; -/** - * @exports opentype.Table - * @class - * @param {string} tableName - * @param {Array} fields - * @param {Object} options - * @constructor - */ -function Table(tableName, fields, options) { - // For coverage tables with coverage format 2, we do not want to add the coverage data directly to the table object, - // as this will result in wrong encoding order of the coverage data on serialization to bytes. - // The fallback of using the field values directly when not present on the table is handled in types.encode.TABLE() already. - if (fields.length && (fields[0].name !== 'coverageFormat' || fields[0].value === 1)) { - for (var i = 0; i < fields.length; i += 1) { - var field = fields[i]; - this[field.name] = field.value; - } - } + if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload: + workInProgress.type !== current.type )) { + // If props or context changed, mark the fiber as having performed work. + // This may be unset if the props are determined to be equal later (memo). + didReceiveUpdate = true; + } else { + // Neither props nor legacy context changes. Check if there's a pending + // update or context change. + var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); - this.tableName = tableName; - this.fields = fields; - if (options) { - var optionKeys = Object.keys(options); - for (var i$1 = 0; i$1 < optionKeys.length; i$1 += 1) { - var k = optionKeys[i$1]; - var v = options[k]; - if (this[k] !== undefined) { - this[k] = v; - } - } - } -} + if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there + // may not be work scheduled on `current`, so we check for this flag. + (workInProgress.flags & DidCapture) === NoFlags) { + // No pending updates or context. Bail out now. + didReceiveUpdate = false; + return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes); + } -/** - * Encodes the table and returns an array of bytes - * @return {Array} - */ -Table.prototype.encode = function() { - return encode.TABLE(this); -}; + if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { + // This is a special case that only exists for legacy mode. + // See https://github.com/facebook/react/pull/19216. + didReceiveUpdate = true; + } else { + // An update was scheduled on this fiber, but there are no new props + // nor legacy context. Set this to false. If an update queue or context + // consumer produces a changed value, it will set this to true. Otherwise, + // the component will assume the children have not changed and bail out. + didReceiveUpdate = false; + } + } + } else { + didReceiveUpdate = false; -/** - * Get the size of the table. - * @return {number} - */ -Table.prototype.sizeOf = function() { - return sizeOf.TABLE(this); -}; + if (getIsHydrating() && isForkedChild(workInProgress)) { + // Check if this child belongs to a list of muliple children in + // its parent. + // + // In a true multi-threaded implementation, we would render children on + // parallel threads. This would represent the beginning of a new render + // thread for this subtree. + // + // We only use this for id generation during hydration, which is why the + // logic is located in this special branch. + var slotIndex = workInProgress.index; + var numberOfForks = getForksAtLevel(); + pushTreeId(workInProgress, numberOfForks, slotIndex); + } + } // Before entering the begin phase, clear pending update priority. + // TODO: This assumes that we're about to evaluate the component and process + // the update queue. However, there's an exception: SimpleMemoComponent + // sometimes bails out later in the begin phase. This indicates that we should + // move this assignment out of the common path and into each branch. -/** - * @private - */ -function ushortList(itemName, list, count) { - if (count === undefined) { - count = list.length; - } - var fields = new Array(list.length + 1); - fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; - for (var i = 0; i < list.length; i++) { - fields[i + 1] = {name: itemName + i, type: 'USHORT', value: list[i]}; - } - return fields; -} -/** - * @private - */ -function tableList(itemName, records, itemCallback) { - var count = records.length; - var fields = new Array(count + 1); - fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; - for (var i = 0; i < count; i++) { - fields[i + 1] = {name: itemName + i, type: 'TABLE', value: itemCallback(records[i], i)}; - } - return fields; -} + workInProgress.lanes = NoLanes; -/** - * @private - */ -function recordList(itemName, records, itemCallback) { - var count = records.length; - var fields = []; - fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; - for (var i = 0; i < count; i++) { - fields = fields.concat(itemCallback(records[i], i)); - } - return fields; -} + switch (workInProgress.tag) { + case IndeterminateComponent: + { + return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes); + } -// Common Layout Tables + case LazyComponent: + { + var elementType = workInProgress.elementType; + return mountLazyComponent(current, workInProgress, elementType, renderLanes); + } -/** - * @exports opentype.Coverage - * @class - * @param {opentype.Table} - * @constructor - * @extends opentype.Table - */ -function Coverage(coverageTable) { - if (coverageTable.format === 1) { - Table.call(this, 'coverageTable', - [{name: 'coverageFormat', type: 'USHORT', value: 1}] - .concat(ushortList('glyph', coverageTable.glyphs)) - ); - } else if (coverageTable.format === 2) { - Table.call(this, 'coverageTable', - [{name: 'coverageFormat', type: 'USHORT', value: 2}] - .concat(recordList('rangeRecord', coverageTable.ranges, function(RangeRecord) { - return [ - {name: 'startGlyphID', type: 'USHORT', value: RangeRecord.start}, - {name: 'endGlyphID', type: 'USHORT', value: RangeRecord.end}, - {name: 'startCoverageIndex', type: 'USHORT', value: RangeRecord.index} ]; - })) - ); - } else { - check.assert(false, 'Coverage format must be 1 or 2.'); - } -} -Coverage.prototype = Object.create(Table.prototype); -Coverage.prototype.constructor = Coverage; - -function ScriptList(scriptListTable) { - Table.call(this, 'scriptListTable', - recordList('scriptRecord', scriptListTable, function(scriptRecord, i) { - var script = scriptRecord.script; - var defaultLangSys = script.defaultLangSys; - check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.'); - return [ - {name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag}, - {name: 'script' + i, type: 'TABLE', value: new Table('scriptTable', [ - {name: 'defaultLangSys', type: 'TABLE', value: new Table('defaultLangSys', [ - {name: 'lookupOrder', type: 'USHORT', value: 0}, - {name: 'reqFeatureIndex', type: 'USHORT', value: defaultLangSys.reqFeatureIndex}] - .concat(ushortList('featureIndex', defaultLangSys.featureIndexes)))} - ].concat(recordList('langSys', script.langSysRecords, function(langSysRecord, i) { - var langSys = langSysRecord.langSys; - return [ - {name: 'langSysTag' + i, type: 'TAG', value: langSysRecord.tag}, - {name: 'langSys' + i, type: 'TABLE', value: new Table('langSys', [ - {name: 'lookupOrder', type: 'USHORT', value: 0}, - {name: 'reqFeatureIndex', type: 'USHORT', value: langSys.reqFeatureIndex} - ].concat(ushortList('featureIndex', langSys.featureIndexes)))} - ]; - })))} - ]; - }) - ); -} -ScriptList.prototype = Object.create(Table.prototype); -ScriptList.prototype.constructor = ScriptList; + case FunctionComponent: + { + var Component = workInProgress.type; + var unresolvedProps = workInProgress.pendingProps; + var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); + return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes); + } -/** - * @exports opentype.FeatureList - * @class - * @param {opentype.Table} - * @constructor - * @extends opentype.Table - */ -function FeatureList(featureListTable) { - Table.call(this, 'featureListTable', - recordList('featureRecord', featureListTable, function(featureRecord, i) { - var feature = featureRecord.feature; - return [ - {name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag}, - {name: 'feature' + i, type: 'TABLE', value: new Table('featureTable', [ - {name: 'featureParams', type: 'USHORT', value: feature.featureParams} ].concat(ushortList('lookupListIndex', feature.lookupListIndexes)))} - ]; - }) - ); -} -FeatureList.prototype = Object.create(Table.prototype); -FeatureList.prototype.constructor = FeatureList; + case ClassComponent: + { + var _Component = workInProgress.type; + var _unresolvedProps = workInProgress.pendingProps; -/** - * @exports opentype.LookupList - * @class - * @param {opentype.Table} - * @param {Object} - * @constructor - * @extends opentype.Table - */ -function LookupList(lookupListTable, subtableMakers) { - Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function(lookupTable) { - var subtableCallback = subtableMakers[lookupTable.lookupType]; - check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.'); - return new Table('lookupTable', [ - {name: 'lookupType', type: 'USHORT', value: lookupTable.lookupType}, - {name: 'lookupFlag', type: 'USHORT', value: lookupTable.lookupFlag} - ].concat(tableList('subtable', lookupTable.subtables, subtableCallback))); - })); -} -LookupList.prototype = Object.create(Table.prototype); -LookupList.prototype.constructor = LookupList; - -// Record = same as Table, but inlined (a Table has an offset and its data is further in the stream) -// Don't use offsets inside Records (probable bug), only in Tables. -var table = { - Table: Table, - Record: Table, - Coverage: Coverage, - ScriptList: ScriptList, - FeatureList: FeatureList, - LookupList: LookupList, - ushortList: ushortList, - tableList: tableList, - recordList: recordList, -}; + var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps); -// Parsing utility functions + return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes); + } -// Retrieve an unsigned byte from the DataView. -function getByte(dataView, offset) { - return dataView.getUint8(offset); -} + case HostRoot: + return updateHostRoot(current, workInProgress, renderLanes); -// Retrieve an unsigned 16-bit short from the DataView. -// The value is stored in big endian. -function getUShort(dataView, offset) { - return dataView.getUint16(offset, false); -} + case HostComponent: + return updateHostComponent$1(current, workInProgress, renderLanes); -// Retrieve a signed 16-bit short from the DataView. -// The value is stored in big endian. -function getShort(dataView, offset) { - return dataView.getInt16(offset, false); -} + case HostText: + return updateHostText$1(current, workInProgress); -// Retrieve an unsigned 32-bit long from the DataView. -// The value is stored in big endian. -function getULong(dataView, offset) { - return dataView.getUint32(offset, false); -} + case SuspenseComponent: + return updateSuspenseComponent(current, workInProgress, renderLanes); -// Retrieve a 32-bit signed fixed-point number (16.16) from the DataView. -// The value is stored in big endian. -function getFixed(dataView, offset) { - var decimal = dataView.getInt16(offset, false); - var fraction = dataView.getUint16(offset + 2, false); - return decimal + fraction / 65535; -} + case HostPortal: + return updatePortalComponent(current, workInProgress, renderLanes); -// Retrieve a 4-character tag from the DataView. -// Tags are used to identify tables. -function getTag(dataView, offset) { - var tag = ''; - for (var i = offset; i < offset + 4; i += 1) { - tag += String.fromCharCode(dataView.getInt8(i)); - } + case ForwardRef: + { + var type = workInProgress.type; + var _unresolvedProps2 = workInProgress.pendingProps; - return tag; -} + var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); -// Retrieve an offset from the DataView. -// Offsets are 1 to 4 bytes in length, depending on the offSize argument. -function getOffset(dataView, offset, offSize) { - var v = 0; - for (var i = 0; i < offSize; i += 1) { - v <<= 8; - v += dataView.getUint8(offset + i); - } + return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes); + } - return v; -} + case Fragment: + return updateFragment(current, workInProgress, renderLanes); -// Retrieve a number of bytes from start offset to the end offset from the DataView. -function getBytes(dataView, startOffset, endOffset) { - var bytes = []; - for (var i = startOffset; i < endOffset; i += 1) { - bytes.push(dataView.getUint8(i)); - } + case Mode: + return updateMode(current, workInProgress, renderLanes); - return bytes; -} + case Profiler: + return updateProfiler(current, workInProgress, renderLanes); -// Convert the list of bytes to a string. -function bytesToString(bytes) { - var s = ''; - for (var i = 0; i < bytes.length; i += 1) { - s += String.fromCharCode(bytes[i]); - } + case ContextProvider: + return updateContextProvider(current, workInProgress, renderLanes); - return s; -} + case ContextConsumer: + return updateContextConsumer(current, workInProgress, renderLanes); -var typeOffsets = { - byte: 1, - uShort: 2, - short: 2, - uLong: 4, - fixed: 4, - longDateTime: 8, - tag: 4 -}; + case MemoComponent: + { + var _type2 = workInProgress.type; + var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. -// A stateful parser that changes the offset whenever a value is retrieved. -// The data is a DataView. -function Parser(data, offset) { - this.data = data; - this.offset = offset; - this.relativeOffset = 0; -} + var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); -Parser.prototype.parseByte = function() { - var v = this.data.getUint8(this.offset + this.relativeOffset); - this.relativeOffset += 1; - return v; -}; + { + if (workInProgress.type !== workInProgress.elementType) { + var outerPropTypes = _type2.propTypes; -Parser.prototype.parseChar = function() { - var v = this.data.getInt8(this.offset + this.relativeOffset); - this.relativeOffset += 1; - return v; -}; + if (outerPropTypes) { + checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only + 'prop', getComponentNameFromType(_type2)); + } + } + } -Parser.prototype.parseCard8 = Parser.prototype.parseByte; + _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes); + } -Parser.prototype.parseUShort = function() { - var v = this.data.getUint16(this.offset + this.relativeOffset); - this.relativeOffset += 2; - return v; -}; + case SimpleMemoComponent: + { + return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes); + } -Parser.prototype.parseCard16 = Parser.prototype.parseUShort; -Parser.prototype.parseSID = Parser.prototype.parseUShort; -Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; + case IncompleteClassComponent: + { + var _Component2 = workInProgress.type; + var _unresolvedProps4 = workInProgress.pendingProps; -Parser.prototype.parseShort = function() { - var v = this.data.getInt16(this.offset + this.relativeOffset); - this.relativeOffset += 2; - return v; -}; + var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4); -Parser.prototype.parseF2Dot14 = function() { - var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; - this.relativeOffset += 2; - return v; -}; + return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes); + } -Parser.prototype.parseULong = function() { - var v = getULong(this.data, this.offset + this.relativeOffset); - this.relativeOffset += 4; - return v; -}; + case SuspenseListComponent: + { + return updateSuspenseListComponent(current, workInProgress, renderLanes); + } -Parser.prototype.parseOffset32 = Parser.prototype.parseULong; + case ScopeComponent: + { -Parser.prototype.parseFixed = function() { - var v = getFixed(this.data, this.offset + this.relativeOffset); - this.relativeOffset += 4; - return v; -}; + break; + } -Parser.prototype.parseString = function(length) { - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - var string = ''; - this.relativeOffset += length; - for (var i = 0; i < length; i++) { - string += String.fromCharCode(dataView.getUint8(offset + i)); - } + case OffscreenComponent: + { + return updateOffscreenComponent(current, workInProgress, renderLanes); + } + } - return string; -}; + throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); + } -Parser.prototype.parseTag = function() { - return this.parseString(4); -}; + function unwindWork(current, workInProgress, renderLanes) { + // Note: This intentionally doesn't check if we're hydrating because comparing + // to the current tree provider fiber is just as fast and less error-prone. + // Ideally we would have a special version of the work loop only + // for hydration. + popTreeContext(workInProgress); -// LONGDATETIME is a 64-bit integer. -// JavaScript and unix timestamps traditionally use 32 bits, so we -// only take the last 32 bits. -// + Since until 2038 those bits will be filled by zeros we can ignore them. -Parser.prototype.parseLongDateTime = function() { - var v = getULong(this.data, this.offset + this.relativeOffset + 4); - // Subtract seconds between 01/01/1904 and 01/01/1970 - // to convert Apple Mac timestamp to Standard Unix timestamp - v -= 2082844800; - this.relativeOffset += 8; - return v; -}; + switch (workInProgress.tag) { + case ClassComponent: + { + var Component = workInProgress.type; -Parser.prototype.parseVersion = function(minorBase) { - var major = getUShort(this.data, this.offset + this.relativeOffset); + if (isContextProvider(Component)) { + popContext(workInProgress); + } - // How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1 - // Default returns the correct number if minor = 0xN000 where N is 0-9 - // Set minorBase to 1 for tables that use minor = N where N is 0-9 - var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); - this.relativeOffset += 4; - if (minorBase === undefined) { minorBase = 0x1000; } - return major + minor / minorBase / 10; -}; + var flags = workInProgress.flags; -Parser.prototype.skip = function(type, amount) { - if (amount === undefined) { - amount = 1; - } + if (flags & ShouldCapture) { + workInProgress.flags = flags & ~ShouldCapture | DidCapture; - this.relativeOffset += typeOffsets[type] * amount; -}; + if ( (workInProgress.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress); + } -///// Parsing lists and records /////////////////////////////// - -// Parse a list of 32 bit unsigned integers. -Parser.prototype.parseULongList = function(count) { - if (count === undefined) { count = this.parseULong(); } - var offsets = new Array(count); - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - for (var i = 0; i < count; i++) { - offsets[i] = dataView.getUint32(offset); - offset += 4; - } + return workInProgress; + } - this.relativeOffset += count * 4; - return offsets; -}; + return null; + } -// Parse a list of 16 bit unsigned integers. The length of the list can be read on the stream -// or provided as an argument. -Parser.prototype.parseOffset16List = -Parser.prototype.parseUShortList = function(count) { - if (count === undefined) { count = this.parseUShort(); } - var offsets = new Array(count); - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - for (var i = 0; i < count; i++) { - offsets[i] = dataView.getUint16(offset); - offset += 2; - } + case HostRoot: + { - this.relativeOffset += count * 2; - return offsets; -}; + popHostContainer(workInProgress); + popTopLevelContextObject(workInProgress); + resetWorkInProgressVersions(); + var _flags = workInProgress.flags; -// Parses a list of 16 bit signed integers. -Parser.prototype.parseShortList = function(count) { - var list = new Array(count); - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - for (var i = 0; i < count; i++) { - list[i] = dataView.getInt16(offset); - offset += 2; - } + if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) { + // There was an error during render that wasn't captured by a suspense + // boundary. Do a second pass on the root to unmount the children. + workInProgress.flags = _flags & ~ShouldCapture | DidCapture; + return workInProgress; + } // We unwound to the root without completing it. Exit. - this.relativeOffset += count * 2; - return list; -}; -// Parses a list of bytes. -Parser.prototype.parseByteList = function(count) { - var list = new Array(count); - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - for (var i = 0; i < count; i++) { - list[i] = dataView.getUint8(offset++); - } + return null; + } - this.relativeOffset += count; - return list; -}; + case HostComponent: + { + // TODO: popHydrationState + popHostContext(workInProgress); + return null; + } -/** - * Parse a list of items. - * Record count is optional, if omitted it is read from the stream. - * itemCallback is one of the Parser methods. - */ -Parser.prototype.parseList = function(count, itemCallback) { - if (!itemCallback) { - itemCallback = count; - count = this.parseUShort(); - } - var list = new Array(count); - for (var i = 0; i < count; i++) { - list[i] = itemCallback.call(this); - } - return list; -}; + case SuspenseComponent: + { + popSuspenseContext(workInProgress); -Parser.prototype.parseList32 = function(count, itemCallback) { - if (!itemCallback) { - itemCallback = count; - count = this.parseULong(); - } - var list = new Array(count); - for (var i = 0; i < count; i++) { - list[i] = itemCallback.call(this); - } - return list; -}; + { + var suspenseState = workInProgress.memoizedState; -/** - * Parse a list of records. - * Record count is optional, if omitted it is read from the stream. - * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } - */ -Parser.prototype.parseRecordList = function(count, recordDescription) { - // If the count argument is absent, read it in the stream. - if (!recordDescription) { - recordDescription = count; - count = this.parseUShort(); - } - var records = new Array(count); - var fields = Object.keys(recordDescription); - for (var i = 0; i < count; i++) { - var rec = {}; - for (var j = 0; j < fields.length; j++) { - var fieldName = fields[j]; - var fieldType = recordDescription[fieldName]; - rec[fieldName] = fieldType.call(this); - } - records[i] = rec; - } - return records; -}; + if (suspenseState !== null && suspenseState.dehydrated !== null) { + if (workInProgress.alternate === null) { + throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.'); + } -Parser.prototype.parseRecordList32 = function(count, recordDescription) { - // If the count argument is absent, read it in the stream. - if (!recordDescription) { - recordDescription = count; - count = this.parseULong(); - } - var records = new Array(count); - var fields = Object.keys(recordDescription); - for (var i = 0; i < count; i++) { - var rec = {}; - for (var j = 0; j < fields.length; j++) { - var fieldName = fields[j]; - var fieldType = recordDescription[fieldName]; - rec[fieldName] = fieldType.call(this); - } - records[i] = rec; - } - return records; -}; + resetHydrationState(); + } + } -// Parse a data structure into an object -// Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } -Parser.prototype.parseStruct = function(description) { - if (typeof description === 'function') { - return description.call(this); - } else { - var fields = Object.keys(description); - var struct = {}; - for (var j = 0; j < fields.length; j++) { - var fieldName = fields[j]; - var fieldType = description[fieldName]; - struct[fieldName] = fieldType.call(this); - } - return struct; - } -}; + var _flags2 = workInProgress.flags; -/** - * Parse a GPOS valueRecord - * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record - * valueFormat is optional, if omitted it is read from the stream. - */ -Parser.prototype.parseValueRecord = function(valueFormat) { - if (valueFormat === undefined) { - valueFormat = this.parseUShort(); - } - if (valueFormat === 0) { - // valueFormat2 in kerning pairs is most often 0 - // in this case return undefined instead of an empty object, to save space - return; - } - var valueRecord = {}; + if (_flags2 & ShouldCapture) { + workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary. - if (valueFormat & 0x0001) { valueRecord.xPlacement = this.parseShort(); } - if (valueFormat & 0x0002) { valueRecord.yPlacement = this.parseShort(); } - if (valueFormat & 0x0004) { valueRecord.xAdvance = this.parseShort(); } - if (valueFormat & 0x0008) { valueRecord.yAdvance = this.parseShort(); } + if ( (workInProgress.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress); + } - // Device table (non-variable font) / VariationIndex table (variable font) not supported - // https://docs.microsoft.com/fr-fr/typography/opentype/spec/chapter2#devVarIdxTbls - if (valueFormat & 0x0010) { valueRecord.xPlaDevice = undefined; this.parseShort(); } - if (valueFormat & 0x0020) { valueRecord.yPlaDevice = undefined; this.parseShort(); } - if (valueFormat & 0x0040) { valueRecord.xAdvDevice = undefined; this.parseShort(); } - if (valueFormat & 0x0080) { valueRecord.yAdvDevice = undefined; this.parseShort(); } + return workInProgress; + } - return valueRecord; -}; + return null; + } -/** - * Parse a list of GPOS valueRecords - * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record - * valueFormat and valueCount are read from the stream. - */ -Parser.prototype.parseValueRecordList = function() { - var valueFormat = this.parseUShort(); - var valueCount = this.parseUShort(); - var values = new Array(valueCount); - for (var i = 0; i < valueCount; i++) { - values[i] = this.parseValueRecord(valueFormat); - } - return values; -}; + case SuspenseListComponent: + { + popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been + // caught by a nested boundary. If not, it should bubble through. -Parser.prototype.parsePointer = function(description) { - var structOffset = this.parseOffset16(); - if (structOffset > 0) { - // NULL offset => return undefined - return new Parser(this.data, this.offset + structOffset).parseStruct(description); - } - return undefined; -}; + return null; + } -Parser.prototype.parsePointer32 = function(description) { - var structOffset = this.parseOffset32(); - if (structOffset > 0) { - // NULL offset => return undefined - return new Parser(this.data, this.offset + structOffset).parseStruct(description); - } - return undefined; -}; + case HostPortal: + popHostContainer(workInProgress); + return null; -/** - * Parse a list of offsets to lists of 16-bit integers, - * or a list of offsets to lists of offsets to any kind of items. - * If itemCallback is not provided, a list of list of UShort is assumed. - * If provided, itemCallback is called on each item and must parse the item. - * See examples in tables/gsub.js - */ -Parser.prototype.parseListOfLists = function(itemCallback) { - var offsets = this.parseOffset16List(); - var count = offsets.length; - var relativeOffset = this.relativeOffset; - var list = new Array(count); - for (var i = 0; i < count; i++) { - var start = offsets[i]; - if (start === 0) { - // NULL offset - // Add i as owned property to list. Convenient with assert. - list[i] = undefined; - continue; - } - this.relativeOffset = start; - if (itemCallback) { - var subOffsets = this.parseOffset16List(); - var subList = new Array(subOffsets.length); - for (var j = 0; j < subOffsets.length; j++) { - this.relativeOffset = start + subOffsets[j]; - subList[j] = itemCallback.call(this); - } - list[i] = subList; - } else { - list[i] = this.parseUShortList(); - } - } - this.relativeOffset = relativeOffset; - return list; -}; + case ContextProvider: + var context = workInProgress.type._context; + popProvider(context, workInProgress); + return null; -///// Complex tables parsing ////////////////////////////////// + case OffscreenComponent: + case LegacyHiddenComponent: + popRenderLanes(workInProgress); -// Parse a coverage table in a GSUB, GPOS or GDEF table. -// https://www.microsoft.com/typography/OTSPEC/chapter2.htm -// parser.offset must point to the start of the table containing the coverage. -Parser.prototype.parseCoverage = function() { - var startOffset = this.offset + this.relativeOffset; - var format = this.parseUShort(); - var count = this.parseUShort(); - if (format === 1) { - return { - format: 1, - glyphs: this.parseUShortList(count) - }; - } else if (format === 2) { - var ranges = new Array(count); - for (var i = 0; i < count; i++) { - ranges[i] = { - start: this.parseUShort(), - end: this.parseUShort(), - index: this.parseUShort() - }; - } - return { - format: 2, - ranges: ranges - }; - } - throw new Error('0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.'); -}; + return null; -// Parse a Class Definition Table in a GSUB, GPOS or GDEF table. -// https://www.microsoft.com/typography/OTSPEC/chapter2.htm -Parser.prototype.parseClassDef = function() { - var startOffset = this.offset + this.relativeOffset; - var format = this.parseUShort(); - if (format === 1) { - return { - format: 1, - startGlyph: this.parseUShort(), - classes: this.parseUShortList() - }; - } else if (format === 2) { - return { - format: 2, - ranges: this.parseRecordList({ - start: Parser.uShort, - end: Parser.uShort, - classId: Parser.uShort - }) - }; - } - throw new Error('0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.'); -}; + case CacheComponent: -///// Static methods /////////////////////////////////// -// These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance. + return null; -Parser.list = function(count, itemCallback) { - return function() { - return this.parseList(count, itemCallback); - }; -}; + default: + return null; + } + } -Parser.list32 = function(count, itemCallback) { - return function() { - return this.parseList32(count, itemCallback); - }; -}; + function unwindInterruptedWork(current, interruptedWork, renderLanes) { + // Note: This intentionally doesn't check if we're hydrating because comparing + // to the current tree provider fiber is just as fast and less error-prone. + // Ideally we would have a special version of the work loop only + // for hydration. + popTreeContext(interruptedWork); -Parser.recordList = function(count, recordDescription) { - return function() { - return this.parseRecordList(count, recordDescription); - }; -}; + switch (interruptedWork.tag) { + case ClassComponent: + { + var childContextTypes = interruptedWork.type.childContextTypes; -Parser.recordList32 = function(count, recordDescription) { - return function() { - return this.parseRecordList32(count, recordDescription); - }; -}; + if (childContextTypes !== null && childContextTypes !== undefined) { + popContext(interruptedWork); + } -Parser.pointer = function(description) { - return function() { - return this.parsePointer(description); - }; -}; + break; + } -Parser.pointer32 = function(description) { - return function() { - return this.parsePointer32(description); - }; -}; + case HostRoot: + { -Parser.tag = Parser.prototype.parseTag; -Parser.byte = Parser.prototype.parseByte; -Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; -Parser.uShortList = Parser.prototype.parseUShortList; -Parser.uLong = Parser.offset32 = Parser.prototype.parseULong; -Parser.uLongList = Parser.prototype.parseULongList; -Parser.struct = Parser.prototype.parseStruct; -Parser.coverage = Parser.prototype.parseCoverage; -Parser.classDef = Parser.prototype.parseClassDef; - -///// Script, Feature, Lookup lists /////////////////////////////////////////////// -// https://www.microsoft.com/typography/OTSPEC/chapter2.htm - -var langSysTable = { - reserved: Parser.uShort, - reqFeatureIndex: Parser.uShort, - featureIndexes: Parser.uShortList -}; + popHostContainer(interruptedWork); + popTopLevelContextObject(interruptedWork); + resetWorkInProgressVersions(); + break; + } -Parser.prototype.parseScriptList = function() { - return this.parsePointer(Parser.recordList({ - tag: Parser.tag, - script: Parser.pointer({ - defaultLangSys: Parser.pointer(langSysTable), - langSysRecords: Parser.recordList({ - tag: Parser.tag, - langSys: Parser.pointer(langSysTable) - }) - }) - })) || []; -}; + case HostComponent: + { + popHostContext(interruptedWork); + break; + } -Parser.prototype.parseFeatureList = function() { - return this.parsePointer(Parser.recordList({ - tag: Parser.tag, - feature: Parser.pointer({ - featureParams: Parser.offset16, - lookupListIndexes: Parser.uShortList - }) - })) || []; -}; + case HostPortal: + popHostContainer(interruptedWork); + break; -Parser.prototype.parseLookupList = function(lookupTableParsers) { - return this.parsePointer(Parser.list(Parser.pointer(function() { - var lookupType = this.parseUShort(); - check.argument(1 <= lookupType && lookupType <= 9, 'GPOS/GSUB lookup type ' + lookupType + ' unknown.'); - var lookupFlag = this.parseUShort(); - var useMarkFilteringSet = lookupFlag & 0x10; - return { - lookupType: lookupType, - lookupFlag: lookupFlag, - subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), - markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined - }; - }))) || []; -}; + case SuspenseComponent: + popSuspenseContext(interruptedWork); + break; -Parser.prototype.parseFeatureVariationsList = function() { - return this.parsePointer32(function() { - var majorVersion = this.parseUShort(); - var minorVersion = this.parseUShort(); - check.argument(majorVersion === 1 && minorVersion < 1, 'GPOS/GSUB feature variations table unknown.'); - var featureVariations = this.parseRecordList32({ - conditionSetOffset: Parser.offset32, - featureTableSubstitutionOffset: Parser.offset32 - }); - return featureVariations; - }) || []; -}; + case SuspenseListComponent: + popSuspenseContext(interruptedWork); + break; -var parse = { - getByte: getByte, - getCard8: getByte, - getUShort: getUShort, - getCard16: getUShort, - getShort: getShort, - getULong: getULong, - getFixed: getFixed, - getTag: getTag, - getOffset: getOffset, - getBytes: getBytes, - bytesToString: bytesToString, - Parser: Parser, -}; + case ContextProvider: + var context = interruptedWork.type._context; + popProvider(context, interruptedWork); + break; -// The `cmap` table stores the mappings from characters to glyphs. + case OffscreenComponent: + case LegacyHiddenComponent: + popRenderLanes(interruptedWork); -function parseCmapTableFormat12(cmap, p) { - //Skip reserved. - p.parseUShort(); + break; + } + } - // Length in bytes of the sub-tables. - cmap.length = p.parseULong(); - cmap.language = p.parseULong(); + function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) { + var funcArgs = Array.prototype.slice.call(arguments, 3); - var groupCount; - cmap.groupCount = groupCount = p.parseULong(); - cmap.glyphIndexMap = {}; + try { + func.apply(context, funcArgs); + } catch (error) { + this.onError(error); + } + } - for (var i = 0; i < groupCount; i += 1) { - var startCharCode = p.parseULong(); - var endCharCode = p.parseULong(); - var startGlyphId = p.parseULong(); + var invokeGuardedCallbackImpl = invokeGuardedCallbackProd; - for (var c = startCharCode; c <= endCharCode; c += 1) { - cmap.glyphIndexMap[c] = startGlyphId; - startGlyphId++; - } - } -} + { + // In DEV mode, we swap out invokeGuardedCallback for a special version + // that plays more nicely with the browser's DevTools. The idea is to preserve + // "Pause on exceptions" behavior. Because React wraps all user-provided + // functions in invokeGuardedCallback, and the production version of + // invokeGuardedCallback uses a try-catch, all user exceptions are treated + // like caught exceptions, and the DevTools won't pause unless the developer + // takes the extra step of enabling pause on caught exceptions. This is + // unintuitive, though, because even though React has caught the error, from + // the developer's perspective, the error is uncaught. + // + // To preserve the expected "Pause on exceptions" behavior, we don't use a + // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake + // DOM node, and call the user-provided callback from inside an event handler + // for that fake event. If the callback throws, the error is "captured" using + // a global event handler. But because the error happens in a different + // event loop context, it does not interrupt the normal program flow. + // Effectively, this gives us try-catch behavior without actually using + // try-catch. Neat! + // Check that the browser supports the APIs we need to implement our special + // DEV version of invokeGuardedCallback + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { + var fakeNode = document.createElement('react'); -function parseCmapTableFormat4(cmap, p, data, start, offset) { - // Length in bytes of the sub-tables. - cmap.length = p.parseUShort(); - cmap.language = p.parseUShort(); - - // segCount is stored x 2. - var segCount; - cmap.segCount = segCount = p.parseUShort() >> 1; - - // Skip searchRange, entrySelector, rangeShift. - p.skip('uShort', 3); - - // The "unrolled" mapping from character codes to glyph indices. - cmap.glyphIndexMap = {}; - var endCountParser = new parse.Parser(data, start + offset + 14); - var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2); - var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4); - var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6); - var glyphIndexOffset = start + offset + 16 + segCount * 8; - for (var i = 0; i < segCount - 1; i += 1) { - var glyphIndex = (void 0); - var endCount = endCountParser.parseUShort(); - var startCount = startCountParser.parseUShort(); - var idDelta = idDeltaParser.parseShort(); - var idRangeOffset = idRangeOffsetParser.parseUShort(); - for (var c = startCount; c <= endCount; c += 1) { - if (idRangeOffset !== 0) { - // The idRangeOffset is relative to the current position in the idRangeOffset array. - // Take the current offset in the idRangeOffset array. - glyphIndexOffset = (idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2); - - // Add the value of the idRangeOffset, which will move us into the glyphIndex array. - glyphIndexOffset += idRangeOffset; - - // Then add the character index of the current segment, multiplied by 2 for USHORTs. - glyphIndexOffset += (c - startCount) * 2; - glyphIndex = parse.getUShort(data, glyphIndexOffset); - if (glyphIndex !== 0) { - glyphIndex = (glyphIndex + idDelta) & 0xFFFF; - } - } else { - glyphIndex = (c + idDelta) & 0xFFFF; - } + invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) { + // If document doesn't exist we know for sure we will crash in this method + // when we call document.createEvent(). However this can cause confusing + // errors: https://github.com/facebook/create-react-app/issues/3482 + // So we preemptively throw with a better message instead. + if (typeof document === 'undefined' || document === null) { + throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.'); + } - cmap.glyphIndexMap[c] = glyphIndex; - } - } -} + var evt = document.createEvent('Event'); + var didCall = false; // Keeps track of whether the user-provided callback threw an error. We + // set this to true at the beginning, then set it to false right after + // calling the function. If the function errors, `didError` will never be + // set to false. This strategy works even if the browser is flaky and + // fails to call our global error handler, because it doesn't rely on + // the error event at all. -// Parse the `cmap` table. This table stores the mappings from characters to glyphs. -// There are many available formats, but we only support the Windows format 4 and 12. -// This function returns a `CmapEncoding` object or null if no supported format could be found. -function parseCmapTable(data, start) { - var cmap = {}; - cmap.version = parse.getUShort(data, start); - check.argument(cmap.version === 0, 'cmap table version should be 0.'); - - // The cmap table can contain many sub-tables, each with their own format. - // We're only interested in a "platform 0" (Unicode format) and "platform 3" (Windows format) table. - cmap.numTables = parse.getUShort(data, start + 2); - var offset = -1; - for (var i = cmap.numTables - 1; i >= 0; i -= 1) { - var platformId = parse.getUShort(data, start + 4 + (i * 8)); - var encodingId = parse.getUShort(data, start + 4 + (i * 8) + 2); - if ((platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10)) || - (platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4))) { - offset = parse.getULong(data, start + 4 + (i * 8) + 4); - break; - } - } + var didError = true; // Keeps track of the value of window.event so that we can reset it + // during the callback to let user code access window.event in the + // browsers that support it. - if (offset === -1) { - // There is no cmap table in the font that we support. - throw new Error('No valid cmap sub-tables found.'); - } + var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event + // dispatching: https://github.com/facebook/react/issues/13688 - var p = new parse.Parser(data, start + offset); - cmap.format = p.parseUShort(); + var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); - if (cmap.format === 12) { - parseCmapTableFormat12(cmap, p); - } else if (cmap.format === 4) { - parseCmapTableFormat4(cmap, p, data, start, offset); - } else { - throw new Error('Only format 4 and 12 cmap tables are supported (found format ' + cmap.format + ').'); - } + function restoreAfterDispatch() { + // We immediately remove the callback from event listeners so that + // nested `invokeGuardedCallback` calls do not clash. Otherwise, a + // nested call would trigger the fake event handlers of any call higher + // in the stack. + fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the + // window.event assignment in both IE <= 10 as they throw an error + // "Member not found" in strict mode, and in Firefox which does not + // support window.event. - return cmap; -} + if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) { + window.event = windowEvent; + } + } // Create an event handler for our fake event. We will synchronously + // dispatch our fake event using `dispatchEvent`. Inside the handler, we + // call the user-provided callback. -function addSegment(t, code, glyphIndex) { - t.segments.push({ - end: code, - start: code, - delta: -(code - glyphIndex), - offset: 0, - glyphIndex: glyphIndex - }); -} -function addTerminatorSegment(t) { - t.segments.push({ - end: 0xFFFF, - start: 0xFFFF, - delta: 1, - offset: 0 - }); -} + var funcArgs = Array.prototype.slice.call(arguments, 3); -// Make cmap table, format 4 by default, 12 if needed only -function makeCmapTable(glyphs) { - // Plan 0 is the base Unicode Plan but emojis, for example are on another plan, and needs cmap 12 format (with 32bit) - var isPlan0Only = true; - var i; + function callCallback() { + didCall = true; + restoreAfterDispatch(); + func.apply(context, funcArgs); + didError = false; + } // Create a global error event handler. We use this to capture the value + // that was thrown. It's possible that this error handler will fire more + // than once; for example, if non-React code also calls `dispatchEvent` + // and a handler for that event throws. We should be resilient to most of + // those cases. Even if our error event handler fires more than once, the + // last error event is always used. If the callback actually does error, + // we know that the last error event is the correct one, because it's not + // possible for anything else to have happened in between our callback + // erroring and the code that follows the `dispatchEvent` call below. If + // the callback doesn't error, but the error event was fired, we know to + // ignore it because `didError` will be false, as described above. - // Check if we need to add cmap format 12 or if format 4 only is fine - for (i = glyphs.length - 1; i > 0; i -= 1) { - var g = glyphs.get(i); - if (g.unicode > 65535) { - console.log('Adding CMAP format 12 (needed!)'); - isPlan0Only = false; - break; - } - } - var cmapTable = [ - {name: 'version', type: 'USHORT', value: 0}, - {name: 'numTables', type: 'USHORT', value: isPlan0Only ? 1 : 2}, + var error; // Use this to track whether the error event is ever called. - // CMAP 4 header - {name: 'platformID', type: 'USHORT', value: 3}, - {name: 'encodingID', type: 'USHORT', value: 1}, - {name: 'offset', type: 'ULONG', value: isPlan0Only ? 12 : (12 + 8)} - ]; + var didSetError = false; + var isCrossOriginError = false; - if (!isPlan0Only) - { cmapTable = cmapTable.concat([ - // CMAP 12 header - {name: 'cmap12PlatformID', type: 'USHORT', value: 3}, // We encode only for PlatformID = 3 (Windows) because it is supported everywhere - {name: 'cmap12EncodingID', type: 'USHORT', value: 10}, - {name: 'cmap12Offset', type: 'ULONG', value: 0} - ]); } - - cmapTable = cmapTable.concat([ - // CMAP 4 Subtable - {name: 'format', type: 'USHORT', value: 4}, - {name: 'cmap4Length', type: 'USHORT', value: 0}, - {name: 'language', type: 'USHORT', value: 0}, - {name: 'segCountX2', type: 'USHORT', value: 0}, - {name: 'searchRange', type: 'USHORT', value: 0}, - {name: 'entrySelector', type: 'USHORT', value: 0}, - {name: 'rangeShift', type: 'USHORT', value: 0} - ]); + function handleWindowError(event) { + error = event.error; + didSetError = true; - var t = new table.Table('cmap', cmapTable); + if (error === null && event.colno === 0 && event.lineno === 0) { + isCrossOriginError = true; + } - t.segments = []; - for (i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs.get(i); - for (var j = 0; j < glyph.unicodes.length; j += 1) { - addSegment(t, glyph.unicodes[j], i); - } + if (event.defaultPrevented) { + // Some other error handler has prevented default. + // Browsers silence the error report if this happens. + // We'll remember this to later decide whether to log it or not. + if (error != null && typeof error === 'object') { + try { + error._suppressLogging = true; + } catch (inner) {// Ignore. + } + } + } + } // Create a fake event type. - t.segments = t.segments.sort(function (a, b) { - return a.start - b.start; - }); - } - addTerminatorSegment(t); - - var segCount = t.segments.length; - var segCountToRemove = 0; - - // CMAP 4 - // Set up parallel segment arrays. - var endCounts = []; - var startCounts = []; - var idDeltas = []; - var idRangeOffsets = []; - var glyphIds = []; - - // CMAP 12 - var cmap12Groups = []; - - // Reminder this loop is not following the specification at 100% - // The specification -> find suites of characters and make a group - // Here we're doing one group for each letter - // Doing as the spec can save 8 times (or more) space - for (i = 0; i < segCount; i += 1) { - var segment = t.segments[i]; - - // CMAP 4 - if (segment.end <= 65535 && segment.start <= 65535) { - endCounts = endCounts.concat({name: 'end_' + i, type: 'USHORT', value: segment.end}); - startCounts = startCounts.concat({name: 'start_' + i, type: 'USHORT', value: segment.start}); - idDeltas = idDeltas.concat({name: 'idDelta_' + i, type: 'SHORT', value: segment.delta}); - idRangeOffsets = idRangeOffsets.concat({name: 'idRangeOffset_' + i, type: 'USHORT', value: segment.offset}); - if (segment.glyphId !== undefined) { - glyphIds = glyphIds.concat({name: 'glyph_' + i, type: 'USHORT', value: segment.glyphId}); - } - } else { - // Skip Unicode > 65535 (16bit unsigned max) for CMAP 4, will be added in CMAP 12 - segCountToRemove += 1; - } + var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers - // CMAP 12 - // Skip Terminator Segment - if (!isPlan0Only && segment.glyphIndex !== undefined) { - cmap12Groups = cmap12Groups.concat({name: 'cmap12Start_' + i, type: 'ULONG', value: segment.start}); - cmap12Groups = cmap12Groups.concat({name: 'cmap12End_' + i, type: 'ULONG', value: segment.end}); - cmap12Groups = cmap12Groups.concat({name: 'cmap12Glyph_' + i, type: 'ULONG', value: segment.glyphIndex}); - } - } + window.addEventListener('error', handleWindowError); + fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function + // errors, it will trigger our global error handler. - // CMAP 4 Subtable - t.segCountX2 = (segCount - segCountToRemove) * 2; - t.searchRange = Math.pow(2, Math.floor(Math.log((segCount - segCountToRemove)) / Math.log(2))) * 2; - t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2); - t.rangeShift = t.segCountX2 - t.searchRange; - - t.fields = t.fields.concat(endCounts); - t.fields.push({name: 'reservedPad', type: 'USHORT', value: 0}); - t.fields = t.fields.concat(startCounts); - t.fields = t.fields.concat(idDeltas); - t.fields = t.fields.concat(idRangeOffsets); - t.fields = t.fields.concat(glyphIds); - - t.cmap4Length = 14 + // Subtable header - endCounts.length * 2 + - 2 + // reservedPad - startCounts.length * 2 + - idDeltas.length * 2 + - idRangeOffsets.length * 2 + - glyphIds.length * 2; - - if (!isPlan0Only) { - // CMAP 12 Subtable - var cmap12Length = 16 + // Subtable header - cmap12Groups.length * 4; - - t.cmap12Offset = 12 + (2 * 2) + 4 + t.cmap4Length; - t.fields = t.fields.concat([ - {name: 'cmap12Format', type: 'USHORT', value: 12}, - {name: 'cmap12Reserved', type: 'USHORT', value: 0}, - {name: 'cmap12Length', type: 'ULONG', value: cmap12Length}, - {name: 'cmap12Language', type: 'ULONG', value: 0}, - {name: 'cmap12nGroups', type: 'ULONG', value: cmap12Groups.length / 3} - ]); - - t.fields = t.fields.concat(cmap12Groups); - } + evt.initEvent(evtType, false, false); + fakeNode.dispatchEvent(evt); - return t; -} - -var cmap = { parse: parseCmapTable, make: makeCmapTable }; - -// Glyph encoding - -var cffStandardStrings = [ - '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', - 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', - 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', - 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', - 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', - 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', - 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', - 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', - 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', - 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', - 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', - 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', - 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', - 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', - 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', - 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', - 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', - 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', - 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', - 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', - 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', - 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', - 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff', 'onedotenleader', - 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', - 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior', - 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', - 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl', - 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', - 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', - 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', - 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', - 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', - 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', - 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', - 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', - 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', - 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', - 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', - 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', - 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', - 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', - 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000', - '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold']; - -var cffStandardEncoding = [ - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', - 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', - 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', - 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', - 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', - 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', - 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', - 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', - 'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', - 'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde', - 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron', - 'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '', - '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '', - 'lslash', 'oslash', 'oe', 'germandbls']; - -var cffExpertEncoding = [ - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior', - 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', - 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', - 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', - 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior', - 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', - 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', - 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', - 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', - 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', - 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', - 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior', - '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', - 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', - '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', - 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', - 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', - 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', - 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', - 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', - 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', - 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', - 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall']; - -var standardNames = [ - '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', - 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', - 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', - 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', - 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', - 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', - 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', - 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', - 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', - 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', - 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', - 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', - 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', - 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', - 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', - 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', - 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', - 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', - 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', - 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth', - 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior', - 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla', - 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat']; + if (windowEventDescriptor) { + Object.defineProperty(window, 'event', windowEventDescriptor); + } -/** - * This is the encoding used for fonts created from scratch. - * It loops through all glyphs and finds the appropriate unicode value. - * Since it's linear time, other encodings will be faster. - * @exports opentype.DefaultEncoding - * @class - * @constructor - * @param {opentype.Font} - */ -function DefaultEncoding(font) { - this.font = font; -} - -DefaultEncoding.prototype.charToGlyphIndex = function(c) { - var code = c.codePointAt(0); - var glyphs = this.font.glyphs; - if (glyphs) { - for (var i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs.get(i); - for (var j = 0; j < glyph.unicodes.length; j += 1) { - if (glyph.unicodes[j] === code) { - return i; - } - } - } - } - return null; -}; + if (didCall && didError) { + if (!didSetError) { + // The callback errored, but the error event never fired. + // eslint-disable-next-line react-internal/prod-error-codes + error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); + } else if (isCrossOriginError) { + // eslint-disable-next-line react-internal/prod-error-codes + error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.'); + } -/** - * @exports opentype.CffEncoding - * @class - * @constructor - * @param {string} encoding - The encoding - * @param {Array} charset - The character set. - */ -function CffEncoding(encoding, charset) { - this.encoding = encoding; - this.charset = charset; -} + this.onError(error); + } // Remove our event listeners -/** - * @param {string} s - The character - * @return {number} The index. - */ -CffEncoding.prototype.charToGlyphIndex = function(s) { - var code = s.codePointAt(0); - var charName = this.encoding[code]; - return this.charset.indexOf(charName); -}; -// Drawing utility functions. + window.removeEventListener('error', handleWindowError); -// Draw a line on the given context from point `x1,y1` to point `x2,y2`. -function line(ctx, x1, y1, x2, y2) { - ctx.beginPath(); - ctx.moveTo(x1, y1); - ctx.lineTo(x2, y2); - ctx.stroke(); -} + if (!didCall) { + // Something went really wrong, and our event was not dispatched. + // https://github.com/facebook/react/issues/16734 + // https://github.com/facebook/react/issues/16585 + // Fall back to the production implementation. + restoreAfterDispatch(); + return invokeGuardedCallbackProd.apply(this, arguments); + } + }; + } + } -var draw = { line: line }; + var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; -// The Glyph object -// import glyf from './tables/glyf' Can't be imported here, because it's a circular dependency + var hasError = false; + var caughtError = null; // Used by event system to capture/rethrow the first error. + var reporter = { + onError: function (error) { + hasError = true; + caughtError = error; + } + }; + /** + * Call a function while guarding against errors that happens within it. + * Returns an error if it throws, otherwise null. + * + * In production, this is implemented using a try-catch. The reason we don't + * use a try-catch directly is so that we can swap out a different + * implementation in DEV mode. + * + * @param {String} name of the guard to use for logging or debugging + * @param {Function} func The function to invoke + * @param {*} context The context to use when calling the function + * @param {...*} args Arguments for function + */ -function getPathDefinition(glyph, path) { - var _path = path || new Path(); - return { - configurable: true, + function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { + hasError = false; + caughtError = null; + invokeGuardedCallbackImpl$1.apply(reporter, arguments); + } + function hasCaughtError() { + return hasError; + } + function clearCaughtError() { + if (hasError) { + var error = caughtError; + hasError = false; + caughtError = null; + return error; + } else { + throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.'); + } + } - get: function() { - if (typeof _path === 'function') { - _path = _path(); - } + var didWarnAboutUndefinedSnapshotBeforeUpdate = null; - return _path; - }, + { + didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); + } // Used during the commit phase to track the state of the Offscreen component stack. + // Allows us to avoid traversing the return path to find the nearest Offscreen ancestor. + // Only used when enableSuspenseLayoutEffectSemantics is enabled. - set: function(p) { - _path = p; - } - }; -} -/** - * @typedef GlyphOptions - * @type Object - * @property {string} [name] - The glyph name - * @property {number} [unicode] - * @property {Array} [unicodes] - * @property {number} [xMin] - * @property {number} [yMin] - * @property {number} [xMax] - * @property {number} [yMax] - * @property {number} [advanceWidth] - */ -// A Glyph is an individual mark that often corresponds to a character. -// Some glyphs, such as ligatures, are a combination of many characters. -// Glyphs are the basic building blocks of a font. -// -// The `Glyph` class contains utility methods for drawing the path and its points. -/** - * @exports opentype.Glyph - * @class - * @param {GlyphOptions} - * @constructor - */ -function Glyph(options) { - // By putting all the code on a prototype function (which is only declared once) - // we reduce the memory requirements for larger fonts by some 2% - this.bindConstructorValues(options); -} + var offscreenSubtreeIsHidden = false; + var offscreenSubtreeWasHidden = false; + var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; + var nextEffect = null; // Used for Profiling builds to track updaters. -/** - * @param {GlyphOptions} - */ -Glyph.prototype.bindConstructorValues = function(options) { - this.index = options.index || 0; - - // These three values cannot be deferred for memory optimization: - this.name = options.name || null; - this.unicode = options.unicode || undefined; - this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : []; - - // But by binding these values only when necessary, we reduce can - // the memory requirements by almost 3% for larger fonts. - if ('xMin' in options) { - this.xMin = options.xMin; - } + var inProgressLanes = null; + var inProgressRoot = null; - if ('yMin' in options) { - this.yMin = options.yMin; - } + function reportUncaughtErrorInDEV(error) { + // Wrapping each small part of the commit phase into a guarded + // callback is a bit too slow (https://github.com/facebook/react/pull/21666). + // But we rely on it to surface errors to DEV tools like overlays + // (https://github.com/facebook/react/issues/21712). + // As a compromise, rethrow only caught errors in a guard. + { + invokeGuardedCallback(null, function () { + throw error; + }); + clearCaughtError(); + } + } - if ('xMax' in options) { - this.xMax = options.xMax; - } + var callComponentWillUnmountWithTimer = function (current, instance) { + instance.props = current.memoizedProps; + instance.state = current.memoizedState; - if ('yMax' in options) { - this.yMax = options.yMax; - } + if ( current.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentWillUnmount(); + } finally { + recordLayoutEffectDuration(current); + } + } else { + instance.componentWillUnmount(); + } + }; // Capture errors so they don't interrupt mounting. - if ('advanceWidth' in options) { - this.advanceWidth = options.advanceWidth; - } - // The path for a glyph is the most memory intensive, and is bound as a value - // with a getter/setter to ensure we actually do path parsing only once the - // path is actually needed by anything. - Object.defineProperty(this, 'path', getPathDefinition(this, options.path)); -}; + function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) { + try { + commitHookEffectListMount(Layout, current); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } // Capture errors so they don't interrupt unmounting. -/** - * @param {number} - */ -Glyph.prototype.addUnicode = function(unicode) { - if (this.unicodes.length === 0) { - this.unicode = unicode; - } - this.unicodes.push(unicode); -}; + function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) { + try { + callComponentWillUnmountWithTimer(current, instance); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } // Capture errors so they don't interrupt mounting. -/** - * Calculate the minimum bounding box for this glyph. - * @return {opentype.BoundingBox} - */ -Glyph.prototype.getBoundingBox = function() { - return this.path.getBoundingBox(); -}; -/** - * Convert the glyph to a Path we can draw on a drawing context. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {Object=} options - xScale, yScale to stretch the glyph. - * @param {opentype.Font} if hinting is to be used, the font - * @return {opentype.Path} - */ -Glyph.prototype.getPath = function(x, y, fontSize, options, font) { - x = x !== undefined ? x : 0; - y = y !== undefined ? y : 0; - fontSize = fontSize !== undefined ? fontSize : 72; - var commands; - var hPoints; - if (!options) { options = { }; } - var xScale = options.xScale; - var yScale = options.yScale; - - if (options.hinting && font && font.hinting) { - // in case of hinting, the hinting engine takes care - // of scaling the points (not the path) before hinting. - hPoints = this.path && font.hinting.exec(this, fontSize); - // in case the hinting engine failed hPoints is undefined - // and thus reverts to plain rending - } + function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) { + try { + instance.componentDidMount(); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } // Capture errors so they don't interrupt mounting. - if (hPoints) { - // Call font.hinting.getCommands instead of `glyf.getPath(hPoints).commands` to avoid a circular dependency - commands = font.hinting.getCommands(hPoints); - x = Math.round(x); - y = Math.round(y); - // TODO in case of hinting xyScaling is not yet supported - xScale = yScale = 1; - } else { - commands = this.path.commands; - var scale = 1 / (this.path.unitsPerEm || 1000) * fontSize; - if (xScale === undefined) { xScale = scale; } - if (yScale === undefined) { yScale = scale; } - } - var p = new Path(); - for (var i = 0; i < commands.length; i += 1) { - var cmd = commands[i]; - if (cmd.type === 'M') { - p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); - } else if (cmd.type === 'L') { - p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); - } else if (cmd.type === 'Q') { - p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), - x + (cmd.x * xScale), y + (-cmd.y * yScale)); - } else if (cmd.type === 'C') { - p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), - x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale), - x + (cmd.x * xScale), y + (-cmd.y * yScale)); - } else if (cmd.type === 'Z') { - p.closePath(); - } - } + function safelyAttachRef(current, nearestMountedAncestor) { + try { + commitAttachRef(current); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } - return p; -}; + function safelyDetachRef(current, nearestMountedAncestor) { + var ref = current.ref; -/** - * Split the glyph into contours. - * This function is here for backwards compatibility, and to - * provide raw access to the TrueType glyph outlines. - * @return {Array} - */ -Glyph.prototype.getContours = function() { - if (this.points === undefined) { - return []; - } + if (ref !== null) { + if (typeof ref === 'function') { + var retVal; - var contours = []; - var currentContour = []; - for (var i = 0; i < this.points.length; i += 1) { - var pt = this.points[i]; - currentContour.push(pt); - if (pt.lastPointOfContour) { - contours.push(currentContour); - currentContour = []; - } - } + try { + if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + retVal = ref(null); + } finally { + recordLayoutEffectDuration(current); + } + } else { + retVal = ref(null); + } + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } - check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); - return contours; -}; + { + if (typeof retVal === 'function') { + error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current)); + } + } + } else { + ref.current = null; + } + } + } -/** - * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph. - * @return {Object} - */ -Glyph.prototype.getMetrics = function() { - var commands = this.path.commands; - var xCoords = []; - var yCoords = []; - for (var i = 0; i < commands.length; i += 1) { - var cmd = commands[i]; - if (cmd.type !== 'Z') { - xCoords.push(cmd.x); - yCoords.push(cmd.y); - } + function safelyCallDestroy(current, nearestMountedAncestor, destroy) { + try { + destroy(); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } + var shouldFireAfterActiveInstanceBlur = false; + function commitBeforeMutationEffects(root, firstChild) { + prepareForCommit(root.containerInfo); + nextEffect = firstChild; + commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber - if (cmd.type === 'Q' || cmd.type === 'C') { - xCoords.push(cmd.x1); - yCoords.push(cmd.y1); - } + var shouldFire = shouldFireAfterActiveInstanceBlur; + shouldFireAfterActiveInstanceBlur = false; + return shouldFire; + } - if (cmd.type === 'C') { - xCoords.push(cmd.x2); - yCoords.push(cmd.y2); - } - } + function commitBeforeMutationEffects_begin() { + while (nextEffect !== null) { + var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur. - var metrics = { - xMin: Math.min.apply(null, xCoords), - yMin: Math.min.apply(null, yCoords), - xMax: Math.max.apply(null, xCoords), - yMax: Math.max.apply(null, yCoords), - leftSideBearing: this.leftSideBearing - }; + var child = fiber.child; - if (!isFinite(metrics.xMin)) { - metrics.xMin = 0; - } + if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) { + ensureCorrectReturnPointer(child, fiber); + nextEffect = child; + } else { + commitBeforeMutationEffects_complete(); + } + } + } - if (!isFinite(metrics.xMax)) { - metrics.xMax = this.advanceWidth; - } + function commitBeforeMutationEffects_complete() { + while (nextEffect !== null) { + var fiber = nextEffect; + setCurrentFiber(fiber); - if (!isFinite(metrics.yMin)) { - metrics.yMin = 0; - } + try { + commitBeforeMutationEffectsOnFiber(fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - if (!isFinite(metrics.yMax)) { - metrics.yMax = 0; - } + resetCurrentFiber(); + var sibling = fiber.sibling; - metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); - return metrics; -}; + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } -/** - * Draw the glyph on the given context. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {Object=} options - xScale, yScale to stretch the glyph. - */ -Glyph.prototype.draw = function(ctx, x, y, fontSize, options) { - this.getPath(x, y, fontSize, options).draw(ctx); -}; + nextEffect = fiber.return; + } + } -/** - * Draw the points of the glyph. - * On-curve points will be drawn in blue, off-curve points will be drawn in red. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - */ -Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) { - function drawCircles(l, x, y, scale) { - ctx.beginPath(); - for (var j = 0; j < l.length; j += 1) { - ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale)); - ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, Math.PI * 2, false); - } + function commitBeforeMutationEffectsOnFiber(finishedWork) { + var current = finishedWork.alternate; + var flags = finishedWork.flags; - ctx.closePath(); - ctx.fill(); - } + if ((flags & Snapshot) !== NoFlags) { + setCurrentFiber(finishedWork); - x = x !== undefined ? x : 0; - y = y !== undefined ? y : 0; - fontSize = fontSize !== undefined ? fontSize : 24; - var scale = 1 / this.path.unitsPerEm * fontSize; - - var blueCircles = []; - var redCircles = []; - var path = this.path; - for (var i = 0; i < path.commands.length; i += 1) { - var cmd = path.commands[i]; - if (cmd.x !== undefined) { - blueCircles.push({x: cmd.x, y: -cmd.y}); - } + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + break; + } - if (cmd.x1 !== undefined) { - redCircles.push({x: cmd.x1, y: -cmd.y1}); - } + case ClassComponent: + { + if (current !== null) { + var prevProps = current.memoizedProps; + var prevState = current.memoizedState; + var instance = finishedWork.stateNode; // We could update instance props and state here, + // but instead we rely on them being set during last render. + // TODO: revisit this when we implement resuming. - if (cmd.x2 !== undefined) { - redCircles.push({x: cmd.x2, y: -cmd.y2}); - } - } + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + + if (instance.state !== finishedWork.memoizedState) { + error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + } + } - ctx.fillStyle = 'blue'; - drawCircles(blueCircles, x, y, scale); - ctx.fillStyle = 'red'; - drawCircles(redCircles, x, y, scale); -}; + var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState); -/** - * Draw lines indicating important font measurements. - * Black lines indicate the origin of the coordinate system (point 0,0). - * Blue lines indicate the glyph bounding box. - * Green line indicates the advance width of the glyph. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - */ -Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) { - var scale; - x = x !== undefined ? x : 0; - y = y !== undefined ? y : 0; - fontSize = fontSize !== undefined ? fontSize : 24; - scale = 1 / this.path.unitsPerEm * fontSize; - ctx.lineWidth = 1; - - // Draw the origin - ctx.strokeStyle = 'black'; - draw.line(ctx, x, -10000, x, 10000); - draw.line(ctx, -10000, y, 10000, y); - - // This code is here due to memory optimization: by not using - // defaults in the constructor, we save a notable amount of memory. - var xMin = this.xMin || 0; - var yMin = this.yMin || 0; - var xMax = this.xMax || 0; - var yMax = this.yMax || 0; - var advanceWidth = this.advanceWidth || 0; - - // Draw the glyph box - ctx.strokeStyle = 'blue'; - draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000); - draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000); - draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale)); - draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale)); - - // Draw the advance width - ctx.strokeStyle = 'green'; - draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000); -}; + { + var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; -// The GlyphSet object + if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { + didWarnSet.add(finishedWork.type); -// Define a property on the glyph that depends on the path being loaded. -function defineDependentProperty(glyph, externalName, internalName) { - Object.defineProperty(glyph, externalName, { - get: function() { - // Request the path property to make sure the path is loaded. - glyph.path; // jshint ignore:line - return glyph[internalName]; - }, - set: function(newValue) { - glyph[internalName] = newValue; - }, - enumerable: true, - configurable: true - }); -} + error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork)); + } + } -/** - * A GlyphSet represents all glyphs available in the font, but modelled using - * a deferred glyph loader, for retrieving glyphs only once they are absolutely - * necessary, to keep the memory footprint down. - * @exports opentype.GlyphSet - * @class - * @param {opentype.Font} - * @param {Array} - */ -function GlyphSet(font, glyphs) { - this.font = font; - this.glyphs = {}; - if (Array.isArray(glyphs)) { - for (var i = 0; i < glyphs.length; i++) { - var glyph = glyphs[i]; - glyph.path.unitsPerEm = font.unitsPerEm; - this.glyphs[i] = glyph; - } - } + instance.__reactInternalSnapshotBeforeUpdate = snapshot; + } - this.length = (glyphs && glyphs.length) || 0; -} + break; + } -/** - * @param {number} index - * @return {opentype.Glyph} - */ -GlyphSet.prototype.get = function(index) { - // this.glyphs[index] is 'undefined' when low memory mode is on. glyph is pushed on request only. - if (this.glyphs[index] === undefined) { - this.font._push(index); - if (typeof this.glyphs[index] === 'function') { - this.glyphs[index] = this.glyphs[index](); - } + case HostRoot: + { + if (supportsMutation) { + var root = finishedWork.stateNode; + clearContainer(root.containerInfo); + } - var glyph = this.glyphs[index]; - var unicodeObj = this.font._IndexToUnicodeMap[index]; + break; + } - if (unicodeObj) { - for (var j = 0; j < unicodeObj.unicodes.length; j++) - { glyph.addUnicode(unicodeObj.unicodes[j]); } - } + case HostComponent: + case HostText: + case HostPortal: + case IncompleteClassComponent: + // Nothing to do for these component types + break; - if (this.font.cffEncoding) { - if (this.font.isCIDFont) { - glyph.name = 'gid' + index; - } else { - glyph.name = this.font.cffEncoding.charset[index]; - } - } else if (this.font.glyphNames.names) { - glyph.name = this.font.glyphNames.glyphIndexToName(index); - } + default: + { + throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); + } + } - this.glyphs[index].advanceWidth = this.font._hmtxTableData[index].advanceWidth; - this.glyphs[index].leftSideBearing = this.font._hmtxTableData[index].leftSideBearing; - } else { - if (typeof this.glyphs[index] === 'function') { - this.glyphs[index] = this.glyphs[index](); - } - } + resetCurrentFiber(); + } + } - return this.glyphs[index]; -}; + function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) { + var updateQueue = finishedWork.updateQueue; + var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; -/** - * @param {number} index - * @param {Object} - */ -GlyphSet.prototype.push = function(index, loader) { - this.glyphs[index] = loader; - this.length++; -}; + if (lastEffect !== null) { + var firstEffect = lastEffect.next; + var effect = firstEffect; -/** - * @alias opentype.glyphLoader - * @param {opentype.Font} font - * @param {number} index - * @return {opentype.Glyph} - */ -function glyphLoader(font, index) { - return new Glyph({index: index, font: font}); -} + do { + if ((effect.tag & flags) === flags) { + // Unmount + var destroy = effect.destroy; + effect.destroy = undefined; -/** - * Generate a stub glyph that can be filled with all metadata *except* - * the "points" and "path" properties, which must be loaded only once - * the glyph's path is actually requested for text shaping. - * @alias opentype.ttfGlyphLoader - * @param {opentype.Font} font - * @param {number} index - * @param {Function} parseGlyph - * @param {Object} data - * @param {number} position - * @param {Function} buildPath - * @return {opentype.Glyph} - */ -function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) { - return function() { - var glyph = new Glyph({index: index, font: font}); + if (destroy !== undefined) { + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectUnmountStarted(finishedWork); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectUnmountStarted(finishedWork); + } + } - glyph.path = function() { - parseGlyph(glyph, data, position); - var path = buildPath(font.glyphs, glyph); - path.unitsPerEm = font.unitsPerEm; - return path; - }; + safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); - defineDependentProperty(glyph, 'xMin', '_xMin'); - defineDependentProperty(glyph, 'xMax', '_xMax'); - defineDependentProperty(glyph, 'yMin', '_yMin'); - defineDependentProperty(glyph, 'yMax', '_yMax'); + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectUnmountStopped(); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectUnmountStopped(); + } + } + } + } - return glyph; - }; -} -/** - * @alias opentype.cffGlyphLoader - * @param {opentype.Font} font - * @param {number} index - * @param {Function} parseCFFCharstring - * @param {string} charstring - * @return {opentype.Glyph} - */ -function cffGlyphLoader(font, index, parseCFFCharstring, charstring) { - return function() { - var glyph = new Glyph({index: index, font: font}); + effect = effect.next; + } while (effect !== firstEffect); + } + } - glyph.path = function() { - var path = parseCFFCharstring(font, glyph, charstring); - path.unitsPerEm = font.unitsPerEm; - return path; - }; + function commitHookEffectListMount(flags, finishedWork) { + var updateQueue = finishedWork.updateQueue; + var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - return glyph; - }; -} + if (lastEffect !== null) { + var firstEffect = lastEffect.next; + var effect = firstEffect; -var glyphset = { GlyphSet: GlyphSet, glyphLoader: glyphLoader, ttfGlyphLoader: ttfGlyphLoader, cffGlyphLoader: cffGlyphLoader }; + do { + if ((effect.tag & flags) === flags) { + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectMountStarted(finishedWork); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectMountStarted(finishedWork); + } + } // Mount -// The `CFF` table contains the glyph outlines in PostScript format. -// Custom equals function that can also check lists. -function equals(a, b) { - if (a === b) { - return true; - } else if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return false; - } + var create = effect.create; + effect.destroy = create(); - for (var i = 0; i < a.length; i += 1) { - if (!equals(a[i], b[i])) { - return false; - } - } + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectMountStopped(); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectMountStopped(); + } + } - return true; - } else { - return false; - } -} + { + var destroy = effect.destroy; -// Subroutines are encoded using the negative half of the number space. -// See type 2 chapter 4.7 "Subroutine operators". -function calcCFFSubroutineBias(subrs) { - var bias; - if (subrs.length < 1240) { - bias = 107; - } else if (subrs.length < 33900) { - bias = 1131; - } else { - bias = 32768; - } + if (destroy !== undefined && typeof destroy !== 'function') { + var hookName = void 0; - return bias; -} - -// Parse a `CFF` INDEX array. -// An index array consists of a list of offsets, then a list of objects at those offsets. -function parseCFFIndex(data, start, conversionFn) { - var offsets = []; - var objects = []; - var count = parse.getCard16(data, start); - var objectOffset; - var endOffset; - if (count !== 0) { - var offsetSize = parse.getByte(data, start + 2); - objectOffset = start + ((count + 1) * offsetSize) + 2; - var pos = start + 3; - for (var i = 0; i < count + 1; i += 1) { - offsets.push(parse.getOffset(data, pos, offsetSize)); - pos += offsetSize; - } + if ((effect.tag & Layout) !== NoFlags) { + hookName = 'useLayoutEffect'; + } else if ((effect.tag & Insertion) !== NoFlags) { + hookName = 'useInsertionEffect'; + } else { + hookName = 'useEffect'; + } - // The total size of the index array is 4 header bytes + the value of the last offset. - endOffset = objectOffset + offsets[count]; - } else { - endOffset = start + 2; - } + var addendum = void 0; - for (var i$1 = 0; i$1 < offsets.length - 1; i$1 += 1) { - var value = parse.getBytes(data, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]); - if (conversionFn) { - value = conversionFn(value); - } + if (destroy === null) { + addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).'; + } else if (typeof destroy.then === 'function') { + addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching'; + } else { + addendum = ' You returned: ' + destroy; + } - objects.push(value); - } + error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum); + } + } + } - return {objects: objects, startOffset: start, endOffset: endOffset}; -} - -function parseCFFIndexLowMemory(data, start) { - var offsets = []; - var count = parse.getCard16(data, start); - var objectOffset; - var endOffset; - if (count !== 0) { - var offsetSize = parse.getByte(data, start + 2); - objectOffset = start + ((count + 1) * offsetSize) + 2; - var pos = start + 3; - for (var i = 0; i < count + 1; i += 1) { - offsets.push(parse.getOffset(data, pos, offsetSize)); - pos += offsetSize; - } + effect = effect.next; + } while (effect !== firstEffect); + } + } - // The total size of the index array is 4 header bytes + the value of the last offset. - endOffset = objectOffset + offsets[count]; - } else { - endOffset = start + 2; - } + function commitPassiveEffectDurations(finishedRoot, finishedWork) { + { + // Only Profilers with work in their subtree will have an Update effect scheduled. + if ((finishedWork.flags & Update) !== NoFlags) { + switch (finishedWork.tag) { + case Profiler: + { + var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration; + var _finishedWork$memoize = finishedWork.memoizedProps, + id = _finishedWork$memoize.id, + onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase. + // It does not get reset until the start of the next commit phase. - return {offsets: offsets, startOffset: start, endOffset: endOffset}; -} -function getCffIndexObject(i, offsets, data, start, conversionFn) { - var count = parse.getCard16(data, start); - var objectOffset = 0; - if (count !== 0) { - var offsetSize = parse.getByte(data, start + 2); - objectOffset = start + ((count + 1) * offsetSize) + 2; - } + var commitTime = getCommitTime(); + var phase = finishedWork.alternate === null ? 'mount' : 'update'; - var value = parse.getBytes(data, objectOffset + offsets[i], objectOffset + offsets[i + 1]); - if (conversionFn) { - value = conversionFn(value); - } - return value; -} + { + if (isCurrentUpdateNested()) { + phase = 'nested-update'; + } + } -// Parse a `CFF` DICT real value. -function parseFloatOperand(parser) { - var s = ''; - var eof = 15; - var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-']; - while (true) { - var b = parser.parseByte(); - var n1 = b >> 4; - var n2 = b & 15; + if (typeof onPostCommit === 'function') { + onPostCommit(id, phase, passiveEffectDuration, commitTime); + } // Bubble times to the next nearest ancestor Profiler. + // After we process that Profiler, we'll bubble further up. - if (n1 === eof) { - break; - } - s += lookup[n1]; + var parentFiber = finishedWork.return; - if (n2 === eof) { - break; - } + outer: while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + root.passiveEffectDuration += passiveEffectDuration; + break outer; - s += lookup[n2]; - } + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.passiveEffectDuration += passiveEffectDuration; + break outer; + } - return parseFloat(s); -} + parentFiber = parentFiber.return; + } -// Parse a `CFF` DICT operand. -function parseOperand(parser, b0) { - var b1; - var b2; - var b3; - var b4; - if (b0 === 28) { - b1 = parser.parseByte(); - b2 = parser.parseByte(); - return b1 << 8 | b2; - } + break; + } + } + } + } + } - if (b0 === 29) { - b1 = parser.parseByte(); - b2 = parser.parseByte(); - b3 = parser.parseByte(); - b4 = parser.parseByte(); - return b1 << 24 | b2 << 16 | b3 << 8 | b4; - } + function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) { + if ((finishedWork.flags & LayoutMask) !== NoFlags) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( !offscreenSubtreeWasHidden) { + // At this point layout effects have already been destroyed (during mutation phase). + // This is done to prevent sibling component effects from interfering with each other, + // e.g. a destroy function in one component should never override a ref set + // by a create function in another component during the same commit. + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListMount(Layout | HasEffect, finishedWork); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + commitHookEffectListMount(Layout | HasEffect, finishedWork); + } + } - if (b0 === 30) { - return parseFloatOperand(parser); - } + break; + } - if (b0 >= 32 && b0 <= 246) { - return b0 - 139; - } + case ClassComponent: + { + var instance = finishedWork.stateNode; - if (b0 >= 247 && b0 <= 250) { - b1 = parser.parseByte(); - return (b0 - 247) * 256 + b1 + 108; - } + if (finishedWork.flags & Update) { + if (!offscreenSubtreeWasHidden) { + if (current === null) { + // We could update instance props and state here, + // but instead we rely on them being set during last render. + // TODO: revisit this when we implement resuming. + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } - if (b0 >= 251 && b0 <= 254) { - b1 = parser.parseByte(); - return -(b0 - 251) * 256 - b1 - 108; - } + if (instance.state !== finishedWork.memoizedState) { + error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + } + } - throw new Error('Invalid b0 ' + b0); -} + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentDidMount(); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + instance.componentDidMount(); + } + } else { + var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps); + var prevState = current.memoizedState; // We could update instance props and state here, + // but instead we rely on them being set during last render. + // TODO: revisit this when we implement resuming. -// Convert the entries returned by `parseDict` to a proper dictionary. -// If a value is a list of one, it is unpacked. -function entriesToObject(entries) { - var o = {}; - for (var i = 0; i < entries.length; i += 1) { - var key = entries[i][0]; - var values = entries[i][1]; - var value = (void 0); - if (values.length === 1) { - value = values[0]; - } else { - value = values; - } + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } - if (o.hasOwnProperty(key) && !isNaN(o[key])) { - throw new Error('Object ' + o + ' already has key ' + key); - } + if (instance.state !== finishedWork.memoizedState) { + error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + } + } - o[key] = value; - } + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); + } + } + } + } // TODO: I think this is now always non-null by the time it reaches the + // commit phase. Consider removing the type check. - return o; -} -// Parse a `CFF` DICT object. -// A dictionary contains key-value pairs in a compact tokenized format. -function parseCFFDict(data, start, size) { - start = start !== undefined ? start : 0; - var parser = new parse.Parser(data, start); - var entries = []; - var operands = []; - size = size !== undefined ? size : data.length; + var updateQueue = finishedWork.updateQueue; - while (parser.relativeOffset < size) { - var op = parser.parseByte(); + if (updateQueue !== null) { + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } - // The first byte for each dict item distinguishes between operator (key) and operand (value). - // Values <= 21 are operators. - if (op <= 21) { - // Two-byte operators have an initial escape byte of 12. - if (op === 12) { - op = 1200 + parser.parseByte(); - } + if (instance.state !== finishedWork.memoizedState) { + error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + } + } // We could update instance props and state here, + // but instead we rely on them being set during last render. + // TODO: revisit this when we implement resuming. - entries.push([op, operands]); - operands = []; - } else { - // Since the operands (values) come before the operators (keys), we store all operands in a list - // until we encounter an operator. - operands.push(parseOperand(parser, op)); - } - } - return entriesToObject(entries); -} + commitUpdateQueue(finishedWork, updateQueue, instance); + } -// Given a String Index (SID), return the value of the string. -// Strings below index 392 are standard CFF strings and are not encoded in the font. -function getCFFString(strings, index) { - if (index <= 390) { - index = cffStandardStrings[index]; - } else { - index = strings[index - 391]; - } + break; + } - return index; -} + case HostRoot: + { + // TODO: I think this is now always non-null by the time it reaches the + // commit phase. Consider removing the type check. + var _updateQueue = finishedWork.updateQueue; -// Interpret a dictionary and return a new dictionary with readable keys and values for missing entries. -// This function takes `meta` which is a list of objects containing `operand`, `name` and `default`. -function interpretDict(dict, meta, strings) { - var newDict = {}; - var value; + if (_updateQueue !== null) { + var _instance = null; - // Because we also want to include missing values, we start out from the meta list - // and lookup values in the dict. - for (var i = 0; i < meta.length; i += 1) { - var m = meta[i]; + if (finishedWork.child !== null) { + switch (finishedWork.child.tag) { + case HostComponent: + _instance = getPublicInstance(finishedWork.child.stateNode); + break; - if (Array.isArray(m.type)) { - var values = []; - values.length = m.type.length; - for (var j = 0; j < m.type.length; j++) { - value = dict[m.op] !== undefined ? dict[m.op][j] : undefined; - if (value === undefined) { - value = m.value !== undefined && m.value[j] !== undefined ? m.value[j] : null; - } - if (m.type[j] === 'SID') { - value = getCFFString(strings, value); - } - values[j] = value; - } - newDict[m.name] = values; - } else { - value = dict[m.op]; - if (value === undefined) { - value = m.value !== undefined ? m.value : null; - } + case ClassComponent: + _instance = finishedWork.child.stateNode; + break; + } + } - if (m.type === 'SID') { - value = getCFFString(strings, value); - } - newDict[m.name] = value; - } - } + commitUpdateQueue(finishedWork, _updateQueue, _instance); + } - return newDict; -} - -// Parse the CFF header. -function parseCFFHeader(data, start) { - var header = {}; - header.formatMajor = parse.getCard8(data, start); - header.formatMinor = parse.getCard8(data, start + 1); - header.size = parse.getCard8(data, start + 2); - header.offsetSize = parse.getCard8(data, start + 3); - header.startOffset = start; - header.endOffset = start + 4; - return header; -} - -var TOP_DICT_META = [ - {name: 'version', op: 0, type: 'SID'}, - {name: 'notice', op: 1, type: 'SID'}, - {name: 'copyright', op: 1200, type: 'SID'}, - {name: 'fullName', op: 2, type: 'SID'}, - {name: 'familyName', op: 3, type: 'SID'}, - {name: 'weight', op: 4, type: 'SID'}, - {name: 'isFixedPitch', op: 1201, type: 'number', value: 0}, - {name: 'italicAngle', op: 1202, type: 'number', value: 0}, - {name: 'underlinePosition', op: 1203, type: 'number', value: -100}, - {name: 'underlineThickness', op: 1204, type: 'number', value: 50}, - {name: 'paintType', op: 1205, type: 'number', value: 0}, - {name: 'charstringType', op: 1206, type: 'number', value: 2}, - { - name: 'fontMatrix', - op: 1207, - type: ['real', 'real', 'real', 'real', 'real', 'real'], - value: [0.001, 0, 0, 0.001, 0, 0] - }, - {name: 'uniqueId', op: 13, type: 'number'}, - {name: 'fontBBox', op: 5, type: ['number', 'number', 'number', 'number'], value: [0, 0, 0, 0]}, - {name: 'strokeWidth', op: 1208, type: 'number', value: 0}, - {name: 'xuid', op: 14, type: [], value: null}, - {name: 'charset', op: 15, type: 'offset', value: 0}, - {name: 'encoding', op: 16, type: 'offset', value: 0}, - {name: 'charStrings', op: 17, type: 'offset', value: 0}, - {name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0]}, - {name: 'ros', op: 1230, type: ['SID', 'SID', 'number']}, - {name: 'cidFontVersion', op: 1231, type: 'number', value: 0}, - {name: 'cidFontRevision', op: 1232, type: 'number', value: 0}, - {name: 'cidFontType', op: 1233, type: 'number', value: 0}, - {name: 'cidCount', op: 1234, type: 'number', value: 8720}, - {name: 'uidBase', op: 1235, type: 'number'}, - {name: 'fdArray', op: 1236, type: 'offset'}, - {name: 'fdSelect', op: 1237, type: 'offset'}, - {name: 'fontName', op: 1238, type: 'SID'} -]; + break; + } -var PRIVATE_DICT_META = [ - {name: 'subrs', op: 19, type: 'offset', value: 0}, - {name: 'defaultWidthX', op: 20, type: 'number', value: 0}, - {name: 'nominalWidthX', op: 21, type: 'number', value: 0} -]; + case HostComponent: + { + var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted + // (eg DOM renderer may schedule auto-focus for inputs and form controls). + // These effects should only be committed when components are first mounted, + // aka when there is no current/alternate. -// Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary. -// The top dictionary contains the essential metadata for the font, together with the private dictionary. -function parseCFFTopDict(data, strings) { - var dict = parseCFFDict(data, 0, data.byteLength); - return interpretDict(dict, TOP_DICT_META, strings); -} + if (current === null && finishedWork.flags & Update) { + var type = finishedWork.type; + var props = finishedWork.memoizedProps; + commitMount(_instance2, type, props, finishedWork); + } -// Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need. -function parseCFFPrivateDict(data, start, size, strings) { - var dict = parseCFFDict(data, start, size); - return interpretDict(dict, PRIVATE_DICT_META, strings); -} + break; + } -// Returns a list of "Top DICT"s found using an INDEX list. -// Used to read both the usual high-level Top DICTs and also the FDArray -// discovered inside CID-keyed fonts. When a Top DICT has a reference to -// a Private DICT that is read and saved into the Top DICT. -// -// In addition to the expected/optional values as outlined in TOP_DICT_META -// the following values might be saved into the Top DICT. -// -// _subrs [] array of local CFF subroutines from Private DICT -// _subrsBias bias value computed from number of subroutines -// (see calcCFFSubroutineBias() and parseCFFCharstring()) -// _defaultWidthX default widths for CFF characters -// _nominalWidthX bias added to width embedded within glyph description -// -// _privateDict saved copy of parsed Private DICT from Top DICT -function gatherCFFTopDicts(data, start, cffIndex, strings) { - var topDictArray = []; - for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) { - var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer); - var topDict = parseCFFTopDict(topDictData, strings); - topDict._subrs = []; - topDict._subrsBias = 0; - topDict._defaultWidthX = 0; - topDict._nominalWidthX = 0; - var privateSize = topDict.private[0]; - var privateOffset = topDict.private[1]; - if (privateSize !== 0 && privateOffset !== 0) { - var privateDict = parseCFFPrivateDict(data, privateOffset + start, privateSize, strings); - topDict._defaultWidthX = privateDict.defaultWidthX; - topDict._nominalWidthX = privateDict.nominalWidthX; - if (privateDict.subrs !== 0) { - var subrOffset = privateOffset + privateDict.subrs; - var subrIndex = parseCFFIndex(data, subrOffset + start); - topDict._subrs = subrIndex.objects; - topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs); - } - topDict._privateDict = privateDict; - } - topDictArray.push(topDict); - } - return topDictArray; -} - -// Parse the CFF charset table, which contains internal names for all the glyphs. -// This function will return a list of glyph names. -// See Adobe TN #5176 chapter 13, "Charsets". -function parseCFFCharset(data, start, nGlyphs, strings) { - var sid; - var count; - var parser = new parse.Parser(data, start); - - // The .notdef glyph is not included, so subtract 1. - nGlyphs -= 1; - var charset = ['.notdef']; - - var format = parser.parseCard8(); - if (format === 0) { - for (var i = 0; i < nGlyphs; i += 1) { - sid = parser.parseSID(); - charset.push(getCFFString(strings, sid)); - } - } else if (format === 1) { - while (charset.length <= nGlyphs) { - sid = parser.parseSID(); - count = parser.parseCard8(); - for (var i$1 = 0; i$1 <= count; i$1 += 1) { - charset.push(getCFFString(strings, sid)); - sid += 1; - } - } - } else if (format === 2) { - while (charset.length <= nGlyphs) { - sid = parser.parseSID(); - count = parser.parseCard16(); - for (var i$2 = 0; i$2 <= count; i$2 += 1) { - charset.push(getCFFString(strings, sid)); - sid += 1; - } - } - } else { - throw new Error('Unknown charset format ' + format); - } + case HostText: + { + // We have no life-cycles associated with text. + break; + } - return charset; -} - -// Parse the CFF encoding data. Only one encoding can be specified per font. -// See Adobe TN #5176 chapter 12, "Encodings". -function parseCFFEncoding(data, start, charset) { - var code; - var enc = {}; - var parser = new parse.Parser(data, start); - var format = parser.parseCard8(); - if (format === 0) { - var nCodes = parser.parseCard8(); - for (var i = 0; i < nCodes; i += 1) { - code = parser.parseCard8(); - enc[code] = i; - } - } else if (format === 1) { - var nRanges = parser.parseCard8(); - code = 1; - for (var i$1 = 0; i$1 < nRanges; i$1 += 1) { - var first = parser.parseCard8(); - var nLeft = parser.parseCard8(); - for (var j = first; j <= first + nLeft; j += 1) { - enc[j] = code; - code += 1; - } - } - } else { - throw new Error('Unknown encoding format ' + format); - } + case HostPortal: + { + // We have no life-cycles associated with portals. + break; + } - return new CffEncoding(enc, charset); -} - -// Take in charstring code and return a Glyph object. -// The encoding is described in the Type 2 Charstring Format -// https://www.microsoft.com/typography/OTSPEC/charstr2.htm -function parseCFFCharstring(font, glyph, code) { - var c1x; - var c1y; - var c2x; - var c2y; - var p = new Path(); - var stack = []; - var nStems = 0; - var haveWidth = false; - var open = false; - var x = 0; - var y = 0; - var subrs; - var subrsBias; - var defaultWidthX; - var nominalWidthX; - if (font.isCIDFont) { - var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index]; - var fdDict = font.tables.cff.topDict._fdArray[fdIndex]; - subrs = fdDict._subrs; - subrsBias = fdDict._subrsBias; - defaultWidthX = fdDict._defaultWidthX; - nominalWidthX = fdDict._nominalWidthX; - } else { - subrs = font.tables.cff.topDict._subrs; - subrsBias = font.tables.cff.topDict._subrsBias; - defaultWidthX = font.tables.cff.topDict._defaultWidthX; - nominalWidthX = font.tables.cff.topDict._nominalWidthX; - } - var width = defaultWidthX; + case Profiler: + { + { + var _finishedWork$memoize2 = finishedWork.memoizedProps, + onCommit = _finishedWork$memoize2.onCommit, + onRender = _finishedWork$memoize2.onRender; + var effectDuration = finishedWork.stateNode.effectDuration; + var commitTime = getCommitTime(); + var phase = current === null ? 'mount' : 'update'; - function newContour(x, y) { - if (open) { - p.closePath(); - } + { + if (isCurrentUpdateNested()) { + phase = 'nested-update'; + } + } - p.moveTo(x, y); - open = true; - } + if (typeof onRender === 'function') { + onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime); + } - function parseStems() { - var hasWidthArg; + { + if (typeof onCommit === 'function') { + onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime); + } // Schedule a passive effect for this Profiler to call onPostCommit hooks. + // This effect should be scheduled even if there is no onPostCommit callback for this Profiler, + // because the effect is also where times bubble to parent Profilers. - // The number of stem operators on the stack is always even. - // If the value is uneven, that means a width is specified. - hasWidthArg = stack.length % 2 !== 0; - if (hasWidthArg && !haveWidth) { - width = stack.shift() + nominalWidthX; - } - nStems += stack.length >> 1; - stack.length = 0; - haveWidth = true; - } + enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor. + // Do not reset these values until the next render so DevTools has a chance to read them first. - function parse(code) { - var b1; - var b2; - var b3; - var b4; - var codeIndex; - var subrCode; - var jpx; - var jpy; - var c3x; - var c3y; - var c4x; - var c4y; - - var i = 0; - while (i < code.length) { - var v = code[i]; - i += 1; - switch (v) { - case 1: // hstem - parseStems(); - break; - case 3: // vstem - parseStems(); - break; - case 4: // vmoveto - if (stack.length > 1 && !haveWidth) { - width = stack.shift() + nominalWidthX; - haveWidth = true; - } + var parentFiber = finishedWork.return; - y += stack.pop(); - newContour(x, y); - break; - case 5: // rlineto - while (stack.length > 0) { - x += stack.shift(); - y += stack.shift(); - p.lineTo(x, y); - } + outer: while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + root.effectDuration += effectDuration; + break outer; - break; - case 6: // hlineto - while (stack.length > 0) { - x += stack.shift(); - p.lineTo(x, y); - if (stack.length === 0) { - break; - } - - y += stack.shift(); - p.lineTo(x, y); - } + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.effectDuration += effectDuration; + break outer; + } - break; - case 7: // vlineto - while (stack.length > 0) { - y += stack.shift(); - p.lineTo(x, y); - if (stack.length === 0) { - break; - } - - x += stack.shift(); - p.lineTo(x, y); - } + parentFiber = parentFiber.return; + } + } + } - break; - case 8: // rrcurveto - while (stack.length > 0) { - c1x = x + stack.shift(); - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + stack.shift(); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + break; + } - break; - case 10: // callsubr - codeIndex = stack.pop() + subrsBias; - subrCode = subrs[codeIndex]; - if (subrCode) { - parse(subrCode); - } + case SuspenseComponent: + { + commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); + break; + } - break; - case 11: // return - return; - case 12: // flex operators - v = code[i]; - i += 1; - switch (v) { - case 35: // flex - // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |- - c1x = x + stack.shift(); // dx1 - c1y = y + stack.shift(); // dy1 - c2x = c1x + stack.shift(); // dx2 - c2y = c1y + stack.shift(); // dy2 - jpx = c2x + stack.shift(); // dx3 - jpy = c2y + stack.shift(); // dy3 - c3x = jpx + stack.shift(); // dx4 - c3y = jpy + stack.shift(); // dy4 - c4x = c3x + stack.shift(); // dx5 - c4y = c3y + stack.shift(); // dy5 - x = c4x + stack.shift(); // dx6 - y = c4y + stack.shift(); // dy6 - stack.shift(); // flex depth - p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); - p.curveTo(c3x, c3y, c4x, c4y, x, y); - break; - case 34: // hflex - // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |- - c1x = x + stack.shift(); // dx1 - c1y = y; // dy1 - c2x = c1x + stack.shift(); // dx2 - c2y = c1y + stack.shift(); // dy2 - jpx = c2x + stack.shift(); // dx3 - jpy = c2y; // dy3 - c3x = jpx + stack.shift(); // dx4 - c3y = c2y; // dy4 - c4x = c3x + stack.shift(); // dx5 - c4y = y; // dy5 - x = c4x + stack.shift(); // dx6 - p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); - p.curveTo(c3x, c3y, c4x, c4y, x, y); - break; - case 36: // hflex1 - // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |- - c1x = x + stack.shift(); // dx1 - c1y = y + stack.shift(); // dy1 - c2x = c1x + stack.shift(); // dx2 - c2y = c1y + stack.shift(); // dy2 - jpx = c2x + stack.shift(); // dx3 - jpy = c2y; // dy3 - c3x = jpx + stack.shift(); // dx4 - c3y = c2y; // dy4 - c4x = c3x + stack.shift(); // dx5 - c4y = c3y + stack.shift(); // dy5 - x = c4x + stack.shift(); // dx6 - p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); - p.curveTo(c3x, c3y, c4x, c4y, x, y); - break; - case 37: // flex1 - // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |- - c1x = x + stack.shift(); // dx1 - c1y = y + stack.shift(); // dy1 - c2x = c1x + stack.shift(); // dx2 - c2y = c1y + stack.shift(); // dy2 - jpx = c2x + stack.shift(); // dx3 - jpy = c2y + stack.shift(); // dy3 - c3x = jpx + stack.shift(); // dx4 - c3y = jpy + stack.shift(); // dy4 - c4x = c3x + stack.shift(); // dx5 - c4y = c3y + stack.shift(); // dy5 - if (Math.abs(c4x - x) > Math.abs(c4y - y)) { - x = c4x + stack.shift(); - } else { - y = c4y + stack.shift(); - } - - p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); - p.curveTo(c3x, c3y, c4x, c4y, x, y); - break; - default: - console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v); - stack.length = 0; - } - break; - case 14: // endchar - if (stack.length > 0 && !haveWidth) { - width = stack.shift() + nominalWidthX; - haveWidth = true; - } + case SuspenseListComponent: + case IncompleteClassComponent: + case ScopeComponent: + case OffscreenComponent: + case LegacyHiddenComponent: + { + break; + } - if (open) { - p.closePath(); - open = false; - } + default: + throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); + } + } - break; - case 18: // hstemhm - parseStems(); - break; - case 19: // hintmask - case 20: // cntrmask - parseStems(); - i += (nStems + 7) >> 3; - break; - case 21: // rmoveto - if (stack.length > 2 && !haveWidth) { - width = stack.shift() + nominalWidthX; - haveWidth = true; - } + if ( !offscreenSubtreeWasHidden) { + { + if (finishedWork.flags & Ref) { + commitAttachRef(finishedWork); + } + } + } + } - y += stack.pop(); - x += stack.pop(); - newContour(x, y); - break; - case 22: // hmoveto - if (stack.length > 1 && !haveWidth) { - width = stack.shift() + nominalWidthX; - haveWidth = true; - } + function reappearLayoutEffectsOnFiber(node) { + // Turn on layout effects in a tree that previously disappeared. + // TODO (Offscreen) Check: flags & LayoutStatic + switch (node.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( node.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + safelyCallCommitHookLayoutEffectListMount(node, node.return); + } finally { + recordLayoutEffectDuration(node); + } + } else { + safelyCallCommitHookLayoutEffectListMount(node, node.return); + } - x += stack.pop(); - newContour(x, y); - break; - case 23: // vstemhm - parseStems(); - break; - case 24: // rcurveline - while (stack.length > 2) { - c1x = x + stack.shift(); - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + stack.shift(); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + break; + } - x += stack.shift(); - y += stack.shift(); - p.lineTo(x, y); - break; - case 25: // rlinecurve - while (stack.length > 6) { - x += stack.shift(); - y += stack.shift(); - p.lineTo(x, y); - } + case ClassComponent: + { + var instance = node.stateNode; - c1x = x + stack.shift(); - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + stack.shift(); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - break; - case 26: // vvcurveto - if (stack.length % 2) { - x += stack.shift(); - } + if (typeof instance.componentDidMount === 'function') { + safelyCallComponentDidMount(node, node.return, instance); + } - while (stack.length > 0) { - c1x = x; - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x; - y = c2y + stack.shift(); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + safelyAttachRef(node, node.return); + break; + } - break; - case 27: // hhcurveto - if (stack.length % 2) { - y += stack.shift(); - } + case HostComponent: + { + safelyAttachRef(node, node.return); + break; + } + } + } - while (stack.length > 0) { - c1x = x + stack.shift(); - c1y = y; - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y; - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + function hideOrUnhideAllChildren(finishedWork, isHidden) { + // Only hide or unhide the top-most host nodes. + var hostSubtreeRoot = null; - break; - case 28: // shortint - b1 = code[i]; - b2 = code[i + 1]; - stack.push(((b1 << 24) | (b2 << 16)) >> 16); - i += 2; - break; - case 29: // callgsubr - codeIndex = stack.pop() + font.gsubrsBias; - subrCode = font.gsubrs[codeIndex]; - if (subrCode) { - parse(subrCode); - } + if (supportsMutation) { + // We only have the top Fiber that was inserted but we need to recurse down its + // children to find all the terminal nodes. + var node = finishedWork; - break; - case 30: // vhcurveto - while (stack.length > 0) { - c1x = x; - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + (stack.length === 1 ? stack.shift() : 0); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - if (stack.length === 0) { - break; - } - - c1x = x + stack.shift(); - c1y = y; - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - y = c2y + stack.shift(); - x = c2x + (stack.length === 1 ? stack.shift() : 0); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + while (true) { + if (node.tag === HostComponent) { + if (hostSubtreeRoot === null) { + hostSubtreeRoot = node; + var instance = node.stateNode; - break; - case 31: // hvcurveto - while (stack.length > 0) { - c1x = x + stack.shift(); - c1y = y; - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - y = c2y + stack.shift(); - x = c2x + (stack.length === 1 ? stack.shift() : 0); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - if (stack.length === 0) { - break; - } - - c1x = x; - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + (stack.length === 1 ? stack.shift() : 0); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + if (isHidden) { + hideInstance(instance); + } else { + unhideInstance(node.stateNode, node.memoizedProps); + } + } + } else if (node.tag === HostText) { + if (hostSubtreeRoot === null) { + var _instance3 = node.stateNode; - break; - default: - if (v < 32) { - console.log('Glyph ' + glyph.index + ': unknown operator ' + v); - } else if (v < 247) { - stack.push(v - 139); - } else if (v < 251) { - b1 = code[i]; - i += 1; - stack.push((v - 247) * 256 + b1 + 108); - } else if (v < 255) { - b1 = code[i]; - i += 1; - stack.push(-(v - 251) * 256 - b1 - 108); - } else { - b1 = code[i]; - b2 = code[i + 1]; - b3 = code[i + 2]; - b4 = code[i + 3]; - i += 4; - stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536); - } - } - } - } + if (isHidden) { + hideTextInstance(_instance3); + } else { + unhideTextInstance(_instance3, node.memoizedProps); + } + } + } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } - parse(code); + if (node === finishedWork) { + return; + } - glyph.advanceWidth = width; - return p; -} + while (node.sibling === null) { + if (node.return === null || node.return === finishedWork) { + return; + } -function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) { - var fdSelect = []; - var fdIndex; - var parser = new parse.Parser(data, start); - var format = parser.parseCard8(); - if (format === 0) { - // Simple list of nGlyphs elements - for (var iGid = 0; iGid < nGlyphs; iGid++) { - fdIndex = parser.parseCard8(); - if (fdIndex >= fdArrayCount) { - throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); - } - fdSelect.push(fdIndex); - } - } else if (format === 3) { - // Ranges - var nRanges = parser.parseCard16(); - var first = parser.parseCard16(); - if (first !== 0) { - throw new Error('CFF Table CID Font FDSelect format 3 range has bad initial GID ' + first); - } - var next; - for (var iRange = 0; iRange < nRanges; iRange++) { - fdIndex = parser.parseCard8(); - next = parser.parseCard16(); - if (fdIndex >= fdArrayCount) { - throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); - } - if (next > nGlyphs) { - throw new Error('CFF Table CID Font FDSelect format 3 range has bad GID ' + next); - } - for (; first < next; first++) { - fdSelect.push(fdIndex); - } - first = next; - } - if (next !== nGlyphs) { - throw new Error('CFF Table CID Font FDSelect format 3 range has bad final GID ' + next); - } - } else { - throw new Error('CFF Table CID Font FDSelect table has unsupported format ' + format); - } - return fdSelect; -} - -// Parse the `CFF` table, which contains the glyph outlines in PostScript format. -function parseCFFTable(data, start, font, opt) { - font.tables.cff = {}; - var header = parseCFFHeader(data, start); - var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString); - var topDictIndex = parseCFFIndex(data, nameIndex.endOffset); - var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString); - var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset); - font.gsubrs = globalSubrIndex.objects; - font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); - - var topDictArray = gatherCFFTopDicts(data, start, topDictIndex.objects, stringIndex.objects); - if (topDictArray.length !== 1) { - throw new Error('CFF table has too many fonts in \'FontSet\' - count of fonts NameIndex.length = ' + topDictArray.length); - } + if (hostSubtreeRoot === node) { + hostSubtreeRoot = null; + } - var topDict = topDictArray[0]; - font.tables.cff.topDict = topDict; + node = node.return; + } - if (topDict._privateDict) { - font.defaultWidthX = topDict._privateDict.defaultWidthX; - font.nominalWidthX = topDict._privateDict.nominalWidthX; - } + if (hostSubtreeRoot === node) { + hostSubtreeRoot = null; + } - if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) { - font.isCIDFont = true; - } + node.sibling.return = node.return; + node = node.sibling; + } + } + } - if (font.isCIDFont) { - var fdArrayOffset = topDict.fdArray; - var fdSelectOffset = topDict.fdSelect; - if (fdArrayOffset === 0 || fdSelectOffset === 0) { - throw new Error('Font is marked as a CID font, but FDArray and/or FDSelect information is missing'); - } - fdArrayOffset += start; - var fdArrayIndex = parseCFFIndex(data, fdArrayOffset); - var fdArray = gatherCFFTopDicts(data, start, fdArrayIndex.objects, stringIndex.objects); - topDict._fdArray = fdArray; - fdSelectOffset += start; - topDict._fdSelect = parseCFFFDSelect(data, fdSelectOffset, font.numGlyphs, fdArray.length); - } + function commitAttachRef(finishedWork) { + var ref = finishedWork.ref; - var privateDictOffset = start + topDict.private[1]; - var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict.private[0], stringIndex.objects); - font.defaultWidthX = privateDict.defaultWidthX; - font.nominalWidthX = privateDict.nominalWidthX; + if (ref !== null) { + var instance = finishedWork.stateNode; + var instanceToUse; - if (privateDict.subrs !== 0) { - var subrOffset = privateDictOffset + privateDict.subrs; - var subrIndex = parseCFFIndex(data, subrOffset); - font.subrs = subrIndex.objects; - font.subrsBias = calcCFFSubroutineBias(font.subrs); - } else { - font.subrs = []; - font.subrsBias = 0; - } + switch (finishedWork.tag) { + case HostComponent: + instanceToUse = getPublicInstance(instance); + break; - // Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset. - var charStringsIndex; - if (opt.lowMemory) { - charStringsIndex = parseCFFIndexLowMemory(data, start + topDict.charStrings); - font.nGlyphs = charStringsIndex.offsets.length; - } else { - charStringsIndex = parseCFFIndex(data, start + topDict.charStrings); - font.nGlyphs = charStringsIndex.objects.length; - } + default: + instanceToUse = instance; + } // Moved outside to ensure DCE works with this flag - var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects); - if (topDict.encoding === 0) { - // Standard encoding - font.cffEncoding = new CffEncoding(cffStandardEncoding, charset); - } else if (topDict.encoding === 1) { - // Expert encoding - font.cffEncoding = new CffEncoding(cffExpertEncoding, charset); - } else { - font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset); - } + if (typeof ref === 'function') { + var retVal; - // Prefer the CMAP encoding to the CFF encoding. - font.encoding = font.encoding || font.cffEncoding; + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + retVal = ref(instanceToUse); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + retVal = ref(instanceToUse); + } - font.glyphs = new glyphset.GlyphSet(font); - if (opt.lowMemory) { - font._push = function(i) { - var charString = getCffIndexObject(i, charStringsIndex.offsets, data, start + topDict.charStrings); - font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); - }; - } else { - for (var i = 0; i < font.nGlyphs; i += 1) { - var charString = charStringsIndex.objects[i]; - font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); - } - } -} + { + if (typeof retVal === 'function') { + error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork)); + } + } + } else { + { + if (!ref.hasOwnProperty('current')) { + error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork)); + } + } -// Convert a string to a String ID (SID). -// The list of strings is modified in place. -function encodeString(s, strings) { - var sid; + ref.current = instanceToUse; + } + } + } - // Is the string in the CFF standard strings? - var i = cffStandardStrings.indexOf(s); - if (i >= 0) { - sid = i; - } + function commitDetachRef(current) { + var currentRef = current.ref; - // Is the string already in the string index? - i = strings.indexOf(s); - if (i >= 0) { - sid = i + cffStandardStrings.length; - } else { - sid = cffStandardStrings.length + strings.length; - strings.push(s); - } + if (currentRef !== null) { + if (typeof currentRef === 'function') { + if ( current.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + currentRef(null); + } finally { + recordLayoutEffectDuration(current); + } + } else { + currentRef(null); + } + } else { + currentRef.current = null; + } + } + } // User-originating errors (lifecycles and refs) should not interrupt + // deletion, so don't let them throw. Host-originating errors should + // interrupt deletion, so it's okay - return sid; -} -function makeHeader() { - return new table.Record('Header', [ - {name: 'major', type: 'Card8', value: 1}, - {name: 'minor', type: 'Card8', value: 0}, - {name: 'hdrSize', type: 'Card8', value: 4}, - {name: 'major', type: 'Card8', value: 1} - ]); -} + function commitUnmount(finishedRoot, current, nearestMountedAncestor) { + onCommitUnmount(current); -function makeNameIndex(fontNames) { - var t = new table.Record('Name INDEX', [ - {name: 'names', type: 'INDEX', value: []} - ]); - t.names = []; - for (var i = 0; i < fontNames.length; i += 1) { - t.names.push({name: 'name_' + i, type: 'NAME', value: fontNames[i]}); - } + switch (current.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: + { + var updateQueue = current.updateQueue; - return t; -} + if (updateQueue !== null) { + var lastEffect = updateQueue.lastEffect; -// Given a dictionary's metadata, create a DICT structure. -function makeDict(meta, attrs, strings) { - var m = {}; - for (var i = 0; i < meta.length; i += 1) { - var entry = meta[i]; - var value = attrs[entry.name]; - if (value !== undefined && !equals(value, entry.value)) { - if (entry.type === 'SID') { - value = encodeString(value, strings); - } + if (lastEffect !== null) { + var firstEffect = lastEffect.next; + var effect = firstEffect; - m[entry.op] = {name: entry.name, type: entry.type, value: value}; - } - } + do { + var _effect = effect, + destroy = _effect.destroy, + tag = _effect.tag; - return m; -} + if (destroy !== undefined) { + if ((tag & Insertion) !== NoFlags$1) { + safelyCallDestroy(current, nearestMountedAncestor, destroy); + } else if ((tag & Layout) !== NoFlags$1) { + { + markComponentLayoutEffectUnmountStarted(current); + } -// The Top DICT houses the global font attributes. -function makeTopDict(attrs, strings) { - var t = new table.Record('Top DICT', [ - {name: 'dict', type: 'DICT', value: {}} - ]); - t.dict = makeDict(TOP_DICT_META, attrs, strings); - return t; -} + if ( current.mode & ProfileMode) { + startLayoutEffectTimer(); + safelyCallDestroy(current, nearestMountedAncestor, destroy); + recordLayoutEffectDuration(current); + } else { + safelyCallDestroy(current, nearestMountedAncestor, destroy); + } -function makeTopDictIndex(topDict) { - var t = new table.Record('Top DICT INDEX', [ - {name: 'topDicts', type: 'INDEX', value: []} - ]); - t.topDicts = [{name: 'topDict_0', type: 'TABLE', value: topDict}]; - return t; -} + { + markComponentLayoutEffectUnmountStopped(); + } + } + } -function makeStringIndex(strings) { - var t = new table.Record('String INDEX', [ - {name: 'strings', type: 'INDEX', value: []} - ]); - t.strings = []; - for (var i = 0; i < strings.length; i += 1) { - t.strings.push({name: 'string_' + i, type: 'STRING', value: strings[i]}); - } + effect = effect.next; + } while (effect !== firstEffect); + } + } - return t; -} + return; + } -function makeGlobalSubrIndex() { - // Currently we don't use subroutines. - return new table.Record('Global Subr INDEX', [ - {name: 'subrs', type: 'INDEX', value: []} - ]); -} + case ClassComponent: + { + safelyDetachRef(current, nearestMountedAncestor); + var instance = current.stateNode; -function makeCharsets(glyphNames, strings) { - var t = new table.Record('Charsets', [ - {name: 'format', type: 'Card8', value: 0} - ]); - for (var i = 0; i < glyphNames.length; i += 1) { - var glyphName = glyphNames[i]; - var glyphSID = encodeString(glyphName, strings); - t.fields.push({name: 'glyph_' + i, type: 'SID', value: glyphSID}); - } + if (typeof instance.componentWillUnmount === 'function') { + safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance); + } - return t; -} - -function glyphToOps(glyph) { - var ops = []; - var path = glyph.path; - ops.push({name: 'width', type: 'NUMBER', value: glyph.advanceWidth}); - var x = 0; - var y = 0; - for (var i = 0; i < path.commands.length; i += 1) { - var dx = (void 0); - var dy = (void 0); - var cmd = path.commands[i]; - if (cmd.type === 'Q') { - // CFF only supports bézier curves, so convert the quad to a bézier. - var _13 = 1 / 3; - var _23 = 2 / 3; - - // We're going to create a new command so we don't change the original path. - // Since all coordinates are relative, we round() them ASAP to avoid propagating errors. - cmd = { - type: 'C', - x: cmd.x, - y: cmd.y, - x1: Math.round(_13 * x + _23 * cmd.x1), - y1: Math.round(_13 * y + _23 * cmd.y1), - x2: Math.round(_13 * cmd.x + _23 * cmd.x1), - y2: Math.round(_13 * cmd.y + _23 * cmd.y1) - }; - } + return; + } - if (cmd.type === 'M') { - dx = Math.round(cmd.x - x); - dy = Math.round(cmd.y - y); - ops.push({name: 'dx', type: 'NUMBER', value: dx}); - ops.push({name: 'dy', type: 'NUMBER', value: dy}); - ops.push({name: 'rmoveto', type: 'OP', value: 21}); - x = Math.round(cmd.x); - y = Math.round(cmd.y); - } else if (cmd.type === 'L') { - dx = Math.round(cmd.x - x); - dy = Math.round(cmd.y - y); - ops.push({name: 'dx', type: 'NUMBER', value: dx}); - ops.push({name: 'dy', type: 'NUMBER', value: dy}); - ops.push({name: 'rlineto', type: 'OP', value: 5}); - x = Math.round(cmd.x); - y = Math.round(cmd.y); - } else if (cmd.type === 'C') { - var dx1 = Math.round(cmd.x1 - x); - var dy1 = Math.round(cmd.y1 - y); - var dx2 = Math.round(cmd.x2 - cmd.x1); - var dy2 = Math.round(cmd.y2 - cmd.y1); - dx = Math.round(cmd.x - cmd.x2); - dy = Math.round(cmd.y - cmd.y2); - ops.push({name: 'dx1', type: 'NUMBER', value: dx1}); - ops.push({name: 'dy1', type: 'NUMBER', value: dy1}); - ops.push({name: 'dx2', type: 'NUMBER', value: dx2}); - ops.push({name: 'dy2', type: 'NUMBER', value: dy2}); - ops.push({name: 'dx', type: 'NUMBER', value: dx}); - ops.push({name: 'dy', type: 'NUMBER', value: dy}); - ops.push({name: 'rrcurveto', type: 'OP', value: 8}); - x = Math.round(cmd.x); - y = Math.round(cmd.y); - } + case HostComponent: + { + safelyDetachRef(current, nearestMountedAncestor); + return; + } - // Contours are closed automatically. - } + case HostPortal: + { + // TODO: this is recursive. + // We are also not using this parent because + // the portal will get pushed immediately. + if (supportsMutation) { + unmountHostComponents(finishedRoot, current, nearestMountedAncestor); + } else if (supportsPersistence) { + emptyPortalContainer(current); + } - ops.push({name: 'endchar', type: 'OP', value: 14}); - return ops; -} + return; + } -function makeCharStringsIndex(glyphs) { - var t = new table.Record('CharStrings INDEX', [ - {name: 'charStrings', type: 'INDEX', value: []} - ]); + case DehydratedFragment: + { - for (var i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs.get(i); - var ops = glyphToOps(glyph); - t.charStrings.push({name: glyph.name, type: 'CHARSTRING', value: ops}); - } + return; + } - return t; -} + case ScopeComponent: + { -function makePrivateDict(attrs, strings) { - var t = new table.Record('Private DICT', [ - {name: 'dict', type: 'DICT', value: {}} - ]); - t.dict = makeDict(PRIVATE_DICT_META, attrs, strings); - return t; -} - -function makeCFFTable(glyphs, options) { - var t = new table.Table('CFF ', [ - {name: 'header', type: 'RECORD'}, - {name: 'nameIndex', type: 'RECORD'}, - {name: 'topDictIndex', type: 'RECORD'}, - {name: 'stringIndex', type: 'RECORD'}, - {name: 'globalSubrIndex', type: 'RECORD'}, - {name: 'charsets', type: 'RECORD'}, - {name: 'charStringsIndex', type: 'RECORD'}, - {name: 'privateDict', type: 'RECORD'} - ]); + return; + } + } + } - var fontScale = 1 / options.unitsPerEm; - // We use non-zero values for the offsets so that the DICT encodes them. - // This is important because the size of the Top DICT plays a role in offset calculation, - // and the size shouldn't change after we've written correct offsets. - var attrs = { - version: options.version, - fullName: options.fullName, - familyName: options.familyName, - weight: options.weightName, - fontBBox: options.fontBBox || [0, 0, 0, 0], - fontMatrix: [fontScale, 0, 0, fontScale, 0, 0], - charset: 999, - encoding: 0, - charStrings: 999, - private: [0, 999] - }; + function commitNestedUnmounts(finishedRoot, root, nearestMountedAncestor) { + // While we're inside a removed host node we don't want to call + // removeChild on the inner nodes because they're removed by the top + // call anyway. We also want to call componentWillUnmount on all + // composites before this host node is removed from the tree. Therefore + // we do an inner loop while we're still inside the host node. + var node = root; - var privateAttrs = {}; + while (true) { + commitUnmount(finishedRoot, node, nearestMountedAncestor); // Visit children because they may contain more composite or host nodes. + // Skip portals because commitUnmount() currently visits them recursively. - var glyphNames = []; - var glyph; + if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above. + // If we don't use mutation we drill down into portals here instead. + !supportsMutation || node.tag !== HostPortal)) { + node.child.return = node; + node = node.child; + continue; + } - // Skip first glyph (.notdef) - for (var i = 1; i < glyphs.length; i += 1) { - glyph = glyphs.get(i); - glyphNames.push(glyph.name); - } + if (node === root) { + return; + } - var strings = []; - - t.header = makeHeader(); - t.nameIndex = makeNameIndex([options.postScriptName]); - var topDict = makeTopDict(attrs, strings); - t.topDictIndex = makeTopDictIndex(topDict); - t.globalSubrIndex = makeGlobalSubrIndex(); - t.charsets = makeCharsets(glyphNames, strings); - t.charStringsIndex = makeCharStringsIndex(glyphs); - t.privateDict = makePrivateDict(privateAttrs, strings); - - // Needs to come at the end, to encode all custom strings used in the font. - t.stringIndex = makeStringIndex(strings); - - var startOffset = t.header.sizeOf() + - t.nameIndex.sizeOf() + - t.topDictIndex.sizeOf() + - t.stringIndex.sizeOf() + - t.globalSubrIndex.sizeOf(); - attrs.charset = startOffset; - - // We use the CFF standard encoding; proper encoding will be handled in cmap. - attrs.encoding = 0; - attrs.charStrings = attrs.charset + t.charsets.sizeOf(); - attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf(); - - // Recreate the Top DICT INDEX with the correct offsets. - topDict = makeTopDict(attrs, strings); - t.topDictIndex = makeTopDictIndex(topDict); - - return t; -} - -var cff = { parse: parseCFFTable, make: makeCFFTable }; - -// The `head` table contains global information about the font. - -// Parse the header `head` table -function parseHeadTable(data, start) { - var head = {}; - var p = new parse.Parser(data, start); - head.version = p.parseVersion(); - head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; - head.checkSumAdjustment = p.parseULong(); - head.magicNumber = p.parseULong(); - check.argument(head.magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.'); - head.flags = p.parseUShort(); - head.unitsPerEm = p.parseUShort(); - head.created = p.parseLongDateTime(); - head.modified = p.parseLongDateTime(); - head.xMin = p.parseShort(); - head.yMin = p.parseShort(); - head.xMax = p.parseShort(); - head.yMax = p.parseShort(); - head.macStyle = p.parseUShort(); - head.lowestRecPPEM = p.parseUShort(); - head.fontDirectionHint = p.parseShort(); - head.indexToLocFormat = p.parseShort(); - head.glyphDataFormat = p.parseShort(); - return head; -} - -function makeHeadTable(options) { - // Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970 - var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; - var createdTimestamp = timestamp; - - if (options.createdTimestamp) { - createdTimestamp = options.createdTimestamp + 2082844800; - } + while (node.sibling === null) { + if (node.return === null || node.return === root) { + return; + } - return new table.Table('head', [ - {name: 'version', type: 'FIXED', value: 0x00010000}, - {name: 'fontRevision', type: 'FIXED', value: 0x00010000}, - {name: 'checkSumAdjustment', type: 'ULONG', value: 0}, - {name: 'magicNumber', type: 'ULONG', value: 0x5F0F3CF5}, - {name: 'flags', type: 'USHORT', value: 0}, - {name: 'unitsPerEm', type: 'USHORT', value: 1000}, - {name: 'created', type: 'LONGDATETIME', value: createdTimestamp}, - {name: 'modified', type: 'LONGDATETIME', value: timestamp}, - {name: 'xMin', type: 'SHORT', value: 0}, - {name: 'yMin', type: 'SHORT', value: 0}, - {name: 'xMax', type: 'SHORT', value: 0}, - {name: 'yMax', type: 'SHORT', value: 0}, - {name: 'macStyle', type: 'USHORT', value: 0}, - {name: 'lowestRecPPEM', type: 'USHORT', value: 0}, - {name: 'fontDirectionHint', type: 'SHORT', value: 2}, - {name: 'indexToLocFormat', type: 'SHORT', value: 0}, - {name: 'glyphDataFormat', type: 'SHORT', value: 0} - ], options); -} - -var head = { parse: parseHeadTable, make: makeHeadTable }; - -// The `hhea` table contains information for horizontal layout. - -// Parse the horizontal header `hhea` table -function parseHheaTable(data, start) { - var hhea = {}; - var p = new parse.Parser(data, start); - hhea.version = p.parseVersion(); - hhea.ascender = p.parseShort(); - hhea.descender = p.parseShort(); - hhea.lineGap = p.parseShort(); - hhea.advanceWidthMax = p.parseUShort(); - hhea.minLeftSideBearing = p.parseShort(); - hhea.minRightSideBearing = p.parseShort(); - hhea.xMaxExtent = p.parseShort(); - hhea.caretSlopeRise = p.parseShort(); - hhea.caretSlopeRun = p.parseShort(); - hhea.caretOffset = p.parseShort(); - p.relativeOffset += 8; - hhea.metricDataFormat = p.parseShort(); - hhea.numberOfHMetrics = p.parseUShort(); - return hhea; -} - -function makeHheaTable(options) { - return new table.Table('hhea', [ - {name: 'version', type: 'FIXED', value: 0x00010000}, - {name: 'ascender', type: 'FWORD', value: 0}, - {name: 'descender', type: 'FWORD', value: 0}, - {name: 'lineGap', type: 'FWORD', value: 0}, - {name: 'advanceWidthMax', type: 'UFWORD', value: 0}, - {name: 'minLeftSideBearing', type: 'FWORD', value: 0}, - {name: 'minRightSideBearing', type: 'FWORD', value: 0}, - {name: 'xMaxExtent', type: 'FWORD', value: 0}, - {name: 'caretSlopeRise', type: 'SHORT', value: 1}, - {name: 'caretSlopeRun', type: 'SHORT', value: 0}, - {name: 'caretOffset', type: 'SHORT', value: 0}, - {name: 'reserved1', type: 'SHORT', value: 0}, - {name: 'reserved2', type: 'SHORT', value: 0}, - {name: 'reserved3', type: 'SHORT', value: 0}, - {name: 'reserved4', type: 'SHORT', value: 0}, - {name: 'metricDataFormat', type: 'SHORT', value: 0}, - {name: 'numberOfHMetrics', type: 'USHORT', value: 0} - ], options); -} - -var hhea = { parse: parseHheaTable, make: makeHheaTable }; - -// The `hmtx` table contains the horizontal metrics for all glyphs. - -function parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs) { - var advanceWidth; - var leftSideBearing; - var p = new parse.Parser(data, start); - for (var i = 0; i < numGlyphs; i += 1) { - // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. - if (i < numMetrics) { - advanceWidth = p.parseUShort(); - leftSideBearing = p.parseShort(); - } + node = node.return; + } - var glyph = glyphs.get(i); - glyph.advanceWidth = advanceWidth; - glyph.leftSideBearing = leftSideBearing; - } -} + node.sibling.return = node.return; + node = node.sibling; + } + } -function parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs) { - font._hmtxTableData = {}; + function detachFiberMutation(fiber) { + // Cut off the return pointer to disconnect it from the tree. + // This enables us to detect and warn against state updates on an unmounted component. + // It also prevents events from bubbling from within disconnected components. + // + // Ideally, we should also clear the child pointer of the parent alternate to let this + // get GC:ed but we don't know which for sure which parent is the current + // one so we'll settle for GC:ing the subtree of this child. + // This child itself will be GC:ed when the parent updates the next time. + // + // Note that we can't clear child or sibling pointers yet. + // They're needed for passive effects and for findDOMNode. + // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects). + // + // Don't reset the alternate yet, either. We need that so we can detach the + // alternate's fields in the passive phase. Clearing the return pointer is + // sufficient for findDOMNode semantics. + var alternate = fiber.alternate; - var advanceWidth; - var leftSideBearing; - var p = new parse.Parser(data, start); - for (var i = 0; i < numGlyphs; i += 1) { - // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. - if (i < numMetrics) { - advanceWidth = p.parseUShort(); - leftSideBearing = p.parseShort(); - } + if (alternate !== null) { + alternate.return = null; + } - font._hmtxTableData[i] = { - advanceWidth: advanceWidth, - leftSideBearing: leftSideBearing - }; - } -} + fiber.return = null; + } -// Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. -// This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. -function parseHmtxTable(font, data, start, numMetrics, numGlyphs, glyphs, opt) { - if (opt.lowMemory) - { parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs); } - else - { parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs); } -} + function detachFiberAfterEffects(fiber) { + var alternate = fiber.alternate; -function makeHmtxTable(glyphs) { - var t = new table.Table('hmtx', []); - for (var i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs.get(i); - var advanceWidth = glyph.advanceWidth || 0; - var leftSideBearing = glyph.leftSideBearing || 0; - t.fields.push({name: 'advanceWidth_' + i, type: 'USHORT', value: advanceWidth}); - t.fields.push({name: 'leftSideBearing_' + i, type: 'SHORT', value: leftSideBearing}); - } + if (alternate !== null) { + fiber.alternate = null; + detachFiberAfterEffects(alternate); + } // Note: Defensively using negation instead of < in case + // `deletedTreeCleanUpLevel` is undefined. - return t; -} -var hmtx = { parse: parseHmtxTable, make: makeHmtxTable }; + { + // Clear cyclical Fiber fields. This level alone is designed to roughly + // approximate the planned Fiber refactor. In that world, `setState` will be + // bound to a special "instance" object instead of a Fiber. The Instance + // object will not have any of these fields. It will only be connected to + // the fiber tree via a single link at the root. So if this level alone is + // sufficient to fix memory issues, that bodes well for our plans. + fiber.child = null; + fiber.deletions = null; + fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host + // tree, which has its own pointers to children, parents, and siblings. + // The other host nodes also point back to fibers, so we should detach that + // one, too. -// The `ltag` table stores IETF BCP-47 language tags. It allows supporting + if (fiber.tag === HostComponent) { + var hostInstance = fiber.stateNode; -function makeLtagTable(tags) { - var result = new table.Table('ltag', [ - {name: 'version', type: 'ULONG', value: 1}, - {name: 'flags', type: 'ULONG', value: 0}, - {name: 'numTags', type: 'ULONG', value: tags.length} - ]); + if (hostInstance !== null) { + detachDeletedInstance(hostInstance); + } + } - var stringPool = ''; - var stringPoolOffset = 12 + tags.length * 4; - for (var i = 0; i < tags.length; ++i) { - var pos = stringPool.indexOf(tags[i]); - if (pos < 0) { - pos = stringPool.length; - stringPool += tags[i]; - } + fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We + // already disconnect the `return` pointer at the root of the deleted + // subtree (in `detachFiberMutation`). Besides, `return` by itself is not + // cyclical — it's only cyclical when combined with `child`, `sibling`, and + // `alternate`. But we'll clear it in the next level anyway, just in case. - result.fields.push({name: 'offset ' + i, type: 'USHORT', value: stringPoolOffset + pos}); - result.fields.push({name: 'length ' + i, type: 'USHORT', value: tags[i].length}); - } + { + fiber._debugOwner = null; + } - result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); - return result; -} + { + // Theoretically, nothing in here should be necessary, because we already + // disconnected the fiber from the tree. So even if something leaks this + // particular fiber, it won't leak anything else + // + // The purpose of this branch is to be super aggressive so we can measure + // if there's any difference in memory impact. If there is, that could + // indicate a React leak we don't know about. + fiber.return = null; + fiber.dependencies = null; + fiber.memoizedProps = null; + fiber.memoizedState = null; + fiber.pendingProps = null; + fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead. -function parseLtagTable(data, start) { - var p = new parse.Parser(data, start); - var tableVersion = p.parseULong(); - check.argument(tableVersion === 1, 'Unsupported ltag table version.'); - // The 'ltag' specification does not define any flags; skip the field. - p.skip('uLong', 1); - var numTags = p.parseULong(); - - var tags = []; - for (var i = 0; i < numTags; i++) { - var tag = ''; - var offset = start + p.parseUShort(); - var length = p.parseUShort(); - for (var j = offset; j < offset + length; ++j) { - tag += String.fromCharCode(data.getInt8(j)); - } + fiber.updateQueue = null; + } + } + } - tags.push(tag); - } + function emptyPortalContainer(current) { + if (!supportsPersistence) { + return; + } - return tags; -} - -var ltag = { make: makeLtagTable, parse: parseLtagTable }; - -// The `maxp` table establishes the memory requirements for the font. - -// Parse the maximum profile `maxp` table. -function parseMaxpTable(data, start) { - var maxp = {}; - var p = new parse.Parser(data, start); - maxp.version = p.parseVersion(); - maxp.numGlyphs = p.parseUShort(); - if (maxp.version === 1.0) { - maxp.maxPoints = p.parseUShort(); - maxp.maxContours = p.parseUShort(); - maxp.maxCompositePoints = p.parseUShort(); - maxp.maxCompositeContours = p.parseUShort(); - maxp.maxZones = p.parseUShort(); - maxp.maxTwilightPoints = p.parseUShort(); - maxp.maxStorage = p.parseUShort(); - maxp.maxFunctionDefs = p.parseUShort(); - maxp.maxInstructionDefs = p.parseUShort(); - maxp.maxStackElements = p.parseUShort(); - maxp.maxSizeOfInstructions = p.parseUShort(); - maxp.maxComponentElements = p.parseUShort(); - maxp.maxComponentDepth = p.parseUShort(); - } + var portal = current.stateNode; + var containerInfo = portal.containerInfo; + var emptyChildSet = createContainerChildSet(containerInfo); + replaceContainerChildren(containerInfo, emptyChildSet); + } - return maxp; -} + function commitContainer(finishedWork) { + if (!supportsPersistence) { + return; + } -function makeMaxpTable(numGlyphs) { - return new table.Table('maxp', [ - {name: 'version', type: 'FIXED', value: 0x00005000}, - {name: 'numGlyphs', type: 'USHORT', value: numGlyphs} - ]); -} + switch (finishedWork.tag) { + case ClassComponent: + case HostComponent: + case HostText: + { + return; + } -var maxp = { parse: parseMaxpTable, make: makeMaxpTable }; - -// The `name` naming table. - -// NameIDs for the name table. -var nameTableNames = [ - 'copyright', // 0 - 'fontFamily', // 1 - 'fontSubfamily', // 2 - 'uniqueID', // 3 - 'fullName', // 4 - 'version', // 5 - 'postScriptName', // 6 - 'trademark', // 7 - 'manufacturer', // 8 - 'designer', // 9 - 'description', // 10 - 'manufacturerURL', // 11 - 'designerURL', // 12 - 'license', // 13 - 'licenseURL', // 14 - 'reserved', // 15 - 'preferredFamily', // 16 - 'preferredSubfamily', // 17 - 'compatibleFullName', // 18 - 'sampleText', // 19 - 'postScriptFindFontName', // 20 - 'wwsFamily', // 21 - 'wwsSubfamily' // 22 -]; + case HostRoot: + case HostPortal: + { + var portalOrRoot = finishedWork.stateNode; + var containerInfo = portalOrRoot.containerInfo, + pendingChildren = portalOrRoot.pendingChildren; + replaceContainerChildren(containerInfo, pendingChildren); + return; + } + } -var macLanguages = { - 0: 'en', - 1: 'fr', - 2: 'de', - 3: 'it', - 4: 'nl', - 5: 'sv', - 6: 'es', - 7: 'da', - 8: 'pt', - 9: 'no', - 10: 'he', - 11: 'ja', - 12: 'ar', - 13: 'fi', - 14: 'el', - 15: 'is', - 16: 'mt', - 17: 'tr', - 18: 'hr', - 19: 'zh-Hant', - 20: 'ur', - 21: 'hi', - 22: 'th', - 23: 'ko', - 24: 'lt', - 25: 'pl', - 26: 'hu', - 27: 'es', - 28: 'lv', - 29: 'se', - 30: 'fo', - 31: 'fa', - 32: 'ru', - 33: 'zh', - 34: 'nl-BE', - 35: 'ga', - 36: 'sq', - 37: 'ro', - 38: 'cz', - 39: 'sk', - 40: 'si', - 41: 'yi', - 42: 'sr', - 43: 'mk', - 44: 'bg', - 45: 'uk', - 46: 'be', - 47: 'uz', - 48: 'kk', - 49: 'az-Cyrl', - 50: 'az-Arab', - 51: 'hy', - 52: 'ka', - 53: 'mo', - 54: 'ky', - 55: 'tg', - 56: 'tk', - 57: 'mn-CN', - 58: 'mn', - 59: 'ps', - 60: 'ks', - 61: 'ku', - 62: 'sd', - 63: 'bo', - 64: 'ne', - 65: 'sa', - 66: 'mr', - 67: 'bn', - 68: 'as', - 69: 'gu', - 70: 'pa', - 71: 'or', - 72: 'ml', - 73: 'kn', - 74: 'ta', - 75: 'te', - 76: 'si', - 77: 'my', - 78: 'km', - 79: 'lo', - 80: 'vi', - 81: 'id', - 82: 'tl', - 83: 'ms', - 84: 'ms-Arab', - 85: 'am', - 86: 'ti', - 87: 'om', - 88: 'so', - 89: 'sw', - 90: 'rw', - 91: 'rn', - 92: 'ny', - 93: 'mg', - 94: 'eo', - 128: 'cy', - 129: 'eu', - 130: 'ca', - 131: 'la', - 132: 'qu', - 133: 'gn', - 134: 'ay', - 135: 'tt', - 136: 'ug', - 137: 'dz', - 138: 'jv', - 139: 'su', - 140: 'gl', - 141: 'af', - 142: 'br', - 143: 'iu', - 144: 'gd', - 145: 'gv', - 146: 'ga', - 147: 'to', - 148: 'el-polyton', - 149: 'kl', - 150: 'az', - 151: 'nn' -}; + throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); + } -// MacOS language ID → MacOS script ID -// -// Note that the script ID is not sufficient to determine what encoding -// to use in TrueType files. For some languages, MacOS used a modification -// of a mainstream script. For example, an Icelandic name would be stored -// with smRoman in the TrueType naming table, but the actual encoding -// is a special Icelandic version of the normal Macintosh Roman encoding. -// As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal -// Syllables but MacOS had run out of available script codes, so this was -// done as a (pretty radical) "modification" of Ethiopic. -// -// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt -var macLanguageToScript = { - 0: 0, // langEnglish → smRoman - 1: 0, // langFrench → smRoman - 2: 0, // langGerman → smRoman - 3: 0, // langItalian → smRoman - 4: 0, // langDutch → smRoman - 5: 0, // langSwedish → smRoman - 6: 0, // langSpanish → smRoman - 7: 0, // langDanish → smRoman - 8: 0, // langPortuguese → smRoman - 9: 0, // langNorwegian → smRoman - 10: 5, // langHebrew → smHebrew - 11: 1, // langJapanese → smJapanese - 12: 4, // langArabic → smArabic - 13: 0, // langFinnish → smRoman - 14: 6, // langGreek → smGreek - 15: 0, // langIcelandic → smRoman (modified) - 16: 0, // langMaltese → smRoman - 17: 0, // langTurkish → smRoman (modified) - 18: 0, // langCroatian → smRoman (modified) - 19: 2, // langTradChinese → smTradChinese - 20: 4, // langUrdu → smArabic - 21: 9, // langHindi → smDevanagari - 22: 21, // langThai → smThai - 23: 3, // langKorean → smKorean - 24: 29, // langLithuanian → smCentralEuroRoman - 25: 29, // langPolish → smCentralEuroRoman - 26: 29, // langHungarian → smCentralEuroRoman - 27: 29, // langEstonian → smCentralEuroRoman - 28: 29, // langLatvian → smCentralEuroRoman - 29: 0, // langSami → smRoman - 30: 0, // langFaroese → smRoman (modified) - 31: 4, // langFarsi → smArabic (modified) - 32: 7, // langRussian → smCyrillic - 33: 25, // langSimpChinese → smSimpChinese - 34: 0, // langFlemish → smRoman - 35: 0, // langIrishGaelic → smRoman (modified) - 36: 0, // langAlbanian → smRoman - 37: 0, // langRomanian → smRoman (modified) - 38: 29, // langCzech → smCentralEuroRoman - 39: 29, // langSlovak → smCentralEuroRoman - 40: 0, // langSlovenian → smRoman (modified) - 41: 5, // langYiddish → smHebrew - 42: 7, // langSerbian → smCyrillic - 43: 7, // langMacedonian → smCyrillic - 44: 7, // langBulgarian → smCyrillic - 45: 7, // langUkrainian → smCyrillic (modified) - 46: 7, // langByelorussian → smCyrillic - 47: 7, // langUzbek → smCyrillic - 48: 7, // langKazakh → smCyrillic - 49: 7, // langAzerbaijani → smCyrillic - 50: 4, // langAzerbaijanAr → smArabic - 51: 24, // langArmenian → smArmenian - 52: 23, // langGeorgian → smGeorgian - 53: 7, // langMoldavian → smCyrillic - 54: 7, // langKirghiz → smCyrillic - 55: 7, // langTajiki → smCyrillic - 56: 7, // langTurkmen → smCyrillic - 57: 27, // langMongolian → smMongolian - 58: 7, // langMongolianCyr → smCyrillic - 59: 4, // langPashto → smArabic - 60: 4, // langKurdish → smArabic - 61: 4, // langKashmiri → smArabic - 62: 4, // langSindhi → smArabic - 63: 26, // langTibetan → smTibetan - 64: 9, // langNepali → smDevanagari - 65: 9, // langSanskrit → smDevanagari - 66: 9, // langMarathi → smDevanagari - 67: 13, // langBengali → smBengali - 68: 13, // langAssamese → smBengali - 69: 11, // langGujarati → smGujarati - 70: 10, // langPunjabi → smGurmukhi - 71: 12, // langOriya → smOriya - 72: 17, // langMalayalam → smMalayalam - 73: 16, // langKannada → smKannada - 74: 14, // langTamil → smTamil - 75: 15, // langTelugu → smTelugu - 76: 18, // langSinhalese → smSinhalese - 77: 19, // langBurmese → smBurmese - 78: 20, // langKhmer → smKhmer - 79: 22, // langLao → smLao - 80: 30, // langVietnamese → smVietnamese - 81: 0, // langIndonesian → smRoman - 82: 0, // langTagalog → smRoman - 83: 0, // langMalayRoman → smRoman - 84: 4, // langMalayArabic → smArabic - 85: 28, // langAmharic → smEthiopic - 86: 28, // langTigrinya → smEthiopic - 87: 28, // langOromo → smEthiopic - 88: 0, // langSomali → smRoman - 89: 0, // langSwahili → smRoman - 90: 0, // langKinyarwanda → smRoman - 91: 0, // langRundi → smRoman - 92: 0, // langNyanja → smRoman - 93: 0, // langMalagasy → smRoman - 94: 0, // langEsperanto → smRoman - 128: 0, // langWelsh → smRoman (modified) - 129: 0, // langBasque → smRoman - 130: 0, // langCatalan → smRoman - 131: 0, // langLatin → smRoman - 132: 0, // langQuechua → smRoman - 133: 0, // langGuarani → smRoman - 134: 0, // langAymara → smRoman - 135: 7, // langTatar → smCyrillic - 136: 4, // langUighur → smArabic - 137: 26, // langDzongkha → smTibetan - 138: 0, // langJavaneseRom → smRoman - 139: 0, // langSundaneseRom → smRoman - 140: 0, // langGalician → smRoman - 141: 0, // langAfrikaans → smRoman - 142: 0, // langBreton → smRoman (modified) - 143: 28, // langInuktitut → smEthiopic (modified) - 144: 0, // langScottishGaelic → smRoman (modified) - 145: 0, // langManxGaelic → smRoman (modified) - 146: 0, // langIrishGaelicScript → smRoman (modified) - 147: 0, // langTongan → smRoman - 148: 6, // langGreekAncient → smRoman - 149: 0, // langGreenlandic → smRoman - 150: 0, // langAzerbaijanRoman → smRoman - 151: 0 // langNynorsk → smRoman -}; + function getHostParentFiber(fiber) { + var parent = fiber.return; -// While Microsoft indicates a region/country for all its language -// IDs, we omit the region code if it's equal to the "most likely -// region subtag" according to Unicode CLDR. For scripts, we omit -// the subtag if it is equal to the Suppress-Script entry in the -// IANA language subtag registry for IETF BCP 47. -// -// For example, Microsoft states that its language code 0x041A is -// Croatian in Croatia. We transform this to the BCP 47 language code 'hr' -// and not 'hr-HR' because Croatia is the default country for Croatian, -// according to Unicode CLDR. As another example, Microsoft states -// that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform -// this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script -// for the Croatian language, according to IANA. -// -// http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html -// http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry -var windowsLanguages = { - 0x0436: 'af', - 0x041C: 'sq', - 0x0484: 'gsw', - 0x045E: 'am', - 0x1401: 'ar-DZ', - 0x3C01: 'ar-BH', - 0x0C01: 'ar', - 0x0801: 'ar-IQ', - 0x2C01: 'ar-JO', - 0x3401: 'ar-KW', - 0x3001: 'ar-LB', - 0x1001: 'ar-LY', - 0x1801: 'ary', - 0x2001: 'ar-OM', - 0x4001: 'ar-QA', - 0x0401: 'ar-SA', - 0x2801: 'ar-SY', - 0x1C01: 'aeb', - 0x3801: 'ar-AE', - 0x2401: 'ar-YE', - 0x042B: 'hy', - 0x044D: 'as', - 0x082C: 'az-Cyrl', - 0x042C: 'az', - 0x046D: 'ba', - 0x042D: 'eu', - 0x0423: 'be', - 0x0845: 'bn', - 0x0445: 'bn-IN', - 0x201A: 'bs-Cyrl', - 0x141A: 'bs', - 0x047E: 'br', - 0x0402: 'bg', - 0x0403: 'ca', - 0x0C04: 'zh-HK', - 0x1404: 'zh-MO', - 0x0804: 'zh', - 0x1004: 'zh-SG', - 0x0404: 'zh-TW', - 0x0483: 'co', - 0x041A: 'hr', - 0x101A: 'hr-BA', - 0x0405: 'cs', - 0x0406: 'da', - 0x048C: 'prs', - 0x0465: 'dv', - 0x0813: 'nl-BE', - 0x0413: 'nl', - 0x0C09: 'en-AU', - 0x2809: 'en-BZ', - 0x1009: 'en-CA', - 0x2409: 'en-029', - 0x4009: 'en-IN', - 0x1809: 'en-IE', - 0x2009: 'en-JM', - 0x4409: 'en-MY', - 0x1409: 'en-NZ', - 0x3409: 'en-PH', - 0x4809: 'en-SG', - 0x1C09: 'en-ZA', - 0x2C09: 'en-TT', - 0x0809: 'en-GB', - 0x0409: 'en', - 0x3009: 'en-ZW', - 0x0425: 'et', - 0x0438: 'fo', - 0x0464: 'fil', - 0x040B: 'fi', - 0x080C: 'fr-BE', - 0x0C0C: 'fr-CA', - 0x040C: 'fr', - 0x140C: 'fr-LU', - 0x180C: 'fr-MC', - 0x100C: 'fr-CH', - 0x0462: 'fy', - 0x0456: 'gl', - 0x0437: 'ka', - 0x0C07: 'de-AT', - 0x0407: 'de', - 0x1407: 'de-LI', - 0x1007: 'de-LU', - 0x0807: 'de-CH', - 0x0408: 'el', - 0x046F: 'kl', - 0x0447: 'gu', - 0x0468: 'ha', - 0x040D: 'he', - 0x0439: 'hi', - 0x040E: 'hu', - 0x040F: 'is', - 0x0470: 'ig', - 0x0421: 'id', - 0x045D: 'iu', - 0x085D: 'iu-Latn', - 0x083C: 'ga', - 0x0434: 'xh', - 0x0435: 'zu', - 0x0410: 'it', - 0x0810: 'it-CH', - 0x0411: 'ja', - 0x044B: 'kn', - 0x043F: 'kk', - 0x0453: 'km', - 0x0486: 'quc', - 0x0487: 'rw', - 0x0441: 'sw', - 0x0457: 'kok', - 0x0412: 'ko', - 0x0440: 'ky', - 0x0454: 'lo', - 0x0426: 'lv', - 0x0427: 'lt', - 0x082E: 'dsb', - 0x046E: 'lb', - 0x042F: 'mk', - 0x083E: 'ms-BN', - 0x043E: 'ms', - 0x044C: 'ml', - 0x043A: 'mt', - 0x0481: 'mi', - 0x047A: 'arn', - 0x044E: 'mr', - 0x047C: 'moh', - 0x0450: 'mn', - 0x0850: 'mn-CN', - 0x0461: 'ne', - 0x0414: 'nb', - 0x0814: 'nn', - 0x0482: 'oc', - 0x0448: 'or', - 0x0463: 'ps', - 0x0415: 'pl', - 0x0416: 'pt', - 0x0816: 'pt-PT', - 0x0446: 'pa', - 0x046B: 'qu-BO', - 0x086B: 'qu-EC', - 0x0C6B: 'qu', - 0x0418: 'ro', - 0x0417: 'rm', - 0x0419: 'ru', - 0x243B: 'smn', - 0x103B: 'smj-NO', - 0x143B: 'smj', - 0x0C3B: 'se-FI', - 0x043B: 'se', - 0x083B: 'se-SE', - 0x203B: 'sms', - 0x183B: 'sma-NO', - 0x1C3B: 'sms', - 0x044F: 'sa', - 0x1C1A: 'sr-Cyrl-BA', - 0x0C1A: 'sr', - 0x181A: 'sr-Latn-BA', - 0x081A: 'sr-Latn', - 0x046C: 'nso', - 0x0432: 'tn', - 0x045B: 'si', - 0x041B: 'sk', - 0x0424: 'sl', - 0x2C0A: 'es-AR', - 0x400A: 'es-BO', - 0x340A: 'es-CL', - 0x240A: 'es-CO', - 0x140A: 'es-CR', - 0x1C0A: 'es-DO', - 0x300A: 'es-EC', - 0x440A: 'es-SV', - 0x100A: 'es-GT', - 0x480A: 'es-HN', - 0x080A: 'es-MX', - 0x4C0A: 'es-NI', - 0x180A: 'es-PA', - 0x3C0A: 'es-PY', - 0x280A: 'es-PE', - 0x500A: 'es-PR', - - // Microsoft has defined two different language codes for - // “Spanish with modern sorting” and “Spanish with traditional - // sorting”. This makes sense for collation APIs, and it would be - // possible to express this in BCP 47 language tags via Unicode - // extensions (eg., es-u-co-trad is Spanish with traditional - // sorting). However, for storing names in fonts, the distinction - // does not make sense, so we give “es” in both cases. - 0x0C0A: 'es', - 0x040A: 'es', - - 0x540A: 'es-US', - 0x380A: 'es-UY', - 0x200A: 'es-VE', - 0x081D: 'sv-FI', - 0x041D: 'sv', - 0x045A: 'syr', - 0x0428: 'tg', - 0x085F: 'tzm', - 0x0449: 'ta', - 0x0444: 'tt', - 0x044A: 'te', - 0x041E: 'th', - 0x0451: 'bo', - 0x041F: 'tr', - 0x0442: 'tk', - 0x0480: 'ug', - 0x0422: 'uk', - 0x042E: 'hsb', - 0x0420: 'ur', - 0x0843: 'uz-Cyrl', - 0x0443: 'uz', - 0x042A: 'vi', - 0x0452: 'cy', - 0x0488: 'wo', - 0x0485: 'sah', - 0x0478: 'ii', - 0x046A: 'yo' -}; + while (parent !== null) { + if (isHostParent(parent)) { + return parent; + } -// Returns a IETF BCP 47 language code, for example 'zh-Hant' -// for 'Chinese in the traditional script'. -function getLanguageCode(platformID, languageID, ltag) { - switch (platformID) { - case 0: // Unicode - if (languageID === 0xFFFF) { - return 'und'; - } else if (ltag) { - return ltag[languageID]; - } + parent = parent.return; + } - break; + throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.'); + } - case 1: // Macintosh - return macLanguages[languageID]; + function isHostParent(fiber) { + return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; + } - case 3: // Windows - return windowsLanguages[languageID]; - } + function getHostSibling(fiber) { + // We're going to search forward into the tree until we find a sibling host + // node. Unfortunately, if multiple insertions are done in a row we have to + // search past them. This leads to exponential search for the next sibling. + // TODO: Find a more efficient way to do this. + var node = fiber; - return undefined; -} - -var utf16 = 'utf-16'; - -// MacOS script ID → encoding. This table stores the default case, -// which can be overridden by macLanguageEncodings. -var macScriptEncodings = { - 0: 'macintosh', // smRoman - 1: 'x-mac-japanese', // smJapanese - 2: 'x-mac-chinesetrad', // smTradChinese - 3: 'x-mac-korean', // smKorean - 6: 'x-mac-greek', // smGreek - 7: 'x-mac-cyrillic', // smCyrillic - 9: 'x-mac-devanagai', // smDevanagari - 10: 'x-mac-gurmukhi', // smGurmukhi - 11: 'x-mac-gujarati', // smGujarati - 12: 'x-mac-oriya', // smOriya - 13: 'x-mac-bengali', // smBengali - 14: 'x-mac-tamil', // smTamil - 15: 'x-mac-telugu', // smTelugu - 16: 'x-mac-kannada', // smKannada - 17: 'x-mac-malayalam', // smMalayalam - 18: 'x-mac-sinhalese', // smSinhalese - 19: 'x-mac-burmese', // smBurmese - 20: 'x-mac-khmer', // smKhmer - 21: 'x-mac-thai', // smThai - 22: 'x-mac-lao', // smLao - 23: 'x-mac-georgian', // smGeorgian - 24: 'x-mac-armenian', // smArmenian - 25: 'x-mac-chinesesimp', // smSimpChinese - 26: 'x-mac-tibetan', // smTibetan - 27: 'x-mac-mongolian', // smMongolian - 28: 'x-mac-ethiopic', // smEthiopic - 29: 'x-mac-ce', // smCentralEuroRoman - 30: 'x-mac-vietnamese', // smVietnamese - 31: 'x-mac-extarabic' // smExtArabic -}; + siblings: while (true) { + // If we didn't find anything, let's try the next sibling. + while (node.sibling === null) { + if (node.return === null || isHostParent(node.return)) { + // If we pop out of the root or hit the parent the fiber we are the + // last sibling. + return null; + } -// MacOS language ID → encoding. This table stores the exceptional -// cases, which override macScriptEncodings. For writing MacOS naming -// tables, we need to emit a MacOS script ID. Therefore, we cannot -// merge macScriptEncodings into macLanguageEncodings. -// -// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt -var macLanguageEncodings = { - 15: 'x-mac-icelandic', // langIcelandic - 17: 'x-mac-turkish', // langTurkish - 18: 'x-mac-croatian', // langCroatian - 24: 'x-mac-ce', // langLithuanian - 25: 'x-mac-ce', // langPolish - 26: 'x-mac-ce', // langHungarian - 27: 'x-mac-ce', // langEstonian - 28: 'x-mac-ce', // langLatvian - 30: 'x-mac-icelandic', // langFaroese - 37: 'x-mac-romanian', // langRomanian - 38: 'x-mac-ce', // langCzech - 39: 'x-mac-ce', // langSlovak - 40: 'x-mac-ce', // langSlovenian - 143: 'x-mac-inuit', // langInuktitut - 146: 'x-mac-gaelic' // langIrishGaelicScript -}; + node = node.return; + } -function getEncoding(platformID, encodingID, languageID) { - switch (platformID) { - case 0: // Unicode - return utf16; + node.sibling.return = node.return; + node = node.sibling; - case 1: // Apple Macintosh - return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; + while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) { + // If it is not host node and, we might have a host node inside it. + // Try to search down until we find one. + if (node.flags & Placement) { + // If we don't have a child, try the siblings instead. + continue siblings; + } // If we don't have a child, try the siblings instead. + // We also skip portals because they are not part of this host tree. - case 3: // Microsoft Windows - if (encodingID === 1 || encodingID === 10) { - return utf16; - } - break; - } + if (node.child === null || node.tag === HostPortal) { + continue siblings; + } else { + node.child.return = node; + node = node.child; + } + } // Check if this host node is stable or about to be placed. - return undefined; -} - -// Parse the naming `name` table. -// FIXME: Format 1 additional fields are not supported yet. -// ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904']. -function parseNameTable(data, start, ltag) { - var name = {}; - var p = new parse.Parser(data, start); - var format = p.parseUShort(); - var count = p.parseUShort(); - var stringOffset = p.offset + p.parseUShort(); - for (var i = 0; i < count; i++) { - var platformID = p.parseUShort(); - var encodingID = p.parseUShort(); - var languageID = p.parseUShort(); - var nameID = p.parseUShort(); - var property = nameTableNames[nameID] || nameID; - var byteLength = p.parseUShort(); - var offset = p.parseUShort(); - var language = getLanguageCode(platformID, languageID, ltag); - var encoding = getEncoding(platformID, encodingID, languageID); - if (encoding !== undefined && language !== undefined) { - var text = (void 0); - if (encoding === utf16) { - text = decode.UTF16(data, stringOffset + offset, byteLength); - } else { - text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding); - } - if (text) { - var translations = name[property]; - if (translations === undefined) { - translations = name[property] = {}; - } + if (!(node.flags & Placement)) { + // Found it! + return node.stateNode; + } + } + } - translations[language] = text; - } - } - } - if (format === 1) { - // FIXME: Also handle Microsoft's 'name' table 1. - p.parseUShort(); - } + function commitPlacement(finishedWork) { + if (!supportsMutation) { + return; + } // Recursively insert all host nodes into the parent. - return name; -} -// {23: 'foo'} → {'foo': 23} -// ['bar', 'baz'] → {'bar': 0, 'baz': 1} -function reverseDict(dict) { - var result = {}; - for (var key in dict) { - result[dict[key]] = parseInt(key); - } + var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. - return result; -} + switch (parentFiber.tag) { + case HostComponent: + { + var parent = parentFiber.stateNode; -function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) { - return new table.Record('NameRecord', [ - {name: 'platformID', type: 'USHORT', value: platformID}, - {name: 'encodingID', type: 'USHORT', value: encodingID}, - {name: 'languageID', type: 'USHORT', value: languageID}, - {name: 'nameID', type: 'USHORT', value: nameID}, - {name: 'length', type: 'USHORT', value: length}, - {name: 'offset', type: 'USHORT', value: offset} - ]); -} + if (parentFiber.flags & ContentReset) { + // Reset the text content of the parent before doing any insertions + resetTextContent(parent); // Clear ContentReset from the effect tag -// Finds the position of needle in haystack, or -1 if not there. -// Like String.indexOf(), but for arrays. -function findSubArray(needle, haystack) { - var needleLength = needle.length; - var limit = haystack.length - needleLength + 1; + parentFiber.flags &= ~ContentReset; + } - loop: - for (var pos = 0; pos < limit; pos++) { - for (; pos < limit; pos++) { - for (var k = 0; k < needleLength; k++) { - if (haystack[pos + k] !== needle[k]) { - continue loop; - } - } + var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its + // children to find all the terminal nodes. - return pos; - } - } + insertOrAppendPlacementNode(finishedWork, before, parent); + break; + } - return -1; -} + case HostRoot: + case HostPortal: + { + var _parent = parentFiber.stateNode.containerInfo; -function addStringToPool(s, pool) { - var offset = findSubArray(s, pool); - if (offset < 0) { - offset = pool.length; - var i = 0; - var len = s.length; - for (; i < len; ++i) { - pool.push(s[i]); - } + var _before = getHostSibling(finishedWork); - } + insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent); + break; + } + // eslint-disable-next-line-no-fallthrough - return offset; -} + default: + throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.'); + } + } -function makeNameTable(names, ltag) { - var nameID; - var nameIDs = []; + function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { + var tag = node.tag; + var isHost = tag === HostComponent || tag === HostText; - var namesWithNumericKeys = {}; - var nameTableIds = reverseDict(nameTableNames); - for (var key in names) { - var id = nameTableIds[key]; - if (id === undefined) { - id = key; - } + if (isHost) { + var stateNode = node.stateNode; - nameID = parseInt(id); + if (before) { + insertInContainerBefore(parent, stateNode, before); + } else { + appendChildToContainer(parent, stateNode); + } + } else if (tag === HostPortal) ; else { + var child = node.child; - if (isNaN(nameID)) { - throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.'); - } + if (child !== null) { + insertOrAppendPlacementNodeIntoContainer(child, before, parent); + var sibling = child.sibling; - namesWithNumericKeys[nameID] = names[key]; - nameIDs.push(nameID); - } + while (sibling !== null) { + insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); + sibling = sibling.sibling; + } + } + } + } - var macLanguageIds = reverseDict(macLanguages); - var windowsLanguageIds = reverseDict(windowsLanguages); - - var nameRecords = []; - var stringPool = []; - - for (var i = 0; i < nameIDs.length; i++) { - nameID = nameIDs[i]; - var translations = namesWithNumericKeys[nameID]; - for (var lang in translations) { - var text = translations[lang]; - - // For MacOS, we try to emit the name in the form that was introduced - // in the initial version of the TrueType spec (in the late 1980s). - // However, this can fail for various reasons: the requested BCP 47 - // language code might not have an old-style Mac equivalent; - // we might not have a codec for the needed character encoding; - // or the name might contain characters that cannot be expressed - // in the old-style Macintosh encoding. In case of failure, we emit - // the name in a more modern fashion (Unicode encoding with BCP 47 - // language tags) that is recognized by MacOS 10.5, released in 2009. - // If fonts were only read by operating systems, we could simply - // emit all names in the modern form; this would be much easier. - // However, there are many applications and libraries that read - // 'name' tables directly, and these will usually only recognize - // the ancient form (silently skipping the unrecognized names). - var macPlatform = 1; // Macintosh - var macLanguage = macLanguageIds[lang]; - var macScript = macLanguageToScript[macLanguage]; - var macEncoding = getEncoding(macPlatform, macScript, macLanguage); - var macName = encode.MACSTRING(text, macEncoding); - if (macName === undefined) { - macPlatform = 0; // Unicode - macLanguage = ltag.indexOf(lang); - if (macLanguage < 0) { - macLanguage = ltag.length; - ltag.push(lang); - } + function insertOrAppendPlacementNode(node, before, parent) { + var tag = node.tag; + var isHost = tag === HostComponent || tag === HostText; - macScript = 4; // Unicode 2.0 and later - macName = encode.UTF16(text); - } + if (isHost) { + var stateNode = node.stateNode; - var macNameOffset = addStringToPool(macName, stringPool); - nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, - nameID, macName.length, macNameOffset)); + if (before) { + insertBefore(parent, stateNode, before); + } else { + appendChild(parent, stateNode); + } + } else if (tag === HostPortal) ; else { + var child = node.child; - var winLanguage = windowsLanguageIds[lang]; - if (winLanguage !== undefined) { - var winName = encode.UTF16(text); - var winNameOffset = addStringToPool(winName, stringPool); - nameRecords.push(makeNameRecord(3, 1, winLanguage, - nameID, winName.length, winNameOffset)); - } - } - } + if (child !== null) { + insertOrAppendPlacementNode(child, before, parent); + var sibling = child.sibling; - nameRecords.sort(function(a, b) { - return ((a.platformID - b.platformID) || - (a.encodingID - b.encodingID) || - (a.languageID - b.languageID) || - (a.nameID - b.nameID)); - }); + while (sibling !== null) { + insertOrAppendPlacementNode(sibling, before, parent); + sibling = sibling.sibling; + } + } + } + } - var t = new table.Table('name', [ - {name: 'format', type: 'USHORT', value: 0}, - {name: 'count', type: 'USHORT', value: nameRecords.length}, - {name: 'stringOffset', type: 'USHORT', value: 6 + nameRecords.length * 12} - ]); + function unmountHostComponents(finishedRoot, current, nearestMountedAncestor) { + // We only have the top Fiber that was deleted but we need to recurse down its + // children to find all the terminal nodes. + var node = current; // Each iteration, currentParent is populated with node's host parent if not + // currentParentIsValid. - for (var r = 0; r < nameRecords.length; r++) { - t.fields.push({name: 'record_' + r, type: 'RECORD', value: nameRecords[r]}); - } + var currentParentIsValid = false; // Note: these two variables *must* always be updated together. - t.fields.push({name: 'strings', type: 'LITERAL', value: stringPool}); - return t; -} - -var _name = { parse: parseNameTable, make: makeNameTable }; - -// The `OS/2` table contains metrics required in OpenType fonts. - -var unicodeRanges = [ - {begin: 0x0000, end: 0x007F}, // Basic Latin - {begin: 0x0080, end: 0x00FF}, // Latin-1 Supplement - {begin: 0x0100, end: 0x017F}, // Latin Extended-A - {begin: 0x0180, end: 0x024F}, // Latin Extended-B - {begin: 0x0250, end: 0x02AF}, // IPA Extensions - {begin: 0x02B0, end: 0x02FF}, // Spacing Modifier Letters - {begin: 0x0300, end: 0x036F}, // Combining Diacritical Marks - {begin: 0x0370, end: 0x03FF}, // Greek and Coptic - {begin: 0x2C80, end: 0x2CFF}, // Coptic - {begin: 0x0400, end: 0x04FF}, // Cyrillic - {begin: 0x0530, end: 0x058F}, // Armenian - {begin: 0x0590, end: 0x05FF}, // Hebrew - {begin: 0xA500, end: 0xA63F}, // Vai - {begin: 0x0600, end: 0x06FF}, // Arabic - {begin: 0x07C0, end: 0x07FF}, // NKo - {begin: 0x0900, end: 0x097F}, // Devanagari - {begin: 0x0980, end: 0x09FF}, // Bengali - {begin: 0x0A00, end: 0x0A7F}, // Gurmukhi - {begin: 0x0A80, end: 0x0AFF}, // Gujarati - {begin: 0x0B00, end: 0x0B7F}, // Oriya - {begin: 0x0B80, end: 0x0BFF}, // Tamil - {begin: 0x0C00, end: 0x0C7F}, // Telugu - {begin: 0x0C80, end: 0x0CFF}, // Kannada - {begin: 0x0D00, end: 0x0D7F}, // Malayalam - {begin: 0x0E00, end: 0x0E7F}, // Thai - {begin: 0x0E80, end: 0x0EFF}, // Lao - {begin: 0x10A0, end: 0x10FF}, // Georgian - {begin: 0x1B00, end: 0x1B7F}, // Balinese - {begin: 0x1100, end: 0x11FF}, // Hangul Jamo - {begin: 0x1E00, end: 0x1EFF}, // Latin Extended Additional - {begin: 0x1F00, end: 0x1FFF}, // Greek Extended - {begin: 0x2000, end: 0x206F}, // General Punctuation - {begin: 0x2070, end: 0x209F}, // Superscripts And Subscripts - {begin: 0x20A0, end: 0x20CF}, // Currency Symbol - {begin: 0x20D0, end: 0x20FF}, // Combining Diacritical Marks For Symbols - {begin: 0x2100, end: 0x214F}, // Letterlike Symbols - {begin: 0x2150, end: 0x218F}, // Number Forms - {begin: 0x2190, end: 0x21FF}, // Arrows - {begin: 0x2200, end: 0x22FF}, // Mathematical Operators - {begin: 0x2300, end: 0x23FF}, // Miscellaneous Technical - {begin: 0x2400, end: 0x243F}, // Control Pictures - {begin: 0x2440, end: 0x245F}, // Optical Character Recognition - {begin: 0x2460, end: 0x24FF}, // Enclosed Alphanumerics - {begin: 0x2500, end: 0x257F}, // Box Drawing - {begin: 0x2580, end: 0x259F}, // Block Elements - {begin: 0x25A0, end: 0x25FF}, // Geometric Shapes - {begin: 0x2600, end: 0x26FF}, // Miscellaneous Symbols - {begin: 0x2700, end: 0x27BF}, // Dingbats - {begin: 0x3000, end: 0x303F}, // CJK Symbols And Punctuation - {begin: 0x3040, end: 0x309F}, // Hiragana - {begin: 0x30A0, end: 0x30FF}, // Katakana - {begin: 0x3100, end: 0x312F}, // Bopomofo - {begin: 0x3130, end: 0x318F}, // Hangul Compatibility Jamo - {begin: 0xA840, end: 0xA87F}, // Phags-pa - {begin: 0x3200, end: 0x32FF}, // Enclosed CJK Letters And Months - {begin: 0x3300, end: 0x33FF}, // CJK Compatibility - {begin: 0xAC00, end: 0xD7AF}, // Hangul Syllables - {begin: 0xD800, end: 0xDFFF}, // Non-Plane 0 * - {begin: 0x10900, end: 0x1091F}, // Phoenicia - {begin: 0x4E00, end: 0x9FFF}, // CJK Unified Ideographs - {begin: 0xE000, end: 0xF8FF}, // Private Use Area (plane 0) - {begin: 0x31C0, end: 0x31EF}, // CJK Strokes - {begin: 0xFB00, end: 0xFB4F}, // Alphabetic Presentation Forms - {begin: 0xFB50, end: 0xFDFF}, // Arabic Presentation Forms-A - {begin: 0xFE20, end: 0xFE2F}, // Combining Half Marks - {begin: 0xFE10, end: 0xFE1F}, // Vertical Forms - {begin: 0xFE50, end: 0xFE6F}, // Small Form Variants - {begin: 0xFE70, end: 0xFEFF}, // Arabic Presentation Forms-B - {begin: 0xFF00, end: 0xFFEF}, // Halfwidth And Fullwidth Forms - {begin: 0xFFF0, end: 0xFFFF}, // Specials - {begin: 0x0F00, end: 0x0FFF}, // Tibetan - {begin: 0x0700, end: 0x074F}, // Syriac - {begin: 0x0780, end: 0x07BF}, // Thaana - {begin: 0x0D80, end: 0x0DFF}, // Sinhala - {begin: 0x1000, end: 0x109F}, // Myanmar - {begin: 0x1200, end: 0x137F}, // Ethiopic - {begin: 0x13A0, end: 0x13FF}, // Cherokee - {begin: 0x1400, end: 0x167F}, // Unified Canadian Aboriginal Syllabics - {begin: 0x1680, end: 0x169F}, // Ogham - {begin: 0x16A0, end: 0x16FF}, // Runic - {begin: 0x1780, end: 0x17FF}, // Khmer - {begin: 0x1800, end: 0x18AF}, // Mongolian - {begin: 0x2800, end: 0x28FF}, // Braille Patterns - {begin: 0xA000, end: 0xA48F}, // Yi Syllables - {begin: 0x1700, end: 0x171F}, // Tagalog - {begin: 0x10300, end: 0x1032F}, // Old Italic - {begin: 0x10330, end: 0x1034F}, // Gothic - {begin: 0x10400, end: 0x1044F}, // Deseret - {begin: 0x1D000, end: 0x1D0FF}, // Byzantine Musical Symbols - {begin: 0x1D400, end: 0x1D7FF}, // Mathematical Alphanumeric Symbols - {begin: 0xFF000, end: 0xFFFFD}, // Private Use (plane 15) - {begin: 0xFE00, end: 0xFE0F}, // Variation Selectors - {begin: 0xE0000, end: 0xE007F}, // Tags - {begin: 0x1900, end: 0x194F}, // Limbu - {begin: 0x1950, end: 0x197F}, // Tai Le - {begin: 0x1980, end: 0x19DF}, // New Tai Lue - {begin: 0x1A00, end: 0x1A1F}, // Buginese - {begin: 0x2C00, end: 0x2C5F}, // Glagolitic - {begin: 0x2D30, end: 0x2D7F}, // Tifinagh - {begin: 0x4DC0, end: 0x4DFF}, // Yijing Hexagram Symbols - {begin: 0xA800, end: 0xA82F}, // Syloti Nagri - {begin: 0x10000, end: 0x1007F}, // Linear B Syllabary - {begin: 0x10140, end: 0x1018F}, // Ancient Greek Numbers - {begin: 0x10380, end: 0x1039F}, // Ugaritic - {begin: 0x103A0, end: 0x103DF}, // Old Persian - {begin: 0x10450, end: 0x1047F}, // Shavian - {begin: 0x10480, end: 0x104AF}, // Osmanya - {begin: 0x10800, end: 0x1083F}, // Cypriot Syllabary - {begin: 0x10A00, end: 0x10A5F}, // Kharoshthi - {begin: 0x1D300, end: 0x1D35F}, // Tai Xuan Jing Symbols - {begin: 0x12000, end: 0x123FF}, // Cuneiform - {begin: 0x1D360, end: 0x1D37F}, // Counting Rod Numerals - {begin: 0x1B80, end: 0x1BBF}, // Sundanese - {begin: 0x1C00, end: 0x1C4F}, // Lepcha - {begin: 0x1C50, end: 0x1C7F}, // Ol Chiki - {begin: 0xA880, end: 0xA8DF}, // Saurashtra - {begin: 0xA900, end: 0xA92F}, // Kayah Li - {begin: 0xA930, end: 0xA95F}, // Rejang - {begin: 0xAA00, end: 0xAA5F}, // Cham - {begin: 0x10190, end: 0x101CF}, // Ancient Symbols - {begin: 0x101D0, end: 0x101FF}, // Phaistos Disc - {begin: 0x102A0, end: 0x102DF}, // Carian - {begin: 0x1F030, end: 0x1F09F} // Domino Tiles -]; + var currentParent; + var currentParentIsContainer; -function getUnicodeRange(unicode) { - for (var i = 0; i < unicodeRanges.length; i += 1) { - var range = unicodeRanges[i]; - if (unicode >= range.begin && unicode < range.end) { - return i; - } - } + while (true) { + if (!currentParentIsValid) { + var parent = node.return; - return -1; -} + findParent: while (true) { + if (parent === null) { + throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.'); + } -// Parse the OS/2 and Windows metrics `OS/2` table -function parseOS2Table(data, start) { - var os2 = {}; - var p = new parse.Parser(data, start); - os2.version = p.parseUShort(); - os2.xAvgCharWidth = p.parseShort(); - os2.usWeightClass = p.parseUShort(); - os2.usWidthClass = p.parseUShort(); - os2.fsType = p.parseUShort(); - os2.ySubscriptXSize = p.parseShort(); - os2.ySubscriptYSize = p.parseShort(); - os2.ySubscriptXOffset = p.parseShort(); - os2.ySubscriptYOffset = p.parseShort(); - os2.ySuperscriptXSize = p.parseShort(); - os2.ySuperscriptYSize = p.parseShort(); - os2.ySuperscriptXOffset = p.parseShort(); - os2.ySuperscriptYOffset = p.parseShort(); - os2.yStrikeoutSize = p.parseShort(); - os2.yStrikeoutPosition = p.parseShort(); - os2.sFamilyClass = p.parseShort(); - os2.panose = []; - for (var i = 0; i < 10; i++) { - os2.panose[i] = p.parseByte(); - } + var parentStateNode = parent.stateNode; - os2.ulUnicodeRange1 = p.parseULong(); - os2.ulUnicodeRange2 = p.parseULong(); - os2.ulUnicodeRange3 = p.parseULong(); - os2.ulUnicodeRange4 = p.parseULong(); - os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); - os2.fsSelection = p.parseUShort(); - os2.usFirstCharIndex = p.parseUShort(); - os2.usLastCharIndex = p.parseUShort(); - os2.sTypoAscender = p.parseShort(); - os2.sTypoDescender = p.parseShort(); - os2.sTypoLineGap = p.parseShort(); - os2.usWinAscent = p.parseUShort(); - os2.usWinDescent = p.parseUShort(); - if (os2.version >= 1) { - os2.ulCodePageRange1 = p.parseULong(); - os2.ulCodePageRange2 = p.parseULong(); - } + switch (parent.tag) { + case HostComponent: + currentParent = parentStateNode; + currentParentIsContainer = false; + break findParent; - if (os2.version >= 2) { - os2.sxHeight = p.parseShort(); - os2.sCapHeight = p.parseShort(); - os2.usDefaultChar = p.parseUShort(); - os2.usBreakChar = p.parseUShort(); - os2.usMaxContent = p.parseUShort(); - } + case HostRoot: + currentParent = parentStateNode.containerInfo; + currentParentIsContainer = true; + break findParent; - return os2; -} - -function makeOS2Table(options) { - return new table.Table('OS/2', [ - {name: 'version', type: 'USHORT', value: 0x0003}, - {name: 'xAvgCharWidth', type: 'SHORT', value: 0}, - {name: 'usWeightClass', type: 'USHORT', value: 0}, - {name: 'usWidthClass', type: 'USHORT', value: 0}, - {name: 'fsType', type: 'USHORT', value: 0}, - {name: 'ySubscriptXSize', type: 'SHORT', value: 650}, - {name: 'ySubscriptYSize', type: 'SHORT', value: 699}, - {name: 'ySubscriptXOffset', type: 'SHORT', value: 0}, - {name: 'ySubscriptYOffset', type: 'SHORT', value: 140}, - {name: 'ySuperscriptXSize', type: 'SHORT', value: 650}, - {name: 'ySuperscriptYSize', type: 'SHORT', value: 699}, - {name: 'ySuperscriptXOffset', type: 'SHORT', value: 0}, - {name: 'ySuperscriptYOffset', type: 'SHORT', value: 479}, - {name: 'yStrikeoutSize', type: 'SHORT', value: 49}, - {name: 'yStrikeoutPosition', type: 'SHORT', value: 258}, - {name: 'sFamilyClass', type: 'SHORT', value: 0}, - {name: 'bFamilyType', type: 'BYTE', value: 0}, - {name: 'bSerifStyle', type: 'BYTE', value: 0}, - {name: 'bWeight', type: 'BYTE', value: 0}, - {name: 'bProportion', type: 'BYTE', value: 0}, - {name: 'bContrast', type: 'BYTE', value: 0}, - {name: 'bStrokeVariation', type: 'BYTE', value: 0}, - {name: 'bArmStyle', type: 'BYTE', value: 0}, - {name: 'bLetterform', type: 'BYTE', value: 0}, - {name: 'bMidline', type: 'BYTE', value: 0}, - {name: 'bXHeight', type: 'BYTE', value: 0}, - {name: 'ulUnicodeRange1', type: 'ULONG', value: 0}, - {name: 'ulUnicodeRange2', type: 'ULONG', value: 0}, - {name: 'ulUnicodeRange3', type: 'ULONG', value: 0}, - {name: 'ulUnicodeRange4', type: 'ULONG', value: 0}, - {name: 'achVendID', type: 'CHARARRAY', value: 'XXXX'}, - {name: 'fsSelection', type: 'USHORT', value: 0}, - {name: 'usFirstCharIndex', type: 'USHORT', value: 0}, - {name: 'usLastCharIndex', type: 'USHORT', value: 0}, - {name: 'sTypoAscender', type: 'SHORT', value: 0}, - {name: 'sTypoDescender', type: 'SHORT', value: 0}, - {name: 'sTypoLineGap', type: 'SHORT', value: 0}, - {name: 'usWinAscent', type: 'USHORT', value: 0}, - {name: 'usWinDescent', type: 'USHORT', value: 0}, - {name: 'ulCodePageRange1', type: 'ULONG', value: 0}, - {name: 'ulCodePageRange2', type: 'ULONG', value: 0}, - {name: 'sxHeight', type: 'SHORT', value: 0}, - {name: 'sCapHeight', type: 'SHORT', value: 0}, - {name: 'usDefaultChar', type: 'USHORT', value: 0}, - {name: 'usBreakChar', type: 'USHORT', value: 0}, - {name: 'usMaxContext', type: 'USHORT', value: 0} - ], options); -} - -var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges: unicodeRanges, getUnicodeRange: getUnicodeRange }; - -// The `post` table stores additional PostScript information, such as glyph names. - -// Parse the PostScript `post` table -function parsePostTable(data, start) { - var post = {}; - var p = new parse.Parser(data, start); - post.version = p.parseVersion(); - post.italicAngle = p.parseFixed(); - post.underlinePosition = p.parseShort(); - post.underlineThickness = p.parseShort(); - post.isFixedPitch = p.parseULong(); - post.minMemType42 = p.parseULong(); - post.maxMemType42 = p.parseULong(); - post.minMemType1 = p.parseULong(); - post.maxMemType1 = p.parseULong(); - switch (post.version) { - case 1: - post.names = standardNames.slice(); - break; - case 2: - post.numberOfGlyphs = p.parseUShort(); - post.glyphNameIndex = new Array(post.numberOfGlyphs); - for (var i = 0; i < post.numberOfGlyphs; i++) { - post.glyphNameIndex[i] = p.parseUShort(); - } + case HostPortal: + currentParent = parentStateNode.containerInfo; + currentParentIsContainer = true; + break findParent; + } - post.names = []; - for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) { - if (post.glyphNameIndex[i$1] >= standardNames.length) { - var nameLength = p.parseChar(); - post.names.push(p.parseString(nameLength)); - } - } + parent = parent.return; + } - break; - case 2.5: - post.numberOfGlyphs = p.parseUShort(); - post.offset = new Array(post.numberOfGlyphs); - for (var i$2 = 0; i$2 < post.numberOfGlyphs; i$2++) { - post.offset[i$2] = p.parseChar(); - } + currentParentIsValid = true; + } - break; - } - return post; -} - -function makePostTable() { - return new table.Table('post', [ - {name: 'version', type: 'FIXED', value: 0x00030000}, - {name: 'italicAngle', type: 'FIXED', value: 0}, - {name: 'underlinePosition', type: 'FWORD', value: 0}, - {name: 'underlineThickness', type: 'FWORD', value: 0}, - {name: 'isFixedPitch', type: 'ULONG', value: 0}, - {name: 'minMemType42', type: 'ULONG', value: 0}, - {name: 'maxMemType42', type: 'ULONG', value: 0}, - {name: 'minMemType1', type: 'ULONG', value: 0}, - {name: 'maxMemType1', type: 'ULONG', value: 0} - ]); -} + if (node.tag === HostComponent || node.tag === HostText) { + commitNestedUnmounts(finishedRoot, node, nearestMountedAncestor); // After all the children have unmounted, it is now safe to remove the + // node from the tree. -var post = { parse: parsePostTable, make: makePostTable }; + if (currentParentIsContainer) { + removeChildFromContainer(currentParent, node.stateNode); + } else { + removeChild(currentParent, node.stateNode); + } // Don't visit children because we already visited them. -// The `GSUB` table contains ligatures, among other things. + } else if ( node.tag === DehydratedFragment) { -var subtableParsers = new Array(9); // subtableParsers[0] is unused -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS -subtableParsers[1] = function parseLookup1() { - var start = this.offset + this.relativeOffset; - var substFormat = this.parseUShort(); - if (substFormat === 1) { - return { - substFormat: 1, - coverage: this.parsePointer(Parser.coverage), - deltaGlyphId: this.parseUShort() - }; - } else if (substFormat === 2) { - return { - substFormat: 2, - coverage: this.parsePointer(Parser.coverage), - substitute: this.parseOffset16List() - }; - } - check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.'); -}; + if (currentParentIsContainer) { + clearSuspenseBoundaryFromContainer(currentParent, node.stateNode); + } else { + clearSuspenseBoundary(currentParent, node.stateNode); + } + } else if (node.tag === HostPortal) { + if (node.child !== null) { + // When we go into a portal, it becomes the parent to remove from. + // We will reassign it back when we pop the portal on the way up. + currentParent = node.stateNode.containerInfo; + currentParentIsContainer = true; // Visit children because portals might contain host components. -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS -subtableParsers[2] = function parseLookup2() { - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1'); - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - sequences: this.parseListOfLists() - }; -}; + node.child.return = node; + node = node.child; + continue; + } + } else { + commitUnmount(finishedRoot, node, nearestMountedAncestor); // Visit children because we may find more host components below. -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS -subtableParsers[3] = function parseLookup3() { - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1'); - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - alternateSets: this.parseListOfLists() - }; -}; + if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS -subtableParsers[4] = function parseLookup4() { - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1'); - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - ligatureSets: this.parseListOfLists(function() { - return { - ligGlyph: this.parseUShort(), - components: this.parseUShortList(this.parseUShort() - 1) - }; - }) - }; -}; + if (node === current) { + return; + } -var lookupRecordDesc = { - sequenceIndex: Parser.uShort, - lookupListIndex: Parser.uShort -}; + while (node.sibling === null) { + if (node.return === null || node.return === current) { + return; + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF -subtableParsers[5] = function parseLookup5() { - var start = this.offset + this.relativeOffset; - var substFormat = this.parseUShort(); + node = node.return; - if (substFormat === 1) { - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - ruleSets: this.parseListOfLists(function() { - var glyphCount = this.parseUShort(); - var substCount = this.parseUShort(); - return { - input: this.parseUShortList(glyphCount - 1), - lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) - }; - }) - }; - } else if (substFormat === 2) { - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - classDef: this.parsePointer(Parser.classDef), - classSets: this.parseListOfLists(function() { - var glyphCount = this.parseUShort(); - var substCount = this.parseUShort(); - return { - classes: this.parseUShortList(glyphCount - 1), - lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) - }; - }) - }; - } else if (substFormat === 3) { - var glyphCount = this.parseUShort(); - var substCount = this.parseUShort(); - return { - substFormat: substFormat, - coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), - lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) - }; - } - check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.'); -}; + if (node.tag === HostPortal) { + // When we go out of the portal, we need to restore the parent. + // Since we don't keep a stack of them, we will search for it. + currentParentIsValid = false; + } + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC -subtableParsers[6] = function parseLookup6() { - var start = this.offset + this.relativeOffset; - var substFormat = this.parseUShort(); - if (substFormat === 1) { - return { - substFormat: 1, - coverage: this.parsePointer(Parser.coverage), - chainRuleSets: this.parseListOfLists(function() { - return { - backtrack: this.parseUShortList(), - input: this.parseUShortList(this.parseShort() - 1), - lookahead: this.parseUShortList(), - lookupRecords: this.parseRecordList(lookupRecordDesc) - }; - }) - }; - } else if (substFormat === 2) { - return { - substFormat: 2, - coverage: this.parsePointer(Parser.coverage), - backtrackClassDef: this.parsePointer(Parser.classDef), - inputClassDef: this.parsePointer(Parser.classDef), - lookaheadClassDef: this.parsePointer(Parser.classDef), - chainClassSet: this.parseListOfLists(function() { - return { - backtrack: this.parseUShortList(), - input: this.parseUShortList(this.parseShort() - 1), - lookahead: this.parseUShortList(), - lookupRecords: this.parseRecordList(lookupRecordDesc) - }; - }) - }; - } else if (substFormat === 3) { - return { - substFormat: 3, - backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), - inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), - lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), - lookupRecords: this.parseRecordList(lookupRecordDesc) - }; - } - check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.'); -}; + node.sibling.return = node.return; + node = node.sibling; + } + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES -subtableParsers[7] = function parseLookup7() { - // Extension Substitution subtable - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1'); - var extensionLookupType = this.parseUShort(); - var extensionParser = new Parser(this.data, this.offset + this.parseULong()); - return { - substFormat: 1, - lookupType: extensionLookupType, - extension: subtableParsers[extensionLookupType].call(extensionParser) - }; -}; + function commitDeletion(finishedRoot, current, nearestMountedAncestor) { + if (supportsMutation) { + // Recursively delete all host nodes from the parent. + // Detach refs and call componentWillUnmount() on the whole subtree. + unmountHostComponents(finishedRoot, current, nearestMountedAncestor); + } else { + // Detach refs and call componentWillUnmount() on the whole subtree. + commitNestedUnmounts(finishedRoot, current, nearestMountedAncestor); + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS -subtableParsers[8] = function parseLookup8() { - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1'); - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), - lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), - substitutes: this.parseUShortList() - }; -}; + detachFiberMutation(current); + } -// https://www.microsoft.com/typography/OTSPEC/gsub.htm -function parseGsubTable(data, start) { - start = start || 0; - var p = new Parser(data, start); - var tableVersion = p.parseVersion(1); - check.argument(tableVersion === 1 || tableVersion === 1.1, 'Unsupported GSUB table version.'); - if (tableVersion === 1) { - return { - version: tableVersion, - scripts: p.parseScriptList(), - features: p.parseFeatureList(), - lookups: p.parseLookupList(subtableParsers) - }; - } else { - return { - version: tableVersion, - scripts: p.parseScriptList(), - features: p.parseFeatureList(), - lookups: p.parseLookupList(subtableParsers), - variations: p.parseFeatureVariationsList() - }; - } + function commitWork(current, finishedWork) { + if (!supportsMutation) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: + { + commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); + commitHookEffectListMount(Insertion | HasEffect, finishedWork); // Layout effects are destroyed during the mutation phase so that all + // destroy functions for all fibers are called before any create functions. + // This prevents sibling component effects from interfering with each other, + // e.g. a destroy function in one component should never override a ref set + // by a create function in another component during the same commit. + // TODO: Check if we're inside an Offscreen subtree that disappeared + // during this commit. If so, we would have already unmounted its + // layout hooks. (However, since we null out the `destroy` function + // right before calling it, the behavior is already correct, so this + // would mostly be for modeling purposes.) -} + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } -// GSUB Writing ////////////////////////////////////////////// -var subtableMakers = new Array(9); + return; + } -subtableMakers[1] = function makeLookup1(subtable) { - if (subtable.substFormat === 1) { - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 1}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}, - {name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId} - ]); - } else { - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 2}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.ushortList('substitute', subtable.substitute))); - } -}; + case Profiler: + { + return; + } -subtableMakers[2] = function makeLookup2(subtable) { - check.assert(subtable.substFormat === 1, 'Lookup type 2 substFormat must be 1.'); - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 1}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.tableList('seqSet', subtable.sequences, function(sequenceSet) { - return new table.Table('sequenceSetTable', table.ushortList('sequence', sequenceSet)); - }))); -}; + case SuspenseComponent: + { + commitSuspenseCallback(finishedWork); + attachSuspenseRetryListeners(finishedWork); + return; + } -subtableMakers[3] = function makeLookup3(subtable) { - check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.'); - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 1}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.tableList('altSet', subtable.alternateSets, function(alternateSet) { - return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet)); - }))); -}; + case SuspenseListComponent: + { + attachSuspenseRetryListeners(finishedWork); + return; + } -subtableMakers[4] = function makeLookup4(subtable) { - check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.'); - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 1}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) { - return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function(ligature) { - return new table.Table('ligatureTable', - [{name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph}] - .concat(table.ushortList('component', ligature.components, ligature.components.length + 1)) - ); - })); - }))); -}; + case HostRoot: + { + if (supportsHydration) { + if (current !== null) { + var prevRootState = current.memoizedState; -subtableMakers[6] = function makeLookup6(subtable) { - if (subtable.substFormat === 1) { - var returnTable = new table.Table('chainContextTable', [ - {name: 'substFormat', type: 'USHORT', value: subtable.substFormat}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.tableList('chainRuleSet', subtable.chainRuleSets, function(chainRuleSet) { - return new table.Table('chainRuleSetTable', table.tableList('chainRule', chainRuleSet, function(chainRule) { - var tableData = table.ushortList('backtrackGlyph', chainRule.backtrack, chainRule.backtrack.length) - .concat(table.ushortList('inputGlyph', chainRule.input, chainRule.input.length + 1)) - .concat(table.ushortList('lookaheadGlyph', chainRule.lookahead, chainRule.lookahead.length)) - .concat(table.ushortList('substitution', [], chainRule.lookupRecords.length)); - - chainRule.lookupRecords.forEach(function (record, i) { - tableData = tableData - .concat({name: 'sequenceIndex' + i, type: 'USHORT', value: record.sequenceIndex}) - .concat({name: 'lookupListIndex' + i, type: 'USHORT', value: record.lookupListIndex}); - }); - return new table.Table('chainRuleTable', tableData); - })); - }))); - return returnTable; - } else if (subtable.substFormat === 2) { - check.assert(false, 'lookup type 6 format 2 is not yet supported.'); - } else if (subtable.substFormat === 3) { - var tableData = [ - {name: 'substFormat', type: 'USHORT', value: subtable.substFormat} ]; - - tableData.push({name: 'backtrackGlyphCount', type: 'USHORT', value: subtable.backtrackCoverage.length}); - subtable.backtrackCoverage.forEach(function (coverage, i) { - tableData.push({name: 'backtrackCoverage' + i, type: 'TABLE', value: new table.Coverage(coverage)}); - }); - tableData.push({name: 'inputGlyphCount', type: 'USHORT', value: subtable.inputCoverage.length}); - subtable.inputCoverage.forEach(function (coverage, i) { - tableData.push({name: 'inputCoverage' + i, type: 'TABLE', value: new table.Coverage(coverage)}); - }); - tableData.push({name: 'lookaheadGlyphCount', type: 'USHORT', value: subtable.lookaheadCoverage.length}); - subtable.lookaheadCoverage.forEach(function (coverage, i) { - tableData.push({name: 'lookaheadCoverage' + i, type: 'TABLE', value: new table.Coverage(coverage)}); - }); + if (prevRootState.isDehydrated) { + var root = finishedWork.stateNode; + commitHydratedContainer(root.containerInfo); + } + } + } - tableData.push({name: 'substitutionCount', type: 'USHORT', value: subtable.lookupRecords.length}); - subtable.lookupRecords.forEach(function (record, i) { - tableData = tableData - .concat({name: 'sequenceIndex' + i, type: 'USHORT', value: record.sequenceIndex}) - .concat({name: 'lookupListIndex' + i, type: 'USHORT', value: record.lookupListIndex}); - }); + break; + } - var returnTable$1 = new table.Table('chainContextTable', tableData); + case OffscreenComponent: + case LegacyHiddenComponent: + { + return; + } + } - return returnTable$1; - } + commitContainer(finishedWork); + return; + } - check.assert(false, 'lookup type 6 format must be 1, 2 or 3.'); -}; + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: + { + commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); + commitHookEffectListMount(Insertion | HasEffect, finishedWork); // Layout effects are destroyed during the mutation phase so that all + // destroy functions for all fibers are called before any create functions. + // This prevents sibling component effects from interfering with each other, + // e.g. a destroy function in one component should never override a ref set + // by a create function in another component during the same commit. -function makeGsubTable(gsub) { - return new table.Table('GSUB', [ - {name: 'version', type: 'ULONG', value: 0x10000}, - {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gsub.scripts)}, - {name: 'features', type: 'TABLE', value: new table.FeatureList(gsub.features)}, - {name: 'lookups', type: 'TABLE', value: new table.LookupList(gsub.lookups, subtableMakers)} - ]); -} + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } -var gsub = { parse: parseGsubTable, make: makeGsubTable }; + return; + } -// The `GPOS` table contains kerning pairs, among other things. + case ClassComponent: + { + return; + } -// Parse the metadata `meta` table. -// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html -function parseMetaTable(data, start) { - var p = new parse.Parser(data, start); - var tableVersion = p.parseULong(); - check.argument(tableVersion === 1, 'Unsupported META table version.'); - p.parseULong(); // flags - currently unused and set to 0 - p.parseULong(); // tableOffset - var numDataMaps = p.parseULong(); + case HostComponent: + { + var instance = finishedWork.stateNode; - var tags = {}; - for (var i = 0; i < numDataMaps; i++) { - var tag = p.parseTag(); - var dataOffset = p.parseULong(); - var dataLength = p.parseULong(); - var text = decode.UTF8(data, start + dataOffset, dataLength); + if (instance != null) { + // Commit the work prepared earlier. + var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps + // as the newProps. The updatePayload will contain the real change in + // this case. - tags[tag] = text; - } - return tags; -} + var oldProps = current !== null ? current.memoizedProps : newProps; + var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. -function makeMetaTable(tags) { - var numTags = Object.keys(tags).length; - var stringPool = ''; - var stringPoolOffset = 16 + numTags * 12; + var updatePayload = finishedWork.updateQueue; + finishedWork.updateQueue = null; - var result = new table.Table('meta', [ - {name: 'version', type: 'ULONG', value: 1}, - {name: 'flags', type: 'ULONG', value: 0}, - {name: 'offset', type: 'ULONG', value: stringPoolOffset}, - {name: 'numTags', type: 'ULONG', value: numTags} - ]); + if (updatePayload !== null) { + commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork); + } + } - for (var tag in tags) { - var pos = stringPool.length; - stringPool += tags[tag]; + return; + } - result.fields.push({name: 'tag ' + tag, type: 'TAG', value: tag}); - result.fields.push({name: 'offset ' + tag, type: 'ULONG', value: stringPoolOffset + pos}); - result.fields.push({name: 'length ' + tag, type: 'ULONG', value: tags[tag].length}); - } + case HostText: + { + if (finishedWork.stateNode === null) { + throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.'); + } - result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); + var textInstance = finishedWork.stateNode; + var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps + // as the newProps. The updatePayload will contain the real change in + // this case. - return result; -} + var oldText = current !== null ? current.memoizedProps : newText; + commitTextUpdate(textInstance, oldText, newText); + return; + } -var meta = { parse: parseMetaTable, make: makeMetaTable }; + case HostRoot: + { + if (supportsHydration) { + if (current !== null) { + var _prevRootState = current.memoizedState; -// The `sfnt` wrapper provides organization for the tables in the font. + if (_prevRootState.isDehydrated) { + var _root = finishedWork.stateNode; + commitHydratedContainer(_root.containerInfo); + } + } + } -function log2(v) { - return Math.log(v) / Math.log(2) | 0; -} + return; + } -function computeCheckSum(bytes) { - while (bytes.length % 4 !== 0) { - bytes.push(0); - } + case Profiler: + { + return; + } - var sum = 0; - for (var i = 0; i < bytes.length; i += 4) { - sum += (bytes[i] << 24) + - (bytes[i + 1] << 16) + - (bytes[i + 2] << 8) + - (bytes[i + 3]); - } + case SuspenseComponent: + { + commitSuspenseCallback(finishedWork); + attachSuspenseRetryListeners(finishedWork); + return; + } - sum %= Math.pow(2, 32); - return sum; -} + case SuspenseListComponent: + { + attachSuspenseRetryListeners(finishedWork); + return; + } -function makeTableRecord(tag, checkSum, offset, length) { - return new table.Record('Table Record', [ - {name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''}, - {name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0}, - {name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0}, - {name: 'length', type: 'ULONG', value: length !== undefined ? length : 0} - ]); -} + case IncompleteClassComponent: + { + return; + } + } -function makeSfntTable(tables) { - var sfnt = new table.Table('sfnt', [ - {name: 'version', type: 'TAG', value: 'OTTO'}, - {name: 'numTables', type: 'USHORT', value: 0}, - {name: 'searchRange', type: 'USHORT', value: 0}, - {name: 'entrySelector', type: 'USHORT', value: 0}, - {name: 'rangeShift', type: 'USHORT', value: 0} - ]); - sfnt.tables = tables; - sfnt.numTables = tables.length; - var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); - sfnt.searchRange = 16 * highestPowerOf2; - sfnt.entrySelector = log2(highestPowerOf2); - sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; - - var recordFields = []; - var tableFields = []; - - var offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables); - while (offset % 4 !== 0) { - offset += 1; - tableFields.push({name: 'padding', type: 'BYTE', value: 0}); - } + throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); + } - for (var i = 0; i < tables.length; i += 1) { - var t = tables[i]; - check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.'); - var tableLength = t.sizeOf(); - var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength); - recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord}); - tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t}); - offset += tableLength; - check.argument(!isNaN(offset), 'Something went wrong calculating the offset.'); - while (offset % 4 !== 0) { - offset += 1; - tableFields.push({name: 'padding', type: 'BYTE', value: 0}); - } - } + function commitSuspenseCallback(finishedWork) { + // TODO: Move this to passive phase + finishedWork.memoizedState; + } - // Table records need to be sorted alphabetically. - recordFields.sort(function(r1, r2) { - if (r1.value.tag > r2.value.tag) { - return 1; - } else { - return -1; - } - }); + function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { + if (!supportsHydration) { + return; + } - sfnt.fields = sfnt.fields.concat(recordFields); - sfnt.fields = sfnt.fields.concat(tableFields); - return sfnt; -} + var newState = finishedWork.memoizedState; -// Get the metrics for a character. If the string has more than one character -// this function returns metrics for the first available character. -// You can provide optional fallback metrics if no characters are available. -function metricsForChar(font, chars, notFoundMetrics) { - for (var i = 0; i < chars.length; i += 1) { - var glyphIndex = font.charToGlyphIndex(chars[i]); - if (glyphIndex > 0) { - var glyph = font.glyphs.get(glyphIndex); - return glyph.getMetrics(); - } - } + if (newState === null) { + var current = finishedWork.alternate; - return notFoundMetrics; -} + if (current !== null) { + var prevState = current.memoizedState; -function average(vs) { - var sum = 0; - for (var i = 0; i < vs.length; i += 1) { - sum += vs[i]; - } + if (prevState !== null) { + var suspenseInstance = prevState.dehydrated; - return sum / vs.length; -} - -// Convert the font object to a SFNT data structure. -// This structure contains all the necessary tables and metadata to create a binary OTF file. -function fontToSfntTable(font) { - var xMins = []; - var yMins = []; - var xMaxs = []; - var yMaxs = []; - var advanceWidths = []; - var leftSideBearings = []; - var rightSideBearings = []; - var firstCharIndex; - var lastCharIndex = 0; - var ulUnicodeRange1 = 0; - var ulUnicodeRange2 = 0; - var ulUnicodeRange3 = 0; - var ulUnicodeRange4 = 0; - - for (var i = 0; i < font.glyphs.length; i += 1) { - var glyph = font.glyphs.get(i); - var unicode = glyph.unicode | 0; - - if (isNaN(glyph.advanceWidth)) { - throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.'); - } + if (suspenseInstance !== null) { + commitHydratedSuspenseInstance(suspenseInstance); + } + } + } + } + } - if (firstCharIndex > unicode || firstCharIndex === undefined) { - // ignore .notdef char - if (unicode > 0) { - firstCharIndex = unicode; - } - } + function attachSuspenseRetryListeners(finishedWork) { + // If this boundary just timed out, then it will have a set of wakeables. + // For each wakeable, attach a listener so that when it resolves, React + // attempts to re-render the boundary in the primary (pre-timeout) state. + var wakeables = finishedWork.updateQueue; - if (lastCharIndex < unicode) { - lastCharIndex = unicode; - } + if (wakeables !== null) { + finishedWork.updateQueue = null; + var retryCache = finishedWork.stateNode; - var position = os2.getUnicodeRange(unicode); - if (position < 32) { - ulUnicodeRange1 |= 1 << position; - } else if (position < 64) { - ulUnicodeRange2 |= 1 << position - 32; - } else if (position < 96) { - ulUnicodeRange3 |= 1 << position - 64; - } else if (position < 123) { - ulUnicodeRange4 |= 1 << position - 96; - } else { - throw new Error('Unicode ranges bits > 123 are reserved for internal usage'); - } - // Skip non-important characters. - if (glyph.name === '.notdef') { continue; } - var metrics = glyph.getMetrics(); - xMins.push(metrics.xMin); - yMins.push(metrics.yMin); - xMaxs.push(metrics.xMax); - yMaxs.push(metrics.yMax); - leftSideBearings.push(metrics.leftSideBearing); - rightSideBearings.push(metrics.rightSideBearing); - advanceWidths.push(glyph.advanceWidth); - } + if (retryCache === null) { + retryCache = finishedWork.stateNode = new PossiblyWeakSet(); + } - var globals = { - xMin: Math.min.apply(null, xMins), - yMin: Math.min.apply(null, yMins), - xMax: Math.max.apply(null, xMaxs), - yMax: Math.max.apply(null, yMaxs), - advanceWidthMax: Math.max.apply(null, advanceWidths), - advanceWidthAvg: average(advanceWidths), - minLeftSideBearing: Math.min.apply(null, leftSideBearings), - maxLeftSideBearing: Math.max.apply(null, leftSideBearings), - minRightSideBearing: Math.min.apply(null, rightSideBearings) - }; - globals.ascender = font.ascender; - globals.descender = font.descender; - - var headTable = head.make({ - flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0) - unitsPerEm: font.unitsPerEm, - xMin: globals.xMin, - yMin: globals.yMin, - xMax: globals.xMax, - yMax: globals.yMax, - lowestRecPPEM: 3, - createdTimestamp: font.createdTimestamp - }); + wakeables.forEach(function (wakeable) { + // Memoize using the boundary fiber to prevent redundant listeners. + var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - var hheaTable = hhea.make({ - ascender: globals.ascender, - descender: globals.descender, - advanceWidthMax: globals.advanceWidthMax, - minLeftSideBearing: globals.minLeftSideBearing, - minRightSideBearing: globals.minRightSideBearing, - xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), - numberOfHMetrics: font.glyphs.length - }); + if (!retryCache.has(wakeable)) { + retryCache.add(wakeable); - var maxpTable = maxp.make(font.glyphs.length); - - var os2Table = os2.make(Object.assign({ - xAvgCharWidth: Math.round(globals.advanceWidthAvg), - usFirstCharIndex: firstCharIndex, - usLastCharIndex: lastCharIndex, - ulUnicodeRange1: ulUnicodeRange1, - ulUnicodeRange2: ulUnicodeRange2, - ulUnicodeRange3: ulUnicodeRange3, - ulUnicodeRange4: ulUnicodeRange4, - // See http://typophile.com/node/13081 for more info on vertical metrics. - // We get metrics for typical characters (such as "x" for xHeight). - // We provide some fallback characters if characters are unavailable: their - // ordering was chosen experimentally. - sTypoAscender: globals.ascender, - sTypoDescender: globals.descender, - sTypoLineGap: 0, - usWinAscent: globals.yMax, - usWinDescent: Math.abs(globals.yMin), - ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now - sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax, - sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax, - usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available. - usBreakChar: font.hasChar(' ') ? 32 : 0, // Use space as the break character, if available. - }, font.tables.os2)); - - var hmtxTable = hmtx.make(font.glyphs); - var cmapTable = cmap.make(font.glyphs); - - var englishFamilyName = font.getEnglishName('fontFamily'); - var englishStyleName = font.getEnglishName('fontSubfamily'); - var englishFullName = englishFamilyName + ' ' + englishStyleName; - var postScriptName = font.getEnglishName('postScriptName'); - if (!postScriptName) { - postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName; - } + { + if (isDevToolsPresent) { + if (inProgressLanes !== null && inProgressRoot !== null) { + // If we have pending work still, associate the original updaters with it. + restorePendingUpdaters(inProgressRoot, inProgressLanes); + } else { + throw Error('Expected finished root and lanes to be set. This is a bug in React.'); + } + } + } - var names = {}; - for (var n in font.names) { - names[n] = font.names[n]; - } + wakeable.then(retry, retry); + } + }); + } + } // This function detects when a Suspense boundary goes from visible to hidden. - if (!names.uniqueID) { - names.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName}; - } + function commitResetTextContent(current) { + if (!supportsMutation) { + return; + } - if (!names.postScriptName) { - names.postScriptName = {en: postScriptName}; - } + resetTextContent(current.stateNode); + } - if (!names.preferredFamily) { - names.preferredFamily = font.names.fontFamily; - } + function commitMutationEffects(root, firstChild, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + nextEffect = firstChild; + commitMutationEffects_begin(root, committedLanes); + inProgressLanes = null; + inProgressRoot = null; + } - if (!names.preferredSubfamily) { - names.preferredSubfamily = font.names.fontSubfamily; - } + function commitMutationEffects_begin(root, lanes) { + while (nextEffect !== null) { + var fiber = nextEffect; // TODO: Should wrap this in flags check, too, as optimization - var languageTags = []; - var nameTable = _name.make(names, languageTags); - var ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined); - - var postTable = post.make(); - var cffTable = cff.make(font.glyphs, { - version: font.getEnglishName('version'), - fullName: englishFullName, - familyName: englishFamilyName, - weightName: englishStyleName, - postScriptName: postScriptName, - unitsPerEm: font.unitsPerEm, - fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax] - }); + var deletions = fiber.deletions; - var metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined; + if (deletions !== null) { + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; - // The order does not matter because makeSfntTable() will sort them. - var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable]; - if (ltagTable) { - tables.push(ltagTable); - } - // Optional tables - if (font.tables.gsub) { - tables.push(gsub.make(font.tables.gsub)); - } - if (metaTable) { - tables.push(metaTable); - } + try { + commitDeletion(root, childToDelete, fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(childToDelete, fiber, error); + } + } + } - var sfntTable = makeSfntTable(tables); - - // Compute the font's checkSum and store it in head.checkSumAdjustment. - var bytes = sfntTable.encode(); - var checkSum = computeCheckSum(bytes); - var tableFields = sfntTable.fields; - var checkSumAdjusted = false; - for (var i$1 = 0; i$1 < tableFields.length; i$1 += 1) { - if (tableFields[i$1].name === 'head table') { - tableFields[i$1].value.checkSumAdjustment = 0xB1B0AFBA - checkSum; - checkSumAdjusted = true; - break; - } - } + var child = fiber.child; - if (!checkSumAdjusted) { - throw new Error('Could not find head table with checkSum to adjust.'); - } + if ((fiber.subtreeFlags & MutationMask) !== NoFlags && child !== null) { + ensureCorrectReturnPointer(child, fiber); + nextEffect = child; + } else { + commitMutationEffects_complete(root, lanes); + } + } + } - return sfntTable; -} + function commitMutationEffects_complete(root, lanes) { + while (nextEffect !== null) { + var fiber = nextEffect; + setCurrentFiber(fiber); -var sfnt = { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum: computeCheckSum }; + try { + commitMutationEffectsOnFiber(fiber, root, lanes); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } -// The Layout object is the prototype of Substitution objects, and provides + resetCurrentFiber(); + var sibling = fiber.sibling; -function searchTag(arr, tag) { - /* jshint bitwise: false */ - var imin = 0; - var imax = arr.length - 1; - while (imin <= imax) { - var imid = (imin + imax) >>> 1; - var val = arr[imid].tag; - if (val === tag) { - return imid; - } else if (val < tag) { - imin = imid + 1; - } else { imax = imid - 1; } - } - // Not found: return -1-insertion point - return -imin - 1; -} - -function binSearch(arr, value) { - /* jshint bitwise: false */ - var imin = 0; - var imax = arr.length - 1; - while (imin <= imax) { - var imid = (imin + imax) >>> 1; - var val = arr[imid]; - if (val === value) { - return imid; - } else if (val < value) { - imin = imid + 1; - } else { imax = imid - 1; } - } - // Not found: return -1-insertion point - return -imin - 1; -} - -// binary search in a list of ranges (coverage, class definition) -function searchRange(ranges, value) { - // jshint bitwise: false - var range; - var imin = 0; - var imax = ranges.length - 1; - while (imin <= imax) { - var imid = (imin + imax) >>> 1; - range = ranges[imid]; - var start = range.start; - if (start === value) { - return range; - } else if (start < value) { - imin = imid + 1; - } else { imax = imid - 1; } - } - if (imin > 0) { - range = ranges[imin - 1]; - if (value > range.end) { return 0; } - return range; - } -} + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } -/** - * @exports opentype.Layout - * @class - */ -function Layout(font, tableName) { - this.font = font; - this.tableName = tableName; -} + nextEffect = fiber.return; + } + } -Layout.prototype = { + function commitMutationEffectsOnFiber(finishedWork, root, lanes) { + // TODO: The factoring of this phase could probably be improved. Consider + // switching on the type of work before checking the flags. That's what + // we do in all the other phases. I think this one is only different + // because of the shared reconciliation logic below. + var flags = finishedWork.flags; - /** - * Binary search an object by "tag" property - * @instance - * @function searchTag - * @memberof opentype.Layout - * @param {Array} arr - * @param {string} tag - * @return {number} - */ - searchTag: searchTag, + if (flags & ContentReset) { + commitResetTextContent(finishedWork); + } - /** - * Binary search in a list of numbers - * @instance - * @function binSearch - * @memberof opentype.Layout - * @param {Array} arr - * @param {number} value - * @return {number} - */ - binSearch: binSearch, + if (flags & Ref) { + var current = finishedWork.alternate; - /** - * Get or create the Layout table (GSUB, GPOS etc). - * @param {boolean} create - Whether to create a new one. - * @return {Object} The GSUB or GPOS table. - */ - getTable: function(create) { - var layout = this.font.tables[this.tableName]; - if (!layout && create) { - layout = this.font.tables[this.tableName] = this.createDefaultTable(); - } - return layout; - }, + if (current !== null) { + commitDetachRef(current); + } + } - /** - * Returns all scripts in the substitution table. - * @instance - * @return {Array} - */ - getScriptNames: function() { - var layout = this.getTable(); - if (!layout) { return []; } - return layout.scripts.map(function(script) { - return script.tag; - }); - }, + if (flags & Visibility) { + switch (finishedWork.tag) { + case SuspenseComponent: + { + var newState = finishedWork.memoizedState; + var isHidden = newState !== null; - /** - * Returns the best bet for a script name. - * Returns 'DFLT' if it exists. - * If not, returns 'latn' if it exists. - * If neither exist, returns undefined. - */ - getDefaultScriptName: function() { - var layout = this.getTable(); - if (!layout) { return; } - var hasLatn = false; - for (var i = 0; i < layout.scripts.length; i++) { - var name = layout.scripts[i].tag; - if (name === 'DFLT') { return name; } - if (name === 'latn') { hasLatn = true; } - } - if (hasLatn) { return 'latn'; } - }, + if (isHidden) { + var _current = finishedWork.alternate; + var wasHidden = _current !== null && _current.memoizedState !== null; - /** - * Returns all LangSysRecords in the given script. - * @instance - * @param {string} [script='DFLT'] - * @param {boolean} create - forces the creation of this script table if it doesn't exist. - * @return {Object} An object with tag and script properties. - */ - getScriptTable: function(script, create) { - var layout = this.getTable(create); - if (layout) { - script = script || 'DFLT'; - var scripts = layout.scripts; - var pos = searchTag(layout.scripts, script); - if (pos >= 0) { - return scripts[pos].script; - } else if (create) { - var scr = { - tag: script, - script: { - defaultLangSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []}, - langSysRecords: [] - } - }; - scripts.splice(-1 - pos, 0, scr); - return scr.script; - } - } - }, + if (!wasHidden) { + // TODO: Move to passive phase + markCommitTimeOfFallback(); + } + } - /** - * Returns a language system table - * @instance - * @param {string} [script='DFLT'] - * @param {string} [language='dlft'] - * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist. - * @return {Object} - */ - getLangSysTable: function(script, language, create) { - var scriptTable = this.getScriptTable(script, create); - if (scriptTable) { - if (!language || language === 'dflt' || language === 'DFLT') { - return scriptTable.defaultLangSys; - } - var pos = searchTag(scriptTable.langSysRecords, language); - if (pos >= 0) { - return scriptTable.langSysRecords[pos].langSys; - } else if (create) { - var langSysRecord = { - tag: language, - langSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []} - }; - scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); - return langSysRecord.langSys; - } - } - }, + break; + } - /** - * Get a specific feature table. - * @instance - * @param {string} [script='DFLT'] - * @param {string} [language='dlft'] - * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm - * @param {boolean} create - forces the creation of the feature table if it doesn't exist. - * @return {Object} - */ - getFeatureTable: function(script, language, feature, create) { - var langSysTable = this.getLangSysTable(script, language, create); - if (langSysTable) { - var featureRecord; - var featIndexes = langSysTable.featureIndexes; - var allFeatures = this.font.tables[this.tableName].features; - // The FeatureIndex array of indices is in arbitrary order, - // even if allFeatures is sorted alphabetically by feature tag. - for (var i = 0; i < featIndexes.length; i++) { - featureRecord = allFeatures[featIndexes[i]]; - if (featureRecord.tag === feature) { - return featureRecord.feature; - } - } - if (create) { - var index = allFeatures.length; - // Automatic ordering of features would require to shift feature indexes in the script list. - check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.'); - featureRecord = { - tag: feature, - feature: { params: 0, lookupListIndexes: [] } - }; - allFeatures.push(featureRecord); - featIndexes.push(index); - return featureRecord.feature; - } - } - }, + case OffscreenComponent: + { + var _newState = finishedWork.memoizedState; - /** - * Get the lookup tables of a given type for a script/language/feature. - * @instance - * @param {string} [script='DFLT'] - * @param {string} [language='dlft'] - * @param {string} feature - 4-letter feature code - * @param {number} lookupType - 1 to 9 - * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables. - * @return {Object[]} - */ - getLookupTables: function(script, language, feature, lookupType, create) { - var featureTable = this.getFeatureTable(script, language, feature, create); - var tables = []; - if (featureTable) { - var lookupTable; - var lookupListIndexes = featureTable.lookupListIndexes; - var allLookups = this.font.tables[this.tableName].lookups; - // lookupListIndexes are in no particular order, so use naive search. - for (var i = 0; i < lookupListIndexes.length; i++) { - lookupTable = allLookups[lookupListIndexes[i]]; - if (lookupTable.lookupType === lookupType) { - tables.push(lookupTable); - } - } - if (tables.length === 0 && create) { - lookupTable = { - lookupType: lookupType, - lookupFlag: 0, - subtables: [], - markFilteringSet: undefined - }; - var index = allLookups.length; - allLookups.push(lookupTable); - lookupListIndexes.push(index); - return [lookupTable]; - } - } - return tables; - }, + var _isHidden = _newState !== null; - /** - * Find a glyph in a class definition table - * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table - * @param {object} classDefTable - an OpenType Layout class definition table - * @param {number} glyphIndex - the index of the glyph to find - * @returns {number} -1 if not found - */ - getGlyphClass: function(classDefTable, glyphIndex) { - switch (classDefTable.format) { - case 1: - if (classDefTable.startGlyph <= glyphIndex && glyphIndex < classDefTable.startGlyph + classDefTable.classes.length) { - return classDefTable.classes[glyphIndex - classDefTable.startGlyph]; - } - return 0; - case 2: - var range = searchRange(classDefTable.ranges, glyphIndex); - return range ? range.classId : 0; - } - }, + var _current2 = finishedWork.alternate; - /** - * Find a glyph in a coverage table - * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-table - * @param {object} coverageTable - an OpenType Layout coverage table - * @param {number} glyphIndex - the index of the glyph to find - * @returns {number} -1 if not found - */ - getCoverageIndex: function(coverageTable, glyphIndex) { - switch (coverageTable.format) { - case 1: - var index = binSearch(coverageTable.glyphs, glyphIndex); - return index >= 0 ? index : -1; - case 2: - var range = searchRange(coverageTable.ranges, glyphIndex); - return range ? range.index + glyphIndex - range.start : -1; - } - }, + var _wasHidden = _current2 !== null && _current2.memoizedState !== null; - /** - * Returns the list of glyph indexes of a coverage table. - * Format 1: the list is stored raw - * Format 2: compact list as range records. - * @instance - * @param {Object} coverageTable - * @return {Array} - */ - expandCoverage: function(coverageTable) { - if (coverageTable.format === 1) { - return coverageTable.glyphs; - } else { - var glyphs = []; - var ranges = coverageTable.ranges; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - var start = range.start; - var end = range.end; - for (var j = start; j <= end; j++) { - glyphs.push(j); - } - } - return glyphs; - } - } + var offscreenBoundary = finishedWork; -}; + if (supportsMutation) { + // TODO: This needs to run whenever there's an insertion or update + // inside a hidden Offscreen tree. + hideOrUnhideAllChildren(offscreenBoundary, _isHidden); + } -// The Position object provides utility methods to manipulate + { + if (_isHidden) { + if (!_wasHidden) { + if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) { + nextEffect = offscreenBoundary; + var offscreenChild = offscreenBoundary.child; -/** - * @exports opentype.Position - * @class - * @extends opentype.Layout - * @param {opentype.Font} - * @constructor - */ -function Position(font) { - Layout.call(this, font, 'gpos'); -} + while (offscreenChild !== null) { + nextEffect = offscreenChild; + disappearLayoutEffects_begin(offscreenChild); + offscreenChild = offscreenChild.sibling; + } + } + } + } -Position.prototype = Layout.prototype; + break; + } + } + } + } // The following switch statement is only concerned about placement, + // updates, and deletions. To avoid needing to add a case for every possible + // bitmap value, we remove the secondary effects from the effect tag and + // switch on that value. -/** - * Init some data for faster and easier access later. - */ -Position.prototype.init = function() { - var script = this.getDefaultScriptName(); - this.defaultKerningTables = this.getKerningTables(script); -}; -/** - * Find a glyph pair in a list of lookup tables of type 2 and retrieve the xAdvance kerning value. - * - * @param {integer} leftIndex - left glyph index - * @param {integer} rightIndex - right glyph index - * @returns {integer} - */ -Position.prototype.getKerningValue = function(kerningLookups, leftIndex, rightIndex) { - for (var i = 0; i < kerningLookups.length; i++) { - var subtables = kerningLookups[i].subtables; - for (var j = 0; j < subtables.length; j++) { - var subtable = subtables[j]; - var covIndex = this.getCoverageIndex(subtable.coverage, leftIndex); - if (covIndex < 0) { continue; } - switch (subtable.posFormat) { - case 1: - // Search Pair Adjustment Positioning Format 1 - var pairSet = subtable.pairSets[covIndex]; - for (var k = 0; k < pairSet.length; k++) { - var pair = pairSet[k]; - if (pair.secondGlyph === rightIndex) { - return pair.value1 && pair.value1.xAdvance || 0; - } - } - break; // left glyph found, not right glyph - try next subtable - case 2: - // Search Pair Adjustment Positioning Format 2 - var class1 = this.getGlyphClass(subtable.classDef1, leftIndex); - var class2 = this.getGlyphClass(subtable.classDef2, rightIndex); - var pair$1 = subtable.classRecords[class1][class2]; - return pair$1.value1 && pair$1.value1.xAdvance || 0; - } - } - } - return 0; -}; + var primaryFlags = flags & (Placement | Update | Hydrating); -/** - * List all kerning lookup tables. - * - * @param {string} [script='DFLT'] - use font.position.getDefaultScriptName() for a better default value - * @param {string} [language='dflt'] - * @return {object[]} The list of kerning lookup tables (may be empty), or undefined if there is no GPOS table (and we should use the kern table) - */ -Position.prototype.getKerningTables = function(script, language) { - if (this.font.tables.gpos) { - return this.getLookupTables(script, language, 'kern', 2); - } -}; + switch (primaryFlags) { + case Placement: + { + commitPlacement(finishedWork); // Clear the "placement" from effect tag so that we know that this is + // inserted, before any life-cycles like componentDidMount gets called. + // TODO: findDOMNode doesn't rely on this any more but isMounted does + // and isMounted is deprecated anyway so we should be able to kill this. -// The Substitution object provides utility methods to manipulate + finishedWork.flags &= ~Placement; + break; + } -/** - * @exports opentype.Substitution - * @class - * @extends opentype.Layout - * @param {opentype.Font} - * @constructor - */ -function Substitution(font) { - Layout.call(this, font, 'gsub'); -} + case PlacementAndUpdate: + { + // Placement + commitPlacement(finishedWork); // Clear the "placement" from effect tag so that we know that this is + // inserted, before any life-cycles like componentDidMount gets called. -// Check if 2 arrays of primitives are equal. -function arraysEqual(ar1, ar2) { - var n = ar1.length; - if (n !== ar2.length) { return false; } - for (var i = 0; i < n; i++) { - if (ar1[i] !== ar2[i]) { return false; } - } - return true; -} + finishedWork.flags &= ~Placement; // Update -// Find the first subtable of a lookup table in a particular format. -function getSubstFormat(lookupTable, format, defaultSubtable) { - var subtables = lookupTable.subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - if (subtable.substFormat === format) { - return subtable; - } - } - if (defaultSubtable) { - subtables.push(defaultSubtable); - return defaultSubtable; - } - return undefined; -} + var _current3 = finishedWork.alternate; + commitWork(_current3, finishedWork); + break; + } -Substitution.prototype = Layout.prototype; + case Hydrating: + { + finishedWork.flags &= ~Hydrating; + break; + } -/** - * Create a default GSUB table. - * @return {Object} gsub - The GSUB table. - */ -Substitution.prototype.createDefaultTable = function() { - // Generate a default empty GSUB table with just a DFLT script and dflt lang sys. - return { - version: 1, - scripts: [{ - tag: 'DFLT', - script: { - defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] }, - langSysRecords: [] - } - }], - features: [], - lookups: [] - }; -}; + case HydratingAndUpdate: + { + finishedWork.flags &= ~Hydrating; // Update -/** - * List all single substitutions (lookup type 1) for a given script, language, and feature. - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...) - * @return {Array} substitutions - The list of substitutions. - */ -Substitution.prototype.getSingle = function(feature, script, language) { - var substitutions = []; - var lookupTables = this.getLookupTables(script, language, feature, 1); - for (var idx = 0; idx < lookupTables.length; idx++) { - var subtables = lookupTables[idx].subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - var glyphs = this.expandCoverage(subtable.coverage); - var j = (void 0); - if (subtable.substFormat === 1) { - var delta = subtable.deltaGlyphId; - for (j = 0; j < glyphs.length; j++) { - var glyph = glyphs[j]; - substitutions.push({ sub: glyph, by: glyph + delta }); - } - } else { - var substitute = subtable.substitute; - for (j = 0; j < glyphs.length; j++) { - substitutions.push({ sub: glyphs[j], by: substitute[j] }); - } - } - } - } - return substitutions; -}; + var _current4 = finishedWork.alternate; + commitWork(_current4, finishedWork); + break; + } -/** - * List all multiple substitutions (lookup type 2) for a given script, language, and feature. - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @param {string} feature - 4-character feature name ('ccmp', 'stch') - * @return {Array} substitutions - The list of substitutions. - */ -Substitution.prototype.getMultiple = function(feature, script, language) { - var substitutions = []; - var lookupTables = this.getLookupTables(script, language, feature, 2); - for (var idx = 0; idx < lookupTables.length; idx++) { - var subtables = lookupTables[idx].subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - var glyphs = this.expandCoverage(subtable.coverage); - var j = (void 0); - - for (j = 0; j < glyphs.length; j++) { - var glyph = glyphs[j]; - var replacements = subtable.sequences[j]; - substitutions.push({ sub: glyph, by: replacements }); - } - } - } - return substitutions; -}; + case Update: + { + var _current5 = finishedWork.alternate; + commitWork(_current5, finishedWork); + break; + } + } + } -/** - * List all alternates (lookup type 3) for a given script, language, and feature. - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @param {string} feature - 4-character feature name ('aalt', 'salt'...) - * @return {Array} alternates - The list of alternates - */ -Substitution.prototype.getAlternates = function(feature, script, language) { - var alternates = []; - var lookupTables = this.getLookupTables(script, language, feature, 3); - for (var idx = 0; idx < lookupTables.length; idx++) { - var subtables = lookupTables[idx].subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - var glyphs = this.expandCoverage(subtable.coverage); - var alternateSets = subtable.alternateSets; - for (var j = 0; j < glyphs.length; j++) { - alternates.push({ sub: glyphs[j], by: alternateSets[j] }); - } - } - } - return alternates; -}; + function commitLayoutEffects(finishedWork, root, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + nextEffect = finishedWork; + commitLayoutEffects_begin(finishedWork, root, committedLanes); + inProgressLanes = null; + inProgressRoot = null; + } -/** - * List all ligatures (lookup type 4) for a given script, language, and feature. - * The result is an array of ligature objects like { sub: [ids], by: id } - * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @return {Array} ligatures - The list of ligatures. - */ -Substitution.prototype.getLigatures = function(feature, script, language) { - var ligatures = []; - var lookupTables = this.getLookupTables(script, language, feature, 4); - for (var idx = 0; idx < lookupTables.length; idx++) { - var subtables = lookupTables[idx].subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - var glyphs = this.expandCoverage(subtable.coverage); - var ligatureSets = subtable.ligatureSets; - for (var j = 0; j < glyphs.length; j++) { - var startGlyph = glyphs[j]; - var ligSet = ligatureSets[j]; - for (var k = 0; k < ligSet.length; k++) { - var lig = ligSet[k]; - ligatures.push({ - sub: [startGlyph].concat(lig.components), - by: lig.ligGlyph - }); - } - } - } - } - return ligatures; -}; + function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) { + // Suspense layout effects semantics don't change for legacy roots. + var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode; -/** - * Add or modify a single substitution (lookup type 1) - * Format 2, more flexible, is always used. - * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) - * @param {Object} substitution - { sub: id, by: id } (format 1 is not supported) - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.addSingle = function(feature, substitution, script, language) { - var lookupTable = this.getLookupTables(script, language, feature, 1, true)[0]; - var subtable = getSubstFormat(lookupTable, 2, { // lookup type 1 subtable, format 2, coverage format 1 - substFormat: 2, - coverage: {format: 1, glyphs: []}, - substitute: [] - }); - check.assert(subtable.coverage.format === 1, 'Single: unable to modify coverage table format ' + subtable.coverage.format); - var coverageGlyph = substitution.sub; - var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); - if (pos < 0) { - pos = -1 - pos; - subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); - subtable.substitute.splice(pos, 0, 0); - } - subtable.substitute[pos] = substitution.by; -}; + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; -/** - * Add or modify a multiple substitution (lookup type 2) - * @param {string} feature - 4-letter feature name ('ccmp', 'stch') - * @param {Object} substitution - { sub: id, by: [id] } for format 2. - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.addMultiple = function(feature, substitution, script, language) { - check.assert(substitution.by instanceof Array && substitution.by.length > 1, 'Multiple: "by" must be an array of two or more ids'); - var lookupTable = this.getLookupTables(script, language, feature, 2, true)[0]; - var subtable = getSubstFormat(lookupTable, 1, { // lookup type 2 subtable, format 1, coverage format 1 - substFormat: 1, - coverage: {format: 1, glyphs: []}, - sequences: [] - }); - check.assert(subtable.coverage.format === 1, 'Multiple: unable to modify coverage table format ' + subtable.coverage.format); - var coverageGlyph = substitution.sub; - var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); - if (pos < 0) { - pos = -1 - pos; - subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); - subtable.sequences.splice(pos, 0, 0); - } - subtable.sequences[pos] = substitution.by; -}; + if ( fiber.tag === OffscreenComponent && isModernRoot) { + // Keep track of the current Offscreen stack's state. + var isHidden = fiber.memoizedState !== null; + var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; -/** - * Add or modify an alternate substitution (lookup type 3) - * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) - * @param {Object} substitution - { sub: id, by: [ids] } - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.addAlternate = function(feature, substitution, script, language) { - var lookupTable = this.getLookupTables(script, language, feature, 3, true)[0]; - var subtable = getSubstFormat(lookupTable, 1, { // lookup type 3 subtable, format 1, coverage format 1 - substFormat: 1, - coverage: {format: 1, glyphs: []}, - alternateSets: [] - }); - check.assert(subtable.coverage.format === 1, 'Alternate: unable to modify coverage table format ' + subtable.coverage.format); - var coverageGlyph = substitution.sub; - var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); - if (pos < 0) { - pos = -1 - pos; - subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); - subtable.alternateSets.splice(pos, 0, 0); - } - subtable.alternateSets[pos] = substitution.by; -}; + if (newOffscreenSubtreeIsHidden) { + // The Offscreen tree is hidden. Skip over its layout effects. + commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); + continue; + } else { + // TODO (Offscreen) Also check: subtreeFlags & LayoutMask + var current = fiber.alternate; + var wasHidden = current !== null && current.memoizedState !== null; + var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; + var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root. -/** - * Add a ligature (lookup type 4) - * Ligatures with more components must be stored ahead of those with fewer components in order to be found - * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) - * @param {Object} ligature - { sub: [ids], by: id } - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.addLigature = function(feature, ligature, script, language) { - var lookupTable = this.getLookupTables(script, language, feature, 4, true)[0]; - var subtable = lookupTable.subtables[0]; - if (!subtable) { - subtable = { // lookup type 4 subtable, format 1, coverage format 1 - substFormat: 1, - coverage: { format: 1, glyphs: [] }, - ligatureSets: [] - }; - lookupTable.subtables[0] = subtable; - } - check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); - var coverageGlyph = ligature.sub[0]; - var ligComponents = ligature.sub.slice(1); - var ligatureTable = { - ligGlyph: ligature.by, - components: ligComponents - }; - var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); - if (pos >= 0) { - // ligatureSet already exists - var ligatureSet = subtable.ligatureSets[pos]; - for (var i = 0; i < ligatureSet.length; i++) { - // If ligature already exists, return. - if (arraysEqual(ligatureSet[i].components, ligComponents)) { - return; - } - } - // ligature does not exist: add it. - ligatureSet.push(ligatureTable); - } else { - // Create a new ligatureSet and add coverage for the first glyph. - pos = -1 - pos; - subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); - subtable.ligatureSets.splice(pos, 0, [ligatureTable]); - } -}; + offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; -/** - * List all feature data for a given script and language. - * @param {string} feature - 4-letter feature name - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @return {Array} substitutions - The list of substitutions. - */ -Substitution.prototype.getFeature = function(feature, script, language) { - if (/ss\d\d/.test(feature)) { - // ss01 - ss20 - return this.getSingle(feature, script, language); - } - switch (feature) { - case 'aalt': - case 'salt': - return this.getSingle(feature, script, language) - .concat(this.getAlternates(feature, script, language)); - case 'dlig': - case 'liga': - case 'rlig': - return this.getLigatures(feature, script, language); - case 'ccmp': - return this.getMultiple(feature, script, language) - .concat(this.getLigatures(feature, script, language)); - case 'stch': - return this.getMultiple(feature, script, language); - } - return undefined; -}; + if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { + // This is the root of a reappearing boundary. Turn its layout effects + // back on. + nextEffect = fiber; + reappearLayoutEffects_begin(fiber); + } -/** - * Add a substitution to a feature for a given script and language. - * @param {string} feature - 4-letter feature name - * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] }) - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.add = function(feature, sub, script, language) { - if (/ss\d\d/.test(feature)) { - // ss01 - ss20 - return this.addSingle(feature, sub, script, language); - } - switch (feature) { - case 'aalt': - case 'salt': - if (typeof sub.by === 'number') { - return this.addSingle(feature, sub, script, language); - } - return this.addAlternate(feature, sub, script, language); - case 'dlig': - case 'liga': - case 'rlig': - return this.addLigature(feature, sub, script, language); - case 'ccmp': - if (sub.by instanceof Array) { - return this.addMultiple(feature, sub, script, language); - } - return this.addLigature(feature, sub, script, language); - } - return undefined; -}; + var child = firstChild; -function isBrowser() { - return typeof window !== 'undefined'; -} + while (child !== null) { + nextEffect = child; + commitLayoutEffects_begin(child, // New root; bubble back up to here and stop. + root, committedLanes); + child = child.sibling; + } // Restore Offscreen state and resume in our-progress traversal. -function arrayBufferToNodeBuffer(ab) { - var buffer = new Buffer(ab.byteLength); - var view = new Uint8Array(ab); - for (var i = 0; i < buffer.length; ++i) { - buffer[i] = view[i]; - } - return buffer; -} + nextEffect = fiber; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); + continue; + } + } -function checkArgument(expression, message) { - if (!expression) { - throw message; - } -} + if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) { + ensureCorrectReturnPointer(firstChild, fiber); + nextEffect = firstChild; + } else { + commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); + } + } + } -// The `glyf` table describes the glyphs in TrueType outline format. + function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) { + while (nextEffect !== null) { + var fiber = nextEffect; -// Parse the coordinate data for a glyph. -function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { - var v; - if ((flag & shortVectorBitMask) > 0) { - // The coordinate is 1 byte long. - v = p.parseByte(); - // The `same` bit is re-used for short values to signify the sign of the value. - if ((flag & sameBitMask) === 0) { - v = -v; - } + if ((fiber.flags & LayoutMask) !== NoFlags) { + var current = fiber.alternate; + setCurrentFiber(fiber); - v = previousValue + v; - } else { - // The coordinate is 2 bytes long. - // If the `same` bit is set, the coordinate is the same as the previous coordinate. - if ((flag & sameBitMask) > 0) { - v = previousValue; - } else { - // Parse the coordinate as a signed 16-bit delta value. - v = previousValue + p.parseShort(); - } - } + try { + commitLayoutEffectOnFiber(root, current, fiber, committedLanes); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - return v; -} + resetCurrentFiber(); + } -// Parse a TrueType glyph. -function parseGlyph(glyph, data, start) { - var p = new parse.Parser(data, start); - glyph.numberOfContours = p.parseShort(); - glyph._xMin = p.parseShort(); - glyph._yMin = p.parseShort(); - glyph._xMax = p.parseShort(); - glyph._yMax = p.parseShort(); - var flags; - var flag; - - if (glyph.numberOfContours > 0) { - // This glyph is not a composite. - var endPointIndices = glyph.endPointIndices = []; - for (var i = 0; i < glyph.numberOfContours; i += 1) { - endPointIndices.push(p.parseUShort()); - } + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } - glyph.instructionLength = p.parseUShort(); - glyph.instructions = []; - for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) { - glyph.instructions.push(p.parseByte()); - } + var sibling = fiber.sibling; - var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; - flags = []; - for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) { - flag = p.parseByte(); - flags.push(flag); - // If bit 3 is set, we repeat this flag n times, where n is the next byte. - if ((flag & 8) > 0) { - var repeatCount = p.parseByte(); - for (var j = 0; j < repeatCount; j += 1) { - flags.push(flag); - i$2 += 1; - } - } - } + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } - check.argument(flags.length === numberOfCoordinates, 'Bad flags.'); - - if (endPointIndices.length > 0) { - var points = []; - var point; - // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. - if (numberOfCoordinates > 0) { - for (var i$3 = 0; i$3 < numberOfCoordinates; i$3 += 1) { - flag = flags[i$3]; - point = {}; - point.onCurve = !!(flag & 1); - point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0; - points.push(point); - } + nextEffect = fiber.return; + } + } - var px = 0; - for (var i$4 = 0; i$4 < numberOfCoordinates; i$4 += 1) { - flag = flags[i$4]; - point = points[i$4]; - point.x = parseGlyphCoordinate(p, flag, px, 2, 16); - px = point.x; - } + function disappearLayoutEffects_begin(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) - var py = 0; - for (var i$5 = 0; i$5 < numberOfCoordinates; i$5 += 1) { - flag = flags[i$5]; - point = points[i$5]; - point.y = parseGlyphCoordinate(p, flag, py, 4, 32); - py = point.y; - } - } + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: + { + if ( fiber.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListUnmount(Layout, fiber, fiber.return); + } finally { + recordLayoutEffectDuration(fiber); + } + } else { + commitHookEffectListUnmount(Layout, fiber, fiber.return); + } - glyph.points = points; - } else { - glyph.points = []; - } - } else if (glyph.numberOfContours === 0) { - glyph.points = []; - } else { - glyph.isComposite = true; - glyph.points = []; - glyph.components = []; - var moreComponents = true; - while (moreComponents) { - flags = p.parseUShort(); - var component = { - glyphIndex: p.parseUShort(), - xScale: 1, - scale01: 0, - scale10: 0, - yScale: 1, - dx: 0, - dy: 0 - }; - if ((flags & 1) > 0) { - // The arguments are words - if ((flags & 2) > 0) { - // values are offset - component.dx = p.parseShort(); - component.dy = p.parseShort(); - } else { - // values are matched points - component.matchedPoints = [p.parseUShort(), p.parseUShort()]; - } + break; + } - } else { - // The arguments are bytes - if ((flags & 2) > 0) { - // values are offset - component.dx = p.parseChar(); - component.dy = p.parseChar(); - } else { - // values are matched points - component.matchedPoints = [p.parseByte(), p.parseByte()]; - } - } + case ClassComponent: + { + // TODO (Offscreen) Check: flags & RefStatic + safelyDetachRef(fiber, fiber.return); + var instance = fiber.stateNode; - if ((flags & 8) > 0) { - // We have a scale - component.xScale = component.yScale = p.parseF2Dot14(); - } else if ((flags & 64) > 0) { - // We have an X / Y scale - component.xScale = p.parseF2Dot14(); - component.yScale = p.parseF2Dot14(); - } else if ((flags & 128) > 0) { - // We have a 2x2 transformation - component.xScale = p.parseF2Dot14(); - component.scale01 = p.parseF2Dot14(); - component.scale10 = p.parseF2Dot14(); - component.yScale = p.parseF2Dot14(); - } + if (typeof instance.componentWillUnmount === 'function') { + safelyCallComponentWillUnmount(fiber, fiber.return, instance); + } - glyph.components.push(component); - moreComponents = !!(flags & 32); - } - if (flags & 0x100) { - // We have instructions - glyph.instructionLength = p.parseUShort(); - glyph.instructions = []; - for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) { - glyph.instructions.push(p.parseByte()); - } - } - } -} + break; + } -// Transform an array of points and return a new array. -function transformPoints(points, transform) { - var newPoints = []; - for (var i = 0; i < points.length; i += 1) { - var pt = points[i]; - var newPt = { - x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, - y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, - onCurve: pt.onCurve, - lastPointOfContour: pt.lastPointOfContour - }; - newPoints.push(newPt); - } + case HostComponent: + { + safelyDetachRef(fiber, fiber.return); + break; + } - return newPoints; -} + case OffscreenComponent: + { + // Check if this is a + var isHidden = fiber.memoizedState !== null; -function getContours(points) { - var contours = []; - var currentContour = []; - for (var i = 0; i < points.length; i += 1) { - var pt = points[i]; - currentContour.push(pt); - if (pt.lastPointOfContour) { - contours.push(currentContour); - currentContour = []; - } - } + if (isHidden) { + // Nested Offscreen tree is already hidden. Don't disappear + // its effects. + disappearLayoutEffects_complete(subtreeRoot); + continue; + } - check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); - return contours; -} + break; + } + } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic -// Convert the TrueType glyph outline to a Path. -function getPath(points) { - var p = new Path(); - if (!points) { - return p; - } - var contours = getContours(points); + if (firstChild !== null) { + firstChild.return = fiber; + nextEffect = firstChild; + } else { + disappearLayoutEffects_complete(subtreeRoot); + } + } + } - for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) { - var contour = contours[contourIndex]; + function disappearLayoutEffects_complete(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; - var prev = null; - var curr = contour[contour.length - 1]; - var next = contour[0]; + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } - if (curr.onCurve) { - p.moveTo(curr.x, curr.y); - } else { - if (next.onCurve) { - p.moveTo(next.x, next.y); - } else { - // If both first and last points are off-curve, start at their middle. - var start = {x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5}; - p.moveTo(start.x, start.y); - } - } + var sibling = fiber.sibling; - for (var i = 0; i < contour.length; ++i) { - prev = curr; - curr = next; - next = contour[(i + 1) % contour.length]; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } - if (curr.onCurve) { - // This is a straight line. - p.lineTo(curr.x, curr.y); - } else { - var next2 = next; + nextEffect = fiber.return; + } + } - if (!prev.onCurve) { - ({ x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 }); - } + function reappearLayoutEffects_begin(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; - if (!next.onCurve) { - next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; - } + if (fiber.tag === OffscreenComponent) { + var isHidden = fiber.memoizedState !== null; - p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); - } - } + if (isHidden) { + // Nested Offscreen tree is still hidden. Don't re-appear its effects. + reappearLayoutEffects_complete(subtreeRoot); + continue; + } + } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic - p.closePath(); - } - return p; -} - -function buildPath(glyphs, glyph) { - if (glyph.isComposite) { - for (var j = 0; j < glyph.components.length; j += 1) { - var component = glyph.components[j]; - var componentGlyph = glyphs.get(component.glyphIndex); - // Force the ttfGlyphLoader to parse the glyph. - componentGlyph.getPath(); - if (componentGlyph.points) { - var transformedPoints = (void 0); - if (component.matchedPoints === undefined) { - // component positioned by offset - transformedPoints = transformPoints(componentGlyph.points, component); - } else { - // component positioned by matched points - if ((component.matchedPoints[0] > glyph.points.length - 1) || - (component.matchedPoints[1] > componentGlyph.points.length - 1)) { - throw Error('Matched points out of range in ' + glyph.name); - } - var firstPt = glyph.points[component.matchedPoints[0]]; - var secondPt = componentGlyph.points[component.matchedPoints[1]]; - var transform = { - xScale: component.xScale, scale01: component.scale01, - scale10: component.scale10, yScale: component.yScale, - dx: 0, dy: 0 - }; - secondPt = transformPoints([secondPt], transform)[0]; - transform.dx = firstPt.x - secondPt.x; - transform.dy = firstPt.y - secondPt.y; - transformedPoints = transformPoints(componentGlyph.points, transform); - } - glyph.points = glyph.points.concat(transformedPoints); - } - } - } - return getPath(glyph.points); -} + if (firstChild !== null) { + // This node may have been reused from a previous render, so we can't + // assume its return pointer is correct. + firstChild.return = fiber; + nextEffect = firstChild; + } else { + reappearLayoutEffects_complete(subtreeRoot); + } + } + } -function parseGlyfTableAll(data, start, loca, font) { - var glyphs = new glyphset.GlyphSet(font); + function reappearLayoutEffects_complete(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic - // The last element of the loca table is invalid. - for (var i = 0; i < loca.length - 1; i += 1) { - var offset = loca[i]; - var nextOffset = loca[i + 1]; - if (offset !== nextOffset) { - glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); - } else { - glyphs.push(i, glyphset.glyphLoader(font, i)); - } - } + setCurrentFiber(fiber); - return glyphs; -} + try { + reappearLayoutEffectsOnFiber(fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } -function parseGlyfTableOnLowMemory(data, start, loca, font) { - var glyphs = new glyphset.GlyphSet(font); + resetCurrentFiber(); - font._push = function(i) { - var offset = loca[i]; - var nextOffset = loca[i + 1]; - if (offset !== nextOffset) { - glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); - } else { - glyphs.push(i, glyphset.glyphLoader(font, i)); - } - }; + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } - return glyphs; -} - -// Parse all the glyphs according to the offsets from the `loca` table. -function parseGlyfTable(data, start, loca, font, opt) { - if (opt.lowMemory) - { return parseGlyfTableOnLowMemory(data, start, loca, font); } - else - { return parseGlyfTableAll(data, start, loca, font); } -} - -var glyf = { getPath: getPath, parse: parseGlyfTable}; - -/* A TrueType font hinting interpreter. -* -* (c) 2017 Axel Kittenberger -* -* This interpreter has been implemented according to this documentation: -* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html -* -* According to the documentation F24DOT6 values are used for pixels. -* That means calculation is 1/64 pixel accurate and uses integer operations. -* However, Javascript has floating point operations by default and only -* those are available. One could make a case to simulate the 1/64 accuracy -* exactly by truncating after every division operation -* (for example with << 0) to get pixel exactly results as other TrueType -* implementations. It may make sense since some fonts are pixel optimized -* by hand using DELTAP instructions. The current implementation doesn't -* and rather uses full floating point precision. -* -* xScale, yScale and rotation is currently ignored. -* -* A few non-trivial instructions are missing as I didn't encounter yet -* a font that used them to test a possible implementation. -* -* Some fonts seem to use undocumented features regarding the twilight zone. -* Only some of them are implemented as they were encountered. -* -* The exports.DEBUG statements are removed on the minified distribution file. -*/ + var sibling = fiber.sibling; -var instructionTable; -var exec; -var execGlyph; -var execComponent; + if (sibling !== null) { + // This node may have been reused from a previous render, so we can't + // assume its return pointer is correct. + sibling.return = fiber.return; + nextEffect = sibling; + return; + } -/* -* Creates a hinting object. -* -* There ought to be exactly one -* for each truetype font that is used for hinting. -*/ -function Hinting(font) { - // the font this hinting object is for - this.font = font; + nextEffect = fiber.return; + } + } - this.getCommands = function (hPoints) { - return glyf.getPath(hPoints).commands; - }; + function commitPassiveMountEffects(root, finishedWork) { + nextEffect = finishedWork; + commitPassiveMountEffects_begin(finishedWork, root); + } - // cached states - this._fpgmState = - this._prepState = - undefined; + function commitPassiveMountEffects_begin(subtreeRoot, root) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; - // errorState - // 0 ... all okay - // 1 ... had an error in a glyf, - // continue working but stop spamming - // the console - // 2 ... error at prep, stop hinting at this ppem - // 3 ... error at fpeg, stop hinting for this font at all - this._errorState = 0; -} + if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { + ensureCorrectReturnPointer(firstChild, fiber); + nextEffect = firstChild; + } else { + commitPassiveMountEffects_complete(subtreeRoot, root); + } + } + } -/* -* Not rounding. -*/ -function roundOff(v) { - return v; -} + function commitPassiveMountEffects_complete(subtreeRoot, root) { + while (nextEffect !== null) { + var fiber = nextEffect; -/* -* Rounding to grid. -*/ -function roundToGrid(v) { - //Rounding in TT is supposed to "symmetrical around zero" - return Math.sign(v) * Math.round(Math.abs(v)); -} + if ((fiber.flags & Passive) !== NoFlags) { + setCurrentFiber(fiber); -/* -* Rounding to double grid. -*/ -function roundToDoubleGrid(v) { - return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2; -} + try { + commitPassiveMountOnFiber(root, fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } -/* -* Rounding to half grid. -*/ -function roundToHalfGrid(v) { - return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5); -} + resetCurrentFiber(); + } -/* -* Rounding to up to grid. -*/ -function roundUpToGrid(v) { - return Math.sign(v) * Math.ceil(Math.abs(v)); -} + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } -/* -* Rounding to down to grid. -*/ -function roundDownToGrid(v) { - return Math.sign(v) * Math.floor(Math.abs(v)); -} + var sibling = fiber.sibling; -/* -* Super rounding. -*/ -var roundSuper = function (v) { - var period = this.srPeriod; - var phase = this.srPhase; - var threshold = this.srThreshold; - var sign = 1; - - if (v < 0) { - v = -v; - sign = -1; - } + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } - v += threshold - phase; + nextEffect = fiber.return; + } + } - v = Math.trunc(v / period) * period; + function commitPassiveMountOnFiber(finishedRoot, finishedWork) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( finishedWork.mode & ProfileMode) { + startPassiveEffectTimer(); - v += phase; + try { + commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); + } finally { + recordPassiveEffectDuration(finishedWork); + } + } else { + commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); + } - // according to http://xgridfit.sourceforge.net/round.html - if (v < 0) { return phase * sign; } + break; + } + } + } - return v * sign; -}; + function commitPassiveUnmountEffects(firstChild) { + nextEffect = firstChild; + commitPassiveUnmountEffects_begin(); + } -/* -* Unit vector of x-axis. -*/ -var xUnitVector = { - x: 1, + function commitPassiveUnmountEffects_begin() { + while (nextEffect !== null) { + var fiber = nextEffect; + var child = fiber.child; - y: 0, + if ((nextEffect.flags & ChildDeletion) !== NoFlags) { + var deletions = fiber.deletions; - axis: 'x', + if (deletions !== null) { + for (var i = 0; i < deletions.length; i++) { + var fiberToDelete = deletions[i]; + nextEffect = fiberToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber); + } - // Gets the projected distance between two points. - // o1/o2 ... if true, respective original position is used. - distance: function (p1, p2, o1, o2) { - return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x); - }, + { + // A fiber was deleted from this parent fiber, but it's still part of + // the previous (alternate) parent fiber's list of children. Because + // children are a linked list, an earlier sibling that's still alive + // will be connected to the deleted fiber via its `alternate`: + // + // live fiber + // --alternate--> previous live fiber + // --sibling--> deleted fiber + // + // We can't disconnect `alternate` on nodes that haven't been deleted + // yet, but we can disconnect the `sibling` and `child` pointers. + var previousFiber = fiber.alternate; - // Moves point p so the moved position has the same relative - // position to the moved positions of rp1 and rp2 than the - // original positions had. - // - // See APPENDIX on INTERPOLATE at the bottom of this file. - interpolate: function (p, rp1, rp2, pv) { - var do1; - var do2; - var doa1; - var doa2; - var dm1; - var dm2; - var dt; - - if (!pv || pv === this) { - do1 = p.xo - rp1.xo; - do2 = p.xo - rp2.xo; - dm1 = rp1.x - rp1.xo; - dm2 = rp2.x - rp2.xo; - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; - - if (dt === 0) { - p.x = p.xo + (dm1 + dm2) / 2; - return; - } + if (previousFiber !== null) { + var detachedChild = previousFiber.child; - p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt; - return; - } + if (detachedChild !== null) { + previousFiber.child = null; - do1 = pv.distance(p, rp1, true, true); - do2 = pv.distance(p, rp2, true, true); - dm1 = pv.distance(rp1, rp1, false, true); - dm2 = pv.distance(rp2, rp2, false, true); - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; + do { + var detachedSibling = detachedChild.sibling; + detachedChild.sibling = null; + detachedChild = detachedSibling; + } while (detachedChild !== null); + } + } + } - if (dt === 0) { - xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); - return; - } + nextEffect = fiber; + } + } - xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); - }, + if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { + ensureCorrectReturnPointer(child, fiber); + nextEffect = child; + } else { + commitPassiveUnmountEffects_complete(); + } + } + } - // Slope of line normal to this - normalSlope: Number.NEGATIVE_INFINITY, - - // Sets the point 'p' relative to point 'rp' - // by the distance 'd'. - // - // See APPENDIX on SETRELATIVE at the bottom of this file. - // - // p ... point to set - // rp ... reference point - // d ... distance on projection vector - // pv ... projection vector (undefined = this) - // org ... if true, uses the original position of rp as reference. - setRelative: function (p, rp, d, pv, org) { - if (!pv || pv === this) { - p.x = (org ? rp.xo : rp.x) + d; - return; - } + function commitPassiveUnmountEffects_complete() { + while (nextEffect !== null) { + var fiber = nextEffect; - var rpx = org ? rp.xo : rp.x; - var rpy = org ? rp.yo : rp.y; - var rpdx = rpx + d * pv.x; - var rpdy = rpy + d * pv.y; + if ((fiber.flags & Passive) !== NoFlags) { + setCurrentFiber(fiber); + commitPassiveUnmountOnFiber(fiber); + resetCurrentFiber(); + } - p.x = rpdx + (p.y - rpdy) / pv.normalSlope; - }, + var sibling = fiber.sibling; - // Slope of vector line. - slope: 0, + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } - // Touches the point p. - touch: function (p) { - p.xTouched = true; - }, + nextEffect = fiber.return; + } + } - // Tests if a point p is touched. - touched: function (p) { - return p.xTouched; - }, + function commitPassiveUnmountOnFiber(finishedWork) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( finishedWork.mode & ProfileMode) { + startPassiveEffectTimer(); + commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); + recordPassiveEffectDuration(finishedWork); + } else { + commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); + } - // Untouches the point p. - untouch: function (p) { - p.xTouched = false; - } -}; + break; + } + } + } -/* -* Unit vector of y-axis. -*/ -var yUnitVector = { - x: 0, + function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) { + while (nextEffect !== null) { + var fiber = nextEffect; // Deletion effects fire in parent -> child order + // TODO: Check if fiber has a PassiveStatic flag - y: 1, + setCurrentFiber(fiber); + commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); + resetCurrentFiber(); + var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we + // do this, still need to handle `deletedTreeCleanUpLevel` correctly.) - axis: 'y', + if (child !== null) { + ensureCorrectReturnPointer(child, fiber); + nextEffect = child; + } else { + commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot); + } + } + } - // Gets the projected distance between two points. - // o1/o2 ... if true, respective original position is used. - distance: function (p1, p2, o1, o2) { - return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y); - }, + function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var sibling = fiber.sibling; + var returnFiber = fiber.return; - // Moves point p so the moved position has the same relative - // position to the moved positions of rp1 and rp2 than the - // original positions had. - // - // See APPENDIX on INTERPOLATE at the bottom of this file. - interpolate: function (p, rp1, rp2, pv) { - var do1; - var do2; - var doa1; - var doa2; - var dm1; - var dm2; - var dt; - - if (!pv || pv === this) { - do1 = p.yo - rp1.yo; - do2 = p.yo - rp2.yo; - dm1 = rp1.y - rp1.yo; - dm2 = rp2.y - rp2.yo; - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; - - if (dt === 0) { - p.y = p.yo + (dm1 + dm2) / 2; - return; - } + { + // Recursively traverse the entire deleted tree and clean up fiber fields. + // This is more aggressive than ideal, and the long term goal is to only + // have to detach the deleted tree at the root. + detachFiberAfterEffects(fiber); - p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt; - return; - } + if (fiber === deletedSubtreeRoot) { + nextEffect = null; + return; + } + } - do1 = pv.distance(p, rp1, true, true); - do2 = pv.distance(p, rp2, true, true); - dm1 = pv.distance(rp1, rp1, false, true); - dm2 = pv.distance(rp2, rp2, false, true); - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, returnFiber); + nextEffect = sibling; + return; + } - if (dt === 0) { - yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); - return; - } + nextEffect = returnFiber; + } + } - yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); - }, + function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) { + switch (current.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( current.mode & ProfileMode) { + startPassiveEffectTimer(); + commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); + recordPassiveEffectDuration(current); + } else { + commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); + } - // Slope of line normal to this. - normalSlope: 0, - - // Sets the point 'p' relative to point 'rp' - // by the distance 'd' - // - // See APPENDIX on SETRELATIVE at the bottom of this file. - // - // p ... point to set - // rp ... reference point - // d ... distance on projection vector - // pv ... projection vector (undefined = this) - // org ... if true, uses the original position of rp as reference. - setRelative: function (p, rp, d, pv, org) { - if (!pv || pv === this) { - p.y = (org ? rp.yo : rp.y) + d; - return; - } + break; + } + } + } - var rpx = org ? rp.xo : rp.x; - var rpy = org ? rp.yo : rp.y; - var rpdx = rpx + d * pv.x; - var rpdy = rpy + d * pv.y; + var didWarnWrongReturnPointer = false; - p.y = rpdy + pv.normalSlope * (p.x - rpdx); - }, + function ensureCorrectReturnPointer(fiber, expectedReturnFiber) { + { + if (!didWarnWrongReturnPointer && fiber.return !== expectedReturnFiber) { + didWarnWrongReturnPointer = true; - // Slope of vector line. - slope: Number.POSITIVE_INFINITY, + error('Internal React error: Return pointer is inconsistent ' + 'with parent.'); + } + } // TODO: Remove this assignment once we're confident that it won't break + // anything, by checking the warning logs for the above invariant - // Touches the point p. - touch: function (p) { - p.yTouched = true; - }, - // Tests if a point p is touched. - touched: function (p) { - return p.yTouched; - }, + fiber.return = expectedReturnFiber; + } // TODO: Reuse reappearLayoutEffects traversal here? - // Untouches the point p. - untouch: function (p) { - p.yTouched = false; - } -}; -Object.freeze(xUnitVector); -Object.freeze(yUnitVector); + function invokeLayoutEffectMountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListMount(Layout | HasEffect, fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } -/* -* Creates a unit vector that is not x- or y-axis. -*/ -function UnitVector(x, y) { - this.x = x; - this.y = y; - this.axis = undefined; - this.slope = y / x; - this.normalSlope = -x / y; - Object.freeze(this); -} + break; + } -/* -* Gets the projected distance between two points. -* o1/o2 ... if true, respective original position is used. -*/ -UnitVector.prototype.distance = function(p1, p2, o1, o2) { - return ( - this.x * xUnitVector.distance(p1, p2, o1, o2) + - this.y * yUnitVector.distance(p1, p2, o1, o2) - ); -}; + case ClassComponent: + { + var instance = fiber.stateNode; -/* -* Moves point p so the moved position has the same relative -* position to the moved positions of rp1 and rp2 than the -* original positions had. -* -* See APPENDIX on INTERPOLATE at the bottom of this file. -*/ -UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) { - var dm1; - var dm2; - var do1; - var do2; - var doa1; - var doa2; - var dt; - - do1 = pv.distance(p, rp1, true, true); - do2 = pv.distance(p, rp2, true, true); - dm1 = pv.distance(rp1, rp1, false, true); - dm2 = pv.distance(rp2, rp2, false, true); - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; - - if (dt === 0) { - this.setRelative(p, p, (dm1 + dm2) / 2, pv, true); - return; - } + try { + instance.componentDidMount(); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); -}; + break; + } + } + } + } -/* -* Sets the point 'p' relative to point 'rp' -* by the distance 'd' -* -* See APPENDIX on SETRELATIVE at the bottom of this file. -* -* p ... point to set -* rp ... reference point -* d ... distance on projection vector -* pv ... projection vector (undefined = this) -* org ... if true, uses the original position of rp as reference. -*/ -UnitVector.prototype.setRelative = function(p, rp, d, pv, org) { - pv = pv || this; + function invokePassiveEffectMountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListMount(Passive$1 | HasEffect, fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - var rpx = org ? rp.xo : rp.x; - var rpy = org ? rp.yo : rp.y; - var rpdx = rpx + d * pv.x; - var rpdy = rpy + d * pv.y; + break; + } + } + } + } - var pvns = pv.normalSlope; - var fvs = this.slope; + function invokeLayoutEffectUnmountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - var px = p.x; - var py = p.y; + break; + } - p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns); - p.y = fvs * (p.x - px) + py; -}; + case ClassComponent: + { + var instance = fiber.stateNode; -/* -* Touches the point p. -*/ -UnitVector.prototype.touch = function(p) { - p.xTouched = true; - p.yTouched = true; -}; + if (typeof instance.componentWillUnmount === 'function') { + safelyCallComponentWillUnmount(fiber, fiber.return, instance); + } -/* -* Returns a unit vector with x/y coordinates. -*/ -function getUnitVector(x, y) { - var d = Math.sqrt(x * x + y * y); + break; + } + } + } + } - x /= d; - y /= d; + function invokePassiveEffectUnmountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } + } + } + } + } - if (x === 1 && y === 0) { return xUnitVector; } - else if (x === 0 && y === 1) { return yUnitVector; } - else { return new UnitVector(x, y); } -} + var COMPONENT_TYPE = 0; + var HAS_PSEUDO_CLASS_TYPE = 1; + var ROLE_TYPE = 2; + var TEST_NAME_TYPE = 3; + var TEXT_TYPE = 4; -/* -* Creates a point in the hinting engine. -*/ -function HPoint( - x, - y, - lastPointOfContour, - onCurve -) { - this.x = this.xo = Math.round(x * 64) / 64; // hinted x value and original x-value - this.y = this.yo = Math.round(y * 64) / 64; // hinted y value and original y-value + if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + COMPONENT_TYPE = symbolFor('selector.component'); + HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class'); + ROLE_TYPE = symbolFor('selector.role'); + TEST_NAME_TYPE = symbolFor('selector.test_id'); + TEXT_TYPE = symbolFor('selector.text'); + } - this.lastPointOfContour = lastPointOfContour; - this.onCurve = onCurve; - this.prevPointOnContour = undefined; - this.nextPointOnContour = undefined; - this.xTouched = false; - this.yTouched = false; + function createComponentSelector(component) { + return { + $$typeof: COMPONENT_TYPE, + value: component + }; + } + function createHasPseudoClassSelector(selectors) { + return { + $$typeof: HAS_PSEUDO_CLASS_TYPE, + value: selectors + }; + } + function createRoleSelector(role) { + return { + $$typeof: ROLE_TYPE, + value: role + }; + } + function createTextSelector(text) { + return { + $$typeof: TEXT_TYPE, + value: text + }; + } + function createTestNameSelector(id) { + return { + $$typeof: TEST_NAME_TYPE, + value: id + }; + } - Object.preventExtensions(this); -} + function findFiberRootForHostRoot(hostRoot) { + var maybeFiber = getInstanceFromNode(hostRoot); -/* -* Returns the next touched point on the contour. -* -* v ... unit vector to test touch axis. -*/ -HPoint.prototype.nextTouched = function(v) { - var p = this.nextPointOnContour; + if (maybeFiber != null) { + if (typeof maybeFiber.memoizedProps['data-testname'] !== 'string') { + throw new Error('Invalid host root specified. Should be either a React container or a node with a testname attribute.'); + } - while (!v.touched(p) && p !== this) { p = p.nextPointOnContour; } + return maybeFiber; + } else { + var fiberRoot = findFiberRoot(hostRoot); - return p; -}; + if (fiberRoot === null) { + throw new Error('Could not find React container within specified host subtree.'); + } // The Flow type for FiberRoot is a little funky. + // createFiberRoot() cheats this by treating the root as :any and adding stateNode lazily. -/* -* Returns the previous touched point on the contour -* -* v ... unit vector to test touch axis. -*/ -HPoint.prototype.prevTouched = function(v) { - var p = this.prevPointOnContour; - while (!v.touched(p) && p !== this) { p = p.prevPointOnContour; } + return fiberRoot.stateNode.current; + } + } - return p; -}; + function matchSelector(fiber, selector) { + switch (selector.$$typeof) { + case COMPONENT_TYPE: + if (fiber.type === selector.value) { + return true; + } -/* -* The zero point. -*/ -var HPZero = Object.freeze(new HPoint(0, 0)); + break; -/* -* The default state of the interpreter. -* -* Note: Freezing the defaultState and then deriving from it -* makes the V8 Javascript engine going awkward, -* so this is avoided, albeit the defaultState shouldn't -* ever change. -*/ -var defaultState = { - cvCutIn: 17 / 16, // control value cut in - deltaBase: 9, - deltaShift: 0.125, - loop: 1, // loops some instructions - minDis: 1, // minimum distance - autoFlip: true -}; + case HAS_PSEUDO_CLASS_TYPE: + return hasMatchingPaths(fiber, selector.value); -/* -* The current state of the interpreter. -* -* env ... 'fpgm' or 'prep' or 'glyf' -* prog ... the program -*/ -function State(env, prog) { - this.env = env; - this.stack = []; - this.prog = prog; - - switch (env) { - case 'glyf' : - this.zp0 = this.zp1 = this.zp2 = 1; - this.rp0 = this.rp1 = this.rp2 = 0; - /* fall through */ - case 'prep' : - this.fv = this.pv = this.dpv = xUnitVector; - this.round = roundToGrid; - } -} + case ROLE_TYPE: + if (fiber.tag === HostComponent) { + var node = fiber.stateNode; -/* -* Executes a glyph program. -* -* This does the hinting for each glyph. -* -* Returns an array of moved points. -* -* glyph: the glyph to hint -* ppem: the size the glyph is rendered for -*/ -Hinting.prototype.exec = function(glyph, ppem) { - if (typeof ppem !== 'number') { - throw new Error('Point size is not a number!'); - } + if (matchAccessibilityRole(node, selector.value)) { + return true; + } + } - // Received a fatal error, don't do any hinting anymore. - if (this._errorState > 2) { return; } + break; - var font = this.font; - var prepState = this._prepState; + case TEXT_TYPE: + if (fiber.tag === HostComponent || fiber.tag === HostText) { + var textContent = getTextContent(fiber); - if (!prepState || prepState.ppem !== ppem) { - var fpgmState = this._fpgmState; + if (textContent !== null && textContent.indexOf(selector.value) >= 0) { + return true; + } + } - if (!fpgmState) { - // Executes the fpgm state. - // This is used by fonts to define functions. - State.prototype = defaultState; + break; - fpgmState = - this._fpgmState = - new State('fpgm', font.tables.fpgm); + case TEST_NAME_TYPE: + if (fiber.tag === HostComponent) { + var dataTestID = fiber.memoizedProps['data-testname']; - fpgmState.funcs = [ ]; - fpgmState.font = font; + if (typeof dataTestID === 'string' && dataTestID.toLowerCase() === selector.value.toLowerCase()) { + return true; + } + } - if (exports.DEBUG) { - console.log('---EXEC FPGM---'); - fpgmState.step = -1; - } + break; - try { - exec(fpgmState); - } catch (e) { - console.log('Hinting error in FPGM:' + e); - this._errorState = 3; - return; - } - } + default: + throw new Error('Invalid selector type specified.'); + } - // Executes the prep program for this ppem setting. - // This is used by fonts to set cvt values - // depending on to be rendered font size. - - State.prototype = fpgmState; - prepState = - this._prepState = - new State('prep', font.tables.prep); - - prepState.ppem = ppem; - - // Creates a copy of the cvt table - // and scales it to the current ppem setting. - var oCvt = font.tables.cvt; - if (oCvt) { - var cvt = prepState.cvt = new Array(oCvt.length); - var scale = ppem / font.unitsPerEm; - for (var c = 0; c < oCvt.length; c++) { - cvt[c] = oCvt[c] * scale; - } - } else { - prepState.cvt = []; - } + return false; + } - if (exports.DEBUG) { - console.log('---EXEC PREP---'); - prepState.step = -1; - } + function selectorToString(selector) { + switch (selector.$$typeof) { + case COMPONENT_TYPE: + var displayName = getComponentNameFromType(selector.value) || 'Unknown'; + return "<" + displayName + ">"; - try { - exec(prepState); - } catch (e) { - if (this._errorState < 2) { - console.log('Hinting error in PREP:' + e); - } - this._errorState = 2; - } - } + case HAS_PSEUDO_CLASS_TYPE: + return ":has(" + (selectorToString(selector) || '') + ")"; - if (this._errorState > 1) { return; } + case ROLE_TYPE: + return "[role=\"" + selector.value + "\"]"; - try { - return execGlyph(glyph, prepState); - } catch (e) { - if (this._errorState < 1) { - console.log('Hinting error:' + e); - console.log('Note: further hinting errors are silenced'); - } - this._errorState = 1; - return undefined; - } -}; + case TEXT_TYPE: + return "\"" + selector.value + "\""; -/* -* Executes the hinting program for a glyph. -*/ -execGlyph = function(glyph, prepState) { - // original point positions - var xScale = prepState.ppem / prepState.font.unitsPerEm; - var yScale = xScale; - var components = glyph.components; - var contours; - var gZone; - var state; - - State.prototype = prepState; - if (!components) { - state = new State('glyf', glyph.instructions); - if (exports.DEBUG) { - console.log('---EXEC GLYPH---'); - state.step = -1; - } - execComponent(glyph, state, xScale, yScale); - gZone = state.gZone; - } else { - var font = prepState.font; - gZone = []; - contours = []; - for (var i = 0; i < components.length; i++) { - var c = components[i]; - var cg = font.glyphs.get(c.glyphIndex); - - state = new State('glyf', cg.instructions); - - if (exports.DEBUG) { - console.log('---EXEC COMP ' + i + '---'); - state.step = -1; - } + case TEST_NAME_TYPE: + return "[data-testname=\"" + selector.value + "\"]"; - execComponent(cg, state, xScale, yScale); - // appends the computed points to the result array - // post processes the component points - var dx = Math.round(c.dx * xScale); - var dy = Math.round(c.dy * yScale); - var gz = state.gZone; - var cc = state.contours; - for (var pi = 0; pi < gz.length; pi++) { - var p = gz[pi]; - p.xTouched = p.yTouched = false; - p.xo = p.x = p.x + dx; - p.yo = p.y = p.y + dy; - } + default: + throw new Error('Invalid selector type specified.'); + } + } - var gLen = gZone.length; - gZone.push.apply(gZone, gz); - for (var j = 0; j < cc.length; j++) { - contours.push(cc[j] + gLen); - } - } + function findPaths(root, selectors) { + var matchingFibers = []; + var stack = [root, 0]; + var index = 0; - if (glyph.instructions && !state.inhibitGridFit) { - // the composite has instructions on its own - state = new State('glyf', glyph.instructions); + while (index < stack.length) { + var fiber = stack[index++]; + var selectorIndex = stack[index++]; + var selector = selectors[selectorIndex]; - state.gZone = state.z0 = state.z1 = state.z2 = gZone; + if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { + continue; + } else { + while (selector != null && matchSelector(fiber, selector)) { + selectorIndex++; + selector = selectors[selectorIndex]; + } + } - state.contours = contours; + if (selectorIndex === selectors.length) { + matchingFibers.push(fiber); + } else { + var child = fiber.child; - // note: HPZero cannot be used here, since - // the point might be modified - gZone.push( - new HPoint(0, 0), - new HPoint(Math.round(glyph.advanceWidth * xScale), 0) - ); + while (child !== null) { + stack.push(child, selectorIndex); + child = child.sibling; + } + } + } - if (exports.DEBUG) { - console.log('---EXEC COMPOSITE---'); - state.step = -1; - } + return matchingFibers; + } // Same as findPaths but with eager bailout on first match - exec(state); - gZone.length -= 2; - } - } + function hasMatchingPaths(root, selectors) { + var stack = [root, 0]; + var index = 0; - return gZone; -}; + while (index < stack.length) { + var fiber = stack[index++]; + var selectorIndex = stack[index++]; + var selector = selectors[selectorIndex]; -/* -* Executes the hinting program for a component of a multi-component glyph -* or of the glyph itself for a non-component glyph. -*/ -execComponent = function(glyph, state, xScale, yScale) -{ - var points = glyph.points || []; - var pLen = points.length; - var gZone = state.gZone = state.z0 = state.z1 = state.z2 = []; - var contours = state.contours = []; - - // Scales the original points and - // makes copies for the hinted points. - var cp; // current point - for (var i = 0; i < pLen; i++) { - cp = points[i]; - - gZone[i] = new HPoint( - cp.x * xScale, - cp.y * yScale, - cp.lastPointOfContour, - cp.onCurve - ); - } + if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { + continue; + } else { + while (selector != null && matchSelector(fiber, selector)) { + selectorIndex++; + selector = selectors[selectorIndex]; + } + } - // Chain links the contours. - var sp; // start point - var np; // next point + if (selectorIndex === selectors.length) { + return true; + } else { + var child = fiber.child; - for (var i$1 = 0; i$1 < pLen; i$1++) { - cp = gZone[i$1]; + while (child !== null) { + stack.push(child, selectorIndex); + child = child.sibling; + } + } + } - if (!sp) { - sp = cp; - contours.push(i$1); - } + return false; + } - if (cp.lastPointOfContour) { - cp.nextPointOnContour = sp; - sp.prevPointOnContour = cp; - sp = undefined; - } else { - np = gZone[i$1 + 1]; - cp.nextPointOnContour = np; - np.prevPointOnContour = cp; - } - } + function findAllNodes(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } - if (state.inhibitGridFit) { return; } + var root = findFiberRootForHostRoot(hostRoot); + var matchingFibers = findPaths(root, selectors); + var instanceRoots = []; + var stack = Array.from(matchingFibers); + var index = 0; - if (exports.DEBUG) { - console.log('PROCESSING GLYPH', state.stack); - for (var i$2 = 0; i$2 < pLen; i$2++) { - console.log(i$2, gZone[i$2].x, gZone[i$2].y); - } - } + while (index < stack.length) { + var node = stack[index++]; - gZone.push( - new HPoint(0, 0), - new HPoint(Math.round(glyph.advanceWidth * xScale), 0) - ); + if (node.tag === HostComponent) { + if (isHiddenSubtree(node)) { + continue; + } - exec(state); + instanceRoots.push(node.stateNode); + } else { + var child = node.child; - // Removes the extra points. - gZone.length -= 2; + while (child !== null) { + stack.push(child); + child = child.sibling; + } + } + } - if (exports.DEBUG) { - console.log('FINISHED GLYPH', state.stack); - for (var i$3 = 0; i$3 < pLen; i$3++) { - console.log(i$3, gZone[i$3].x, gZone[i$3].y); - } - } -}; + return instanceRoots; + } + function getFindAllNodesFailureDescription(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } -/* -* Executes the program loaded in state. -*/ -exec = function(state) { - var prog = state.prog; + var root = findFiberRootForHostRoot(hostRoot); + var maxSelectorIndex = 0; + var matchedNames = []; // The logic of this loop should be kept in sync with findPaths() - if (!prog) { return; } + var stack = [root, 0]; + var index = 0; - var pLen = prog.length; - var ins; + while (index < stack.length) { + var fiber = stack[index++]; + var selectorIndex = stack[index++]; + var selector = selectors[selectorIndex]; - for (state.ip = 0; state.ip < pLen; state.ip++) { - if (exports.DEBUG) { state.step++; } - ins = instructionTable[prog[state.ip]]; + if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { + continue; + } else if (matchSelector(fiber, selector)) { + matchedNames.push(selectorToString(selector)); + selectorIndex++; - if (!ins) { - throw new Error( - 'unknown instruction: 0x' + - Number(prog[state.ip]).toString(16) - ); - } + if (selectorIndex > maxSelectorIndex) { + maxSelectorIndex = selectorIndex; + } + } - ins(state); - - // very extensive debugging for each step - /* - if (exports.DEBUG) { - var da; - if (state.gZone) { - da = []; - for (let i = 0; i < state.gZone.length; i++) - { - da.push(i + ' ' + - state.gZone[i].x * 64 + ' ' + - state.gZone[i].y * 64 + ' ' + - (state.gZone[i].xTouched ? 'x' : '') + - (state.gZone[i].yTouched ? 'y' : '') - ); - } - console.log('GZ', da); - } + if (selectorIndex < selectors.length) { + var child = fiber.child; - if (state.tZone) { - da = []; - for (let i = 0; i < state.tZone.length; i++) { - da.push(i + ' ' + - state.tZone[i].x * 64 + ' ' + - state.tZone[i].y * 64 + ' ' + - (state.tZone[i].xTouched ? 'x' : '') + - (state.tZone[i].yTouched ? 'y' : '') - ); - } - console.log('TZ', da); - } + while (child !== null) { + stack.push(child, selectorIndex); + child = child.sibling; + } + } + } - if (state.stack.length > 10) { - console.log( - state.stack.length, - '...', state.stack.slice(state.stack.length - 10) - ); - } else { - console.log(state.stack.length, state.stack); - } - } - */ - } -}; + if (maxSelectorIndex < selectors.length) { + var unmatchedNames = []; -/* -* Initializes the twilight zone. -* -* This is only done if a SZPx instruction -* refers to the twilight zone. -*/ -function initTZone(state) -{ - var tZone = state.tZone = new Array(state.gZone.length); + for (var i = maxSelectorIndex; i < selectors.length; i++) { + unmatchedNames.push(selectorToString(selectors[i])); + } - // no idea if this is actually correct... - for (var i = 0; i < tZone.length; i++) - { - tZone[i] = new HPoint(0, 0); - } -} + return 'findAllNodes was able to match part of the selector:\n' + (" " + matchedNames.join(' > ') + "\n\n") + 'No matching component was found for:\n' + (" " + unmatchedNames.join(' > ')); + } -/* -* Skips the instruction pointer ahead over an IF/ELSE block. -* handleElse .. if true breaks on matching ELSE -*/ -function skip(state, handleElse) -{ - var prog = state.prog; - var ip = state.ip; - var nesting = 1; - var ins; - - do { - ins = prog[++ip]; - if (ins === 0x58) // IF - { nesting++; } - else if (ins === 0x59) // EIF - { nesting--; } - else if (ins === 0x40) // NPUSHB - { ip += prog[ip + 1] + 1; } - else if (ins === 0x41) // NPUSHW - { ip += 2 * prog[ip + 1] + 1; } - else if (ins >= 0xB0 && ins <= 0xB7) // PUSHB - { ip += ins - 0xB0 + 1; } - else if (ins >= 0xB8 && ins <= 0xBF) // PUSHW - { ip += (ins - 0xB8 + 1) * 2; } - else if (handleElse && nesting === 1 && ins === 0x1B) // ELSE - { break; } - } while (nesting > 0); - - state.ip = ip; -} - -/*----------------------------------------------------------* -* And then a lot of instructions... * -*----------------------------------------------------------*/ - -// SVTCA[a] Set freedom and projection Vectors To Coordinate Axis -// 0x00-0x01 -function SVTCA(v, state) { - if (exports.DEBUG) { console.log(state.step, 'SVTCA[' + v.axis + ']'); } - - state.fv = state.pv = state.dpv = v; -} - -// SPVTCA[a] Set Projection Vector to Coordinate Axis -// 0x02-0x03 -function SPVTCA(v, state) { - if (exports.DEBUG) { console.log(state.step, 'SPVTCA[' + v.axis + ']'); } - - state.pv = state.dpv = v; -} - -// SFVTCA[a] Set Freedom Vector to Coordinate Axis -// 0x04-0x05 -function SFVTCA(v, state) { - if (exports.DEBUG) { console.log(state.step, 'SFVTCA[' + v.axis + ']'); } - - state.fv = v; -} - -// SPVTL[a] Set Projection Vector To Line -// 0x06-0x07 -function SPVTL(a, state) { - var stack = state.stack; - var p2i = stack.pop(); - var p1i = stack.pop(); - var p2 = state.z2[p2i]; - var p1 = state.z1[p1i]; - - if (exports.DEBUG) { console.log('SPVTL[' + a + ']', p2i, p1i); } - - var dx; - var dy; - - if (!a) { - dx = p1.x - p2.x; - dy = p1.y - p2.y; - } else { - dx = p2.y - p1.y; - dy = p1.x - p2.x; - } + return null; + } + function findBoundingRects(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } - state.pv = state.dpv = getUnitVector(dx, dy); -} + var instanceRoots = findAllNodes(hostRoot, selectors); + var boundingRects = []; -// SFVTL[a] Set Freedom Vector To Line -// 0x08-0x09 -function SFVTL(a, state) { - var stack = state.stack; - var p2i = stack.pop(); - var p1i = stack.pop(); - var p2 = state.z2[p2i]; - var p1 = state.z1[p1i]; + for (var i = 0; i < instanceRoots.length; i++) { + boundingRects.push(getBoundingRect(instanceRoots[i])); + } - if (exports.DEBUG) { console.log('SFVTL[' + a + ']', p2i, p1i); } + for (var _i = boundingRects.length - 1; _i > 0; _i--) { + var targetRect = boundingRects[_i]; + var targetLeft = targetRect.x; + var targetRight = targetLeft + targetRect.width; + var targetTop = targetRect.y; + var targetBottom = targetTop + targetRect.height; - var dx; - var dy; + for (var j = _i - 1; j >= 0; j--) { + if (_i !== j) { + var otherRect = boundingRects[j]; + var otherLeft = otherRect.x; + var otherRight = otherLeft + otherRect.width; + var otherTop = otherRect.y; + var otherBottom = otherTop + otherRect.height; // Merging all rects to the minimums set would be complicated, + // but we can handle the most common cases: + // 1. completely overlapping rects + // 2. adjacent rects that are the same width or height (e.g. items in a list) + // + // Even given the above constraints, + // we still won't end up with the fewest possible rects without doing multiple passes, + // but it's good enough for this purpose. - if (!a) { - dx = p1.x - p2.x; - dy = p1.y - p2.y; - } else { - dx = p2.y - p1.y; - dy = p1.x - p2.x; - } + if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) { + // Complete overlapping rects; remove the inner one. + boundingRects.splice(_i, 1); + break; + } else if (targetLeft === otherLeft && targetRect.width === otherRect.width && !(otherBottom < targetTop) && !(otherTop > targetBottom)) { + // Adjacent vertical rects; merge them. + if (otherTop > targetTop) { + otherRect.height += otherTop - targetTop; + otherRect.y = targetTop; + } - state.fv = getUnitVector(dx, dy); -} + if (otherBottom < targetBottom) { + otherRect.height = targetBottom - otherTop; + } -// SPVFS[] Set Projection Vector From Stack -// 0x0A -function SPVFS(state) { - var stack = state.stack; - var y = stack.pop(); - var x = stack.pop(); + boundingRects.splice(_i, 1); + break; + } else if (targetTop === otherTop && targetRect.height === otherRect.height && !(otherRight < targetLeft) && !(otherLeft > targetRight)) { + // Adjacent horizontal rects; merge them. + if (otherLeft > targetLeft) { + otherRect.width += otherLeft - targetLeft; + otherRect.x = targetLeft; + } - if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); } + if (otherRight < targetRight) { + otherRect.width = targetRight - otherLeft; + } - state.pv = state.dpv = getUnitVector(x, y); -} + boundingRects.splice(_i, 1); + break; + } + } + } + } -// SFVFS[] Set Freedom Vector From Stack -// 0x0B -function SFVFS(state) { - var stack = state.stack; - var y = stack.pop(); - var x = stack.pop(); + return boundingRects; + } + function focusWithin(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } - if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); } + var root = findFiberRootForHostRoot(hostRoot); + var matchingFibers = findPaths(root, selectors); + var stack = Array.from(matchingFibers); + var index = 0; - state.fv = getUnitVector(x, y); -} + while (index < stack.length) { + var fiber = stack[index++]; -// GPV[] Get Projection Vector -// 0x0C -function GPV(state) { - var stack = state.stack; - var pv = state.pv; + if (isHiddenSubtree(fiber)) { + continue; + } - if (exports.DEBUG) { console.log(state.step, 'GPV[]'); } + if (fiber.tag === HostComponent) { + var node = fiber.stateNode; - stack.push(pv.x * 0x4000); - stack.push(pv.y * 0x4000); -} + if (setFocusIfFocusable(node)) { + return true; + } + } -// GFV[] Get Freedom Vector -// 0x0C -function GFV(state) { - var stack = state.stack; - var fv = state.fv; + var child = fiber.child; - if (exports.DEBUG) { console.log(state.step, 'GFV[]'); } + while (child !== null) { + stack.push(child); + child = child.sibling; + } + } - stack.push(fv.x * 0x4000); - stack.push(fv.y * 0x4000); -} + return false; + } + var commitHooks = []; + function onCommitRoot$1() { + if (supportsTestSelectors) { + commitHooks.forEach(function (commitHook) { + return commitHook(); + }); + } + } + function observeVisibleRects(hostRoot, selectors, callback, options) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } -// SFVTPV[] Set Freedom Vector To Projection Vector -// 0x0E -function SFVTPV(state) { - state.fv = state.pv; + var instanceRoots = findAllNodes(hostRoot, selectors); - if (exports.DEBUG) { console.log(state.step, 'SFVTPV[]'); } -} + var _setupIntersectionObs = setupIntersectionObserver(instanceRoots, callback, options), + disconnect = _setupIntersectionObs.disconnect, + observe = _setupIntersectionObs.observe, + unobserve = _setupIntersectionObs.unobserve; // When React mutates the host environment, we may need to change what we're listening to. -// ISECT[] moves point p to the InterSECTion of two lines -// 0x0F -function ISECT(state) -{ - var stack = state.stack; - var pa0i = stack.pop(); - var pa1i = stack.pop(); - var pb0i = stack.pop(); - var pb1i = stack.pop(); - var pi = stack.pop(); - var z0 = state.z0; - var z1 = state.z1; - var pa0 = z0[pa0i]; - var pa1 = z0[pa1i]; - var pb0 = z1[pb0i]; - var pb1 = z1[pb1i]; - var p = state.z2[pi]; - if (exports.DEBUG) { console.log('ISECT[], ', pa0i, pa1i, pb0i, pb1i, pi); } + var commitHook = function () { + var nextInstanceRoots = findAllNodes(hostRoot, selectors); + instanceRoots.forEach(function (target) { + if (nextInstanceRoots.indexOf(target) < 0) { + unobserve(target); + } + }); + nextInstanceRoots.forEach(function (target) { + if (instanceRoots.indexOf(target) < 0) { + observe(target); + } + }); + }; - // math from - // en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line + commitHooks.push(commitHook); + return { + disconnect: function () { + // Stop listening for React mutations: + var index = commitHooks.indexOf(commitHook); - var x1 = pa0.x; - var y1 = pa0.y; - var x2 = pa1.x; - var y2 = pa1.y; - var x3 = pb0.x; - var y3 = pb0.y; - var x4 = pb1.x; - var y4 = pb1.y; + if (index >= 0) { + commitHooks.splice(index, 1); + } // Disconnect the host observer: - var div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); - var f1 = x1 * y2 - y1 * x2; - var f2 = x3 * y4 - y3 * x4; - p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div; - p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div; -} + disconnect(); + } + }; + } -// SRP0[] Set Reference Point 0 -// 0x10 -function SRP0(state) { - state.rp0 = state.stack.pop(); + var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; + function isLegacyActEnvironment(fiber) { + { + // Legacy mode. We preserve the behavior of React 17's act. It assumes an + // act environment whenever `jest` is defined, but you can still turn off + // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly + // to false. + var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global + typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest - if (exports.DEBUG) { console.log(state.step, 'SRP0[]', state.rp0); } -} + var jestIsDefined = typeof jest !== 'undefined'; + return warnsIfNotActing && jestIsDefined && isReactActEnvironmentGlobal !== false; + } + } + function isConcurrentActEnvironment() { + { + var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global + typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; -// SRP1[] Set Reference Point 1 -// 0x11 -function SRP1(state) { - state.rp1 = state.stack.pop(); + if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { + // TODO: Include link to relevant documentation page. + error('The current testing environment is not configured to support ' + 'act(...)'); + } - if (exports.DEBUG) { console.log(state.step, 'SRP1[]', state.rp1); } -} + return isReactActEnvironmentGlobal; + } + } -// SRP1[] Set Reference Point 2 -// 0x12 -function SRP2(state) { - state.rp2 = state.stack.pop(); + var ceil = Math.ceil; + var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, + ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, + ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig, + ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue; + var NoContext = + /* */ + 0; + var BatchedContext = + /* */ + 1; + var RenderContext = + /* */ + 2; + var CommitContext = + /* */ + 4; + var RootInProgress = 0; + var RootFatalErrored = 1; + var RootErrored = 2; + var RootSuspended = 3; + var RootSuspendedWithDelay = 4; + var RootCompleted = 5; + var RootDidNotComplete = 6; // Describes where we are in the React execution stack - if (exports.DEBUG) { console.log(state.step, 'SRP2[]', state.rp2); } -} + var executionContext = NoContext; // The root we're working on -// SZP0[] Set Zone Pointer 0 -// 0x13 -function SZP0(state) { - var n = state.stack.pop(); + var workInProgressRoot = null; // The fiber we're working on - if (exports.DEBUG) { console.log(state.step, 'SZP0[]', n); } + var workInProgress = null; // The lanes we're rendering - state.zp0 = n; + var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree + // This is a superset of the lanes we started working on at the root. The only + // case where it's different from `workInProgressRootRenderLanes` is when we + // enter a subtree that is hidden and needs to be unhidden: Suspense and + // Offscreen component. + // + // Most things in the work loop should deal with workInProgressRootRenderLanes. + // Most things in begin/complete phases should deal with subtreeRenderLanes. - switch (n) { - case 0: - if (!state.tZone) { initTZone(state); } - state.z0 = state.tZone; - break; - case 1 : - state.z0 = state.gZone; - break; - default : - throw new Error('Invalid zone pointer'); - } -} + var subtreeRenderLanes = NoLanes; + var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc. -// SZP1[] Set Zone Pointer 1 -// 0x14 -function SZP1(state) { - var n = state.stack.pop(); + var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown - if (exports.DEBUG) { console.log(state.step, 'SZP1[]', n); } + var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's + // includes unprocessed updates, not work in bailed out children. - state.zp1 = n; + var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render. - switch (n) { - case 0: - if (!state.tZone) { initTZone(state); } - state.z1 = state.tZone; - break; - case 1 : - state.z1 = state.gZone; - break; - default : - throw new Error('Invalid zone pointer'); - } -} + var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event). -// SZP2[] Set Zone Pointer 2 -// 0x15 -function SZP2(state) { - var n = state.stack.pop(); + var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase. - if (exports.DEBUG) { console.log(state.step, 'SZP2[]', n); } + var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI. + // We will log them once the tree commits. - state.zp2 = n; + var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train + // model where we don't commit new loading states in too quick succession. - switch (n) { - case 0: - if (!state.tZone) { initTZone(state); } - state.z2 = state.tZone; - break; - case 1 : - state.z2 = state.gZone; - break; - default : - throw new Error('Invalid zone pointer'); - } -} + var globalMostRecentFallbackTime = 0; + var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering + // more and prefer CPU suspense heuristics instead. -// SZPS[] Set Zone PointerS -// 0x16 -function SZPS(state) { - var n = state.stack.pop(); + var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU + // suspense heuristics and opt out of rendering more content. - if (exports.DEBUG) { console.log(state.step, 'SZPS[]', n); } + var RENDER_TIMEOUT_MS = 500; - state.zp0 = state.zp1 = state.zp2 = n; + function resetRenderTimer() { + workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS; + } - switch (n) { - case 0: - if (!state.tZone) { initTZone(state); } - state.z0 = state.z1 = state.z2 = state.tZone; - break; - case 1 : - state.z0 = state.z1 = state.z2 = state.gZone; - break; - default : - throw new Error('Invalid zone pointer'); - } -} + function getRenderTargetTime() { + return workInProgressRootRenderTargetTime; + } + var hasUncaughtError = false; + var firstUncaughtError = null; + var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true; + var rootDoesHavePassiveEffects = false; + var rootWithPendingPassiveEffects = null; + var pendingPassiveEffectsLanes = NoLanes; + var pendingPassiveProfilerEffects = []; -// SLOOP[] Set LOOP variable -// 0x17 -function SLOOP(state) { - state.loop = state.stack.pop(); + var NESTED_UPDATE_LIMIT = 50; + var nestedUpdateCount = 0; + var rootWithNestedUpdates = null; + var NESTED_PASSIVE_UPDATE_LIMIT = 50; + var nestedPassiveUpdateCount = 0; // If two updates are scheduled within the same event, we should treat their + // event times as simultaneous, even if the actual clock time has advanced + // between the first and second call. - if (exports.DEBUG) { console.log(state.step, 'SLOOP[]', state.loop); } -} + var currentEventTime = NoTimestamp; + var currentEventTransitionLane = NoLanes; + function getWorkInProgressRoot() { + return workInProgressRoot; + } + function requestEventTime() { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + // We're inside React, so it's fine to read the actual time. + return now$1(); + } // We're not inside React, so we may be in the middle of a browser event. -// RTG[] Round To Grid -// 0x18 -function RTG(state) { - if (exports.DEBUG) { console.log(state.step, 'RTG[]'); } - state.round = roundToGrid; -} + if (currentEventTime !== NoTimestamp) { + // Use the same start time for all updates until we enter React again. + return currentEventTime; + } // This is the first update since React yielded. Compute a new start time. -// RTHG[] Round To Half Grid -// 0x19 -function RTHG(state) { - if (exports.DEBUG) { console.log(state.step, 'RTHG[]'); } - state.round = roundToHalfGrid; -} + currentEventTime = now$1(); + return currentEventTime; + } + function requestUpdateLane(fiber) { + // Special cases + var mode = fiber.mode; -// SMD[] Set Minimum Distance -// 0x1A -function SMD(state) { - var d = state.stack.pop(); + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { + // This is a render phase update. These are not officially supported. The + // old behavior is to give this the same "thread" (lanes) as + // whatever is currently rendering. So if you call `setState` on a component + // that happens later in the same render, it will flush. Ideally, we want to + // remove the special case and treat them as if they came from an + // interleaved event. Regardless, this pattern is not officially supported. + // This behavior is only a fallback. The flag only exists until we can roll + // out the setState warning, since existing code might accidentally rely on + // the current behavior. + return pickArbitraryLane(workInProgressRootRenderLanes); + } - if (exports.DEBUG) { console.log(state.step, 'SMD[]', d); } + var isTransition = requestCurrentTransition() !== NoTransition; - state.minDis = d / 0x40; -} + if (isTransition) { + if ( ReactCurrentBatchConfig$2.transition !== null) { + var transition = ReactCurrentBatchConfig$2.transition; -// ELSE[] ELSE clause -// 0x1B -function ELSE(state) { - // This instruction has been reached by executing a then branch - // so it just skips ahead until matching EIF. - // - // In case the IF was negative the IF[] instruction already - // skipped forward over the ELSE[] + if (!transition._updatedFibers) { + transition._updatedFibers = new Set(); + } - if (exports.DEBUG) { console.log(state.step, 'ELSE[]'); } + transition._updatedFibers.add(fiber); + } // The algorithm for assigning an update to a lane should be stable for all + // updates at the same priority within the same event. To do this, the + // inputs to the algorithm must be the same. + // + // The trick we use is to cache the first of each of these inputs within an + // event. Then reset the cached values once we can be sure the event is + // over. Our heuristic for that is whenever we enter a concurrent work loop. - skip(state, false); -} -// JMPR[] JuMP Relative -// 0x1C -function JMPR(state) { - var o = state.stack.pop(); + if (currentEventTransitionLane === NoLane) { + // All transitions within the same event are assigned the same lane. + currentEventTransitionLane = claimNextTransitionLane(); + } - if (exports.DEBUG) { console.log(state.step, 'JMPR[]', o); } + return currentEventTransitionLane; + } // Updates originating inside certain React methods, like flushSync, have + // their priority set by tracking it with a context variable. + // + // The opaque type returned by the host config is internally a lane, so we can + // use that directly. + // TODO: Move this type conversion to the event priority module. - // A jump by 1 would do nothing. - state.ip += o - 1; -} -// SCVTCI[] Set Control Value Table Cut-In -// 0x1D -function SCVTCI(state) { - var n = state.stack.pop(); + var updateLane = getCurrentUpdatePriority(); - if (exports.DEBUG) { console.log(state.step, 'SCVTCI[]', n); } + if (updateLane !== NoLane) { + return updateLane; + } // This update originated outside React. Ask the host environment for an + // appropriate priority, based on the type of event. + // + // The opaque type returned by the host config is internally a lane, so we can + // use that directly. + // TODO: Move this type conversion to the event priority module. - state.cvCutIn = n / 0x40; -} -// DUP[] DUPlicate top stack element -// 0x20 -function DUP(state) { - var stack = state.stack; + var eventLane = getCurrentEventPriority(); + return eventLane; + } - if (exports.DEBUG) { console.log(state.step, 'DUP[]'); } + function requestRetryLane(fiber) { + // This is a fork of `requestUpdateLane` designed specifically for Suspense + // "retries" — a special update that attempts to flip a Suspense boundary + // from its placeholder state to its primary/resolved state. + // Special cases + var mode = fiber.mode; - stack.push(stack[stack.length - 1]); -} + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } -// POP[] POP top stack element -// 0x21 -function POP(state) { - if (exports.DEBUG) { console.log(state.step, 'POP[]'); } + return claimNextRetryLane(); + } - state.stack.pop(); -} + function scheduleUpdateOnFiber(fiber, lane, eventTime) { + checkForNestedUpdates(); + var root = markUpdateLaneFromFiberToRoot(fiber, lane); -// CLEAR[] CLEAR the stack -// 0x22 -function CLEAR(state) { - if (exports.DEBUG) { console.log(state.step, 'CLEAR[]'); } + if (root === null) { + return null; + } // Mark that the root has a pending update. - state.stack.length = 0; -} -// SWAP[] SWAP the top two elements on the stack -// 0x23 -function SWAP(state) { - var stack = state.stack; + markRootUpdated(root, lane, eventTime); - var a = stack.pop(); - var b = stack.pop(); + if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) { + // This update was dispatched during the render phase. This is a mistake + // if the update originates from user space (with the exception of local + // hook updates, which are handled differently and don't reach this + // function), but there are some internal React features that use this as + // an implementation detail, like selective hydration. + warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase + } else { + // This is a normal update, scheduled from outside the render phase. For + // example, during an input event. + { + if (isDevToolsPresent) { + addFiberToLanesMap(root, fiber, lane); + } + } - if (exports.DEBUG) { console.log(state.step, 'SWAP[]'); } + warnIfUpdatesNotWrappedWithActDEV(fiber); - stack.push(a); - stack.push(b); -} + if (root === workInProgressRoot) { + // TODO: Consolidate with `isInterleavedUpdate` check + // Received an update to a tree that's in the middle of rendering. Mark + // that there was an interleaved update work on this root. Unless the + // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render + // phase update. In that case, we don't treat render phase updates as if + // they were interleaved, for backwards compat reasons. + if ( (executionContext & RenderContext) === NoContext) { + workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); + } -// DEPTH[] DEPTH of the stack -// 0x24 -function DEPTH(state) { - var stack = state.stack; + if (workInProgressRootExitStatus === RootSuspendedWithDelay) { + // The root already suspended with a delay, which means this render + // definitely won't finish. Since we have a new update, let's mark it as + // suspended now, right before marking the incoming update. This has the + // effect of interrupting the current render and switching to the update. + // TODO: Make sure this doesn't override pings that happen while we've + // already started rendering. + markRootSuspended$1(root, workInProgressRootRenderLanes); + } + } - if (exports.DEBUG) { console.log(state.step, 'DEPTH[]'); } + ensureRootIsScheduled(root, eventTime); - stack.push(stack.length); -} + if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. + !( ReactCurrentActQueue$1.isBatchingLegacy)) { + // Flush the synchronous work now, unless we're already working or inside + // a batch. This is intentionally inside scheduleUpdateOnFiber instead of + // scheduleCallbackForFiber to preserve the ability to schedule a callback + // without immediately flushing it. We only do this for user-initiated + // updates, to preserve historical behavior of legacy mode. + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } -// LOOPCALL[] LOOPCALL function -// 0x2A -function LOOPCALL(state) { - var stack = state.stack; - var fn = stack.pop(); - var c = stack.pop(); + return root; + } + function scheduleInitialHydrationOnRoot(root, lane, eventTime) { + // This is a special fork of scheduleUpdateOnFiber that is only used to + // schedule the initial hydration of a root that has just been created. Most + // of the stuff in scheduleUpdateOnFiber can be skipped. + // + // The main reason for this separate path, though, is to distinguish the + // initial children from subsequent updates. In fully client-rendered roots + // (createRoot instead of hydrateRoot), all top-level renders are modeled as + // updates, but hydration roots are special because the initial render must + // match what was rendered on the server. + var current = root.current; + current.lanes = lane; + markRootUpdated(root, lane, eventTime); + ensureRootIsScheduled(root, eventTime); + } // This is split into a separate function so we can mark a fiber with pending + // work without treating it as a typical update that originates from an event; + // e.g. retrying a Suspense boundary isn't an update, but it does schedule work + // on a fiber. - if (exports.DEBUG) { console.log(state.step, 'LOOPCALL[]', fn, c); } + function markUpdateLaneFromFiberToRoot(sourceFiber, lane) { + // Update the source fiber's lanes + sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); + var alternate = sourceFiber.alternate; - // saves callers program - var cip = state.ip; - var cprog = state.prog; + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, lane); + } - state.prog = state.funcs[fn]; + { + if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) { + warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); + } + } // Walk the parent path to the root and update the child lanes. - // executes the function - for (var i = 0; i < c; i++) { - exec(state); - if (exports.DEBUG) { console.log( - ++state.step, - i + 1 < c ? 'next loopcall' : 'done loopcall', - i - ); } - } + var node = sourceFiber; + var parent = sourceFiber.return; - // restores the callers program - state.ip = cip; - state.prog = cprog; -} + while (parent !== null) { + parent.childLanes = mergeLanes(parent.childLanes, lane); + alternate = parent.alternate; -// CALL[] CALL function -// 0x2B -function CALL(state) { - var fn = state.stack.pop(); + if (alternate !== null) { + alternate.childLanes = mergeLanes(alternate.childLanes, lane); + } else { + { + if ((parent.flags & (Placement | Hydrating)) !== NoFlags) { + warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); + } + } + } - if (exports.DEBUG) { console.log(state.step, 'CALL[]', fn); } + node = parent; + parent = parent.return; + } - // saves callers program - var cip = state.ip; - var cprog = state.prog; + if (node.tag === HostRoot) { + var root = node.stateNode; + return root; + } else { + return null; + } + } - state.prog = state.funcs[fn]; + function isInterleavedUpdate(fiber, lane) { + return (// TODO: Optimize slightly by comparing to root that fiber belongs to. + // Requires some refactoring. Not a big deal though since it's rare for + // concurrent apps to have more than a single root. + workInProgressRoot !== null && (fiber.mode & ConcurrentMode) !== NoMode && ( // If this is a render phase update (i.e. UNSAFE_componentWillReceiveProps), + // then don't treat this as an interleaved update. This pattern is + // accompanied by a warning but we haven't fully deprecated it yet. We can + // remove once the deferRenderPhaseUpdateToNextBatch flag is enabled. + (executionContext & RenderContext) === NoContext) + ); + } // Use this function to schedule a task for a root. There's only one task per + // root; if a task was already scheduled, we'll check to make sure the priority + // of the existing task is the same as the priority of the next level that the + // root has work on. This function is called on every update, and right before + // exiting a task. - // executes the function - exec(state); + function ensureRootIsScheduled(root, currentTime) { + var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as + // expired so we know to work on those next. - // restores the callers program - state.ip = cip; - state.prog = cprog; + markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority. - if (exports.DEBUG) { console.log(++state.step, 'returning from', fn); } -} + var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); -// CINDEX[] Copy the INDEXed element to the top of the stack -// 0x25 -function CINDEX(state) { - var stack = state.stack; - var k = stack.pop(); + if (nextLanes === NoLanes) { + // Special case: There's nothing to work on. + if (existingCallbackNode !== null) { + cancelCallback$1(existingCallbackNode); + } - if (exports.DEBUG) { console.log(state.step, 'CINDEX[]', k); } + root.callbackNode = null; + root.callbackPriority = NoLane; + return; + } // We use the highest priority lane to represent the priority of the callback. - // In case of k == 1, it copies the last element after popping - // thus stack.length - k. - stack.push(stack[stack.length - k]); -} -// MINDEX[] Move the INDEXed element to the top of the stack -// 0x26 -function MINDEX(state) { - var stack = state.stack; - var k = stack.pop(); + var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it. - if (exports.DEBUG) { console.log(state.step, 'MINDEX[]', k); } + var existingCallbackPriority = root.callbackPriority; - stack.push(stack.splice(stack.length - k, 1)[0]); -} + if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a + // Scheduler task, rather than an `act` task, cancel it and re-scheduled + // on the `act` queue. + !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { + { + // If we're going to re-use an existing task, it needs to exist. + // Assume that discrete update microtasks are non-cancellable and null. + // TODO: Temporary until we confirm this warning is not fired. + if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) { + error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.'); + } + } // The priority hasn't changed. We can reuse the existing task. Exit. -// FDEF[] Function DEFinition -// 0x2C -function FDEF(state) { - if (state.env !== 'fpgm') { throw new Error('FDEF not allowed here'); } - var stack = state.stack; - var prog = state.prog; - var ip = state.ip; - var fn = stack.pop(); - var ipBegin = ip; + return; + } - if (exports.DEBUG) { console.log(state.step, 'FDEF[]', fn); } + if (existingCallbackNode != null) { + // Cancel the existing callback. We'll schedule a new one below. + cancelCallback$1(existingCallbackNode); + } // Schedule a new callback. - while (prog[++ip] !== 0x2D){ } - state.ip = ip; - state.funcs[fn] = prog.slice(ipBegin + 1, ip); -} + var newCallbackNode; -// MDAP[a] Move Direct Absolute Point -// 0x2E-0x2F -function MDAP(round, state) { - var pi = state.stack.pop(); - var p = state.z0[pi]; - var fv = state.fv; - var pv = state.pv; + if (newCallbackPriority === SyncLane) { + // Special case: Sync React callbacks are scheduled on a special + // internal queue + if (root.tag === LegacyRoot) { + if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) { + ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; + } - if (exports.DEBUG) { console.log(state.step, 'MDAP[' + round + ']', pi); } + scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); + } else { + scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); + } - var d = pv.distance(p, HPZero); + if (supportsMicrotasks) { + // Flush the queue in a microtask. + if ( ReactCurrentActQueue$1.current !== null) { + // Inside `act`, use our internal `act` queue so that these get flushed + // at the end of the current scope even when using the sync version + // of `act`. + ReactCurrentActQueue$1.current.push(flushSyncCallbacks); + } else { + scheduleMicrotask(function () { + // In Safari, appending an iframe forces microtasks to run. + // https://github.com/facebook/react/issues/22459 + // We don't support running callbacks in the middle of render + // or commit so we need to check against that. + if (executionContext === NoContext) { + // It's only safe to do this conditionally because we always + // check for pending work before we exit the task. + flushSyncCallbacks(); + } + }); + } + } else { + // Flush the queue in an Immediate task. + scheduleCallback$1(ImmediatePriority, flushSyncCallbacks); + } - if (round) { d = state.round(d); } + newCallbackNode = null; + } else { + var schedulerPriorityLevel; - fv.setRelative(p, HPZero, d, pv); - fv.touch(p); + switch (lanesToEventPriority(nextLanes)) { + case DiscreteEventPriority: + schedulerPriorityLevel = ImmediatePriority; + break; - state.rp0 = state.rp1 = pi; -} + case ContinuousEventPriority: + schedulerPriorityLevel = UserBlockingPriority; + break; -// IUP[a] Interpolate Untouched Points through the outline -// 0x30 -function IUP(v, state) { - var z2 = state.z2; - var pLen = z2.length - 2; - var cp; - var pp; - var np; + case DefaultEventPriority: + schedulerPriorityLevel = NormalPriority; + break; - if (exports.DEBUG) { console.log(state.step, 'IUP[' + v.axis + ']'); } + case IdleEventPriority: + schedulerPriorityLevel = IdlePriority; + break; - for (var i = 0; i < pLen; i++) { - cp = z2[i]; // current point + default: + schedulerPriorityLevel = NormalPriority; + break; + } - // if this point has been touched go on - if (v.touched(cp)) { continue; } + newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root)); + } - pp = cp.prevTouched(v); + root.callbackPriority = newCallbackPriority; + root.callbackNode = newCallbackNode; + } // This is the entry point for every concurrent task, i.e. anything that + // goes through Scheduler. - // no point on the contour has been touched? - if (pp === cp) { continue; } - np = cp.nextTouched(v); + function performConcurrentWorkOnRoot(root, didTimeout) { + { + resetNestedUpdateFlag(); + } // Since we know we're in a React event, we can clear the current + // event time. The next update will compute a new event time. - if (pp === np) { - // only one point on the contour has been touched - // so simply moves the point like that - v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true); - } + currentEventTime = NoTimestamp; + currentEventTransitionLane = NoLanes; - v.interpolate(cp, pp, np, v); - } -} + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Should not already be working.'); + } // Flush any pending passive effects before deciding which lanes to work on, + // in case they schedule additional work. -// SHP[] SHift Point using reference point -// 0x32-0x33 -function SHP(a, state) { - var stack = state.stack; - var rpi = a ? state.rp1 : state.rp2; - var rp = (a ? state.z0 : state.z1)[rpi]; - var fv = state.fv; - var pv = state.pv; - var loop = state.loop; - var z2 = state.z2; - while (loop--) - { - var pi = stack.pop(); - var p = z2[pi]; - - var d = pv.distance(rp, rp, false, true); - fv.setRelative(p, p, d, pv); - fv.touch(p); - - if (exports.DEBUG) { - console.log( - state.step, - (state.loop > 1 ? - 'loop ' + (state.loop - loop) + ': ' : - '' - ) + - 'SHP[' + (a ? 'rp1' : 'rp2') + ']', pi - ); - } - } + var originalCallbackNode = root.callbackNode; + var didFlushPassiveEffects = flushPassiveEffects(); - state.loop = 1; -} + if (didFlushPassiveEffects) { + // Something in the passive effect phase may have canceled the current task. + // Check if the task node for this root was changed. + if (root.callbackNode !== originalCallbackNode) { + // The current task was canceled. Exit. We don't need to call + // `ensureRootIsScheduled` because the check above implies either that + // there's a new task, or that there's no remaining work on this root. + return null; + } + } // Determine the next lanes to work on, using the fields stored + // on the root. -// SHC[] SHift Contour using reference point -// 0x36-0x37 -function SHC(a, state) { - var stack = state.stack; - var rpi = a ? state.rp1 : state.rp2; - var rp = (a ? state.z0 : state.z1)[rpi]; - var fv = state.fv; - var pv = state.pv; - var ci = stack.pop(); - var sp = state.z2[state.contours[ci]]; - var p = sp; - if (exports.DEBUG) { console.log(state.step, 'SHC[' + a + ']', ci); } + var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); - var d = pv.distance(rp, rp, false, true); + if (lanes === NoLanes) { + // Defensive coding. This is never expected to happen. + return null; + } // We disable time-slicing in some cases: if the work has been CPU-bound + // for too long ("expired" work, to prevent starvation), or we're in + // sync-updates-by-default mode. + // TODO: We only check `didTimeout` defensively, to account for a Scheduler + // bug we're still investigating. Once the bug in Scheduler is fixed, + // we can remove this, since we track expiration ourselves. - do { - if (p !== rp) { fv.setRelative(p, p, d, pv); } - p = p.nextPointOnContour; - } while (p !== sp); -} -// SHZ[] SHift Zone using reference point -// 0x36-0x37 -function SHZ(a, state) { - var stack = state.stack; - var rpi = a ? state.rp1 : state.rp2; - var rp = (a ? state.z0 : state.z1)[rpi]; - var fv = state.fv; - var pv = state.pv; + var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout); + var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes); - var e = stack.pop(); + if (exitStatus !== RootInProgress) { + if (exitStatus === RootErrored) { + // If something threw an error, try rendering one more time. We'll + // render synchronously to block concurrent data mutations, and we'll + // includes all pending updates are included. If it still fails after + // the second attempt, we'll give up and commit the resulting tree. + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - if (exports.DEBUG) { console.log(state.step, 'SHZ[' + a + ']', e); } + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, errorRetryLanes); + } + } - var z; - switch (e) { - case 0 : z = state.tZone; break; - case 1 : z = state.gZone; break; - default : throw new Error('Invalid zone'); - } + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now$1()); + throw fatalError; + } - var p; - var d = pv.distance(rp, rp, false, true); - var pLen = z.length - 2; - for (var i = 0; i < pLen; i++) - { - p = z[i]; - fv.setRelative(p, p, d, pv); - //if (p !== rp) fv.setRelative(p, p, d, pv); - } -} + if (exitStatus === RootDidNotComplete) { + // The render unwound without completing the tree. This happens in special + // cases where need to exit the current render without producing a + // consistent tree or committing. + // + // This should only happen during a concurrent render, not a discrete or + // synchronous update. We should have already checked for this when we + // unwound the stack. + markRootSuspended$1(root, lanes); + } else { + // The render completed. + // Check if this render may have yielded to a concurrent event, and if so, + // confirm that any newly rendered stores are consistent. + // TODO: It's possible that even a concurrent render may never have yielded + // to the main thread, if it was fast enough, or if it expired. We could + // skip the consistency check in that case, too. + var renderWasConcurrent = !includesBlockingLane(root, lanes); + var finishedWork = root.current.alternate; -// SHPIX[] SHift point by a PIXel amount -// 0x38 -function SHPIX(state) { - var stack = state.stack; - var loop = state.loop; - var fv = state.fv; - var d = stack.pop() / 0x40; - var z2 = state.z2; - - while (loop--) { - var pi = stack.pop(); - var p = z2[pi]; - - if (exports.DEBUG) { - console.log( - state.step, - (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + - 'SHPIX[]', pi, d - ); - } + if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { + // A store was mutated in an interleaved event. Render again, + // synchronously, to block further mutations. + exitStatus = renderRootSync(root, lanes); // We need to check again if something threw - fv.setRelative(p, p, d); - fv.touch(p); - } + if (exitStatus === RootErrored) { + var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - state.loop = 1; -} - -// IP[] Interpolate Point -// 0x39 -function IP(state) { - var stack = state.stack; - var rp1i = state.rp1; - var rp2i = state.rp2; - var loop = state.loop; - var rp1 = state.z0[rp1i]; - var rp2 = state.z1[rp2i]; - var fv = state.fv; - var pv = state.dpv; - var z2 = state.z2; - - while (loop--) { - var pi = stack.pop(); - var p = z2[pi]; - - if (exports.DEBUG) { - console.log( - state.step, - (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + - 'IP[]', pi, rp1i, '<->', rp2i - ); - } + if (_errorRetryLanes !== NoLanes) { + lanes = _errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any + // concurrent events. + } + } - fv.interpolate(p, rp1, rp2, pv); + if (exitStatus === RootFatalErrored) { + var _fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now$1()); + throw _fatalError; + } + } // We now have a consistent tree. The next step is either to commit it, + // or, if something suspended, wait to commit it after a timeout. - fv.touch(p); - } - state.loop = 1; -} - -// MSIRP[a] Move Stack Indirect Relative Point -// 0x3A-0x3B -function MSIRP(a, state) { - var stack = state.stack; - var d = stack.pop() / 64; - var pi = stack.pop(); - var p = state.z1[pi]; - var rp0 = state.z0[state.rp0]; - var fv = state.fv; - var pv = state.pv; - - fv.setRelative(p, rp0, d, pv); - fv.touch(p); - - if (exports.DEBUG) { console.log(state.step, 'MSIRP[' + a + ']', d, pi); } - - state.rp1 = state.rp0; - state.rp2 = pi; - if (a) { state.rp0 = pi; } -} - -// ALIGNRP[] Align to reference point. -// 0x3C -function ALIGNRP(state) { - var stack = state.stack; - var rp0i = state.rp0; - var rp0 = state.z0[rp0i]; - var loop = state.loop; - var fv = state.fv; - var pv = state.pv; - var z1 = state.z1; - - while (loop--) { - var pi = stack.pop(); - var p = z1[pi]; - - if (exports.DEBUG) { - console.log( - state.step, - (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + - 'ALIGNRP[]', pi - ); - } + root.finishedWork = finishedWork; + root.finishedLanes = lanes; + finishConcurrentRender(root, exitStatus, lanes); + } + } - fv.setRelative(p, rp0, 0, pv); - fv.touch(p); - } + ensureRootIsScheduled(root, now$1()); - state.loop = 1; -} + if (root.callbackNode === originalCallbackNode) { + // The task node scheduled for this root is the same one that's + // currently executed. Need to return a continuation. + return performConcurrentWorkOnRoot.bind(null, root); + } -// RTG[] Round To Double Grid -// 0x3D -function RTDG(state) { - if (exports.DEBUG) { console.log(state.step, 'RTDG[]'); } + return null; + } - state.round = roundToDoubleGrid; -} + function recoverFromConcurrentError(root, errorRetryLanes) { + // If an error occurred during hydration, discard server response and fall + // back to client side render. + // Before rendering again, save the errors from the previous attempt. + var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; -// MIAP[a] Move Indirect Absolute Point -// 0x3E-0x3F -function MIAP(round, state) { - var stack = state.stack; - var n = stack.pop(); - var pi = stack.pop(); - var p = state.z0[pi]; - var fv = state.fv; - var pv = state.pv; - var cv = state.cvt[n]; + if (isRootDehydrated(root)) { + // The shell failed to hydrate. Set a flag to force a client rendering + // during the next attempt. To do this, we call prepareFreshStack now + // to create the root work-in-progress fiber. This is a bit weird in terms + // of factoring, because it relies on renderRootSync not calling + // prepareFreshStack again in the call below, which happens because the + // root and lanes haven't changed. + // + // TODO: I think what we should do is set ForceClientRender inside + // throwException, like we do for nested Suspense boundaries. The reason + // it's here instead is so we can switch to the synchronous work loop, too. + // Something to consider for a future refactor. + var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); + rootWorkInProgress.flags |= ForceClientRender; - if (exports.DEBUG) { - console.log( - state.step, - 'MIAP[' + round + ']', - n, '(', cv, ')', pi - ); - } + { + errorHydratingContainer(root.containerInfo); + } + } - var d = pv.distance(p, HPZero); + var exitStatus = renderRootSync(root, errorRetryLanes); - if (round) { - if (Math.abs(d - cv) < state.cvCutIn) { d = cv; } + if (exitStatus !== RootErrored) { + // Successfully finished rendering on retry + // The errors from the failed first attempt have been recovered. Add + // them to the collection of recoverable errors. We'll log them in the + // commit phase. + var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; + workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors + // from the first attempt, to preserve the causal sequence. - d = state.round(d); - } + if (errorsFromSecondAttempt !== null) { + queueRecoverableErrors(errorsFromSecondAttempt); + } + } - fv.setRelative(p, HPZero, d, pv); + return exitStatus; + } - if (state.zp0 === 0) { - p.xo = p.x; - p.yo = p.y; - } + function queueRecoverableErrors(errors) { + if (workInProgressRootRecoverableErrors === null) { + workInProgressRootRecoverableErrors = errors; + } else { + workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); + } + } - fv.touch(p); + function finishConcurrentRender(root, exitStatus, lanes) { + switch (exitStatus) { + case RootInProgress: + case RootFatalErrored: + { + throw new Error('Root did not complete. This is a bug in React.'); + } + // Flow knows about invariant, so it complains if I add a break + // statement, but eslint doesn't know about invariant, so it complains + // if I do. eslint-disable-next-line no-fallthrough - state.rp0 = state.rp1 = pi; -} + case RootErrored: + { + // We should have already attempted to retry this tree. If we reached + // this point, it errored again. Commit it. + commitRoot(root, workInProgressRootRecoverableErrors); + break; + } -// NPUSB[] PUSH N Bytes -// 0x40 -function NPUSHB(state) { - var prog = state.prog; - var ip = state.ip; - var stack = state.stack; + case RootSuspended: + { + markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we + // should immediately commit it or wait a bit. - var n = prog[++ip]; + if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope + !shouldForceFlushFallbacksInDEV()) { + // This render only included retries, no updates. Throttle committing + // retries so that we don't show too many loading states too quickly. + var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now$1(); // Don't bother with a very short suspense time. - if (exports.DEBUG) { console.log(state.step, 'NPUSHB[]', n); } + if (msUntilTimeout > 10) { + var nextLanes = getNextLanes(root, NoLanes); - for (var i = 0; i < n; i++) { stack.push(prog[++ip]); } + if (nextLanes !== NoLanes) { + // There's additional work on this root. + break; + } - state.ip = ip; -} + var suspendedLanes = root.suspendedLanes; -// NPUSHW[] PUSH N Words -// 0x41 -function NPUSHW(state) { - var ip = state.ip; - var prog = state.prog; - var stack = state.stack; - var n = prog[++ip]; + if (!isSubsetOfLanes(suspendedLanes, lanes)) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + // FIXME: What if the suspended lanes are Idle? Should not restart. + requestEventTime(); + markRootPinged(root, suspendedLanes); + break; + } // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback + // immediately, wait for more data to arrive. - if (exports.DEBUG) { console.log(state.step, 'NPUSHW[]', n); } - for (var i = 0; i < n; i++) { - var w = (prog[++ip] << 8) | prog[++ip]; - if (w & 0x8000) { w = -((w ^ 0xffff) + 1); } - stack.push(w); - } + root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors), msUntilTimeout); + break; + } + } // The work expired. Commit immediately. - state.ip = ip; -} -// WS[] Write Store -// 0x42 -function WS(state) { - var stack = state.stack; - var store = state.store; + commitRoot(root, workInProgressRootRecoverableErrors); + break; + } - if (!store) { store = state.store = []; } + case RootSuspendedWithDelay: + { + markRootSuspended$1(root, lanes); - var v = stack.pop(); - var l = stack.pop(); + if (includesOnlyTransitions(lanes)) { + // This is a transition, so we should exit without committing a + // placeholder and without scheduling a timeout. Delay indefinitely + // until we receive more data. + break; + } - if (exports.DEBUG) { console.log(state.step, 'WS', v, l); } + if (!shouldForceFlushFallbacksInDEV()) { + // This is not a transition, but we did trigger an avoided state. + // Schedule a placeholder to display after a short delay, using the Just + // Noticeable Difference. + // TODO: Is the JND optimization worth the added complexity? If this is + // the only reason we track the event time, then probably not. + // Consider removing. + var mostRecentEventTime = getMostRecentEventTime(root, lanes); + var eventTimeMs = mostRecentEventTime; + var timeElapsedMs = now$1() - eventTimeMs; - store[l] = v; -} + var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time. -// RS[] Read Store -// 0x43 -function RS(state) { - var stack = state.stack; - var store = state.store; - var l = stack.pop(); + if (_msUntilTimeout > 10) { + // Instead of committing the fallback immediately, wait for more data + // to arrive. + root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors), _msUntilTimeout); + break; + } + } // Commit the placeholder. - if (exports.DEBUG) { console.log(state.step, 'RS', l); } - var v = (store && store[l]) || 0; + commitRoot(root, workInProgressRootRecoverableErrors); + break; + } - stack.push(v); -} + case RootCompleted: + { + // The work completed. Ready to commit. + commitRoot(root, workInProgressRootRecoverableErrors); + break; + } -// WCVTP[] Write Control Value Table in Pixel units -// 0x44 -function WCVTP(state) { - var stack = state.stack; + default: + { + throw new Error('Unknown root exit status.'); + } + } + } - var v = stack.pop(); - var l = stack.pop(); + function isRenderConsistentWithExternalStores(finishedWork) { + // Search the rendered tree for external store reads, and check whether the + // stores were mutated in a concurrent event. Intentionally using an iterative + // loop instead of recursion so we can exit early. + var node = finishedWork; - if (exports.DEBUG) { console.log(state.step, 'WCVTP', v, l); } + while (true) { + if (node.flags & StoreConsistency) { + var updateQueue = node.updateQueue; - state.cvt[l] = v / 0x40; -} + if (updateQueue !== null) { + var checks = updateQueue.stores; -// RCVT[] Read Control Value Table entry -// 0x45 -function RCVT(state) { - var stack = state.stack; - var cvte = stack.pop(); + if (checks !== null) { + for (var i = 0; i < checks.length; i++) { + var check = checks[i]; + var getSnapshot = check.getSnapshot; + var renderedValue = check.value; - if (exports.DEBUG) { console.log(state.step, 'RCVT', cvte); } + try { + if (!objectIs(getSnapshot(), renderedValue)) { + // Found an inconsistent store. + return false; + } + } catch (error) { + // If `getSnapshot` throws, return `false`. This will schedule + // a re-render, and the error will be rethrown during render. + return false; + } + } + } + } + } - stack.push(state.cvt[cvte] * 0x40); -} + var child = node.child; -// GC[] Get Coordinate projected onto the projection vector -// 0x46-0x47 -function GC(a, state) { - var stack = state.stack; - var pi = stack.pop(); - var p = state.z2[pi]; + if (node.subtreeFlags & StoreConsistency && child !== null) { + child.return = node; + node = child; + continue; + } - if (exports.DEBUG) { console.log(state.step, 'GC[' + a + ']', pi); } + if (node === finishedWork) { + return true; + } - stack.push(state.dpv.distance(p, HPZero, a, false) * 0x40); -} + while (node.sibling === null) { + if (node.return === null || node.return === finishedWork) { + return true; + } -// MD[a] Measure Distance -// 0x49-0x4A -function MD(a, state) { - var stack = state.stack; - var pi2 = stack.pop(); - var pi1 = stack.pop(); - var p2 = state.z1[pi2]; - var p1 = state.z0[pi1]; - var d = state.dpv.distance(p1, p2, a, a); + node = node.return; + } - if (exports.DEBUG) { console.log(state.step, 'MD[' + a + ']', pi2, pi1, '->', d); } + node.sibling.return = node.return; + node = node.sibling; + } // Flow doesn't know this is unreachable, but eslint does + // eslint-disable-next-line no-unreachable - state.stack.push(Math.round(d * 64)); -} -// MPPEM[] Measure Pixels Per EM -// 0x4B -function MPPEM(state) { - if (exports.DEBUG) { console.log(state.step, 'MPPEM[]'); } - state.stack.push(state.ppem); -} + return true; + } -// FLIPON[] set the auto FLIP Boolean to ON -// 0x4D -function FLIPON(state) { - if (exports.DEBUG) { console.log(state.step, 'FLIPON[]'); } - state.autoFlip = true; -} + function markRootSuspended$1(root, suspendedLanes) { + // When suspending, we should always exclude lanes that were pinged or (more + // rarely, since we try to avoid it) updated during the render phase. + // TODO: Lol maybe there's a better way to factor this besides this + // obnoxiously named function :) + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); + markRootSuspended(root, suspendedLanes); + } // This is the entry point for synchronous tasks that don't go + // through Scheduler -// LT[] Less Than -// 0x50 -function LT(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'LT[]', e2, e1); } + function performSyncWorkOnRoot(root) { + { + syncNestedUpdateFlag(); + } - stack.push(e1 < e2 ? 1 : 0); -} + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Should not already be working.'); + } -// LTEQ[] Less Than or EQual -// 0x53 -function LTEQ(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + flushPassiveEffects(); + var lanes = getNextLanes(root, NoLanes); - if (exports.DEBUG) { console.log(state.step, 'LTEQ[]', e2, e1); } + if (!includesSomeLane(lanes, SyncLane)) { + // There's no remaining sync work left. + ensureRootIsScheduled(root, now$1()); + return null; + } - stack.push(e1 <= e2 ? 1 : 0); -} + var exitStatus = renderRootSync(root, lanes); -// GTEQ[] Greater Than -// 0x52 -function GT(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + if (root.tag !== LegacyRoot && exitStatus === RootErrored) { + // If something threw an error, try rendering one more time. We'll render + // synchronously to block concurrent data mutations, and we'll includes + // all pending updates are included. If it still fails after the second + // attempt, we'll give up and commit the resulting tree. + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - if (exports.DEBUG) { console.log(state.step, 'GT[]', e2, e1); } + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, errorRetryLanes); + } + } - stack.push(e1 > e2 ? 1 : 0); -} + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now$1()); + throw fatalError; + } -// GTEQ[] Greater Than or EQual -// 0x53 -function GTEQ(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + if (exitStatus === RootDidNotComplete) { + throw new Error('Root did not complete. This is a bug in React.'); + } // We now have a consistent tree. Because this is a sync render, we + // will commit it even if something suspended. - if (exports.DEBUG) { console.log(state.step, 'GTEQ[]', e2, e1); } - stack.push(e1 >= e2 ? 1 : 0); -} + var finishedWork = root.current.alternate; + root.finishedWork = finishedWork; + root.finishedLanes = lanes; + commitRoot(root, workInProgressRootRecoverableErrors); // Before exiting, make sure there's a callback scheduled for the next + // pending level. -// EQ[] EQual -// 0x54 -function EQ(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + ensureRootIsScheduled(root, now$1()); + return null; + } - if (exports.DEBUG) { console.log(state.step, 'EQ[]', e2, e1); } + function flushRoot(root, lanes) { + if (lanes !== NoLanes) { + markRootEntangled(root, mergeLanes(lanes, SyncLane)); + ensureRootIsScheduled(root, now$1()); - stack.push(e2 === e1 ? 1 : 0); -} + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + resetRenderTimer(); + flushSyncCallbacks(); + } + } + } + function deferredUpdates(fn) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$2.transition; -// NEQ[] Not EQual -// 0x55 -function NEQ(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DefaultEventPriority); + return fn(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + } + } + function batchedUpdates(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; - if (exports.DEBUG) { console.log(state.step, 'NEQ[]', e2, e1); } + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer + // most batchedUpdates-like method. - stack.push(e2 !== e1 ? 1 : 0); -} + if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. + !( ReactCurrentActQueue$1.isBatchingLegacy)) { + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } + } + function discreteUpdates(fn, a, b, c, d) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$2.transition; -// ODD[] ODD -// 0x56 -function ODD(state) { - var stack = state.stack; - var n = stack.pop(); + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + return fn(a, b, c, d); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; - if (exports.DEBUG) { console.log(state.step, 'ODD[]', n); } + if (executionContext === NoContext) { + resetRenderTimer(); + } + } + } // Overload the definition to the two valid signatures. + // Warning, this opts-out of checking the function body. - stack.push(Math.trunc(n) % 2 ? 1 : 0); -} + // eslint-disable-next-line no-redeclare + function flushSync(fn) { + // In legacy mode, we flush pending passive effects at the beginning of the + // next event, not at the end of the previous one. + if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { + flushPassiveEffects(); + } -// EVEN[] EVEN -// 0x57 -function EVEN(state) { - var stack = state.stack; - var n = stack.pop(); + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + var prevTransition = ReactCurrentBatchConfig$2.transition; + var previousPriority = getCurrentUpdatePriority(); - if (exports.DEBUG) { console.log(state.step, 'EVEN[]', n); } + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); - stack.push(Math.trunc(n) % 2 ? 0 : 1); -} + if (fn) { + return fn(); + } else { + return undefined; + } + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. + // Note that this will happen even if batchedUpdates is higher up + // the stack. -// IF[] IF test -// 0x58 -function IF(state) { - var test = state.stack.pop(); + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + flushSyncCallbacks(); + } + } + } + function isAlreadyRendering() { + // Used by the renderer to print a warning if certain APIs are called from + // the wrong context. + return (executionContext & (RenderContext | CommitContext)) !== NoContext; + } + function flushControlled(fn) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + var prevTransition = ReactCurrentBatchConfig$2.transition; + var previousPriority = getCurrentUpdatePriority(); - if (exports.DEBUG) { console.log(state.step, 'IF[]', test); } + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + fn(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + executionContext = prevExecutionContext; - // if test is true it just continues - // if not the ip is skipped until matching ELSE or EIF - if (!test) { - skip(state, true); + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + resetRenderTimer(); + flushSyncCallbacks(); + } + } + } + function pushRenderLanes(fiber, lanes) { + push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); + subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); + } + function popRenderLanes(fiber) { + subtreeRenderLanes = subtreeRenderLanesCursor.current; + pop(subtreeRenderLanesCursor, fiber); + } - if (exports.DEBUG) { console.log(state.step, 'EIF[]'); } - } -} + function prepareFreshStack(root, lanes) { + root.finishedWork = null; + root.finishedLanes = NoLanes; + var timeoutHandle = root.timeoutHandle; -// EIF[] End IF -// 0x59 -function EIF(state) { - // this can be reached normally when - // executing an else branch. - // -> just ignore it + if (timeoutHandle !== noTimeout) { + // The root previous suspended and scheduled a timeout to commit a fallback + // state. Now that we have additional work, cancel the timeout. + root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above - if (exports.DEBUG) { console.log(state.step, 'EIF[]'); } -} + cancelTimeout(timeoutHandle); + } -// AND[] logical AND -// 0x5A -function AND(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + if (workInProgress !== null) { + var interruptedWork = workInProgress.return; - if (exports.DEBUG) { console.log(state.step, 'AND[]', e2, e1); } + while (interruptedWork !== null) { + var current = interruptedWork.alternate; + unwindInterruptedWork(current, interruptedWork); + interruptedWork = interruptedWork.return; + } + } - stack.push(e2 && e1 ? 1 : 0); -} + workInProgressRoot = root; + var rootWorkInProgress = createWorkInProgress(root.current, null); + workInProgress = rootWorkInProgress; + workInProgressRootRenderLanes = subtreeRenderLanes = lanes; + workInProgressRootExitStatus = RootInProgress; + workInProgressRootFatalError = null; + workInProgressRootSkippedLanes = NoLanes; + workInProgressRootInterleavedUpdatedLanes = NoLanes; + workInProgressRootPingedLanes = NoLanes; + workInProgressRootConcurrentErrors = null; + workInProgressRootRecoverableErrors = null; + enqueueInterleavedUpdates(); -// OR[] logical OR -// 0x5B -function OR(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + { + ReactStrictModeWarnings.discardPendingWarnings(); + } - if (exports.DEBUG) { console.log(state.step, 'OR[]', e2, e1); } + return rootWorkInProgress; + } - stack.push(e2 || e1 ? 1 : 0); -} + function handleError(root, thrownValue) { + do { + var erroredWork = workInProgress; -// NOT[] logical NOT -// 0x5C -function NOT(state) { - var stack = state.stack; - var e = stack.pop(); + try { + // Reset module-level state that was set during the render phase. + resetContextDependencies(); + resetHooksAfterThrow(); + resetCurrentFiber(); // TODO: I found and added this missing line while investigating a + // separate issue. Write a regression test using string refs. - if (exports.DEBUG) { console.log(state.step, 'NOT[]', e); } + ReactCurrentOwner$2.current = null; - stack.push(e ? 0 : 1); -} + if (erroredWork === null || erroredWork.return === null) { + // Expected to be working on a non-root fiber. This is a fatal error + // because there's no ancestor that can handle it; the root is + // supposed to capture all errors that weren't caught by an error + // boundary. + workInProgressRootExitStatus = RootFatalErrored; + workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next + // sibling, or the parent if there are no siblings. But since the root + // has no siblings nor a parent, we set it to null. Usually this is + // handled by `completeUnitOfWork` or `unwindWork`, but since we're + // intentionally not calling those, we need set it here. + // TODO: Consider calling `unwindWork` to pop the contexts. -// DELTAP1[] DELTA exception P1 -// DELTAP2[] DELTA exception P2 -// DELTAP3[] DELTA exception P3 -// 0x5D, 0x71, 0x72 -function DELTAP123(b, state) { - var stack = state.stack; - var n = stack.pop(); - var fv = state.fv; - var pv = state.pv; - var ppem = state.ppem; - var base = state.deltaBase + (b - 1) * 16; - var ds = state.deltaShift; - var z0 = state.z0; + workInProgress = null; + return; + } - if (exports.DEBUG) { console.log(state.step, 'DELTAP[' + b + ']', n, stack); } + if (enableProfilerTimer && erroredWork.mode & ProfileMode) { + // Record the time spent rendering before an error was thrown. This + // avoids inaccurate Profiler durations in the case of a + // suspended render. + stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); + } - for (var i = 0; i < n; i++) { - var pi = stack.pop(); - var arg = stack.pop(); - var appem = base + ((arg & 0xF0) >> 4); - if (appem !== ppem) { continue; } + if (enableSchedulingProfiler) { + markComponentRenderStopped(); - var mag = (arg & 0x0F) - 8; - if (mag >= 0) { mag++; } - if (exports.DEBUG) { console.log(state.step, 'DELTAPFIX', pi, 'by', mag * ds); } + if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') { + var wakeable = thrownValue; + markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes); + } else { + markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes); + } + } - var p = z0[pi]; - fv.setRelative(p, p, mag * ds, pv); - } -} + throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); + completeUnitOfWork(erroredWork); + } catch (yetAnotherThrownValue) { + // Something in the return path also threw. + thrownValue = yetAnotherThrownValue; -// SDB[] Set Delta Base in the graphics state -// 0x5E -function SDB(state) { - var stack = state.stack; - var n = stack.pop(); + if (workInProgress === erroredWork && erroredWork !== null) { + // If this boundary has already errored, then we had trouble processing + // the error. Bubble it to the next boundary. + erroredWork = erroredWork.return; + workInProgress = erroredWork; + } else { + erroredWork = workInProgress; + } - if (exports.DEBUG) { console.log(state.step, 'SDB[]', n); } + continue; + } // Return to the normal work loop. - state.deltaBase = n; -} -// SDS[] Set Delta Shift in the graphics state -// 0x5F -function SDS(state) { - var stack = state.stack; - var n = stack.pop(); + return; + } while (true); + } - if (exports.DEBUG) { console.log(state.step, 'SDS[]', n); } + function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher$2.current; + ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; - state.deltaShift = Math.pow(0.5, n); -} + if (prevDispatcher === null) { + // The React isomorphic package does not include a default dispatcher. + // Instead the first renderer will lazily attach one, in order to give + // nicer error messages. + return ContextOnlyDispatcher; + } else { + return prevDispatcher; + } + } -// ADD[] ADD -// 0x60 -function ADD(state) { - var stack = state.stack; - var n2 = stack.pop(); - var n1 = stack.pop(); + function popDispatcher(prevDispatcher) { + ReactCurrentDispatcher$2.current = prevDispatcher; + } - if (exports.DEBUG) { console.log(state.step, 'ADD[]', n2, n1); } + function markCommitTimeOfFallback() { + globalMostRecentFallbackTime = now$1(); + } + function markSkippedUpdateLanes(lane) { + workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes); + } + function renderDidSuspend() { + if (workInProgressRootExitStatus === RootInProgress) { + workInProgressRootExitStatus = RootSuspended; + } + } + function renderDidSuspendDelayIfPossible() { + if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) { + workInProgressRootExitStatus = RootSuspendedWithDelay; + } // Check if there are updates that we skipped tree that might have unblocked + // this render. - stack.push(n1 + n2); -} -// SUB[] SUB -// 0x61 -function SUB(state) { - var stack = state.stack; - var n2 = stack.pop(); - var n1 = stack.pop(); + if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { + // Mark the current render as suspended so that we switch to working on + // the updates that were skipped. Usually we only suspend at the end of + // the render phase. + // TODO: We should probably always mark the root as suspended immediately + // (inside this function), since by suspending at the end of the render + // phase introduces a potential mistake where we suspend lanes that were + // pinged or updated while we were rendering. + markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); + } + } + function renderDidError(error) { + if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { + workInProgressRootExitStatus = RootErrored; + } - if (exports.DEBUG) { console.log(state.step, 'SUB[]', n2, n1); } + if (workInProgressRootConcurrentErrors === null) { + workInProgressRootConcurrentErrors = [error]; + } else { + workInProgressRootConcurrentErrors.push(error); + } + } // Called during render to determine if anything has suspended. + // Returns false if we're not sure. - stack.push(n1 - n2); -} + function renderHasNotSuspendedYet() { + // If something errored or completed, we can't really be sure, + // so those are false. + return workInProgressRootExitStatus === RootInProgress; + } -// DIV[] DIV -// 0x62 -function DIV(state) { - var stack = state.stack; - var n2 = stack.pop(); - var n1 = stack.pop(); + function renderRootSync(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. - if (exports.DEBUG) { console.log(state.step, 'DIV[]', n2, n1); } + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; - stack.push(n1 * 64 / n2); -} + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. + // If we bailout on this work, we'll move them back (like above). + // It's important to move them now in case the work spawns more work at the same priority with different updaters. + // That way we can keep the current update and future updates separate. -// MUL[] MUL -// 0x63 -function MUL(state) { - var stack = state.stack; - var n2 = stack.pop(); - var n1 = stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'MUL[]', n2, n1); } + movePendingFibersToMemoized(root, lanes); + } + } + prepareFreshStack(root, lanes); + } - stack.push(n1 * n2 / 64); -} + { + markRenderStarted(lanes); + } -// ABS[] ABSolute value -// 0x64 -function ABS(state) { - var stack = state.stack; - var n = stack.pop(); + do { + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); - if (exports.DEBUG) { console.log(state.step, 'ABS[]', n); } + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); - stack.push(Math.abs(n)); -} + if (workInProgress !== null) { + // This is a sync render, so we should have finished the whole tree. + throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.'); + } -// NEG[] NEGate -// 0x65 -function NEG(state) { - var stack = state.stack; - var n = stack.pop(); + { + markRenderStopped(); + } // Set this to null to indicate there's no in-progress render. - if (exports.DEBUG) { console.log(state.step, 'NEG[]', n); } - stack.push(-n); -} + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; + return workInProgressRootExitStatus; + } // The work loop is an extremely hot path. Tell Closure not to inline it. -// FLOOR[] FLOOR -// 0x66 -function FLOOR(state) { - var stack = state.stack; - var n = stack.pop(); + /** @noinline */ - if (exports.DEBUG) { console.log(state.step, 'FLOOR[]', n); } - stack.push(Math.floor(n / 0x40) * 0x40); -} + function workLoopSync() { + // Already timed out, so perform work without checking if we need to yield. + while (workInProgress !== null) { + performUnitOfWork(workInProgress); + } + } -// CEILING[] CEILING -// 0x67 -function CEILING(state) { - var stack = state.stack; - var n = stack.pop(); + function renderRootConcurrent(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. - if (exports.DEBUG) { console.log(state.step, 'CEILING[]', n); } + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; - stack.push(Math.ceil(n / 0x40) * 0x40); -} + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. + // If we bailout on this work, we'll move them back (like above). + // It's important to move them now in case the work spawns more work at the same priority with different updaters. + // That way we can keep the current update and future updates separate. -// ROUND[ab] ROUND value -// 0x68-0x6B -function ROUND(dt, state) { - var stack = state.stack; - var n = stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'ROUND[]'); } + movePendingFibersToMemoized(root, lanes); + } + } + resetRenderTimer(); + prepareFreshStack(root, lanes); + } - stack.push(state.round(n / 0x40) * 0x40); -} + { + markRenderStarted(lanes); + } -// WCVTF[] Write Control Value Table in Funits -// 0x70 -function WCVTF(state) { - var stack = state.stack; - var v = stack.pop(); - var l = stack.pop(); + do { + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); - if (exports.DEBUG) { console.log(state.step, 'WCVTF[]', v, l); } + resetContextDependencies(); + popDispatcher(prevDispatcher); + executionContext = prevExecutionContext; - state.cvt[l] = v * state.ppem / state.font.unitsPerEm; -} -// DELTAC1[] DELTA exception C1 -// DELTAC2[] DELTA exception C2 -// DELTAC3[] DELTA exception C3 -// 0x73, 0x74, 0x75 -function DELTAC123(b, state) { - var stack = state.stack; - var n = stack.pop(); - var ppem = state.ppem; - var base = state.deltaBase + (b - 1) * 16; - var ds = state.deltaShift; + if (workInProgress !== null) { + // Still work remaining. + { + markRenderYielded(); + } - if (exports.DEBUG) { console.log(state.step, 'DELTAC[' + b + ']', n, stack); } + return RootInProgress; + } else { + // Completed the tree. + { + markRenderStopped(); + } // Set this to null to indicate there's no in-progress render. - for (var i = 0; i < n; i++) { - var c = stack.pop(); - var arg = stack.pop(); - var appem = base + ((arg & 0xF0) >> 4); - if (appem !== ppem) { continue; } - var mag = (arg & 0x0F) - 8; - if (mag >= 0) { mag++; } + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; // Return the final exit status. - var delta = mag * ds; + return workInProgressRootExitStatus; + } + } + /** @noinline */ - if (exports.DEBUG) { console.log(state.step, 'DELTACFIX', c, 'by', delta); } - state.cvt[c] += delta; - } -} + function workLoopConcurrent() { + // Perform work until Scheduler asks us to yield + while (workInProgress !== null && !shouldYield()) { + performUnitOfWork(workInProgress); + } + } -// SROUND[] Super ROUND -// 0x76 -function SROUND(state) { - var n = state.stack.pop(); + function performUnitOfWork(unitOfWork) { + // The current, flushed, state of this fiber is the alternate. Ideally + // nothing should rely on this, but relying on it here means that we don't + // need an additional field on the work in progress. + var current = unitOfWork.alternate; + setCurrentFiber(unitOfWork); + var next; - if (exports.DEBUG) { console.log(state.step, 'SROUND[]', n); } + if ( (unitOfWork.mode & ProfileMode) !== NoMode) { + startProfilerTimer(unitOfWork); + next = beginWork$1(current, unitOfWork, subtreeRenderLanes); + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); + } else { + next = beginWork$1(current, unitOfWork, subtreeRenderLanes); + } - state.round = roundSuper; + resetCurrentFiber(); + unitOfWork.memoizedProps = unitOfWork.pendingProps; - var period; + if (next === null) { + // If this doesn't spawn new work, complete the current work. + completeUnitOfWork(unitOfWork); + } else { + workInProgress = next; + } - switch (n & 0xC0) { - case 0x00: - period = 0.5; - break; - case 0x40: - period = 1; - break; - case 0x80: - period = 2; - break; - default: - throw new Error('invalid SROUND value'); - } + ReactCurrentOwner$2.current = null; + } - state.srPeriod = period; - - switch (n & 0x30) { - case 0x00: - state.srPhase = 0; - break; - case 0x10: - state.srPhase = 0.25 * period; - break; - case 0x20: - state.srPhase = 0.5 * period; - break; - case 0x30: - state.srPhase = 0.75 * period; - break; - default: throw new Error('invalid SROUND value'); - } + function completeUnitOfWork(unitOfWork) { + // Attempt to complete the current unit of work, then move to the next + // sibling. If there are no more siblings, return to the parent fiber. + var completedWork = unitOfWork; - n &= 0x0F; + do { + // The current, flushed, state of this fiber is the alternate. Ideally + // nothing should rely on this, but relying on it here means that we don't + // need an additional field on the work in progress. + var current = completedWork.alternate; + var returnFiber = completedWork.return; // Check if the work completed or if something threw. - if (n === 0) { state.srThreshold = 0; } - else { state.srThreshold = (n / 8 - 0.5) * period; } -} + if ((completedWork.flags & Incomplete) === NoFlags) { + setCurrentFiber(completedWork); + var next = void 0; -// S45ROUND[] Super ROUND 45 degrees -// 0x77 -function S45ROUND(state) { - var n = state.stack.pop(); + if ( (completedWork.mode & ProfileMode) === NoMode) { + next = completeWork(current, completedWork, subtreeRenderLanes); + } else { + startProfilerTimer(completedWork); + next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error. - if (exports.DEBUG) { console.log(state.step, 'S45ROUND[]', n); } + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); + } - state.round = roundSuper; + resetCurrentFiber(); - var period; + if (next !== null) { + // Completing this fiber spawned new work. Work on that next. + workInProgress = next; + return; + } + } else { + // This fiber did not complete because something threw. Pop values off + // the stack without entering the complete phase. If this is a boundary, + // capture values if possible. + var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes. - switch (n & 0xC0) { - case 0x00: - period = Math.sqrt(2) / 2; - break; - case 0x40: - period = Math.sqrt(2); - break; - case 0x80: - period = 2 * Math.sqrt(2); - break; - default: - throw new Error('invalid S45ROUND value'); - } - state.srPeriod = period; - - switch (n & 0x30) { - case 0x00: - state.srPhase = 0; - break; - case 0x10: - state.srPhase = 0.25 * period; - break; - case 0x20: - state.srPhase = 0.5 * period; - break; - case 0x30: - state.srPhase = 0.75 * period; - break; - default: - throw new Error('invalid S45ROUND value'); - } + if (_next !== null) { + // If completing this work spawned new work, do that next. We'll come + // back here again. + // Since we're restarting, remove anything that is not a host effect + // from the effect tag. + _next.flags &= HostEffectMask; + workInProgress = _next; + return; + } - n &= 0x0F; + if ( (completedWork.mode & ProfileMode) !== NoMode) { + // Record the render duration for the fiber that errored. + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing. - if (n === 0) { state.srThreshold = 0; } - else { state.srThreshold = (n / 8 - 0.5) * period; } -} + var actualDuration = completedWork.actualDuration; + var child = completedWork.child; -// ROFF[] Round Off -// 0x7A -function ROFF(state) { - if (exports.DEBUG) { console.log(state.step, 'ROFF[]'); } + while (child !== null) { + actualDuration += child.actualDuration; + child = child.sibling; + } - state.round = roundOff; -} + completedWork.actualDuration = actualDuration; + } -// RUTG[] Round Up To Grid -// 0x7C -function RUTG(state) { - if (exports.DEBUG) { console.log(state.step, 'RUTG[]'); } + if (returnFiber !== null) { + // Mark the parent fiber as incomplete and clear its subtree flags. + returnFiber.flags |= Incomplete; + returnFiber.subtreeFlags = NoFlags; + returnFiber.deletions = null; + } else { + // We've unwound all the way to the root. + workInProgressRootExitStatus = RootDidNotComplete; + workInProgress = null; + return; + } + } - state.round = roundUpToGrid; -} + var siblingFiber = completedWork.sibling; -// RDTG[] Round Down To Grid -// 0x7D -function RDTG(state) { - if (exports.DEBUG) { console.log(state.step, 'RDTG[]'); } + if (siblingFiber !== null) { + // If there is more work to do in this returnFiber, do that next. + workInProgress = siblingFiber; + return; + } // Otherwise, return to the parent - state.round = roundDownToGrid; -} -// SCANCTRL[] SCAN conversion ConTRoL -// 0x85 -function SCANCTRL(state) { - var n = state.stack.pop(); + completedWork = returnFiber; // Update the next thing we're working on in case something throws. - // ignored by opentype.js + workInProgress = completedWork; + } while (completedWork !== null); // We've reached the root. - if (exports.DEBUG) { console.log(state.step, 'SCANCTRL[]', n); } -} -// SDPVTL[a] Set Dual Projection Vector To Line -// 0x86-0x87 -function SDPVTL(a, state) { - var stack = state.stack; - var p2i = stack.pop(); - var p1i = stack.pop(); - var p2 = state.z2[p2i]; - var p1 = state.z1[p1i]; + if (workInProgressRootExitStatus === RootInProgress) { + workInProgressRootExitStatus = RootCompleted; + } + } - if (exports.DEBUG) { console.log(state.step, 'SDPVTL[' + a + ']', p2i, p1i); } + function commitRoot(root, recoverableErrors) { + // TODO: This no longer makes any sense. We already wrap the mutation and + // layout phases. Should be able to remove. + var previousUpdateLanePriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$2.transition; - var dx; - var dy; + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + commitRootImpl(root, recoverableErrors, previousUpdateLanePriority); + } finally { + ReactCurrentBatchConfig$2.transition = prevTransition; + setCurrentUpdatePriority(previousUpdateLanePriority); + } - if (!a) { - dx = p1.x - p2.x; - dy = p1.y - p2.y; - } else { - dx = p2.y - p1.y; - dy = p1.x - p2.x; - } + return null; + } - state.dpv = getUnitVector(dx, dy); -} + function commitRootImpl(root, recoverableErrors, renderPriorityLevel) { + do { + // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which + // means `flushPassiveEffects` will sometimes result in additional + // passive effects. So we need to keep flushing in a loop until there are + // no more pending effects. + // TODO: Might be better if `flushPassiveEffects` did not automatically + // flush synchronous work at the end, to avoid factoring hazards like this. + flushPassiveEffects(); + } while (rootWithPendingPassiveEffects !== null); -// GETINFO[] GET INFOrmation -// 0x88 -function GETINFO(state) { - var stack = state.stack; - var sel = stack.pop(); - var r = 0; + flushRenderPhaseStrictModeWarningsInDEV(); - if (exports.DEBUG) { console.log(state.step, 'GETINFO[]', sel); } + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Should not already be working.'); + } - // v35 as in no subpixel hinting - if (sel & 0x01) { r = 35; } + var finishedWork = root.finishedWork; + var lanes = root.finishedLanes; - // TODO rotation and stretch currently not supported - // and thus those GETINFO are always 0. + { + markCommitStarted(lanes); + } - // opentype.js is always gray scaling - if (sel & 0x20) { r |= 0x1000; } + if (finishedWork === null) { - stack.push(r); -} + { + markCommitStopped(); + } -// ROLL[] ROLL the top three stack elements -// 0x8A -function ROLL(state) { - var stack = state.stack; - var a = stack.pop(); - var b = stack.pop(); - var c = stack.pop(); + return null; + } else { + { + if (lanes === NoLanes) { + error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.'); + } + } + } - if (exports.DEBUG) { console.log(state.step, 'ROLL[]'); } + root.finishedWork = null; + root.finishedLanes = NoLanes; - stack.push(b); - stack.push(a); - stack.push(c); -} + if (finishedWork === root.current) { + throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.'); + } // commitRoot never returns a continuation; it always finishes synchronously. + // So we can clear these now to allow a new callback to be scheduled. -// MAX[] MAXimum of top two stack elements -// 0x8B -function MAX(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'MAX[]', e2, e1); } + root.callbackNode = null; + root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first + // pending time is whatever is left on the root fiber. - stack.push(Math.max(e1, e2)); -} + var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); + markRootFinished(root, remainingLanes); -// MIN[] MINimum of top two stack elements -// 0x8C -function MIN(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + if (root === workInProgressRoot) { + // We can reset these now that they are finished. + workInProgressRoot = null; + workInProgress = null; + workInProgressRootRenderLanes = NoLanes; + } // If there are pending passive effects, schedule a callback to process them. + // Do this as early as possible, so it is queued before anything else that + // might get scheduled in the commit phase. (See #16714.) + // TODO: Delete all other places that schedule the passive effect callback + // They're redundant. - if (exports.DEBUG) { console.log(state.step, 'MIN[]', e2, e1); } - stack.push(Math.min(e1, e2)); -} + if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback$1(NormalPriority, function () { + flushPassiveEffects(); // This render triggered passive effects: release the root cache pool + // *after* passive effects fire to avoid freeing a cache pool that may + // be referenced by a node in the tree (HostRoot, Cache boundary etc) -// SCANTYPE[] SCANTYPE -// 0x8D -function SCANTYPE(state) { - var n = state.stack.pop(); - // ignored by opentype.js - if (exports.DEBUG) { console.log(state.step, 'SCANTYPE[]', n); } -} + return null; + }); + } + } // Check if there are any effects in the whole tree. + // TODO: This is left over from the effect list implementation, where we had + // to check for the existence of `firstEffect` to satisfy Flow. I think the + // only other reason this optimization exists is because it affects profiling. + // Reconsider whether this is necessary. -// INSTCTRL[] INSTCTRL -// 0x8D -function INSTCTRL(state) { - var s = state.stack.pop(); - var v = state.stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'INSTCTRL[]', s, v); } + var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; + var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; - switch (s) { - case 1 : state.inhibitGridFit = !!v; return; - case 2 : state.ignoreCvt = !!v; return; - default: throw new Error('invalid INSTCTRL[] selector'); - } -} + if (subtreeHasEffects || rootHasEffect) { + var prevTransition = ReactCurrentBatchConfig$2.transition; + ReactCurrentBatchConfig$2.transition = null; + var previousPriority = getCurrentUpdatePriority(); + setCurrentUpdatePriority(DiscreteEventPriority); + var prevExecutionContext = executionContext; + executionContext |= CommitContext; // Reset this to null before calling lifecycles -// PUSHB[abc] PUSH Bytes -// 0xB0-0xB7 -function PUSHB(n, state) { - var stack = state.stack; - var prog = state.prog; - var ip = state.ip; + ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass + // of the effect list for each phase: all mutation effects come before all + // layout effects, and so on. + // The first phase a "before mutation" phase. We use this phase to read the + // state of the host tree right before we mutate it. This is where + // getSnapshotBeforeUpdate is called. - if (exports.DEBUG) { console.log(state.step, 'PUSHB[' + n + ']'); } + commitBeforeMutationEffects(root, finishedWork); - for (var i = 0; i < n; i++) { stack.push(prog[++ip]); } + { + // Mark the current commit time to be shared by all Profilers in this + // batch. This enables them to be grouped later. + recordCommitTime(); + } - state.ip = ip; -} -// PUSHW[abc] PUSH Words -// 0xB8-0xBF -function PUSHW(n, state) { - var ip = state.ip; - var prog = state.prog; - var stack = state.stack; + commitMutationEffects(root, finishedWork, lanes); - if (exports.DEBUG) { console.log(state.ip, 'PUSHW[' + n + ']'); } + resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after + // the mutation phase, so that the previous tree is still current during + // componentWillUnmount, but before the layout phase, so that the finished + // work is current during componentDidMount/Update. - for (var i = 0; i < n; i++) { - var w = (prog[++ip] << 8) | prog[++ip]; - if (w & 0x8000) { w = -((w ^ 0xffff) + 1); } - stack.push(w); - } + root.current = finishedWork; // The next phase is the layout phase, where we call effects that read - state.ip = ip; -} + { + markLayoutEffectsStarted(lanes); + } -// MDRP[abcde] Move Direct Relative Point -// 0xD0-0xEF -// (if indirect is 0) -// -// and -// -// MIRP[abcde] Move Indirect Relative Point -// 0xE0-0xFF -// (if indirect is 1) - -function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) { - var stack = state.stack; - var cvte = indirect && stack.pop(); - var pi = stack.pop(); - var rp0i = state.rp0; - var rp = state.z0[rp0i]; - var p = state.z1[pi]; - - var md = state.minDis; - var fv = state.fv; - var pv = state.dpv; - var od; // original distance - var d; // moving distance - var sign; // sign of distance - var cv; - - d = od = pv.distance(p, rp, true, true); - sign = d >= 0 ? 1 : -1; // Math.sign would be 0 in case of 0 - - // TODO consider autoFlip - d = Math.abs(d); - - if (indirect) { - cv = state.cvt[cvte]; - - if (ro && Math.abs(d - cv) < state.cvCutIn) { d = cv; } - } + commitLayoutEffects(finishedWork, root, lanes); - if (keepD && d < md) { d = md; } + { + markLayoutEffectsStopped(); + } + // opportunity to paint. - if (ro) { d = state.round(d); } - fv.setRelative(p, rp, sign * d, pv); - fv.touch(p); + requestPaint(); + executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value. - if (exports.DEBUG) { - console.log( - state.step, - (indirect ? 'MIRP[' : 'MDRP[') + - (setRp0 ? 'M' : 'm') + - (keepD ? '>' : '_') + - (ro ? 'R' : '_') + - (dt === 0 ? 'Gr' : (dt === 1 ? 'Bl' : (dt === 2 ? 'Wh' : ''))) + - ']', - indirect ? - cvte + '(' + state.cvt[cvte] + ',' + cv + ')' : - '', - pi, - '(d =', od, '->', sign * d, ')' - ); - } + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + } else { + // No effects. + root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were + // no effects. + // TODO: Maybe there's a better way to report this. - state.rp1 = state.rp0; - state.rp2 = pi; - if (setRp0) { state.rp0 = pi; } -} + { + recordCommitTime(); + } + } -/* -* The instruction table. -*/ -instructionTable = [ - /* 0x00 */ SVTCA.bind(undefined, yUnitVector), - /* 0x01 */ SVTCA.bind(undefined, xUnitVector), - /* 0x02 */ SPVTCA.bind(undefined, yUnitVector), - /* 0x03 */ SPVTCA.bind(undefined, xUnitVector), - /* 0x04 */ SFVTCA.bind(undefined, yUnitVector), - /* 0x05 */ SFVTCA.bind(undefined, xUnitVector), - /* 0x06 */ SPVTL.bind(undefined, 0), - /* 0x07 */ SPVTL.bind(undefined, 1), - /* 0x08 */ SFVTL.bind(undefined, 0), - /* 0x09 */ SFVTL.bind(undefined, 1), - /* 0x0A */ SPVFS, - /* 0x0B */ SFVFS, - /* 0x0C */ GPV, - /* 0x0D */ GFV, - /* 0x0E */ SFVTPV, - /* 0x0F */ ISECT, - /* 0x10 */ SRP0, - /* 0x11 */ SRP1, - /* 0x12 */ SRP2, - /* 0x13 */ SZP0, - /* 0x14 */ SZP1, - /* 0x15 */ SZP2, - /* 0x16 */ SZPS, - /* 0x17 */ SLOOP, - /* 0x18 */ RTG, - /* 0x19 */ RTHG, - /* 0x1A */ SMD, - /* 0x1B */ ELSE, - /* 0x1C */ JMPR, - /* 0x1D */ SCVTCI, - /* 0x1E */ undefined, // TODO SSWCI - /* 0x1F */ undefined, // TODO SSW - /* 0x20 */ DUP, - /* 0x21 */ POP, - /* 0x22 */ CLEAR, - /* 0x23 */ SWAP, - /* 0x24 */ DEPTH, - /* 0x25 */ CINDEX, - /* 0x26 */ MINDEX, - /* 0x27 */ undefined, // TODO ALIGNPTS - /* 0x28 */ undefined, - /* 0x29 */ undefined, // TODO UTP - /* 0x2A */ LOOPCALL, - /* 0x2B */ CALL, - /* 0x2C */ FDEF, - /* 0x2D */ undefined, // ENDF (eaten by FDEF) - /* 0x2E */ MDAP.bind(undefined, 0), - /* 0x2F */ MDAP.bind(undefined, 1), - /* 0x30 */ IUP.bind(undefined, yUnitVector), - /* 0x31 */ IUP.bind(undefined, xUnitVector), - /* 0x32 */ SHP.bind(undefined, 0), - /* 0x33 */ SHP.bind(undefined, 1), - /* 0x34 */ SHC.bind(undefined, 0), - /* 0x35 */ SHC.bind(undefined, 1), - /* 0x36 */ SHZ.bind(undefined, 0), - /* 0x37 */ SHZ.bind(undefined, 1), - /* 0x38 */ SHPIX, - /* 0x39 */ IP, - /* 0x3A */ MSIRP.bind(undefined, 0), - /* 0x3B */ MSIRP.bind(undefined, 1), - /* 0x3C */ ALIGNRP, - /* 0x3D */ RTDG, - /* 0x3E */ MIAP.bind(undefined, 0), - /* 0x3F */ MIAP.bind(undefined, 1), - /* 0x40 */ NPUSHB, - /* 0x41 */ NPUSHW, - /* 0x42 */ WS, - /* 0x43 */ RS, - /* 0x44 */ WCVTP, - /* 0x45 */ RCVT, - /* 0x46 */ GC.bind(undefined, 0), - /* 0x47 */ GC.bind(undefined, 1), - /* 0x48 */ undefined, // TODO SCFS - /* 0x49 */ MD.bind(undefined, 0), - /* 0x4A */ MD.bind(undefined, 1), - /* 0x4B */ MPPEM, - /* 0x4C */ undefined, // TODO MPS - /* 0x4D */ FLIPON, - /* 0x4E */ undefined, // TODO FLIPOFF - /* 0x4F */ undefined, // TODO DEBUG - /* 0x50 */ LT, - /* 0x51 */ LTEQ, - /* 0x52 */ GT, - /* 0x53 */ GTEQ, - /* 0x54 */ EQ, - /* 0x55 */ NEQ, - /* 0x56 */ ODD, - /* 0x57 */ EVEN, - /* 0x58 */ IF, - /* 0x59 */ EIF, - /* 0x5A */ AND, - /* 0x5B */ OR, - /* 0x5C */ NOT, - /* 0x5D */ DELTAP123.bind(undefined, 1), - /* 0x5E */ SDB, - /* 0x5F */ SDS, - /* 0x60 */ ADD, - /* 0x61 */ SUB, - /* 0x62 */ DIV, - /* 0x63 */ MUL, - /* 0x64 */ ABS, - /* 0x65 */ NEG, - /* 0x66 */ FLOOR, - /* 0x67 */ CEILING, - /* 0x68 */ ROUND.bind(undefined, 0), - /* 0x69 */ ROUND.bind(undefined, 1), - /* 0x6A */ ROUND.bind(undefined, 2), - /* 0x6B */ ROUND.bind(undefined, 3), - /* 0x6C */ undefined, // TODO NROUND[ab] - /* 0x6D */ undefined, // TODO NROUND[ab] - /* 0x6E */ undefined, // TODO NROUND[ab] - /* 0x6F */ undefined, // TODO NROUND[ab] - /* 0x70 */ WCVTF, - /* 0x71 */ DELTAP123.bind(undefined, 2), - /* 0x72 */ DELTAP123.bind(undefined, 3), - /* 0x73 */ DELTAC123.bind(undefined, 1), - /* 0x74 */ DELTAC123.bind(undefined, 2), - /* 0x75 */ DELTAC123.bind(undefined, 3), - /* 0x76 */ SROUND, - /* 0x77 */ S45ROUND, - /* 0x78 */ undefined, // TODO JROT[] - /* 0x79 */ undefined, // TODO JROF[] - /* 0x7A */ ROFF, - /* 0x7B */ undefined, - /* 0x7C */ RUTG, - /* 0x7D */ RDTG, - /* 0x7E */ POP, // actually SANGW, supposed to do only a pop though - /* 0x7F */ POP, // actually AA, supposed to do only a pop though - /* 0x80 */ undefined, // TODO FLIPPT - /* 0x81 */ undefined, // TODO FLIPRGON - /* 0x82 */ undefined, // TODO FLIPRGOFF - /* 0x83 */ undefined, - /* 0x84 */ undefined, - /* 0x85 */ SCANCTRL, - /* 0x86 */ SDPVTL.bind(undefined, 0), - /* 0x87 */ SDPVTL.bind(undefined, 1), - /* 0x88 */ GETINFO, - /* 0x89 */ undefined, // TODO IDEF - /* 0x8A */ ROLL, - /* 0x8B */ MAX, - /* 0x8C */ MIN, - /* 0x8D */ SCANTYPE, - /* 0x8E */ INSTCTRL, - /* 0x8F */ undefined, - /* 0x90 */ undefined, - /* 0x91 */ undefined, - /* 0x92 */ undefined, - /* 0x93 */ undefined, - /* 0x94 */ undefined, - /* 0x95 */ undefined, - /* 0x96 */ undefined, - /* 0x97 */ undefined, - /* 0x98 */ undefined, - /* 0x99 */ undefined, - /* 0x9A */ undefined, - /* 0x9B */ undefined, - /* 0x9C */ undefined, - /* 0x9D */ undefined, - /* 0x9E */ undefined, - /* 0x9F */ undefined, - /* 0xA0 */ undefined, - /* 0xA1 */ undefined, - /* 0xA2 */ undefined, - /* 0xA3 */ undefined, - /* 0xA4 */ undefined, - /* 0xA5 */ undefined, - /* 0xA6 */ undefined, - /* 0xA7 */ undefined, - /* 0xA8 */ undefined, - /* 0xA9 */ undefined, - /* 0xAA */ undefined, - /* 0xAB */ undefined, - /* 0xAC */ undefined, - /* 0xAD */ undefined, - /* 0xAE */ undefined, - /* 0xAF */ undefined, - /* 0xB0 */ PUSHB.bind(undefined, 1), - /* 0xB1 */ PUSHB.bind(undefined, 2), - /* 0xB2 */ PUSHB.bind(undefined, 3), - /* 0xB3 */ PUSHB.bind(undefined, 4), - /* 0xB4 */ PUSHB.bind(undefined, 5), - /* 0xB5 */ PUSHB.bind(undefined, 6), - /* 0xB6 */ PUSHB.bind(undefined, 7), - /* 0xB7 */ PUSHB.bind(undefined, 8), - /* 0xB8 */ PUSHW.bind(undefined, 1), - /* 0xB9 */ PUSHW.bind(undefined, 2), - /* 0xBA */ PUSHW.bind(undefined, 3), - /* 0xBB */ PUSHW.bind(undefined, 4), - /* 0xBC */ PUSHW.bind(undefined, 5), - /* 0xBD */ PUSHW.bind(undefined, 6), - /* 0xBE */ PUSHW.bind(undefined, 7), - /* 0xBF */ PUSHW.bind(undefined, 8), - /* 0xC0 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0), - /* 0xC1 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1), - /* 0xC2 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2), - /* 0xC3 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3), - /* 0xC4 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0), - /* 0xC5 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1), - /* 0xC6 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2), - /* 0xC7 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3), - /* 0xC8 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0), - /* 0xC9 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1), - /* 0xCA */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2), - /* 0xCB */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3), - /* 0xCC */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0), - /* 0xCD */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1), - /* 0xCE */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2), - /* 0xCF */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3), - /* 0xD0 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0), - /* 0xD1 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1), - /* 0xD2 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2), - /* 0xD3 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3), - /* 0xD4 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0), - /* 0xD5 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1), - /* 0xD6 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2), - /* 0xD7 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3), - /* 0xD8 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0), - /* 0xD9 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1), - /* 0xDA */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2), - /* 0xDB */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3), - /* 0xDC */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0), - /* 0xDD */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1), - /* 0xDE */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2), - /* 0xDF */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3), - /* 0xE0 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0), - /* 0xE1 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1), - /* 0xE2 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2), - /* 0xE3 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3), - /* 0xE4 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0), - /* 0xE5 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1), - /* 0xE6 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2), - /* 0xE7 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3), - /* 0xE8 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0), - /* 0xE9 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1), - /* 0xEA */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2), - /* 0xEB */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3), - /* 0xEC */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0), - /* 0xED */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1), - /* 0xEE */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2), - /* 0xEF */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3), - /* 0xF0 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0), - /* 0xF1 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1), - /* 0xF2 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2), - /* 0xF3 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3), - /* 0xF4 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0), - /* 0xF5 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1), - /* 0xF6 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2), - /* 0xF7 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3), - /* 0xF8 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0), - /* 0xF9 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1), - /* 0xFA */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2), - /* 0xFB */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3), - /* 0xFC */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0), - /* 0xFD */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1), - /* 0xFE */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2), - /* 0xFF */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3) -]; + var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; -/***************************** - Mathematical Considerations -****************************** - -fv ... refers to freedom vector -pv ... refers to projection vector -rp ... refers to reference point -p ... refers to to point being operated on -d ... refers to distance + if (rootDoesHavePassiveEffects) { + // This commit has passive effects. Stash a reference to them. But don't + // schedule a callback until after flushing layout work. + rootDoesHavePassiveEffects = false; + rootWithPendingPassiveEffects = root; + pendingPassiveEffectsLanes = lanes; + } // Read this again, since an effect might have updated it -SETRELATIVE: -============ -case freedom vector == x-axis: ------------------------------- + remainingLanes = root.pendingLanes; // Check if there's remaining work on this root + // TODO: This is part of the `componentDidCatch` implementation. Its purpose + // is to detect whether something might have called setState inside + // `componentDidCatch`. The mechanism is known to be flawed because `setState` + // inside `componentDidCatch` is itself flawed — that's why we recommend + // `getDerivedStateFromError` instead. However, it could be improved by + // checking if remainingLanes includes Sync work, instead of whether there's + // any work remaining at all (which would also include stuff like Suspense + // retries or transitions). It's been like this for a while, though, so fixing + // it probably isn't that urgent. - (pv) - .-' - rpd .-' - .-* - d .-'90°' - .-' ' - .-' ' - *-' ' b - rp ' - ' - ' - p *----------*-------------- (fv) - pm + if (remainingLanes === NoLanes) { + // If there's no remaining work, we can clear the set of already failed + // error boundaries. + legacyErrorBoundariesThatAlreadyFailed = null; + } - rpdx = rpx + d * pv.x - rpdy = rpy + d * pv.y + { + if (!rootDidHavePassiveEffects) { + commitDoubleInvokeEffectsInDEV(root.current, false); + } + } - equation of line b + onCommitRoot(finishedWork.stateNode, renderPriorityLevel); - y - rpdy = pvns * (x- rpdx) + { + if (isDevToolsPresent) { + root.memoizedUpdaters.clear(); + } + } - y = p.y + { + onCommitRoot$1(); + } // Always call this before exiting `commitRoot`, to ensure that any + // additional work on this root is scheduled. - x = rpdx + ( p.y - rpdy ) / pvns + ensureRootIsScheduled(root, now$1()); -case freedom vector == y-axis: ------------------------------- + if (recoverableErrors !== null) { + // There were errors during this render, but recovered from them without + // needing to surface it to the UI. We log them here. + var onRecoverableError = root.onRecoverableError; - * pm - |\ - | \ - | \ - | \ - | \ - | \ - | \ - | \ - | \ - | \ b - | \ - | \ - | \ .-' (pv) - | 90° \.-' - | .-'* rpd - | .-' - * *-' d - p rp + for (var i = 0; i < recoverableErrors.length; i++) { + var recoverableError = recoverableErrors[i]; + onRecoverableError(recoverableError); + } + } - rpdx = rpx + d * pv.x - rpdy = rpy + d * pv.y + if (hasUncaughtError) { + hasUncaughtError = false; + var error$1 = firstUncaughtError; + firstUncaughtError = null; + throw error$1; + } // If the passive effects are the result of a discrete render, flush them + // synchronously at the end of the current task so that the result is + // immediately observable. Otherwise, we assume that they are not + // order-dependent and do not need to be observed by external systems, so we + // can wait until after paint. + // TODO: We can optimize this by not scheduling the callback earlier. Since we + // currently schedule the callback in multiple places, will wait until those + // are consolidated. - equation of line b: - pvns ... normal slope to pv - y - rpdy = pvns * (x - rpdx) + if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) { + flushPassiveEffects(); + } // Read this again, since a passive effect might have updated it - x = p.x - y = rpdy + pvns * (p.x - rpdx) + remainingLanes = root.pendingLanes; + if (includesSomeLane(remainingLanes, SyncLane)) { + { + markNestedUpdateScheduled(); + } // Count the number of times the root synchronously re-renders without + // finishing. If there are too many, it indicates an infinite update loop. -generic case: -------------- + if (root === rootWithNestedUpdates) { + nestedUpdateCount++; + } else { + nestedUpdateCount = 0; + rootWithNestedUpdates = root; + } + } else { + nestedUpdateCount = 0; + } // If layout work was scheduled, flush it now. - .'(fv) - .' - .* pm - .' ! - .' . - .' ! - .' . b - .' ! - * . - p ! - 90° . ... (pv) - ...-*-''' - ...---''' rpd - ...---''' d - *--''' - rp + flushSyncCallbacks(); - rpdx = rpx + d * pv.x - rpdy = rpy + d * pv.y + { + markCommitStopped(); + } - equation of line b: - pvns... normal slope to pv + return null; + } - y - rpdy = pvns * (x - rpdx) + function flushPassiveEffects() { + // Returns whether passive effects were flushed. + // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should + // probably just combine the two functions. I believe they were only separate + // in the first place because we used to wrap it with + // `Scheduler.runWithPriority`, which accepts a function. But now we track the + // priority within React itself, so we can mutate the variable directly. + if (rootWithPendingPassiveEffects !== null) { + var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); + var priority = lowerEventPriority(DefaultEventPriority, renderPriority); + var prevTransition = ReactCurrentBatchConfig$2.transition; + var previousPriority = getCurrentUpdatePriority(); - equation of freedom vector line: - fvs ... slope of freedom vector (=fy/fx) + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(priority); + return flushPassiveEffectsImpl(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; // Once passive effects have run for the tree - giving components a + } + } - y - py = fvs * (x - px) + return false; + } + function enqueuePendingPassiveProfilerEffect(fiber) { + { + pendingPassiveProfilerEffects.push(fiber); + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback$1(NormalPriority, function () { + flushPassiveEffects(); + return null; + }); + } + } + } - on pm both equations are true for same x/y + function flushPassiveEffectsImpl() { + if (rootWithPendingPassiveEffects === null) { + return false; + } - y - rpdy = pvns * (x - rpdx) + var root = rootWithPendingPassiveEffects; + var lanes = pendingPassiveEffectsLanes; + rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects. + // Figure out why and fix it. It's not causing any known issues (probably + // because it's only used for profiling), but it's a refactor hazard. - y - py = fvs * (x - px) + pendingPassiveEffectsLanes = NoLanes; - form to y and set equal: + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Cannot flush passive effects while already rendering.'); + } - pvns * (x - rpdx) + rpdy = fvs * (x - px) + py + { + markPassiveEffectsStarted(lanes); + } - expand: + var prevExecutionContext = executionContext; + executionContext |= CommitContext; + commitPassiveUnmountEffects(root.current); + commitPassiveMountEffects(root, root.current); // TODO: Move to commitPassiveMountEffects - pvns * x - pvns * rpdx + rpdy = fvs * x - fvs * px + py + { + var profilerEffects = pendingPassiveProfilerEffects; + pendingPassiveProfilerEffects = []; - switch: + for (var i = 0; i < profilerEffects.length; i++) { + var _fiber = profilerEffects[i]; + commitPassiveEffectDurations(root, _fiber); + } + } - fvs * x - fvs * px + py = pvns * x - pvns * rpdx + rpdy + { + markPassiveEffectsStopped(); + } - solve for x: + { + commitDoubleInvokeEffectsInDEV(root.current, true); + } - fvs * x - pvns * x = fvs * px - pvns * rpdx - py + rpdy + executionContext = prevExecutionContext; + flushSyncCallbacks(); // If additional passive effects were scheduled, increment a counter. If this + // exceeds the limit, we'll fire a warning. + nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1; // TODO: Move to commitPassiveMountEffects + onPostCommitRoot(root); - fvs * px - pvns * rpdx + rpdy - py - x = ----------------------------------- - fvs - pvns + { + var stateNode = root.current.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } - and: + return true; + } - y = fvs * (x - px) + py + function isAlreadyFailedLegacyErrorBoundary(instance) { + return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); + } + function markLegacyErrorBoundaryAsFailed(instance) { + if (legacyErrorBoundariesThatAlreadyFailed === null) { + legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); + } else { + legacyErrorBoundariesThatAlreadyFailed.add(instance); + } + } + function prepareToThrowUncaughtError(error) { + if (!hasUncaughtError) { + hasUncaughtError = true; + firstUncaughtError = error; + } + } + var onUncaughtError = prepareToThrowUncaughtError; -INTERPOLATE: -============ + function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { + var errorInfo = createCapturedValue(error, sourceFiber); + var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); + enqueueUpdate(rootFiber, update); + var eventTime = requestEventTime(); + var root = markUpdateLaneFromFiberToRoot(rootFiber, SyncLane); -Examples of point interpolation. + if (root !== null) { + markRootUpdated(root, SyncLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + } -The weight of the movement of the reference point gets bigger -the further the other reference point is away, thus the safest -option (that is avoiding 0/0 divisions) is to weight the -original distance of the other point by the sum of both distances. + function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { + if (sourceFiber.tag === HostRoot) { + // Error was thrown at the root. There is no parent, so the root + // itself should capture it. + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1); + return; + } -If the sum of both distances is 0, then move the point by the -arithmetic average of the movement of both reference points. + var fiber = null; + { + fiber = nearestMountedAncestor; + } + while (fiber !== null) { + if (fiber.tag === HostRoot) { + captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1); + return; + } else if (fiber.tag === ClassComponent) { + var ctor = fiber.type; + var instance = fiber.stateNode; + if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) { + var errorInfo = createCapturedValue(error$1, sourceFiber); + var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); + enqueueUpdate(fiber, update); + var eventTime = requestEventTime(); + var root = markUpdateLaneFromFiberToRoot(fiber, SyncLane); - (+6) - rp1o *---->*rp1 - . . (+12) - . . rp2o *---------->* rp2 - . . . . - . . . . - . 10 20 . . - |.........|...................| . - . . . - . . (+8) . - po *------>*p . - . . . - . 12 . 24 . - |...........|.......................| - 36 + if (root !== null) { + markRootUpdated(root, SyncLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + return; + } + } -------- + fiber = fiber.return; + } + { + // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning + // will fire for errors that are thrown by destroy functions inside deleted + // trees. What it should instead do is propagate the error to the parent of + // the deleted tree. In the meantime, do not add this warning to the + // allowlist; this is only for our internal use. + error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1); + } + } + function pingSuspendedRoot(root, wakeable, pingedLanes) { + var pingCache = root.pingCache; + if (pingCache !== null) { + // The wakeable resolved, so we no longer need to memoize, because it will + // never be thrown again. + pingCache.delete(wakeable); + } - (+10) - rp1o *-------->*rp1 - . . (-10) - . . rp2 *<---------* rpo2 - . . . . - . . . . - . 10 . 30 . . - |.........|.............................| - . . - . (+5) . - po *--->* p . - . . . - . . 20 . - |....|..............| - 5 15 + var eventTime = requestEventTime(); + markRootPinged(root, pingedLanes); + warnIfSuspenseResolutionNotWrappedWithActDEV(root); + if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { + // Received a ping at the same priority level at which we're currently + // rendering. We might want to restart this render. This should mirror + // the logic of whether or not a root suspends once it completes. + // TODO: If we're rendering sync either due to Sync, Batched or expired, + // we should probably never restart. + // If we're suspended with delay, or if it's a retry, we'll always suspend + // so we can always restart. + if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now$1() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { + // Restart from the root. + prepareFreshStack(root, NoLanes); + } else { + // Even though we can't restart right now, we might get an + // opportunity later. So we mark this render as having a ping. + workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); + } + } -------- + ensureRootIsScheduled(root, eventTime); + } + function retryTimedOutBoundary(boundaryFiber, retryLane) { + // The boundary fiber (a Suspense component or SuspenseList component) + // previously was rendered in its fallback state. One of the promises that + // suspended it has resolved, which means at least part of the tree was + // likely unblocked. Try rendering again, at a new lanes. + if (retryLane === NoLane) { + // TODO: Assign this to `suspenseState.retryLane`? to avoid + // unnecessary entanglement? + retryLane = requestRetryLane(boundaryFiber); + } // TODO: Special case idle priority? - (+10) - rp1o *-------->*rp1 - . . - . . - rp2o *-------->*rp2 + var eventTime = requestEventTime(); + var root = markUpdateLaneFromFiberToRoot(boundaryFiber, retryLane); - (+10) - po *-------->* p + if (root !== null) { + markRootUpdated(root, retryLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + } -------- + function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState; + var retryLane = NoLane; + if (suspenseState !== null) { + retryLane = suspenseState.retryLane; + } - (+10) - rp1o *-------->*rp1 - . . - . .(+30) - rp2o *---------------------------->*rp2 + retryTimedOutBoundary(boundaryFiber, retryLane); + } + function resolveRetryWakeable(boundaryFiber, wakeable) { + var retryLane = NoLane; // Default + var retryCache; - (+25) - po *----------------------->* p + { + switch (boundaryFiber.tag) { + case SuspenseComponent: + retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + if (suspenseState !== null) { + retryLane = suspenseState.retryLane; + } + break; -vim: set ts=4 sw=4 expandtab: -*****/ + case SuspenseListComponent: + retryCache = boundaryFiber.stateNode; + break; -/** - * Converts a string into a list of tokens. - */ + default: + throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.'); + } + } -/** - * Create a new token - * @param {string} char a single char - */ -function Token(char) { - this.char = char; - this.state = {}; - this.activeState = null; -} + if (retryCache !== null) { + // The wakeable resolved, so we no longer need to memoize, because it will + // never be thrown again. + retryCache.delete(wakeable); + } -/** - * Create a new context range - * @param {number} startIndex range start index - * @param {number} endOffset range end index offset - * @param {string} contextName owner context name - */ -function ContextRange(startIndex, endOffset, contextName) { - this.contextName = contextName; - this.startIndex = startIndex; - this.endOffset = endOffset; -} + retryTimedOutBoundary(boundaryFiber, retryLane); + } // Computes the next Just Noticeable Difference (JND) boundary. + // The theory is that a person can't tell the difference between small differences in time. + // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable + // difference in the experience. However, waiting for longer might mean that we can avoid + // showing an intermediate loading state. The longer we have already waited, the harder it + // is to tell small differences in time. Therefore, the longer we've already waited, + // the longer we can wait additionally. At some point we have to give up though. + // We pick a train model where the next boundary commits at a consistent schedule. + // These particular numbers are vague estimates. We expect to adjust them based on research. -/** - * Check context start and end - * @param {string} contextName a unique context name - * @param {function} checkStart a predicate function the indicates a context's start - * @param {function} checkEnd a predicate function the indicates a context's end - */ -function ContextChecker(contextName, checkStart, checkEnd) { - this.contextName = contextName; - this.openRange = null; - this.ranges = []; - this.checkStart = checkStart; - this.checkEnd = checkEnd; -} + function jnd(timeElapsed) { + return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960; + } -/** - * @typedef ContextParams - * @type Object - * @property {array} context context items - * @property {number} currentIndex current item index - */ + function checkForNestedUpdates() { + if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { + nestedUpdateCount = 0; + rootWithNestedUpdates = null; + throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.'); + } -/** - * Create a context params - * @param {array} context a list of items - * @param {number} currentIndex current item index - */ -function ContextParams(context, currentIndex) { - this.context = context; - this.index = currentIndex; - this.length = context.length; - this.current = context[currentIndex]; - this.backtrack = context.slice(0, currentIndex); - this.lookahead = context.slice(currentIndex + 1); -} + { + if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { + nestedPassiveUpdateCount = 0; -/** - * Create an event instance - * @param {string} eventId event unique id - */ -function Event(eventId) { - this.eventId = eventId; - this.subscribers = []; -} + error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.'); + } + } + } -/** - * Initialize a core events and auto subscribe required event handlers - * @param {any} events an object that enlists core events handlers - */ -function initializeCoreEvents(events) { - var this$1$1 = this; + function flushRenderPhaseStrictModeWarningsInDEV() { + { + ReactStrictModeWarnings.flushLegacyContextWarning(); - var coreEvents = [ - 'start', 'end', 'next', 'newToken', 'contextStart', - 'contextEnd', 'insertToken', 'removeToken', 'removeRange', - 'replaceToken', 'replaceRange', 'composeRUD', 'updateContextsRanges' - ]; + { + ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); + } + } + } - coreEvents.forEach(function (eventId) { - Object.defineProperty(this$1$1.events, eventId, { - value: new Event(eventId) - }); - }); + function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) { + { + // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects + // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level. + // Maybe not a big deal since this is DEV only behavior. + setCurrentFiber(fiber); + invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); - if (!!events) { - coreEvents.forEach(function (eventId) { - var event = events[eventId]; - if (typeof event === 'function') { - this$1$1.events[eventId].subscribe(event); - } - }); - } - var requiresContextUpdate = [ - 'insertToken', 'removeToken', 'removeRange', - 'replaceToken', 'replaceRange', 'composeRUD' - ]; - requiresContextUpdate.forEach(function (eventId) { - this$1$1.events[eventId].subscribe( - this$1$1.updateContextsRanges - ); - }); -} + if (hasPassiveEffects) { + invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); + } -/** - * Converts a string into a list of tokens - * @param {any} events tokenizer core events - */ -function Tokenizer(events) { - this.tokens = []; - this.registeredContexts = {}; - this.contextCheckers = []; - this.events = {}; - this.registeredModifiers = []; + invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); - initializeCoreEvents.call(this, events); -} + if (hasPassiveEffects) { + invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); + } -/** - * Sets the state of a token, usually called by a state modifier. - * @param {string} key state item key - * @param {any} value state item value - */ -Token.prototype.setState = function(key, value) { - this.state[key] = value; - this.activeState = { key: key, value: this.state[key] }; - return this.activeState; -}; + resetCurrentFiber(); + } + } -Token.prototype.getState = function (stateId) { - return this.state[stateId] || null; -}; + function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + var current = firstChild; + var subtreeRoot = null; -/** - * Checks if an index exists in the tokens list. - * @param {number} index token index - */ -Tokenizer.prototype.inboundIndex = function(index) { - return index >= 0 && index < this.tokens.length; -}; + while (current !== null) { + var primarySubtreeFlag = current.subtreeFlags & fiberFlags; -/** - * Compose and apply a list of operations (replace, update, delete) - * @param {array} RUDs replace, update and delete operations - * TODO: Perf. Optimization (lengthBefore === lengthAfter ? dispatch once) - */ -Tokenizer.prototype.composeRUD = function (RUDs) { - var this$1$1 = this; - - var silent = true; - var state = RUDs.map(function (RUD) { return ( - this$1$1[RUD[0]].apply(this$1$1, RUD.slice(1).concat(silent)) - ); }); - var hasFAILObject = function (obj) { return ( - typeof obj === 'object' && - obj.hasOwnProperty('FAIL') - ); }; - if (state.every(hasFAILObject)) { - return { - FAIL: "composeRUD: one or more operations hasn't completed successfully", - report: state.filter(hasFAILObject) - }; - } - this.dispatch('composeRUD', [state.filter(function (op) { return !hasFAILObject(op); })]); -}; + if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) { + current = current.child; + } else { + if ((current.flags & fiberFlags) !== NoFlags) { + invokeEffectFn(current); + } -/** - * Replace a range of tokens with a list of tokens - * @param {number} startIndex range start index - * @param {number} offset range offset - * @param {token} tokens a list of tokens to replace - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.replaceRange = function (startIndex, offset, tokens, silent) { - offset = offset !== null ? offset : this.tokens.length; - var isTokenType = tokens.every(function (token) { return token instanceof Token; }); - if (!isNaN(startIndex) && this.inboundIndex(startIndex) && isTokenType) { - var replaced = this.tokens.splice.apply( - this.tokens, [startIndex, offset].concat(tokens) - ); - if (!silent) { this.dispatch('replaceToken', [startIndex, offset, tokens]); } - return [replaced, tokens]; - } else { - return { FAIL: 'replaceRange: invalid tokens or startIndex.' }; - } -}; + if (current.sibling !== null) { + current = current.sibling; + } else { + current = subtreeRoot = current.return; + } + } + } + } + } -/** - * Replace a token with another token - * @param {number} index token index - * @param {token} token a token to replace - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.replaceToken = function (index, token, silent) { - if (!isNaN(index) && this.inboundIndex(index) && token instanceof Token) { - var replaced = this.tokens.splice(index, 1, token); - if (!silent) { this.dispatch('replaceToken', [index, token]); } - return [replaced[0], token]; - } else { - return { FAIL: 'replaceToken: invalid token or index.' }; - } -}; + var didWarnStateUpdateForNotYetMountedComponent = null; -/** - * Removes a range of tokens - * @param {number} startIndex range start index - * @param {number} offset range offset - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.removeRange = function(startIndex, offset, silent) { - offset = !isNaN(offset) ? offset : this.tokens.length; - var tokens = this.tokens.splice(startIndex, offset); - if (!silent) { this.dispatch('removeRange', [tokens, startIndex, offset]); } - return tokens; -}; + function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { + { + if ((executionContext & RenderContext) !== NoContext) { + // We let the other warning about render phase updates deal with this one. + return; + } -/** - * Remove a token at a certain index - * @param {number} index token index - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.removeToken = function(index, silent) { - if (!isNaN(index) && this.inboundIndex(index)) { - var token = this.tokens.splice(index, 1); - if (!silent) { this.dispatch('removeToken', [token, index]); } - return token; - } else { - return { FAIL: 'removeToken: invalid token index.' }; - } -}; + if (!(fiber.mode & ConcurrentMode)) { + return; + } -/** - * Insert a list of tokens at a certain index - * @param {array} tokens a list of tokens to insert - * @param {number} index insert the list of tokens at index - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.insertToken = function (tokens, index, silent) { - var tokenType = tokens.every( - function (token) { return token instanceof Token; } - ); - if (tokenType) { - this.tokens.splice.apply( - this.tokens, [index, 0].concat(tokens) - ); - if (!silent) { this.dispatch('insertToken', [tokens, index]); } - return tokens; - } else { - return { FAIL: 'insertToken: invalid token(s).' }; - } -}; + var tag = fiber.tag; -/** - * A state modifier that is called on 'newToken' event - * @param {string} modifierId state modifier id - * @param {function} condition a predicate function that returns true or false - * @param {function} modifier a function to update token state - */ -Tokenizer.prototype.registerModifier = function(modifierId, condition, modifier) { - this.events.newToken.subscribe(function(token, contextParams) { - var conditionParams = [token, contextParams]; - var canApplyModifier = ( - condition === null || - condition.apply(this, conditionParams) === true - ); - var modifierParams = [token, contextParams]; - if (canApplyModifier) { - var newStateValue = modifier.apply(this, modifierParams); - token.setState(modifierId, newStateValue); - } - }); - this.registeredModifiers.push(modifierId); -}; + if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) { + // Only warn for user-defined components, not internal ones like Suspense. + return; + } // We show the whole stack but dedupe on the top component's name because + // the problematic code almost always lies inside that component. -/** - * Subscribe a handler to an event - * @param {function} eventHandler an event handler function - */ -Event.prototype.subscribe = function (eventHandler) { - if (typeof eventHandler === 'function') { - return ((this.subscribers.push(eventHandler)) - 1); - } else { - return { FAIL: ("invalid '" + (this.eventId) + "' event handler")}; - } -}; -/** - * Unsubscribe an event handler - * @param {string} subsId subscription id - */ -Event.prototype.unsubscribe = function (subsId) { - this.subscribers.splice(subsId, 1); -}; + var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent'; -/** - * Sets context params current value index - * @param {number} index context params current value index - */ -ContextParams.prototype.setCurrentIndex = function(index) { - this.index = index; - this.current = this.context[index]; - this.backtrack = this.context.slice(0, index); - this.lookahead = this.context.slice(index + 1); -}; + if (didWarnStateUpdateForNotYetMountedComponent !== null) { + if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { + return; + } -/** - * Get an item at an offset from the current value - * example (current value is 3): - * 1 2 [3] 4 5 | items values - * -2 -1 0 1 2 | offset values - * @param {number} offset an offset from current value index - */ -ContextParams.prototype.get = function (offset) { - switch (true) { - case (offset === 0): - return this.current; - case (offset < 0 && Math.abs(offset) <= this.backtrack.length): - return this.backtrack.slice(offset)[0]; - case (offset > 0 && offset <= this.lookahead.length): - return this.lookahead[offset - 1]; - default: - return null; - } -}; + didWarnStateUpdateForNotYetMountedComponent.add(componentName); + } else { + didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]); + } -/** - * Converts a context range into a string value - * @param {contextRange} range a context range - */ -Tokenizer.prototype.rangeToText = function (range) { - if (range instanceof ContextRange) { - return ( - this.getRangeTokens(range) - .map(function (token) { return token.char; }).join('') - ); - } -}; + var previousFiber = current; -/** - * Converts all tokens into a string - */ -Tokenizer.prototype.getText = function () { - return this.tokens.map(function (token) { return token.char; }).join(''); -}; + try { + setCurrentFiber(fiber); -/** - * Get a context by name - * @param {string} contextName context name to get - */ -Tokenizer.prototype.getContext = function (contextName) { - var context = this.registeredContexts[contextName]; - return !!context ? context : null; -}; + error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.'); + } finally { + if (previousFiber) { + setCurrentFiber(fiber); + } else { + resetCurrentFiber(); + } + } + } + } -/** - * Subscribes a new event handler to an event - * @param {string} eventName event name to subscribe to - * @param {function} eventHandler a function to be invoked on event - */ -Tokenizer.prototype.on = function(eventName, eventHandler) { - var event = this.events[eventName]; - if (!!event) { - return event.subscribe(eventHandler); - } else { - return null; - } -}; + var beginWork$1; -/** - * Dispatches an event - * @param {string} eventName event name - * @param {any} args event handler arguments - */ -Tokenizer.prototype.dispatch = function(eventName, args) { - var this$1$1 = this; + { + var dummyFiber = null; - var event = this.events[eventName]; - if (event instanceof Event) { - event.subscribers.forEach(function (subscriber) { - subscriber.apply(this$1$1, args || []); - }); - } -}; + beginWork$1 = function (current, unitOfWork, lanes) { + // If a component throws an error, we replay it again in a synchronously + // dispatched event, so that the debugger will treat it as an uncaught + // error See ReactErrorUtils for more information. + // Before entering the begin phase, copy the work-in-progress onto a dummy + // fiber. If beginWork throws, we'll use this to reset the state. + var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); -/** - * Register a new context checker - * @param {string} contextName a unique context name - * @param {function} contextStartCheck a predicate function that returns true on context start - * @param {function} contextEndCheck a predicate function that returns true on context end - * TODO: call tokenize on registration to update context ranges with the new context. - */ -Tokenizer.prototype.registerContextChecker = function(contextName, contextStartCheck, contextEndCheck) { - if (!!this.getContext(contextName)) { return { - FAIL: - ("context name '" + contextName + "' is already registered.") - }; } - if (typeof contextStartCheck !== 'function') { return { - FAIL: - "missing context start check." - }; } - if (typeof contextEndCheck !== 'function') { return { - FAIL: - "missing context end check." - }; } - var contextCheckers = new ContextChecker( - contextName, contextStartCheck, contextEndCheck - ); - this.registeredContexts[contextName] = contextCheckers; - this.contextCheckers.push(contextCheckers); - return contextCheckers; -}; + try { + return beginWork(current, unitOfWork, lanes); + } catch (originalError) { + if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') { + // Don't replay promises. Treat everything else like an error. + throw originalError; + } // Keep this code in sync with handleError; any changes here must have + // corresponding changes there. -/** - * Gets a context range tokens - * @param {contextRange} range a context range - */ -Tokenizer.prototype.getRangeTokens = function(range) { - var endIndex = range.startIndex + range.endOffset; - return [].concat( - this.tokens - .slice(range.startIndex, endIndex) - ); -}; -/** - * Gets the ranges of a context - * @param {string} contextName context name - */ -Tokenizer.prototype.getContextRanges = function(contextName) { - var context = this.getContext(contextName); - if (!!context) { - return context.ranges; - } else { - return { FAIL: ("context checker '" + contextName + "' is not registered.") }; - } -}; + resetContextDependencies(); + resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the + // same fiber again. + // Unwind the failed stack frame -/** - * Resets context ranges to run context update - */ -Tokenizer.prototype.resetContextsRanges = function () { - var registeredContexts = this.registeredContexts; - for (var contextName in registeredContexts) { - if (registeredContexts.hasOwnProperty(contextName)) { - var context = registeredContexts[contextName]; - context.ranges = []; - } - } -}; + unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber. -/** - * Updates context ranges - */ -Tokenizer.prototype.updateContextsRanges = function () { - this.resetContextsRanges(); - var chars = this.tokens.map(function (token) { return token.char; }); - for (var i = 0; i < chars.length; i++) { - var contextParams = new ContextParams(chars, i); - this.runContextCheck(contextParams); - } - this.dispatch('updateContextsRanges', [this.registeredContexts]); -}; + assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); -/** - * Sets the end offset of an open range - * @param {number} offset range end offset - * @param {string} contextName context name - */ -Tokenizer.prototype.setEndOffset = function (offset, contextName) { - var startIndex = this.getContext(contextName).openRange.startIndex; - var range = new ContextRange(startIndex, offset, contextName); - var ranges = this.getContext(contextName).ranges; - range.rangeId = contextName + "." + (ranges.length); - ranges.push(range); - this.getContext(contextName).openRange = null; - return range; -}; + if ( unitOfWork.mode & ProfileMode) { + // Reset the profiler timer. + startProfilerTimer(unitOfWork); + } // Run beginWork again. -/** - * Runs a context check on the current context - * @param {contextParams} contextParams current context params - */ -Tokenizer.prototype.runContextCheck = function(contextParams) { - var this$1$1 = this; - - var index = contextParams.index; - this.contextCheckers.forEach(function (contextChecker) { - var contextName = contextChecker.contextName; - var openRange = this$1$1.getContext(contextName).openRange; - if (!openRange && contextChecker.checkStart(contextParams)) { - openRange = new ContextRange(index, null, contextName); - this$1$1.getContext(contextName).openRange = openRange; - this$1$1.dispatch('contextStart', [contextName, index]); - } - if (!!openRange && contextChecker.checkEnd(contextParams)) { - var offset = (index - openRange.startIndex) + 1; - var range = this$1$1.setEndOffset(offset, contextName); - this$1$1.dispatch('contextEnd', [contextName, range]); - } - }); -}; -/** - * Converts a text into a list of tokens - * @param {string} text a text to tokenize - */ -Tokenizer.prototype.tokenize = function (text) { - this.tokens = []; - this.resetContextsRanges(); - var chars = Array.from(text); - this.dispatch('start'); - for (var i = 0; i < chars.length; i++) { - var char = chars[i]; - var contextParams = new ContextParams(chars, i); - this.dispatch('next', [contextParams]); - this.runContextCheck(contextParams); - var token = new Token(char); - this.tokens.push(token); - this.dispatch('newToken', [token, contextParams]); - } - this.dispatch('end', [this.tokens]); - return this.tokens; -}; + invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes); -// ╭─┄┄┄────────────────────────┄─────────────────────────────────────────────╮ -// ┊ Character Class Assertions ┊ Checks if a char belongs to a certain class ┊ -// ╰─╾──────────────────────────┄─────────────────────────────────────────────╯ -// jscs:disable maximumLineLength -/** - * Check if a char is Arabic - * @param {string} c a single char - */ -function isArabicChar(c) { - return /[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c); -} + if (hasCaughtError()) { + var replayError = clearCaughtError(); -/** - * Check if a char is an isolated arabic char - * @param {string} c a single char - */ -function isIsolatedArabicChar(char) { - return /[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(char); -} + if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) { + // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. + originalError._suppressLogging = true; + } + } // We always throw the original error in case the second render pass is not idempotent. + // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. -/** - * Check if a char is an Arabic Tashkeel char - * @param {string} c a single char - */ -function isTashkeelArabicChar(char) { - return /[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(char); -} -/** - * Check if a char is Latin - * @param {string} c a single char - */ -function isLatinChar(c) { - return /[A-z]/.test(c); -} + throw originalError; + } + }; + } -/** - * Check if a char is whitespace char - * @param {string} c a single char - */ -function isWhiteSpace(c) { - return /\s/.test(c); -} + var didWarnAboutUpdateInRender = false; + var didWarnAboutUpdateInRenderForAnotherComponent; -/** - * Query a feature by some of it's properties to lookup a glyph substitution. - */ + { + didWarnAboutUpdateInRenderForAnotherComponent = new Set(); + } -/** - * Create feature query instance - * @param {Font} font opentype font instance - */ -function FeatureQuery(font) { - this.font = font; - this.features = {}; -} + function warnAboutRenderPhaseUpdatesInDEV(fiber) { + { + if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed. -/** - * @typedef SubstitutionAction - * @type Object - * @property {number} id substitution type - * @property {string} tag feature tag - * @property {any} substitution substitution value(s) - */ + var dedupeKey = renderingComponentName; -/** - * Create a substitution action instance - * @param {SubstitutionAction} action - */ -function SubstitutionAction(action) { - this.id = action.id; - this.tag = action.tag; - this.substitution = action.substitution; -} + if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { + didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); + var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown'; -/** - * Lookup a coverage table - * @param {number} glyphIndex glyph index - * @param {CoverageTable} coverage coverage table - */ -function lookupCoverage(glyphIndex, coverage) { - if (!glyphIndex) { return -1; } - switch (coverage.format) { - case 1: - return coverage.glyphs.indexOf(glyphIndex); - - case 2: - var ranges = coverage.ranges; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (glyphIndex >= range.start && glyphIndex <= range.end) { - var offset = glyphIndex - range.start; - return range.index + offset; - } - } - break; - default: - return -1; // not found - } - return -1; -} + error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName); + } -/** - * Handle a single substitution - format 1 - * @param {ContextParams} contextParams context params to lookup - */ -function singleSubstitutionFormat1(glyphIndex, subtable) { - var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); - if (substituteIndex === -1) { return null; } - return glyphIndex + subtable.deltaGlyphId; -} + break; + } -/** - * Handle a single substitution - format 2 - * @param {ContextParams} contextParams context params to lookup - */ -function singleSubstitutionFormat2(glyphIndex, subtable) { - var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); - if (substituteIndex === -1) { return null; } - return subtable.substitute[substituteIndex]; -} + case ClassComponent: + { + if (!didWarnAboutUpdateInRender) { + error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.'); -/** - * Lookup a list of coverage tables - * @param {any} coverageList a list of coverage tables - * @param {ContextParams} contextParams context params to lookup - */ -function lookupCoverageList(coverageList, contextParams) { - var lookupList = []; - for (var i = 0; i < coverageList.length; i++) { - var coverage = coverageList[i]; - var glyphIndex = contextParams.current; - glyphIndex = Array.isArray(glyphIndex) ? glyphIndex[0] : glyphIndex; - var lookupIndex = lookupCoverage(glyphIndex, coverage); - if (lookupIndex !== -1) { - lookupList.push(lookupIndex); - } - } - if (lookupList.length !== coverageList.length) { return -1; } - return lookupList; -} + didWarnAboutUpdateInRender = true; + } -/** - * Handle chaining context substitution - format 3 - * @param {ContextParams} contextParams context params to lookup - */ -function chainingSubstitutionFormat3(contextParams, subtable) { - var lookupsCount = ( - subtable.inputCoverage.length + - subtable.lookaheadCoverage.length + - subtable.backtrackCoverage.length - ); - if (contextParams.context.length < lookupsCount) { return []; } - // INPUT LOOKUP // - var inputLookups = lookupCoverageList( - subtable.inputCoverage, contextParams - ); - if (inputLookups === -1) { return []; } - // LOOKAHEAD LOOKUP // - var lookaheadOffset = subtable.inputCoverage.length - 1; - if (contextParams.lookahead.length < subtable.lookaheadCoverage.length) { return []; } - var lookaheadContext = contextParams.lookahead.slice(lookaheadOffset); - while (lookaheadContext.length && isTashkeelArabicChar(lookaheadContext[0].char)) { - lookaheadContext.shift(); - } - var lookaheadParams = new ContextParams(lookaheadContext, 0); - var lookaheadLookups = lookupCoverageList( - subtable.lookaheadCoverage, lookaheadParams - ); - // BACKTRACK LOOKUP // - var backtrackContext = [].concat(contextParams.backtrack); - backtrackContext.reverse(); - while (backtrackContext.length && isTashkeelArabicChar(backtrackContext[0].char)) { - backtrackContext.shift(); - } - if (backtrackContext.length < subtable.backtrackCoverage.length) { return []; } - var backtrackParams = new ContextParams(backtrackContext, 0); - var backtrackLookups = lookupCoverageList( - subtable.backtrackCoverage, backtrackParams - ); - var contextRulesMatch = ( - inputLookups.length === subtable.inputCoverage.length && - lookaheadLookups.length === subtable.lookaheadCoverage.length && - backtrackLookups.length === subtable.backtrackCoverage.length - ); - var substitutions = []; - if (contextRulesMatch) { - for (var i = 0; i < subtable.lookupRecords.length; i++) { - var lookupRecord = subtable.lookupRecords[i]; - var lookupListIndex = lookupRecord.lookupListIndex; - var lookupTable = this.getLookupByIndex(lookupListIndex); - for (var s = 0; s < lookupTable.subtables.length; s++) { - var subtable$1 = lookupTable.subtables[s]; - var lookup = this.getLookupMethod(lookupTable, subtable$1); - var substitutionType = this.getSubstitutionType(lookupTable, subtable$1); - if (substitutionType === '12') { - for (var n = 0; n < inputLookups.length; n++) { - var glyphIndex = contextParams.get(n); - var substitution = lookup(glyphIndex); - if (substitution) { substitutions.push(substitution); } - } - } - } - } - } - return substitutions; -} + break; + } + } + } + } + } -/** - * Handle ligature substitution - format 1 - * @param {ContextParams} contextParams context params to lookup - */ -function ligatureSubstitutionFormat1(contextParams, subtable) { - // COVERAGE LOOKUP // - var glyphIndex = contextParams.current; - var ligSetIndex = lookupCoverage(glyphIndex, subtable.coverage); - if (ligSetIndex === -1) { return null; } - // COMPONENTS LOOKUP - // (!) note, components are ordered in the written direction. - var ligature; - var ligatureSet = subtable.ligatureSets[ligSetIndex]; - for (var s = 0; s < ligatureSet.length; s++) { - ligature = ligatureSet[s]; - for (var l = 0; l < ligature.components.length; l++) { - var lookaheadItem = contextParams.lookahead[l]; - var component = ligature.components[l]; - if (lookaheadItem !== component) { break; } - if (l === ligature.components.length - 1) { return ligature; } - } - } - return null; -} + function restorePendingUpdaters(root, lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + memoizedUpdaters.forEach(function (schedulingFiber) { + addFiberToLanesMap(root, schedulingFiber, lanes); + }); // This function intentionally does not clear memoized updaters. + // Those may still be relevant to the current commit + // and a future one (e.g. Suspense). + } + } + } + var fakeActCallbackNode = {}; -/** - * Handle decomposition substitution - format 1 - * @param {number} glyphIndex glyph index - * @param {any} subtable subtable - */ -function decompositionSubstitutionFormat1(glyphIndex, subtable) { - var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); - if (substituteIndex === -1) { return null; } - return subtable.sequences[substituteIndex]; -} + function scheduleCallback$1(priorityLevel, callback) { + { + // If we're currently inside an `act` scope, bypass Scheduler and push to + // the `act` queue instead. + var actQueue = ReactCurrentActQueue$1.current; -/** - * Get default script features indexes - */ -FeatureQuery.prototype.getDefaultScriptFeaturesIndexes = function () { - var scripts = this.font.tables.gsub.scripts; - for (var s = 0; s < scripts.length; s++) { - var script = scripts[s]; - if (script.tag === 'DFLT') { return ( - script.script.defaultLangSys.featureIndexes - ); } - } - return []; -}; + if (actQueue !== null) { + actQueue.push(callback); + return fakeActCallbackNode; + } else { + return scheduleCallback(priorityLevel, callback); + } + } + } -/** - * Get feature indexes of a specific script - * @param {string} scriptTag script tag - */ -FeatureQuery.prototype.getScriptFeaturesIndexes = function(scriptTag) { - var tables = this.font.tables; - if (!tables.gsub) { return []; } - if (!scriptTag) { return this.getDefaultScriptFeaturesIndexes(); } - var scripts = this.font.tables.gsub.scripts; - for (var i = 0; i < scripts.length; i++) { - var script = scripts[i]; - if (script.tag === scriptTag && script.script.defaultLangSys) { - return script.script.defaultLangSys.featureIndexes; - } else { - var langSysRecords = script.langSysRecords; - if (!!langSysRecords) { - for (var j = 0; j < langSysRecords.length; j++) { - var langSysRecord = langSysRecords[j]; - if (langSysRecord.tag === scriptTag) { - var langSys = langSysRecord.langSys; - return langSys.featureIndexes; - } - } - } - } - } - return this.getDefaultScriptFeaturesIndexes(); -}; + function cancelCallback$1(callbackNode) { + if ( callbackNode === fakeActCallbackNode) { + return; + } // In production, always call Scheduler. This function will be stripped out. -/** - * Map a feature tag to a gsub feature - * @param {any} features gsub features - * @param {string} scriptTag script tag - */ -FeatureQuery.prototype.mapTagsToFeatures = function (features, scriptTag) { - var tags = {}; - for (var i = 0; i < features.length; i++) { - var tag = features[i].tag; - var feature = features[i].feature; - tags[tag] = feature; - } - this.features[scriptTag].tags = tags; -}; -/** - * Get features of a specific script - * @param {string} scriptTag script tag - */ -FeatureQuery.prototype.getScriptFeatures = function (scriptTag) { - var features = this.features[scriptTag]; - if (this.features.hasOwnProperty(scriptTag)) { return features; } - var featuresIndexes = this.getScriptFeaturesIndexes(scriptTag); - if (!featuresIndexes) { return null; } - var gsub = this.font.tables.gsub; - features = featuresIndexes.map(function (index) { return gsub.features[index]; }); - this.features[scriptTag] = features; - this.mapTagsToFeatures(features, scriptTag); - return features; -}; + return cancelCallback(callbackNode); + } -/** - * Get substitution type - * @param {any} lookupTable lookup table - * @param {any} subtable subtable - */ -FeatureQuery.prototype.getSubstitutionType = function(lookupTable, subtable) { - var lookupType = lookupTable.lookupType.toString(); - var substFormat = subtable.substFormat.toString(); - return lookupType + substFormat; -}; + function shouldForceFlushFallbacksInDEV() { + // Never force flush in production. This function should get stripped out. + return ReactCurrentActQueue$1.current !== null; + } -/** - * Get lookup method - * @param {any} lookupTable lookup table - * @param {any} subtable subtable - */ -FeatureQuery.prototype.getLookupMethod = function(lookupTable, subtable) { - var this$1$1 = this; - - var substitutionType = this.getSubstitutionType(lookupTable, subtable); - switch (substitutionType) { - case '11': - return function (glyphIndex) { return singleSubstitutionFormat1.apply( - this$1$1, [glyphIndex, subtable] - ); }; - case '12': - return function (glyphIndex) { return singleSubstitutionFormat2.apply( - this$1$1, [glyphIndex, subtable] - ); }; - case '63': - return function (contextParams) { return chainingSubstitutionFormat3.apply( - this$1$1, [contextParams, subtable] - ); }; - case '41': - return function (contextParams) { return ligatureSubstitutionFormat1.apply( - this$1$1, [contextParams, subtable] - ); }; - case '21': - return function (glyphIndex) { return decompositionSubstitutionFormat1.apply( - this$1$1, [glyphIndex, subtable] - ); }; - default: - throw new Error( - "lookupType: " + (lookupTable.lookupType) + " - " + - "substFormat: " + (subtable.substFormat) + " " + - "is not yet supported" - ); - } -}; + function warnIfUpdatesNotWrappedWithActDEV(fiber) { + { + if (fiber.mode & ConcurrentMode) { + if (!isConcurrentActEnvironment()) { + // Not in an act environment. No need to warn. + return; + } + } else { + // Legacy mode has additional cases where we suppress a warning. + if (!isLegacyActEnvironment()) { + // Not in an act environment. No need to warn. + return; + } -/** - * [ LOOKUP TYPES ] - * ------------------------------- - * Single 1; - * Multiple 2; - * Alternate 3; - * Ligature 4; - * Context 5; - * ChainingContext 6; - * ExtensionSubstitution 7; - * ReverseChainingContext 8; - * ------------------------------- - * - */ + if (executionContext !== NoContext) { + // Legacy mode doesn't warn if the update is batched, i.e. + // batchedUpdates or flushSync. + return; + } -/** - * @typedef FQuery - * @type Object - * @param {string} tag feature tag - * @param {string} script feature script - * @param {ContextParams} contextParams context params - */ + if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { + // For backwards compatibility with pre-hooks code, legacy mode only + // warns for updates that originate from a hook. + return; + } + } -/** - * Lookup a feature using a query parameters - * @param {FQuery} query feature query - */ -FeatureQuery.prototype.lookupFeature = function (query) { - var contextParams = query.contextParams; - var currentIndex = contextParams.index; - var feature = this.getFeature({ - tag: query.tag, script: query.script - }); - if (!feature) { return new Error( - "font '" + (this.font.names.fullName.en) + "' " + - "doesn't support feature '" + (query.tag) + "' " + - "for script '" + (query.script) + "'." - ); } - var lookups = this.getFeatureLookups(feature); - var substitutions = [].concat(contextParams.context); - for (var l = 0; l < lookups.length; l++) { - var lookupTable = lookups[l]; - var subtables = this.getLookupSubtables(lookupTable); - for (var s = 0; s < subtables.length; s++) { - var subtable = subtables[s]; - var substType = this.getSubstitutionType(lookupTable, subtable); - var lookup = this.getLookupMethod(lookupTable, subtable); - var substitution = (void 0); - switch (substType) { - case '11': - substitution = lookup(contextParams.current); - if (substitution) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 11, tag: query.tag, substitution: substitution - })); - } - break; - case '12': - substitution = lookup(contextParams.current); - if (substitution) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 12, tag: query.tag, substitution: substitution - })); - } - break; - case '63': - substitution = lookup(contextParams); - if (Array.isArray(substitution) && substitution.length) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 63, tag: query.tag, substitution: substitution - })); - } - break; - case '41': - substitution = lookup(contextParams); - if (substitution) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 41, tag: query.tag, substitution: substitution - })); - } - break; - case '21': - substitution = lookup(contextParams.current); - if (substitution) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 21, tag: query.tag, substitution: substitution - })); - } - break; - } - contextParams = new ContextParams(substitutions, currentIndex); - if (Array.isArray(substitution) && !substitution.length) { continue; } - substitution = null; - } - } - return substitutions.length ? substitutions : null; -}; + if (ReactCurrentActQueue$1.current === null) { + var previousFiber = current; -/** - * Checks if a font supports a specific features - * @param {FQuery} query feature query object - */ -FeatureQuery.prototype.supports = function (query) { - if (!query.script) { return false; } - this.getScriptFeatures(query.script); - var supportedScript = this.features.hasOwnProperty(query.script); - if (!query.tag) { return supportedScript; } - var supportedFeature = ( - this.features[query.script].some(function (feature) { return feature.tag === query.tag; }) - ); - return supportedScript && supportedFeature; -}; + try { + setCurrentFiber(fiber); -/** - * Get lookup table subtables - * @param {any} lookupTable lookup table - */ -FeatureQuery.prototype.getLookupSubtables = function (lookupTable) { - return lookupTable.subtables || null; -}; + error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber)); + } finally { + if (previousFiber) { + setCurrentFiber(fiber); + } else { + resetCurrentFiber(); + } + } + } + } + } -/** - * Get lookup table by index - * @param {number} index lookup table index - */ -FeatureQuery.prototype.getLookupByIndex = function (index) { - var lookups = this.font.tables.gsub.lookups; - return lookups[index] || null; -}; + function warnIfSuspenseResolutionNotWrappedWithActDEV(root) { + { + if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) { + error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + ' /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act'); + } + } + } -/** - * Get lookup tables for a feature - * @param {string} feature - */ -FeatureQuery.prototype.getFeatureLookups = function (feature) { - // TODO: memoize - return feature.lookupListIndexes.map(this.getLookupByIndex.bind(this)); -}; + /* eslint-disable react-internal/prod-error-codes */ + var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. -/** - * Query a feature by it's properties - * @param {any} query an object that describes the properties of a query - */ -FeatureQuery.prototype.getFeature = function getFeature(query) { - if (!this.font) { return { FAIL: "No font was found"}; } - if (!this.features.hasOwnProperty(query.script)) { - this.getScriptFeatures(query.script); - } - var scriptFeatures = this.features[query.script]; - if (!scriptFeatures) { return ( - { FAIL: ("No feature for script " + (query.script))} - ); } - if (!scriptFeatures.tags[query.tag]) { return null; } - return this.features[query.script].tags[query.tag]; -}; + var failedBoundaries = null; + var setRefreshHandler = function (handler) { + { + resolveFamily = handler; + } + }; + function resolveFunctionForHotReloading(type) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return type; + } -/** - * Arabic word context checkers - */ + var family = resolveFamily(type); -function arabicWordStartCheck(contextParams) { - var char = contextParams.current; - var prevChar = contextParams.get(-1); - return ( - // ? arabic first char - (prevChar === null && isArabicChar(char)) || - // ? arabic char preceded with a non arabic char - (!isArabicChar(prevChar) && isArabicChar(char)) - ); -} + if (family === undefined) { + return type; + } // Use the latest known implementation. -function arabicWordEndCheck(contextParams) { - var nextChar = contextParams.get(1); - return ( - // ? last arabic char - (nextChar === null) || - // ? next char is not arabic - (!isArabicChar(nextChar)) - ); -} -var arabicWordCheck = { - startCheck: arabicWordStartCheck, - endCheck: arabicWordEndCheck -}; + return family.current; + } + } + function resolveClassForHotReloading(type) { + // No implementation differences. + return resolveFunctionForHotReloading(type); + } + function resolveForwardRefForHotReloading(type) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return type; + } -/** - * Arabic sentence context checkers - */ + var family = resolveFamily(type); -function arabicSentenceStartCheck(contextParams) { - var char = contextParams.current; - var prevChar = contextParams.get(-1); - return ( - // ? an arabic char preceded with a non arabic char - (isArabicChar(char) || isTashkeelArabicChar(char)) && - !isArabicChar(prevChar) - ); -} + if (family === undefined) { + // Check if we're dealing with a real forwardRef. Don't want to crash early. + if (type !== null && type !== undefined && typeof type.render === 'function') { + // ForwardRef is special because its resolved .type is an object, + // but it's possible that we only have its inner render function in the map. + // If that inner render function is different, we'll build a new forwardRef type. + var currentRender = resolveFunctionForHotReloading(type.render); -function arabicSentenceEndCheck(contextParams) { - var nextChar = contextParams.get(1); - switch (true) { - case nextChar === null: - return true; - case (!isArabicChar(nextChar) && !isTashkeelArabicChar(nextChar)): - var nextIsWhitespace = isWhiteSpace(nextChar); - if (!nextIsWhitespace) { return true; } - if (nextIsWhitespace) { - var arabicCharAhead = false; - arabicCharAhead = ( - contextParams.lookahead.some( - function (c) { return isArabicChar(c) || isTashkeelArabicChar(c); } - ) - ); - if (!arabicCharAhead) { return true; } - } - break; - default: - return false; - } -} + if (type.render !== currentRender) { + var syntheticType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render: currentRender + }; -var arabicSentenceCheck = { - startCheck: arabicSentenceStartCheck, - endCheck: arabicSentenceEndCheck -}; + if (type.displayName !== undefined) { + syntheticType.displayName = type.displayName; + } -/** - * Apply single substitution format 1 - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function singleSubstitutionFormat1$1(action, tokens, index) { - tokens[index].setState(action.tag, action.substitution); -} + return syntheticType; + } + } -/** - * Apply single substitution format 2 - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function singleSubstitutionFormat2$1(action, tokens, index) { - tokens[index].setState(action.tag, action.substitution); -} + return type; + } // Use the latest known implementation. -/** - * Apply chaining context substitution format 3 - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function chainingSubstitutionFormat3$1(action, tokens, index) { - action.substitution.forEach(function (subst, offset) { - var token = tokens[index + offset]; - token.setState(action.tag, subst); - }); -} -/** - * Apply ligature substitution format 1 - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function ligatureSubstitutionFormat1$1(action, tokens, index) { - var token = tokens[index]; - token.setState(action.tag, action.substitution.ligGlyph); - var compsCount = action.substitution.components.length; - for (var i = 0; i < compsCount; i++) { - token = tokens[index + i + 1]; - token.setState('deleted', true); - } -} + return family.current; + } + } + function isCompatibleFamilyForHotReloading(fiber, element) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return false; + } -/** - * Supported substitutions - */ -var SUBSTITUTIONS = { - 11: singleSubstitutionFormat1$1, - 12: singleSubstitutionFormat2$1, - 63: chainingSubstitutionFormat3$1, - 41: ligatureSubstitutionFormat1$1 -}; + var prevType = fiber.elementType; + var nextType = element.type; // If we got here, we know types aren't === equal. -/** - * Apply substitutions to a list of tokens - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function applySubstitution(action, tokens, index) { - if (action instanceof SubstitutionAction && SUBSTITUTIONS[action.id]) { - SUBSTITUTIONS[action.id](action, tokens, index); - } -} + var needsCompareFamilies = false; + var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null; -/** - * Apply Arabic presentation forms to a range of tokens - */ + switch (fiber.tag) { + case ClassComponent: + { + if (typeof nextType === 'function') { + needsCompareFamilies = true; + } -/** - * Check if a char can be connected to it's preceding char - * @param {ContextParams} charContextParams context params of a char - */ -function willConnectPrev(charContextParams) { - var backtrack = [].concat(charContextParams.backtrack); - for (var i = backtrack.length - 1; i >= 0; i--) { - var prevChar = backtrack[i]; - var isolated = isIsolatedArabicChar(prevChar); - var tashkeel = isTashkeelArabicChar(prevChar); - if (!isolated && !tashkeel) { return true; } - if (isolated) { return false; } - } - return false; -} + break; + } -/** - * Check if a char can be connected to it's proceeding char - * @param {ContextParams} charContextParams context params of a char - */ -function willConnectNext(charContextParams) { - if (isIsolatedArabicChar(charContextParams.current)) { return false; } - for (var i = 0; i < charContextParams.lookahead.length; i++) { - var nextChar = charContextParams.lookahead[i]; - var tashkeel = isTashkeelArabicChar(nextChar); - if (!tashkeel) { return true; } - } - return false; -} + case FunctionComponent: + { + if (typeof nextType === 'function') { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + // We don't know the inner type yet. + // We're going to assume that the lazy inner type is stable, + // and so it is sufficient to avoid reconciling it away. + // We're not going to unwrap or actually use the new lazy type. + needsCompareFamilies = true; + } -/** - * Apply arabic presentation forms to a list of tokens - * @param {ContextRange} range a range of tokens - */ -function arabicPresentationForms(range) { - var this$1$1 = this; - - var script = 'arab'; - var tags = this.featuresTags[script]; - var tokens = this.tokenizer.getRangeTokens(range); - if (tokens.length === 1) { return; } - var contextParams = new ContextParams( - tokens.map(function (token) { return token.getState('glyphIndex'); } - ), 0); - var charContextParams = new ContextParams( - tokens.map(function (token) { return token.char; } - ), 0); - tokens.forEach(function (token, index) { - if (isTashkeelArabicChar(token.char)) { return; } - contextParams.setCurrentIndex(index); - charContextParams.setCurrentIndex(index); - var CONNECT = 0; // 2 bits 00 (10: can connect next) (01: can connect prev) - if (willConnectPrev(charContextParams)) { CONNECT |= 1; } - if (willConnectNext(charContextParams)) { CONNECT |= 2; } - var tag; - switch (CONNECT) { - case 1: (tag = 'fina'); break; - case 2: (tag = 'init'); break; - case 3: (tag = 'medi'); break; - } - if (tags.indexOf(tag) === -1) { return; } - var substitutions = this$1$1.query.lookupFeature({ - tag: tag, script: script, contextParams: contextParams - }); - if (substitutions instanceof Error) { return console.info(substitutions.message); } - substitutions.forEach(function (action, index) { - if (action instanceof SubstitutionAction) { - applySubstitution(action, tokens, index); - contextParams.context[index] = action.substitution; - } - }); - }); -} + break; + } -/** - * Apply Arabic required ligatures feature to a range of tokens - */ + case ForwardRef: + { + if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } -/** - * Update context params - * @param {any} tokens a list of tokens - * @param {number} index current item index - */ -function getContextParams(tokens, index) { - var context = tokens.map(function (token) { return token.activeState.value; }); - return new ContextParams(context, index || 0); -} + break; + } -/** - * Apply Arabic required ligatures to a context range - * @param {ContextRange} range a range of tokens - */ -function arabicRequiredLigatures(range) { - var this$1$1 = this; - - var script = 'arab'; - var tokens = this.tokenizer.getRangeTokens(range); - var contextParams = getContextParams(tokens); - contextParams.context.forEach(function (glyphIndex, index) { - contextParams.setCurrentIndex(index); - var substitutions = this$1$1.query.lookupFeature({ - tag: 'rlig', script: script, contextParams: contextParams - }); - if (substitutions.length) { - substitutions.forEach( - function (action) { return applySubstitution(action, tokens, index); } - ); - contextParams = getContextParams(tokens); - } - }); -} + case MemoComponent: + case SimpleMemoComponent: + { + if ($$typeofNextType === REACT_MEMO_TYPE) { + // TODO: if it was but can no longer be simple, + // we shouldn't set this. + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } -/** - * Latin word context checkers - */ + break; + } -function latinWordStartCheck(contextParams) { - var char = contextParams.current; - var prevChar = contextParams.get(-1); - return ( - // ? latin first char - (prevChar === null && isLatinChar(char)) || - // ? latin char preceded with a non latin char - (!isLatinChar(prevChar) && isLatinChar(char)) - ); -} + default: + return false; + } // Check if both types have a family and it's the same one. -function latinWordEndCheck(contextParams) { - var nextChar = contextParams.get(1); - return ( - // ? last latin char - (nextChar === null) || - // ? next char is not latin - (!isLatinChar(nextChar)) - ); -} -var latinWordCheck = { - startCheck: latinWordStartCheck, - endCheck: latinWordEndCheck -}; + if (needsCompareFamilies) { + // Note: memo() and forwardRef() we'll compare outer rather than inner type. + // This means both of them need to be registered to preserve state. + // If we unwrapped and compared the inner types for wrappers instead, + // then we would risk falsely saying two separate memo(Foo) + // calls are equivalent because they wrap the same Foo function. + var prevFamily = resolveFamily(prevType); -/** - * Apply Latin ligature feature to a range of tokens - */ + if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { + return true; + } + } -/** - * Update context params - * @param {any} tokens a list of tokens - * @param {number} index current item index - */ -function getContextParams$1(tokens, index) { - var context = tokens.map(function (token) { return token.activeState.value; }); - return new ContextParams(context, index || 0); -} + return false; + } + } + function markFailedErrorBoundaryForHotReloading(fiber) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return; + } -/** - * Apply Arabic required ligatures to a context range - * @param {ContextRange} range a range of tokens - */ -function latinLigature(range) { - var this$1$1 = this; - - var script = 'latn'; - var tokens = this.tokenizer.getRangeTokens(range); - var contextParams = getContextParams$1(tokens); - contextParams.context.forEach(function (glyphIndex, index) { - contextParams.setCurrentIndex(index); - var substitutions = this$1$1.query.lookupFeature({ - tag: 'liga', script: script, contextParams: contextParams - }); - if (substitutions.length) { - substitutions.forEach( - function (action) { return applySubstitution(action, tokens, index); } - ); - contextParams = getContextParams$1(tokens); - } - }); -} + if (typeof WeakSet !== 'function') { + return; + } -/** - * Infer bidirectional properties for a given text and apply - * the corresponding layout rules. - */ + if (failedBoundaries === null) { + failedBoundaries = new WeakSet(); + } -/** - * Create Bidi. features - * @param {string} baseDir text base direction. value either 'ltr' or 'rtl' - */ -function Bidi(baseDir) { - this.baseDir = baseDir || 'ltr'; - this.tokenizer = new Tokenizer(); - this.featuresTags = {}; -} + failedBoundaries.add(fiber); + } + } + var scheduleRefresh = function (root, update) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return; + } -/** - * Sets Bidi text - * @param {string} text a text input - */ -Bidi.prototype.setText = function (text) { - this.text = text; -}; + var staleFamilies = update.staleFamilies, + updatedFamilies = update.updatedFamilies; + flushPassiveEffects(); + flushSync(function () { + scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies); + }); + } + }; + var scheduleRoot = function (root, element) { + { + if (root.context !== emptyContextObject) { + // Super edge case: root has a legacy _renderSubtree context + // but we don't know the parentComponent so we can't pass it. + // Just ignore. We'll delete this with _renderSubtree code path later. + return; + } -/** - * Store essential context checks: - * arabic word check for applying gsub features - * arabic sentence check for adjusting arabic layout - */ -Bidi.prototype.contextChecks = ({ - latinWordCheck: latinWordCheck, - arabicWordCheck: arabicWordCheck, - arabicSentenceCheck: arabicSentenceCheck -}); + flushPassiveEffects(); + flushSync(function () { + updateContainer(element, root, null, null); + }); + } + }; -/** - * Register arabic word check - */ -function registerContextChecker(checkId) { - var check = this.contextChecks[(checkId + "Check")]; - return this.tokenizer.registerContextChecker( - checkId, check.startCheck, check.endCheck - ); -} + function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { + { + var alternate = fiber.alternate, + child = fiber.child, + sibling = fiber.sibling, + tag = fiber.tag, + type = fiber.type; + var candidateType = null; -/** - * Perform pre tokenization procedure then - * tokenize text input - */ -function tokenizeText() { - registerContextChecker.call(this, 'latinWord'); - registerContextChecker.call(this, 'arabicWord'); - registerContextChecker.call(this, 'arabicSentence'); - return this.tokenizer.tokenize(this.text); -} + switch (tag) { + case FunctionComponent: + case SimpleMemoComponent: + case ClassComponent: + candidateType = type; + break; -/** - * Reverse arabic sentence layout - * TODO: check base dir before applying adjustments - priority low - */ -function reverseArabicSentences() { - var this$1$1 = this; - - var ranges = this.tokenizer.getContextRanges('arabicSentence'); - ranges.forEach(function (range) { - var rangeTokens = this$1$1.tokenizer.getRangeTokens(range); - this$1$1.tokenizer.replaceRange( - range.startIndex, - range.endOffset, - rangeTokens.reverse() - ); - }); -} + case ForwardRef: + candidateType = type.render; + break; + } -/** - * Register supported features tags - * @param {script} script script tag - * @param {Array} tags features tags list - */ -Bidi.prototype.registerFeatures = function (script, tags) { - var this$1$1 = this; + if (resolveFamily === null) { + throw new Error('Expected resolveFamily to be set during hot reload.'); + } - var supportedTags = tags.filter( - function (tag) { return this$1$1.query.supports({script: script, tag: tag}); } - ); - if (!this.featuresTags.hasOwnProperty(script)) { - this.featuresTags[script] = supportedTags; - } else { - this.featuresTags[script] = - this.featuresTags[script].concat(supportedTags); - } -}; + var needsRender = false; + var needsRemount = false; -/** - * Apply GSUB features - * @param {Array} tagsList a list of features tags - * @param {string} script a script tag - * @param {Font} font opentype font instance - */ -Bidi.prototype.applyFeatures = function (font, features) { - if (!font) { throw new Error( - 'No valid font was provided to apply features' - ); } - if (!this.query) { this.query = new FeatureQuery(font); } - for (var f = 0; f < features.length; f++) { - var feature = features[f]; - if (!this.query.supports({script: feature.script})) { continue; } - this.registerFeatures(feature.script, feature.tags); - } -}; + if (candidateType !== null) { + var family = resolveFamily(candidateType); -/** - * Register a state modifier - * @param {string} modifierId state modifier id - * @param {function} condition a predicate function that returns true or false - * @param {function} modifier a modifier function to set token state - */ -Bidi.prototype.registerModifier = function (modifierId, condition, modifier) { - this.tokenizer.registerModifier(modifierId, condition, modifier); -}; + if (family !== undefined) { + if (staleFamilies.has(family)) { + needsRemount = true; + } else if (updatedFamilies.has(family)) { + if (tag === ClassComponent) { + needsRemount = true; + } else { + needsRender = true; + } + } + } + } -/** - * Check if 'glyphIndex' is registered - */ -function checkGlyphIndexStatus() { - if (this.tokenizer.registeredModifiers.indexOf('glyphIndex') === -1) { - throw new Error( - 'glyphIndex modifier is required to apply ' + - 'arabic presentation features.' - ); - } -} + if (failedBoundaries !== null) { + if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) { + needsRemount = true; + } + } -/** - * Apply arabic presentation forms features - */ -function applyArabicPresentationForms() { - var this$1$1 = this; - - var script = 'arab'; - if (!this.featuresTags.hasOwnProperty(script)) { return; } - checkGlyphIndexStatus.call(this); - var ranges = this.tokenizer.getContextRanges('arabicWord'); - ranges.forEach(function (range) { - arabicPresentationForms.call(this$1$1, range); - }); -} + if (needsRemount) { + fiber._debugNeedsRemount = true; + } -/** - * Apply required arabic ligatures - */ -function applyArabicRequireLigatures() { - var this$1$1 = this; - - var script = 'arab'; - if (!this.featuresTags.hasOwnProperty(script)) { return; } - var tags = this.featuresTags[script]; - if (tags.indexOf('rlig') === -1) { return; } - checkGlyphIndexStatus.call(this); - var ranges = this.tokenizer.getContextRanges('arabicWord'); - ranges.forEach(function (range) { - arabicRequiredLigatures.call(this$1$1, range); - }); -} + if (needsRemount || needsRender) { + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } -/** - * Apply required arabic ligatures - */ -function applyLatinLigatures() { - var this$1$1 = this; - - var script = 'latn'; - if (!this.featuresTags.hasOwnProperty(script)) { return; } - var tags = this.featuresTags[script]; - if (tags.indexOf('liga') === -1) { return; } - checkGlyphIndexStatus.call(this); - var ranges = this.tokenizer.getContextRanges('latinWord'); - ranges.forEach(function (range) { - latinLigature.call(this$1$1, range); - }); -} + if (child !== null && !needsRemount) { + scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); + } -/** - * Check if a context is registered - * @param {string} contextId context id - */ -Bidi.prototype.checkContextReady = function (contextId) { - return !!this.tokenizer.getContext(contextId); -}; + if (sibling !== null) { + scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); + } + } + } -/** - * Apply features to registered contexts - */ -Bidi.prototype.applyFeaturesToContexts = function () { - if (this.checkContextReady('arabicWord')) { - applyArabicPresentationForms.call(this); - applyArabicRequireLigatures.call(this); - } - if (this.checkContextReady('latinWord')) { - applyLatinLigatures.call(this); - } - if (this.checkContextReady('arabicSentence')) { - reverseArabicSentences.call(this); - } -}; + var findHostInstancesForRefresh = function (root, families) { + { + var hostInstances = new Set(); + var types = new Set(families.map(function (family) { + return family.current; + })); + findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances); + return hostInstances; + } + }; -/** - * process text input - * @param {string} text an input text - */ -Bidi.prototype.processText = function(text) { - if (!this.text || this.text !== text) { - this.setText(text); - tokenizeText.call(this); - this.applyFeaturesToContexts(); - } -}; + function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { + { + var child = fiber.child, + sibling = fiber.sibling, + tag = fiber.tag, + type = fiber.type; + var candidateType = null; -/** - * Process a string of text to identify and adjust - * bidirectional text entities. - * @param {string} text input text - */ -Bidi.prototype.getBidiText = function (text) { - this.processText(text); - return this.tokenizer.getText(); -}; + switch (tag) { + case FunctionComponent: + case SimpleMemoComponent: + case ClassComponent: + candidateType = type; + break; -/** - * Get the current state index of each token - * @param {text} text an input text - */ -Bidi.prototype.getTextGlyphs = function (text) { - this.processText(text); - var indexes = []; - for (var i = 0; i < this.tokenizer.tokens.length; i++) { - var token = this.tokenizer.tokens[i]; - if (token.state.deleted) { continue; } - var index = token.activeState.value; - indexes.push(Array.isArray(index) ? index[0] : index); - } - return indexes; -}; + case ForwardRef: + candidateType = type.render; + break; + } -// The Font object + var didMatch = false; -/** - * @typedef FontOptions - * @type Object - * @property {Boolean} empty - whether to create a new empty font - * @property {string} familyName - * @property {string} styleName - * @property {string=} fullName - * @property {string=} postScriptName - * @property {string=} designer - * @property {string=} designerURL - * @property {string=} manufacturer - * @property {string=} manufacturerURL - * @property {string=} license - * @property {string=} licenseURL - * @property {string=} version - * @property {string=} description - * @property {string=} copyright - * @property {string=} trademark - * @property {Number} unitsPerEm - * @property {Number} ascender - * @property {Number} descender - * @property {Number} createdTimestamp - * @property {string=} weightClass - * @property {string=} widthClass - * @property {string=} fsSelection - */ + if (candidateType !== null) { + if (types.has(candidateType)) { + didMatch = true; + } + } -/** - * A Font represents a loaded OpenType font file. - * It contains a set of glyphs and methods to draw text on a drawing context, - * or to get a path representing the text. - * @exports opentype.Font - * @class - * @param {FontOptions} - * @constructor - */ -function Font(options) { - options = options || {}; - options.tables = options.tables || {}; - - if (!options.empty) { - // Check that we've provided the minimum set of names. - checkArgument(options.familyName, 'When creating a new Font object, familyName is required.'); - checkArgument(options.styleName, 'When creating a new Font object, styleName is required.'); - checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.'); - checkArgument(options.ascender, 'When creating a new Font object, ascender is required.'); - checkArgument(options.descender <= 0, 'When creating a new Font object, negative descender value is required.'); - - // OS X will complain if the names are empty, so we put a single space everywhere by default. - this.names = { - fontFamily: {en: options.familyName || ' '}, - fontSubfamily: {en: options.styleName || ' '}, - fullName: {en: options.fullName || options.familyName + ' ' + options.styleName}, - // postScriptName may not contain any whitespace - postScriptName: {en: options.postScriptName || (options.familyName + options.styleName).replace(/\s/g, '')}, - designer: {en: options.designer || ' '}, - designerURL: {en: options.designerURL || ' '}, - manufacturer: {en: options.manufacturer || ' '}, - manufacturerURL: {en: options.manufacturerURL || ' '}, - license: {en: options.license || ' '}, - licenseURL: {en: options.licenseURL || ' '}, - version: {en: options.version || 'Version 0.1'}, - description: {en: options.description || ' '}, - copyright: {en: options.copyright || ' '}, - trademark: {en: options.trademark || ' '} - }; - this.unitsPerEm = options.unitsPerEm || 1000; - this.ascender = options.ascender; - this.descender = options.descender; - this.createdTimestamp = options.createdTimestamp; - this.tables = Object.assign(options.tables, { - os2: Object.assign({ - usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, - usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, - fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR, - }, options.tables.os2) - }); - } + if (didMatch) { + // We have a match. This only drills down to the closest host components. + // There's no need to search deeper because for the purpose of giving + // visual feedback, "flashing" outermost parent rectangles is sufficient. + findHostInstancesForFiberShallowly(fiber, hostInstances); + } else { + // If there's no match, maybe there will be one further down in the child tree. + if (child !== null) { + findHostInstancesForMatchingFibersRecursively(child, types, hostInstances); + } + } - this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported. - this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); - this.encoding = new DefaultEncoding(this); - this.position = new Position(this); - this.substitution = new Substitution(this); - this.tables = this.tables || {}; - - // needed for low memory mode only. - this._push = null; - this._hmtxTableData = {}; - - Object.defineProperty(this, 'hinting', { - get: function() { - if (this._hinting) { return this._hinting; } - if (this.outlinesFormat === 'truetype') { - return (this._hinting = new Hinting(this)); - } - } - }); -} + if (sibling !== null) { + findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); + } + } + } -/** - * Check if the font has a glyph for the given character. - * @param {string} - * @return {Boolean} - */ -Font.prototype.hasChar = function(c) { - return this.encoding.charToGlyphIndex(c) !== null; -}; + function findHostInstancesForFiberShallowly(fiber, hostInstances) { + { + var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances); -/** - * Convert the given character to a single glyph index. - * Note that this function assumes that there is a one-to-one mapping between - * the given character and a glyph; for complex scripts this might not be the case. - * @param {string} - * @return {Number} - */ -Font.prototype.charToGlyphIndex = function(s) { - return this.encoding.charToGlyphIndex(s); -}; + if (foundHostInstances) { + return; + } // If we didn't find any host children, fallback to closest host parent. -/** - * Convert the given character to a single Glyph object. - * Note that this function assumes that there is a one-to-one mapping between - * the given character and a glyph; for complex scripts this might not be the case. - * @param {string} - * @return {opentype.Glyph} - */ -Font.prototype.charToGlyph = function(c) { - var glyphIndex = this.charToGlyphIndex(c); - var glyph = this.glyphs.get(glyphIndex); - if (!glyph) { - // .notdef - glyph = this.glyphs.get(0); - } - return glyph; -}; + var node = fiber; -/** - * Update features - * @param {any} options features options - */ -Font.prototype.updateFeatures = function (options) { - // TODO: update all features options not only 'latn'. - return this.defaultRenderOptions.features.map(function (feature) { - if (feature.script === 'latn') { - return { - script: 'latn', - tags: feature.tags.filter(function (tag) { return options[tag]; }) - }; - } else { - return feature; - } - }); -}; + while (true) { + switch (node.tag) { + case HostComponent: + hostInstances.add(node.stateNode); + return; -/** - * Convert the given text to a list of Glyph objects. - * Note that there is no strict one-to-one mapping between characters and - * glyphs, so the list of returned glyphs can be larger or smaller than the - * length of the given string. - * @param {string} - * @param {GlyphRenderOptions} [options] - * @return {opentype.Glyph[]} - */ -Font.prototype.stringToGlyphs = function(s, options) { - var this$1$1 = this; + case HostPortal: + hostInstances.add(node.stateNode.containerInfo); + return; + case HostRoot: + hostInstances.add(node.stateNode.containerInfo); + return; + } - var bidi = new Bidi(); + if (node.return === null) { + throw new Error('Expected to reach root first.'); + } - // Create and register 'glyphIndex' state modifier - var charToGlyphIndexMod = function (token) { return this$1$1.charToGlyphIndex(token.char); }; - bidi.registerModifier('glyphIndex', null, charToGlyphIndexMod); + node = node.return; + } + } + } - // roll-back to default features - var features = options ? - this.updateFeatures(options.features) : - this.defaultRenderOptions.features; + function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { + { + var node = fiber; + var foundHostInstances = false; - bidi.applyFeatures(this, features); + while (true) { + if (node.tag === HostComponent) { + // We got a match. + foundHostInstances = true; + hostInstances.add(node.stateNode); // There may still be more, so keep searching. + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } - var indexes = bidi.getTextGlyphs(s); + if (node === fiber) { + return foundHostInstances; + } - var length = indexes.length; + while (node.sibling === null) { + if (node.return === null || node.return === fiber) { + return foundHostInstances; + } - // convert glyph indexes to glyph objects - var glyphs = new Array(length); - var notdef = this.glyphs.get(0); - for (var i = 0; i < length; i += 1) { - glyphs[i] = this.glyphs.get(indexes[i]) || notdef; - } - return glyphs; -}; + node = node.return; + } -/** - * @param {string} - * @return {Number} - */ -Font.prototype.nameToGlyphIndex = function(name) { - return this.glyphNames.nameToGlyphIndex(name); -}; + node.sibling.return = node.return; + node = node.sibling; + } + } -/** - * @param {string} - * @return {opentype.Glyph} - */ -Font.prototype.nameToGlyph = function(name) { - var glyphIndex = this.nameToGlyphIndex(name); - var glyph = this.glyphs.get(glyphIndex); - if (!glyph) { - // .notdef - glyph = this.glyphs.get(0); - } + return false; + } - return glyph; -}; + var hasBadMapPolyfill; -/** - * @param {Number} - * @return {String} - */ -Font.prototype.glyphIndexToName = function(gid) { - if (!this.glyphNames.glyphIndexToName) { - return ''; - } + { + hasBadMapPolyfill = false; - return this.glyphNames.glyphIndexToName(gid); -}; + try { + var nonExtensibleObject = Object.preventExtensions({}); + /* eslint-disable no-new */ -/** - * Retrieve the value of the kerning pair between the left glyph (or its index) - * and the right glyph (or its index). If no kerning pair is found, return 0. - * The kerning value gets added to the advance width when calculating the spacing - * between glyphs. - * For GPOS kerning, this method uses the default script and language, which covers - * most use cases. To have greater control, use font.position.getKerningValue . - * @param {opentype.Glyph} leftGlyph - * @param {opentype.Glyph} rightGlyph - * @return {Number} - */ -Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { - leftGlyph = leftGlyph.index || leftGlyph; - rightGlyph = rightGlyph.index || rightGlyph; - var gposKerning = this.position.defaultKerningTables; - if (gposKerning) { - return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph); - } - // "kern" table - return this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0; -}; + new Map([[nonExtensibleObject, null]]); + new Set([nonExtensibleObject]); + /* eslint-enable no-new */ + } catch (e) { + // TODO: Consider warning about bad polyfills + hasBadMapPolyfill = true; + } + } -/** - * @typedef GlyphRenderOptions - * @type Object - * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used. - * See https://www.microsoft.com/typography/otspec/scripttags.htm - * @property {string} [language='dflt'] - language system used to determine which features to apply. - * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx - * @property {boolean} [kerning=true] - whether to include kerning values - * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system. - * See https://www.microsoft.com/typography/otspec/featuretags.htm - */ -Font.prototype.defaultRenderOptions = { - kerning: true, - features: [ - /** - * these 4 features are required to render Arabic text properly - * and shouldn't be turned off when rendering arabic text. - */ - { script: 'arab', tags: ['init', 'medi', 'fina', 'rlig'] }, - { script: 'latn', tags: ['liga', 'rlig'] } - ] -}; + function FiberNode(tag, pendingProps, key, mode) { + // Instance + this.tag = tag; + this.key = key; + this.elementType = null; + this.type = null; + this.stateNode = null; // Fiber -/** - * Helper function that invokes the given callback for each glyph in the given text. - * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text - * @param {string} text - The text to apply. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - * @param {Function} callback - */ -Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) { - x = x !== undefined ? x : 0; - y = y !== undefined ? y : 0; - fontSize = fontSize !== undefined ? fontSize : 72; - options = Object.assign({}, this.defaultRenderOptions, options); - var fontScale = 1 / this.unitsPerEm * fontSize; - var glyphs = this.stringToGlyphs(text, options); - var kerningLookups; - if (options.kerning) { - var script = options.script || this.position.getDefaultScriptName(); - kerningLookups = this.position.getKerningTables(script, options.language); - } - for (var i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs[i]; - callback.call(this, glyph, x, y, fontSize, options); - if (glyph.advanceWidth) { - x += glyph.advanceWidth * fontScale; - } + this.return = null; + this.child = null; + this.sibling = null; + this.index = 0; + this.ref = null; + this.pendingProps = pendingProps; + this.memoizedProps = null; + this.updateQueue = null; + this.memoizedState = null; + this.dependencies = null; + this.mode = mode; // Effects - if (options.kerning && i < glyphs.length - 1) { - // We should apply position adjustment lookups in a more generic way. - // Here we only use the xAdvance value. - var kerningValue = kerningLookups ? - this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) : - this.getKerningValue(glyph, glyphs[i + 1]); - x += kerningValue * fontScale; - } + this.flags = NoFlags; + this.subtreeFlags = NoFlags; + this.deletions = null; + this.lanes = NoLanes; + this.childLanes = NoLanes; + this.alternate = null; - if (options.letterSpacing) { - x += options.letterSpacing * fontSize; - } else if (options.tracking) { - x += (options.tracking / 1000) * fontSize; - } - } - return x; -}; + { + // Note: The following is done to avoid a v8 performance cliff. + // + // Initializing the fields below to smis and later updating them with + // double values will cause Fibers to end up having separate shapes. + // This behavior/bug has something to do with Object.preventExtension(). + // Fortunately this only impacts DEV builds. + // Unfortunately it makes React unusably slow for some applications. + // To work around this, initialize the fields below with doubles. + // + // Learn more about this here: + // https://github.com/facebook/react/issues/14365 + // https://bugs.chromium.org/p/v8/issues/detail?id=8538 + this.actualDuration = Number.NaN; + this.actualStartTime = Number.NaN; + this.selfBaseDuration = Number.NaN; + this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. + // This won't trigger the performance cliff mentioned above, + // and it simplifies other profiler code (including DevTools). -/** - * Create a Path object that represents the given text. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - * @return {opentype.Path} - */ -Font.prototype.getPath = function(text, x, y, fontSize, options) { - var fullPath = new Path(); - this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { - var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); - fullPath.extend(glyphPath); - }); - return fullPath; -}; + this.actualDuration = 0; + this.actualStartTime = -1; + this.selfBaseDuration = 0; + this.treeBaseDuration = 0; + } -/** - * Create an array of Path objects that represent the glyphs of a given text. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - * @return {opentype.Path[]} - */ -Font.prototype.getPaths = function(text, x, y, fontSize, options) { - var glyphPaths = []; - this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { - var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); - glyphPaths.push(glyphPath); - }); + { + // This isn't directly used but is handy for debugging internals: + this._debugSource = null; + this._debugOwner = null; + this._debugNeedsRemount = false; + this._debugHookTypes = null; - return glyphPaths; -}; + if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { + Object.preventExtensions(this); + } + } + } // This is a constructor function, rather than a POJO constructor, still + // please ensure we do the following: + // 1) Nobody should add any instance methods on this. Instance methods can be + // more difficult to predict when they get optimized and they are almost + // never inlined properly in static compilers. + // 2) Nobody should rely on `instanceof Fiber` for type testing. We should + // always know when it is a fiber. + // 3) We might want to experiment with using numeric keys since they are easier + // to optimize in a non-JIT environment. + // 4) We can easily go from a constructor to a createFiber object literal if that + // is faster. + // 5) It should be easy to port this to a C struct and keep a C implementation + // compatible. -/** - * Returns the advance width of a text. - * - * This is something different than Path.getBoundingBox() as for example a - * suffixed whitespace increases the advanceWidth but not the bounding box - * or an overhanging letter like a calligraphic 'f' might have a quite larger - * bounding box than its advance width. - * - * This corresponds to canvas2dContext.measureText(text).width - * - * @param {string} text - The text to create. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - * @return advance width - */ -Font.prototype.getAdvanceWidth = function(text, fontSize, options) { - return this.forEachGlyph(text, 0, 0, fontSize, options, function() {}); -}; -/** - * Draw the text on the given drawing context. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - */ -Font.prototype.draw = function(ctx, text, x, y, fontSize, options) { - this.getPath(text, x, y, fontSize, options).draw(ctx); -}; + var createFiber = function (tag, pendingProps, key, mode) { + // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors + return new FiberNode(tag, pendingProps, key, mode); + }; -/** - * Draw the points of all glyphs in the text. - * On-curve points will be drawn in blue, off-curve points will be drawn in red. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - */ -Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) { - this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { - glyph.drawPoints(ctx, gX, gY, gFontSize); - }); -}; + function shouldConstruct$1(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } -/** - * Draw lines indicating important font measurements for all glyphs in the text. - * Black lines indicate the origin of the coordinate system (point 0,0). - * Blue lines indicate the glyph bounding box. - * Green line indicates the advance width of the glyph. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - */ -Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) { - this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { - glyph.drawMetrics(ctx, gX, gY, gFontSize); - }); -}; + function isSimpleFunctionComponent(type) { + return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined; + } + function resolveLazyComponentTag(Component) { + if (typeof Component === 'function') { + return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent; + } else if (Component !== undefined && Component !== null) { + var $$typeof = Component.$$typeof; -/** - * @param {string} - * @return {string} - */ -Font.prototype.getEnglishName = function(name) { - var translations = this.names[name]; - if (translations) { - return translations.en; - } -}; + if ($$typeof === REACT_FORWARD_REF_TYPE) { + return ForwardRef; + } -/** - * Validate - */ -Font.prototype.validate = function() { - var _this = this; + if ($$typeof === REACT_MEMO_TYPE) { + return MemoComponent; + } + } - function assert(predicate, message) { - } + return IndeterminateComponent; + } // This is used to create an alternate fiber to do work on. - function assertNamePresent(name) { - var englishName = _this.getEnglishName(name); - assert(englishName && englishName.trim().length > 0); - } + function createWorkInProgress(current, pendingProps) { + var workInProgress = current.alternate; - // Identification information - assertNamePresent('fontFamily'); - assertNamePresent('weightName'); - assertNamePresent('manufacturer'); - assertNamePresent('copyright'); - assertNamePresent('version'); + if (workInProgress === null) { + // We use a double buffering pooling technique because we know that we'll + // only ever need at most two versions of a tree. We pool the "other" unused + // node that we're free to reuse. This is lazily created to avoid allocating + // extra objects for things that are never updated. It also allow us to + // reclaim the extra memory if needed. + workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode); + workInProgress.elementType = current.elementType; + workInProgress.type = current.type; + workInProgress.stateNode = current.stateNode; - // Dimension information - assert(this.unitsPerEm > 0); -}; + { + // DEV-only fields + workInProgress._debugSource = current._debugSource; + workInProgress._debugOwner = current._debugOwner; + workInProgress._debugHookTypes = current._debugHookTypes; + } -/** - * Convert the font object to a SFNT data structure. - * This structure contains all the necessary tables and metadata to create a binary OTF file. - * @return {opentype.Table} - */ -Font.prototype.toTables = function() { - return sfnt.fontToTable(this); -}; -/** - * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. - */ -Font.prototype.toBuffer = function() { - console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'); - return this.toArrayBuffer(); -}; -/** - * Converts a `opentype.Font` into an `ArrayBuffer` - * @return {ArrayBuffer} - */ -Font.prototype.toArrayBuffer = function() { - var sfntTable = this.toTables(); - var bytes = sfntTable.encode(); - var buffer = new ArrayBuffer(bytes.length); - var intArray = new Uint8Array(buffer); - for (var i = 0; i < bytes.length; i++) { - intArray[i] = bytes[i]; - } + workInProgress.alternate = current; + current.alternate = workInProgress; + } else { + workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type. - return buffer; -}; + workInProgress.type = current.type; // We already have an alternate. + // Reset the effect tag. -/** - * Initiate a download of the OpenType font. - */ -Font.prototype.download = function(fileName) { - var familyName = this.getEnglishName('fontFamily'); - var styleName = this.getEnglishName('fontSubfamily'); - fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf'; - var arrayBuffer = this.toArrayBuffer(); - - if (isBrowser()) { - window.URL = window.URL || window.webkitURL; - - if (window.URL) { - var dataView = new DataView(arrayBuffer); - var blob = new Blob([dataView], {type: 'font/opentype'}); - - var link = document.createElement('a'); - link.href = window.URL.createObjectURL(blob); - link.download = fileName; - - var event = document.createEvent('MouseEvents'); - event.initEvent('click', true, false); - link.dispatchEvent(event); - } else { - console.warn('Font file could not be downloaded. Try using a different browser.'); - } - } else { - var fs = require('fs'); - var buffer = arrayBufferToNodeBuffer(arrayBuffer); - fs.writeFileSync(fileName, buffer); - } -}; -/** - * @private - */ -Font.prototype.fsSelectionValues = { - ITALIC: 0x001, //1 - UNDERSCORE: 0x002, //2 - NEGATIVE: 0x004, //4 - OUTLINED: 0x008, //8 - STRIKEOUT: 0x010, //16 - BOLD: 0x020, //32 - REGULAR: 0x040, //64 - USER_TYPO_METRICS: 0x080, //128 - WWS: 0x100, //256 - OBLIQUE: 0x200 //512 -}; + workInProgress.flags = NoFlags; // The effects are no longer valid. -/** - * @private - */ -Font.prototype.usWidthClasses = { - ULTRA_CONDENSED: 1, - EXTRA_CONDENSED: 2, - CONDENSED: 3, - SEMI_CONDENSED: 4, - MEDIUM: 5, - SEMI_EXPANDED: 6, - EXPANDED: 7, - EXTRA_EXPANDED: 8, - ULTRA_EXPANDED: 9 -}; + workInProgress.subtreeFlags = NoFlags; + workInProgress.deletions = null; -/** - * @private - */ -Font.prototype.usWeightClasses = { - THIN: 100, - EXTRA_LIGHT: 200, - LIGHT: 300, - NORMAL: 400, - MEDIUM: 500, - SEMI_BOLD: 600, - BOLD: 700, - EXTRA_BOLD: 800, - BLACK: 900 -}; + { + // We intentionally reset, rather than copy, actualDuration & actualStartTime. + // This prevents time from endlessly accumulating in new commits. + // This has the downside of resetting values for different priority renders, + // But works for yielding (the common case) and should support resuming. + workInProgress.actualDuration = 0; + workInProgress.actualStartTime = -1; + } + } // Reset all effects except static ones. + // Static effects are not specific to a render. -// The `GPOS` table contains kerning pairs, among other things. -var subtableParsers$1 = new Array(10); // subtableParsers[0] is unused + workInProgress.flags = current.flags & StaticMask; + workInProgress.childLanes = current.childLanes; + workInProgress.lanes = current.lanes; + workInProgress.child = current.child; + workInProgress.memoizedProps = current.memoizedProps; + workInProgress.memoizedState = current.memoizedState; + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so + // it cannot be shared with the current fiber. -// https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-1-single-adjustment-positioning-subtable -// this = Parser instance -subtableParsers$1[1] = function parseLookup1() { - var start = this.offset + this.relativeOffset; - var posformat = this.parseUShort(); - if (posformat === 1) { - return { - posFormat: 1, - coverage: this.parsePointer(Parser.coverage), - value: this.parseValueRecord() - }; - } else if (posformat === 2) { - return { - posFormat: 2, - coverage: this.parsePointer(Parser.coverage), - values: this.parseValueRecordList() - }; - } - check.assert(false, '0x' + start.toString(16) + ': GPOS lookup type 1 format must be 1 or 2.'); -}; + var currentDependencies = current.dependencies; + workInProgress.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; // These will be overridden during the parent's reconciliation -// https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable -subtableParsers$1[2] = function parseLookup2() { - var start = this.offset + this.relativeOffset; - var posFormat = this.parseUShort(); - check.assert(posFormat === 1 || posFormat === 2, '0x' + start.toString(16) + ': GPOS lookup type 2 format must be 1 or 2.'); - var coverage = this.parsePointer(Parser.coverage); - var valueFormat1 = this.parseUShort(); - var valueFormat2 = this.parseUShort(); - if (posFormat === 1) { - // Adjustments for Glyph Pairs - return { - posFormat: posFormat, - coverage: coverage, - valueFormat1: valueFormat1, - valueFormat2: valueFormat2, - pairSets: this.parseList(Parser.pointer(Parser.list(function() { - return { // pairValueRecord - secondGlyph: this.parseUShort(), - value1: this.parseValueRecord(valueFormat1), - value2: this.parseValueRecord(valueFormat2) - }; - }))) - }; - } else if (posFormat === 2) { - var classDef1 = this.parsePointer(Parser.classDef); - var classDef2 = this.parsePointer(Parser.classDef); - var class1Count = this.parseUShort(); - var class2Count = this.parseUShort(); - return { - // Class Pair Adjustment - posFormat: posFormat, - coverage: coverage, - valueFormat1: valueFormat1, - valueFormat2: valueFormat2, - classDef1: classDef1, - classDef2: classDef2, - class1Count: class1Count, - class2Count: class2Count, - classRecords: this.parseList(class1Count, Parser.list(class2Count, function() { - return { - value1: this.parseValueRecord(valueFormat1), - value2: this.parseValueRecord(valueFormat2) - }; - })) - }; - } -}; + workInProgress.sibling = current.sibling; + workInProgress.index = current.index; + workInProgress.ref = current.ref; -subtableParsers$1[3] = function parseLookup3() { return { error: 'GPOS Lookup 3 not supported' }; }; -subtableParsers$1[4] = function parseLookup4() { return { error: 'GPOS Lookup 4 not supported' }; }; -subtableParsers$1[5] = function parseLookup5() { return { error: 'GPOS Lookup 5 not supported' }; }; -subtableParsers$1[6] = function parseLookup6() { return { error: 'GPOS Lookup 6 not supported' }; }; -subtableParsers$1[7] = function parseLookup7() { return { error: 'GPOS Lookup 7 not supported' }; }; -subtableParsers$1[8] = function parseLookup8() { return { error: 'GPOS Lookup 8 not supported' }; }; -subtableParsers$1[9] = function parseLookup9() { return { error: 'GPOS Lookup 9 not supported' }; }; + { + workInProgress.selfBaseDuration = current.selfBaseDuration; + workInProgress.treeBaseDuration = current.treeBaseDuration; + } -// GPOS Writing ////////////////////////////////////////////// -// NOT SUPPORTED -new Array(10); + { + workInProgress._debugNeedsRemount = current._debugNeedsRemount; -var AssimpLoader = function (manager) { - Loader.call(this, manager); -}; + switch (workInProgress.tag) { + case IndeterminateComponent: + case FunctionComponent: + case SimpleMemoComponent: + workInProgress.type = resolveFunctionForHotReloading(current.type); + break; -AssimpLoader.prototype = Object.assign(Object.create(Loader.prototype), { - constructor: AssimpLoader, - load: function (url, onLoad, onProgress, onError) { - var scope = this; - var path = scope.path === '' ? LoaderUtils.extractUrlBase(url) : scope.path; - var loader = new FileLoader(scope.manager); - loader.setPath(scope.path); - loader.setResponseType('arraybuffer'); - loader.setRequestHeader(scope.requestHeader); - loader.setWithCredentials(scope.withCredentials); - loader.load(url, function (buffer) { - try { - onLoad(scope.parse(buffer, path)); - } catch (e) { - if (onError) { - onError(e); - } else { - console.error(e); - } + case ClassComponent: + workInProgress.type = resolveClassForHotReloading(current.type); + break; - scope.manager.itemError(url); - } - }, onProgress, onError); - }, - parse: function (buffer, path) { - var textureLoader = new TextureLoader(this.manager); - textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin); - var Virtulous = {}; - - Virtulous.KeyFrame = function (time, matrix) { - this.time = time; - this.matrix = matrix.clone(); - this.position = new Vector3(); - this.quaternion = new Quaternion(); - this.scale = new Vector3(1, 1, 1); - this.matrix.decompose(this.position, this.quaternion, this.scale); - - this.clone = function () { - var n = new Virtulous.KeyFrame(this.time, this.matrix); - return n; - }; + case ForwardRef: + workInProgress.type = resolveForwardRefForHotReloading(current.type); + break; + } + } - this.lerp = function (nextKey, time) { - time -= this.time; - var dist = nextKey.time - this.time; - var l = time / dist; - var l2 = 1 - l; - var keypos = this.position; - var keyrot = this.quaternion; // var keyscl = key.parentspaceScl || key.scl; - - var key2pos = nextKey.position; - var key2rot = nextKey.quaternion; // var key2scl = key2.parentspaceScl || key2.scl; - - Virtulous.KeyFrame.tempAniPos.x = keypos.x * l2 + key2pos.x * l; - Virtulous.KeyFrame.tempAniPos.y = keypos.y * l2 + key2pos.y * l; - Virtulous.KeyFrame.tempAniPos.z = keypos.z * l2 + key2pos.z * l; // tempAniScale.x = keyscl[0] * l2 + key2scl[0] * l; - // tempAniScale.y = keyscl[1] * l2 + key2scl[1] * l; - // tempAniScale.z = keyscl[2] * l2 + key2scl[2] * l; - - Virtulous.KeyFrame.tempAniQuat.set(keyrot.x, keyrot.y, keyrot.z, keyrot.w); - Virtulous.KeyFrame.tempAniQuat.slerp(key2rot, l); - return Virtulous.KeyFrame.tempAniMatrix.compose(Virtulous.KeyFrame.tempAniPos, Virtulous.KeyFrame.tempAniQuat, Virtulous.KeyFrame.tempAniScale); - }; - }; + return workInProgress; + } // Used to reuse a Fiber for a second pass. - Virtulous.KeyFrame.tempAniPos = new Vector3(); - Virtulous.KeyFrame.tempAniQuat = new Quaternion(); - Virtulous.KeyFrame.tempAniScale = new Vector3(1, 1, 1); - Virtulous.KeyFrame.tempAniMatrix = new Matrix4(); + function resetWorkInProgress(workInProgress, renderLanes) { + // This resets the Fiber to what createFiber or createWorkInProgress would + // have set the values to before during the first pass. Ideally this wouldn't + // be necessary but unfortunately many code paths reads from the workInProgress + // when they should be reading from current and writing to workInProgress. + // We assume pendingProps, index, key, ref, return are still untouched to + // avoid doing another reconciliation. + // Reset the effect flags but keep any Placement tags, since that's something + // that child fiber is setting, not the reconciliation. + workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid. - Virtulous.KeyFrameTrack = function () { - this.keys = []; - this.target = null; - this.time = 0; - this.length = 0; - this._accelTable = {}; - this.fps = 20; + var current = workInProgress.alternate; - this.addKey = function (key) { - this.keys.push(key); - }; + if (current === null) { + // Reset to createFiber's initial values. + workInProgress.childLanes = NoLanes; + workInProgress.lanes = renderLanes; + workInProgress.child = null; + workInProgress.subtreeFlags = NoFlags; + workInProgress.memoizedProps = null; + workInProgress.memoizedState = null; + workInProgress.updateQueue = null; + workInProgress.dependencies = null; + workInProgress.stateNode = null; - this.init = function () { - this.sortKeys(); - if (this.keys.length > 0) this.length = this.keys[this.keys.length - 1].time;else this.length = 0; - if (!this.fps) return; + { + // Note: We don't reset the actualTime counts. It's useful to accumulate + // actual time across multiple render passes. + workInProgress.selfBaseDuration = 0; + workInProgress.treeBaseDuration = 0; + } + } else { + // Reset to the cloned values that createWorkInProgress would've. + workInProgress.childLanes = current.childLanes; + workInProgress.lanes = current.lanes; + workInProgress.child = current.child; + workInProgress.subtreeFlags = NoFlags; + workInProgress.deletions = null; + workInProgress.memoizedProps = current.memoizedProps; + workInProgress.memoizedState = current.memoizedState; + workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type. - for (let j = 0; j < this.length * this.fps; j++) { - for (let i = 0; i < this.keys.length; i++) { - if (this.keys[i].time == j) { - this._accelTable[j] = i; - break; - } else if (this.keys[i].time < j / this.fps && this.keys[i + 1] && this.keys[i + 1].time >= j / this.fps) { - this._accelTable[j] = i; - break; - } - } - } - }; + workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so + // it cannot be shared with the current fiber. - this.parseFromThree = function (data) { - var fps = data.fps; - this.target = data.node; - var track = data.hierarchy[0].keys; + var currentDependencies = current.dependencies; + workInProgress.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; - for (let i = 0; i < track.length; i++) { - this.addKey(new Virtulous.KeyFrame(i / fps || track[i].time, track[i].targets[0].data)); - } + { + // Note: We don't reset the actualTime counts. It's useful to accumulate + // actual time across multiple render passes. + workInProgress.selfBaseDuration = current.selfBaseDuration; + workInProgress.treeBaseDuration = current.treeBaseDuration; + } + } - this.init(); - }; + return workInProgress; + } + function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { + var mode; - this.parseFromCollada = function (data) { - var track = data.keys; - var fps = this.fps; + if (tag === ConcurrentRoot) { + mode = ConcurrentMode; - for (let i = 0; i < track.length; i++) { - this.addKey(new Virtulous.KeyFrame(i / fps || track[i].time, track[i].matrix)); - } + if (isStrictMode === true) { + mode |= StrictLegacyMode; - this.init(); - }; + { + mode |= StrictEffectsMode; + } + } + } else { + mode = NoMode; + } - this.sortKeys = function () { - this.keys.sort(this.keySortFunc); - }; + if ( isDevToolsPresent) { + // Always collect profile timings when DevTools are present. + // This enables DevTools to start capturing timing at any point– + // Without some nodes in the tree having empty base times. + mode |= ProfileMode; + } - this.keySortFunc = function (a, b) { - return a.time - b.time; - }; + return createFiber(HostRoot, null, null, mode); + } + function createFiberFromTypeAndProps(type, // React$ElementType + key, pendingProps, owner, mode, lanes) { + var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. - this.clone = function () { - var t = new Virtulous.KeyFrameTrack(); - t.target = this.target; - t.time = this.time; - t.length = this.length; + var resolvedType = type; - for (let i = 0; i < this.keys.length; i++) { - t.addKey(this.keys[i].clone()); - } + if (typeof type === 'function') { + if (shouldConstruct$1(type)) { + fiberTag = ClassComponent; - t.init(); - return t; - }; + { + resolvedType = resolveClassForHotReloading(resolvedType); + } + } else { + { + resolvedType = resolveFunctionForHotReloading(resolvedType); + } + } + } else if (typeof type === 'string') { + fiberTag = HostComponent; + } else { + getTag: switch (type) { + case REACT_FRAGMENT_TYPE: + return createFiberFromFragment(pendingProps.children, mode, lanes, key); - this.reTarget = function (root, compareitor) { - if (!compareitor) compareitor = Virtulous.TrackTargetNodeNameCompare; - this.target = compareitor(root, this.target); - }; + case REACT_STRICT_MODE_TYPE: + fiberTag = Mode; + mode |= StrictLegacyMode; - this.keySearchAccel = function (time) { - time *= this.fps; - time = Math.floor(time); - return this._accelTable[time] || 0; - }; + if ( (mode & ConcurrentMode) !== NoMode) { + // Strict effects should never run on legacy roots + mode |= StrictEffectsMode; + } - this.setTime = function (time) { - time = Math.abs(time); - if (this.length) time = time % this.length + 0.05; - var key0 = null; - var key1 = null; - - for (let i = this.keySearchAccel(time); i < this.keys.length; i++) { - if (this.keys[i].time == time) { - key0 = this.keys[i]; - key1 = this.keys[i]; - break; - } else if (this.keys[i].time < time && this.keys[i + 1] && this.keys[i + 1].time > time) { - key0 = this.keys[i]; - key1 = this.keys[i + 1]; - break; - } else if (this.keys[i].time < time && i == this.keys.length - 1) { - key0 = this.keys[i]; - key1 = this.keys[0].clone(); - key1.time += this.length + 0.05; - break; - } - } + break; - if (key0 && key1 && key0 !== key1) { - this.target.matrixAutoUpdate = false; - this.target.matrix.copy(key0.lerp(key1, time)); - this.target.matrixWorldNeedsUpdate = true; - return; - } + case REACT_PROFILER_TYPE: + return createFiberFromProfiler(pendingProps, mode, lanes, key); - if (key0 && key1 && key0 == key1) { - this.target.matrixAutoUpdate = false; - this.target.matrix.copy(key0.matrix); - this.target.matrixWorldNeedsUpdate = true; - return; - } - }; - }; + case REACT_SUSPENSE_TYPE: + return createFiberFromSuspense(pendingProps, mode, lanes, key); - Virtulous.TrackTargetNodeNameCompare = function (root, target) { - function find(node, name) { - if (node.name == name) return node; + case REACT_SUSPENSE_LIST_TYPE: + return createFiberFromSuspenseList(pendingProps, mode, lanes, key); - for (let i = 0; i < node.children.length; i++) { - var r = find(node.children[i], name); - if (r) return r; - } + case REACT_OFFSCREEN_TYPE: + return createFiberFromOffscreen(pendingProps, mode, lanes, key); - return null; - } + case REACT_LEGACY_HIDDEN_TYPE: - return find(root, target.name); - }; + // eslint-disable-next-line no-fallthrough - Virtulous.Animation = function () { - this.tracks = []; - this.length = 0; + case REACT_SCOPE_TYPE: - this.addTrack = function (track) { - this.tracks.push(track); - this.length = Math.max(track.length, this.length); - }; + // eslint-disable-next-line no-fallthrough - this.setTime = function (time) { - this.time = time; + case REACT_CACHE_TYPE: - for (let i = 0; i < this.tracks.length; i++) this.tracks[i].setTime(time); - }; + // eslint-disable-next-line no-fallthrough - this.clone = function (target, compareitor) { - if (!compareitor) compareitor = Virtulous.TrackTargetNodeNameCompare; - var n = new Virtulous.Animation(); - n.target = target; + case REACT_TRACING_MARKER_TYPE: - for (let i = 0; i < this.tracks.length; i++) { - var track = this.tracks[i].clone(); - track.reTarget(target, compareitor); - n.addTrack(track); - } + // eslint-disable-next-line no-fallthrough - return n; - }; - }; + case REACT_DEBUG_TRACING_MODE_TYPE: - var ASSBIN_CHUNK_AICAMERA = 0x1234; - var ASSBIN_CHUNK_AILIGHT = 0x1235; - var ASSBIN_CHUNK_AITEXTURE = 0x1236; - var ASSBIN_CHUNK_AIMESH = 0x1237; - var ASSBIN_CHUNK_AINODEANIM = 0x1238; - var ASSBIN_CHUNK_AISCENE = 0x1239; - var ASSBIN_CHUNK_AIBONE = 0x123a; - var ASSBIN_CHUNK_AIANIMATION = 0x123b; - var ASSBIN_CHUNK_AINODE = 0x123c; - var ASSBIN_CHUNK_AIMATERIAL = 0x123d; - var ASSBIN_CHUNK_AIMATERIALPROPERTY = 0x123e; - var ASSBIN_MESH_HAS_POSITIONS = 0x1; - var ASSBIN_MESH_HAS_NORMALS = 0x2; - var ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS = 0x4; - var ASSBIN_MESH_HAS_TEXCOORD_BASE = 0x100; - var ASSBIN_MESH_HAS_COLOR_BASE = 0x10000; - var AI_MAX_NUMBER_OF_COLOR_SETS = 1; - var AI_MAX_NUMBER_OF_TEXTURECOORDS = 4; //var aiLightSource_UNDEFINED = 0x0; - //! A directional light source has a well-defined direction - //! but is infinitely far away. That's quite a good - //! approximation for sun light. - - var aiLightSource_DIRECTIONAL = 0x1; //! A point light source has a well-defined position - //! in space but no direction - it emits light in all - //! directions. A normal bulb is a point light. - //var aiLightSource_POINT = 0x2; - //! A spot light source emits light in a specific - //! angle. It has a position and a direction it is pointing to. - //! A good example for a spot light is a light spot in - //! sport arenas. - - var aiLightSource_SPOT = 0x3; //! The generic light level of the world, including the bounces - //! of all other lightsources. - //! Typically, there's at most one ambient light in a scene. - //! This light type doesn't have a valid position, direction, or - //! other properties, just a color. - //var aiLightSource_AMBIENT = 0x4; - - /** Flat shading. Shading is done on per-face base, - * diffuse only. Also known as 'faceted shading'. - */ - //var aiShadingMode_Flat = 0x1; + // eslint-disable-next-line no-fallthrough - /** Simple Gouraud shading. - */ - //var aiShadingMode_Gouraud = 0x2; + default: + { + if (typeof type === 'object' && type !== null) { + switch (type.$$typeof) { + case REACT_PROVIDER_TYPE: + fiberTag = ContextProvider; + break getTag; - /** Phong-Shading - - */ - //var aiShadingMode_Phong = 0x3; + case REACT_CONTEXT_TYPE: + // This is a consumer + fiberTag = ContextConsumer; + break getTag; - /** Phong-Blinn-Shading - */ - //var aiShadingMode_Blinn = 0x4; + case REACT_FORWARD_REF_TYPE: + fiberTag = ForwardRef; - /** Toon-Shading per pixel - * - * Also known as 'comic' shader. - */ - //var aiShadingMode_Toon = 0x5; + { + resolvedType = resolveForwardRefForHotReloading(resolvedType); + } - /** OrenNayar-Shading per pixel - * - * Extension to standard Lambertian shading, taking the - * roughness of the material into account - */ - //var aiShadingMode_OrenNayar = 0x6; + break getTag; - /** Minnaert-Shading per pixel - * - * Extension to standard Lambertian shading, taking the - * "darkness" of the material into account - */ - //var aiShadingMode_Minnaert = 0x7; + case REACT_MEMO_TYPE: + fiberTag = MemoComponent; + break getTag; - /** CookTorrance-Shading per pixel - * - * Special shader for metallic surfaces. - */ - //var aiShadingMode_CookTorrance = 0x8; + case REACT_LAZY_TYPE: + fiberTag = LazyComponent; + resolvedType = null; + break getTag; + } + } - /** No shading at all. Constant light influence of 1.0. - */ - //var aiShadingMode_NoShading = 0x9; + var info = ''; - /** Fresnel shading - */ - //var aiShadingMode_Fresnel = 0xa; - //var aiTextureType_NONE = 0x0; + { + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; + } - /** The texture is combined with the result of the diffuse - * lighting equation. - */ + var ownerName = owner ? getComponentNameFromFiber(owner) : null; - var aiTextureType_DIFFUSE = 0x1; - /** The texture is combined with the result of the specular - * lighting equation. - */ - //var aiTextureType_SPECULAR = 0x2; + if (ownerName) { + info += '\n\nCheck the render method of `' + ownerName + '`.'; + } + } - /** The texture is combined with the result of the ambient - * lighting equation. - */ - //var aiTextureType_AMBIENT = 0x3; + throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); + } + } + } - /** The texture is added to the result of the lighting - * calculation. It isn't influenced by incoming light. - */ - //var aiTextureType_EMISSIVE = 0x4; + var fiber = createFiber(fiberTag, pendingProps, key, mode); + fiber.elementType = type; + fiber.type = resolvedType; + fiber.lanes = lanes; - /** The texture is a height map. - * - * By convention, higher gray-scale values stand for - * higher elevations from the base height. - */ - //var aiTextureType_HEIGHT = 0x5; + { + fiber._debugOwner = owner; + } - /** The texture is a (tangent space) normal-map. - * - * Again, there are several conventions for tangent-space - * normal maps. Assimp does (intentionally) not - * distinguish here. - */ + return fiber; + } + function createFiberFromElement(element, mode, lanes) { + var owner = null; - var aiTextureType_NORMALS = 0x6; - /** The texture defines the glossiness of the material. - * - * The glossiness is in fact the exponent of the specular - * (phong) lighting equation. Usually there is a conversion - * function defined to map the linear color values in the - * texture to a suitable exponent. Have fun. - */ - //var aiTextureType_SHININESS = 0x7; + { + owner = element._owner; + } - /** The texture defines per-pixel opacity. - * - * Usually 'white' means opaque and 'black' means - * 'transparency'. Or quite the opposite. Have fun. - */ + var type = element.type; + var key = element.key; + var pendingProps = element.props; + var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes); - var aiTextureType_OPACITY = 0x8; - /** Displacement texture - * - * The exact purpose and format is application-dependent. - * Higher color values stand for higher vertex displacements. - */ - //var aiTextureType_DISPLACEMENT = 0x9; + { + fiber._debugSource = element._source; + fiber._debugOwner = element._owner; + } - /** Lightmap texture (aka Ambient Occlusion) - * - * Both 'Lightmaps' and dedicated 'ambient occlusion maps' are - * covered by this material property. The texture contains a - * scaling value for the final color value of a pixel. Its - * intensity is not affected by incoming light. - */ + return fiber; + } + function createFiberFromFragment(elements, mode, lanes, key) { + var fiber = createFiber(Fragment, elements, key, mode); + fiber.lanes = lanes; + return fiber; + } - var aiTextureType_LIGHTMAP = 0xa; - /** Reflection texture - * - * Contains the color of a perfect mirror reflection. - * Rarely used, almost never for real-time applications. - */ - //var aiTextureType_REFLECTION = 0xB; + function createFiberFromProfiler(pendingProps, mode, lanes, key) { + { + if (typeof pendingProps.id !== 'string') { + error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id); + } + } - /** Unknown texture - * - * A texture reference that does not match any of the definitions - * above is considered to be 'unknown'. It is still imported, - * but is excluded from any further postprocessing. - */ - //var aiTextureType_UNKNOWN = 0xC; + var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); + fiber.elementType = REACT_PROFILER_TYPE; + fiber.lanes = lanes; - var BONESPERVERT = 4; + { + fiber.stateNode = { + effectDuration: 0, + passiveEffectDuration: 0 + }; + } - function ASSBIN_MESH_HAS_TEXCOORD(n) { - return ASSBIN_MESH_HAS_TEXCOORD_BASE << n; - } + return fiber; + } - function ASSBIN_MESH_HAS_COLOR(n) { - return ASSBIN_MESH_HAS_COLOR_BASE << n; - } + function createFiberFromSuspense(pendingProps, mode, lanes, key) { + var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); + fiber.elementType = REACT_SUSPENSE_TYPE; + fiber.lanes = lanes; + return fiber; + } + function createFiberFromSuspenseList(pendingProps, mode, lanes, key) { + var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); + fiber.elementType = REACT_SUSPENSE_LIST_TYPE; + fiber.lanes = lanes; + return fiber; + } + function createFiberFromOffscreen(pendingProps, mode, lanes, key) { + var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); + fiber.elementType = REACT_OFFSCREEN_TYPE; + fiber.lanes = lanes; + var primaryChildInstance = {}; + fiber.stateNode = primaryChildInstance; + return fiber; + } + function createFiberFromText(content, mode, lanes) { + var fiber = createFiber(HostText, content, null, mode); + fiber.lanes = lanes; + return fiber; + } + function createFiberFromHostInstanceForDeletion() { + var fiber = createFiber(HostComponent, null, null, NoMode); + fiber.elementType = 'DELETED'; + return fiber; + } + function createFiberFromDehydratedFragment(dehydratedNode) { + var fiber = createFiber(DehydratedFragment, null, null, NoMode); + fiber.stateNode = dehydratedNode; + return fiber; + } + function createFiberFromPortal(portal, mode, lanes) { + var pendingProps = portal.children !== null ? portal.children : []; + var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); + fiber.lanes = lanes; + fiber.stateNode = { + containerInfo: portal.containerInfo, + pendingChildren: null, + // Used by persistent updates + implementation: portal.implementation + }; + return fiber; + } // Used for stashing WIP properties to replay failed work in DEV. - function markBones(scene) { - for (let i in scene.mMeshes) { - var mesh = scene.mMeshes[i]; + function assignFiberPropertiesInDEV(target, source) { + if (target === null) { + // This Fiber's initial properties will always be overwritten. + // We only use a Fiber to ensure the same hidden class so DEV isn't slow. + target = createFiber(IndeterminateComponent, null, null, NoMode); + } // This is intentionally written as a list of all properties. + // We tried to use Object.assign() instead but this is called in + // the hottest path, and Object.assign() was too slow: + // https://github.com/facebook/react/issues/12502 + // This code is DEV-only so size is not a concern. - for (let k in mesh.mBones) { - var boneNode = scene.findNode(mesh.mBones[k].mName); - if (boneNode) boneNode.isBone = true; - } - } - } - function cloneTreeToBones(root, scene) { - var rootBone = new Bone(); - rootBone.matrix.copy(root.matrix); - rootBone.matrixWorld.copy(root.matrixWorld); - rootBone.position.copy(root.position); - rootBone.quaternion.copy(root.quaternion); - rootBone.scale.copy(root.scale); - scene.nodeCount++; - rootBone.name = 'bone_' + root.name + scene.nodeCount.toString(); - if (!scene.nodeToBoneMap[root.name]) scene.nodeToBoneMap[root.name] = []; - scene.nodeToBoneMap[root.name].push(rootBone); - - for (let i in root.children) { - var child = cloneTreeToBones(root.children[i], scene); - rootBone.add(child); - } + target.tag = source.tag; + target.key = source.key; + target.elementType = source.elementType; + target.type = source.type; + target.stateNode = source.stateNode; + target.return = source.return; + target.child = source.child; + target.sibling = source.sibling; + target.index = source.index; + target.ref = source.ref; + target.pendingProps = source.pendingProps; + target.memoizedProps = source.memoizedProps; + target.updateQueue = source.updateQueue; + target.memoizedState = source.memoizedState; + target.dependencies = source.dependencies; + target.mode = source.mode; + target.flags = source.flags; + target.subtreeFlags = source.subtreeFlags; + target.deletions = source.deletions; + target.lanes = source.lanes; + target.childLanes = source.childLanes; + target.alternate = source.alternate; - return rootBone; - } + { + target.actualDuration = source.actualDuration; + target.actualStartTime = source.actualStartTime; + target.selfBaseDuration = source.selfBaseDuration; + target.treeBaseDuration = source.treeBaseDuration; + } - function sortWeights(indexes, weights) { - var pairs = []; + target._debugSource = source._debugSource; + target._debugOwner = source._debugOwner; + target._debugNeedsRemount = source._debugNeedsRemount; + target._debugHookTypes = source._debugHookTypes; + return target; + } - for (let i = 0; i < indexes.length; i++) { - pairs.push({ - i: indexes[i], - w: weights[i] - }); - } + function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) { + this.tag = tag; + this.containerInfo = containerInfo; + this.pendingChildren = null; + this.current = null; + this.pingCache = null; + this.finishedWork = null; + this.timeoutHandle = noTimeout; + this.context = null; + this.pendingContext = null; + this.callbackNode = null; + this.callbackPriority = NoLane; + this.eventTimes = createLaneMap(NoLanes); + this.expirationTimes = createLaneMap(NoTimestamp); + this.pendingLanes = NoLanes; + this.suspendedLanes = NoLanes; + this.pingedLanes = NoLanes; + this.expiredLanes = NoLanes; + this.mutableReadLanes = NoLanes; + this.finishedLanes = NoLanes; + this.entangledLanes = NoLanes; + this.entanglements = createLaneMap(NoLanes); + this.identifierPrefix = identifierPrefix; + this.onRecoverableError = onRecoverableError; - pairs.sort(function (a, b) { - return b.w - a.w; - }); + if (supportsHydration) { + this.mutableSourceEagerHydrationData = null; + } - while (pairs.length < 4) { - pairs.push({ - i: 0, - w: 0 - }); - } + { + this.effectDuration = 0; + this.passiveEffectDuration = 0; + } + + { + this.memoizedUpdaters = new Set(); + var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = []; + + for (var _i = 0; _i < TotalLanes; _i++) { + pendingUpdatersLaneMap.push(new Set()); + } + } - if (pairs.length > 4) pairs.length = 4; - var sum = 0; + { + switch (tag) { + case ConcurrentRoot: + this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()'; + break; - for (let i = 0; i < 4; i++) { - sum += pairs[i].w * pairs[i].w; - } + case LegacyRoot: + this._debugRootType = hydrate ? 'hydrate()' : 'render()'; + break; + } + } + } - sum = Math.sqrt(sum); + function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the + // host config, but because they are passed in at runtime, we have to thread + // them through the root constructor. Perhaps we should put them all into a + // single type, like a DynamicHostConfig that is defined by the renderer. + identifierPrefix, onRecoverableError, transitionCallbacks) { + var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); + // stateNode is any. - for (let i = 0; i < 4; i++) { - pairs[i].w = pairs[i].w / sum; - indexes[i] = pairs[i].i; - weights[i] = pairs[i].w; - } - } - function findMatchingBone(root, name) { - if (root.name.indexOf('bone_' + name) == 0) return root; + var uninitializedFiber = createHostRootFiber(tag, isStrictMode); + root.current = uninitializedFiber; + uninitializedFiber.stateNode = root; - for (let i in root.children) { - var ret = findMatchingBone(root.children[i], name); - if (ret) return ret; - } + { + var _initialState = { + element: initialChildren, + isDehydrated: hydrate, + cache: null, + // not enabled yet + transitions: null + }; + uninitializedFiber.memoizedState = _initialState; + } - return undefined; - } + initializeUpdateQueue(uninitializedFiber); + return root; + } - function aiMesh() { - this.mPrimitiveTypes = 0; - this.mNumVertices = 0; - this.mNumFaces = 0; - this.mNumBones = 0; - this.mMaterialIndex = 0; - this.mVertices = []; - this.mNormals = []; - this.mTangents = []; - this.mBitangents = []; - this.mColors = [[]]; - this.mTextureCoords = [[]]; - this.mFaces = []; - this.mBones = []; - - this.hookupSkeletons = function (scene) { - if (this.mBones.length == 0) return; - var allBones = []; - var offsetMatrix = []; - var skeletonRoot = scene.findNode(this.mBones[0].mName); - - while (skeletonRoot.mParent && skeletonRoot.mParent.isBone) { - skeletonRoot = skeletonRoot.mParent; - } + var ReactVersion = '18.0.0-fc46dba67-20220329'; - var threeSkeletonRoot = skeletonRoot.toTHREE(scene); - var threeSkeletonRootBone = cloneTreeToBones(threeSkeletonRoot, scene); - this.threeNode.add(threeSkeletonRootBone); + function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation. + implementation) { + var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - for (let i = 0; i < this.mBones.length; i++) { - var bone = findMatchingBone(threeSkeletonRootBone, this.mBones[i].mName); + { + checkKeyStringCoercion(key); + } - if (bone) { - var tbone = bone; - allBones.push(tbone); //tbone.matrixAutoUpdate = false; + return { + // This tag allow us to uniquely identify this as a React Portal + $$typeof: REACT_PORTAL_TYPE, + key: key == null ? null : '' + key, + children: children, + containerInfo: containerInfo, + implementation: implementation + }; + } - offsetMatrix.push(this.mBones[i].mOffsetMatrix.toTHREE()); - } else { - var skeletonRoot = scene.findNode(this.mBones[i].mName); - if (!skeletonRoot) return; - var threeSkeletonRoot = skeletonRoot.toTHREE(scene); - var threeSkeletonRootBone = cloneTreeToBones(threeSkeletonRoot, scene); - this.threeNode.add(threeSkeletonRootBone); - var bone = findMatchingBone(threeSkeletonRootBone, this.mBones[i].mName); - var tbone = bone; - allBones.push(tbone); //tbone.matrixAutoUpdate = false; - - offsetMatrix.push(this.mBones[i].mOffsetMatrix.toTHREE()); - } - } + var didWarnAboutNestedUpdates; + var didWarnAboutFindNodeInStrictMode; - var skeleton = new Skeleton(allBones, offsetMatrix); - this.threeNode.bind(skeleton, new Matrix4()); - this.threeNode.material.skinning = true; - }; + { + didWarnAboutNestedUpdates = false; + didWarnAboutFindNodeInStrictMode = {}; + } - this.toTHREE = function (scene) { - if (this.threeNode) return this.threeNode; - var geometry = new BufferGeometry(); - var mat; - if (scene.mMaterials[this.mMaterialIndex]) mat = scene.mMaterials[this.mMaterialIndex].toTHREE(scene);else mat = new MeshLambertMaterial(); - geometry.setIndex(new BufferAttribute(new Uint32Array(this.mIndexArray), 1)); - geometry.setAttribute('position', new BufferAttribute(this.mVertexBuffer, 3)); + function getContextForSubtree(parentComponent) { + if (!parentComponent) { + return emptyContextObject; + } - if (this.mNormalBuffer && this.mNormalBuffer.length > 0) { - geometry.setAttribute('normal', new BufferAttribute(this.mNormalBuffer, 3)); - } + var fiber = get(parentComponent); + var parentContext = findCurrentUnmaskedContext(fiber); - if (this.mColorBuffer && this.mColorBuffer.length > 0) { - geometry.setAttribute('color', new BufferAttribute(this.mColorBuffer, 4)); - } + if (fiber.tag === ClassComponent) { + var Component = fiber.type; - if (this.mTexCoordsBuffers[0] && this.mTexCoordsBuffers[0].length > 0) { - geometry.setAttribute('uv', new BufferAttribute(new Float32Array(this.mTexCoordsBuffers[0]), 2)); - } + if (isContextProvider(Component)) { + return processChildContext(fiber, Component, parentContext); + } + } - if (this.mTexCoordsBuffers[1] && this.mTexCoordsBuffers[1].length > 0) { - geometry.setAttribute('uv1', new BufferAttribute(new Float32Array(this.mTexCoordsBuffers[1]), 2)); - } + return parentContext; + } - if (this.mTangentBuffer && this.mTangentBuffer.length > 0) { - geometry.setAttribute('tangents', new BufferAttribute(this.mTangentBuffer, 3)); - } + function findHostInstance(component) { + var fiber = get(component); - if (this.mBitangentBuffer && this.mBitangentBuffer.length > 0) { - geometry.setAttribute('bitangents', new BufferAttribute(this.mBitangentBuffer, 3)); - } + if (fiber === undefined) { + if (typeof component.render === 'function') { + throw new Error('Unable to find node on an unmounted component.'); + } else { + var keys = Object.keys(component).join(','); + throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); + } + } - if (this.mBones.length > 0) { - var weights = []; - var bones = []; + var hostFiber = findCurrentHostFiber(fiber); - for (let i = 0; i < this.mBones.length; i++) { - for (let j = 0; j < this.mBones[i].mWeights.length; j++) { - var weight = this.mBones[i].mWeights[j]; + if (hostFiber === null) { + return null; + } - if (weight) { - if (!weights[weight.mVertexId]) weights[weight.mVertexId] = []; - if (!bones[weight.mVertexId]) bones[weight.mVertexId] = []; - weights[weight.mVertexId].push(weight.mWeight); - bones[weight.mVertexId].push(parseInt(i)); - } - } - } + return hostFiber.stateNode; + } - for (let i in bones) { - sortWeights(bones[i], weights[i]); - } + function findHostInstanceWithWarning(component, methodName) { + { + var fiber = get(component); - var _weights = []; - var _bones = []; + if (fiber === undefined) { + if (typeof component.render === 'function') { + throw new Error('Unable to find node on an unmounted component.'); + } else { + var keys = Object.keys(component).join(','); + throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); + } + } - for (let i = 0; i < weights.length; i++) { - for (let j = 0; j < 4; j++) { - if (weights[i] && bones[i]) { - _weights.push(weights[i][j]); + var hostFiber = findCurrentHostFiber(fiber); - _bones.push(bones[i][j]); - } else { - _weights.push(0); + if (hostFiber === null) { + return null; + } - _bones.push(0); - } - } - } + if (hostFiber.mode & StrictLegacyMode) { + var componentName = getComponentNameFromFiber(fiber) || 'Component'; - geometry.setAttribute('skinWeight', new BufferAttribute(new Float32Array(_weights), BONESPERVERT)); - geometry.setAttribute('skinIndex', new BufferAttribute(new Float32Array(_bones), BONESPERVERT)); - } + if (!didWarnAboutFindNodeInStrictMode[componentName]) { + didWarnAboutFindNodeInStrictMode[componentName] = true; + var previousFiber = current; - var mesh; - if (this.mBones.length == 0) mesh = new Mesh(geometry, mat); + try { + setCurrentFiber(hostFiber); - if (this.mBones.length > 0) { - mesh = new SkinnedMesh(geometry, mat); - mesh.normalizeSkinWeights(); - } + if (fiber.mode & StrictLegacyMode) { + error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); + } else { + error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); + } + } finally { + // Ideally this should reset to previous but this shouldn't be called in + // render and there's another warning for that anyway. + if (previousFiber) { + setCurrentFiber(previousFiber); + } else { + resetCurrentFiber(); + } + } + } + } - this.threeNode = mesh; //mesh.matrixAutoUpdate = false; + return hostFiber.stateNode; + } + } - return mesh; - }; - } + function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate = false; + var initialChildren = null; + return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + } + function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode. + callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate = true; + var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor - function aiFace() { - this.mNumIndices = 0; - this.mIndices = []; - } + root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from + // a regular update because the initial render must match was was rendered + // on the server. + // NOTE: This update intentionally doesn't have a payload. We're only using + // the update to schedule work on the root fiber (and, for legacy roots, to + // enqueue the callback if one is provided). - function aiVector3D() { - this.x = 0; - this.y = 0; - this.z = 0; + var current = root.current; + var eventTime = requestEventTime(); + var lane = requestUpdateLane(current); + var update = createUpdate(eventTime, lane); + update.callback = callback !== undefined && callback !== null ? callback : null; + enqueueUpdate(current, update); + scheduleInitialHydrationOnRoot(root, lane, eventTime); + return root; + } + function updateContainer(element, container, parentComponent, callback) { + { + onScheduleRoot(container, element); + } - this.toTHREE = function () { - return new Vector3(this.x, this.y, this.z); - }; - } + var current$1 = container.current; + var eventTime = requestEventTime(); + var lane = requestUpdateLane(current$1); - function aiColor3D() { - this.r = 0; - this.g = 0; - this.b = 0; - this.a = 0; + { + markRenderScheduled(lane); + } - this.toTHREE = function () { - return new Color(this.r, this.g, this.b); - }; - } + var context = getContextForSubtree(parentComponent); - function aiQuaternion() { - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 0; + if (container.context === null) { + container.context = context; + } else { + container.pendingContext = context; + } - this.toTHREE = function () { - return new Quaternion(this.x, this.y, this.z, this.w); - }; - } + { + if (isRendering && current !== null && !didWarnAboutNestedUpdates) { + didWarnAboutNestedUpdates = true; - function aiVertexWeight() { - this.mVertexId = 0; - this.mWeight = 0; - } + error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown'); + } + } - function aiString() { - this.data = []; + var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property + // being called "element". - this.toString = function () { - var str = ''; - this.data.forEach(function (i) { - str += String.fromCharCode(i); - }); - return str.replace(/[^\x20-\x7E]+/g, ''); - }; - } + update.payload = { + element: element + }; + callback = callback === undefined ? null : callback; - function aiVectorKey() { - this.mTime = 0; - this.mValue = null; - } + if (callback !== null) { + { + if (typeof callback !== 'function') { + error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback); + } + } - function aiQuatKey() { - this.mTime = 0; - this.mValue = null; - } + update.callback = callback; + } - function aiNode() { - this.mName = ''; - this.mTransformation = []; - this.mNumChildren = 0; - this.mNumMeshes = 0; - this.mMeshes = []; - this.mChildren = []; - - this.toTHREE = function (scene) { - if (this.threeNode) return this.threeNode; - var o = new Object3D(); - o.name = this.mName; - o.matrix = this.mTransformation.toTHREE(); - - for (let i = 0; i < this.mChildren.length; i++) { - o.add(this.mChildren[i].toTHREE(scene)); - } + enqueueUpdate(current$1, update); + var root = scheduleUpdateOnFiber(current$1, lane, eventTime); - for (let i = 0; i < this.mMeshes.length; i++) { - o.add(scene.mMeshes[this.mMeshes[i]].toTHREE(scene)); - } + if (root !== null) { + entangleTransitions(root, current$1, lane); + } - this.threeNode = o; //o.matrixAutoUpdate = false; + return lane; + } + function getPublicRootInstance(container) { + var containerFiber = container.current; - o.matrix.decompose(o.position, o.quaternion, o.scale); - return o; - }; - } + if (!containerFiber.child) { + return null; + } - function aiBone() { - this.mName = ''; - this.mNumWeights = 0; - this.mOffsetMatrix = 0; - } + switch (containerFiber.child.tag) { + case HostComponent: + return getPublicInstance(containerFiber.child.stateNode); - function aiMaterialProperty() { - this.mKey = ''; - this.mSemantic = 0; - this.mIndex = 0; - this.mData = []; - this.mDataLength = 0; - this.mType = 0; - - this.dataAsColor = function () { - var array = new Uint8Array(this.mData).buffer; - var reader = new DataView(array); - var r = reader.getFloat32(0, true); - var g = reader.getFloat32(4, true); - var b = reader.getFloat32(8, true); //var a = reader.getFloat32(12, true); - - return new Color(r, g, b); - }; + default: + return containerFiber.child.stateNode; + } + } + function attemptSynchronousHydration(fiber) { + switch (fiber.tag) { + case HostRoot: + var root = fiber.stateNode; - this.dataAsFloat = function () { - var array = new Uint8Array(this.mData).buffer; - var reader = new DataView(array); - var r = reader.getFloat32(0, true); - return r; - }; + if (isRootDehydrated(root)) { + // Flush the first scheduled "update". + var lanes = getHighestPriorityPendingLanes(root); + flushRoot(root, lanes); + } - this.dataAsBool = function () { - var array = new Uint8Array(this.mData).buffer; - var reader = new DataView(array); - var r = reader.getFloat32(0, true); - return !!r; - }; + break; - this.dataAsString = function () { - var s = new aiString(); - s.data = this.mData; - return s.toString(); - }; + case SuspenseComponent: + var eventTime = requestEventTime(); + flushSync(function () { + return scheduleUpdateOnFiber(fiber, SyncLane, eventTime); + }); // If we're still blocked after this, we need to increase + // the priority of any promises resolving within this + // boundary so that they next attempt also has higher pri. - this.dataAsMap = function () { - var s = new aiString(); - s.data = this.mData; - var path = s.toString(); - path = path.replace(/\\/g, '/'); + var retryLane = SyncLane; + markRetryLaneIfNotHydrated(fiber, retryLane); + break; + } + } - if (path.indexOf('/') != -1) { - path = path.substr(path.lastIndexOf('/') + 1); - } + function markRetryLaneImpl(fiber, retryLane) { + var suspenseState = fiber.memoizedState; - return textureLoader.load(path); - }; - } + if (suspenseState !== null && suspenseState.dehydrated !== null) { + suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane); + } + } // Increases the priority of thenables when they resolve within this boundary. - var namePropMapping = { - '?mat.name': 'name', - '$mat.shadingm': 'shading', - '$mat.twosided': 'twoSided', - '$mat.wireframe': 'wireframe', - '$clr.ambient': 'ambient', - '$clr.diffuse': 'color', - '$clr.specular': 'specular', - '$clr.emissive': 'emissive', - '$clr.transparent': 'transparent', - '$clr.reflective': 'reflect', - '$mat.shininess': 'shininess', - '$mat.reflectivity': 'reflectivity', - '$mat.refracti': 'refraction', - '$tex.file': 'map' - }; - var nameTypeMapping = { - '?mat.name': 'string', - '$mat.shadingm': 'bool', - '$mat.twosided': 'bool', - '$mat.wireframe': 'bool', - '$clr.ambient': 'color', - '$clr.diffuse': 'color', - '$clr.specular': 'color', - '$clr.emissive': 'color', - '$clr.transparent': 'color', - '$clr.reflective': 'color', - '$mat.shininess': 'float', - '$mat.reflectivity': 'float', - '$mat.refracti': 'float', - '$tex.file': 'map' - }; - function aiMaterial() { - this.mNumAllocated = 0; - this.mNumProperties = 0; - this.mProperties = []; + function markRetryLaneIfNotHydrated(fiber, retryLane) { + markRetryLaneImpl(fiber, retryLane); + var alternate = fiber.alternate; - this.toTHREE = function () { - var mat = new MeshPhongMaterial(); + if (alternate) { + markRetryLaneImpl(alternate, retryLane); + } + } - for (let i = 0; i < this.mProperties.length; i++) { - if (nameTypeMapping[this.mProperties[i].mKey] == 'float') { - mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsFloat(); - } + function attemptContinuousHydration(fiber) { + if (fiber.tag !== SuspenseComponent) { + // We ignore HostRoots here because we can't increase + // their priority and they should not suspend on I/O, + // since you have to wrap anything that might suspend in + // Suspense. + return; + } - if (nameTypeMapping[this.mProperties[i].mKey] == 'color') { - mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsColor(); - } + var eventTime = requestEventTime(); + var lane = SelectiveHydrationLane; + scheduleUpdateOnFiber(fiber, lane, eventTime); + markRetryLaneIfNotHydrated(fiber, lane); + } + function attemptHydrationAtCurrentPriority(fiber) { + if (fiber.tag !== SuspenseComponent) { + // We ignore HostRoots here because we can't increase + // their priority other than synchronously flush it. + return; + } - if (nameTypeMapping[this.mProperties[i].mKey] == 'bool') { - mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsBool(); - } + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + scheduleUpdateOnFiber(fiber, lane, eventTime); + markRetryLaneIfNotHydrated(fiber, lane); + } + function findHostInstanceWithNoPortals(fiber) { + var hostFiber = findCurrentHostFiberWithNoPortals(fiber); - if (nameTypeMapping[this.mProperties[i].mKey] == 'string') { - mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsString(); - } + if (hostFiber === null) { + return null; + } - if (nameTypeMapping[this.mProperties[i].mKey] == 'map') { - var prop = this.mProperties[i]; - if (prop.mSemantic == aiTextureType_DIFFUSE) mat.map = this.mProperties[i].dataAsMap(); - if (prop.mSemantic == aiTextureType_NORMALS) mat.normalMap = this.mProperties[i].dataAsMap(); - if (prop.mSemantic == aiTextureType_LIGHTMAP) mat.lightMap = this.mProperties[i].dataAsMap(); - if (prop.mSemantic == aiTextureType_OPACITY) mat.alphaMap = this.mProperties[i].dataAsMap(); - } - } + return hostFiber.stateNode; + } - mat.ambient.r = 0.53; - mat.ambient.g = 0.53; - mat.ambient.b = 0.53; - mat.color.r = 1; - mat.color.g = 1; - mat.color.b = 1; - return mat; - }; - } + var shouldErrorImpl = function (fiber) { + return null; + }; - function veclerp(v1, v2, l) { - var v = new Vector3(); - var lm1 = 1 - l; - v.x = v1.x * l + v2.x * lm1; - v.y = v1.y * l + v2.y * lm1; - v.z = v1.z * l + v2.z * lm1; - return v; - } + function shouldError(fiber) { + return shouldErrorImpl(fiber); + } - function quatlerp(q1, q2, l) { - return q1.clone().slerp(q2, 1 - l); - } + var shouldSuspendImpl = function (fiber) { + return false; + }; - function sampleTrack(keys, time, lne, lerp) { - if (keys.length == 1) return keys[0].mValue.toTHREE(); - var dist = Infinity; - var key = null; - var nextKey = null; + function shouldSuspend(fiber) { + return shouldSuspendImpl(fiber); + } + var overrideHookState = null; + var overrideHookStateDeletePath = null; + var overrideHookStateRenamePath = null; + var overrideProps = null; + var overridePropsDeletePath = null; + var overridePropsRenamePath = null; + var scheduleUpdate = null; + var setErrorHandler = null; + var setSuspenseHandler = null; - for (let i = 0; i < keys.length; i++) { - var timeDist = Math.abs(keys[i].mTime - time); + { + var copyWithDeleteImpl = function (obj, path, index) { + var key = path[index]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); - if (timeDist < dist && keys[i].mTime <= time) { - dist = timeDist; - key = keys[i]; - nextKey = keys[i + 1]; - } - } + if (index + 1 === path.length) { + if (isArray(updated)) { + updated.splice(key, 1); + } else { + delete updated[key]; + } - if (!key) { - return null; - } else if (nextKey) { - var dT = nextKey.mTime - key.mTime; - var T = key.mTime - time; - var l = T / dT; - return lerp(key.mValue.toTHREE(), nextKey.mValue.toTHREE(), l); - } else { - nextKey = keys[0].clone(); - nextKey.mTime += lne; - var dT = nextKey.mTime - key.mTime; - var T = key.mTime - time; - var l = T / dT; - return lerp(key.mValue.toTHREE(), nextKey.mValue.toTHREE(), l); - } - } + return updated; + } // $FlowFixMe number or string is fine here - function aiNodeAnim() { - this.mNodeName = ''; - this.mNumPositionKeys = 0; - this.mNumRotationKeys = 0; - this.mNumScalingKeys = 0; - this.mPositionKeys = []; - this.mRotationKeys = []; - this.mScalingKeys = []; - this.mPreState = ''; - this.mPostState = ''; - - this.init = function (tps) { - if (!tps) tps = 1; - - function t(t) { - t.mTime /= tps; - } - this.mPositionKeys.forEach(t); - this.mRotationKeys.forEach(t); - this.mScalingKeys.forEach(t); - }; + updated[key] = copyWithDeleteImpl(obj[key], path, index + 1); + return updated; + }; - this.sortKeys = function () { - function comp(a, b) { - return a.mTime - b.mTime; - } + var copyWithDelete = function (obj, path) { + return copyWithDeleteImpl(obj, path, 0); + }; - this.mPositionKeys.sort(comp); - this.mRotationKeys.sort(comp); - this.mScalingKeys.sort(comp); - }; + var copyWithRenameImpl = function (obj, oldPath, newPath, index) { + var oldKey = oldPath[index]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); - this.getLength = function () { - return Math.max(Math.max.apply(null, this.mPositionKeys.map(function (a) { - return a.mTime; - })), Math.max.apply(null, this.mRotationKeys.map(function (a) { - return a.mTime; - })), Math.max.apply(null, this.mScalingKeys.map(function (a) { - return a.mTime; - }))); - }; + if (index + 1 === oldPath.length) { + var newKey = newPath[index]; // $FlowFixMe number or string is fine here - this.toTHREE = function (o) { - this.sortKeys(); - var length = this.getLength(); - var track = new Virtulous.KeyFrameTrack(); - - for (let i = 0; i < length; i += 0.05) { - var matrix = new Matrix4(); - var time = i; - var pos = sampleTrack(this.mPositionKeys, time, length, veclerp); - var scale = sampleTrack(this.mScalingKeys, time, length, veclerp); - var rotation = sampleTrack(this.mRotationKeys, time, length, quatlerp); - matrix.compose(pos, rotation, scale); - var key = new Virtulous.KeyFrame(time, matrix); - track.addKey(key); - } + updated[newKey] = updated[oldKey]; - track.target = o.findNode(this.mNodeName).toTHREE(); - var tracks = [track]; + if (isArray(updated)) { + updated.splice(oldKey, 1); + } else { + delete updated[oldKey]; + } + } else { + // $FlowFixMe number or string is fine here + updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here + obj[oldKey], oldPath, newPath, index + 1); + } - if (o.nodeToBoneMap[this.mNodeName]) { - for (let i = 0; i < o.nodeToBoneMap[this.mNodeName].length; i++) { - var t2 = track.clone(); - t2.target = o.nodeToBoneMap[this.mNodeName][i]; - tracks.push(t2); - } - } + return updated; + }; - return tracks; - }; - } + var copyWithRename = function (obj, oldPath, newPath) { + if (oldPath.length !== newPath.length) { + warn('copyWithRename() expects paths of the same length'); - function aiAnimation() { - this.mName = ''; - this.mDuration = 0; - this.mTicksPerSecond = 0; - this.mNumChannels = 0; - this.mChannels = []; + return; + } else { + for (var i = 0; i < newPath.length - 1; i++) { + if (oldPath[i] !== newPath[i]) { + warn('copyWithRename() expects paths to be the same except for the deepest key'); - this.toTHREE = function (root) { - var animationHandle = new Virtulous.Animation(); + return; + } + } + } - for (let i in this.mChannels) { - this.mChannels[i].init(this.mTicksPerSecond); - var tracks = this.mChannels[i].toTHREE(root); + return copyWithRenameImpl(obj, oldPath, newPath, 0); + }; - for (let j in tracks) { - tracks[j].init(); - animationHandle.addTrack(tracks[j]); - } - } + var copyWithSetImpl = function (obj, path, index, value) { + if (index >= path.length) { + return value; + } - animationHandle.length = Math.max.apply(null, animationHandle.tracks.map(function (e) { - return e.length; - })); - return animationHandle; - }; - } + var key = path[index]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here - function aiTexture() { - this.mWidth = 0; - this.mHeight = 0; - this.texAchFormatHint = []; - this.pcData = []; - } + updated[key] = copyWithSetImpl(obj[key], path, index + 1, value); + return updated; + }; - function aiLight() { - this.mName = ''; - this.mType = 0; - this.mAttenuationConstant = 0; - this.mAttenuationLinear = 0; - this.mAttenuationQuadratic = 0; - this.mAngleInnerCone = 0; - this.mAngleOuterCone = 0; - this.mColorDiffuse = null; - this.mColorSpecular = null; - this.mColorAmbient = null; - } + var copyWithSet = function (obj, path, value) { + return copyWithSetImpl(obj, path, 0, value); + }; - function aiCamera() { - this.mName = ''; - this.mPosition = null; - this.mLookAt = null; - this.mUp = null; - this.mHorizontalFOV = 0; - this.mClipPlaneNear = 0; - this.mClipPlaneFar = 0; - this.mAspect = 0; - } + var findHook = function (fiber, id) { + // For now, the "id" of stateful hooks is just the stateful hook index. + // This may change in the future with e.g. nested hooks. + var currentHook = fiber.memoizedState; - function aiScene() { - this.versionMajor = 0; - this.versionMinor = 0; - this.versionRevision = 0; - this.compileFlags = 0; - this.mFlags = 0; - this.mNumMeshes = 0; - this.mNumMaterials = 0; - this.mNumAnimations = 0; - this.mNumTextures = 0; - this.mNumLights = 0; - this.mNumCameras = 0; - this.mRootNode = null; - this.mMeshes = []; - this.mMaterials = []; - this.mAnimations = []; - this.mLights = []; - this.mCameras = []; - this.nodeToBoneMap = {}; - - this.findNode = function (name, root) { - if (!root) { - root = this.mRootNode; - } + while (currentHook !== null && id > 0) { + currentHook = currentHook.next; + id--; + } - if (root.mName == name) { - return root; - } + return currentHook; + }; // Support DevTools editable values for useState and useReducer. - for (let i = 0; i < root.mChildren.length; i++) { - var ret = this.findNode(name, root.mChildren[i]); - if (ret) return ret; - } - return null; - }; + overrideHookState = function (fiber, id, path, value) { + var hook = findHook(fiber, id); - this.toTHREE = function () { - this.nodeCount = 0; - markBones(this); - var o = this.mRootNode.toTHREE(this); + if (hook !== null) { + var newState = copyWithSet(hook.memoizedState, path, value); + hook.memoizedState = newState; + hook.baseState = newState; // We aren't actually adding an update to the queue, + // because there is no update we can add for useReducer hooks that won't trigger an error. + // (There's no appropriate action type for DevTools overrides.) + // As a result though, React will see the scheduled update as a noop and bailout. + // Shallow cloning props works as a workaround for now to bypass the bailout check. - for (let i in this.mMeshes) this.mMeshes[i].hookupSkeletons(this); + fiber.memoizedProps = assign({}, fiber.memoizedProps); + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } + }; - if (this.mAnimations.length > 0) { - var a = this.mAnimations[0].toTHREE(this); - } + overrideHookStateDeletePath = function (fiber, id, path) { + var hook = findHook(fiber, id); - return { - object: o, - animation: a - }; - }; - } + if (hook !== null) { + var newState = copyWithDelete(hook.memoizedState, path); + hook.memoizedState = newState; + hook.baseState = newState; // We aren't actually adding an update to the queue, + // because there is no update we can add for useReducer hooks that won't trigger an error. + // (There's no appropriate action type for DevTools overrides.) + // As a result though, React will see the scheduled update as a noop and bailout. + // Shallow cloning props works as a workaround for now to bypass the bailout check. - function aiMatrix4() { - this.elements = [[], [], [], []]; + fiber.memoizedProps = assign({}, fiber.memoizedProps); + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } + }; - this.toTHREE = function () { - var m = new Matrix4(); + overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) { + var hook = findHook(fiber, id); - for (let i = 0; i < 4; ++i) { - for (let i2 = 0; i2 < 4; ++i2) { - m.elements[i * 4 + i2] = this.elements[i2][i]; - } - } + if (hook !== null) { + var newState = copyWithRename(hook.memoizedState, oldPath, newPath); + hook.memoizedState = newState; + hook.baseState = newState; // We aren't actually adding an update to the queue, + // because there is no update we can add for useReducer hooks that won't trigger an error. + // (There's no appropriate action type for DevTools overrides.) + // As a result though, React will see the scheduled update as a noop and bailout. + // Shallow cloning props works as a workaround for now to bypass the bailout check. - return m; - }; - } + fiber.memoizedProps = assign({}, fiber.memoizedProps); + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } + }; // Support DevTools props for function components, forwardRef, memo, host components, etc. - var littleEndian = true; - function readFloat(dataview) { - var val = dataview.getFloat32(dataview.readOffset, littleEndian); - dataview.readOffset += 4; - return val; - } + overrideProps = function (fiber, path, value) { + fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); - function Read_double(dataview) { - var val = dataview.getFloat64(dataview.readOffset, littleEndian); - dataview.readOffset += 8; - return val; - } + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } - function Read_uint8_t(dataview) { - var val = dataview.getUint8(dataview.readOffset); - dataview.readOffset += 1; - return val; - } + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + }; - function Read_uint16_t(dataview) { - var val = dataview.getUint16(dataview.readOffset, littleEndian); - dataview.readOffset += 2; - return val; - } + overridePropsDeletePath = function (fiber, path) { + fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); - function Read_unsigned_int(dataview) { - var val = dataview.getUint32(dataview.readOffset, littleEndian); - dataview.readOffset += 4; - return val; - } + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } - function Read_uint32_t(dataview) { - var val = dataview.getUint32(dataview.readOffset, littleEndian); - dataview.readOffset += 4; - return val; - } + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + }; - function Read_aiVector3D(stream) { - var v = new aiVector3D(); - v.x = readFloat(stream); - v.y = readFloat(stream); - v.z = readFloat(stream); - return v; - } + overridePropsRenamePath = function (fiber, oldPath, newPath) { + fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); - function Read_aiColor3D(stream) { - var c = new aiColor3D(); - c.r = readFloat(stream); - c.g = readFloat(stream); - c.b = readFloat(stream); - return c; - } + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } - function Read_aiQuaternion(stream) { - var v = new aiQuaternion(); - v.w = readFloat(stream); - v.x = readFloat(stream); - v.y = readFloat(stream); - v.z = readFloat(stream); - return v; - } + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + }; - function Read_aiString(stream) { - var s = new aiString(); - var stringlengthbytes = Read_unsigned_int(stream); - stream.ReadBytes(s.data, 1, stringlengthbytes); - return s.toString(); - } + scheduleUpdate = function (fiber) { + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + }; - function Read_aiVertexWeight(stream) { - var w = new aiVertexWeight(); - w.mVertexId = Read_unsigned_int(stream); - w.mWeight = readFloat(stream); - return w; - } + setErrorHandler = function (newShouldErrorImpl) { + shouldErrorImpl = newShouldErrorImpl; + }; - function Read_aiMatrix4x4(stream) { - var m = new aiMatrix4(); + setSuspenseHandler = function (newShouldSuspendImpl) { + shouldSuspendImpl = newShouldSuspendImpl; + }; + } - for (let i = 0; i < 4; ++i) { - for (let i2 = 0; i2 < 4; ++i2) { - m.elements[i][i2] = readFloat(stream); - } - } + function findHostInstanceByFiber(fiber) { + var hostFiber = findCurrentHostFiber(fiber); - return m; - } + if (hostFiber === null) { + return null; + } - function Read_aiVectorKey(stream) { - var v = new aiVectorKey(); - v.mTime = Read_double(stream); - v.mValue = Read_aiVector3D(stream); - return v; - } + return hostFiber.stateNode; + } - function Read_aiQuatKey(stream) { - var v = new aiQuatKey(); - v.mTime = Read_double(stream); - v.mValue = Read_aiQuaternion(stream); - return v; - } + function emptyFindFiberByHostInstance(instance) { + return null; + } - function ReadArray_aiVertexWeight(stream, data, size) { - for (let i = 0; i < size; i++) data[i] = Read_aiVertexWeight(stream); - } + function getCurrentFiberForDevTools() { + return current; + } - function ReadArray_aiVectorKey(stream, data, size) { - for (let i = 0; i < size; i++) data[i] = Read_aiVectorKey(stream); - } + function injectIntoDevTools(devToolsConfig) { + var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + return injectInternals({ + bundleType: devToolsConfig.bundleType, + version: devToolsConfig.version, + rendererPackageName: devToolsConfig.rendererPackageName, + rendererConfig: devToolsConfig.rendererConfig, + overrideHookState: overrideHookState, + overrideHookStateDeletePath: overrideHookStateDeletePath, + overrideHookStateRenamePath: overrideHookStateRenamePath, + overrideProps: overrideProps, + overridePropsDeletePath: overridePropsDeletePath, + overridePropsRenamePath: overridePropsRenamePath, + setErrorHandler: setErrorHandler, + setSuspenseHandler: setSuspenseHandler, + scheduleUpdate: scheduleUpdate, + currentDispatcherRef: ReactCurrentDispatcher, + findHostInstanceByFiber: findHostInstanceByFiber, + findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, + // React Refresh + findHostInstancesForRefresh: findHostInstancesForRefresh , + scheduleRefresh: scheduleRefresh , + scheduleRoot: scheduleRoot , + setRefreshHandler: setRefreshHandler , + // Enables DevTools to append owner stacks to error messages in DEV mode. + getCurrentFiber: getCurrentFiberForDevTools , + // Enables DevTools to detect reconciler version rather than renderer version + // which may not match for third party renderers. + reconcilerVersion: ReactVersion + }); + } - function ReadArray_aiQuatKey(stream, data, size) { - for (let i = 0; i < size; i++) data[i] = Read_aiQuatKey(stream); - } + exports.attemptContinuousHydration = attemptContinuousHydration; + exports.attemptHydrationAtCurrentPriority = attemptHydrationAtCurrentPriority; + exports.attemptSynchronousHydration = attemptSynchronousHydration; + exports.batchedUpdates = batchedUpdates; + exports.createComponentSelector = createComponentSelector; + exports.createContainer = createContainer; + exports.createHasPseudoClassSelector = createHasPseudoClassSelector; + exports.createHydrationContainer = createHydrationContainer; + exports.createPortal = createPortal; + exports.createRoleSelector = createRoleSelector; + exports.createTestNameSelector = createTestNameSelector; + exports.createTextSelector = createTextSelector; + exports.deferredUpdates = deferredUpdates; + exports.discreteUpdates = discreteUpdates; + exports.findAllNodes = findAllNodes; + exports.findBoundingRects = findBoundingRects; + exports.findHostInstance = findHostInstance; + exports.findHostInstanceWithNoPortals = findHostInstanceWithNoPortals; + exports.findHostInstanceWithWarning = findHostInstanceWithWarning; + exports.flushControlled = flushControlled; + exports.flushPassiveEffects = flushPassiveEffects; + exports.flushSync = flushSync; + exports.focusWithin = focusWithin; + exports.getCurrentUpdatePriority = getCurrentUpdatePriority; + exports.getFindAllNodesFailureDescription = getFindAllNodesFailureDescription; + exports.getPublicRootInstance = getPublicRootInstance; + exports.injectIntoDevTools = injectIntoDevTools; + exports.isAlreadyRendering = isAlreadyRendering; + exports.observeVisibleRects = observeVisibleRects; + exports.registerMutableSourceForHydration = registerMutableSourceForHydration; + exports.runWithPriority = runWithPriority; + exports.shouldError = shouldError; + exports.shouldSuspend = shouldSuspend; + exports.updateContainer = updateContainer; + return exports; + }; + } + return reactReconciler_development.exports; +} - function ReadBounds(stream, T - /*p*/ - , n) { - // not sure what to do here, the data isn't really useful. - return stream.Seek(sizeof(T) * n, aiOrigin_CUR); // eslint-disable-line no-undef - } +(function (module) { - function ai_assert(bool) { - if (!bool) throw 'asset failed'; - } + if (process.env.NODE_ENV === 'production') { + module.exports = requireReactReconciler_production_min(); + } else { + module.exports = requireReactReconciler_development(); + } +} (reactReconciler)); - function ReadBinaryNode(stream, parent, depth) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AINODE); - /*uint32_t size =*/ - - Read_uint32_t(stream); - var node = new aiNode(); - node.mParent = parent; - node.mDepth = depth; - node.mName = Read_aiString(stream); - node.mTransformation = Read_aiMatrix4x4(stream); - node.mNumChildren = Read_unsigned_int(stream); - node.mNumMeshes = Read_unsigned_int(stream); - - if (node.mNumMeshes) { - node.mMeshes = []; - - for (let i = 0; i < node.mNumMeshes; ++i) { - node.mMeshes[i] = Read_unsigned_int(stream); - } - } +var Reconciler = /*@__PURE__*/getDefaultExportFromCjs(reactReconciler.exports); - if (node.mNumChildren) { - node.mChildren = []; +function shallowEqualArrays(arrA, arrB, equal = (a, b) => a === b) { + if (arrA === arrB) return true; + if (!arrA || !arrB) return false; + const len = arrA.length; + if (arrB.length !== len) return false; - for (let i = 0; i < node.mNumChildren; ++i) { - var node2 = ReadBinaryNode(stream, node, depth++); - node.mChildren[i] = node2; - } - } + for (let i = 0; i < len; i++) if (!equal(arrA[i], arrB[i])) return false; - return node; - } // ----------------------------------------------------------------------------------- + return true; +} +const globalCache = []; - function ReadBinaryBone(stream, b) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIBONE); - /*uint32_t size =*/ +function query(fn, keys, preload = false, config = {}) { + for (const entry of globalCache) { + // Find a match + if (shallowEqualArrays(keys, entry.keys, entry.equal)) { + // If we're pre-loading and the element is present, just return + if (preload) return undefined; // If an error occurred, throw - Read_uint32_t(stream); - b.mName = Read_aiString(stream); - b.mNumWeights = Read_unsigned_int(stream); - b.mOffsetMatrix = Read_aiMatrix4x4(stream); // for the moment we write dumb min/max values for the bones, too. - // maybe I'll add a better, hash-like solution later + if (Object.prototype.hasOwnProperty.call(entry, 'error')) throw entry.error; // If a response was successful, return - if (shortened) { - ReadBounds(stream, b.mWeights, b.mNumWeights); - } else { - // else write as usual - b.mWeights = []; - ReadArray_aiVertexWeight(stream, b.mWeights, b.mNumWeights); - } + if (Object.prototype.hasOwnProperty.call(entry, 'response')) return entry.response; // If the promise is still unresolved, throw - return b; + if (!preload) throw entry.promise; } + } // The request is new or has changed. - function ReadBinaryMesh(stream, mesh) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIMESH); - /*uint32_t size =*/ - - Read_uint32_t(stream); - mesh.mPrimitiveTypes = Read_unsigned_int(stream); - mesh.mNumVertices = Read_unsigned_int(stream); - mesh.mNumFaces = Read_unsigned_int(stream); - mesh.mNumBones = Read_unsigned_int(stream); - mesh.mMaterialIndex = Read_unsigned_int(stream); - mesh.mNumUVComponents = []; // first of all, write bits for all existent vertex components - - var c = Read_unsigned_int(stream); - if (c & ASSBIN_MESH_HAS_POSITIONS) { - if (shortened) { - ReadBounds(stream, mesh.mVertices, mesh.mNumVertices); - } else { - // else write as usual - mesh.mVertices = []; - mesh.mVertexBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); - stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); - } + const entry = { + keys, + equal: config.equal, + promise: // Execute the promise + fn(...keys) // When it resolves, store its value + .then(response => entry.response = response) // Remove the entry if a lifespan was given + .then(() => { + if (config.lifespan && config.lifespan > 0) { + setTimeout(() => { + const index = globalCache.indexOf(entry); + if (index !== -1) globalCache.splice(index, 1); + }, config.lifespan); } + }) // Store caught errors, they will be thrown in the render-phase to bubble into an error-bound + .catch(error => entry.error = error) + }; // Register the entry - if (c & ASSBIN_MESH_HAS_NORMALS) { - if (shortened) { - ReadBounds(stream, mesh.mNormals, mesh.mNumVertices); - } else { - // else write as usual - mesh.mNormals = []; - mesh.mNormalBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); - stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); - } - } + globalCache.push(entry); // And throw the promise, this yields control back to React - if (c & ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS) { - if (shortened) { - ReadBounds(stream, mesh.mTangents, mesh.mNumVertices); - ReadBounds(stream, mesh.mBitangents, mesh.mNumVertices); - } else { - // else write as usual - mesh.mTangents = []; - mesh.mTangentBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); - stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); - mesh.mBitangents = []; - mesh.mBitangentBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); - stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); - } - } + if (!preload) throw entry.promise; + return undefined; +} - for (let n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) { - if (!(c & ASSBIN_MESH_HAS_COLOR(n))) break; +const suspend = (fn, keys, config) => query(fn, keys, false, config); - if (shortened) { - ReadBounds(stream, mesh.mColors[n], mesh.mNumVertices); - } else { - // else write as usual - mesh.mColors[n] = []; - mesh.mColorBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 4 * 4); - stream.Seek(mesh.mNumVertices * 4 * 4, aiOrigin_CUR); - } - } +const isOrthographicCamera = def => def && def.isOrthographicCamera; // React currently throws a warning when using useLayoutEffect on the server. +// To get around it, we can conditionally useEffect on the server (no-op) and +// useLayoutEffect on the client. - mesh.mTexCoordsBuffers = []; +const isSSR$2 = typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); +const useIsomorphicLayoutEffect$1 = isSSR$2 ? React.useEffect : React.useLayoutEffect; +function useMutableCallback(fn) { + const ref = React.useRef(fn); + useIsomorphicLayoutEffect$1(() => void (ref.current = fn), [fn]); + return ref; +} +function Block({ + set +}) { + useIsomorphicLayoutEffect$1(() => { + set(new Promise(() => null)); + return () => set(false); + }, [set]); + return null; +} +class ErrorBoundary extends React.Component { + constructor(...args) { + super(...args); + this.state = { + error: false + }; + } - for (let n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) { - if (!(c & ASSBIN_MESH_HAS_TEXCOORD(n))) break; // write number of UV components + componentDidCatch(error) { + this.props.set(error); + } - mesh.mNumUVComponents[n] = Read_unsigned_int(stream); + render() { + return this.state.error ? null : this.props.children; + } - if (shortened) { - ReadBounds(stream, mesh.mTextureCoords[n], mesh.mNumVertices); - } else { - // else write as usual - mesh.mTextureCoords[n] = []; //note that assbin always writes 3d texcoords +} - mesh.mTexCoordsBuffers[n] = []; +ErrorBoundary.getDerivedStateFromError = () => ({ + error: true +}); - for (let uv = 0; uv < mesh.mNumVertices; uv++) { - mesh.mTexCoordsBuffers[n].push(readFloat(stream)); - mesh.mTexCoordsBuffers[n].push(readFloat(stream)); - readFloat(stream); - } - } - } // write faces. There are no floating-point calculations involved - // in these, so we can write a simple hash over the face data - // to the dump file. We generate a single 32 Bit hash for 512 faces - // using Assimp's standard hashing function. +const DEFAULT = '__default'; +const isDiffSet = def => def && !!def.memoized && !!def.changes; +function calculateDpr(dpr) { + return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], window.devicePixelRatio), dpr[1]) : dpr; +} +/** + * Returns instance root state + */ +const getRootState = obj => { + var _r3f; - if (shortened) { - Read_unsigned_int(stream); - } else { - // else write as usual - // if there are less than 2^16 vertices, we can simply use 16 bit integers ... - mesh.mFaces = []; - mesh.mIndexArray = []; + return (_r3f = obj.__r3f) == null ? void 0 : _r3f.root.getState(); +}; +// A collection of compare functions +const is$1 = { + obj: a => a === Object(a) && !is$1.arr(a) && typeof a !== 'function', + fun: a => typeof a === 'function', + str: a => typeof a === 'string', + num: a => typeof a === 'number', + boo: a => typeof a === 'boolean', + und: a => a === void 0, + arr: a => Array.isArray(a), - for (let i = 0; i < mesh.mNumFaces; ++i) { - var f = mesh.mFaces[i] = new aiFace(); // BOOST_STATIC_ASSERT(AI_MAX_FACE_INDICES <= 0xffff); + equ(a, b, { + arrays = 'shallow', + objects = 'reference', + strict = true + } = {}) { + // Wrong type or one of the two undefined, doesn't match + if (typeof a !== typeof b || !!a !== !!b) return false; // Atomic, just compare a against b - f.mNumIndices = Read_uint16_t(stream); - f.mIndices = []; + if (is$1.str(a) || is$1.num(a)) return a === b; + const isObj = is$1.obj(a); + if (isObj && objects === 'reference') return a === b; + const isArr = is$1.arr(a); + if (isArr && arrays === 'reference') return a === b; // Array or Object, shallow compare first to see if it's a match - for (let a = 0; a < f.mNumIndices; ++a) { - if (mesh.mNumVertices < 1 << 16) { - f.mIndices[a] = Read_uint16_t(stream); - } else { - f.mIndices[a] = Read_unsigned_int(stream); - } - } + if ((isArr || isObj) && a === b) return true; // Last resort, go through keys - if (f.mNumIndices === 3) { - mesh.mIndexArray.push(f.mIndices[0]); - mesh.mIndexArray.push(f.mIndices[1]); - mesh.mIndexArray.push(f.mIndices[2]); - } else if (f.mNumIndices === 4) { - mesh.mIndexArray.push(f.mIndices[0]); - mesh.mIndexArray.push(f.mIndices[1]); - mesh.mIndexArray.push(f.mIndices[2]); - mesh.mIndexArray.push(f.mIndices[2]); - mesh.mIndexArray.push(f.mIndices[3]); - mesh.mIndexArray.push(f.mIndices[0]); - } else { - throw new Error("Sorry, can't currently triangulate polys. Use the triangulate preprocessor in Assimp."); - } - } - } // write bones + let i; + for (i in a) if (!(i in b)) return false; - if (mesh.mNumBones) { - mesh.mBones = []; + for (i in strict ? b : a) if (a[i] !== b[i]) return false; - for (let a = 0; a < mesh.mNumBones; ++a) { - mesh.mBones[a] = new aiBone(); - ReadBinaryBone(stream, mesh.mBones[a]); - } - } + if (is$1.und(i)) { + if (isArr && a.length === 0 && b.length === 0) return true; + if (isObj && Object.keys(a).length === 0 && Object.keys(b).length === 0) return true; + if (a !== b) return false; } - function ReadBinaryMaterialProperty(stream, prop) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIMATERIALPROPERTY); - /*uint32_t size =*/ - - Read_uint32_t(stream); - prop.mKey = Read_aiString(stream); - prop.mSemantic = Read_unsigned_int(stream); - prop.mIndex = Read_unsigned_int(stream); - prop.mDataLength = Read_unsigned_int(stream); - prop.mType = Read_unsigned_int(stream); - prop.mData = []; - stream.ReadBytes(prop.mData, 1, prop.mDataLength); - } // ----------------------------------------------------------------------------------- - - - function ReadBinaryMaterial(stream, mat) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIMATERIAL); - /*uint32_t size =*/ - - Read_uint32_t(stream); - mat.mNumAllocated = mat.mNumProperties = Read_unsigned_int(stream); - - if (mat.mNumProperties) { - if (mat.mProperties) { - delete mat.mProperties; - } + return true; + } - mat.mProperties = []; +}; // Collects nodes and materials from a THREE.Object3D - for (let i = 0; i < mat.mNumProperties; ++i) { - mat.mProperties[i] = new aiMaterialProperty(); - ReadBinaryMaterialProperty(stream, mat.mProperties[i]); - } - } - } +function dispose(obj) { + if (obj.dispose && obj.type !== 'Scene') obj.dispose(); - function ReadBinaryNodeAnim(stream, nd) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AINODEANIM); - /*uint32_t size =*/ - - Read_uint32_t(stream); - nd.mNodeName = Read_aiString(stream); - nd.mNumPositionKeys = Read_unsigned_int(stream); - nd.mNumRotationKeys = Read_unsigned_int(stream); - nd.mNumScalingKeys = Read_unsigned_int(stream); - nd.mPreState = Read_unsigned_int(stream); - nd.mPostState = Read_unsigned_int(stream); - - if (nd.mNumPositionKeys) { - if (shortened) { - ReadBounds(stream, nd.mPositionKeys, nd.mNumPositionKeys); - } else { - // else write as usual - nd.mPositionKeys = []; - ReadArray_aiVectorKey(stream, nd.mPositionKeys, nd.mNumPositionKeys); - } - } + for (const p in obj) { + p.dispose == null ? void 0 : p.dispose(); + delete obj[p]; + } +} // Each object in the scene carries a small LocalState descriptor - if (nd.mNumRotationKeys) { - if (shortened) { - ReadBounds(stream, nd.mRotationKeys, nd.mNumRotationKeys); - } else { - // else write as usual - nd.mRotationKeys = []; - ReadArray_aiQuatKey(stream, nd.mRotationKeys, nd.mNumRotationKeys); - } - } +function prepare(object, state) { + const instance = object; - if (nd.mNumScalingKeys) { - if (shortened) { - ReadBounds(stream, nd.mScalingKeys, nd.mNumScalingKeys); - } else { - // else write as usual - nd.mScalingKeys = []; - ReadArray_aiVectorKey(stream, nd.mScalingKeys, nd.mNumScalingKeys); - } - } - } + if (state != null && state.primitive || !instance.__r3f) { + instance.__r3f = { + type: '', + root: null, + previousAttach: null, + memoizedProps: {}, + eventCount: 0, + handlers: {}, + objects: [], + parent: null, + ...state + }; + } - function ReadBinaryAnim(stream, anim) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIANIMATION); - /*uint32_t size =*/ + return object; +} + +function resolve(instance, key) { + let target = instance; - Read_uint32_t(stream); - anim.mName = Read_aiString(stream); - anim.mDuration = Read_double(stream); - anim.mTicksPerSecond = Read_double(stream); - anim.mNumChannels = Read_unsigned_int(stream); + if (key.includes('-')) { + const entries = key.split('-'); + const last = entries.pop(); + target = entries.reduce((acc, key) => acc[key], instance); + return { + target, + key: last + }; + } else return { + target, + key + }; +} // Checks if a dash-cased string ends with an integer - if (anim.mNumChannels) { - anim.mChannels = []; - for (let a = 0; a < anim.mNumChannels; ++a) { - anim.mChannels[a] = new aiNodeAnim(); - ReadBinaryNodeAnim(stream, anim.mChannels[a]); - } - } +const INDEX_REGEX = /-\d+$/; +function attach(parent, child, type) { + if (is$1.str(type)) { + // If attaching into an array (foo-0), create one + if (INDEX_REGEX.test(type)) { + const root = type.replace(INDEX_REGEX, ''); + const { + target, + key + } = resolve(parent, root); + if (!Array.isArray(target[key])) target[key] = []; } - function ReadBinaryTexture(stream, tex) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AITEXTURE); - /*uint32_t size =*/ + const { + target, + key + } = resolve(parent, type); + child.__r3f.previousAttach = target[key]; + target[key] = child; + } else child.__r3f.previousAttach = type(parent, child); +} +function detach(parent, child, type) { + var _child$__r3f, _child$__r3f2; - Read_uint32_t(stream); - tex.mWidth = Read_unsigned_int(stream); - tex.mHeight = Read_unsigned_int(stream); - stream.ReadBytes(tex.achFormatHint, 1, 4); + if (is$1.str(type)) { + const { + target, + key + } = resolve(parent, type); + const previous = child.__r3f.previousAttach; // When the previous value was undefined, it means the value was never set to begin with - if (!shortened) { - if (!tex.mHeight) { - tex.pcData = []; - stream.ReadBytes(tex.pcData, 1, tex.mWidth); - } else { - tex.pcData = []; - stream.ReadBytes(tex.pcData, 1, tex.mWidth * tex.mHeight * 4); - } - } - } + if (previous === undefined) delete target[key]; // Otherwise set the previous value + else target[key] = previous; + } else (_child$__r3f = child.__r3f) == null ? void 0 : _child$__r3f.previousAttach == null ? void 0 : _child$__r3f.previousAttach(parent, child); - function ReadBinaryLight(stream, l) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AILIGHT); - /*uint32_t size =*/ + (_child$__r3f2 = child.__r3f) == null ? true : delete _child$__r3f2.previousAttach; +} // This function prepares a set of changes to be applied to the instance - Read_uint32_t(stream); - l.mName = Read_aiString(stream); - l.mType = Read_unsigned_int(stream); +function diffProps(instance, { + children: cN, + key: kN, + ref: rN, + ...props +}, { + children: cP, + key: kP, + ref: rP, + ...previous +} = {}, remove = false) { + var _instance$__r3f; - if (l.mType != aiLightSource_DIRECTIONAL) { - l.mAttenuationConstant = readFloat(stream); - l.mAttenuationLinear = readFloat(stream); - l.mAttenuationQuadratic = readFloat(stream); - } + const localState = (_instance$__r3f = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f : {}; + const entries = Object.entries(props); + const changes = []; // Catch removed props, prepend them so they can be reset or removed - l.mColorDiffuse = Read_aiColor3D(stream); - l.mColorSpecular = Read_aiColor3D(stream); - l.mColorAmbient = Read_aiColor3D(stream); + if (remove) { + const previousKeys = Object.keys(previous); - if (l.mType == aiLightSource_SPOT) { - l.mAngleInnerCone = readFloat(stream); - l.mAngleOuterCone = readFloat(stream); - } + for (let i = 0; i < previousKeys.length; i++) { + if (!props.hasOwnProperty(previousKeys[i])) entries.unshift([previousKeys[i], DEFAULT + 'remove']); } + } - function ReadBinaryCamera(stream, cam) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AICAMERA); - /*uint32_t size =*/ - - Read_uint32_t(stream); - cam.mName = Read_aiString(stream); - cam.mPosition = Read_aiVector3D(stream); - cam.mLookAt = Read_aiVector3D(stream); - cam.mUp = Read_aiVector3D(stream); - cam.mHorizontalFOV = readFloat(stream); - cam.mClipPlaneNear = readFloat(stream); - cam.mClipPlaneFar = readFloat(stream); - cam.mAspect = readFloat(stream); - } + entries.forEach(([key, value]) => { + var _instance$__r3f2; - function ReadBinaryScene(stream, scene) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AISCENE); - /*uint32_t size =*/ - - Read_uint32_t(stream); - scene.mFlags = Read_unsigned_int(stream); - scene.mNumMeshes = Read_unsigned_int(stream); - scene.mNumMaterials = Read_unsigned_int(stream); - scene.mNumAnimations = Read_unsigned_int(stream); - scene.mNumTextures = Read_unsigned_int(stream); - scene.mNumLights = Read_unsigned_int(stream); - scene.mNumCameras = Read_unsigned_int(stream); // Read node graph - - scene.mRootNode = new aiNode(); - scene.mRootNode = ReadBinaryNode(stream, null, 0); // Read all meshes - - if (scene.mNumMeshes) { - scene.mMeshes = []; - - for (let i = 0; i < scene.mNumMeshes; ++i) { - scene.mMeshes[i] = new aiMesh(); - ReadBinaryMesh(stream, scene.mMeshes[i]); - } - } // Read materials + // Bail out on primitive object + if ((_instance$__r3f2 = instance.__r3f) != null && _instance$__r3f2.primitive && key === 'object') return; // When props match bail out + if (is$1.equ(value, previous[key])) return; // Collect handlers and bail out - if (scene.mNumMaterials) { - scene.mMaterials = []; + if (/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key)) return changes.push([key, value, true, []]); // Split dashed props - for (let i = 0; i < scene.mNumMaterials; ++i) { - scene.mMaterials[i] = new aiMaterial(); - ReadBinaryMaterial(stream, scene.mMaterials[i]); - } - } // Read all animations + let entries = []; + if (key.includes('-')) entries = key.split('-'); + changes.push([key, value, false, entries]); + }); + const memoized = { ...props + }; + if (localState.memoizedProps && localState.memoizedProps.args) memoized.args = localState.memoizedProps.args; + if (localState.memoizedProps && localState.memoizedProps.attach) memoized.attach = localState.memoizedProps.attach; + return { + memoized, + changes + }; +} // This function applies a set of changes to the instance +function applyProps$1(instance, data) { + var _instance$__r3f3, _root$getState; - if (scene.mNumAnimations) { - scene.mAnimations = []; + // Filter equals, events and reserved props + const localState = (_instance$__r3f3 = instance.__r3f) != null ? _instance$__r3f3 : {}; + const root = localState.root; + const rootState = (_root$getState = root == null ? void 0 : root.getState == null ? void 0 : root.getState()) != null ? _root$getState : {}; + const { + memoized, + changes + } = isDiffSet(data) ? data : diffProps(instance, data); + const prevHandlers = localState.eventCount; // Prepare memoized props - for (let i = 0; i < scene.mNumAnimations; ++i) { - scene.mAnimations[i] = new aiAnimation(); - ReadBinaryAnim(stream, scene.mAnimations[i]); - } - } // Read all textures + if (instance.__r3f) instance.__r3f.memoizedProps = memoized; + changes.forEach(([key, value, isEvent, keys]) => { + let currentInstance = instance; + let targetProp = currentInstance[key]; // Revolve dashed props + if (keys.length) { + targetProp = keys.reduce((acc, key) => acc[key], instance); // If the target is atomic, it forces us to switch the root - if (scene.mNumTextures) { - scene.mTextures = []; + if (!(targetProp && targetProp.set)) { + const [name, ...reverseEntries] = keys.reverse(); + currentInstance = reverseEntries.reverse().reduce((acc, key) => acc[key], instance); + key = name; + } + } // https://github.com/mrdoob/three.js/issues/21209 + // HMR/fast-refresh relies on the ability to cancel out props, but threejs + // has no means to do this. Hence we curate a small collection of value-classes + // with their respective constructor/set arguments + // For removed props, try to set default values, if possible - for (let i = 0; i < scene.mNumTextures; ++i) { - scene.mTextures[i] = new aiTexture(); - ReadBinaryTexture(stream, scene.mTextures[i]); - } - } // Read lights + if (value === DEFAULT + 'remove') { + if (targetProp && targetProp.constructor) { + var _memoized$args; - if (scene.mNumLights) { - scene.mLights = []; + // use the prop constructor to find the default it should be + value = new targetProp.constructor(...((_memoized$args = memoized.args) != null ? _memoized$args : [])); + } else if (currentInstance.constructor) { + var _currentInstance$__r; - for (let i = 0; i < scene.mNumLights; ++i) { - scene.mLights[i] = new aiLight(); - ReadBinaryLight(stream, scene.mLights[i]); - } - } // Read cameras + // create a blank slate of the instance and copy the particular parameter. + // @ts-ignore + const defaultClassCall = new currentInstance.constructor(...((_currentInstance$__r = currentInstance.__r3f.memoizedProps.args) != null ? _currentInstance$__r : [])); + value = defaultClassCall[targetProp]; // destory the instance + if (defaultClassCall.dispose) defaultClassCall.dispose(); // instance does not have constructor, just set it to 0 + } else { + value = 0; + } + } // Deal with pointer events ... - if (scene.mNumCameras) { - scene.mCameras = []; - for (let i = 0; i < scene.mNumCameras; ++i) { - scene.mCameras[i] = new aiCamera(); - ReadBinaryCamera(stream, scene.mCameras[i]); - } + if (isEvent) { + if (value) localState.handlers[key] = value;else delete localState.handlers[key]; + localState.eventCount = Object.keys(localState.handlers).length; + } // Special treatment for objects with support for set/copy, and layers + else if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof Layers)) { + // If value is an array + if (Array.isArray(value)) { + if (targetProp.fromArray) targetProp.fromArray(value);else targetProp.set(...value); + } // Test again target.copy(class) next ... + else if (targetProp.copy && value && value.constructor && targetProp.constructor.name === value.constructor.name) { + targetProp.copy(value); + } // If nothing else fits, just set the single value, ignore undefined + // https://github.com/pmndrs/react-three-fiber/issues/274 + else if (value !== undefined) { + const isColor = targetProp instanceof Color; // Allow setting array scalars + + if (!isColor && targetProp.setScalar) targetProp.setScalar(value); // Layers have no copy function, we must therefore copy the mask property + else if (targetProp instanceof Layers && value instanceof Layers) targetProp.mask = value.mask; // Otherwise just set ... + else targetProp.set(value); // For versions of three which don't support THREE.ColorManagement, + // Auto-convert sRGB colors + // https://github.com/pmndrs/react-three-fiber/issues/344 + + const supportsColorManagement = ('ColorManagement' in THREE); + if (!supportsColorManagement && !rootState.linear && isColor) targetProp.convertSRGBToLinear(); + } // Else, just overwrite the value + + } else { + currentInstance[key] = value; // Auto-convert sRGB textures, for now ... + // https://github.com/pmndrs/react-three-fiber/issues/344 + + if (!rootState.linear && currentInstance[key] instanceof Texture) { + currentInstance[key].encoding = sRGBEncoding; } } - var aiOrigin_CUR = 0; - var aiOrigin_BEG = 1; - - function extendStream(stream) { - stream.readOffset = 0; + invalidateInstance(instance); + }); - stream.Seek = function (off, ori) { - if (ori == aiOrigin_CUR) { - stream.readOffset += off; - } + if (localState.parent && rootState.internal && instance.raycast && prevHandlers !== localState.eventCount) { + // Pre-emptively remove the instance from the interaction manager + const index = rootState.internal.interaction.indexOf(instance); + if (index > -1) rootState.internal.interaction.splice(index, 1); // Add the instance to the interaction manager only when it has handlers - if (ori == aiOrigin_BEG) { - stream.readOffset = off; - } - }; + if (localState.eventCount) rootState.internal.interaction.push(instance); + } // Call the update lifecycle when it is being updated, but only when it is part of the scene - stream.ReadBytes = function (buff, size, n) { - var bytes = size * n; - for (let i = 0; i < bytes; i++) buff[i] = Read_uint8_t(this); - }; + if (changes.length && instance.parent) updateInstance(instance); + return instance; +} +function invalidateInstance(instance) { + var _instance$__r3f4, _instance$__r3f4$root; - stream.subArray32 = function (start, end) { - var buff = this.buffer; - var newbuff = buff.slice(start, end); - return new Float32Array(newbuff); - }; + const state = (_instance$__r3f4 = instance.__r3f) == null ? void 0 : (_instance$__r3f4$root = _instance$__r3f4.root) == null ? void 0 : _instance$__r3f4$root.getState == null ? void 0 : _instance$__r3f4$root.getState(); + if (state && state.internal.frames === 0) state.invalidate(); +} +function updateInstance(instance) { + instance.onUpdate == null ? void 0 : instance.onUpdate(instance); +} +function updateCamera(camera, size) { + // https://github.com/pmndrs/react-three-fiber/issues/92 + // Do not mess with the camera if it belongs to the user + if (!camera.manual) { + if (isOrthographicCamera(camera)) { + camera.left = size.width / -2; + camera.right = size.width / 2; + camera.top = size.height / 2; + camera.bottom = size.height / -2; + } else { + camera.aspect = size.width / size.height; + } - stream.subArrayUint16 = function (start, end) { - var buff = this.buffer; - var newbuff = buff.slice(start, end); - return new Uint16Array(newbuff); - }; + camera.updateProjectionMatrix(); // https://github.com/pmndrs/react-three-fiber/issues/178 + // Update matrix world since the renderer is a frame late - stream.subArrayUint8 = function (start, end) { - var buff = this.buffer; - var newbuff = buff.slice(start, end); - return new Uint8Array(newbuff); - }; + camera.updateMatrixWorld(); + } +} +/** + * Safely sets a deeply-nested value on an object. + */ - stream.subArrayUint32 = function (start, end) { - var buff = this.buffer; - var newbuff = buff.slice(start, end); - return new Uint32Array(newbuff); - }; - } +function setDeep(obj, value, keys) { + const key = keys.pop(); + const target = keys.reduce((acc, key) => acc[key], obj); + return target[key] = value; +} - var shortened, compressed; +function makeId(event) { + return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId; +} // https://github.com/facebook/react/tree/main/packages/react-reconciler#getcurrenteventpriority +// Gives React a clue as to how import the current interaction is - function InternReadFile(pFiledata) { - var pScene = new aiScene(); - var stream = new DataView(pFiledata); - extendStream(stream); - stream.Seek(44, aiOrigin_CUR); // signature - /*unsigned int versionMajor =*/ +function getEventPriority() { + var _window, _window$event; - pScene.versionMajor = Read_unsigned_int(stream); - /*unsigned int versionMinor =*/ + let name = (_window = window) == null ? void 0 : (_window$event = _window.event) == null ? void 0 : _window$event.type; - pScene.versionMinor = Read_unsigned_int(stream); - /*unsigned int versionRevision =*/ + switch (name) { + case 'click': + case 'contextmenu': + case 'dblclick': + case 'pointercancel': + case 'pointerdown': + case 'pointerup': + return constants.exports.DiscreteEventPriority; - pScene.versionRevision = Read_unsigned_int(stream); - /*unsigned int compileFlags =*/ + case 'pointermove': + case 'pointerout': + case 'pointerover': + case 'pointerenter': + case 'pointerleave': + case 'wheel': + return constants.exports.ContinuousEventPriority; - pScene.compileFlags = Read_unsigned_int(stream); - shortened = Read_uint16_t(stream) > 0; - compressed = Read_uint16_t(stream) > 0; - if (shortened) throw 'Shortened binaries are not supported!'; - stream.Seek(256, aiOrigin_CUR); // original filename + default: + return constants.exports.DefaultEventPriority; + } +} +/** + * Release pointer captures. + * This is called by releasePointerCapture in the API, and when an object is removed. + */ - stream.Seek(128, aiOrigin_CUR); // options +function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) { + const captureData = captures.get(obj); - stream.Seek(64, aiOrigin_CUR); // padding + if (captureData) { + captures.delete(obj); // If this was the last capturing object for this pointer - if (compressed) { - var uncompressedSize = Read_uint32_t(stream); - var compressedSize = stream.FileSize() - stream.Tell(); - var compressedData = []; - stream.Read(compressedData, 1, compressedSize); - var uncompressedData = []; - uncompress(uncompressedData, uncompressedSize, compressedData, compressedSize); // eslint-disable-line no-undef + if (captures.size === 0) { + capturedMap.delete(pointerId); + captureData.target.releasePointerCapture(pointerId); + } + } +} - var buff = new ArrayBuffer(uncompressedData); - ReadBinaryScene(buff, pScene); - } else { - ReadBinaryScene(stream, pScene); - } +function removeInteractivity(store, object) { + const { + internal + } = store.getState(); // Removes every trace of an object from the data store - return pScene.toTHREE(); + internal.interaction = internal.interaction.filter(o => o !== object); + internal.initialHits = internal.initialHits.filter(o => o !== object); + internal.hovered.forEach((value, key) => { + if (value.eventObject === object || value.object === object) { + // Clear out intersects, they are outdated by now + internal.hovered.delete(key); } + }); + internal.capturedMap.forEach((captures, pointerId) => { + releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId); + }); +} +function createEvents(store) { + const temp = new Vector3(); + /** Calculates delta */ - return InternReadFile(buffer); + function calculateDistance(event) { + const { + internal + } = store.getState(); + const dx = event.offsetX - internal.initialClick[0]; + const dy = event.offsetY - internal.initialClick[1]; + return Math.round(Math.sqrt(dx * dx + dy * dy)); } -}); - -new Vector3(); + /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */ -new Vector3(); -new Ray(); + function filterPointerEvents(objects) { + return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => { + var _r3f; -function LWO3Parser(IFFParser) { - this.IFF = IFFParser; -} + return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers['onPointer' + name]; + })); + } -LWO3Parser.prototype = { - constructor: LWO3Parser, - parseBlock: function () { - this.IFF.debugger.offset = this.IFF.reader.offset; - this.IFF.debugger.closeForms(); - var blockID = this.IFF.reader.getIDTag(); - var length = this.IFF.reader.getUint32(); // size of data in bytes + function intersect(event, filter) { + const state = store.getState(); + const duplicates = new Set(); + const intersections = []; // Allow callers to eliminate event objects - this.IFF.debugger.dataOffset = this.IFF.reader.offset; - this.IFF.debugger.length = length; // Data types may be found in either LWO2 OR LWO3 spec + const eventsObjects = filter ? filter(state.internal.interaction) : state.internal.interaction; // Reset all raycaster cameras to undefined - switch (blockID) { - case 'FORM': - // form blocks may consist of sub -chunks or sub-forms - this.IFF.parseForm(length); - break; - // SKIPPED CHUNKS - // MISC skipped - - case 'ICON': // Thumbnail Icon Image - - case 'VMPA': // Vertex Map Parameter - - case 'BBOX': // bounding box - // case 'VMMD': - // case 'VTYP': - // normal maps can be specified, normally on models imported from other applications. Currently ignored - - case 'NORM': // ENVL FORM skipped - - case 'PRE ': - case 'POST': - case 'KEY ': - case 'SPAN': // CLIP FORM skipped - - case 'TIME': - case 'CLRS': - case 'CLRA': - case 'FILT': - case 'DITH': - case 'CONT': - case 'BRIT': - case 'SATR': - case 'HUE ': - case 'GAMM': - case 'NEGA': - case 'IFLT': - case 'PFLT': // Image Map Layer skipped - - case 'PROJ': - case 'AXIS': - case 'AAST': - case 'PIXB': - case 'STCK': // Procedural Textures skipped - - case 'VALU': // Gradient Textures skipped - - case 'PNAM': - case 'INAM': - case 'GRST': - case 'GREN': - case 'GRPT': - case 'FKEY': - case 'IKEY': // Texture Mapping Form skipped - - case 'CSYS': // Surface CHUNKs skipped - - case 'OPAQ': // top level 'opacity' checkbox - - case 'CMAP': // clip map - // Surface node CHUNKS skipped - // These mainly specify the node editor setup in LW - - case 'NLOC': - case 'NZOM': - case 'NVER': - case 'NSRV': - case 'NCRD': - case 'NMOD': - case 'NSEL': - case 'NPRW': - case 'NPLA': - case 'VERS': - case 'ENUM': - case 'TAG ': // Car Material CHUNKS - - case 'CGMD': - case 'CGTY': - case 'CGST': - case 'CGEN': - case 'CGTS': - case 'CGTE': - case 'OSMP': - case 'OMDE': - case 'OUTR': - case 'FLAG': - case 'TRNL': - case 'SHRP': - case 'RFOP': - case 'RSAN': - case 'TROP': - case 'RBLR': - case 'TBLR': - case 'CLRH': - case 'CLRF': - case 'ADTR': - case 'GLOW': - case 'LINE': - case 'ALPH': - case 'VCOL': - case 'ENAB': - this.IFF.debugger.skipped = true; - this.IFF.reader.skip(length); - break; - // Texture node chunks (not in spec) + eventsObjects.forEach(obj => { + const state = getRootState(obj); - case 'IPIX': // usePixelBlending + if (state) { + state.raycaster.camera = undefined; + } + }); - case 'IMIP': // useMipMaps + if (!state.previousRoot) { + // Make sure root-level pointer and ray are set up + state.events.compute == null ? void 0 : state.events.compute(event, state); + } // Collect events - case 'IMOD': // imageBlendingMode - case 'AMOD': // unknown + let hits = eventsObjects // Intersect objects + .flatMap(obj => { + const state = getRootState(obj); // Skip event handling when noEvents is set, or when the raycasters camera is null - case 'IINV': // imageInvertAlpha + if (!state || !state.events.enabled || state.raycaster.camera === null) return []; // When the camera is undefined we have to call the event layers update function - case 'INCR': // imageInvertColor + if (state.raycaster.camera === undefined) { + var _state$previousRoot; - case 'IAXS': // imageAxis ( for non-UV maps) + state.events.compute == null ? void 0 : state.events.compute(event, state, (_state$previousRoot = state.previousRoot) == null ? void 0 : _state$previousRoot.getState()); // If the camera is still undefined we have to skip this layer entirely - case 'IFOT': // imageFallofType + if (state.raycaster.camera === undefined) state.raycaster.camera = null; + } // Intersect object by object - case 'ITIM': // timing for animated textures - case 'IWRL': - case 'IUTI': - case 'IINX': - case 'IINY': - case 'IINZ': - case 'IREF': - // possibly a VX for reused texture nodes - if (length === 4) this.IFF.currentNode[blockID] = this.IFF.reader.getInt32();else this.IFF.reader.skip(length); - break; + return state.raycaster.camera ? state.raycaster.intersectObject(obj, true) : []; + }) // Sort by event priority and distance + .sort((a, b) => { + const aState = getRootState(a.object); + const bState = getRootState(b.object); + if (!aState || !bState) return 0; + return bState.events.priority - aState.events.priority || a.distance - b.distance; + }) // Filter out duplicates + .filter(item => { + const id = makeId(item); + if (duplicates.has(id)) return false; + duplicates.add(id); + return true; + }); // https://github.com/mrdoob/three.js/issues/16031 + // Allow custom userland intersect sort order, this likely only makes sense on the root filter - case 'OTAG': - this.IFF.parseObjectTag(); - break; + if (state.events.filter) hits = state.events.filter(hits, state); // Bubble up the events, find the event source (eventObject) - case 'LAYR': - this.IFF.parseLayer(length); - break; + for (const hit of hits) { + let eventObject = hit.object; // Bubble event up - case 'PNTS': - this.IFF.parsePoints(length); - break; + while (eventObject) { + var _r3f2; - case 'VMAP': - this.IFF.parseVertexMapping(length); - break; + if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({ ...hit, + eventObject + }); + eventObject = eventObject.parent; + } + } // If the interaction is captured, make all capturing targets part of the intersect. - case 'POLS': - this.IFF.parsePolygonList(length); - break; - case 'TAGS': - this.IFF.parseTagStrings(length); - break; + if ('pointerId' in event && state.internal.capturedMap.has(event.pointerId)) { + for (let captureData of state.internal.capturedMap.get(event.pointerId).values()) { + intersections.push(captureData.intersection); + } + } - case 'PTAG': - this.IFF.parsePolygonTagMapping(length); - break; + return intersections; + } + /** Handles intersections by forwarding them to handlers */ - case 'VMAD': - this.IFF.parseVertexMapping(length, true); - break; - // Misc CHUNKS - case 'DESC': - // Description Line - this.IFF.currentForm.description = this.IFF.reader.getString(); - break; + function handleIntersects(intersections, event, delta, callback) { + const { + raycaster, + pointer, + camera, + internal + } = store.getState(); // If anything has been found, forward it to the event listeners - case 'TEXT': - case 'CMNT': - case 'NCOM': - this.IFF.currentForm.comment = this.IFF.reader.getString(); - break; - // Envelope Form + if (intersections.length) { + const unprojectedPoint = temp.set(pointer.x, pointer.y, 0).unproject(camera); + const localState = { + stopped: false + }; - case 'NAME': - this.IFF.currentForm.channelName = this.IFF.reader.getString(); - break; - // Image Map Layer + for (const hit of intersections) { + const hasPointerCapture = id => { + var _internal$capturedMap, _internal$capturedMap2; - case 'WRAP': - this.IFF.currentForm.wrap = { - w: this.IFF.reader.getUint16(), - h: this.IFF.reader.getUint16() + return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false; }; - break; - - case 'IMAG': - var index = this.IFF.reader.getVariableLengthIndex(); - this.IFF.currentForm.imageIndex = index; - break; - // Texture Mapping Form - - case 'OREF': - this.IFF.currentForm.referenceObject = this.IFF.reader.getString(); - break; - - case 'ROID': - this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32(); - break; - // Surface Blocks - case 'SSHN': - this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString(); - break; + const setPointerCapture = id => { + const captureData = { + intersection: hit, + target: event.target + }; - case 'AOVN': - this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString(); - break; - // Nodal Blocks + if (internal.capturedMap.has(id)) { + // if the pointerId was previously captured, we add the hit to the + // event capturedMap. + internal.capturedMap.get(id).set(hit.eventObject, captureData); + } else { + // if the pointerId was not previously captured, we create a map + // containing the hitObject, and the hit. hitObject is used for + // faster access. + internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]])); + } // Call the original event now + event.target.setPointerCapture(id); + }; - case 'NSTA': - this.IFF.currentForm.disabled = this.IFF.reader.getUint16(); - break; + const releasePointerCapture = id => { + const captures = internal.capturedMap.get(id); - case 'NRNM': - this.IFF.currentForm.realName = this.IFF.reader.getString(); - break; + if (captures) { + releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id); + } + }; // Add native event props - case 'NNME': - this.IFF.currentForm.refName = this.IFF.reader.getString(); - this.IFF.currentSurface.nodes[this.IFF.currentForm.refName] = this.IFF.currentForm; - break; - // Nodal Blocks : connections - case 'INME': - if (!this.IFF.currentForm.nodeName) this.IFF.currentForm.nodeName = []; - this.IFF.currentForm.nodeName.push(this.IFF.reader.getString()); - break; + let extractEventProps = {}; // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones. - case 'IINN': - if (!this.IFF.currentForm.inputNodeName) this.IFF.currentForm.inputNodeName = []; - this.IFF.currentForm.inputNodeName.push(this.IFF.reader.getString()); - break; + for (let prop in event) { + let property = event[prop]; // Only copy over atomics, leave functions alone as these should be + // called as event.nativeEvent.fn() - case 'IINM': - if (!this.IFF.currentForm.inputName) this.IFF.currentForm.inputName = []; - this.IFF.currentForm.inputName.push(this.IFF.reader.getString()); - break; + if (typeof property !== 'function') extractEventProps[prop] = property; + } - case 'IONM': - if (!this.IFF.currentForm.inputOutputName) this.IFF.currentForm.inputOutputName = []; - this.IFF.currentForm.inputOutputName.push(this.IFF.reader.getString()); - break; + let raycastEvent = { ...hit, + ...extractEventProps, + pointer, + intersections, + stopped: localState.stopped, + delta, + unprojectedPoint, + ray: raycaster.ray, + camera: camera, + // Hijack stopPropagation, which just sets a flag + stopPropagation: () => { + // https://github.com/pmndrs/react-three-fiber/issues/596 + // Events are not allowed to stop propagation if the pointer has been captured + const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId); // We only authorize stopPropagation... - case 'FNAM': - this.IFF.currentForm.fileName = this.IFF.reader.getString(); - break; + if ( // ...if this pointer hasn't been captured + !capturesForPointer || // ... or if the hit object is capturing the pointer + capturesForPointer.has(hit.eventObject)) { + raycastEvent.stopped = localState.stopped = true; // Propagation is stopped, remove all other hover records + // An event handler is only allowed to flush other handlers if it is hovered itself - case 'CHAN': - // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored - if (length === 4) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();else this.IFF.reader.skip(length); - break; - // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format + if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) { + // Objects cannot flush out higher up objects that have already caught the event + const higher = intersections.slice(0, intersections.indexOf(hit)); + cancelPointer([...higher, hit]); + } + } + }, + // there should be a distinction between target and currentTarget + target: { + hasPointerCapture, + setPointerCapture, + releasePointerCapture + }, + currentTarget: { + hasPointerCapture, + setPointerCapture, + releasePointerCapture + }, + nativeEvent: event + }; // Call subscribers - case 'SMAN': - var maxSmoothingAngle = this.IFF.reader.getFloat32(); - this.IFF.currentSurface.attributes.smooth = maxSmoothingAngle < 0 ? false : true; - break; - // LWO2: Basic Surface Parameters + callback(raycastEvent); // Event bubbling may be interrupted by stopPropagation - case 'COLR': - this.IFF.currentSurface.attributes.Color = { - value: this.IFF.reader.getFloat32Array(3) - }; - this.IFF.reader.skip(2); // VX: envelope + if (localState.stopped === true) break; + } + } - break; + return intersections; + } - case 'LUMI': - this.IFF.currentSurface.attributes.Luminosity = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + function cancelPointer(intersections) { + const { + internal + } = store.getState(); + Array.from(internal.hovered.values()).forEach(hoveredObj => { + // When no objects were hit or the the hovered object wasn't found underneath the cursor + // we call onPointerOut and delete the object from the hovered-elements map + if (!intersections.length || !intersections.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) { + const eventObject = hoveredObj.eventObject; + const instance = eventObject.__r3f; + const handlers = instance == null ? void 0 : instance.handlers; + internal.hovered.delete(makeId(hoveredObj)); - case 'SPEC': - this.IFF.currentSurface.attributes.Specular = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + if (instance != null && instance.eventCount) { + // Clear out intersects, they are outdated by now + const data = { ...hoveredObj, + intersections + }; + handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data); + handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data); + } + } + }); + } - case 'DIFF': - this.IFF.currentSurface.attributes.Diffuse = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + const handlePointer = name => { + // Deal with cancelation + switch (name) { + case 'onPointerLeave': + case 'onPointerCancel': + return () => cancelPointer([]); - case 'REFL': - this.IFF.currentSurface.attributes.Reflection = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + case 'onLostPointerCapture': + return event => { + const { + internal + } = store.getState(); - case 'GLOS': - this.IFF.currentSurface.attributes.Glossiness = { - value: this.IFF.reader.getFloat32() + if ('pointerId' in event && !internal.capturedMap.has(event.pointerId)) { + // If the object event interface had onLostPointerCapture, we'd call it here on every + // object that's getting removed. + internal.capturedMap.delete(event.pointerId); + cancelPointer([]); + } }; - this.IFF.reader.skip(2); - break; - - case 'TRAN': - this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; - - case 'BUMP': - this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; - - case 'SIDE': - this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16(); - break; - - case 'RIMG': - this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex(); - break; - - case 'RIND': - this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; + } // Any other pointer goes here ... - case 'TIMG': - this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex(); - break; - case 'IMAP': - this.IFF.currentSurface.attributes.imageMapIndex = this.IFF.reader.getUint32(); - break; + return event => { + const { + onPointerMissed, + internal + } = store.getState(); //prepareRay(event) - case 'IUVI': - // uv channel name - this.IFF.currentNode.UVChannel = this.IFF.reader.getString(length); - break; + internal.lastEvent.current = event; // Get fresh intersects - case 'IUTL': - // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge - this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32(); - break; + const isPointerMove = name === 'onPointerMove'; + const isClickEvent = name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick'; + const filter = isPointerMove ? filterPointerEvents : undefined; //const hits = patchIntersects(intersect(filter), event) - case 'IVTL': - // heightWrappingMode - this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32(); - break; + const hits = intersect(event, filter); + const delta = isClickEvent ? calculateDistance(event) : 0; // Save initial coordinates on pointer-down - default: - this.IFF.parseUnknownCHUNK(blockID, length); - } + if (name === 'onPointerDown') { + internal.initialClick = [event.offsetX, event.offsetY]; + internal.initialHits = hits.map(hit => hit.eventObject); + } // If a click yields no results, pass it back to the user as a miss + // Missed events have to come first in order to establish user-land side-effect clean up - if (blockID != 'FORM') { - this.IFF.debugger.node = 1; - this.IFF.debugger.nodeID = blockID; - this.IFF.debugger.log(); - } - if (this.IFF.reader.offset >= this.IFF.currentFormEnd) { - this.IFF.currentForm = this.IFF.parentForm; - } - } -}; + if (isClickEvent && !hits.length) { + if (delta <= 2) { + pointerMissed(event, internal.interaction); + if (onPointerMissed) onPointerMissed(event); + } + } // Take care of unhover -function LWO2Parser(IFFParser) { - this.IFF = IFFParser; -} -LWO2Parser.prototype = { - constructor: LWO2Parser, - parseBlock: function () { - this.IFF.debugger.offset = this.IFF.reader.offset; - this.IFF.debugger.closeForms(); - var blockID = this.IFF.reader.getIDTag(); - var length = this.IFF.reader.getUint32(); // size of data in bytes + if (isPointerMove) cancelPointer(hits); + handleIntersects(hits, event, delta, data => { + const eventObject = data.eventObject; + const instance = eventObject.__r3f; + const handlers = instance == null ? void 0 : instance.handlers; // Check presence of handlers - if (length > this.IFF.reader.dv.byteLength - this.IFF.reader.offset) { - this.IFF.reader.offset -= 4; - length = this.IFF.reader.getUint16(); - } + if (!(instance != null && instance.eventCount)) return; - this.IFF.debugger.dataOffset = this.IFF.reader.offset; - this.IFF.debugger.length = length; // Data types may be found in either LWO2 OR LWO3 spec + if (isPointerMove) { + // Move event ... + if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) { + // When enter or out is present take care of hover-state + const id = makeId(data); + const hoveredItem = internal.hovered.get(id); - switch (blockID) { - case 'FORM': - // form blocks may consist of sub -chunks or sub-forms - this.IFF.parseForm(length); - break; - // SKIPPED CHUNKS - // if break; is called directly, the position in the lwoTree is not created - // any sub chunks and forms are added to the parent form instead - // MISC skipped - - case 'ICON': // Thumbnail Icon Image - - case 'VMPA': // Vertex Map Parameter - - case 'BBOX': // bounding box - // case 'VMMD': - // case 'VTYP': - // normal maps can be specified, normally on models imported from other applications. Currently ignored - - case 'NORM': // ENVL FORM skipped - - case 'PRE ': - case 'POST': - case 'KEY ': - case 'SPAN': // CLIP FORM skipped - - case 'TIME': - case 'CLRS': - case 'CLRA': - case 'FILT': - case 'DITH': - case 'CONT': - case 'BRIT': - case 'SATR': - case 'HUE ': - case 'GAMM': - case 'NEGA': - case 'IFLT': - case 'PFLT': // Image Map Layer skipped - - case 'PROJ': - case 'AXIS': - case 'AAST': - case 'PIXB': - case 'AUVO': - case 'STCK': // Procedural Textures skipped - - case 'PROC': - case 'VALU': - case 'FUNC': // Gradient Textures skipped - - case 'PNAM': - case 'INAM': - case 'GRST': - case 'GREN': - case 'GRPT': - case 'FKEY': - case 'IKEY': // Texture Mapping Form skipped - - case 'CSYS': // Surface CHUNKs skipped - - case 'OPAQ': // top level 'opacity' checkbox - - case 'CMAP': // clip map - // Surface node CHUNKS skipped - // These mainly specify the node editor setup in LW - - case 'NLOC': - case 'NZOM': - case 'NVER': - case 'NSRV': - case 'NVSK': // unknown - - case 'NCRD': - case 'WRPW': // image wrap w ( for cylindrical and spherical projections) - - case 'WRPH': // image wrap h - - case 'NMOD': - case 'NPRW': - case 'NPLA': - case 'NODS': - case 'VERS': - case 'ENUM': - case 'TAG ': - case 'OPAC': // Car Material CHUNKS - - case 'CGMD': - case 'CGTY': - case 'CGST': - case 'CGEN': - case 'CGTS': - case 'CGTE': - case 'OSMP': - case 'OMDE': - case 'OUTR': - case 'FLAG': - case 'TRNL': - case 'GLOW': - case 'GVAL': // glow intensity - - case 'SHRP': - case 'RFOP': - case 'RSAN': - case 'TROP': - case 'RBLR': - case 'TBLR': - case 'CLRH': - case 'CLRF': - case 'ADTR': - case 'LINE': - case 'ALPH': - case 'VCOL': - case 'ENAB': - this.IFF.debugger.skipped = true; - this.IFF.reader.skip(length); - break; + if (!hoveredItem) { + // If the object wasn't previously hovered, book it and call its handler + internal.hovered.set(id, data); + handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data); + handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data); + } else if (hoveredItem.stopped) { + // If the object was previously hovered and stopped, we shouldn't allow other items to proceed + data.stopPropagation(); + } + } // Call mouse move - case 'SURF': - this.IFF.parseSurfaceLwo2(length); - break; - case 'CLIP': - this.IFF.parseClipLwo2(length); - break; - // Texture node chunks (not in spec) + handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data); + } else { + // All other events ... + const handler = handlers[name]; - case 'IPIX': // usePixelBlending + if (handler) { + // Forward all events back to their respective handlers with the exception of click events, + // which must use the initial target + if (!isClickEvent || internal.initialHits.includes(eventObject)) { + // Missed events have to come first + pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); // Now call the handler - case 'IMIP': // useMipMaps + handler(data); + } + } else { + // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit + if (isClickEvent && internal.initialHits.includes(eventObject)) { + pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); + } + } + } + }); + }; + }; - case 'IMOD': // imageBlendingMode + function pointerMissed(event, objects) { + objects.forEach(object => { + var _r3f3; - case 'AMOD': // unknown + return (_r3f3 = object.__r3f) == null ? void 0 : _r3f3.handlers.onPointerMissed == null ? void 0 : _r3f3.handlers.onPointerMissed(event); + }); + } - case 'IINV': // imageInvertAlpha + return { + handlePointer + }; +} - case 'INCR': // imageInvertColor +let catalogue = {}; - case 'IAXS': // imageAxis ( for non-UV maps) +let extend = objects => void (catalogue = { ...catalogue, + ...objects +}); - case 'IFOT': // imageFallofType +function createRenderer(roots, getEventPriority) { + function createInstance(type, { + args = [], + attach, + ...props + }, root) { + let name = `${type[0].toUpperCase()}${type.slice(1)}`; + let instance; // Auto-attach geometries and materials - case 'ITIM': // timing for animated textures + if (attach === undefined) { + if (name.endsWith('Geometry')) attach = 'geometry';else if (name.endsWith('Material')) attach = 'material'; + } - case 'IWRL': - case 'IUTI': - case 'IINX': - case 'IINY': - case 'IINZ': - case 'IREF': - // possibly a VX for reused texture nodes - if (length === 4) this.IFF.currentNode[blockID] = this.IFF.reader.getInt32();else this.IFF.reader.skip(length); - break; + if (type === 'primitive') { + if (props.object === undefined) throw `Primitives without 'object' are invalid!`; + const object = props.object; + instance = prepare(object, { + type, + root, + attach, + primitive: true + }); + } else { + const target = catalogue[name]; - case 'OTAG': - this.IFF.parseObjectTag(); - break; + if (!target) { + throw `${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`; + } // Throw if an object or literal was passed for args - case 'LAYR': - this.IFF.parseLayer(length); - break; - case 'PNTS': - this.IFF.parsePoints(length); - break; + if (!Array.isArray(args)) throw 'The args prop must be an array!'; // Instanciate new object, link it to the root + // Append memoized props with args so it's not forgotten - case 'VMAP': - this.IFF.parseVertexMapping(length); - break; + instance = prepare(new target(...args), { + type, + root, + attach, + // Save args in case we need to reconstruct later for HMR + memoizedProps: { + args + } + }); + } // It should NOT call onUpdate on object instanciation, because it hasn't been added to the + // view yet. If the callback relies on references for instance, they won't be ready yet, this is + // why it passes "true" here + // There is no reason to apply props to injects - case 'AUVU': - case 'AUVN': - this.IFF.reader.skip(length - 1); - this.IFF.reader.getVariableLengthIndex(); // VX - break; + if (name !== 'inject') applyProps$1(instance, props); + return instance; + } - case 'POLS': - this.IFF.parsePolygonList(length); - break; + function appendChild(parentInstance, child) { + let added = false; - case 'TAGS': - this.IFF.parseTagStrings(length); - break; + if (child) { + var _child$__r3f, _parentInstance$__r3f; - case 'PTAG': - this.IFF.parsePolygonTagMapping(length); - break; + // The attach attribute implies that the object attaches itself on the parent + if ((_child$__r3f = child.__r3f) != null && _child$__r3f.attach) { + attach(parentInstance, child, child.__r3f.attach); + } else if (child.isObject3D && parentInstance.isObject3D) { + // add in the usual parent-child way + parentInstance.add(child); + added = true; + } // This is for anything that used attach, and for non-Object3Ds that don't get attached to props; + // that is, anything that's a child in React but not a child in the scenegraph. - case 'VMAD': - this.IFF.parseVertexMapping(length, true); - break; - // Misc CHUNKS - case 'DESC': - // Description Line - this.IFF.currentForm.description = this.IFF.reader.getString(); - break; + if (!added) (_parentInstance$__r3f = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f.objects.push(child); + if (!child.__r3f) prepare(child, {}); + child.__r3f.parent = parentInstance; + updateInstance(child); + invalidateInstance(child); + } + } - case 'TEXT': - case 'CMNT': - case 'NCOM': - this.IFF.currentForm.comment = this.IFF.reader.getString(); - break; - // Envelope Form + function insertBefore(parentInstance, child, beforeChild) { + let added = false; - case 'NAME': - this.IFF.currentForm.channelName = this.IFF.reader.getString(); - break; - // Image Map Layer + if (child) { + var _child$__r3f2, _parentInstance$__r3f2; - case 'WRAP': - this.IFF.currentForm.wrap = { - w: this.IFF.reader.getUint16(), - h: this.IFF.reader.getUint16() - }; - break; + if ((_child$__r3f2 = child.__r3f) != null && _child$__r3f2.attach) { + attach(parentInstance, child, child.__r3f.attach); + } else if (child.isObject3D && parentInstance.isObject3D) { + child.parent = parentInstance; + child.dispatchEvent({ + type: 'added' + }); + const restSiblings = parentInstance.children.filter(sibling => sibling !== child); + const index = restSiblings.indexOf(beforeChild); + parentInstance.children = [...restSiblings.slice(0, index), child, ...restSiblings.slice(index)]; + added = true; + } - case 'IMAG': - var index = this.IFF.reader.getVariableLengthIndex(); - this.IFF.currentForm.imageIndex = index; - break; - // Texture Mapping Form + if (!added) (_parentInstance$__r3f2 = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f2.objects.push(child); + if (!child.__r3f) prepare(child, {}); + child.__r3f.parent = parentInstance; + updateInstance(child); + invalidateInstance(child); + } + } - case 'OREF': - this.IFF.currentForm.referenceObject = this.IFF.reader.getString(); - break; + function removeRecursive(array, parent, dispose = false) { + if (array) [...array].forEach(child => removeChild(parent, child, dispose)); + } - case 'ROID': - this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32(); - break; - // Surface Blocks + function removeChild(parentInstance, child, dispose) { + if (child) { + var _parentInstance$__r3f3, _child$__r3f3, _child$__r3f5; - case 'SSHN': - this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString(); - break; + // Clear the parent reference + if (child.__r3f) child.__r3f.parent = null; // Remove child from the parents objects - case 'AOVN': - this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString(); - break; - // Nodal Blocks + if ((_parentInstance$__r3f3 = parentInstance.__r3f) != null && _parentInstance$__r3f3.objects) parentInstance.__r3f.objects = parentInstance.__r3f.objects.filter(x => x !== child); // Remove attachment - case 'NSTA': - this.IFF.currentForm.disabled = this.IFF.reader.getUint16(); - break; + if ((_child$__r3f3 = child.__r3f) != null && _child$__r3f3.attach) { + detach(parentInstance, child, child.__r3f.attach); + } else if (child.isObject3D && parentInstance.isObject3D) { + var _child$__r3f4; - case 'NRNM': - this.IFF.currentForm.realName = this.IFF.reader.getString(); - break; + parentInstance.remove(child); // Remove interactivity - case 'NNME': - this.IFF.currentForm.refName = this.IFF.reader.getString(); - this.IFF.currentSurface.nodes[this.IFF.currentForm.refName] = this.IFF.currentForm; - break; - // Nodal Blocks : connections + if ((_child$__r3f4 = child.__r3f) != null && _child$__r3f4.root) { + removeInteractivity(child.__r3f.root, child); + } + } // Allow objects to bail out of recursive dispose altogether by passing dispose={null} + // Never dispose of primitives because their state may be kept outside of React! + // In order for an object to be able to dispose it has to have + // - a dispose method, + // - it cannot be a + // - it cannot be a THREE.Scene, because three has broken it's own api + // + // Since disposal is recursive, we can check the optional dispose arg, which will be undefined + // when the reconciler calls it, but then carry our own check recursively - case 'INME': - if (!this.IFF.currentForm.nodeName) this.IFF.currentForm.nodeName = []; - this.IFF.currentForm.nodeName.push(this.IFF.reader.getString()); - break; - case 'IINN': - if (!this.IFF.currentForm.inputNodeName) this.IFF.currentForm.inputNodeName = []; - this.IFF.currentForm.inputNodeName.push(this.IFF.reader.getString()); - break; + const isPrimitive = (_child$__r3f5 = child.__r3f) == null ? void 0 : _child$__r3f5.primitive; + const shouldDispose = dispose === undefined ? child.dispose !== null && !isPrimitive : dispose; // Remove nested child objects. Primitives should not have objects and children that are + // attached to them declaratively ... - case 'IINM': - if (!this.IFF.currentForm.inputName) this.IFF.currentForm.inputName = []; - this.IFF.currentForm.inputName.push(this.IFF.reader.getString()); - break; + if (!isPrimitive) { + var _child$__r3f6; - case 'IONM': - if (!this.IFF.currentForm.inputOutputName) this.IFF.currentForm.inputOutputName = []; - this.IFF.currentForm.inputOutputName.push(this.IFF.reader.getString()); - break; + removeRecursive((_child$__r3f6 = child.__r3f) == null ? void 0 : _child$__r3f6.objects, child, shouldDispose); + removeRecursive(child.children, child, shouldDispose); + } // Remove references - case 'FNAM': - this.IFF.currentForm.fileName = this.IFF.reader.getString(); - break; - case 'CHAN': - // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored - if (length === 4) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();else this.IFF.reader.skip(length); - break; - // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format + if (child.__r3f) { + delete child.__r3f.root; + delete child.__r3f.objects; + delete child.__r3f.handlers; + delete child.__r3f.memoizedProps; + if (!isPrimitive) delete child.__r3f; + } // Dispose item whenever the reconciler feels like it - case 'SMAN': - var maxSmoothingAngle = this.IFF.reader.getFloat32(); - this.IFF.currentSurface.attributes.smooth = maxSmoothingAngle < 0 ? false : true; - break; - // LWO2: Basic Surface Parameters - case 'COLR': - this.IFF.currentSurface.attributes.Color = { - value: this.IFF.reader.getFloat32Array(3) - }; - this.IFF.reader.skip(2); // VX: envelope + if (shouldDispose && child.dispose && child.type !== 'Scene') { + scheduler$1.exports.unstable_scheduleCallback(scheduler$1.exports.unstable_IdlePriority, () => { + try { + child.dispose(); + } catch (e) { + /* ... */ + } + }); + } - break; + invalidateInstance(parentInstance); + } + } - case 'LUMI': - this.IFF.currentSurface.attributes.Luminosity = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + function switchInstance(instance, type, newProps, fiber) { + var _instance$__r3f; - case 'SPEC': - this.IFF.currentSurface.attributes.Specular = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + const parent = (_instance$__r3f = instance.__r3f) == null ? void 0 : _instance$__r3f.parent; + if (!parent) return; + const newInstance = createInstance(type, newProps, instance.__r3f.root); // https://github.com/pmndrs/react-three-fiber/issues/1348 + // When args change the instance has to be re-constructed, which then + // forces r3f to re-parent the children and non-scene objects + // This can not include primitives, which should not have declarative children - case 'DIFF': - this.IFF.currentSurface.attributes.Diffuse = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + if (type !== 'primitive' && instance.children) { + instance.children.forEach(child => appendChild(newInstance, child)); + instance.children = []; + } - case 'REFL': - this.IFF.currentSurface.attributes.Reflection = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + instance.__r3f.objects.forEach(child => appendChild(newInstance, child)); - case 'GLOS': - this.IFF.currentSurface.attributes.Glossiness = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + instance.__r3f.objects = []; + removeChild(parent, instance); + appendChild(parent, newInstance); // Re-bind event handlers - case 'TRAN': - this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; + if (newInstance.raycast && newInstance.__r3f.eventCount) { + const rootState = newInstance.__r3f.root.getState(); - case 'BUMP': - this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; + rootState.internal.interaction.push(newInstance); + } // This evil hack switches the react-internal fiber node + [fiber, fiber.alternate].forEach(fiber => { + if (fiber !== null) { + fiber.stateNode = newInstance; - case 'SIDE': - this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16(); - break; + if (fiber.ref) { + if (typeof fiber.ref === 'function') fiber.ref(newInstance);else fiber.ref.current = newInstance; + } + } + }); + } - case 'RIMG': - this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex(); - break; + const reconciler = Reconciler({ + createInstance, + removeChild, + appendChild, + appendInitialChild: appendChild, + insertBefore, + supportsMicrotask: true, + warnsIfNotActing: true, + supportsMutation: true, + isPrimaryRenderer: false, + noTimeout: -1, + appendChildToContainer: (container, child) => { + const scene = container.getState().scene; // Link current root to the default scene - case 'RIND': - this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; + scene.__r3f.root = container; + appendChild(scene, child); + }, + removeChildFromContainer: (container, child) => removeChild(container.getState().scene, child), + insertInContainerBefore: (container, child, beforeChild) => insertBefore(container.getState().scene, child, beforeChild), + getRootHostContext: () => null, + getChildHostContext: parentHostContext => parentHostContext, - case 'TIMG': - this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex(); - break; + finalizeInitialChildren(instance) { + var _instance$__r3f2; - case 'IMAP': - this.IFF.reader.skip(2); - break; + const localState = (_instance$__r3f2 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f2 : {}; // https://github.com/facebook/react/issues/20271 + // Returning true will trigger commitMount - case 'TMAP': - this.IFF.debugger.skipped = true; - this.IFF.reader.skip(length); // needs implementing + return !!localState.handlers; + }, - break; + prepareUpdate(instance, type, oldProps, newProps) { + // Create diff-sets + if (instance.__r3f.primitive && newProps.object && newProps.object !== instance) { + return [true]; + } else { + // This is a data object, let's extract critical information about it + const { + args: argsNew = [], + children: cN, + ...restNew + } = newProps; + const { + args: argsOld = [], + children: cO, + ...restOld + } = oldProps; // Throw if an object or literal was passed for args - case 'IUVI': - // uv channel name - this.IFF.currentNode.UVChannel = this.IFF.reader.getString(length); - break; + if (!Array.isArray(argsNew)) throw 'The args prop must be an array!'; // If it has new props or arguments, then it needs to be re-instanciated - case 'IUTL': - // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge - this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32(); - break; + if (argsNew.some((value, index) => value !== argsOld[index])) return [true]; // Create a diff-set, flag if there are any changes - case 'IVTL': - // heightWrappingMode - this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32(); - break; - // LWO2 USE + const diff = diffProps(instance, restNew, restOld, true); + if (diff.changes.length) return [false, diff]; // Otherwise do not touch the instance - case 'BLOK': - // skip - break; + return null; + } + }, - default: - this.IFF.parseUnknownCHUNK(blockID, length); - } + commitUpdate(instance, [reconstruct, diff], type, oldProps, newProps, fiber) { + // Reconstruct when args or = this.IFF.currentFormEnd) { - this.IFF.currentForm = this.IFF.parentForm; - } - } -}; + // https://github.com/facebook/react/issues/20271 + // This will make sure events are only added once to the central container + const localState = (_instance$__r3f3 = instance.__r3f) != null ? _instance$__r3f3 : {}; -/** - * === IFFParser === - * - Parses data from the IFF buffer. - * - LWO3 files are in IFF format and can contain the following data types, referred to by shorthand codes - * - * ATOMIC DATA TYPES - * ID Tag - 4x 7 bit uppercase ASCII chars: ID4 - * signed integer, 1, 2, or 4 byte length: I1, I2, I4 - * unsigned integer, 1, 2, or 4 byte length: U1, U2, U4 - * float, 4 byte length: F4 - * string, series of ASCII chars followed by null byte (If the length of the string including the null terminating byte is odd, an extra null is added so that the data that follows will begin on an even byte boundary): S0 - * - * COMPOUND DATA TYPES - * Variable-length Index (index into an array or collection): U2 or U4 : VX - * Color (RGB): F4 + F4 + F4: COL12 - * Coordinate (x, y, z): F4 + F4 + F4: VEC12 - * Percentage F4 data type from 0->1 with 1 = 100%: FP4 - * Angle in radian F4: ANG4 - * Filename (string) S0: FNAM0 - * XValue F4 + index (VX) + optional envelope( ENVL ): XVAL - * XValue vector VEC12 + index (VX) + optional envelope( ENVL ): XVAL3 - * - * The IFF file is arranged in chunks: - * CHUNK = ID4 + length (U4) + length X bytes of data + optional 0 pad byte - * optional 0 pad byte is there to ensure chunk ends on even boundary, not counted in size - * - * COMPOUND DATA TYPES - * - Chunks are combined in Forms (collections of chunks) - * - FORM = string 'FORM' (ID4) + length (U4) + type (ID4) + optional ( CHUNK | FORM ) - * - CHUNKS and FORMS are collectively referred to as blocks - * - The entire file is contained in one top level FORM - * - **/ + if (instance.raycast && localState.handlers && localState.eventCount) { + instance.__r3f.root.getState().internal.interaction.push(instance); + } + }, -function IFFParser() { - this.debugger = new Debugger(); // this.debugger.enable(); // un-comment to log IFF hierarchy. -} + getPublicInstance: instance => instance, + shouldDeprioritizeSubtree: () => false, + prepareForCommit: () => null, + preparePortalMount: container => prepare(container.getState().scene), + resetAfterCommit: () => {}, + shouldSetTextContent: () => false, + clearContainer: () => false, + detachDeletedInstance: () => {}, -IFFParser.prototype = { - constructor: IFFParser, - parse: function (buffer) { - this.reader = new DataViewReader(buffer); - this.tree = { - materials: {}, - layers: [], - tags: [], - textures: [] - }; // start out at the top level to add any data before first layer is encountered + hideInstance(instance) { + var _instance$__r3f4; - this.currentLayer = this.tree; - this.currentForm = this.tree; - this.parseTopForm(); - if (this.tree.format === undefined) return; + // Deatch while the instance is hidden + const { + attach: type, + parent + } = (_instance$__r3f4 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f4 : {}; + if (type && parent) detach(parent, instance, type); + if (instance.isObject3D) instance.visible = false; + invalidateInstance(instance); + }, - if (this.tree.format === 'LWO2') { - this.parser = new LWO2Parser(this); + unhideInstance(instance, props) { + var _instance$__r3f5; - while (!this.reader.endOfFile()) this.parser.parseBlock(); - } else if (this.tree.format === 'LWO3') { - this.parser = new LWO3Parser(this); + // Re-attach when the instance is unhidden + const { + attach: type, + parent + } = (_instance$__r3f5 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f5 : {}; + if (type && parent) attach(parent, instance, type); + if (instance.isObject3D && props.visible == null || props.visible) instance.visible = true; + invalidateInstance(instance); + }, - while (!this.reader.endOfFile()) this.parser.parseBlock(); - } + createTextInstance: () => {}, + hideTextInstance: () => { + throw new Error('Text is not allowed in the R3F tree.'); + }, + unhideTextInstance: () => {}, + getCurrentEventPriority: () => getEventPriority ? getEventPriority() : constants.exports.DefaultEventPriority, + // @ts-ignore + now: typeof performance !== 'undefined' && is$1.fun(performance.now) ? performance.now : is$1.fun(Date.now) ? Date.now : undefined, + // @ts-ignore + scheduleTimeout: is$1.fun(setTimeout) ? setTimeout : undefined, + // @ts-ignore + cancelTimeout: is$1.fun(clearTimeout) ? clearTimeout : undefined, + setTimeout: is$1.fun(setTimeout) ? setTimeout : undefined, + clearTimeout: is$1.fun(clearTimeout) ? clearTimeout : undefined + }); + return { + reconciler, + applyProps: applyProps$1 + }; +} +const isRenderer = def => !!(def != null && def.render); +const context = /*#__PURE__*/React.createContext(null); - this.debugger.offset = this.reader.offset; - this.debugger.closeForms(); - return this.tree; - }, +const createStore$2 = (invalidate, advance) => { + const rootState = create$4((set, get) => { + const position = new Vector3(); + const defaultTarget = new Vector3(); + const tempTarget = new Vector3(); - parseTopForm() { - this.debugger.offset = this.reader.offset; - var topForm = this.reader.getIDTag(); + function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) { + const { + width, + height + } = size; + const aspect = width / height; + if (target instanceof Vector3) tempTarget.copy(target);else tempTarget.set(...target); + const distance = camera.getWorldPosition(position).distanceTo(tempTarget); - if (topForm !== 'FORM') { - console.warn('LWOLoader: Top-level FORM missing.'); - return; - } + if (isOrthographicCamera(camera)) { + return { + width: width / camera.zoom, + height: height / camera.zoom, + factor: 1, + distance, + aspect + }; + } else { + const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians - var length = this.reader.getUint32(); - this.debugger.dataOffset = this.reader.offset; - this.debugger.length = length; - var type = this.reader.getIDTag(); + const h = 2 * Math.tan(fov / 2) * distance; // visible height - if (type === 'LWO2') { - this.tree.format = type; - } else if (type === 'LWO3') { - this.tree.format = type; + const w = h * (width / height); + return { + width: w, + height: h, + factor: width / w, + distance, + aspect + }; + } } - this.debugger.node = 0; - this.debugger.nodeID = type; - this.debugger.log(); - return; - }, - - /// - // FORM PARSING METHODS - /// - // Forms are organisational and can contain any number of sub chunks and sub forms - // FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * } - parseForm(length) { - var type = this.reader.getIDTag(); - - switch (type) { - // SKIPPED FORMS - // if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped - case 'ISEQ': // Image sequence - - case 'ANIM': // plug in animation - - case 'STCC': // Color-cycling Still - - case 'VPVL': - case 'VPRM': - case 'NROT': - case 'WRPW': // image wrap w ( for cylindrical and spherical projections) + let performanceTimeout = undefined; - case 'WRPH': // image wrap h + const setPerformanceCurrent = current => set(state => ({ + performance: { ...state.performance, + current + } + })); - case 'FUNC': - case 'FALL': - case 'OPAC': - case 'GRAD': // gradient texture + const pointer = new Vector2(); + return { + set, + get, + // Mock objects that have to be configured + gl: null, + camera: null, + raycaster: null, + events: { + priority: 1, + enabled: true, + connected: false + }, + xr: null, + invalidate: (frames = 1) => invalidate(get(), frames), + advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()), + legacy: false, + linear: false, + flat: false, + scene: prepare(new Scene$1()), + controls: null, + clock: new Clock(), + pointer, + mouse: pointer, + frameloop: 'always', + onPointerMissed: undefined, + performance: { + current: 1, + min: 0.5, + max: 1, + debounce: 200, + regress: () => { + const state = get(); // Clear timeout - case 'ENVS': - case 'VMOP': - case 'VMBG': // Car Material FORMS + if (performanceTimeout) clearTimeout(performanceTimeout); // Set lower bound performance - case 'OMAX': - case 'STEX': - case 'CKBG': - case 'CKEY': - case 'VMLA': - case 'VMLB': - this.debugger.skipped = true; - this.skipForm(length); // not currently supported + if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min); // Go back to upper bound performance after a while unless something regresses meanwhile - break; - // if break; is called directly, the position in the lwoTree is not created - // any sub chunks and forms are added to the parent form instead + performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce); + } + }, + size: { + width: 0, + height: 0, + updateStyle: false + }, + viewport: { + initialDpr: 0, + dpr: 0, + width: 0, + height: 0, + aspect: 0, + distance: 0, + factor: 0, + getCurrentViewport + }, + setEvents: events => set(state => ({ ...state, + events: { ...state.events, + ...events + } + })), + setSize: (width, height, updateStyle) => { + const camera = get().camera; + const size = { + width, + height, + updateStyle + }; + set(state => ({ + size, + viewport: { ...state.viewport, + ...getCurrentViewport(camera, defaultTarget, size) + } + })); + }, + setDpr: dpr => set(state => { + const resolved = calculateDpr(dpr); + return { + viewport: { ...state.viewport, + dpr: resolved, + initialDpr: state.viewport.initialDpr || resolved + } + }; + }), + setFrameloop: (frameloop = 'always') => { + const clock = get().clock; // if frameloop === "never" clock.elapsedTime is updated using advance(timestamp) - case 'META': - case 'NNDS': - case 'NODS': - case 'NDTA': - case 'ADAT': - case 'AOVS': - case 'BLOK': // used by texture nodes + clock.stop(); + clock.elapsedTime = 0; - case 'IBGC': // imageBackgroundColor + if (frameloop !== 'never') { + clock.start(); + clock.elapsedTime = 0; + } - case 'IOPC': // imageOpacity + set(() => ({ + frameloop + })); + }, + previousRoot: undefined, + internal: { + active: false, + priority: 0, + frames: 0, + lastEvent: /*#__PURE__*/React.createRef(), + interaction: [], + hovered: new Map(), + subscribers: [], + initialClick: [0, 0], + initialHits: [], + capturedMap: new Map(), + subscribe: (ref, priority, store) => { + const internal = get().internal; // If this subscription was given a priority, it takes rendering into its own hands + // For that reason we switch off automatic rendering and increase the manual flag + // As long as this flag is positive there can be no internal rendering at all + // because there could be multiple render subscriptions - case 'IIMG': // hold reference to image path + internal.priority = internal.priority + (priority > 0 ? 1 : 0); + internal.subscribers.push({ + ref, + priority, + store + }); // Register subscriber and sort layers from lowest to highest, meaning, + // highest priority renders last (on top of the other frames) - case 'TXTR': - // this.setupForm( type, length ); - this.debugger.length = 4; - this.debugger.skipped = true; - break; + internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority); + return () => { + const internal = get().internal; - case 'IFAL': // imageFallof + if (internal != null && internal.subscribers) { + // Decrease manual flag if this subscription had a priority + internal.priority = internal.priority - (priority > 0 ? 1 : 0); // Remove subscriber from list - case 'ISCL': // imageScale + internal.subscribers = internal.subscribers.filter(s => s.ref !== ref); + } + }; + } + } + }; + }); + const state = rootState.getState(); + let oldSize = state.size; + let oldDpr = state.viewport.dpr; + let oldCamera = state.camera; + rootState.subscribe(() => { + const { + camera, + size, + viewport, + gl, + set + } = rootState.getState(); // Resize camera and renderer on changes to size and pixelratio - case 'IPOS': // imagePosition + if (size !== oldSize || viewport.dpr !== oldDpr) { + oldSize = size; + oldDpr = viewport.dpr; // Update camera & renderer - case 'IROT': // imageRotation + updateCamera(camera, size); + gl.setPixelRatio(viewport.dpr); + gl.setSize(size.width, size.height, size.updateStyle); + } // Update viewport once the camera changes - case 'IBMP': - case 'IUTD': - case 'IVTD': - this.parseTextureNodeAttribute(type); - break; - case 'ENVL': - this.parseEnvelope(length); - break; - // CLIP FORM AND SUB FORMS + if (camera !== oldCamera) { + oldCamera = camera; // Update viewport - case 'CLIP': - if (this.tree.format === 'LWO2') { - this.parseForm(length); - } else { - this.parseClip(length); + set(state => ({ + viewport: { ...state.viewport, + ...state.viewport.getCurrentViewport(camera) } + })); + } + }); // Invalidate on any change - break; - - case 'STIL': - this.parseImage(); - break; + rootState.subscribe(state => invalidate(state)); // Return root state - case 'XREF': - // clone of another STIL - this.reader.skip(8); // unknown + return rootState; +}; - this.currentForm.referenceTexture = { - index: this.reader.getUint32(), - refName: this.reader.getString() // internal unique ref +function createSubs(callback, subs) { + const index = subs.length; + subs.push(callback); + return () => void subs.splice(index, 1); +} - }; - break; - // Not in spec, used by texture nodes +let i$1; +let globalEffects = []; +let globalAfterEffects = []; +let globalTailEffects = []; +/** + * Adds a global render callback which is called each frame. + * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect + */ - case 'IMST': - this.parseImageStateForm(length); - break; - // SURF FORM AND SUB FORMS +const addEffect = callback => createSubs(callback, globalEffects); - case 'SURF': - this.parseSurfaceForm(length); - break; +function run(effects, timestamp) { + for (i$1 = 0; i$1 < effects.length; i$1++) effects[i$1](timestamp); +} - case 'VALU': - // Not in spec - this.parseValueForm(length); - break; +let subscribers; +let subscription; - case 'NTAG': - this.parseSubNode(length); - break; +function render$1(timestamp, state, frame) { + // Run local effects + let delta = state.clock.getDelta(); // In frameloop='never' mode, clock times are updated using the provided timestamp - case 'ATTR': // BSDF Node Attributes + if (state.frameloop === 'never' && typeof timestamp === 'number') { + delta = timestamp - state.clock.elapsedTime; + state.clock.oldTime = state.clock.elapsedTime; + state.clock.elapsedTime = timestamp; + } // Call subscribers (useFrame) - case 'SATR': - // Standard Node Attributes - this.setupForm('attributes', length); - break; - case 'NCON': - this.parseConnections(length); - break; + subscribers = state.internal.subscribers; - case 'SSHA': - this.parentForm = this.currentForm; - this.currentForm = this.currentSurface; - this.setupForm('surfaceShader', length); - break; + for (i$1 = 0; i$1 < subscribers.length; i$1++) { + subscription = subscribers[i$1]; + subscription.ref.current(subscription.store.getState(), delta, frame); + } // Render content - case 'SSHD': - this.setupForm('surfaceShaderData', length); - break; - case 'ENTR': - // Not in spec - this.parseEntryForm(length); - break; - // Image Map Layer + if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera); // Decrease frame count - case 'IMAP': - this.parseImageMap(length); - break; + state.internal.frames = Math.max(0, state.internal.frames - 1); + return state.frameloop === 'always' ? 1 : state.internal.frames; +} - case 'TAMP': - this.parseXVAL('amplitude', length); - break; - //Texture Mapping Form +function createLoop(roots) { + let running = false; + let repeat; + let frame; + let state; - case 'TMAP': - this.setupForm('textureMap', length); - break; + function loop(timestamp) { + frame = requestAnimationFrame(loop); + running = true; + repeat = 0; // Run effects - case 'CNTR': - this.parseXVAL3('center', length); - break; + if (globalEffects.length) run(globalEffects, timestamp); // Render all roots - case 'SIZE': - this.parseXVAL3('scale', length); - break; + roots.forEach(root => { + var _state$gl$xr; - case 'ROTA': - this.parseXVAL3('rotation', length); - break; + state = root.store.getState(); // If the frameloop is invalidated, do not run another frame - default: - this.parseUnknownForm(type, length); - } + if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) { + repeat += render$1(timestamp, state); + } + }); // Run after-effects - this.debugger.node = 0; - this.debugger.nodeID = type; - this.debugger.log(); - }, + if (globalAfterEffects.length) run(globalAfterEffects, timestamp); // Stop the loop if nothing invalidates it - setupForm(type, length) { - if (!this.currentForm) this.currentForm = this.currentNode; - this.currentFormEnd = this.reader.offset + length; - this.parentForm = this.currentForm; + if (repeat === 0) { + // Tail call effects, they are called when rendering stops + if (globalTailEffects.length) run(globalTailEffects, timestamp); // Flag end of operation - if (!this.currentForm[type]) { - this.currentForm[type] = {}; - this.currentForm = this.currentForm[type]; - } else { - // should never see this unless there's a bug in the reader - console.warn('LWOLoader: form already exists on parent: ', type, this.currentForm); - this.currentForm = this.currentForm[type]; + running = false; + return cancelAnimationFrame(frame); } - }, - - skipForm(length) { - this.reader.skip(length - 4); - }, + } - parseUnknownForm(type, length) { - console.warn('LWOLoader: unknown FORM encountered: ' + type, length); - printBuffer(this.reader.dv.buffer, this.reader.offset, length - 4); - this.reader.skip(length - 4); - }, + function invalidate(state, frames = 1) { + var _state$gl$xr2; - parseSurfaceForm(length) { - this.reader.skip(8); // unknown Uint32 x2 - - var name = this.reader.getString(); - var surface = { - attributes: {}, - // LWO2 style non-node attributes will go here - connections: {}, - name: name, - inputName: name, - nodes: {}, - source: this.reader.getString() - }; - this.tree.materials[name] = surface; - this.currentSurface = surface; - this.parentForm = this.tree.materials; - this.currentForm = surface; - this.currentFormEnd = this.reader.offset + length; - }, + if (!state) return roots.forEach(root => invalidate(root.store.getState()), frames); + if ((_state$gl$xr2 = state.gl.xr) != null && _state$gl$xr2.isPresenting || !state.internal.active || state.frameloop === 'never') return; // Increase frames, do not go higher than 60 - parseSurfaceLwo2(length) { - var name = this.reader.getString(); - var surface = { - attributes: {}, - // LWO2 style non-node attributes will go here - connections: {}, - name: name, - nodes: {}, - source: this.reader.getString() - }; - this.tree.materials[name] = surface; - this.currentSurface = surface; - this.parentForm = this.tree.materials; - this.currentForm = surface; - this.currentFormEnd = this.reader.offset + length; - }, + state.internal.frames = Math.min(60, state.internal.frames + frames); // If the render-loop isn't active, start it - parseSubNode(length) { - // parse the NRNM CHUNK of the subnode FORM to get - // a meaningful name for the subNode - // some subnodes can be renamed, but Input and Surface cannot - this.reader.skip(8); // NRNM + length + if (!running) { + running = true; + requestAnimationFrame(loop); + } + } - var name = this.reader.getString(); - var node = { - name: name - }; - this.currentForm = node; - this.currentNode = node; - this.currentFormEnd = this.reader.offset + length; - }, + function advance(timestamp, runGlobalEffects = true, state, frame) { + if (runGlobalEffects) run(globalEffects, timestamp); + if (!state) roots.forEach(root => render$1(timestamp, root.store.getState()));else render$1(timestamp, state, frame); + if (runGlobalEffects) run(globalAfterEffects, timestamp); + } - // collect attributes from all nodes at the top level of a surface - parseConnections(length) { - this.currentFormEnd = this.reader.offset + length; - this.parentForm = this.currentForm; - this.currentForm = this.currentSurface.connections; - }, + return { + loop, - // surface node attribute data, e.g. specular, roughness etc - parseEntryForm(length) { - this.reader.skip(8); // NAME + length + /** + * Invalidates the view, requesting a frame to be rendered. Will globally invalidate unless passed a root's state. + * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate + */ + invalidate, - var name = this.reader.getString(); - this.currentForm = this.currentNode.attributes; - this.setupForm(name, length); - }, + /** + * Advances the frameloop and runs render effects, useful for when manually rendering via `frameloop="never"`. + * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance + */ + advance + }; +} - // parse values from material - doesn't match up to other LWO3 data types - // sub form of entry form - parseValueForm() { - this.reader.skip(8); // unknown + length - - var valueType = this.reader.getString(); - - if (valueType === 'double') { - this.currentForm.value = this.reader.getUint64(); - } else if (valueType === 'int') { - this.currentForm.value = this.reader.getUint32(); - } else if (valueType === 'vparam') { - this.reader.skip(24); - this.currentForm.value = this.reader.getFloat64(); - } else if (valueType === 'vparam3') { - this.reader.skip(24); - this.currentForm.value = this.reader.getFloat64Array(3); - } - }, +function useStore$1() { + const store = React.useContext(context); + if (!store) throw `R3F hooks can only be used within the Canvas component!`; + return store; +} +/** + * Accesses R3F's internal state, containing renderer, canvas, scene, etc. + * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usethree + */ - // holds various data about texture node image state - // Data other thanmipMapLevel unknown - parseImageStateForm() { - this.reader.skip(8); // unknown +function useThree(selector = state => state, equalityFn) { + return useStore$1()(selector, equalityFn); +} +/** + * Executes a callback before render in a shared frame loop. + * Can order effects with render priority or manually render with a positive priority. + * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe + */ - this.currentForm.mipMapLevel = this.reader.getFloat32(); - }, +function useFrame(callback, renderPriority = 0) { + const store = useStore$1(); + const subscribe = store.getState().internal.subscribe; // Memoize ref - // LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node) - parseImageMap(length) { - this.currentFormEnd = this.reader.offset + length; - this.parentForm = this.currentForm; - if (!this.currentForm.maps) this.currentForm.maps = []; - var map = {}; - this.currentForm.maps.push(map); - this.currentForm = map; - this.reader.skip(10); // unknown, could be an issue if it contains a VX - }, + const ref = useMutableCallback(callback); // Subscribe on mount, unsubscribe on unmount - parseTextureNodeAttribute(type) { - this.reader.skip(28); // FORM + length + VPRM + unknown + Uint32 x2 + float32 + useIsomorphicLayoutEffect$1(() => subscribe(ref, renderPriority, store), [renderPriority, subscribe, store]); + return null; +} - this.reader.skip(20); // FORM + length + VPVL + float32 + Uint32 +const roots = new Map(); +const { + invalidate, + advance: advance$1 +} = createLoop(roots); +const { + reconciler, + applyProps +} = createRenderer(roots, getEventPriority); +const shallowLoose = { + objects: 'shallow', + strict: false +}; - switch (type) { - case 'ISCL': - this.currentNode.scale = this.reader.getFloat32Array(3); - break; +const createRendererInstance = (gl, canvas) => { + const customRenderer = typeof gl === 'function' ? gl(canvas) : gl; + if (isRenderer(customRenderer)) return customRenderer;else return new WebGLRenderer({ + powerPreference: 'high-performance', + canvas: canvas, + antialias: true, + alpha: true, + ...gl + }); +}; - case 'IPOS': - this.currentNode.position = this.reader.getFloat32Array(3); - break; +function createRoot(canvas) { + // Check against mistaken use of createRoot + let prevRoot = roots.get(canvas); + let prevFiber = prevRoot == null ? void 0 : prevRoot.fiber; + let prevStore = prevRoot == null ? void 0 : prevRoot.store; + if (prevRoot) console.warn('R3F.createRoot should only be called once!'); // Report when an error was detected in a previous render + // https://github.com/pmndrs/react-three-fiber/pull/2261 - case 'IROT': - this.currentNode.rotation = this.reader.getFloat32Array(3); - break; + const logRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event, + // emulating an uncaught JavaScript error. + reportError : // In older browsers and test environments, fallback to console.error. + console.error; // Create store - case 'IFAL': - this.currentNode.falloff = this.reader.getFloat32Array(3); - break; + const store = prevStore || createStore$2(invalidate, advance$1); // Create renderer - case 'IBMP': - this.currentNode.amplitude = this.reader.getFloat32(); - break; + const fiber = prevFiber || reconciler.createContainer(store, constants.exports.ConcurrentRoot, null, false, null, '', logRecoverableError, null); // Map it - case 'IUTD': - this.currentNode.uTiles = this.reader.getFloat32(); - break; + if (!prevRoot) roots.set(canvas, { + fiber, + store + }); // Locals - case 'IVTD': - this.currentNode.vTiles = this.reader.getFloat32(); - break; - } + let onCreated; + let configured = false; + return { + configure(props = {}) { + var _canvas$parentElement, _canvas$parentElement2, _canvas$parentElement3, _canvas$parentElement4; - this.reader.skip(2); // unknown - }, + let { + gl: glConfig, + size, + events, + onCreated: onCreatedCallback, + shadows = false, + linear = false, + flat = false, + legacy = false, + orthographic = false, + frameloop = 'always', + dpr = [1, 2], + performance, + raycaster: raycastOptions, + camera: cameraOptions, + onPointerMissed + } = props; + let state = store.getState(); // Set up renderer (one time only!) - // ENVL forms are currently ignored - parseEnvelope(length) { - this.reader.skip(length - 4); // skipping entirely for now - }, + let gl = state.gl; + if (!state.gl) state.set({ + gl: gl = createRendererInstance(glConfig, canvas) + }); // Set up raycaster (one time only!) - /// - // CHUNK PARSING METHODS - /// - // clips can either be defined inside a surface node, or at the top - // level and they have a different format in each case - parseClip(length) { - var tag = this.reader.getIDTag(); // inside surface node + let raycaster = state.raycaster; + if (!raycaster) state.set({ + raycaster: raycaster = new Raycaster() + }); // Set raycaster options - if (tag === 'FORM') { - this.reader.skip(16); - this.currentNode.fileName = this.reader.getString(); - return; - } // otherwise top level + const { + params, + ...options + } = raycastOptions || {}; + if (!is$1.equ(options, raycaster, shallowLoose)) applyProps(raycaster, { ...options + }); + if (!is$1.equ(params, raycaster.params, shallowLoose)) applyProps(raycaster, { + params: { ...raycaster.params, + ...params + } + }); // Create default camera (one time only!) + if (!state.camera) { + const isCamera = cameraOptions instanceof Camera; + const camera = isCamera ? cameraOptions : orthographic ? new OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new PerspectiveCamera(75, 0, 0.1, 1000); - this.reader.setOffset(this.reader.offset - 4); - this.currentFormEnd = this.reader.offset + length; - this.parentForm = this.currentForm; - this.reader.skip(8); // unknown + if (!isCamera) { + camera.position.z = 5; + if (cameraOptions) applyProps(camera, cameraOptions); // Always look at center by default - var texture = { - index: this.reader.getUint32() - }; - this.tree.textures.push(texture); - this.currentForm = texture; - }, + if (!(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0); + } - parseClipLwo2(length) { - var texture = { - index: this.reader.getUint32(), - fileName: '' - }; // seach STIL block + state.set({ + camera + }); + } // Set up XR (one time only!) - while (true) { - var tag = this.reader.getIDTag(); - var n_length = this.reader.getUint16(); - if (tag === 'STIL') { - texture.fileName = this.reader.getString(); - break; - } + if (!state.xr) { + // Handle frame behavior in WebXR + const handleXRFrame = (timestamp, frame) => { + const state = store.getState(); + if (state.frameloop === 'never') return; + advance$1(timestamp, true, state, frame); + }; // Toggle render switching on session - if (n_length >= length) { - break; - } - } - this.tree.textures.push(texture); - this.currentForm = texture; - }, + const handleSessionChange = () => { + const state = store.getState(); + state.gl.xr.enabled = state.gl.xr.isPresenting; + state.gl.xr.setAnimationLoop(state.gl.xr.isPresenting ? handleXRFrame : null); + if (!state.gl.xr.isPresenting) invalidate(state); + }; // WebXR session manager - parseImage() { - this.reader.skip(8); // unknown - this.currentForm.fileName = this.reader.getString(); - }, + const xr = { + connect() { + const gl = store.getState().gl; + gl.xr.addEventListener('sessionstart', handleSessionChange); + gl.xr.addEventListener('sessionend', handleSessionChange); + }, - parseXVAL(type, length) { - var endOffset = this.reader.offset + length - 4; - this.reader.skip(8); - this.currentForm[type] = this.reader.getFloat32(); - this.reader.setOffset(endOffset); // set end offset directly to skip optional envelope - }, + disconnect() { + const gl = store.getState().gl; + gl.xr.removeEventListener('sessionstart', handleSessionChange); + gl.xr.removeEventListener('sessionend', handleSessionChange); + } - parseXVAL3(type, length) { - var endOffset = this.reader.offset + length - 4; - this.reader.skip(8); - this.currentForm[type] = { - x: this.reader.getFloat32(), - y: this.reader.getFloat32(), - z: this.reader.getFloat32() - }; - this.reader.setOffset(endOffset); - }, + }; // Subscribe to WebXR session events - // Tags associated with an object - // OTAG { type[ID4], tag-string[S0] } - parseObjectTag() { - if (!this.tree.objectTags) this.tree.objectTags = {}; - this.tree.objectTags[this.reader.getIDTag()] = { - tagString: this.reader.getString() - }; - }, + if (gl.xr) xr.connect(); + state.set({ + xr + }); + } // Set shadowmap - // Signals the start of a new layer. All the data chunks which follow will be included in this layer until another layer chunk is encountered. - // LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2] - parseLayer(length) { - var layer = { - number: this.reader.getUint16(), - flags: this.reader.getUint16(), - // If the least significant bit of flags is set, the layer is hidden. - pivot: this.reader.getFloat32Array(3), - // Note: this seems to be superflous, as the geometry is translated when pivot is present - name: this.reader.getString() - }; - this.tree.layers.push(layer); - this.currentLayer = layer; - var parsedLength = 16 + stringOffset(this.currentLayer.name); // index ( 2 ) + flags( 2 ) + pivot( 12 ) + stringlength - // if we have not reached then end of the layer block, there must be a parent defined - this.currentLayer.parent = parsedLength < length ? this.reader.getUint16() : -1; // omitted or -1 for no parent - }, + if (gl.shadowMap) { + const isBoolean = is$1.boo(shadows); - // VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors - // Converting from left to right handed coordinate system: - // x -> -x and switch material FrontSide -> BackSide - parsePoints(length) { - this.currentPoints = []; + if (isBoolean && gl.shadowMap.enabled !== shadows || !is$1.equ(shadows, gl.shadowMap, shallowLoose)) { + const old = gl.shadowMap.enabled; + gl.shadowMap.enabled = !!shadows; + if (!isBoolean) Object.assign(gl.shadowMap, shadows);else gl.shadowMap.type = PCFSoftShadowMap; + if (old !== gl.shadowMap.enabled) gl.shadowMap.needsUpdate = true; + } + } // Safely set color management if available. + // Avoid accessing THREE.ColorManagement to play nice with older versions - for (let i = 0; i < length / 4; i += 3) { - // z -> -z to match three.js right handed coords - this.currentPoints.push(this.reader.getFloat32(), this.reader.getFloat32(), -this.reader.getFloat32()); - } - }, - // parse VMAP or VMAD - // Associates a set of floating-point vectors with a set of points. - // VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * } - // VMAD Associates a set of floating-point vectors with the vertices of specific polygons. - // Similar to VMAP UVs, but associates with polygon vertices rather than points - // to solve to problem of UV seams: VMAD chunks are paired with VMAPs of the same name, - // if they exist. The vector values in the VMAD will then replace those in the - // corresponding VMAP, but only for calculations involving the specified polygons. - // VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * } - parseVertexMapping(length, discontinuous) { - var finalOffset = this.reader.offset + length; - var channelName = this.reader.getString(); - - if (this.reader.offset === finalOffset) { - // then we are in a texture node and the VMAP chunk is just a reference to a UV channel name - this.currentForm.UVChannel = channelName; - return; - } // otherwise reset to initial length and parse normal VMAP CHUNK - - - this.reader.setOffset(this.reader.offset - stringOffset(channelName)); - var type = this.reader.getIDTag(); - this.reader.getUint16(); // dimension - - var name = this.reader.getString(); - var remainingLength = length - 6 - stringOffset(name); - - switch (type) { - case 'TXUV': - this.parseUVMapping(name, finalOffset, discontinuous); - break; + if ('ColorManagement' in THREE) { + setDeep(THREE, legacy, ['ColorManagement', 'legacyMode']); + } - case 'MORF': - case 'SPOT': - this.parseMorphTargets(name, finalOffset, type); // can't be discontinuous + const outputEncoding = linear ? LinearEncoding : sRGBEncoding; + const toneMapping = flat ? NoToneMapping : ACESFilmicToneMapping; + if (gl.outputEncoding !== outputEncoding) gl.outputEncoding = outputEncoding; + if (gl.toneMapping !== toneMapping) gl.toneMapping = toneMapping; // Update color management state - break; - // unsupported VMAPs - - case 'APSL': - case 'NORM': - case 'WGHT': - case 'MNVW': - case 'PICK': - case 'RGB ': - case 'RGBA': - this.reader.skip(remainingLength); - break; + if (state.legacy !== legacy) state.set(() => ({ + legacy + })); + if (state.linear !== linear) state.set(() => ({ + linear + })); + if (state.flat !== flat) state.set(() => ({ + flat + })); // Set gl props - default: - console.warn('LWOLoader: unknown vertex map type: ' + type); - this.reader.skip(remainingLength); - } - }, + if (glConfig && !is$1.fun(glConfig) && !isRenderer(glConfig) && !is$1.equ(glConfig, gl, shallowLoose)) applyProps(gl, glConfig); // Store events internally - parseUVMapping(name, finalOffset, discontinuous) { - var uvIndices = []; - var polyIndices = []; - var uvs = []; + if (events && !state.events.handlers) state.set({ + events: events(store) + }); // Check pixelratio - while (this.reader.offset < finalOffset) { - uvIndices.push(this.reader.getVariableLengthIndex()); - if (discontinuous) polyIndices.push(this.reader.getVariableLengthIndex()); - uvs.push(this.reader.getFloat32(), this.reader.getFloat32()); - } + if (dpr && state.viewport.dpr !== calculateDpr(dpr)) state.setDpr(dpr); // Check size, allow it to take on container bounds initially - if (discontinuous) { - if (!this.currentLayer.discontinuousUVs) this.currentLayer.discontinuousUVs = {}; - this.currentLayer.discontinuousUVs[name] = { - uvIndices: uvIndices, - polyIndices: polyIndices, - uvs: uvs - }; - } else { - if (!this.currentLayer.uvs) this.currentLayer.uvs = {}; - this.currentLayer.uvs[name] = { - uvIndices: uvIndices, - uvs: uvs + size = size || { + width: (_canvas$parentElement = (_canvas$parentElement2 = canvas.parentElement) == null ? void 0 : _canvas$parentElement2.clientWidth) != null ? _canvas$parentElement : 0, + height: (_canvas$parentElement3 = (_canvas$parentElement4 = canvas.parentElement) == null ? void 0 : _canvas$parentElement4.clientHeight) != null ? _canvas$parentElement3 : 0 }; - } - }, + if (!is$1.equ(size, state.size, shallowLoose)) state.setSize(size.width, size.height, size.updateStyle); // Check frameloop - parseMorphTargets(name, finalOffset, type) { - var indices = []; - var points = []; - type = type === 'MORF' ? 'relative' : 'absolute'; + if (state.frameloop !== frameloop) state.setFrameloop(frameloop); // Check pointer missed - while (this.reader.offset < finalOffset) { - indices.push(this.reader.getVariableLengthIndex()); // z -> -z to match three.js right handed coords + if (!state.onPointerMissed) state.set({ + onPointerMissed + }); // Check performance - points.push(this.reader.getFloat32(), this.reader.getFloat32(), -this.reader.getFloat32()); - } + if (performance && !is$1.equ(performance, state.performance, shallowLoose)) state.set(state => ({ + performance: { ...state.performance, + ...performance + } + })); // Set locals - if (!this.currentLayer.morphTargets) this.currentLayer.morphTargets = {}; - this.currentLayer.morphTargets[name] = { - indices: indices, - points: points, - type: type - }; - }, + onCreated = onCreatedCallback; + configured = true; + return this; + }, - // A list of polygons for the current layer. - // POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * } - parsePolygonList(length) { - var finalOffset = this.reader.offset + length; - var type = this.reader.getIDTag(); - var indices = []; // hold a list of polygon sizes, to be split up later + render(children) { + // The root has to be configured before it can be rendered + if (!configured) this.configure(); + reconciler.updateContainer( /*#__PURE__*/React.createElement(Provider, { + store: store, + children: children, + onCreated: onCreated, + rootElement: canvas + }), fiber, null, () => undefined); + return store; + }, - var polygonDimensions = []; + unmount() { + unmountComponentAtNode(canvas); + } - while (this.reader.offset < finalOffset) { - var numverts = this.reader.getUint16(); //var flags = numverts & 64512; // 6 high order bits are flags - ignoring for now + }; +} - numverts = numverts & 1023; // remaining ten low order bits are vertex num +function Provider({ + store, + children, + onCreated, + rootElement +}) { + useIsomorphicLayoutEffect$1(() => { + const state = store.getState(); // Flag the canvas active, rendering will now begin - polygonDimensions.push(numverts); + state.set(state => ({ + internal: { ...state.internal, + active: true + } + })); // Notifiy that init is completed, the scene graph exists, but nothing has yet rendered - for (let j = 0; j < numverts; j++) indices.push(this.reader.getVariableLengthIndex()); - } + if (onCreated) onCreated(state); // Connect events to the targets parent, this is done to ensure events are registered on + // a shared target, and not on the canvas itself - var geometryData = { - type: type, - vertexIndices: indices, - polygonDimensions: polygonDimensions, - points: this.currentPoints - }; // Note: assuming that all polys will be lines or points if the first is + if (!store.getState().events.connected) state.events.connect == null ? void 0 : state.events.connect(rootElement); // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + return /*#__PURE__*/React.createElement(context.Provider, { + value: store + }, children); +} - if (polygonDimensions[0] === 1) geometryData.type = 'points';else if (polygonDimensions[0] === 2) geometryData.type = 'lines'; - this.currentLayer.geometry = geometryData; - }, +function unmountComponentAtNode(canvas, callback) { + const root = roots.get(canvas); + const fiber = root == null ? void 0 : root.fiber; - // Lists the tag strings that can be associated with polygons by the PTAG chunk. - // TAGS { tag-string[S0] * } - parseTagStrings(length) { - this.tree.tags = this.reader.getStringArray(length); - }, + if (fiber) { + const state = root == null ? void 0 : root.store.getState(); + if (state) state.internal.active = false; + reconciler.updateContainer(null, fiber, null, () => { + if (state) { + setTimeout(() => { + try { + var _state$gl, _state$gl$renderLists, _state$gl2, _state$gl3; - // Associates tags of a given type with polygons in the most recent POLS chunk. - // PTAG { type[ID4], ( poly[VX], tag[U2] ) * } - parsePolygonTagMapping(length) { - var finalOffset = this.reader.offset + length; - var type = this.reader.getIDTag(); + state.events.disconnect == null ? void 0 : state.events.disconnect(); + (_state$gl = state.gl) == null ? void 0 : (_state$gl$renderLists = _state$gl.renderLists) == null ? void 0 : _state$gl$renderLists.dispose == null ? void 0 : _state$gl$renderLists.dispose(); + (_state$gl2 = state.gl) == null ? void 0 : _state$gl2.forceContextLoss == null ? void 0 : _state$gl2.forceContextLoss(); + if ((_state$gl3 = state.gl) != null && _state$gl3.xr) state.xr.disconnect(); + dispose(state); + roots.delete(canvas); + if (callback) callback(canvas); + } catch (e) { + /* ... */ + } + }, 500); + } + }); + } +} - if (type === 'SURF') { - this.parseMaterialIndices(finalOffset); - } else { - //PART, SMGP, COLR not supported - this.reader.skip(length - 4); - } - }, +reconciler.injectIntoDevTools({ + bundleType: process.env.NODE_ENV === 'production' ? 0 : 1, + rendererPackageName: '@react-three/fiber', + version: React.version +}); - parseMaterialIndices(finalOffset) { - // array holds polygon index followed by material index - this.currentLayer.geometry.materialIndices = []; +function _extends$3() { + _extends$3 = Object.assign ? Object.assign.bind() : function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - while (this.reader.offset < finalOffset) { - var polygonIndex = this.reader.getVariableLengthIndex(); - var materialIndex = this.reader.getUint16(); - this.currentLayer.geometry.materialIndices.push(polygonIndex, materialIndex); + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } } - }, - - parseUnknownCHUNK(blockID, length) { - console.warn('LWOLoader: unknown chunk type: ' + blockID + ' length: ' + length); // print the chunk plus some bytes padding either side - // printBuffer( this.reader.dv.buffer, this.reader.offset - 20, length + 40 ); - var data = this.reader.getString(length); - this.currentForm[blockID] = data; - } + return target; + }; + return _extends$3.apply(this, arguments); +} -}; +/** + * Returns a function, that, as long as it continues to be invoked, will not + * be triggered. The function will be called after it stops being called for + * N milliseconds. If `immediate` is passed, trigger the function on the + * leading edge, instead of the trailing. The function also has a property 'clear' + * that is a function which will clear the timer to prevent previously scheduled executions. + * + * @source underscore.js + * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ + * @param {Function} function to wrap + * @param {Number} timeout in ms (`100`) + * @param {Boolean} whether to execute at the beginning (`false`) + * @api public + */ -function DataViewReader(buffer) { - this.dv = new DataView(buffer); - this.offset = 0; -} +function debounce(func, wait, immediate){ + var timeout, args, context, timestamp, result; + if (null == wait) wait = 100; -DataViewReader.prototype = { - constructor: DataViewReader, - size: function () { - return this.dv.buffer.byteLength; - }, + function later() { + var last = Date.now() - timestamp; - setOffset(offset) { - if (offset > 0 && offset < this.dv.buffer.byteLength) { - this.offset = offset; + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); } else { - console.error('LWOLoader: invalid buffer offset'); + timeout = null; + if (!immediate) { + result = func.apply(context, args); + context = args = null; + } } - }, - - endOfFile: function () { - if (this.offset >= this.size()) return true; - return false; - }, - skip: function (length) { - this.offset += length; - }, - getUint8: function () { - var value = this.dv.getUint8(this.offset); - this.offset += 1; - return value; - }, - getUint16: function () { - var value = this.dv.getUint16(this.offset); - this.offset += 2; - return value; - }, - getInt32: function () { - var value = this.dv.getInt32(this.offset, false); - this.offset += 4; - return value; - }, - getUint32: function () { - var value = this.dv.getUint32(this.offset, false); - this.offset += 4; - return value; - }, - getUint64: function () { - var low, high; - high = this.getUint32(); - low = this.getUint32(); - return high * 0x100000000 + low; - }, - getFloat32: function () { - var value = this.dv.getFloat32(this.offset, false); - this.offset += 4; - return value; - }, - getFloat32Array: function (size) { - var a = []; - - for (let i = 0; i < size; i++) { - a.push(this.getFloat32()); + } + var debounced = function(){ + context = this; + args = arguments; + timestamp = Date.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; } - return a; - }, - getFloat64: function () { - var value = this.dv.getFloat64(this.offset, this.littleEndian); - this.offset += 8; - return value; - }, - getFloat64Array: function (size) { - var a = []; + return result; + }; - for (let i = 0; i < size; i++) { - a.push(this.getFloat64()); + debounced.clear = function() { + if (timeout) { + clearTimeout(timeout); + timeout = null; } - - return a; - }, - - // get variable-length index data type - // VX ::= index[U2] | (index + 0xFF000000)[U4] - // If the index value is less than 65,280 (0xFF00),then VX === U2 - // otherwise VX === U4 with bits 24-31 set - // When reading an index, if the first byte encountered is 255 (0xFF), then - // the four-byte form is being used and the first byte should be discarded or masked out. - getVariableLengthIndex() { - var firstByte = this.getUint8(); - - if (firstByte === 255) { - return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8(); + }; + + debounced.flush = function() { + if (timeout) { + result = func.apply(context, args); + context = args = null; + + clearTimeout(timeout); + timeout = null; } + }; - return firstByte * 256 + this.getUint8(); - }, - - // An ID tag is a sequence of 4 bytes containing 7-bit ASCII values - getIDTag() { - return this.getString(4); - }, - - getString: function (size) { - if (size === 0) return; // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead + return debounced; +} +// Adds compatibility for ES modules +debounce.debounce = debounce; - var a = []; +var debounce_1 = debounce; - if (size) { - for (let i = 0; i < size; i++) { - a[i] = this.getUint8(); - } - } else { - var currentChar; - var len = 0; +function useMeasure(_temp) { + let { + debounce, + scroll, + polyfill, + offsetSize + } = _temp === void 0 ? { + debounce: 0, + scroll: false, + offsetSize: false + } : _temp; + const ResizeObserver = polyfill || (typeof window === 'undefined' ? class ResizeObserver {} : window.ResizeObserver); - while (currentChar !== 0) { - currentChar = this.getUint8(); - if (currentChar !== 0) a.push(currentChar); - len++; - } + if (!ResizeObserver) { + throw new Error('This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills'); + } - if (!isEven(len + 1)) this.getUint8(); // if string with terminating nullbyte is uneven, extra nullbyte is added - } + const [bounds, set] = useState({ + left: 0, + top: 0, + width: 0, + height: 0, + bottom: 0, + right: 0, + x: 0, + y: 0 + }); // keep all state in a ref - return LoaderUtils.decodeText(new Uint8Array(a)); - }, - getStringArray: function (size) { - var a = this.getString(size); - a = a.split('\0'); - return a.filter(Boolean); // return array with any empty strings removed - } -}; // ************** DEBUGGER ************** + const state = useRef({ + element: null, + scrollContainers: null, + resizeObserver: null, + lastBounds: bounds + }); // set actual debounce values early, so effects know if they should react accordingly -function Debugger() { - this.active = false; - this.depth = 0; - this.formList = []; -} + const scrollDebounce = debounce ? typeof debounce === 'number' ? debounce : debounce.scroll : null; + const resizeDebounce = debounce ? typeof debounce === 'number' ? debounce : debounce.resize : null; // make sure to update state only as long as the component is truly mounted -Debugger.prototype = { - constructor: Debugger, - enable: function () { - this.active = true; - }, - log: function () { - if (!this.active) return; - var nodeType; + const mounted = useRef(false); + useEffect(() => { + mounted.current = true; + return () => void (mounted.current = false); + }); // memoize handlers, so event-listeners know when they should update - switch (this.node) { - case 0: - nodeType = 'FORM'; - break; + const [forceRefresh, resizeChange, scrollChange] = useMemo(() => { + const callback = () => { + if (!state.current.element) return; + const { + left, + top, + width, + height, + bottom, + right, + x, + y + } = state.current.element.getBoundingClientRect(); + const size = { + left, + top, + width, + height, + bottom, + right, + x, + y + }; - case 1: - nodeType = 'CHK'; - break; + if (state.current.element instanceof HTMLElement && offsetSize) { + size.height = state.current.element.offsetHeight; + size.width = state.current.element.offsetWidth; + } - case 2: - nodeType = 'S-CHK'; - break; - } + Object.freeze(size); + if (mounted.current && !areBoundsEqual(state.current.lastBounds, size)) set(state.current.lastBounds = size); + }; - console.log('| '.repeat(this.depth) + nodeType, this.nodeID, `( ${this.offset} ) -> ( ${this.dataOffset + this.length} )`, this.node == 0 ? ' {' : '', this.skipped ? 'SKIPPED' : '', this.node == 0 && this.skipped ? '}' : ''); + return [callback, resizeDebounce ? debounce_1(callback, resizeDebounce) : callback, scrollDebounce ? debounce_1(callback, scrollDebounce) : callback]; + }, [set, offsetSize, scrollDebounce, resizeDebounce]); // cleanup current scroll-listeners / observers - if (this.node == 0 && !this.skipped) { - this.depth += 1; - this.formList.push(this.dataOffset + this.length); + function removeListeners() { + if (state.current.scrollContainers) { + state.current.scrollContainers.forEach(element => element.removeEventListener('scroll', scrollChange, true)); + state.current.scrollContainers = null; } - this.skipped = false; - }, - closeForms: function () { - if (!this.active) return; - - for (let i = this.formList.length - 1; i >= 0; i--) { - if (this.offset >= this.formList[i]) { - this.depth -= 1; - console.log('| '.repeat(this.depth) + '}'); - this.formList.splice(-1, 1); - } + if (state.current.resizeObserver) { + state.current.resizeObserver.disconnect(); + state.current.resizeObserver = null; } - } -}; // ************** UTILITY FUNCTIONS ************** + } // add scroll-listeners / observers -function isEven(num) { - return num % 2; -} // calculate the length of the string in the buffer -// this will be string.length + nullbyte + optional padbyte to make the length even + function addListeners() { + if (!state.current.element) return; + state.current.resizeObserver = new ResizeObserver(scrollChange); + state.current.resizeObserver.observe(state.current.element); -function stringOffset(string) { - return string.length + 1 + (isEven(string.length + 1) ? 1 : 0); -} // for testing purposes, dump buffer to console -// printBuffer( this.reader.dv.buffer, this.reader.offset, length ); + if (scroll && state.current.scrollContainers) { + state.current.scrollContainers.forEach(scrollContainer => scrollContainer.addEventListener('scroll', scrollChange, { + capture: true, + passive: true + })); + } + } // the ref we expose to the user -function printBuffer(buffer, from, to) { - console.log(LoaderUtils.decodeText(new Uint8Array(buffer, from, to))); -} + const ref = node => { + if (!node || node === state.current.element) return; + removeListeners(); + state.current.element = node; + state.current.scrollContainers = findScrollContainers(node); + addListeners(); + }; // add general event listeners -new Vector3(); -new Vector3(); + useOnWindowScroll(scrollChange, Boolean(scroll)); + useOnWindowResize(resizeChange); // respond to changes that are relevant for the listeners -new Vector3(); + useEffect(() => { + removeListeners(); + addListeners(); + }, [scroll, scrollChange, resizeChange]); // remove all listeners when the components unmounts -new Vector3(); + useEffect(() => removeListeners, []); + return [ref, bounds, forceRefresh]; +} // Adds native resize listener to window -new Vector3(); -var UPNG = {}; - -UPNG.toRGBA8 = function (out) { - var w = out.width, - h = out.height; - if (out.tabs.acTL == null) return [UPNG.toRGBA8.decodeImage(out.data, w, h, out).buffer]; - var frms = []; - if (out.frames[0].data == null) out.frames[0].data = out.data; - var len = w * h * 4, - img = new Uint8Array(len), - empty = new Uint8Array(len), - prev = new Uint8Array(len); - - for (var i = 0; i < out.frames.length; i++) { - var frm = out.frames[i]; - var fx = frm.rect.x, - fy = frm.rect.y, - fw = frm.rect.width, - fh = frm.rect.height; - var fdata = UPNG.toRGBA8.decodeImage(frm.data, fw, fh, out); - if (i != 0) for (var j = 0; j < len; j++) prev[j] = img[j]; - if (frm.blend == 0) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 0);else if (frm.blend == 1) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 1); - frms.push(img.buffer.slice(0)); - if (frm.dispose == 1) UPNG._copyTile(empty, fw, fh, img, w, h, fx, fy, 0);else if (frm.dispose == 2) for (var j = 0; j < len; j++) img[j] = prev[j]; - } - - return frms; -}; +function useOnWindowResize(onWindowResize) { + useEffect(() => { + const cb = onWindowResize; + window.addEventListener('resize', cb); + return () => void window.removeEventListener('resize', cb); + }, [onWindowResize]); +} -UPNG.toRGBA8.decodeImage = function (data, w, h, out) { - var area = w * h, - bpp = UPNG.decode._getBPP(out); - - var bpl = Math.ceil(w * bpp / 8); // bytes per line - - var bf = new Uint8Array(area * 4), - bf32 = new Uint32Array(bf.buffer); - var ctype = out.ctype, - depth = out.depth; - var rs = UPNG._bin.readUshort; - - if (ctype == 6) { - // RGB + alpha - var qarea = area << 2; - if (depth == 8) for (var i = 0; i < qarea; i += 4) { - bf[i] = data[i]; - bf[i + 1] = data[i + 1]; - bf[i + 2] = data[i + 2]; - bf[i + 3] = data[i + 3]; - } - if (depth == 16) for (var i = 0; i < qarea; i++) { - bf[i] = data[i << 1]; - } - } else if (ctype == 2) { - // RGB - var ts = out.tabs['tRNS']; - - if (ts == null) { - if (depth == 8) for (var i = 0; i < area; i++) { - var ti = i * 3; - bf32[i] = 255 << 24 | data[ti + 2] << 16 | data[ti + 1] << 8 | data[ti]; - } - if (depth == 16) for (var i = 0; i < area; i++) { - var ti = i * 6; - bf32[i] = 255 << 24 | data[ti + 4] << 16 | data[ti + 2] << 8 | data[ti]; - } - } else { - var tr = ts[0], - tg = ts[1], - tb = ts[2]; - if (depth == 8) for (var i = 0; i < area; i++) { - var qi = i << 2, - ti = i * 3; - bf32[i] = 255 << 24 | data[ti + 2] << 16 | data[ti + 1] << 8 | data[ti]; - if (data[ti] == tr && data[ti + 1] == tg && data[ti + 2] == tb) bf[qi + 3] = 0; - } - if (depth == 16) for (var i = 0; i < area; i++) { - var qi = i << 2, - ti = i * 6; - bf32[i] = 255 << 24 | data[ti + 4] << 16 | data[ti + 2] << 8 | data[ti]; - if (rs(data, ti) == tr && rs(data, ti + 2) == tg && rs(data, ti + 4) == tb) bf[qi + 3] = 0; - } - } - } else if (ctype == 3) { - // palette - var p = out.tabs['PLTE'], - ap = out.tabs['tRNS'], - tl = ap ? ap.length : 0; //console.log(p, ap); - - if (depth == 1) for (var y = 0; y < h; y++) { - var s0 = y * bpl, - t0 = y * w; - - for (var i = 0; i < w; i++) { - var qi = t0 + i << 2, - j = data[s0 + (i >> 3)] >> 7 - ((i & 7) << 0) & 1, - cj = 3 * j; - bf[qi] = p[cj]; - bf[qi + 1] = p[cj + 1]; - bf[qi + 2] = p[cj + 2]; - bf[qi + 3] = j < tl ? ap[j] : 255; - } - } - if (depth == 2) for (var y = 0; y < h; y++) { - var s0 = y * bpl, - t0 = y * w; - - for (var i = 0; i < w; i++) { - var qi = t0 + i << 2, - j = data[s0 + (i >> 2)] >> 6 - ((i & 3) << 1) & 3, - cj = 3 * j; - bf[qi] = p[cj]; - bf[qi + 1] = p[cj + 1]; - bf[qi + 2] = p[cj + 2]; - bf[qi + 3] = j < tl ? ap[j] : 255; - } - } - if (depth == 4) for (var y = 0; y < h; y++) { - var s0 = y * bpl, - t0 = y * w; - - for (var i = 0; i < w; i++) { - var qi = t0 + i << 2, - j = data[s0 + (i >> 1)] >> 4 - ((i & 1) << 2) & 15, - cj = 3 * j; - bf[qi] = p[cj]; - bf[qi + 1] = p[cj + 1]; - bf[qi + 2] = p[cj + 2]; - bf[qi + 3] = j < tl ? ap[j] : 255; - } - } - if (depth == 8) for (var i = 0; i < area; i++) { - var qi = i << 2, - j = data[i], - cj = 3 * j; - bf[qi] = p[cj]; - bf[qi + 1] = p[cj + 1]; - bf[qi + 2] = p[cj + 2]; - bf[qi + 3] = j < tl ? ap[j] : 255; - } - } else if (ctype == 4) { - // gray + alpha - if (depth == 8) for (var i = 0; i < area; i++) { - var qi = i << 2, - di = i << 1, - gr = data[di]; - bf[qi] = gr; - bf[qi + 1] = gr; - bf[qi + 2] = gr; - bf[qi + 3] = data[di + 1]; - } - if (depth == 16) for (var i = 0; i < area; i++) { - var qi = i << 2, - di = i << 2, - gr = data[di]; - bf[qi] = gr; - bf[qi + 1] = gr; - bf[qi + 2] = gr; - bf[qi + 3] = data[di + 2]; - } - } else if (ctype == 0) { - // gray - var tr = out.tabs['tRNS'] ? out.tabs['tRNS'] : -1; - - for (var y = 0; y < h; y++) { - var off = y * bpl, - to = y * w; - if (depth == 1) for (var x = 0; x < w; x++) { - var gr = 255 * (data[off + (x >>> 3)] >>> 7 - (x & 7) & 1), - al = gr == tr * 255 ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } else if (depth == 2) for (var x = 0; x < w; x++) { - var gr = 85 * (data[off + (x >>> 2)] >>> 6 - ((x & 3) << 1) & 3), - al = gr == tr * 85 ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } else if (depth == 4) for (var x = 0; x < w; x++) { - var gr = 17 * (data[off + (x >>> 1)] >>> 4 - ((x & 1) << 2) & 15), - al = gr == tr * 17 ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } else if (depth == 8) for (var x = 0; x < w; x++) { - var gr = data[off + x], - al = gr == tr ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } else if (depth == 16) for (var x = 0; x < w; x++) { - var gr = data[off + (x << 1)], - al = rs(data, off + (x << 1)) == tr ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } +function useOnWindowScroll(onScroll, enabled) { + useEffect(() => { + if (enabled) { + const cb = onScroll; + window.addEventListener('scroll', cb, { + capture: true, + passive: true + }); + return () => void window.removeEventListener('scroll', cb, true); } - } //console.log(Date.now()-time); - + }, [onScroll, enabled]); +} // Returns a list of scroll offsets - return bf; -}; -UPNG.decode = function (buff) { - var data = new Uint8Array(buff), - offset = 8, - bin = UPNG._bin, - rUs = bin.readUshort, - rUi = bin.readUint; - var out = { - tabs: {}, - frames: [] - }; - var dd = new Uint8Array(data.length), - doff = 0; // put all IDAT data into it - - var fd, - foff = 0; // frames - - var text, keyw, bfr; - var mgck = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; - - for (var i = 0; i < 8; i++) if (data[i] != mgck[i]) throw new Error('The input is not a PNG file!'); - - while (offset < data.length) { - var len = bin.readUint(data, offset); - offset += 4; - var type = bin.readASCII(data, offset, 4); - offset += 4; //console.log(type,len); - - if (type == 'IHDR') { - UPNG.decode._IHDR(data, offset, out); - } else if (type == 'CgBI') { - out.tabs[type] = data.slice(offset, offset + 4); - } else if (type == 'IDAT') { - for (var i = 0; i < len; i++) dd[doff + i] = data[offset + i]; - - doff += len; - } else if (type == 'acTL') { - out.tabs[type] = { - num_frames: rUi(data, offset), - num_plays: rUi(data, offset + 4) - }; - fd = new Uint8Array(data.length); - } else if (type == 'fcTL') { - if (foff != 0) { - var fr = out.frames[out.frames.length - 1]; - fr.data = UPNG.decode._decompress(out, fd.slice(0, foff), fr.rect.width, fr.rect.height); - foff = 0; - } +function findScrollContainers(element) { + const result = []; + if (!element || element === document.body) return result; + const { + overflow, + overflowX, + overflowY + } = window.getComputedStyle(element); + if ([overflow, overflowX, overflowY].some(prop => prop === 'auto' || prop === 'scroll')) result.push(element); + return [...result, ...findScrollContainers(element.parentElement)]; +} // Checks if element boundaries are equal - var rct = { - x: rUi(data, offset + 12), - y: rUi(data, offset + 16), - width: rUi(data, offset + 4), - height: rUi(data, offset + 8) - }; - var del = rUs(data, offset + 22); - del = rUs(data, offset + 20) / (del == 0 ? 100 : del); - var frm = { - rect: rct, - delay: Math.round(del * 1000), - dispose: data[offset + 24], - blend: data[offset + 25] - }; //console.log(frm); - - out.frames.push(frm); - } else if (type == 'fdAT') { - for (var i = 0; i < len - 4; i++) fd[foff + i] = data[offset + i + 4]; - - foff += len - 4; - } else if (type == 'pHYs') { - out.tabs[type] = [bin.readUint(data, offset), bin.readUint(data, offset + 4), data[offset + 8]]; - } else if (type == 'cHRM') { - out.tabs[type] = []; - - for (var i = 0; i < 8; i++) out.tabs[type].push(bin.readUint(data, offset + i * 4)); - } else if (type == 'tEXt' || type == 'zTXt') { - if (out.tabs[type] == null) out.tabs[type] = {}; - var nz = bin.nextZero(data, offset); - keyw = bin.readASCII(data, offset, nz - offset); - var tl = offset + len - nz - 1; - if (type == 'tEXt') text = bin.readASCII(data, nz + 1, tl);else { - bfr = UPNG.decode._inflate(data.slice(nz + 2, nz + 2 + tl)); - text = bin.readUTF8(bfr, 0, bfr.length); - } - out.tabs[type][keyw] = text; - } else if (type == 'iTXt') { - if (out.tabs[type] == null) out.tabs[type] = {}; - var nz = 0, - off = offset; - nz = bin.nextZero(data, off); - keyw = bin.readASCII(data, off, nz - off); - off = nz + 1; - var cflag = data[off]; - off += 2; - nz = bin.nextZero(data, off); - bin.readASCII(data, off, nz - off); - off = nz + 1; - nz = bin.nextZero(data, off); - bin.readUTF8(data, off, nz - off); - off = nz + 1; - var tl = len - (off - offset); - if (cflag == 0) text = bin.readUTF8(data, off, tl);else { - bfr = UPNG.decode._inflate(data.slice(off, off + tl)); - text = bin.readUTF8(bfr, 0, bfr.length); - } - out.tabs[type][keyw] = text; - } else if (type == 'PLTE') { - out.tabs[type] = bin.readBytes(data, offset, len); - } else if (type == 'hIST') { - var pl = out.tabs['PLTE'].length / 3; - out.tabs[type] = []; - - for (var i = 0; i < pl; i++) out.tabs[type].push(rUs(data, offset + i * 2)); - } else if (type == 'tRNS') { - if (out.ctype == 3) out.tabs[type] = bin.readBytes(data, offset, len);else if (out.ctype == 0) out.tabs[type] = rUs(data, offset);else if (out.ctype == 2) out.tabs[type] = [rUs(data, offset), rUs(data, offset + 2), rUs(data, offset + 4)]; //else console.log("tRNS for unsupported color type",out.ctype, len); - } else if (type == 'gAMA') out.tabs[type] = bin.readUint(data, offset) / 100000;else if (type == 'sRGB') out.tabs[type] = data[offset];else if (type == 'bKGD') { - if (out.ctype == 0 || out.ctype == 4) out.tabs[type] = [rUs(data, offset)];else if (out.ctype == 2 || out.ctype == 6) out.tabs[type] = [rUs(data, offset), rUs(data, offset + 2), rUs(data, offset + 4)];else if (out.ctype == 3) out.tabs[type] = data[offset]; - } else if (type == 'IEND') { - break; - } //else { console.log("unknown chunk type", type, len); out.tabs[type]=data.slice(offset,offset+len); } - - - offset += len; - bin.readUint(data, offset); - offset += 4; - } - - if (foff != 0) { - var fr = out.frames[out.frames.length - 1]; - fr.data = UPNG.decode._decompress(out, fd.slice(0, foff), fr.rect.width, fr.rect.height); - } - - out.data = UPNG.decode._decompress(out, dd, out.width, out.height); - delete out.compress; - delete out.interlace; - delete out.filter; - return out; -}; -UPNG.decode._decompress = function (out, dd, w, h) { - var bpp = UPNG.decode._getBPP(out), - bpl = Math.ceil(w * bpp / 8), - buff = new Uint8Array((bpl + 1 + out.interlace) * h); +const keys = ['x', 'y', 'top', 'bottom', 'left', 'right', 'width', 'height']; - if (out.tabs['CgBI']) dd = UPNG.inflateRaw(dd, buff);else dd = UPNG.decode._inflate(dd, buff); - if (out.interlace == 0) dd = UPNG.decode._filterZero(dd, out, 0, w, h);else if (out.interlace == 1) dd = UPNG.decode._readInterlace(dd, out); - return dd; -}; +const areBoundsEqual = (a, b) => keys.every(key => a[key] === b[key]); -UPNG.decode._inflate = function (data, buff) { - var out = UPNG['inflateRaw'](new Uint8Array(data.buffer, 2, data.length - 6), buff); - return out; +const DOM_EVENTS = { + onClick: ['click', false], + onContextMenu: ['contextmenu', false], + onDoubleClick: ['dblclick', false], + onWheel: ['wheel', true], + onPointerDown: ['pointerdown', true], + onPointerUp: ['pointerup', true], + onPointerLeave: ['pointerleave', true], + onPointerMove: ['pointermove', true], + onPointerCancel: ['pointercancel', true], + onLostPointerCapture: ['lostpointercapture', true] }; +/** Default R3F event manager for web */ -UPNG.inflateRaw = function () { - var H = {}; - H.H = {}; - - H.H.N = function (N, W) { - var R = Uint8Array, - i = 0, - m = 0, - J = 0, - h = 0, - Q = 0, - X = 0, - u = 0, - w = 0, - d = 0, - v, - C; - if (N[0] == 3 && N[1] == 0) return W ? W : new R(0); - var V = H.H, - n = V.b, - A = V.e, - l = V.R, - M = V.n, - I = V.A, - e = V.Z, - b = V.m, - Z = W == null; - if (Z) W = new R(N.length >>> 2 << 5); - - while (i == 0) { - i = n(N, d, 1); - m = n(N, d + 1, 2); - d += 3; - - if (m == 0) { - if ((d & 7) != 0) d += 8 - (d & 7); - var D = (d >>> 3) + 4, - q = N[D - 4] | N[D - 3] << 8; - if (Z) W = H.H.W(W, w + q); - W.set(new R(N.buffer, N.byteOffset + D, q), w); - d = D + q << 3; - w += q; - continue; - } - - if (Z) W = H.H.W(W, w + (1 << 17)); - - if (m == 1) { - v = b.J; - C = b.h; - X = (1 << 9) - 1; - u = (1 << 5) - 1; - } +function createPointerEvents(store) { + const { + handlePointer + } = createEvents(store); + return { + priority: 1, + enabled: true, - if (m == 2) { - J = A(N, d, 5) + 257; - h = A(N, d + 5, 5) + 1; - Q = A(N, d + 10, 4) + 4; - d += 14; - var j = 1; + compute(event, state, previous) { + // https://github.com/pmndrs/react-three-fiber/pull/782 + // Events trigger outside of canvas when moved, use offsetX/Y by default and allow overrides + state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1); + state.raycaster.setFromCamera(state.pointer, state.camera); + }, - for (var c = 0; c < 38; c += 2) { - b.Q[c] = 0; - b.Q[c + 1] = 0; - } + connected: undefined, + handlers: Object.keys(DOM_EVENTS).reduce((acc, key) => ({ ...acc, + [key]: handlePointer(key) + }), {}), + connect: target => { + var _events$handlers; - for (var c = 0; c < Q; c++) { - var K = A(N, d + c * 3, 3); - b.Q[(b.X[c] << 1) + 1] = K; - if (K > j) j = K; + const { + set, + events + } = store.getState(); + events.disconnect == null ? void 0 : events.disconnect(); + set(state => ({ + events: { ...state.events, + connected: target } + })); + Object.entries((_events$handlers = events.handlers) != null ? _events$handlers : []).forEach(([name, event]) => { + const [eventName, passive] = DOM_EVENTS[name]; + target.addEventListener(eventName, event, { + passive + }); + }); + }, + disconnect: () => { + const { + set, + events + } = store.getState(); - d += 3 * Q; - M(b.Q, j); - I(b.Q, j, b.u); - v = b.w; - C = b.d; - d = l(b.u, (1 << j) - 1, J + h, N, d, b.v); - var r = V.V(b.v, 0, J, b.C); - X = (1 << r) - 1; - var S = V.V(b.v, J, h, b.D); - u = (1 << S) - 1; - M(b.C, r); - I(b.C, r, v); - M(b.D, S); - I(b.D, S, C); - } - - while (!0) { - var T = v[e(N, d) & X]; - d += T & 15; - var p = T >>> 4; - - if (p >>> 8 == 0) { - W[w++] = p; - } else if (p == 256) { - break; - } else { - var z = w + p - 254; + if (events.connected) { + var _events$handlers2; - if (p > 264) { - var _ = b.q[p - 257]; - z = w + (_ >>> 3) + A(N, d, _ & 7); - d += _ & 7; + Object.entries((_events$handlers2 = events.handlers) != null ? _events$handlers2 : []).forEach(([name, event]) => { + if (events && events.connected instanceof HTMLElement) { + const [eventName] = DOM_EVENTS[name]; + events.connected.removeEventListener(eventName, event); } - - var $ = C[e(N, d) & u]; - d += $ & 15; - var s = $ >>> 4, - Y = b.c[s], - a = (Y >>> 4) + n(N, d, Y & 15); - d += Y & 15; - - while (w < z) { - W[w] = W[w++ - a]; - W[w] = W[w++ - a]; - W[w] = W[w++ - a]; - W[w] = W[w++ - a]; + }); + set(state => ({ + events: { ...state.events, + connected: undefined } - - w = z; - } + })); } } - - return W.length == w ? W : W.slice(0, w); - }; - - H.H.W = function (N, W) { - var R = N.length; - if (W <= R) return N; - var V = new Uint8Array(R << 1); - V.set(N, 0); - return V; }; +} - H.H.R = function (N, W, R, V, n, A) { - var l = H.H.e, - M = H.H.Z, - I = 0; - - while (I < R) { - var e = N[M(V, n) & W]; - n += e & 15; - var b = e >>> 4; +/** + * A DOM canvas which accepts threejs elements as children. + * @see https://docs.pmnd.rs/react-three-fiber/api/canvas + */ +const Canvas = /*#__PURE__*/React.forwardRef(function Canvas({ + children, + fallback, + resize, + style, + gl, + events = createPointerEvents, + shadows, + linear, + flat, + legacy, + orthographic, + frameloop, + dpr, + performance, + raycaster, + camera, + onPointerMissed, + onCreated, + ...props +}, forwardedRef) { + // Create a known catalogue of Threejs-native elements + // This will include the entire THREE namespace by default, users can extend + // their own elements by using the createRoot API instead + React.useMemo(() => extend(THREE), []); + const [containerRef, { + width, + height + }] = useMeasure({ + scroll: true, + debounce: { + scroll: 50, + resize: 0 + }, + ...resize + }); + const canvasRef = React.useRef(null); + const divRef = React.useRef(null); + const [canvas, setCanvas] = React.useState(null); + React.useImperativeHandle(forwardedRef, () => canvasRef.current); + const handlePointerMissed = useMutableCallback(onPointerMissed); + const [block, setBlock] = React.useState(false); + const [error, setError] = React.useState(false); // Suspend this component if block is a promise (2nd run) - if (b <= 15) { - A[I] = b; - I++; - } else { - var Z = 0, - m = 0; - - if (b == 16) { - m = 3 + l(V, n, 2); - n += 2; - Z = A[I - 1]; - } else if (b == 17) { - m = 3 + l(V, n, 3); - n += 3; - } else if (b == 18) { - m = 11 + l(V, n, 7); - n += 7; - } + if (block) throw block; // Throw exception outwards if anything within canvas throws - var J = I + m; + if (error) throw error; + const root = React.useRef(null); - while (I < J) { - A[I] = Z; - I++; - } + if (width > 0 && height > 0 && canvas) { + if (!root.current) root.current = createRoot(canvas); + root.current.configure({ + gl, + events, + shadows, + linear, + flat, + legacy, + orthographic, + frameloop, + dpr, + performance, + raycaster, + camera, + size: { + width, + height + }, + // Pass mutable reference to onPointerMissed so it's free to update + onPointerMissed: (...args) => handlePointerMissed.current == null ? void 0 : handlePointerMissed.current(...args), + onCreated: state => { + state.events.connect == null ? void 0 : state.events.connect(divRef.current); + onCreated == null ? void 0 : onCreated(state); } - } - - return n; - }; + }); + root.current.render( /*#__PURE__*/React.createElement(ErrorBoundary, { + set: setError + }, /*#__PURE__*/React.createElement(React.Suspense, { + fallback: /*#__PURE__*/React.createElement(Block, { + set: setBlock + }) + }, children))); + } - H.H.V = function (N, W, R, V) { - var n = 0, - A = 0, - l = V.length >>> 1; - - while (A < R) { - var M = N[A + W]; - V[A << 1] = 0; - V[(A << 1) + 1] = M; - if (M > n) n = M; - A++; + useIsomorphicLayoutEffect$1(() => { + setCanvas(canvasRef.current); + }, []); + React.useEffect(() => { + if (canvas) return () => unmountComponentAtNode(canvas); + }, [canvas]); + return /*#__PURE__*/React.createElement("div", _extends$3({ + ref: divRef, + style: { + position: 'relative', + width: '100%', + height: '100%', + overflow: 'hidden', + ...style } - - while (A < l) { - V[A << 1] = 0; - V[(A << 1) + 1] = 0; - A++; + }, props), /*#__PURE__*/React.createElement("div", { + ref: containerRef, + style: { + width: '100%', + height: '100%' + } + }, /*#__PURE__*/React.createElement("canvas", { + ref: canvasRef, + style: { + display: 'block' } + }, fallback))); +}); - return n; - }; +var resizeObservers = []; + +var hasActiveObservations = function () { + return resizeObservers.some(function (ro) { return ro.activeTargets.length > 0; }); +}; - H.H.n = function (N, W) { - var R = H.H.m, - V = N.length, - n, - A, - l, - M, - I, - e = R.j; +var hasSkippedObservations = function () { + return resizeObservers.some(function (ro) { return ro.skippedTargets.length > 0; }); +}; - for (var M = 0; M <= W; M++) e[M] = 0; +var msg = 'ResizeObserver loop completed with undelivered notifications.'; +var deliverResizeLoopError = function () { + var event; + if (typeof ErrorEvent === 'function') { + event = new ErrorEvent('error', { + message: msg + }); + } + else { + event = document.createEvent('Event'); + event.initEvent('error', false, false); + event.message = msg; + } + window.dispatchEvent(event); +}; - for (M = 1; M < V; M += 2) e[N[M]]++; +var ResizeObserverBoxOptions; +(function (ResizeObserverBoxOptions) { + ResizeObserverBoxOptions["BORDER_BOX"] = "border-box"; + ResizeObserverBoxOptions["CONTENT_BOX"] = "content-box"; + ResizeObserverBoxOptions["DEVICE_PIXEL_CONTENT_BOX"] = "device-pixel-content-box"; +})(ResizeObserverBoxOptions || (ResizeObserverBoxOptions = {})); - var b = R.K; - n = 0; - e[0] = 0; +var freeze = function (obj) { return Object.freeze(obj); }; - for (A = 1; A <= W; A++) { - n = n + e[A - 1] << 1; - b[A] = n; +var ResizeObserverSize = (function () { + function ResizeObserverSize(inlineSize, blockSize) { + this.inlineSize = inlineSize; + this.blockSize = blockSize; + freeze(this); } + return ResizeObserverSize; +}()); - for (l = 0; l < V; l += 2) { - I = N[l + 1]; - - if (I != 0) { - N[l] = b[I]; - b[I]++; - } +var DOMRectReadOnly = (function () { + function DOMRectReadOnly(x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.top = this.y; + this.left = this.x; + this.bottom = this.top + this.height; + this.right = this.left + this.width; + return freeze(this); } - }; + DOMRectReadOnly.prototype.toJSON = function () { + var _a = this, x = _a.x, y = _a.y, top = _a.top, right = _a.right, bottom = _a.bottom, left = _a.left, width = _a.width, height = _a.height; + return { x: x, y: y, top: top, right: right, bottom: bottom, left: left, width: width, height: height }; + }; + DOMRectReadOnly.fromRect = function (rectangle) { + return new DOMRectReadOnly(rectangle.x, rectangle.y, rectangle.width, rectangle.height); + }; + return DOMRectReadOnly; +}()); - H.H.A = function (N, W, R) { - var V = N.length, - n = H.H.m, - A = n.r; - - for (var l = 0; l < V; l += 2) if (N[l + 1] != 0) { - var M = l >> 1, - I = N[l + 1], - e = M << 4 | I, - b = W - I, - Z = N[l] << b, - m = Z + (1 << b); - - while (Z != m) { - var J = A[Z] >>> 15 - W; - R[J] = e; - Z++; - } +var isSVG = function (target) { return target instanceof SVGElement && 'getBBox' in target; }; +var isHidden = function (target) { + if (isSVG(target)) { + var _a = target.getBBox(), width = _a.width, height = _a.height; + return !width && !height; + } + var _b = target, offsetWidth = _b.offsetWidth, offsetHeight = _b.offsetHeight; + return !(offsetWidth || offsetHeight || target.getClientRects().length); +}; +var isElement = function (obj) { + var _a, _b; + if (obj instanceof Element) { + return true; + } + var scope = (_b = (_a = obj) === null || _a === void 0 ? void 0 : _a.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView; + return !!(scope && obj instanceof scope.Element); +}; +var isReplacedElement = function (target) { + switch (target.tagName) { + case 'INPUT': + if (target.type !== 'image') { + break; + } + case 'VIDEO': + case 'AUDIO': + case 'EMBED': + case 'OBJECT': + case 'CANVAS': + case 'IFRAME': + case 'IMG': + return true; } - }; + return false; +}; - H.H.l = function (N, W) { - var R = H.H.m.r, - V = 15 - W; +var global$1 = typeof window !== 'undefined' ? window : {}; - for (var n = 0; n < N.length; n += 2) { - var A = N[n] << W - N[n + 1]; - N[n] = R[A] >>> V; +var cache = new WeakMap(); +var scrollRegexp = /auto|scroll/; +var verticalRegexp = /^tb|vertical/; +var IE = (/msie|trident/i).test(global$1.navigator && global$1.navigator.userAgent); +var parseDimension = function (pixel) { return parseFloat(pixel || '0'); }; +var size = function (inlineSize, blockSize, switchSizes) { + if (inlineSize === void 0) { inlineSize = 0; } + if (blockSize === void 0) { blockSize = 0; } + if (switchSizes === void 0) { switchSizes = false; } + return new ResizeObserverSize((switchSizes ? blockSize : inlineSize) || 0, (switchSizes ? inlineSize : blockSize) || 0); +}; +var zeroBoxes = freeze({ + devicePixelContentBoxSize: size(), + borderBoxSize: size(), + contentBoxSize: size(), + contentRect: new DOMRectReadOnly(0, 0, 0, 0) +}); +var calculateBoxSizes = function (target, forceRecalculation) { + if (forceRecalculation === void 0) { forceRecalculation = false; } + if (cache.has(target) && !forceRecalculation) { + return cache.get(target); } - }; - - H.H.M = function (N, W, R) { - R = R << (W & 7); - var V = W >>> 3; - N[V] |= R; - N[V + 1] |= R >>> 8; - }; - - H.H.I = function (N, W, R) { - R = R << (W & 7); - var V = W >>> 3; - N[V] |= R; - N[V + 1] |= R >>> 8; - N[V + 2] |= R >>> 16; - }; - - H.H.e = function (N, W, R) { - return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R) - 1; - }; - - H.H.b = function (N, W, R) { - return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R) - 1; - }; - - H.H.Z = function (N, W) { - return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7); - }; - - H.H.i = function (N, W) { - return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7); - }; - - H.H.m = function () { - var N = Uint16Array, - W = Uint32Array; - return { - K: new N(16), - j: new N(16), - X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], - S: [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 999, 999, 999], - T: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0], - q: new N(32), - p: [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 65535, 65535], - z: [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0], - c: new W(32), - J: new N(512), - _: [], - h: new N(32), - $: [], - w: new N(32768), - C: [], - v: [], - d: new N(32768), - D: [], - u: new N(512), - Q: [], - r: new N(1 << 15), - s: new W(286), - Y: new W(30), - a: new W(19), - t: new W(15e3), - k: new N(1 << 16), - g: new N(1 << 15) - }; - }(); - - (function () { - var N = H.H.m, - W = 1 << 15; - - for (var R = 0; R < W; R++) { - var V = R; - V = (V & 2863311530) >>> 1 | (V & 1431655765) << 1; - V = (V & 3435973836) >>> 2 | (V & 858993459) << 2; - V = (V & 4042322160) >>> 4 | (V & 252645135) << 4; - V = (V & 4278255360) >>> 8 | (V & 16711935) << 8; - N.r[R] = (V >>> 16 | V << 16) >>> 17; + if (isHidden(target)) { + cache.set(target, zeroBoxes); + return zeroBoxes; } - - function n(A, l, M) { - while (l-- != 0) A.push(0, M); + var cs = getComputedStyle(target); + var svg = isSVG(target) && target.ownerSVGElement && target.getBBox(); + var removePadding = !IE && cs.boxSizing === 'border-box'; + var switchSizes = verticalRegexp.test(cs.writingMode || ''); + var canScrollVertically = !svg && scrollRegexp.test(cs.overflowY || ''); + var canScrollHorizontally = !svg && scrollRegexp.test(cs.overflowX || ''); + var paddingTop = svg ? 0 : parseDimension(cs.paddingTop); + var paddingRight = svg ? 0 : parseDimension(cs.paddingRight); + var paddingBottom = svg ? 0 : parseDimension(cs.paddingBottom); + var paddingLeft = svg ? 0 : parseDimension(cs.paddingLeft); + var borderTop = svg ? 0 : parseDimension(cs.borderTopWidth); + var borderRight = svg ? 0 : parseDimension(cs.borderRightWidth); + var borderBottom = svg ? 0 : parseDimension(cs.borderBottomWidth); + var borderLeft = svg ? 0 : parseDimension(cs.borderLeftWidth); + var horizontalPadding = paddingLeft + paddingRight; + var verticalPadding = paddingTop + paddingBottom; + var horizontalBorderArea = borderLeft + borderRight; + var verticalBorderArea = borderTop + borderBottom; + var horizontalScrollbarThickness = !canScrollHorizontally ? 0 : target.offsetHeight - verticalBorderArea - target.clientHeight; + var verticalScrollbarThickness = !canScrollVertically ? 0 : target.offsetWidth - horizontalBorderArea - target.clientWidth; + var widthReduction = removePadding ? horizontalPadding + horizontalBorderArea : 0; + var heightReduction = removePadding ? verticalPadding + verticalBorderArea : 0; + var contentWidth = svg ? svg.width : parseDimension(cs.width) - widthReduction - verticalScrollbarThickness; + var contentHeight = svg ? svg.height : parseDimension(cs.height) - heightReduction - horizontalScrollbarThickness; + var borderBoxWidth = contentWidth + horizontalPadding + verticalScrollbarThickness + horizontalBorderArea; + var borderBoxHeight = contentHeight + verticalPadding + horizontalScrollbarThickness + verticalBorderArea; + var boxes = freeze({ + devicePixelContentBoxSize: size(Math.round(contentWidth * devicePixelRatio), Math.round(contentHeight * devicePixelRatio), switchSizes), + borderBoxSize: size(borderBoxWidth, borderBoxHeight, switchSizes), + contentBoxSize: size(contentWidth, contentHeight, switchSizes), + contentRect: new DOMRectReadOnly(paddingLeft, paddingTop, contentWidth, contentHeight) + }); + cache.set(target, boxes); + return boxes; +}; +var calculateBoxSize = function (target, observedBox, forceRecalculation) { + var _a = calculateBoxSizes(target, forceRecalculation), borderBoxSize = _a.borderBoxSize, contentBoxSize = _a.contentBoxSize, devicePixelContentBoxSize = _a.devicePixelContentBoxSize; + switch (observedBox) { + case ResizeObserverBoxOptions.DEVICE_PIXEL_CONTENT_BOX: + return devicePixelContentBoxSize; + case ResizeObserverBoxOptions.BORDER_BOX: + return borderBoxSize; + default: + return contentBoxSize; } +}; - for (var R = 0; R < 32; R++) { - N.q[R] = N.S[R] << 3 | N.T[R]; - N.c[R] = N.p[R] << 4 | N.z[R]; +var ResizeObserverEntry = (function () { + function ResizeObserverEntry(target) { + var boxes = calculateBoxSizes(target); + this.target = target; + this.contentRect = boxes.contentRect; + this.borderBoxSize = freeze([boxes.borderBoxSize]); + this.contentBoxSize = freeze([boxes.contentBoxSize]); + this.devicePixelContentBoxSize = freeze([boxes.devicePixelContentBoxSize]); } + return ResizeObserverEntry; +}()); - n(N._, 144, 8); - n(N._, 255 - 143, 9); - n(N._, 279 - 255, 7); - n(N._, 287 - 279, 8); - H.H.n(N._, 9); - H.H.A(N._, 9, N.J); - H.H.l(N._, 9); - n(N.$, 32, 5); - H.H.n(N.$, 5); - H.H.A(N.$, 5, N.h); - H.H.l(N.$, 5); - n(N.Q, 19, 0); - n(N.C, 286, 0); - n(N.D, 30, 0); - n(N.v, 320, 0); - })(); - - return H.H.N; -}(); - -UPNG.decode._readInterlace = function (data, out) { - var w = out.width, - h = out.height; - - var bpp = UPNG.decode._getBPP(out), - cbpp = bpp >> 3, - bpl = Math.ceil(w * bpp / 8); - - var img = new Uint8Array(h * bpl); - var di = 0; - var starting_row = [0, 0, 4, 0, 2, 0, 1]; - var starting_col = [0, 4, 0, 2, 0, 1, 0]; - var row_increment = [8, 8, 8, 4, 4, 2, 2]; - var col_increment = [8, 8, 4, 4, 2, 2, 1]; - var pass = 0; - - while (pass < 7) { - var ri = row_increment[pass], - ci = col_increment[pass]; - var sw = 0, - sh = 0; - var cr = starting_row[pass]; - - while (cr < h) { - cr += ri; - sh++; +var calculateDepthForNode = function (node) { + if (isHidden(node)) { + return Infinity; } - - var cc = starting_col[pass]; - - while (cc < w) { - cc += ci; - sw++; + var depth = 0; + var parent = node.parentNode; + while (parent) { + depth += 1; + parent = parent.parentNode; } + return depth; +}; - var bpll = Math.ceil(sw * bpp / 8); - - UPNG.decode._filterZero(data, out, di, sw, sh); - - var y = 0, - row = starting_row[pass]; - var val; - - while (row < h) { - var col = starting_col[pass]; - var cdi = di + y * bpll << 3; - - while (col < w) { - if (bpp == 1) { - val = data[cdi >> 3]; - val = val >> 7 - (cdi & 7) & 1; - img[row * bpl + (col >> 3)] |= val << 7 - ((col & 7) << 0); - } - - if (bpp == 2) { - val = data[cdi >> 3]; - val = val >> 6 - (cdi & 7) & 3; - img[row * bpl + (col >> 2)] |= val << 6 - ((col & 3) << 1); - } - - if (bpp == 4) { - val = data[cdi >> 3]; - val = val >> 4 - (cdi & 7) & 15; - img[row * bpl + (col >> 1)] |= val << 4 - ((col & 1) << 2); - } - - if (bpp >= 8) { - var ii = row * bpl + col * cbpp; - - for (var j = 0; j < cbpp; j++) img[ii + j] = data[(cdi >> 3) + j]; +var broadcastActiveObservations = function () { + var shallowestDepth = Infinity; + var callbacks = []; + resizeObservers.forEach(function processObserver(ro) { + if (ro.activeTargets.length === 0) { + return; } - - cdi += bpp; - col += ci; - } - - y++; - row += ri; + var entries = []; + ro.activeTargets.forEach(function processTarget(ot) { + var entry = new ResizeObserverEntry(ot.target); + var targetDepth = calculateDepthForNode(ot.target); + entries.push(entry); + ot.lastReportedSize = calculateBoxSize(ot.target, ot.observedBox); + if (targetDepth < shallowestDepth) { + shallowestDepth = targetDepth; + } + }); + callbacks.push(function resizeObserverCallback() { + ro.callback.call(ro.observer, entries, ro.observer); + }); + ro.activeTargets.splice(0, ro.activeTargets.length); + }); + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var callback = callbacks_1[_i]; + callback(); } - - if (sw * sh != 0) di += sh * (1 + bpll); - pass = pass + 1; - } - - return img; + return shallowestDepth; }; -UPNG.decode._getBPP = function (out) { - var noc = [1, null, 3, 1, 2, null, 4][out.ctype]; - return noc * out.depth; +var gatherActiveObservationsAtDepth = function (depth) { + resizeObservers.forEach(function processObserver(ro) { + ro.activeTargets.splice(0, ro.activeTargets.length); + ro.skippedTargets.splice(0, ro.skippedTargets.length); + ro.observationTargets.forEach(function processTarget(ot) { + if (ot.isActive()) { + if (calculateDepthForNode(ot.target) > depth) { + ro.activeTargets.push(ot); + } + else { + ro.skippedTargets.push(ot); + } + } + }); + }); }; -UPNG.decode._filterZero = function (data, out, off, w, h) { - var bpp = UPNG.decode._getBPP(out), - bpl = Math.ceil(w * bpp / 8), - paeth = UPNG.decode._paeth; - - bpp = Math.ceil(bpp / 8); - var i, - di, - type = data[off], - x = 0; - if (type > 1) data[off] = [0, 0, 1][type - 2]; - if (type == 3) for (x = bpp; x < bpl; x++) data[x + 1] = data[x + 1] + (data[x + 1 - bpp] >>> 1) & 255; - - for (var y = 0; y < h; y++) { - i = off + y * bpl; - di = i + y + 1; - type = data[di - 1]; - x = 0; - if (type == 0) for (; x < bpl; x++) data[i + x] = data[di + x];else if (type == 1) { - for (; x < bpp; x++) data[i + x] = data[di + x]; - - for (; x < bpl; x++) data[i + x] = data[di + x] + data[i + x - bpp]; - } else if (type == 2) { - for (; x < bpl; x++) data[i + x] = data[di + x] + data[i + x - bpl]; - } else if (type == 3) { - for (; x < bpp; x++) data[i + x] = data[di + x] + (data[i + x - bpl] >>> 1); - - for (; x < bpl; x++) data[i + x] = data[di + x] + (data[i + x - bpl] + data[i + x - bpp] >>> 1); - } else { - for (; x < bpp; x++) data[i + x] = data[di + x] + paeth(0, data[i + x - bpl], 0); - - for (; x < bpl; x++) data[i + x] = data[di + x] + paeth(data[i + x - bpp], data[i + x - bpl], data[i + x - bpp - bpl]); +var process$1 = function () { + var depth = 0; + gatherActiveObservationsAtDepth(depth); + while (hasActiveObservations()) { + depth = broadcastActiveObservations(); + gatherActiveObservationsAtDepth(depth); } - } - - return data; + if (hasSkippedObservations()) { + deliverResizeLoopError(); + } + return depth > 0; }; -UPNG.decode._paeth = function (a, b, c) { - var p = a + b - c, - pa = p - a, - pb = p - b, - pc = p - c; - if (pa * pa <= pb * pb && pa * pa <= pc * pc) return a;else if (pb * pb <= pc * pc) return b; - return c; +var trigger; +var callbacks = []; +var notify = function () { return callbacks.splice(0).forEach(function (cb) { return cb(); }); }; +var queueMicroTask = function (callback) { + if (!trigger) { + var toggle_1 = 0; + var el_1 = document.createTextNode(''); + var config = { characterData: true }; + new MutationObserver(function () { return notify(); }).observe(el_1, config); + trigger = function () { el_1.textContent = "" + (toggle_1 ? toggle_1-- : toggle_1++); }; + } + callbacks.push(callback); + trigger(); }; -UPNG.decode._IHDR = function (data, offset, out) { - var bin = UPNG._bin; - out.width = bin.readUint(data, offset); - offset += 4; - out.height = bin.readUint(data, offset); - offset += 4; - out.depth = data[offset]; - offset++; - out.ctype = data[offset]; - offset++; - out.compress = data[offset]; - offset++; - out.filter = data[offset]; - offset++; - out.interlace = data[offset]; - offset++; +var queueResizeObserver = function (cb) { + queueMicroTask(function ResizeObserver() { + requestAnimationFrame(cb); + }); }; -UPNG._bin = { - nextZero: function (data, p) { - while (data[p] != 0) p++; - - return p; - }, - readUshort: function (buff, p) { - return buff[p] << 8 | buff[p + 1]; - }, - writeUshort: function (buff, p, n) { - buff[p] = n >> 8 & 255; - buff[p + 1] = n & 255; - }, - readUint: function (buff, p) { - return buff[p] * (256 * 256 * 256) + (buff[p + 1] << 16 | buff[p + 2] << 8 | buff[p + 3]); - }, - writeUint: function (buff, p, n) { - buff[p] = n >> 24 & 255; - buff[p + 1] = n >> 16 & 255; - buff[p + 2] = n >> 8 & 255; - buff[p + 3] = n & 255; - }, - readASCII: function (buff, p, l) { - var s = ''; - - for (var i = 0; i < l; i++) s += String.fromCharCode(buff[p + i]); - - return s; - }, - writeASCII: function (data, p, s) { - for (var i = 0; i < s.length; i++) data[p + i] = s.charCodeAt(i); - }, - readBytes: function (buff, p, l) { - var arr = []; - - for (var i = 0; i < l; i++) arr.push(buff[p + i]); - - return arr; - }, - pad: function (n) { - return n.length < 2 ? '0' + n : n; - }, - readUTF8: function (buff, p, l) { - var s = '', - ns; - - for (var i = 0; i < l; i++) s += '%' + UPNG._bin.pad(buff[p + i].toString(16)); - - try { - ns = decodeURIComponent(s); - } catch (e) { - return UPNG._bin.readASCII(buff, p, l); - } - - return ns; - } +var watching = 0; +var isWatching = function () { return !!watching; }; +var CATCH_PERIOD = 250; +var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true }; +var events = [ + 'resize', + 'load', + 'transitionend', + 'animationend', + 'animationstart', + 'animationiteration', + 'keyup', + 'keydown', + 'mouseup', + 'mousedown', + 'mouseover', + 'mouseout', + 'blur', + 'focus' +]; +var time = function (timeout) { + if (timeout === void 0) { timeout = 0; } + return Date.now() + timeout; }; - -UPNG._copyTile = function (sb, sw, sh, tb, tw, th, xoff, yoff, mode) { - var w = Math.min(sw, tw), - h = Math.min(sh, th); - var si = 0, - ti = 0; - - for (var y = 0; y < h; y++) for (var x = 0; x < w; x++) { - if (xoff >= 0 && yoff >= 0) { - si = y * sw + x << 2; - ti = (yoff + y) * tw + xoff + x << 2; - } else { - si = (-yoff + y) * sw - xoff + x << 2; - ti = y * tw + x << 2; - } - - if (mode == 0) { - tb[ti] = sb[si]; - tb[ti + 1] = sb[si + 1]; - tb[ti + 2] = sb[si + 2]; - tb[ti + 3] = sb[si + 3]; - } else if (mode == 1) { - var fa = sb[si + 3] * (1 / 255), - fr = sb[si] * fa, - fg = sb[si + 1] * fa, - fb = sb[si + 2] * fa; - var ba = tb[ti + 3] * (1 / 255), - br = tb[ti] * ba, - bg = tb[ti + 1] * ba, - bb = tb[ti + 2] * ba; - var ifa = 1 - fa, - oa = fa + ba * ifa, - ioa = oa == 0 ? 0 : 1 / oa; - tb[ti + 3] = 255 * oa; - tb[ti + 0] = (fr + br * ifa) * ioa; - tb[ti + 1] = (fg + bg * ifa) * ioa; - tb[ti + 2] = (fb + bb * ifa) * ioa; - } else if (mode == 2) { - // copy only differences, otherwise zero - var fa = sb[si + 3], - fr = sb[si], - fg = sb[si + 1], - fb = sb[si + 2]; - var ba = tb[ti + 3], - br = tb[ti], - bg = tb[ti + 1], - bb = tb[ti + 2]; - - if (fa == ba && fr == br && fg == bg && fb == bb) { - tb[ti] = 0; - tb[ti + 1] = 0; - tb[ti + 2] = 0; - tb[ti + 3] = 0; - } else { - tb[ti] = fr; - tb[ti + 1] = fg; - tb[ti + 2] = fb; - tb[ti + 3] = fa; - } - } else if (mode == 3) { - // check if can be blended - var fa = sb[si + 3], - fr = sb[si], - fg = sb[si + 1], - fb = sb[si + 2]; - var ba = tb[ti + 3], - br = tb[ti], - bg = tb[ti + 1], - bb = tb[ti + 2]; - if (fa == ba && fr == br && fg == bg && fb == bb) continue; //if(fa!=255 && ba!=0) return false; - - if (fa < 220 && ba > 20) return false; +var scheduled = false; +var Scheduler = (function () { + function Scheduler() { + var _this = this; + this.stopped = true; + this.listener = function () { return _this.schedule(); }; } - } - - return true; + Scheduler.prototype.run = function (timeout) { + var _this = this; + if (timeout === void 0) { timeout = CATCH_PERIOD; } + if (scheduled) { + return; + } + scheduled = true; + var until = time(timeout); + queueResizeObserver(function () { + var elementsHaveResized = false; + try { + elementsHaveResized = process$1(); + } + finally { + scheduled = false; + timeout = until - time(); + if (!isWatching()) { + return; + } + if (elementsHaveResized) { + _this.run(1000); + } + else if (timeout > 0) { + _this.run(timeout); + } + else { + _this.start(); + } + } + }); + }; + Scheduler.prototype.schedule = function () { + this.stop(); + this.run(); + }; + Scheduler.prototype.observe = function () { + var _this = this; + var cb = function () { return _this.observer && _this.observer.observe(document.body, observerConfig); }; + document.body ? cb() : global$1.addEventListener('DOMContentLoaded', cb); + }; + Scheduler.prototype.start = function () { + var _this = this; + if (this.stopped) { + this.stopped = false; + this.observer = new MutationObserver(this.listener); + this.observe(); + events.forEach(function (name) { return global$1.addEventListener(name, _this.listener, true); }); + } + }; + Scheduler.prototype.stop = function () { + var _this = this; + if (!this.stopped) { + this.observer && this.observer.disconnect(); + events.forEach(function (name) { return global$1.removeEventListener(name, _this.listener, true); }); + this.stopped = true; + } + }; + return Scheduler; +}()); +var scheduler = new Scheduler(); +var updateCount = function (n) { + !watching && n > 0 && scheduler.start(); + watching += n; + !watching && scheduler.stop(); }; -class LineSegmentsGeometry extends InstancedBufferGeometry { - constructor() { - super(); - - _defineProperty$1(this, "isLineSegmentsGeometry", true); - - _defineProperty$1(this, "type", 'LineSegmentsGeometry'); - - _defineProperty$1(this, "boundingBox", null); - - _defineProperty$1(this, "boundingSphere", null); - - _defineProperty$1(this, "box", new Box3()); - - _defineProperty$1(this, "vector", new Vector3()); - - const positions = [-1, 2, 0, 1, 2, 0, -1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0, -1, -1, 0, 1, -1, 0]; - const uvs = [-1, 2, 1, 2, -1, 1, 1, 1, -1, -1, 1, -1, -1, -2, 1, -2]; - const index = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5]; - this.setIndex(index); - this.setAttribute('position', new Float32BufferAttribute(positions, 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); - } - - applyMatrix4(matrix) { - const start = this.attributes.instanceStart; - const end = this.attributes.instanceEnd; - - if (start !== undefined) { - start.applyMatrix4(matrix); - end.applyMatrix4(matrix); - start.needsUpdate = true; - } - - if (this.boundingBox !== null) { - this.computeBoundingBox(); - } - - if (this.boundingSphere !== null) { - this.computeBoundingSphere(); - } - - return this; - } - - setPositions(array) { - let lineSegments; - - if (array instanceof Float32Array) { - lineSegments = array; - } else if (Array.isArray(array)) { - lineSegments = new Float32Array(array); - } else { - console.error('LineSegmentsGeometry.setPosition requires either a Float32Array or regular array of numbers'); - return this; - } - - const instanceBuffer = new InstancedInterleavedBuffer(lineSegments, 6, 1); // xyz, xyz - - this.setAttribute('instanceStart', new InterleavedBufferAttribute(instanceBuffer, 3, 0)); // xyz - - this.setAttribute('instanceEnd', new InterleavedBufferAttribute(instanceBuffer, 3, 3)); // xyz - // - - this.computeBoundingBox(); - this.computeBoundingSphere(); - return this; - } - - setColors(array) { - let colors; - - if (array instanceof Float32Array) { - colors = array; - } else if (Array.isArray(array)) { - colors = new Float32Array(array); - } else { - console.error('LineSegmentsGeometry.setColors requires either a Float32Array or regular array of numbers'); - return this; - } - - const instanceColorBuffer = new InstancedInterleavedBuffer(colors, 6, 1); // rgb, rgb - - this.setAttribute('instanceColorStart', new InterleavedBufferAttribute(instanceColorBuffer, 3, 0)); // rgb - - this.setAttribute('instanceColorEnd', new InterleavedBufferAttribute(instanceColorBuffer, 3, 3)); // rgb - - return this; - } - - fromWireframeGeometry(geometry) { - this.setPositions(Array.from(geometry.attributes.position.array)); - return this; - } - - fromEdgesGeometry(geometry) { - this.setPositions(Array.from(geometry.attributes.position.array)); - return this; - } - - fromMesh(mesh) { - this.fromWireframeGeometry(new WireframeGeometry(mesh.geometry)); - return this; - } - - fromLineSegments(lineSegments) { - const geometry = lineSegments.geometry; - - if (geometry.isBufferGeometry) { - this.setPositions(Array.from(geometry.attributes.position.array)); // assumes non-indexed - } // set colors, maybe - - - return this; - } - - computeBoundingBox() { - if (this.boundingBox === null) { - this.boundingBox = new Box3(); +var skipNotifyOnElement = function (target) { + return !isSVG(target) + && !isReplacedElement(target) + && getComputedStyle(target).display === 'inline'; +}; +var ResizeObservation = (function () { + function ResizeObservation(target, observedBox) { + this.target = target; + this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX; + this.lastReportedSize = { + inlineSize: 0, + blockSize: 0 + }; } + ResizeObservation.prototype.isActive = function () { + var size = calculateBoxSize(this.target, this.observedBox, true); + if (skipNotifyOnElement(this.target)) { + this.lastReportedSize = size; + } + if (this.lastReportedSize.inlineSize !== size.inlineSize + || this.lastReportedSize.blockSize !== size.blockSize) { + return true; + } + return false; + }; + return ResizeObservation; +}()); - const start = this.attributes.instanceStart; - const end = this.attributes.instanceEnd; - - if (start !== undefined && end !== undefined) { - this.boundingBox.setFromBufferAttribute(start); - this.box.setFromBufferAttribute(end); - this.boundingBox.union(this.box); +var ResizeObserverDetail = (function () { + function ResizeObserverDetail(resizeObserver, callback) { + this.activeTargets = []; + this.skippedTargets = []; + this.observationTargets = []; + this.observer = resizeObserver; + this.callback = callback; } - } + return ResizeObserverDetail; +}()); - computeBoundingSphere() { - if (this.boundingSphere === null) { - this.boundingSphere = new Sphere(); +var observerMap = new WeakMap(); +var getObservationIndex = function (observationTargets, target) { + for (var i = 0; i < observationTargets.length; i += 1) { + if (observationTargets[i].target === target) { + return i; + } } - - if (this.boundingBox === null) { - this.computeBoundingBox(); + return -1; +}; +var ResizeObserverController = (function () { + function ResizeObserverController() { } + ResizeObserverController.connect = function (resizeObserver, callback) { + var detail = new ResizeObserverDetail(resizeObserver, callback); + observerMap.set(resizeObserver, detail); + }; + ResizeObserverController.observe = function (resizeObserver, target, options) { + var detail = observerMap.get(resizeObserver); + var firstObservation = detail.observationTargets.length === 0; + if (getObservationIndex(detail.observationTargets, target) < 0) { + firstObservation && resizeObservers.push(detail); + detail.observationTargets.push(new ResizeObservation(target, options && options.box)); + updateCount(1); + scheduler.schedule(); + } + }; + ResizeObserverController.unobserve = function (resizeObserver, target) { + var detail = observerMap.get(resizeObserver); + var index = getObservationIndex(detail.observationTargets, target); + var lastObservation = detail.observationTargets.length === 1; + if (index >= 0) { + lastObservation && resizeObservers.splice(resizeObservers.indexOf(detail), 1); + detail.observationTargets.splice(index, 1); + updateCount(-1); + } + }; + ResizeObserverController.disconnect = function (resizeObserver) { + var _this = this; + var detail = observerMap.get(resizeObserver); + detail.observationTargets.slice().forEach(function (ot) { return _this.unobserve(resizeObserver, ot.target); }); + detail.activeTargets.splice(0, detail.activeTargets.length); + }; + return ResizeObserverController; +}()); - const start = this.attributes.instanceStart; - const end = this.attributes.instanceEnd; - - if (start !== undefined && end !== undefined) { - const center = this.boundingSphere.center; - - if (this.boundingBox) { - this.boundingBox.getCenter(center); - } - - let maxRadiusSq = 0; - - for (let i = 0, il = start.count; i < il; i++) { - this.vector.fromBufferAttribute(start, i); - maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(this.vector)); - this.vector.fromBufferAttribute(end, i); - maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(this.vector)); - } - - this.boundingSphere.radius = Math.sqrt(maxRadiusSq); - - if (isNaN(this.boundingSphere.radius)) { - console.error('THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this); - } +var ResizeObserver = (function () { + function ResizeObserver(callback) { + if (arguments.length === 0) { + throw new TypeError("Failed to construct 'ResizeObserver': 1 argument required, but only 0 present."); + } + if (typeof callback !== 'function') { + throw new TypeError("Failed to construct 'ResizeObserver': The callback provided as parameter 1 is not a function."); + } + ResizeObserverController.connect(this, callback); } - } - - toJSON() {// todo - } - -} - -class LineGeometry extends LineSegmentsGeometry { - constructor() { - super(); - - _defineProperty$1(this, "type", 'LineGeometry'); - - _defineProperty$1(this, "isLineGeometry", true); - - _defineProperty$1(this, "setColors", array => { - // converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format - const length = array.length - 3; - const colors = new Float32Array(2 * length); - - for (let i = 0; i < length; i += 3) { - colors[2 * i] = array[i]; - colors[2 * i + 1] = array[i + 1]; - colors[2 * i + 2] = array[i + 2]; - colors[2 * i + 3] = array[i + 3]; - colors[2 * i + 4] = array[i + 4]; - colors[2 * i + 5] = array[i + 5]; - } - - super.setColors(colors); - return this; - }); + ResizeObserver.prototype.observe = function (target, options) { + if (arguments.length === 0) { + throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': 1 argument required, but only 0 present."); + } + if (!isElement(target)) { + throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element"); + } + ResizeObserverController.observe(this, target, options); + }; + ResizeObserver.prototype.unobserve = function (target) { + if (arguments.length === 0) { + throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': 1 argument required, but only 0 present."); + } + if (!isElement(target)) { + throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': parameter 1 is not of type 'Element"); + } + ResizeObserverController.unobserve(this, target); + }; + ResizeObserver.prototype.disconnect = function () { + ResizeObserverController.disconnect(this); + }; + ResizeObserver.toString = function () { + return 'function ResizeObserver () { [polyfill code] }'; + }; + return ResizeObserver; +}()); - _defineProperty$1(this, "fromLine", line => { - const geometry = line.geometry; +const v1 = new Vector3(); +const v2 = new Vector3(); +const v3 = new Vector3(); - if (geometry.isBufferGeometry) { - this.setPositions(Array.from(geometry.attributes.position.array)); // assumes non-indexed - } // set colors, maybe +function defaultCalculatePosition(el, camera, size) { + const objectPos = v1.setFromMatrixPosition(el.matrixWorld); + objectPos.project(camera); + const widthHalf = size.width / 2; + const heightHalf = size.height / 2; + return [objectPos.x * widthHalf + widthHalf, -(objectPos.y * heightHalf) + heightHalf]; +} +function isObjectBehindCamera(el, camera) { + const objectPos = v1.setFromMatrixPosition(el.matrixWorld); + const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); + const deltaCamObj = objectPos.sub(cameraPos); + const camDir = camera.getWorldDirection(v3); + return deltaCamObj.angleTo(camDir) > Math.PI / 2; +} - return this; - }); +function isObjectVisible(el, camera, raycaster, occlude) { + const elPos = v1.setFromMatrixPosition(el.matrixWorld); + const screenPos = elPos.clone(); + screenPos.project(camera); + raycaster.setFromCamera(screenPos, camera); + const intersects = raycaster.intersectObjects(occlude, true); - _defineProperty$1(this, "copy", () => { - // todo - return this; - }); + if (intersects.length) { + const intersectionDistance = intersects[0].distance; + const pointDistance = elPos.distanceTo(raycaster.ray.origin); + return pointDistance < intersectionDistance; } - setPositions(array) { - // converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format - const length = array.length - 3; - const points = new Float32Array(2 * length); - - for (let i = 0; i < length; i += 3) { - points[2 * i] = array[i]; - points[2 * i + 1] = array[i + 1]; - points[2 * i + 2] = array[i + 2]; - points[2 * i + 3] = array[i + 3]; - points[2 * i + 4] = array[i + 4]; - points[2 * i + 5] = array[i + 5]; - } + return true; +} - super.setPositions(points); - return this; +function objectScale(el, camera) { + if (camera instanceof OrthographicCamera) { + return camera.zoom; + } else if (camera instanceof PerspectiveCamera) { + const objectPos = v1.setFromMatrixPosition(el.matrixWorld); + const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); + const vFOV = camera.fov * Math.PI / 180; + const dist = objectPos.distanceTo(cameraPos); + const scaleFOV = 2 * Math.tan(vFOV / 2) * dist; + return 1 / scaleFOV; + } else { + return 1; } - } -/** - * parameters = { - * color: , - * linewidth: , - * dashed: , - * dashScale: , - * dashSize: , - * dashOffset: , - * gapSize: , - * resolution: , // to be set by renderer - * } - */ -const LineUniforms = { - linewidth: { - value: 1 - }, - resolution: { - value: new Vector2(1, 1) - }, - dashScale: { - value: 1 - }, - dashSize: { - value: 1 - }, - dashOffset: { - value: 0 - }, - gapSize: { - value: 1 - }, - // todo FIX - maybe change to totalSize - opacity: { - value: 1 +function objectZIndex(el, camera, zIndexRange) { + if (camera instanceof PerspectiveCamera || camera instanceof OrthographicCamera) { + const objectPos = v1.setFromMatrixPosition(el.matrixWorld); + const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); + const dist = objectPos.distanceTo(cameraPos); + const A = (zIndexRange[1] - zIndexRange[0]) / (camera.far - camera.near); + const B = zIndexRange[1] - A * camera.far; + return Math.round(A * dist + B); } -}; -ShaderLib['line'] = { - uniforms: UniformsUtils.merge([UniformsLib.common, UniformsLib.fog, LineUniforms]), - vertexShader: - /* glsl */ - ` - #include - #include - #include - #include - #include - uniform float linewidth; - uniform vec2 resolution; + return undefined; +} + +const epsilon = value => Math.abs(value) < 1e-10 ? 0 : value; - attribute vec3 instanceStart; - attribute vec3 instanceEnd; +function getCSSMatrix(matrix, multipliers, prepend = '') { + let matrix3d = 'matrix3d('; - attribute vec3 instanceColorStart; - attribute vec3 instanceColorEnd; + for (let i = 0; i !== 16; i++) { + matrix3d += epsilon(multipliers[i] * matrix.elements[i]) + (i !== 15 ? ',' : ')'); + } - varying vec2 vUv; + return prepend + matrix3d; +} - #ifdef USE_DASH +const getCameraCSSMatrix = (multipliers => { + return matrix => getCSSMatrix(matrix, multipliers); +})([1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1]); - uniform float dashScale; - attribute float instanceDistanceStart; - attribute float instanceDistanceEnd; - varying float vLineDistance; +const getObjectCSSMatrix = (scaleMultipliers => { + return (matrix, factor) => getCSSMatrix(matrix, scaleMultipliers(factor), 'translate(-50%,-50%)'); +})(f => [1 / f, 1 / f, 1 / f, 1, -1 / f, -1 / f, -1 / f, -1, 1 / f, 1 / f, 1 / f, 1, 1, 1, 1, 1]); - #endif +const Html = /*#__PURE__*/React.forwardRef(({ + children, + eps = 0.001, + style, + className, + prepend, + center, + fullscreen, + portal, + distanceFactor, + sprite = false, + transform = false, + occlude, + onOcclude, + zIndexRange = [16777271, 0], + calculatePosition = defaultCalculatePosition, + as = 'div', + wrapperClass, + pointerEvents = 'auto', + ...props +}, ref) => { + var _portal$current; - void trimSegment( const in vec4 start, inout vec4 end ) { + const gl = useThree(({ + gl + }) => gl); + const camera = useThree(({ + camera + }) => camera); + const scene = useThree(({ + scene + }) => scene); + const size = useThree(({ + size + }) => size); + const raycaster = useThree(({ + raycaster + }) => raycaster); + const [el] = React.useState(() => document.createElement(as)); + const root = React.useRef(); + const group = React.useRef(null); + const oldZoom = React.useRef(0); + const oldPosition = React.useRef([0, 0]); + const transformOuterRef = React.useRef(null); + const transformInnerRef = React.useRef(null); + const target = (_portal$current = portal == null ? void 0 : portal.current) !== null && _portal$current !== void 0 ? _portal$current : gl.domElement.parentNode; + React.useLayoutEffect(() => { + if (group.current) { + const currentRoot = root.current = ReactDOM.createRoot(el); + scene.updateMatrixWorld(); - // trim end segment so it terminates between the camera plane and the near plane + if (transform) { + el.style.cssText = `position:absolute;top:0;left:0;pointer-events:none;overflow:hidden;`; + } else { + const vec = calculatePosition(group.current, camera, size); + el.style.cssText = `position:absolute;top:0;left:0;transform:translate3d(${vec[0]}px,${vec[1]}px,0);transform-origin:0 0;`; + } - // conservative estimate of the near plane - float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column - float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column - float nearEstimate = - 0.5 * b / a; + if (target) { + if (prepend) target.prepend(el);else target.appendChild(el); + } - float alpha = ( nearEstimate - start.z ) / ( end.z - start.z ); + return () => { + if (target) target.removeChild(el); + currentRoot.unmount(); + }; + } + }, [target, transform]); + React.useLayoutEffect(() => { + if (wrapperClass) el.className = wrapperClass; + }, [wrapperClass]); + const styles = React.useMemo(() => { + if (transform) { + return { + position: 'absolute', + top: 0, + left: 0, + width: size.width, + height: size.height, + transformStyle: 'preserve-3d', + pointerEvents: 'none' + }; + } else { + return { + position: 'absolute', + transform: center ? 'translate3d(-50%,-50%,0)' : 'none', + ...(fullscreen && { + top: -size.height / 2, + left: -size.width / 2, + width: size.width, + height: size.height + }), + ...style + }; + } + }, [style, center, fullscreen, size, transform]); + const transformInnerStyles = React.useMemo(() => ({ + position: 'absolute', + pointerEvents + }), [pointerEvents]); + React.useLayoutEffect(() => { + if (transform) { + var _root$current; - end.xyz = mix( start.xyz, end.xyz, alpha ); + (_root$current = root.current) == null ? void 0 : _root$current.render( /*#__PURE__*/React.createElement("div", { + ref: transformOuterRef, + style: styles + }, /*#__PURE__*/React.createElement("div", { + ref: transformInnerRef, + style: transformInnerStyles + }, /*#__PURE__*/React.createElement("div", { + ref: ref, + className: className, + style: style, + children: children + })))); + } else { + var _root$current2; - } + (_root$current2 = root.current) == null ? void 0 : _root$current2.render( /*#__PURE__*/React.createElement("div", { + ref: ref, + style: styles, + className: className, + children: children + })); + } + }); + const visible = React.useRef(true); + useFrame(() => { + if (group.current) { + camera.updateMatrixWorld(); + group.current.updateWorldMatrix(true, false); + const vec = transform ? oldPosition.current : calculatePosition(group.current, camera, size); - void main() { + if (transform || Math.abs(oldZoom.current - camera.zoom) > eps || Math.abs(oldPosition.current[0] - vec[0]) > eps || Math.abs(oldPosition.current[1] - vec[1]) > eps) { + const isBehindCamera = isObjectBehindCamera(group.current, camera); + let raytraceTarget = false; - #ifdef USE_COLOR + if (typeof occlude === 'boolean') { + if (occlude === true) { + raytraceTarget = [scene]; + } + } else if (Array.isArray(occlude)) { + raytraceTarget = occlude.map(item => item.current); + } - vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd; + const previouslyVisible = visible.current; - #endif + if (raytraceTarget) { + const isvisible = isObjectVisible(group.current, camera, raycaster, raytraceTarget); + visible.current = isvisible && !isBehindCamera; + } else { + visible.current = !isBehindCamera; + } - #ifdef USE_DASH + if (previouslyVisible !== visible.current) { + if (onOcclude) onOcclude(!visible.current);else el.style.display = visible.current ? 'block' : 'none'; + } - vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd; + el.style.zIndex = `${objectZIndex(group.current, camera, zIndexRange)}`; - #endif + if (transform) { + const [widthHalf, heightHalf] = [size.width / 2, size.height / 2]; + const fov = camera.projectionMatrix.elements[5] * heightHalf; + const { + isOrthographicCamera, + top, + left, + bottom, + right + } = camera; + const cameraMatrix = getCameraCSSMatrix(camera.matrixWorldInverse); + const cameraTransform = isOrthographicCamera ? `scale(${fov})translate(${epsilon(-(right + left) / 2)}px,${epsilon((top + bottom) / 2)}px)` : `translateZ(${fov}px)`; + let matrix = group.current.matrixWorld; - float aspect = resolution.x / resolution.y; + if (sprite) { + matrix = camera.matrixWorldInverse.clone().transpose().copyPosition(matrix).scale(group.current.scale); + matrix.elements[3] = matrix.elements[7] = matrix.elements[11] = 0; + matrix.elements[15] = 1; + } - vUv = uv; + el.style.width = size.width + 'px'; + el.style.height = size.height + 'px'; + el.style.perspective = isOrthographicCamera ? '' : `${fov}px`; - // camera space - vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 ); - vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 ); + if (transformOuterRef.current && transformInnerRef.current) { + transformOuterRef.current.style.transform = `${cameraTransform}${cameraMatrix}translate(${widthHalf}px,${heightHalf}px)`; + transformInnerRef.current.style.transform = getObjectCSSMatrix(matrix, 1 / ((distanceFactor || 10) / 400)); + } + } else { + const scale = distanceFactor === undefined ? 1 : objectScale(group.current, camera) * distanceFactor; + el.style.transform = `translate3d(${vec[0]}px,${vec[1]}px,0) scale(${scale})`; + } - // special case for perspective projection, and segments that terminate either in, or behind, the camera plane - // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space - // but we need to perform ndc-space calculations in the shader, so we must address this issue directly - // perhaps there is a more elegant solution -- WestLangley + oldPosition.current = vec; + oldZoom.current = camera.zoom; + } + } + }); + return /*#__PURE__*/React.createElement("group", _extends$3({}, props, { + ref: group + })); +}); - bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column +function createStore$1(createState) { + let state; + const listeners = /* @__PURE__ */ new Set(); + const setState = (partial, replace) => { + const nextState = typeof partial === "function" ? partial(state) : partial; + if (nextState !== state) { + const previousState = state; + state = replace ? nextState : Object.assign({}, state, nextState); + listeners.forEach((listener) => listener(state, previousState)); + } + }; + const getState = () => state; + const subscribeWithSelector = (listener, selector = getState, equalityFn = Object.is) => { + console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware"); + let currentSlice = selector(state); + function listenerToAdd() { + const nextSlice = selector(state); + if (!equalityFn(currentSlice, nextSlice)) { + const previousSlice = currentSlice; + listener(currentSlice = nextSlice, previousSlice); + } + } + listeners.add(listenerToAdd); + return () => listeners.delete(listenerToAdd); + }; + const subscribe = (listener, selector, equalityFn) => { + if (selector || equalityFn) { + return subscribeWithSelector(listener, selector, equalityFn); + } + listeners.add(listener); + return () => listeners.delete(listener); + }; + const destroy = () => listeners.clear(); + const api = { setState, getState, subscribe, destroy }; + state = createState(setState, getState, api); + return api; +} - if ( perspective ) { +const isSSR$1 = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); +const useIsomorphicLayoutEffect = isSSR$1 ? useEffect : useLayoutEffect$1; +function create$3(createState) { + const api = typeof createState === "function" ? createStore$1(createState) : createState; + const useStore = (selector = api.getState, equalityFn = Object.is) => { + const [, forceUpdate] = useReducer((c) => c + 1, 0); + const state = api.getState(); + const stateRef = useRef(state); + const selectorRef = useRef(selector); + const equalityFnRef = useRef(equalityFn); + const erroredRef = useRef(false); + const currentSliceRef = useRef(); + if (currentSliceRef.current === void 0) { + currentSliceRef.current = selector(state); + } + let newStateSlice; + let hasNewStateSlice = false; + if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) { + newStateSlice = selector(state); + hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice); + } + useIsomorphicLayoutEffect(() => { + if (hasNewStateSlice) { + currentSliceRef.current = newStateSlice; + } + stateRef.current = state; + selectorRef.current = selector; + equalityFnRef.current = equalityFn; + erroredRef.current = false; + }); + const stateBeforeSubscriptionRef = useRef(state); + useIsomorphicLayoutEffect(() => { + const listener = () => { + try { + const nextState = api.getState(); + const nextStateSlice = selectorRef.current(nextState); + if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) { + stateRef.current = nextState; + currentSliceRef.current = nextStateSlice; + forceUpdate(); + } + } catch (error) { + erroredRef.current = true; + forceUpdate(); + } + }; + const unsubscribe = api.subscribe(listener); + if (api.getState() !== stateBeforeSubscriptionRef.current) { + listener(); + } + return unsubscribe; + }, []); + const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current; + useDebugValue(sliceToReturn); + return sliceToReturn; + }; + Object.assign(useStore, api); + useStore[Symbol.iterator] = function() { + console.warn("[useStore, api] = create() is deprecated and will be removed in v4"); + const items = [useStore, api]; + return { + next() { + const done = items.length <= 0; + return { value: items.shift(), done }; + } + }; + }; + return useStore; +} - if ( start.z < 0.0 && end.z >= 0.0 ) { +let saveLastTotalLoaded = 0; +create$3(set => { + DefaultLoadingManager.onStart = (item, loaded, total) => { + set({ + active: true, + item, + loaded, + total, + progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 + }); + }; - trimSegment( start, end ); + DefaultLoadingManager.onLoad = () => { + set({ + active: false + }); + }; - } else if ( end.z < 0.0 && start.z >= 0.0 ) { + DefaultLoadingManager.onError = item => set(state => ({ + errors: [...state.errors, item] + })); - trimSegment( end, start ); + DefaultLoadingManager.onProgress = (item, loaded, total) => { + if (loaded === total) { + saveLastTotalLoaded = total; + } - } + set({ + active: true, + item, + loaded, + total, + progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 || 100 + }); + }; - } + return { + errors: [], + active: false, + progress: 0, + item: '', + loaded: 0, + total: 0 + }; +}); - // clip space - vec4 clipStart = projectionMatrix * start; - vec4 clipEnd = projectionMatrix * end; +function mergeRefs(refs) { + return function (value) { + refs.forEach(function (ref) { + if (typeof ref === "function") { + ref(value); + } else if (ref != null) { + ref.current = value; + } + }); + }; +} - // ndc space - vec2 ndcStart = clipStart.xy / clipStart.w; - vec2 ndcEnd = clipEnd.xy / clipEnd.w; +let updateQueue = makeQueue(); +const raf = fn => schedule(fn, updateQueue); +let writeQueue = makeQueue(); - // direction - vec2 dir = ndcEnd - ndcStart; +raf.write = fn => schedule(fn, writeQueue); - // account for clip-space aspect ratio - dir.x *= aspect; - dir = normalize( dir ); +let onStartQueue = makeQueue(); - // perpendicular to dir - vec2 offset = vec2( dir.y, - dir.x ); +raf.onStart = fn => schedule(fn, onStartQueue); - // undo aspect ratio adjustment - dir.x /= aspect; - offset.x /= aspect; +let onFrameQueue = makeQueue(); - // sign flip - if ( position.x < 0.0 ) offset *= - 1.0; +raf.onFrame = fn => schedule(fn, onFrameQueue); - // endcaps - if ( position.y < 0.0 ) { +let onFinishQueue = makeQueue(); - offset += - dir; +raf.onFinish = fn => schedule(fn, onFinishQueue); - } else if ( position.y > 1.0 ) { +let timeouts = []; - offset += dir; +raf.setTimeout = (handler, ms) => { + let time = raf.now() + ms; - } + let cancel = () => { + let i = timeouts.findIndex(t => t.cancel == cancel); + if (~i) timeouts.splice(i, 1); + pendingCount -= ~i ? 1 : 0; + }; - // adjust for linewidth - offset *= linewidth; + let timeout = { + time, + handler, + cancel + }; + timeouts.splice(findTimeout(time), 0, timeout); + pendingCount += 1; + start(); + return timeout; +}; - // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ... - offset /= resolution.y; +let findTimeout = time => ~(~timeouts.findIndex(t => t.time > time) || ~timeouts.length); - // select end - vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd; +raf.cancel = fn => { + onStartQueue.delete(fn); + onFrameQueue.delete(fn); + updateQueue.delete(fn); + writeQueue.delete(fn); + onFinishQueue.delete(fn); +}; - // back to clip space - offset *= clip.w; +raf.sync = fn => { + sync = true; + raf.batchedUpdates(fn); + sync = false; +}; - clip.xy += offset; +raf.throttle = fn => { + let lastArgs; - gl_Position = clip; + function queuedFn() { + try { + fn(...lastArgs); + } finally { + lastArgs = null; + } + } - vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation + function throttled(...args) { + lastArgs = args; + raf.onStart(queuedFn); + } - #include - #include - #include + throttled.handler = fn; - } - `, - fragmentShader: - /* glsl */ - ` - uniform vec3 diffuse; - uniform float opacity; + throttled.cancel = () => { + onStartQueue.delete(queuedFn); + lastArgs = null; + }; - #ifdef USE_DASH + return throttled; +}; - uniform float dashSize; - uniform float dashOffset; - uniform float gapSize; +let nativeRaf = typeof window != 'undefined' ? window.requestAnimationFrame : () => {}; - #endif +raf.use = impl => nativeRaf = impl; - varying float vLineDistance; +raf.now = typeof performance != 'undefined' ? () => performance.now() : Date.now; - #include - #include - #include - #include - #include +raf.batchedUpdates = fn => fn(); - varying vec2 vUv; +raf.catch = console.error; +raf.frameLoop = 'always'; - void main() { +raf.advance = () => { + if (raf.frameLoop !== 'demand') { + console.warn('Cannot call the manual advancement of rafz whilst frameLoop is not set as demand'); + } else { + update(); + } +}; - #include +let ts = -1; +let pendingCount = 0; +let sync = false; - #ifdef USE_DASH +function schedule(fn, queue) { + if (sync) { + queue.delete(fn); + fn(0); + } else { + queue.add(fn); + start(); + } +} - if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps +function start() { + if (ts < 0) { + ts = 0; - if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX + if (raf.frameLoop !== 'demand') { + nativeRaf(loop); + } + } +} - #endif +function stop() { + ts = -1; +} - float alpha = opacity; +function loop() { + if (~ts) { + nativeRaf(loop); + raf.batchedUpdates(update); + } +} - #ifdef ALPHA_TO_COVERAGE +function update() { + let prevTs = ts; + ts = raf.now(); + let count = findTimeout(ts); - // artifacts appear on some hardware if a derivative is taken within a conditional - float a = vUv.x; - float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; - float len2 = a * a + b * b; - float dlen = fwidth( len2 ); + if (count) { + eachSafely(timeouts.splice(0, count), t => t.handler()); + pendingCount -= count; + } - if ( abs( vUv.y ) > 1.0 ) { + onStartQueue.flush(); + updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667); + onFrameQueue.flush(); + writeQueue.flush(); + onFinishQueue.flush(); - alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 ); + if (!pendingCount) { + stop(); + } +} - } +function makeQueue() { + let next = new Set(); + let current = next; + return { + add(fn) { + pendingCount += current == next && !next.has(fn) ? 1 : 0; + next.add(fn); + }, - #else + delete(fn) { + pendingCount -= current == next && next.has(fn) ? 1 : 0; + return next.delete(fn); + }, - if ( abs( vUv.y ) > 1.0 ) { + flush(arg) { + if (current.size) { + next = new Set(); + pendingCount -= current.size; + eachSafely(current, fn => fn(arg) && next.add(fn)); + pendingCount += next.size; + current = next; + } + } - float a = vUv.x; - float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; - float len2 = a * a + b * b; + }; +} - if ( len2 > 1.0 ) discard; +function eachSafely(values, each) { + values.forEach(value => { + try { + each(value); + } catch (e) { + raf.catch(e); + } + }); +} - } +function noop() {} +const defineHidden = (obj, key, value) => Object.defineProperty(obj, key, { + value, + writable: true, + configurable: true +}); +const is = { + arr: Array.isArray, + obj: a => !!a && a.constructor.name === 'Object', + fun: a => typeof a === 'function', + str: a => typeof a === 'string', + num: a => typeof a === 'number', + und: a => a === undefined +}; +function isEqual(a, b) { + if (is.arr(a)) { + if (!is.arr(b) || a.length !== b.length) return false; - #endif + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } - vec4 diffuseColor = vec4( diffuse, alpha ); + return true; + } - #include - #include + return a === b; +} +const each = (obj, fn) => obj.forEach(fn); +function eachProp(obj, fn, ctx) { + if (is.arr(obj)) { + for (let i = 0; i < obj.length; i++) { + fn.call(ctx, obj[i], `${i}`); + } - gl_FragColor = vec4( diffuseColor.rgb, alpha ); + return; + } - #include - #include - #include - #include + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + fn.call(ctx, obj[key], key); + } + } +} +const toArray = a => is.und(a) ? [] : is.arr(a) ? a : [a]; +const isSSR = () => typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); - } - ` +let createStringInterpolator$1; +let to; +let colors$1 = null; +let skipAnimation = false; +let willAdvance = noop; +const assign$2 = globals => { + if (globals.to) to = globals.to; + if (globals.now) raf.now = globals.now; + if (globals.colors !== undefined) colors$1 = globals.colors; + if (globals.skipAnimation != null) skipAnimation = globals.skipAnimation; + if (globals.createStringInterpolator) createStringInterpolator$1 = globals.createStringInterpolator; + if (globals.requestAnimationFrame) raf.use(globals.requestAnimationFrame); + if (globals.batchedUpdates) raf.batchedUpdates = globals.batchedUpdates; + if (globals.willAdvance) willAdvance = globals.willAdvance; + if (globals.frameLoop) raf.frameLoop = globals.frameLoop; }; -class LineMaterial extends ShaderMaterial { - constructor(parameters = {}) { - super({ - uniforms: UniformsUtils.clone(ShaderLib['line'].uniforms), - vertexShader: ShaderLib['line'].vertexShader, - fragmentShader: ShaderLib['line'].fragmentShader, - clipping: true // required for clipping support +var globals = /*#__PURE__*/Object.freeze({ + __proto__: null, + get createStringInterpolator () { return createStringInterpolator$1; }, + get to () { return to; }, + get colors () { return colors$1; }, + get skipAnimation () { return skipAnimation; }, + get willAdvance () { return willAdvance; }, + assign: assign$2 +}); - }); - /** - * Everytime I remove this, everything just breaks, - * so I'm just gonna leave it here. - */ +const startQueue = new Set(); +let currentFrame = []; +let prevFrame = []; +let priority = 0; +const frameLoop = { + get idle() { + return !startQueue.size && !currentFrame.length; + }, - _defineProperty$1(this, "isLineMaterial", true); + start(animation) { + if (priority > animation.priority) { + startQueue.add(animation); + raf.onStart(flushStartQueue); + } else { + startSafely(animation); + raf(advance); + } + }, - _defineProperty$1(this, "dashed", false); + advance, - _defineProperty$1(this, "color", new Color(0x000000)); + sort(animation) { + if (priority) { + raf.onFrame(() => frameLoop.sort(animation)); + } else { + const prevIndex = currentFrame.indexOf(animation); - _defineProperty$1(this, "lineWidth", 0); + if (~prevIndex) { + currentFrame.splice(prevIndex, 1); + startUnsafely(animation); + } + } + }, - _defineProperty$1(this, "dashScale", 0); + clear() { + currentFrame = []; + startQueue.clear(); + } - _defineProperty$1(this, "dashOffset", 0); +}; - _defineProperty$1(this, "dashSize", 0); +function flushStartQueue() { + startQueue.forEach(startSafely); + startQueue.clear(); + raf(advance); +} - _defineProperty$1(this, "opacity", 0); +function startSafely(animation) { + if (!currentFrame.includes(animation)) startUnsafely(animation); +} - _defineProperty$1(this, "resolution", new Vector2()); +function startUnsafely(animation) { + currentFrame.splice(findIndex(currentFrame, other => other.priority > animation.priority), 0, animation); +} - _defineProperty$1(this, "alphaToCoverage", false); +function advance(dt) { + const nextFrame = prevFrame; - Object.defineProperties(this, { - color: { - enumerable: true, - get: function () { - return this.uniforms.diffuse.value; - }, - set: function (value) { - const colorObj = new Color(value); - this.uniforms.diffuse.value = colorObj.getHex(); - } - }, - linewidth: { - enumerable: true, - get: function () { - return this.uniforms.linewidth.value; - }, - set: function (value) { - this.uniforms.linewidth.value = value; - } - }, - dashScale: { - enumerable: true, - get: function () { - return this.uniforms.dashScale.value; - }, - set: function (value) { - this.uniforms.dashScale.value = value; - } - }, - dashSize: { - enumerable: true, - get: function () { - return this.uniforms.dashSize.value; - }, - set: function (value) { - this.uniforms.dashSize.value = value; - } - }, - dashOffset: { - enumerable: true, - get: function () { - return this.uniforms.dashOffset.value; - }, - set: function (value) { - this.uniforms.dashOffset.value = value; - } - }, - gapSize: { - enumerable: true, - get: function () { - return this.uniforms.gapSize.value; - }, - set: function (value) { - this.uniforms.gapSize.value = value; - } - }, - opacity: { - enumerable: true, - get: function () { - return this.uniforms.opacity.value; - }, - set: function (value) { - this.uniforms.opacity.value = value; - } - }, - resolution: { - enumerable: true, - get: function () { - return this.uniforms.resolution.value; - }, - set: function (value) { - this.uniforms.resolution.value.copy(value); - } - }, - alphaToCoverage: { - enumerable: true, - get: function () { - return Boolean('ALPHA_TO_COVERAGE' in this.defines); - }, - set: function (value) { - if (Boolean(value) !== Boolean('ALPHA_TO_COVERAGE' in this.defines)) { - this.needsUpdate = true; - } + for (let i = 0; i < currentFrame.length; i++) { + const animation = currentFrame[i]; + priority = animation.priority; - if (value) { - this.defines.ALPHA_TO_COVERAGE = ''; - this.extensions.derivatives = true; - } else { - delete this.defines.ALPHA_TO_COVERAGE; - this.extensions.derivatives = false; - } - } - }, - dashed: { - enumerable: true, - get: function () { - return Boolean('USE_DASH' in this.defines); - }, - set: function (value) { - if (Boolean(value) !== Boolean('USE_DASH' in this.defines)) { - this.needsUpdate = true; - } + if (!animation.idle) { + willAdvance(animation); + animation.advance(dt); - if (value) { - this.defines.USE_DASH = ''; - } else { - delete this.defines.USE_DASH; - } - } + if (!animation.idle) { + nextFrame.push(animation); } - }); - this.setValues(parameters); + } } + priority = 0; + prevFrame = currentFrame; + prevFrame.length = 0; + currentFrame = nextFrame; + return currentFrame.length > 0; } -var Wireframe = function (geometry, material) { - Mesh.call(this); - this.type = 'Wireframe'; - this.geometry = geometry !== undefined ? geometry : new LineSegmentsGeometry(); - this.material = material !== undefined ? material : new LineMaterial({ - color: Math.random() * 0xffffff - }); -}; - -Wireframe.prototype = Object.assign(Object.create(Mesh.prototype), { - constructor: Wireframe, - isWireframe: true, - computeLineDistances: function () { - // for backwards-compatability, but could be a method of LineSegmentsGeometry... - var start = new Vector3(); - var end = new Vector3(); - return function computeLineDistances() { - var geometry = this.geometry; - var instanceStart = geometry.attributes.instanceStart; - var instanceEnd = geometry.attributes.instanceEnd; - var lineDistances = new Float32Array(2 * instanceStart.data.count); - - for (let i = 0, j = 0, l = instanceStart.data.count; i < l; i++, j += 2) { - start.fromBufferAttribute(instanceStart, i); - end.fromBufferAttribute(instanceEnd, i); - lineDistances[j] = j === 0 ? 0 : lineDistances[j - 1]; - lineDistances[j + 1] = lineDistances[j] + start.distanceTo(end); - } - - var instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1); // d0, d1 +function findIndex(arr, test) { + const index = arr.findIndex(test); + return index < 0 ? arr.length : index; +} - geometry.setAttribute('instanceDistanceStart', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0)); // d0 +const colors = { + transparent: 0x00000000, + aliceblue: 0xf0f8ffff, + antiquewhite: 0xfaebd7ff, + aqua: 0x00ffffff, + aquamarine: 0x7fffd4ff, + azure: 0xf0ffffff, + beige: 0xf5f5dcff, + bisque: 0xffe4c4ff, + black: 0x000000ff, + blanchedalmond: 0xffebcdff, + blue: 0x0000ffff, + blueviolet: 0x8a2be2ff, + brown: 0xa52a2aff, + burlywood: 0xdeb887ff, + burntsienna: 0xea7e5dff, + cadetblue: 0x5f9ea0ff, + chartreuse: 0x7fff00ff, + chocolate: 0xd2691eff, + coral: 0xff7f50ff, + cornflowerblue: 0x6495edff, + cornsilk: 0xfff8dcff, + crimson: 0xdc143cff, + cyan: 0x00ffffff, + darkblue: 0x00008bff, + darkcyan: 0x008b8bff, + darkgoldenrod: 0xb8860bff, + darkgray: 0xa9a9a9ff, + darkgreen: 0x006400ff, + darkgrey: 0xa9a9a9ff, + darkkhaki: 0xbdb76bff, + darkmagenta: 0x8b008bff, + darkolivegreen: 0x556b2fff, + darkorange: 0xff8c00ff, + darkorchid: 0x9932ccff, + darkred: 0x8b0000ff, + darksalmon: 0xe9967aff, + darkseagreen: 0x8fbc8fff, + darkslateblue: 0x483d8bff, + darkslategray: 0x2f4f4fff, + darkslategrey: 0x2f4f4fff, + darkturquoise: 0x00ced1ff, + darkviolet: 0x9400d3ff, + deeppink: 0xff1493ff, + deepskyblue: 0x00bfffff, + dimgray: 0x696969ff, + dimgrey: 0x696969ff, + dodgerblue: 0x1e90ffff, + firebrick: 0xb22222ff, + floralwhite: 0xfffaf0ff, + forestgreen: 0x228b22ff, + fuchsia: 0xff00ffff, + gainsboro: 0xdcdcdcff, + ghostwhite: 0xf8f8ffff, + gold: 0xffd700ff, + goldenrod: 0xdaa520ff, + gray: 0x808080ff, + green: 0x008000ff, + greenyellow: 0xadff2fff, + grey: 0x808080ff, + honeydew: 0xf0fff0ff, + hotpink: 0xff69b4ff, + indianred: 0xcd5c5cff, + indigo: 0x4b0082ff, + ivory: 0xfffff0ff, + khaki: 0xf0e68cff, + lavender: 0xe6e6faff, + lavenderblush: 0xfff0f5ff, + lawngreen: 0x7cfc00ff, + lemonchiffon: 0xfffacdff, + lightblue: 0xadd8e6ff, + lightcoral: 0xf08080ff, + lightcyan: 0xe0ffffff, + lightgoldenrodyellow: 0xfafad2ff, + lightgray: 0xd3d3d3ff, + lightgreen: 0x90ee90ff, + lightgrey: 0xd3d3d3ff, + lightpink: 0xffb6c1ff, + lightsalmon: 0xffa07aff, + lightseagreen: 0x20b2aaff, + lightskyblue: 0x87cefaff, + lightslategray: 0x778899ff, + lightslategrey: 0x778899ff, + lightsteelblue: 0xb0c4deff, + lightyellow: 0xffffe0ff, + lime: 0x00ff00ff, + limegreen: 0x32cd32ff, + linen: 0xfaf0e6ff, + magenta: 0xff00ffff, + maroon: 0x800000ff, + mediumaquamarine: 0x66cdaaff, + mediumblue: 0x0000cdff, + mediumorchid: 0xba55d3ff, + mediumpurple: 0x9370dbff, + mediumseagreen: 0x3cb371ff, + mediumslateblue: 0x7b68eeff, + mediumspringgreen: 0x00fa9aff, + mediumturquoise: 0x48d1ccff, + mediumvioletred: 0xc71585ff, + midnightblue: 0x191970ff, + mintcream: 0xf5fffaff, + mistyrose: 0xffe4e1ff, + moccasin: 0xffe4b5ff, + navajowhite: 0xffdeadff, + navy: 0x000080ff, + oldlace: 0xfdf5e6ff, + olive: 0x808000ff, + olivedrab: 0x6b8e23ff, + orange: 0xffa500ff, + orangered: 0xff4500ff, + orchid: 0xda70d6ff, + palegoldenrod: 0xeee8aaff, + palegreen: 0x98fb98ff, + paleturquoise: 0xafeeeeff, + palevioletred: 0xdb7093ff, + papayawhip: 0xffefd5ff, + peachpuff: 0xffdab9ff, + peru: 0xcd853fff, + pink: 0xffc0cbff, + plum: 0xdda0ddff, + powderblue: 0xb0e0e6ff, + purple: 0x800080ff, + rebeccapurple: 0x663399ff, + red: 0xff0000ff, + rosybrown: 0xbc8f8fff, + royalblue: 0x4169e1ff, + saddlebrown: 0x8b4513ff, + salmon: 0xfa8072ff, + sandybrown: 0xf4a460ff, + seagreen: 0x2e8b57ff, + seashell: 0xfff5eeff, + sienna: 0xa0522dff, + silver: 0xc0c0c0ff, + skyblue: 0x87ceebff, + slateblue: 0x6a5acdff, + slategray: 0x708090ff, + slategrey: 0x708090ff, + snow: 0xfffafaff, + springgreen: 0x00ff7fff, + steelblue: 0x4682b4ff, + tan: 0xd2b48cff, + teal: 0x008080ff, + thistle: 0xd8bfd8ff, + tomato: 0xff6347ff, + turquoise: 0x40e0d0ff, + violet: 0xee82eeff, + wheat: 0xf5deb3ff, + white: 0xffffffff, + whitesmoke: 0xf5f5f5ff, + yellow: 0xffff00ff, + yellowgreen: 0x9acd32ff +}; - geometry.setAttribute('instanceDistanceEnd', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1)); // d1 +const NUMBER = '[-+]?\\d*\\.?\\d+'; +const PERCENTAGE = NUMBER + '%'; - return this; - }; - }() -}); +function call$1(...parts) { + return '\\(\\s*(' + parts.join(')\\s*,\\s*(') + ')\\s*\\)'; +} -var WireframeGeometry2 = function (geometry) { - LineSegmentsGeometry.call(this); - this.type = 'WireframeGeometry2'; - this.fromWireframeGeometry(new WireframeGeometry(geometry)); // set colors, maybe -}; +const rgb = new RegExp('rgb' + call$1(NUMBER, NUMBER, NUMBER)); +const rgba = new RegExp('rgba' + call$1(NUMBER, NUMBER, NUMBER, NUMBER)); +const hsl = new RegExp('hsl' + call$1(NUMBER, PERCENTAGE, PERCENTAGE)); +const hsla = new RegExp('hsla' + call$1(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)); +const hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; +const hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; +const hex6 = /^#([0-9a-fA-F]{6})$/; +const hex8 = /^#([0-9a-fA-F]{8})$/; -WireframeGeometry2.prototype = Object.assign(Object.create(LineSegmentsGeometry.prototype), { - constructor: WireframeGeometry2, - isWireframeGeometry2: true -}); +function normalizeColor(color) { + let match; -class LineSegments2 extends Mesh { - constructor(_geometry = new LineSegmentsGeometry(), _material = new LineMaterial({ - color: Math.random() * 0xffffff - })) { - super(_geometry, _material); + if (typeof color === 'number') { + return color >>> 0 === color && color >= 0 && color <= 0xffffffff ? color : null; + } - _defineProperty$1(this, "type", 'LineSegments2'); + if (match = hex6.exec(color)) return parseInt(match[1] + 'ff', 16) >>> 0; - _defineProperty$1(this, "isLineSegments2", true); + if (colors$1 && colors$1[color] !== undefined) { + return colors$1[color]; + } - _defineProperty$1(this, "distStart", new Vector3()); + if (match = rgb.exec(color)) { + return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | 0x000000ff) >>> 0; + } - _defineProperty$1(this, "distEnd", new Vector3()); + if (match = rgba.exec(color)) { + return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | parse1(match[4])) >>> 0; + } - _defineProperty$1(this, "computeLineDistances", () => { - const geometry = this.geometry; - const instanceStart = geometry.attributes.instanceStart; - const instanceEnd = geometry.attributes.instanceEnd; - const lineDistances = new Float32Array(2 * instanceStart.data.count); + if (match = hex3.exec(color)) { + return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + 'ff', 16) >>> 0; + } - for (let i = 0, j = 0, l = instanceStart.data.count; i < l; i++, j += 2) { - this.distStart.fromBufferAttribute(instanceStart, i); - this.distEnd.fromBufferAttribute(instanceEnd, i); - lineDistances[j] = j === 0 ? 0 : lineDistances[j - 1]; - lineDistances[j + 1] = lineDistances[j] + this.distStart.distanceTo(this.distEnd); - } + if (match = hex8.exec(color)) return parseInt(match[1], 16) >>> 0; - const instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1); // d0, d1 + if (match = hex4.exec(color)) { + return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + match[4] + match[4], 16) >>> 0; + } - geometry.setAttribute('instanceDistanceStart', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0)); // d0 + if (match = hsl.exec(color)) { + return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | 0x000000ff) >>> 0; + } - geometry.setAttribute('instanceDistanceEnd', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1)); // d1 + if (match = hsla.exec(color)) { + return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | parse1(match[4])) >>> 0; + } - return this; - }); + return null; +} - _defineProperty$1(this, "rayStart", new Vector4()); +function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; +} - _defineProperty$1(this, "rayEnd", new Vector4()); +function hslToRgb(h, s, l) { + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + const r = hue2rgb(p, q, h + 1 / 3); + const g = hue2rgb(p, q, h); + const b = hue2rgb(p, q, h - 1 / 3); + return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8; +} - _defineProperty$1(this, "ssOrigin", new Vector4()); +function parse255(str) { + const int = parseInt(str, 10); + if (int < 0) return 0; + if (int > 255) return 255; + return int; +} - _defineProperty$1(this, "ssOrigin3", new Vector3()); +function parse360(str) { + const int = parseFloat(str); + return (int % 360 + 360) % 360 / 360; +} - _defineProperty$1(this, "mvMatrix", new Matrix4()); +function parse1(str) { + const num = parseFloat(str); + if (num < 0) return 0; + if (num > 1) return 255; + return Math.round(num * 255); +} - _defineProperty$1(this, "line", new Line3()); +function parsePercentage(str) { + const int = parseFloat(str); + if (int < 0) return 0; + if (int > 100) return 1; + return int / 100; +} - _defineProperty$1(this, "closestPoint", new Vector3()); +function colorToRgba(input) { + let int32Color = normalizeColor(input); + if (int32Color === null) return input; + int32Color = int32Color || 0; + let r = (int32Color & 0xff000000) >>> 24; + let g = (int32Color & 0x00ff0000) >>> 16; + let b = (int32Color & 0x0000ff00) >>> 8; + let a = (int32Color & 0x000000ff) / 255; + return `rgba(${r}, ${g}, ${b}, ${a})`; +} - _defineProperty$1(this, "raycast", (raycaster, intersects) => { - if (raycaster.camera === null) { - console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2.'); - } +const createInterpolator = (range, output, extrapolate) => { + if (is.fun(range)) { + return range; + } - const threshold = 0; - const ray = raycaster.ray; - const camera = raycaster.camera; - const projectionMatrix = camera.projectionMatrix; - const geometry = this.geometry; - const material = this.material; - const resolution = material.resolution; - const lineWidth = material.linewidth + threshold; - const instanceStart = geometry.attributes.instanceStart; - const instanceEnd = geometry.attributes.instanceEnd; // camera forward is negative - - const near = -camera.near; // pick a point 1 unit out along the ray to avoid the ray origin - // sitting at the camera origin which will cause "w" to be 0 when - // applying the projection matrix. - - ray.at(1, this.ssOrigin); // ndc space [ - 1.0, 1.0 ] - - this.ssOrigin.w = 1; - this.ssOrigin.applyMatrix4(camera.matrixWorldInverse); - this.ssOrigin.applyMatrix4(projectionMatrix); - this.ssOrigin.multiplyScalar(1 / this.ssOrigin.w); // screen space - - this.ssOrigin.x *= resolution.x / 2; - this.ssOrigin.y *= resolution.y / 2; - this.ssOrigin.z = 0; - this.ssOrigin3.set(this.ssOrigin.x, this.ssOrigin.y, this.ssOrigin.z); - const matrixWorld = this.matrixWorld; - this.mvMatrix.multiplyMatrices(camera.matrixWorldInverse, matrixWorld); - - for (let i = 0, l = instanceStart.count; i < l; i++) { - this.rayStart.fromBufferAttribute(instanceStart, i); - this.rayEnd.fromBufferAttribute(instanceEnd, i); - this.rayStart.w = 1; - this.rayEnd.w = 1; // camera space - - this.rayStart.applyMatrix4(this.mvMatrix); - this.rayEnd.applyMatrix4(this.mvMatrix); // skip the segment if it's entirely behind the camera - - const isBehindCameraNear = this.rayStart.z > near && this.rayEnd.z > near; - - if (isBehindCameraNear) { - continue; - } // trim the segment if it extends behind camera near - - - if (this.rayStart.z > near) { - const deltaDist = this.rayStart.z - this.rayEnd.z; - const t = (this.rayStart.z - near) / deltaDist; - this.rayStart.lerp(this.rayEnd, t); - } else if (this.rayEnd.z > near) { - const deltaDist = this.rayEnd.z - this.rayStart.z; - const t = (this.rayEnd.z - near) / deltaDist; - this.rayEnd.lerp(this.rayStart, t); - } // clip space - - - this.rayStart.applyMatrix4(projectionMatrix); - this.rayEnd.applyMatrix4(projectionMatrix); // ndc space [ - 1.0, 1.0 ] - - this.rayStart.multiplyScalar(1 / this.rayStart.w); - this.rayEnd.multiplyScalar(1 / this.rayEnd.w); // screen space - - this.rayStart.x *= resolution.x / 2; - this.rayStart.y *= resolution.y / 2; - this.rayEnd.x *= resolution.x / 2; - this.rayEnd.y *= resolution.y / 2; // create 2d segment - - this.line.start.set(this.rayStart.x, this.rayStart.y, this.rayStart.z); - this.line.start.z = 0; - this.line.end.set(this.rayEnd.x, this.rayEnd.y, this.rayEnd.z); - this.line.end.z = 0; // get closest point on ray to segment - - const param = this.line.closestPointToPointParameter(this.ssOrigin3, true); - this.line.at(param, this.closestPoint); // check if the intersection point is within clip space - - const zPos = MathUtils.lerp(this.rayStart.z, this.rayEnd.z, param); - const isInClipSpace = zPos >= -1 && zPos <= 1; - const isInside = this.ssOrigin3.distanceTo(this.closestPoint) < lineWidth * 0.5; - - if (isInClipSpace && isInside) { - this.line.start.fromBufferAttribute(instanceStart, i); - this.line.end.fromBufferAttribute(instanceEnd, i); - this.line.start.applyMatrix4(matrixWorld); - this.line.end.applyMatrix4(matrixWorld); - const pointOnLine = new Vector3(); - const point = new Vector3(); - ray.distanceSqToSegment(this.line.start, this.line.end, point, pointOnLine); - intersects.push({ - distance: ray.origin.distanceTo(point), - point: point, - face: null, - faceIndex: i, - object: this, - uv: undefined, - pointOnLine - }); - } - } + if (is.arr(range)) { + return createInterpolator({ + range, + output: output, + extrapolate }); } -} - -class Line2 extends LineSegments2 { - constructor(geometry = new LineGeometry(), material = new LineMaterial({ - color: Math.random() * 0xffffff - })) { - super(geometry, material); - - _defineProperty$1(this, "type", 'Line2'); - - _defineProperty$1(this, "isLine2", true); + if (is.str(range.output[0])) { + return createStringInterpolator$1(range); } -} - -new Vector3(); + const config = range; + const outputRange = config.output; + const inputRange = config.range || [0, 1]; + const extrapolateLeft = config.extrapolateLeft || config.extrapolate || 'extend'; + const extrapolateRight = config.extrapolateRight || config.extrapolate || 'extend'; -new Vector3(); + const easing = config.easing || (t => t); -new Vector3(); + return input => { + const range = findRange(input, inputRange); + return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight, config.map); + }; +}; -new Vector3(); +function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) { + let result = map ? map(input) : input; -new Matrix3(); + if (result < inputMin) { + if (extrapolateLeft === 'identity') return result;else if (extrapolateLeft === 'clamp') result = inputMin; + } -const _m1 = new Matrix4(); + if (result > inputMax) { + if (extrapolateRight === 'identity') return result;else if (extrapolateRight === 'clamp') result = inputMax; + } -const _obj = new Object3D(); + if (outputMin === outputMax) return outputMin; + if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax; + if (inputMin === -Infinity) result = -result;else if (inputMax === Infinity) result = result - inputMin;else result = (result - inputMin) / (inputMax - inputMin); + result = easing(result); + if (outputMin === -Infinity) result = -result;else if (outputMax === Infinity) result = result + outputMin;else result = result * (outputMax - outputMin) + outputMin; + return result; +} -const _offset = new Vector3(); +function findRange(input, inputRange) { + for (var i = 1; i < inputRange.length - 1; ++i) if (inputRange[i] >= input) break; -class Geometry extends EventDispatcher { - constructor() { - super(); - this.isGeometry = true; - this.uuid = MathUtils.generateUUID(); - this.name = ''; - this.type = 'Geometry'; - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [[]]; - this.morphTargets = []; - this.morphNormals = []; - this.skinWeights = []; - this.skinIndices = []; - this.lineDistances = []; - this.boundingBox = null; - this.boundingSphere = null; // update flags - - this.elementsNeedUpdate = false; - this.verticesNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; - this.groupsNeedUpdate = false; - } - - applyMatrix4(matrix) { - const normalMatrix = new Matrix3().getNormalMatrix(matrix); - - for (let i = 0, il = this.vertices.length; i < il; i++) { - const vertex = this.vertices[i]; - vertex.applyMatrix4(matrix); - } + return i - 1; +} - for (let i = 0, il = this.faces.length; i < il; i++) { - const face = this.faces[i]; - face.normal.applyMatrix3(normalMatrix).normalize(); +function _extends$2() { + _extends$2 = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - for (let j = 0, jl = face.vertexNormals.length; j < jl; j++) { - face.vertexNormals[j].applyMatrix3(normalMatrix).normalize(); + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } } } - if (this.boundingBox !== null) { - this.computeBoundingBox(); - } - - if (this.boundingSphere !== null) { - this.computeBoundingSphere(); - } + return target; + }; - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; - return this; - } + return _extends$2.apply(this, arguments); +} - rotateX(angle) { - // rotate geometry around world x-axis - _m1.makeRotationX(angle); +const $get = Symbol.for('FluidValue.get'); +const $observers = Symbol.for('FluidValue.observers'); - this.applyMatrix4(_m1); - return this; - } +const hasFluidValue = arg => Boolean(arg && arg[$get]); - rotateY(angle) { - // rotate geometry around world y-axis - _m1.makeRotationY(angle); +const getFluidValue = arg => arg && arg[$get] ? arg[$get]() : arg; - this.applyMatrix4(_m1); - return this; +function callFluidObserver(observer, event) { + if (observer.eventObserved) { + observer.eventObserved(event); + } else { + observer(event); } +} - rotateZ(angle) { - // rotate geometry around world z-axis - _m1.makeRotationZ(angle); +function callFluidObservers(target, event) { + let observers = target[$observers]; - this.applyMatrix4(_m1); - return this; + if (observers) { + observers.forEach(observer => { + callFluidObserver(observer, event); + }); } +} - translate(x, y, z) { - // translate geometry - _m1.makeTranslation(x, y, z); - - this.applyMatrix4(_m1); - return this; - } +class FluidValue { + constructor(get) { + this[$get] = void 0; + this[$observers] = void 0; - scale(x, y, z) { - // scale geometry - _m1.makeScale(x, y, z); + if (!get && !(get = this.get)) { + throw Error('Unknown getter'); + } - this.applyMatrix4(_m1); - return this; + setFluidGetter(this, get); } - lookAt(vector) { - _obj.lookAt(vector); - - _obj.updateMatrix(); +} - this.applyMatrix4(_obj.matrix); - return this; - } +const setFluidGetter = (target, get) => setHidden(target, $get, get); - fromBufferGeometry(geometry) { - const scope = this; - const index = geometry.index !== null ? geometry.index : undefined; - const attributes = geometry.attributes; +function addFluidObserver(target, observer) { + if (target[$get]) { + let observers = target[$observers]; - if (attributes.position === undefined) { - console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.'); - return this; + if (!observers) { + setHidden(target, $observers, observers = new Set()); } - const position = attributes.position; - const normal = attributes.normal; - const color = attributes.color; - const uv = attributes.uv; - const uv2 = attributes.uv2; - if (uv2 !== undefined) this.faceVertexUvs[1] = []; - - for (let i = 0; i < position.count; i++) { - scope.vertices.push(new Vector3().fromBufferAttribute(position, i)); + if (!observers.has(observer)) { + observers.add(observer); - if (color !== undefined) { - scope.colors.push(new Color().fromBufferAttribute(color, i)); + if (target.observerAdded) { + target.observerAdded(observers.size, observer); } } + } - function addFace(a, b, c, materialIndex) { - const vertexColors = color === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()]; - const vertexNormals = normal === undefined ? [] : [new Vector3().fromBufferAttribute(normal, a), new Vector3().fromBufferAttribute(normal, b), new Vector3().fromBufferAttribute(normal, c)]; - const face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex); - scope.faces.push(face); - - if (uv !== undefined) { - scope.faceVertexUvs[0].push([new Vector2().fromBufferAttribute(uv, a), new Vector2().fromBufferAttribute(uv, b), new Vector2().fromBufferAttribute(uv, c)]); - } - - if (uv2 !== undefined) { - scope.faceVertexUvs[1].push([new Vector2().fromBufferAttribute(uv2, a), new Vector2().fromBufferAttribute(uv2, b), new Vector2().fromBufferAttribute(uv2, c)]); - } - } + return observer; +} - const groups = geometry.groups; +function removeFluidObserver(target, observer) { + let observers = target[$observers]; - if (groups.length > 0) { - for (let i = 0; i < groups.length; i++) { - const group = groups[i]; - const start = group.start; - const count = group.count; + if (observers && observers.has(observer)) { + const count = observers.size - 1; - for (let j = start, jl = start + count; j < jl; j += 3) { - if (index !== undefined) { - addFace(index.getX(j), index.getX(j + 1), index.getX(j + 2), group.materialIndex); - } else { - addFace(j, j + 1, j + 2, group.materialIndex); - } - } - } + if (count) { + observers.delete(observer); } else { - if (index !== undefined) { - for (let i = 0; i < index.count; i += 3) { - addFace(index.getX(i), index.getX(i + 1), index.getX(i + 2)); - } - } else { - for (let i = 0; i < position.count; i += 3) { - addFace(i, i + 1, i + 2); - } - } + target[$observers] = null; } - this.computeFaceNormals(); - - if (geometry.boundingBox !== null) { - this.boundingBox = geometry.boundingBox.clone(); + if (target.observerRemoved) { + target.observerRemoved(count, observer); } + } +} - if (geometry.boundingSphere !== null) { - this.boundingSphere = geometry.boundingSphere.clone(); - } +const setHidden = (target, key, value) => Object.defineProperty(target, key, { + value, + writable: true, + configurable: true +}); - return this; - } +const numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; +const colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi; +const unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, 'i'); +const rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi; +const cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/; - center() { - this.computeBoundingBox(); - this.boundingBox.getCenter(_offset).negate(); - this.translate(_offset.x, _offset.y, _offset.z); - return this; - } +const variableToRgba = input => { + const [token, fallback] = parseCSSVariable(input); - normalize() { - this.computeBoundingSphere(); - const center = this.boundingSphere.center; - const radius = this.boundingSphere.radius; - const s = radius === 0 ? 1 : 1.0 / radius; - const matrix = new Matrix4(); - matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1); - this.applyMatrix4(matrix); - return this; + if (!token || isSSR()) { + return input; } - computeFaceNormals() { - const cb = new Vector3(), - ab = new Vector3(); - - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const vA = this.vertices[face.a]; - const vB = this.vertices[face.b]; - const vC = this.vertices[face.c]; - cb.subVectors(vC, vB); - ab.subVectors(vA, vB); - cb.cross(ab); - cb.normalize(); - face.normal.copy(cb); - } - } + const value = window.getComputedStyle(document.documentElement).getPropertyValue(token); - computeVertexNormals(areaWeighted = true) { - const vertices = new Array(this.vertices.length); + if (value) { + return value.trim(); + } else if (fallback && fallback.startsWith('--')) { + const _value = window.getComputedStyle(document.documentElement).getPropertyValue(fallback); - for (let v = 0, vl = this.vertices.length; v < vl; v++) { - vertices[v] = new Vector3(); + if (_value) { + return _value; + } else { + return input; } + } else if (fallback && cssVariableRegex.test(fallback)) { + return variableToRgba(fallback); + } else if (fallback) { + return fallback; + } - if (areaWeighted) { - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm - const cb = new Vector3(), - ab = new Vector3(); - - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const vA = this.vertices[face.a]; - const vB = this.vertices[face.b]; - const vC = this.vertices[face.c]; - cb.subVectors(vC, vB); - ab.subVectors(vA, vB); - cb.cross(ab); - vertices[face.a].add(cb); - vertices[face.b].add(cb); - vertices[face.c].add(cb); - } - } else { - this.computeFaceNormals(); + return input; +}; - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - vertices[face.a].add(face.normal); - vertices[face.b].add(face.normal); - vertices[face.c].add(face.normal); - } - } +const parseCSSVariable = current => { + const match = cssVariableRegex.exec(current); + if (!match) return [,]; + const [, token, fallback] = match; + return [token, fallback]; +}; - for (let v = 0, vl = this.vertices.length; v < vl; v++) { - vertices[v].normalize(); - } +let namedColorRegex; - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const vertexNormals = face.vertexNormals; +const rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`; - if (vertexNormals.length === 3) { - vertexNormals[0].copy(vertices[face.a]); - vertexNormals[1].copy(vertices[face.b]); - vertexNormals[2].copy(vertices[face.c]); - } else { - vertexNormals[0] = vertices[face.a].clone(); - vertexNormals[1] = vertices[face.b].clone(); - vertexNormals[2] = vertices[face.c].clone(); - } +const createStringInterpolator = config => { + if (!namedColorRegex) namedColorRegex = colors$1 ? new RegExp(`(${Object.keys(colors$1).join('|')})(?!\\w)`, 'g') : /^\b$/; + const output = config.output.map(value => { + return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba); + }); + const keyframes = output.map(value => value.match(numberRegex).map(Number)); + const outputRanges = keyframes[0].map((_, i) => keyframes.map(values => { + if (!(i in values)) { + throw Error('The arity of each "output" value must be equal'); } - if (this.faces.length > 0) { - this.normalsNeedUpdate = true; - } - } + return values[i]; + })); + const interpolators = outputRanges.map(output => createInterpolator(_extends$2({}, config, { + output + }))); + return input => { + var _output$find; - computeFlatVertexNormals() { - this.computeFaceNormals(); + const missingUnit = !unitRegex.test(output[0]) && ((_output$find = output.find(value => unitRegex.test(value))) == null ? void 0 : _output$find.replace(numberRegex, '')); + let i = 0; + return output[0].replace(numberRegex, () => `${interpolators[i++](input)}${missingUnit || ''}`).replace(rgbaRegex, rgbaRound); + }; +}; - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const vertexNormals = face.vertexNormals; +const prefix = 'react-spring: '; - if (vertexNormals.length === 3) { - vertexNormals[0].copy(face.normal); - vertexNormals[1].copy(face.normal); - vertexNormals[2].copy(face.normal); - } else { - vertexNormals[0] = face.normal.clone(); - vertexNormals[1] = face.normal.clone(); - vertexNormals[2] = face.normal.clone(); - } - } +const once = fn => { + const func = fn; + let called = false; - if (this.faces.length > 0) { - this.normalsNeedUpdate = true; - } + if (typeof func != 'function') { + throw new TypeError(`${prefix}once requires a function parameter`); } - computeMorphNormals() { - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - - if (!face.__originalFaceNormal) { - face.__originalFaceNormal = face.normal.clone(); - } else { - face.__originalFaceNormal.copy(face.normal); - } + return (...args) => { + if (!called) { + func(...args); + called = true; + } + }; +}; - if (!face.__originalVertexNormals) face.__originalVertexNormals = []; +const warnInterpolate = once(console.warn); +function deprecateInterpolate() { + warnInterpolate(`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`); +} +once(console.warn); - for (let i = 0, il = face.vertexNormals.length; i < il; i++) { - if (!face.__originalVertexNormals[i]) { - face.__originalVertexNormals[i] = face.vertexNormals[i].clone(); - } else { - face.__originalVertexNormals[i].copy(face.vertexNormals[i]); - } - } - } // use temp geometry to compute face and vertex normals for each morph - - - const tmpGeo = new Geometry(); - tmpGeo.faces = this.faces; - - for (let i = 0, il = this.morphTargets.length; i < il; i++) { - // create on first access - if (!this.morphNormals[i]) { - this.morphNormals[i] = {}; - this.morphNormals[i].faceNormals = []; - this.morphNormals[i].vertexNormals = []; - const dstNormalsFace = this.morphNormals[i].faceNormals; - const dstNormalsVertex = this.morphNormals[i].vertexNormals; - - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const faceNormal = new Vector3(); - const vertexNormals = { - a: new Vector3(), - b: new Vector3(), - c: new Vector3() - }; - dstNormalsFace.push(faceNormal); - dstNormalsVertex.push(vertexNormals); - } - } +function isAnimatedString(value) { + return is.str(value) && (value[0] == '#' || /\d/.test(value) || !isSSR() && cssVariableRegex.test(value) || value in (colors$1 || {})); +} - const morphNormals = this.morphNormals[i]; // set vertices to morph target +const useLayoutEffect = typeof window !== 'undefined' && window.document && window.document.createElement ? React.useLayoutEffect : React.useEffect; - tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals +const useIsMounted = () => { + const isMounted = useRef(false); + useLayoutEffect(() => { + isMounted.current = true; + return () => { + isMounted.current = false; + }; + }, []); + return isMounted; +}; - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); // store morph normals +function useForceUpdate() { + const update = useState()[1]; + const isMounted = useIsMounted(); + return () => { + if (isMounted.current) { + update(Math.random()); + } + }; +} - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const faceNormal = morphNormals.faceNormals[f]; - const vertexNormals = morphNormals.vertexNormals[f]; - faceNormal.copy(face.normal); - vertexNormals.a.copy(face.vertexNormals[0]); - vertexNormals.b.copy(face.vertexNormals[1]); - vertexNormals.c.copy(face.vertexNormals[2]); - } - } // restore original normals +function useMemoOne(getResult, inputs) { + const [initial] = useState(() => ({ + inputs, + result: getResult() + })); + const committed = useRef(); + const prevCache = committed.current; + let cache = prevCache; + if (cache) { + const useCache = Boolean(inputs && cache.inputs && areInputsEqual(inputs, cache.inputs)); - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + if (!useCache) { + cache = { + inputs, + result: getResult() + }; } + } else { + cache = initial; } - computeBoundingBox() { - if (this.boundingBox === null) { - this.boundingBox = new Box3(); - } - - this.boundingBox.setFromPoints(this.vertices); - } + useEffect(() => { + committed.current = cache; - computeBoundingSphere() { - if (this.boundingSphere === null) { - this.boundingSphere = new Sphere(); + if (prevCache == initial) { + initial.inputs = initial.result = undefined; } + }, [cache]); + return cache.result; +} - this.boundingSphere.setFromPoints(this.vertices); +function areInputsEqual(next, prev) { + if (next.length !== prev.length) { + return false; } - merge(geometry, matrix, materialIndexOffset = 0) { - if (!(geometry && geometry.isGeometry)) { - console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry); - return; + for (let i = 0; i < next.length; i++) { + if (next[i] !== prev[i]) { + return false; } + } - let normalMatrix; - const vertexOffset = this.vertices.length, - vertices1 = this.vertices, - vertices2 = geometry.vertices, - faces1 = this.faces, - faces2 = geometry.faces, - colors1 = this.colors, - colors2 = geometry.colors; - - if (matrix !== undefined) { - normalMatrix = new Matrix3().getNormalMatrix(matrix); - } // vertices - - - for (let i = 0, il = vertices2.length; i < il; i++) { - const vertex = vertices2[i]; - const vertexCopy = vertex.clone(); - if (matrix !== undefined) vertexCopy.applyMatrix4(matrix); - vertices1.push(vertexCopy); - } // colors - - - for (let i = 0, il = colors2.length; i < il; i++) { - colors1.push(colors2[i].clone()); - } // faces - - - for (let i = 0, il = faces2.length; i < il; i++) { - const face = faces2[i]; - let normal, color; - const faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; - const faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset); - faceCopy.normal.copy(face.normal); - - if (normalMatrix !== undefined) { - faceCopy.normal.applyMatrix3(normalMatrix).normalize(); - } - - for (let j = 0, jl = faceVertexNormals.length; j < jl; j++) { - normal = faceVertexNormals[j].clone(); - - if (normalMatrix !== undefined) { - normal.applyMatrix3(normalMatrix).normalize(); - } - - faceCopy.vertexNormals.push(normal); - } - - faceCopy.color.copy(face.color); - - for (let j = 0, jl = faceVertexColors.length; j < jl; j++) { - color = faceVertexColors[j]; - faceCopy.vertexColors.push(color.clone()); - } + return true; +} - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - faces1.push(faceCopy); - } // uvs +const useOnce = effect => useEffect(effect, emptyDeps); +const emptyDeps = []; +const $node = Symbol.for('Animated:node'); +const isAnimated = value => !!value && value[$node] === value; +const getAnimated = owner => owner && owner[$node]; +const setAnimated = (owner, node) => defineHidden(owner, $node, node); +const getPayload = owner => owner && owner[$node] && owner[$node].getPayload(); +class Animated { + constructor() { + this.payload = void 0; + setAnimated(this, this); + } - for (let i = 0, il = geometry.faceVertexUvs.length; i < il; i++) { - const faceVertexUvs2 = geometry.faceVertexUvs[i]; - if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = []; + getPayload() { + return this.payload || []; + } - for (let j = 0, jl = faceVertexUvs2.length; j < jl; j++) { - const uvs2 = faceVertexUvs2[j], - uvsCopy = []; +} - for (let k = 0, kl = uvs2.length; k < kl; k++) { - uvsCopy.push(uvs2[k].clone()); - } +class AnimatedValue extends Animated { + constructor(_value) { + super(); + this.done = true; + this.elapsedTime = void 0; + this.lastPosition = void 0; + this.lastVelocity = void 0; + this.v0 = void 0; + this.durationProgress = 0; + this._value = _value; - this.faceVertexUvs[i].push(uvsCopy); - } + if (is.num(this._value)) { + this.lastPosition = this._value; } } - mergeMesh(mesh) { - if (!(mesh && mesh.isMesh)) { - console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh); - return; - } - - if (mesh.matrixAutoUpdate) mesh.updateMatrix(); - this.merge(mesh.geometry, mesh.matrix); + static create(value) { + return new AnimatedValue(value); } - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ - - - mergeVertices(precisionPoints = 4) { - const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) - - const unique = [], - changes = []; - const precision = Math.pow(10, precisionPoints); - - for (let i = 0, il = this.vertices.length; i < il; i++) { - const v = this.vertices[i]; - const key = `${Math.round(v.x * precision)}_${Math.round(v.y * precision)}_${Math.round(v.z * precision)}`; - if (verticesMap[key] === undefined) { - verticesMap[key] = i; - unique.push(this.vertices[i]); - changes[i] = unique.length - 1; - } else { - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[i] = changes[verticesMap[key]]; - } - } // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. + getPayload() { + return [this]; + } + getValue() { + return this._value; + } - const faceIndicesToRemove = []; + setValue(value, step) { + if (is.num(value)) { + this.lastPosition = value; - for (let i = 0, il = this.faces.length; i < il; i++) { - const face = this.faces[i]; - face.a = changes[face.a]; - face.b = changes[face.b]; - face.c = changes[face.c]; - const indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3 - // we have to remove the face as nothing can be saved + if (step) { + value = Math.round(value / step) * step; - for (let n = 0; n < 3; n++) { - if (indices[n] === indices[(n + 1) % 3]) { - faceIndicesToRemove.push(i); - break; + if (this.done) { + this.lastPosition = value; } } } - for (let i = faceIndicesToRemove.length - 1; i >= 0; i--) { - const idx = faceIndicesToRemove[i]; - this.faces.splice(idx, 1); - - for (let j = 0, jl = this.faceVertexUvs.length; j < jl; j++) { - this.faceVertexUvs[j].splice(idx, 1); - } - } // Use unique set of vertices - - - const diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; - } - - setFromPoints(points) { - this.vertices = []; - - for (let i = 0, l = points.length; i < l; i++) { - const point = points[i]; - this.vertices.push(new Vector3(point.x, point.y, point.z || 0)); + if (this._value === value) { + return false; } - return this; + this._value = value; + return true; } - sortFacesByMaterialIndex() { - const faces = this.faces; - const length = faces.length; // tag faces - - for (let i = 0; i < length; i++) { - faces[i]._id = i; - } // sort faces - + reset() { + const { + done + } = this; + this.done = false; - function materialIndexSort(a, b) { - return a.materialIndex - b.materialIndex; + if (is.num(this._value)) { + this.elapsedTime = 0; + this.durationProgress = 0; + this.lastPosition = this._value; + if (done) this.lastVelocity = null; + this.v0 = null; } + } - faces.sort(materialIndexSort); // sort uvs - - const uvs1 = this.faceVertexUvs[0]; - const uvs2 = this.faceVertexUvs[1]; - let newUvs1, newUvs2; - if (uvs1 && uvs1.length === length) newUvs1 = []; - if (uvs2 && uvs2.length === length) newUvs2 = []; - - for (let i = 0; i < length; i++) { - const id = faces[i]._id; - if (newUvs1) newUvs1.push(uvs1[id]); - if (newUvs2) newUvs2.push(uvs2[id]); - } +} - if (newUvs1) this.faceVertexUvs[0] = newUvs1; - if (newUvs2) this.faceVertexUvs[1] = newUvs2; +class AnimatedString extends AnimatedValue { + constructor(value) { + super(0); + this._string = null; + this._toString = void 0; + this._toString = createInterpolator({ + output: [value, value] + }); } - toJSON() { - const data = { - metadata: { - version: 4.5, - type: 'Geometry', - generator: 'Geometry.toJSON' - } - }; // standard Geometry serialization - - data.uuid = this.uuid; - data.type = this.type; - if (this.name !== '') data.name = this.name; + static create(value) { + return new AnimatedString(value); + } - if (this.parameters !== undefined) { - const parameters = this.parameters; + getValue() { + let value = this._string; + return value == null ? this._string = this._toString(this._value) : value; + } - for (let key in parameters) { - if (parameters[key] !== undefined) data[key] = parameters[key]; + setValue(value) { + if (is.str(value)) { + if (value == this._string) { + return false; } - return data; - } - - const vertices = []; - - for (let i = 0; i < this.vertices.length; i++) { - const vertex = this.vertices[i]; - vertices.push(vertex.x, vertex.y, vertex.z); + this._string = value; + this._value = 1; + } else if (super.setValue(value)) { + this._string = null; + } else { + return false; } - const faces = []; - const normals = []; - const normalsHash = {}; - const colors = []; - const colorsHash = {}; - const uvs = []; - const uvsHash = {}; - - for (let i = 0; i < this.faces.length; i++) { - const face = this.faces[i]; - const hasMaterial = true; - const hasFaceUv = false; // deprecated - - const hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined; - const hasFaceNormal = face.normal.length() > 0; - const hasFaceVertexNormal = face.vertexNormals.length > 0; - const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; - const hasFaceVertexColor = face.vertexColors.length > 0; - let faceType = 0; - faceType = setBit(faceType, 0, 0); // isQuad - - faceType = setBit(faceType, 1, hasMaterial); - faceType = setBit(faceType, 2, hasFaceUv); - faceType = setBit(faceType, 3, hasFaceVertexUv); - faceType = setBit(faceType, 4, hasFaceNormal); - faceType = setBit(faceType, 5, hasFaceVertexNormal); - faceType = setBit(faceType, 6, hasFaceColor); - faceType = setBit(faceType, 7, hasFaceVertexColor); - faces.push(faceType); - faces.push(face.a, face.b, face.c); - faces.push(face.materialIndex); - - if (hasFaceVertexUv) { - const faceVertexUvs = this.faceVertexUvs[0][i]; - faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2])); - } - - if (hasFaceNormal) { - faces.push(getNormalIndex(face.normal)); - } - - if (hasFaceVertexNormal) { - const vertexNormals = face.vertexNormals; - faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2])); - } - - if (hasFaceColor) { - faces.push(getColorIndex(face.color)); - } - - if (hasFaceVertexColor) { - const vertexColors = face.vertexColors; - faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2])); - } - } + return true; + } - function setBit(value, position, enabled) { - return enabled ? value | 1 << position : value & ~(1 << position); + reset(goal) { + if (goal) { + this._toString = createInterpolator({ + output: [this.getValue(), goal] + }); } - function getNormalIndex(normal) { - const hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); + this._value = 0; + super.reset(); + } - if (normalsHash[hash] !== undefined) { - return normalsHash[hash]; - } +} - normalsHash[hash] = normals.length / 3; - normals.push(normal.x, normal.y, normal.z); - return normalsHash[hash]; - } +const TreeContext = { + dependencies: null +}; - function getColorIndex(color) { - const hash = color.r.toString() + color.g.toString() + color.b.toString(); +class AnimatedObject extends Animated { + constructor(source) { + super(); + this.source = source; + this.setValue(source); + } - if (colorsHash[hash] !== undefined) { - return colorsHash[hash]; + getValue(animated) { + const values = {}; + eachProp(this.source, (source, key) => { + if (isAnimated(source)) { + values[key] = source.getValue(animated); + } else if (hasFluidValue(source)) { + values[key] = getFluidValue(source); + } else if (!animated) { + values[key] = source; } + }); + return values; + } - colorsHash[hash] = colors.length; - colors.push(color.getHex()); - return colorsHash[hash]; - } - - function getUvIndex(uv) { - const hash = uv.x.toString() + uv.y.toString(); - - if (uvsHash[hash] !== undefined) { - return uvsHash[hash]; - } + setValue(source) { + this.source = source; + this.payload = this._makePayload(source); + } - uvsHash[hash] = uvs.length / 2; - uvs.push(uv.x, uv.y); - return uvsHash[hash]; + reset() { + if (this.payload) { + each(this.payload, node => node.reset()); } - - data.data = {}; - data.data.vertices = vertices; - data.data.normals = normals; - if (colors.length > 0) data.data.colors = colors; - if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility - - data.data.faces = faces; - return data; } - clone() { - /* - // Handle primitives - const parameters = this.parameters; - if ( parameters !== undefined ) { - const values = []; - for ( const key in parameters ) { - values.push( parameters[ key ] ); - } - const geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + _makePayload(source) { + if (source) { + const payload = new Set(); + eachProp(source, this._addToPayload, payload); + return Array.from(payload); } - return new this.constructor().copy( this ); - */ - return new Geometry().copy(this); } - copy(source) { - // reset - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [[]]; - this.morphTargets = []; - this.morphNormals = []; - this.skinWeights = []; - this.skinIndices = []; - this.lineDistances = []; - this.boundingBox = null; - this.boundingSphere = null; // name + _addToPayload(source) { + if (TreeContext.dependencies && hasFluidValue(source)) { + TreeContext.dependencies.add(source); + } - this.name = source.name; // vertices + const payload = getPayload(source); - const vertices = source.vertices; + if (payload) { + each(payload, node => this.add(node)); + } + } - for (let i = 0, il = vertices.length; i < il; i++) { - this.vertices.push(vertices[i].clone()); - } // colors +} +class AnimatedArray extends AnimatedObject { + constructor(source) { + super(source); + } - const colors = source.colors; + static create(source) { + return new AnimatedArray(source); + } - for (let i = 0, il = colors.length; i < il; i++) { - this.colors.push(colors[i].clone()); - } // faces + getValue() { + return this.source.map(node => node.getValue()); + } + setValue(source) { + const payload = this.getPayload(); - const faces = source.faces; + if (source.length == payload.length) { + return payload.map((node, i) => node.setValue(source[i])).some(Boolean); + } - for (let i = 0, il = faces.length; i < il; i++) { - this.faces.push(faces[i].clone()); - } // face vertex uvs + super.setValue(source.map(makeAnimated)); + return true; + } +} - for (let i = 0, il = source.faceVertexUvs.length; i < il; i++) { - const faceVertexUvs = source.faceVertexUvs[i]; +function makeAnimated(value) { + const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue; + return nodeType.create(value); +} - if (this.faceVertexUvs[i] === undefined) { - this.faceVertexUvs[i] = []; - } +function getAnimatedType(value) { + const parentNode = getAnimated(value); + return parentNode ? parentNode.constructor : is.arr(value) ? AnimatedArray : isAnimatedString(value) ? AnimatedString : AnimatedValue; +} - for (let j = 0, jl = faceVertexUvs.length; j < jl; j++) { - const uvs = faceVertexUvs[j], - uvsCopy = []; +function _extends$1() { + _extends$1 = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - for (let k = 0, kl = uvs.length; k < kl; k++) { - const uv = uvs[k]; - uvsCopy.push(uv.clone()); + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; } - - this.faceVertexUvs[i].push(uvsCopy); } - } // morph targets - - - const morphTargets = source.morphTargets; - - for (let i = 0, il = morphTargets.length; i < il; i++) { - const morphTarget = {}; - morphTarget.name = morphTargets[i].name; // vertices + } - if (morphTargets[i].vertices !== undefined) { - morphTarget.vertices = []; + return target; + }; - for (let j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) { - morphTarget.vertices.push(morphTargets[i].vertices[j].clone()); - } - } // normals + return _extends$1.apply(this, arguments); +} +const withAnimated = (Component, host) => { + const hasInstance = !is.fun(Component) || Component.prototype && Component.prototype.isReactComponent; + return forwardRef((givenProps, givenRef) => { + const instanceRef = useRef(null); + const ref = hasInstance && useCallback(value => { + instanceRef.current = updateRef(givenRef, value); + }, [givenRef]); + const [props, deps] = getAnimatedState(givenProps, host); + const forceUpdate = useForceUpdate(); - if (morphTargets[i].normals !== undefined) { - morphTarget.normals = []; + const callback = () => { + const instance = instanceRef.current; - for (let j = 0, jl = morphTargets[i].normals.length; j < jl; j++) { - morphTarget.normals.push(morphTargets[i].normals[j].clone()); - } + if (hasInstance && !instance) { + return; } - this.morphTargets.push(morphTarget); - } // morph normals + const didUpdate = instance ? host.applyAnimatedValues(instance, props.getValue(true)) : false; + if (didUpdate === false) { + forceUpdate(); + } + }; - const morphNormals = source.morphNormals; + const observer = new PropsObserver(callback, deps); + const observerRef = useRef(); + useLayoutEffect(() => { + observerRef.current = observer; + each(deps, dep => addFluidObserver(dep, observer)); + return () => { + if (observerRef.current) { + each(observerRef.current.deps, dep => removeFluidObserver(dep, observerRef.current)); + raf.cancel(observerRef.current.update); + } + }; + }); + useEffect(callback, []); + useOnce(() => () => { + const observer = observerRef.current; + each(observer.deps, dep => removeFluidObserver(dep, observer)); + }); + const usedProps = host.getComponentProps(props.getValue()); + return React.createElement(Component, _extends$1({}, usedProps, { + ref: ref + })); + }); +}; - for (let i = 0, il = morphNormals.length; i < il; i++) { - const morphNormal = {}; // vertex normals +class PropsObserver { + constructor(update, deps) { + this.update = update; + this.deps = deps; + } - if (morphNormals[i].vertexNormals !== undefined) { - morphNormal.vertexNormals = []; + eventObserved(event) { + if (event.type == 'change') { + raf.write(this.update); + } + } - for (let j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) { - const srcVertexNormal = morphNormals[i].vertexNormals[j]; - const destVertexNormal = {}; - destVertexNormal.a = srcVertexNormal.a.clone(); - destVertexNormal.b = srcVertexNormal.b.clone(); - destVertexNormal.c = srcVertexNormal.c.clone(); - morphNormal.vertexNormals.push(destVertexNormal); - } - } // face normals +} +function getAnimatedState(props, host) { + const dependencies = new Set(); + TreeContext.dependencies = dependencies; + if (props.style) props = _extends$1({}, props, { + style: host.createAnimatedStyle(props.style) + }); + props = new AnimatedObject(props); + TreeContext.dependencies = null; + return [props, dependencies]; +} - if (morphNormals[i].faceNormals !== undefined) { - morphNormal.faceNormals = []; +function updateRef(ref, value) { + if (ref) { + if (is.fun(ref)) ref(value);else ref.current = value; + } - for (let j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) { - morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone()); - } - } + return value; +} - this.morphNormals.push(morphNormal); - } // skin weights +const cacheKey = Symbol.for('AnimatedComponent'); +const createHost = (components, { + applyAnimatedValues: _applyAnimatedValues = () => false, + createAnimatedStyle: _createAnimatedStyle = style => new AnimatedObject(style), + getComponentProps: _getComponentProps = props => props +} = {}) => { + const hostConfig = { + applyAnimatedValues: _applyAnimatedValues, + createAnimatedStyle: _createAnimatedStyle, + getComponentProps: _getComponentProps + }; + const animated = Component => { + const displayName = getDisplayName(Component) || 'Anonymous'; - const skinWeights = source.skinWeights; + if (is.str(Component)) { + Component = animated[Component] || (animated[Component] = withAnimated(Component, hostConfig)); + } else { + Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig)); + } - for (let i = 0, il = skinWeights.length; i < il; i++) { - this.skinWeights.push(skinWeights[i].clone()); - } // skin indices + Component.displayName = `Animated(${displayName})`; + return Component; + }; + eachProp(components, (Component, key) => { + if (is.arr(components)) { + key = getDisplayName(Component); + } - const skinIndices = source.skinIndices; + animated[key] = animated(Component); + }); + return { + animated + }; +}; - for (let i = 0, il = skinIndices.length; i < il; i++) { - this.skinIndices.push(skinIndices[i].clone()); - } // line distances +const getDisplayName = arg => is.str(arg) ? arg : arg && is.str(arg.displayName) ? arg.displayName : is.fun(arg) && arg.name || null; +function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - const lineDistances = source.lineDistances; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } - for (let i = 0, il = lineDistances.length; i < il; i++) { - this.lineDistances.push(lineDistances[i]); - } // bounding box + return target; + }; + return _extends.apply(this, arguments); +} - const boundingBox = source.boundingBox; +const config = { + default: { + tension: 170, + friction: 26 + }, + gentle: { + tension: 120, + friction: 14 + }, + wobbly: { + tension: 180, + friction: 12 + }, + stiff: { + tension: 210, + friction: 20 + }, + slow: { + tension: 280, + friction: 60 + }, + molasses: { + tension: 280, + friction: 120 + } +}; +const c1 = 1.70158; +const c2 = c1 * 1.525; +const c3 = c1 + 1; +const c4 = 2 * Math.PI / 3; +const c5 = 2 * Math.PI / 4.5; - if (boundingBox !== null) { - this.boundingBox = boundingBox.clone(); - } // bounding sphere +const bounceOut = x => { + const n1 = 7.5625; + const d1 = 2.75; + if (x < 1 / d1) { + return n1 * x * x; + } else if (x < 2 / d1) { + return n1 * (x -= 1.5 / d1) * x + 0.75; + } else if (x < 2.5 / d1) { + return n1 * (x -= 2.25 / d1) * x + 0.9375; + } else { + return n1 * (x -= 2.625 / d1) * x + 0.984375; + } +}; - const boundingSphere = source.boundingSphere; +const easings = { + linear: x => x, + easeInQuad: x => x * x, + easeOutQuad: x => 1 - (1 - x) * (1 - x), + easeInOutQuad: x => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2, + easeInCubic: x => x * x * x, + easeOutCubic: x => 1 - Math.pow(1 - x, 3), + easeInOutCubic: x => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2, + easeInQuart: x => x * x * x * x, + easeOutQuart: x => 1 - Math.pow(1 - x, 4), + easeInOutQuart: x => x < 0.5 ? 8 * x * x * x * x : 1 - Math.pow(-2 * x + 2, 4) / 2, + easeInQuint: x => x * x * x * x * x, + easeOutQuint: x => 1 - Math.pow(1 - x, 5), + easeInOutQuint: x => x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2, + easeInSine: x => 1 - Math.cos(x * Math.PI / 2), + easeOutSine: x => Math.sin(x * Math.PI / 2), + easeInOutSine: x => -(Math.cos(Math.PI * x) - 1) / 2, + easeInExpo: x => x === 0 ? 0 : Math.pow(2, 10 * x - 10), + easeOutExpo: x => x === 1 ? 1 : 1 - Math.pow(2, -10 * x), + easeInOutExpo: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2, + easeInCirc: x => 1 - Math.sqrt(1 - Math.pow(x, 2)), + easeOutCirc: x => Math.sqrt(1 - Math.pow(x - 1, 2)), + easeInOutCirc: x => x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2, + easeInBack: x => c3 * x * x * x - c1 * x * x, + easeOutBack: x => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2), + easeInOutBack: x => x < 0.5 ? Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2, + easeInElastic: x => x === 0 ? 0 : x === 1 ? 1 : -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4), + easeOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1, + easeInOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2 : Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5) / 2 + 1, + easeInBounce: x => 1 - bounceOut(1 - x), + easeOutBounce: bounceOut, + easeInOutBounce: x => x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2 +}; - if (boundingSphere !== null) { - this.boundingSphere = boundingSphere.clone(); - } // update flags +_extends({}, config.default, { + mass: 1, + damping: 1, + easing: easings.linear, + clamp: false +}); +const isFrameValue = value => value instanceof FrameValue; +let nextId$1 = 1; +class FrameValue extends FluidValue { + constructor(...args) { + super(...args); + this.id = nextId$1++; + this.key = void 0; + this._priority = 0; + } - this.elementsNeedUpdate = source.elementsNeedUpdate; - this.verticesNeedUpdate = source.verticesNeedUpdate; - this.uvsNeedUpdate = source.uvsNeedUpdate; - this.normalsNeedUpdate = source.normalsNeedUpdate; - this.colorsNeedUpdate = source.colorsNeedUpdate; - this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate; - this.groupsNeedUpdate = source.groupsNeedUpdate; - return this; + get priority() { + return this._priority; } - toBufferGeometry() { - const geometry = new DirectGeometry().fromGeometry(this); - const buffergeometry = new BufferGeometry(); - const positions = new Float32Array(geometry.vertices.length * 3); - buffergeometry.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices)); + set priority(priority) { + if (this._priority != priority) { + this._priority = priority; - if (geometry.normals.length > 0) { - const normals = new Float32Array(geometry.normals.length * 3); - buffergeometry.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals)); + this._onPriorityChange(priority); } + } - if (geometry.colors.length > 0) { - const colors = new Float32Array(geometry.colors.length * 3); - buffergeometry.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors)); - } + get() { + const node = getAnimated(this); + return node && node.getValue(); + } - if (geometry.uvs.length > 0) { - const uvs = new Float32Array(geometry.uvs.length * 2); - buffergeometry.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs)); - } + to(...args) { + return globals.to(this, args); + } - if (geometry.uvs2.length > 0) { - const uvs2 = new Float32Array(geometry.uvs2.length * 2); - buffergeometry.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2)); - } // groups + interpolate(...args) { + deprecateInterpolate(); + return globals.to(this, args); + } + toJSON() { + return this.get(); + } - buffergeometry.groups = geometry.groups; // morphs + observerAdded(count) { + if (count == 1) this._attach(); + } - for (let name in geometry.morphTargets) { - const array = []; - const morphTargets = geometry.morphTargets[name]; + observerRemoved(count) { + if (count == 0) this._detach(); + } - for (let i = 0, l = morphTargets.length; i < l; i++) { - const morphTarget = morphTargets[i]; - const attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3); - attribute.name = morphTarget.name; - array.push(attribute.copyVector3sArray(morphTarget.data)); - } + _attach() {} - buffergeometry.morphAttributes[name] = array; - } // skinning + _detach() {} + _onChange(value, idle = false) { + callFluidObservers(this, { + type: 'change', + parent: this, + value, + idle + }); + } - if (geometry.skinIndices.length > 0) { - const skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4); - buffergeometry.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices)); + _onPriorityChange(priority) { + if (!this.idle) { + frameLoop.sort(this); } - if (geometry.skinWeights.length > 0) { - const skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4); - buffergeometry.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights)); - } // - - - if (geometry.boundingSphere !== null) { - buffergeometry.boundingSphere = geometry.boundingSphere.clone(); - } + callFluidObservers(this, { + type: 'priority', + parent: this, + priority + }); + } - if (geometry.boundingBox !== null) { - buffergeometry.boundingBox = geometry.boundingBox.clone(); - } +} - return buffergeometry; - } +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - computeTangents() { - console.error('THREE.Geometry: .computeTangents() has been removed.'); + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; } - computeLineDistances() { - console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.'); - } + return target; +} - applyMatrix(matrix) { - console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().'); - return this.applyMatrix4(matrix); - } +const _excluded$3 = ["children"]; +const SpringContext = _ref => { + let { + children + } = _ref, + props = _objectWithoutPropertiesLoose(_ref, _excluded$3); - dispose() { - this.dispatchEvent({ - type: 'dispose' - }); - } + const inherited = useContext(ctx); + const pause = props.pause || !!inherited.pause, + immediate = props.immediate || !!inherited.immediate; + props = useMemoOne(() => ({ + pause, + immediate + }), [pause, immediate]); + const { + Provider + } = ctx; + return React.createElement(Provider, { + value: props + }, children); +}; +const ctx = makeContext(SpringContext, {}); +SpringContext.Provider = ctx.Provider; +SpringContext.Consumer = ctx.Consumer; +function makeContext(target, init) { + Object.assign(target, React.createContext(init)); + target.Provider._context = target; + target.Consumer._context = target; + return target; } -Geometry.createBufferGeometryFromObject = object => { - let buffergeometry = new BufferGeometry(); - const geometry = object.geometry; +let TransitionPhase; - if (object.isPoints || object.isLine) { - const positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3); - const colors = new Float32BufferAttribute(geometry.colors.length * 3, 3); - buffergeometry.setAttribute('position', positions.copyVector3sArray(geometry.vertices)); - buffergeometry.setAttribute('color', colors.copyColorsArray(geometry.colors)); +(function (TransitionPhase) { + TransitionPhase["MOUNT"] = "mount"; + TransitionPhase["ENTER"] = "enter"; + TransitionPhase["UPDATE"] = "update"; + TransitionPhase["LEAVE"] = "leave"; +})(TransitionPhase || (TransitionPhase = {})); - if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) { - const lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1); - buffergeometry.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances)); - } +class Interpolation extends FrameValue { + constructor(source, args) { + super(); + this.key = void 0; + this.idle = true; + this.calc = void 0; + this._active = new Set(); + this.source = source; + this.calc = createInterpolator(...args); - if (geometry.boundingSphere !== null) { - buffergeometry.boundingSphere = geometry.boundingSphere.clone(); - } + const value = this._get(); - if (geometry.boundingBox !== null) { - buffergeometry.boundingBox = geometry.boundingBox.clone(); - } - } else if (object.isMesh) { - buffergeometry = geometry.toBufferGeometry(); + const nodeType = getAnimatedType(value); + setAnimated(this, nodeType.create(value)); } - return buffergeometry; -}; + advance(_dt) { + const value = this._get(); -class DirectGeometry { - constructor() { - this.vertices = []; - this.normals = []; - this.colors = []; - this.uvs = []; - this.uvs2 = []; - this.groups = []; - this.morphTargets = {}; - this.skinWeights = []; - this.skinIndices = []; // this.lineDistances = []; - - this.boundingBox = null; - this.boundingSphere = null; // update flags - - this.verticesNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.groupsNeedUpdate = false; - } - - computeGroups(geometry) { - const groups = []; - let group, i; - let materialIndex = undefined; - const faces = geometry.faces; - - for (i = 0; i < faces.length; i++) { - const face = faces[i]; // materials - - if (face.materialIndex !== materialIndex) { - materialIndex = face.materialIndex; - - if (group !== undefined) { - group.count = i * 3 - group.start; - groups.push(group); - } + const oldValue = this.get(); - group = { - start: i * 3, - materialIndex - }; - } - } + if (!isEqual(value, oldValue)) { + getAnimated(this).setValue(value); - if (group !== undefined) { - group.count = i * 3 - group.start; - groups.push(group); + this._onChange(value, this.idle); } - this.groups = groups; + if (!this.idle && checkIdle(this._active)) { + becomeIdle(this); + } } - fromGeometry(geometry) { - const faces = geometry.faces; - const vertices = geometry.vertices; - const faceVertexUvs = geometry.faceVertexUvs; - const hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0; - const hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs - - const morphTargets = geometry.morphTargets; - const morphTargetsLength = morphTargets.length; - let morphTargetsPosition; + _get() { + const inputs = is.arr(this.source) ? this.source.map(getFluidValue) : toArray(getFluidValue(this.source)); + return this.calc(...inputs); + } - if (morphTargetsLength > 0) { - morphTargetsPosition = []; + _start() { + if (this.idle && !checkIdle(this._active)) { + this.idle = false; + each(getPayload(this), node => { + node.done = false; + }); - for (let i = 0; i < morphTargetsLength; i++) { - morphTargetsPosition[i] = { - name: morphTargets[i].name, - data: [] - }; + if (globals.skipAnimation) { + raf.batchedUpdates(() => this.advance()); + becomeIdle(this); + } else { + frameLoop.start(this); } - - this.morphTargets.position = morphTargetsPosition; } + } - const morphNormals = geometry.morphNormals; - const morphNormalsLength = morphNormals.length; - let morphTargetsNormal; + _attach() { + let priority = 1; + each(toArray(this.source), source => { + if (hasFluidValue(source)) { + addFluidObserver(source, this); + } - if (morphNormalsLength > 0) { - morphTargetsNormal = []; + if (isFrameValue(source)) { + if (!source.idle) { + this._active.add(source); + } - for (let i = 0; i < morphNormalsLength; i++) { - morphTargetsNormal[i] = { - name: morphNormals[i].name, - data: [] - }; + priority = Math.max(priority, source.priority + 1); } + }); + this.priority = priority; - this.morphTargets.normal = morphTargetsNormal; - } // skins - + this._start(); + } - const skinIndices = geometry.skinIndices; - const skinWeights = geometry.skinWeights; - const hasSkinIndices = skinIndices.length === vertices.length; - const hasSkinWeights = skinWeights.length === vertices.length; // + _detach() { + each(toArray(this.source), source => { + if (hasFluidValue(source)) { + removeFluidObserver(source, this); + } + }); - if (vertices.length > 0 && faces.length === 0) { - console.error('THREE.DirectGeometry: Faceless geometries are not supported.'); - } + this._active.clear(); - for (let i = 0; i < faces.length; i++) { - const face = faces[i]; - this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]); - const vertexNormals = face.vertexNormals; + becomeIdle(this); + } - if (vertexNormals.length === 3) { - this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]); + eventObserved(event) { + if (event.type == 'change') { + if (event.idle) { + this.advance(); } else { - const normal = face.normal; - this.normals.push(normal, normal, normal); + this._active.add(event.parent); + + this._start(); } + } else if (event.type == 'idle') { + this._active.delete(event.parent); + } else if (event.type == 'priority') { + this.priority = toArray(this.source).reduce((highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1), 0); + } + } - const vertexColors = face.vertexColors; +} - if (vertexColors.length === 3) { - this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]); - } else { - const color = face.color; - this.colors.push(color, color, color); - } +function isIdle(source) { + return source.idle !== false; +} - if (hasFaceVertexUv === true) { - const vertexUvs = faceVertexUvs[0][i]; +function checkIdle(active) { + return !active.size || Array.from(active).every(isIdle); +} - if (vertexUvs !== undefined) { - this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]); - } else { - console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i); - this.uvs.push(new Vector2(), new Vector2(), new Vector2()); - } - } +function becomeIdle(self) { + if (!self.idle) { + self.idle = true; + each(getPayload(self), node => { + node.done = true; + }); + callFluidObservers(self, { + type: 'idle', + parent: self + }); + } +} - if (hasFaceVertexUv2 === true) { - const vertexUvs = faceVertexUvs[1][i]; +globals.assign({ + createStringInterpolator, + to: (source, args) => new Interpolation(source, args) +}); - if (vertexUvs !== undefined) { - this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]); - } else { - console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i); - this.uvs2.push(new Vector2(), new Vector2(), new Vector2()); - } - } // morphs +const primitives = ['primitive'].concat(Object.keys(THREE).filter(key => /^[A-Z]/.test(key)).map(key => key[0].toLowerCase() + key.slice(1))); + +globals.assign({ + createStringInterpolator, + colors, + frameLoop: 'demand' +}); +addEffect(() => { + raf.advance(); +}); +createHost(primitives, { + applyAnimatedValues: applyProps +}); +const V = { + toVector(v, fallback) { + if (v === undefined) v = fallback; + return Array.isArray(v) ? v : [v, v]; + }, - for (let j = 0; j < morphTargetsLength; j++) { - const morphTarget = morphTargets[j].vertices; - morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]); - } + add(v1, v2) { + return [v1[0] + v2[0], v1[1] + v2[1]]; + }, - for (let j = 0; j < morphNormalsLength; j++) { - const morphNormal = morphNormals[j].vertexNormals[i]; - morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c); - } // skins + sub(v1, v2) { + return [v1[0] - v2[0], v1[1] - v2[1]]; + }, + addTo(v1, v2) { + v1[0] += v2[0]; + v1[1] += v2[1]; + }, - if (hasSkinIndices) { - this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]); - } + subTo(v1, v2) { + v1[0] -= v2[0]; + v1[1] -= v2[1]; + } - if (hasSkinWeights) { - this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]); - } - } +}; - this.computeGroups(geometry); - this.verticesNeedUpdate = geometry.verticesNeedUpdate; - this.normalsNeedUpdate = geometry.normalsNeedUpdate; - this.colorsNeedUpdate = geometry.colorsNeedUpdate; - this.uvsNeedUpdate = geometry.uvsNeedUpdate; - this.groupsNeedUpdate = geometry.groupsNeedUpdate; +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } - if (geometry.boundingSphere !== null) { - this.boundingSphere = geometry.boundingSphere.clone(); - } + return obj; +} - if (geometry.boundingBox !== null) { - this.boundingBox = geometry.boundingBox.clone(); - } +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - return this; + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); } + return keys; } -class Face3 { - constructor(a, b, c, normal, color, materialIndex = 0) { - this.a = a; - this.b = b; - this.c = c; - this.normal = normal && normal.isVector3 ? normal : new Vector3(); - this.vertexNormals = Array.isArray(normal) ? normal : []; - this.color = color && color.isColor ? color : new Color(); - this.vertexColors = Array.isArray(color) ? color : []; - this.materialIndex = materialIndex; +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - clone() { - return new this.constructor().copy(this); + return target; +} + +function call(v, ...args) { + if (typeof v === 'function') { + return v(...args); + } else { + return v; } +} +function assignDefault(value, fallback) { + return Object.assign({}, fallback, value || {}); +} - copy(source) { - this.a = source.a; - this.b = source.b; - this.c = source.c; - this.normal.copy(source.normal); - this.color.copy(source.color); - this.materialIndex = source.materialIndex; +const identity = v => v; +const DEFAULT_RUBBERBAND = 0.15; +const commonConfigResolver = { + enabled(value = true) { + return value; + }, - for (let i = 0, il = source.vertexNormals.length; i < il; i++) { - this.vertexNormals[i] = source.vertexNormals[i].clone(); - } + eventOptions(value, _k, config) { + return _objectSpread2(_objectSpread2({}, config.shared.eventOptions), value); + }, - for (let i = 0, il = source.vertexColors.length; i < il; i++) { - this.vertexColors[i] = source.vertexColors[i].clone(); - } + preventDefault(value = false) { + return value; + }, - return this; - } + triggerAllEvents(value = false) { + return value; + }, -} + rubberband(value = 0) { + switch (value) { + case true: + return [DEFAULT_RUBBERBAND, DEFAULT_RUBBERBAND]; -class NodeMaterial extends ShaderMaterial { - constructor() { - super(); - this.type = this.constructor.name; - this.lights = true; - } + case false: + return [0, 0]; - setDefaultValues(values) { - // This approach is to reuse the native refreshUniforms* - // and turn available the use of features like transmission and environment in core - let value; + default: + return V.toVector(value); + } + }, - for (const property in values) { - value = values[property]; + from(value) { + if (typeof value === 'function') return value; + if (value != null) return V.toVector(value); + }, - if (this[property] === undefined) { - if (value && typeof value.clone === 'function') { - this[property] = value.clone(); - } else { - this[property] = value; - } - } - } + transform(value, _k, config) { + const transform = value || config.shared.transform; + this.hasCustomTransform = !!transform; - Object.assign(this.defines, values.defines); - } + if (process.env.NODE_ENV === 'development') { + const originalTransform = transform || identity; + return v => { + const r = originalTransform(v); - toJSON(meta) { - const isRoot = meta === undefined || typeof meta === 'string'; + if (!isFinite(r[0]) || !isFinite(r[1])) { + console.warn(`[@use-gesture]: config.transform() must produce a valid result, but it was: [${r[0]},${[1]}]`); + } - if (isRoot) { - meta = { - textures: {}, - images: {}, - nodes: {} + return r; }; } - const data = Material.prototype.toJSON.call(this, meta); - const nodeKeys = getNodesKeys(this); - data.inputNodes = {}; + return transform || identity; + }, + + threshold(value) { + return V.toVector(value, 0); + } - for (const name of nodeKeys) { - data.inputNodes[name] = this[name].toJSON(meta).uuid; - } // TODO: Copied from Object3D.toJSON +}; +if (process.env.NODE_ENV === 'development') { + Object.assign(commonConfigResolver, { + domTarget(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`); + } - function extractFromCache(cache) { - const values = []; + return NaN; + }, - for (const key in cache) { - const data = cache[key]; - delete data.metadata; - values.push(data); + lockDirection(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`lockDirection\` option has been merged with \`axis\`. Use it as in \`{ axis: 'lock' }\``); } - return values; - } + return NaN; + }, - if (isRoot) { - const textures = extractFromCache(meta.textures); - const images = extractFromCache(meta.images); - const nodes = extractFromCache(meta.nodes); - if (textures.length > 0) data.textures = textures; - if (images.length > 0) data.images = images; - if (nodes.length > 0) data.nodes = nodes; - } + initial(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`initial\` option has been renamed to \`from\`.`); + } - return data; - } + return NaN; + } + }); } -NodeMaterial.prototype.isNodeMaterial = true; +const DEFAULT_AXIS_THRESHOLD = 0; +const coordinatesConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { + axis(_v, _k, { + axis + }) { + this.lockDirection = axis === 'lock'; + if (!this.lockDirection) return axis; + }, -const defaultValues$3 = new LineBasicMaterial(); + axisThreshold(value = DEFAULT_AXIS_THRESHOLD) { + return value; + }, -class LineBasicNodeMaterial extends NodeMaterial { - constructor(parameters) { - super(); - this.colorNode = null; - this.opacityNode = null; - this.alphaTestNode = null; - this.lightNode = null; - this.positionNode = null; - this.setDefaultValues(defaultValues$3); - this.setValues(parameters); - } + bounds(value = {}) { + if (typeof value === 'function') { + return state => coordinatesConfigResolver.bounds(value(state)); + } - copy(source) { - this.colorNode = source.colorNode; - this.opacityNode = source.opacityNode; - this.alphaTestNode = source.alphaTestNode; - this.lightNode = source.lightNode; - this.positionNode = source.positionNode; - return super.copy(source); - } + if ('current' in value) { + return () => value.current; + } -} + if (typeof HTMLElement === 'function' && value instanceof HTMLElement) { + return value; + } -LineBasicNodeMaterial.prototype.isLineBasicNodeMaterial = true; + const { + left = -Infinity, + right = Infinity, + top = -Infinity, + bottom = Infinity + } = value; + return [[left, right], [top, bottom]]; + } -const defaultValues$2 = new MeshBasicMaterial(); +}); -class MeshBasicNodeMaterial extends NodeMaterial { - constructor(parameters) { - super(); - this.lights = true; - this.colorNode = null; - this.opacityNode = null; - this.alphaTestNode = null; - this.lightNode = null; - this.positionNode = null; - this.setDefaultValues(defaultValues$2); - this.setValues(parameters); - } +const isBrowser = typeof window !== 'undefined' && window.document && window.document.createElement; - copy(source) { - this.colorNode = source.colorNode; - this.opacityNode = source.opacityNode; - this.alphaTestNode = source.alphaTestNode; - this.lightNode = source.lightNode; - this.positionNode = source.positionNode; - return super.copy(source); - } +function supportsTouchEvents() { + return isBrowser && 'ontouchstart' in window; +} +function isTouchScreen() { + return supportsTouchEvents() || isBrowser && window.navigator.maxTouchPoints > 1; } -MeshBasicNodeMaterial.prototype.isMeshBasicNodeMaterial = true; +function supportsPointerEvents() { + return isBrowser && 'onpointerdown' in window; +} -const defaultValues$1 = new MeshStandardMaterial(); -class MeshStandardNodeMaterial extends NodeMaterial { - constructor(parameters) { - super(); - this.colorNode = null; - this.opacityNode = null; - this.alphaTestNode = null; - this.normalNode = null; - this.emissiveNode = null; - this.metalnessNode = null; - this.roughnessNode = null; - this.clearcoatNode = null; - this.clearcoatRoughnessNode = null; - this.envNode = null; - this.lightNode = null; - this.positionNode = null; - this.setDefaultValues(defaultValues$1); - this.setValues(parameters); - } +function supportsPointerLock() { + return isBrowser && 'exitPointerLock' in window.document; +} - copy(source) { - this.colorNode = source.colorNode; - this.opacityNode = source.opacityNode; - this.alphaTestNode = source.alphaTestNode; - this.normalNode = source.normalNode; - this.emissiveNode = source.emissiveNode; - this.metalnessNode = source.metalnessNode; - this.roughnessNode = source.roughnessNode; - this.clearcoatNode = source.clearcoatNode; - this.clearcoatRoughnessNode = source.clearcoatRoughnessNode; - this.envNode = source.envNode; - this.lightNode = source.lightNode; - this.positionNode = source.positionNode; - return super.copy(source); +function supportsGestureEvents() { + try { + return 'constructor' in GestureEvent; + } catch (e) { + return false; } - } -MeshStandardNodeMaterial.prototype.isMeshStandardNodeMaterial = true; - -const defaultValues = new PointsMaterial(); -class PointsNodeMaterial extends NodeMaterial { - constructor(parameters) { - super(); - this.transparent = true; - this.colorNode = null; - this.opacityNode = null; - this.alphaTestNode = null; - this.lightNode = null; - this.sizeNode = null; - this.positionNode = null; - this.setDefaultValues(defaultValues); - this.setValues(parameters); - } +const SUPPORT = { + isBrowser, + gesture: supportsGestureEvents(), + touch: isTouchScreen(), + touchscreen: isTouchScreen(), + pointer: supportsPointerEvents(), + pointerLock: supportsPointerLock() +}; - copy(source) { - this.colorNode = source.colorNode; - this.opacityNode = source.opacityNode; - this.alphaTestNode = source.alphaTestNode; - this.lightNode = source.lightNode; - this.sizeNode = source.sizeNode; - this.positionNode = source.positionNode; - return super.copy(source); - } +const DEFAULT_PREVENT_SCROLL_DELAY = 250; +const DEFAULT_DRAG_DELAY = 180; +const DEFAULT_SWIPE_VELOCITY = 0.5; +const DEFAULT_SWIPE_DISTANCE = 50; +const DEFAULT_SWIPE_DURATION = 250; +const DEFAULT_DRAG_AXIS_THRESHOLD = { + mouse: 0, + touch: 0, + pen: 8 +}; +const dragConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { + device(_v, _k, { + pointer: { + touch = false, + lock = false, + mouse = false + } = {} + }) { + this.pointerLock = lock && SUPPORT.pointerLock; + if (SUPPORT.touch && touch) return 'touch'; + if (this.pointerLock) return 'mouse'; + if (SUPPORT.pointer && !mouse) return 'pointer'; + if (SUPPORT.touch) return 'touch'; + return 'mouse'; + }, -} + preventScrollAxis(value, _k, { + preventScroll + }) { + this.preventScrollDelay = typeof preventScroll === 'number' ? preventScroll : preventScroll || preventScroll === undefined && value ? DEFAULT_PREVENT_SCROLL_DELAY : undefined; + if (!SUPPORT.touchscreen || preventScroll === false) return undefined; + return value ? value : preventScroll !== undefined ? 'y' : undefined; + }, -PointsNodeMaterial.prototype.isPointsNodeMaterial = true; + pointerCapture(_v, _k, { + pointer: { + capture = true, + buttons = 1 + } = {} + }) { + this.pointerButtons = buttons; + return !this.pointerLock && this.device === 'pointer' && capture; + }, -/** - * Color correction - */ + threshold(value, _k, { + filterTaps = false, + tapsThreshold = 3, + axis = undefined + }) { + const threshold = V.toVector(value, filterTaps ? tapsThreshold : axis ? 1 : 0); + this.filterTaps = filterTaps; + this.tapsThreshold = tapsThreshold; + return threshold; + }, -({ - uniforms: { - tDiffuse: { - value: null - }, - powRGB: { - value: new Vector3(2, 2, 2) - }, - mulRGB: { - value: new Vector3(1, 1, 1) - }, - addRGB: { - value: new Vector3(0, 0, 0) - } + swipe({ + velocity = DEFAULT_SWIPE_VELOCITY, + distance = DEFAULT_SWIPE_DISTANCE, + duration = DEFAULT_SWIPE_DURATION + } = {}) { + return { + velocity: this.transform(V.toVector(velocity)), + distance: this.transform(V.toVector(distance)), + duration + }; }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform vec3 powRGB;', 'uniform vec3 mulRGB;', 'uniform vec3 addRGB;', 'varying vec2 vUv;', 'void main() {', ' gl_FragColor = texture2D( tDiffuse, vUv );', ' gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB );', '}'].join('\n') -}); -/** - * Colorify shader - */ + delay(value = 0) { + switch (value) { + case true: + return DEFAULT_DRAG_DELAY; -({ - uniforms: { - tDiffuse: { - value: null - }, - color: { - value: new Color(0xffffff) + case false: + return 0; + + default: + return value; } }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform vec3 color;', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' vec3 luma = vec3( 0.299, 0.587, 0.114 );', ' float v = dot( texel.xyz, luma );', ' gl_FragColor = vec4( v * color, texel.w );', '}'].join('\n') -}); -/** - * NVIDIA FXAA by Timothy Lottes - * http://timothylottes.blogspot.com/2011/06/fxaa3-source-released.html - * - WebGL port by @supereggbert - * http://www.glge.org/demos/fxaa/ - */ + axisThreshold(value) { + if (!value) return DEFAULT_DRAG_AXIS_THRESHOLD; + return _objectSpread2(_objectSpread2({}, DEFAULT_DRAG_AXIS_THRESHOLD), value); + } -({ - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2(1 / 1024, 1 / 512) - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['precision highp float;', '', 'uniform sampler2D tDiffuse;', '', 'uniform vec2 resolution;', '', 'varying vec2 vUv;', '', '// FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)', '', '//----------------------------------------------------------------------------------', '// File: es3-keplerFXAAassetsshaders/FXAA_DefaultES.frag', '// SDK Version: v3.00', '// Email: gameworks@nvidia.com', '// Site: http://developer.nvidia.com/', '//', '// Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.', '//', '// Redistribution and use in source and binary forms, with or without', '// modification, are permitted provided that the following conditions', '// are met:', '// * Redistributions of source code must retain the above copyright', '// notice, this list of conditions and the following disclaimer.', '// * Redistributions in binary form must reproduce the above copyright', '// notice, this list of conditions and the following disclaimer in the', '// documentation and/or other materials provided with the distribution.', '// * Neither the name of NVIDIA CORPORATION nor the names of its', '// contributors may be used to endorse or promote products derived', '// from this software without specific prior written permission.', '//', "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY", '// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE', '// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR', '// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR', '// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,', '// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,', '// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR', '// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY', '// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT', '// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE', '// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.', '//', '//----------------------------------------------------------------------------------', '', '#define FXAA_PC 1', '#define FXAA_GLSL_100 1', '#define FXAA_QUALITY_PRESET 12', '', '#define FXAA_GREEN_AS_LUMA 1', '', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_PC_CONSOLE', ' //', ' // The console algorithm for PC is included', ' // for developers targeting really low spec machines.', ' // Likely better to just run FXAA_PC, and use a really low preset.', ' //', ' #define FXAA_PC_CONSOLE 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_GLSL_120', ' #define FXAA_GLSL_120 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_GLSL_130', ' #define FXAA_GLSL_130 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_HLSL_3', ' #define FXAA_HLSL_3 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_HLSL_4', ' #define FXAA_HLSL_4 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_HLSL_5', ' #define FXAA_HLSL_5 0', '#endif', '/*==========================================================================*/', '#ifndef FXAA_GREEN_AS_LUMA', ' //', ' // For those using non-linear color,', ' // and either not able to get luma in alpha, or not wanting to,', ' // this enables FXAA to run using green as a proxy for luma.', ' // So with this enabled, no need to pack luma in alpha.', ' //', ' // This will turn off AA on anything which lacks some amount of green.', ' // Pure red and blue or combination of only R and B, will get no AA.', ' //', ' // Might want to lower the settings for both,', ' // fxaaConsoleEdgeThresholdMin', ' // fxaaQualityEdgeThresholdMin', ' // In order to insure AA does not get turned off on colors', ' // which contain a minor amount of green.', ' //', ' // 1 = On.', ' // 0 = Off.', ' //', ' #define FXAA_GREEN_AS_LUMA 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_EARLY_EXIT', ' //', " // Controls algorithm's early exit path.", ' // On PS3 turning this ON adds 2 cycles to the shader.', ' // On 360 turning this OFF adds 10ths of a millisecond to the shader.', ' // Turning this off on console will result in a more blurry image.', ' // So this defaults to on.', ' //', ' // 1 = On.', ' // 0 = Off.', ' //', ' #define FXAA_EARLY_EXIT 1', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_DISCARD', ' //', ' // Only valid for PC OpenGL currently.', ' // Probably will not work when FXAA_GREEN_AS_LUMA = 1.', ' //', " // 1 = Use discard on pixels which don't need AA.", ' // For APIs which enable concurrent TEX+ROP from same surface.', " // 0 = Return unchanged color on pixels which don't need AA.", ' //', ' #define FXAA_DISCARD 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_FAST_PIXEL_OFFSET', ' //', ' // Used for GLSL 120 only.', ' //', ' // 1 = GL API supports fast pixel offsets', ' // 0 = do not use fast pixel offsets', ' //', ' #ifdef GL_EXT_gpu_shader4', ' #define FXAA_FAST_PIXEL_OFFSET 1', ' #endif', ' #ifdef GL_NV_gpu_shader5', ' #define FXAA_FAST_PIXEL_OFFSET 1', ' #endif', ' #ifdef GL_ARB_gpu_shader5', ' #define FXAA_FAST_PIXEL_OFFSET 1', ' #endif', ' #ifndef FXAA_FAST_PIXEL_OFFSET', ' #define FXAA_FAST_PIXEL_OFFSET 0', ' #endif', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_GATHER4_ALPHA', ' //', ' // 1 = API supports gather4 on alpha channel.', ' // 0 = API does not support gather4 on alpha channel.', ' //', ' #if (FXAA_HLSL_5 == 1)', ' #define FXAA_GATHER4_ALPHA 1', ' #endif', ' #ifdef GL_ARB_gpu_shader5', ' #define FXAA_GATHER4_ALPHA 1', ' #endif', ' #ifdef GL_NV_gpu_shader5', ' #define FXAA_GATHER4_ALPHA 1', ' #endif', ' #ifndef FXAA_GATHER4_ALPHA', ' #define FXAA_GATHER4_ALPHA 0', ' #endif', '#endif', '', '', '/*============================================================================', ' FXAA QUALITY - TUNING KNOBS', '------------------------------------------------------------------------------', 'NOTE the other tuning knobs are now in the shader function inputs!', '============================================================================*/', '#ifndef FXAA_QUALITY_PRESET', ' //', ' // Choose the quality preset.', ' // This needs to be compiled into the shader as it effects code.', ' // Best option to include multiple presets is to', ' // in each shader define the preset, then include this file.', ' //', ' // OPTIONS', ' // -----------------------------------------------------------------------', ' // 10 to 15 - default medium dither (10=fastest, 15=highest quality)', ' // 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality)', ' // 39 - no dither, very expensive', ' //', ' // NOTES', ' // -----------------------------------------------------------------------', ' // 12 = slightly faster then FXAA 3.9 and higher edge quality (default)', ' // 13 = about same speed as FXAA 3.9 and better than 12', ' // 23 = closest to FXAA 3.9 visually and performance wise', ' // _ = the lowest digit is directly related to performance', ' // _ = the highest digit is directly related to style', ' //', ' #define FXAA_QUALITY_PRESET 12', '#endif', '', '', '/*============================================================================', '', ' FXAA QUALITY - PRESETS', '', '============================================================================*/', '', '/*============================================================================', ' FXAA QUALITY - MEDIUM DITHER PRESETS', '============================================================================*/', '#if (FXAA_QUALITY_PRESET == 10)', ' #define FXAA_QUALITY_PS 3', ' #define FXAA_QUALITY_P0 1.5', ' #define FXAA_QUALITY_P1 3.0', ' #define FXAA_QUALITY_P2 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 11)', ' #define FXAA_QUALITY_PS 4', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 3.0', ' #define FXAA_QUALITY_P3 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 12)', ' #define FXAA_QUALITY_PS 5', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 4.0', ' #define FXAA_QUALITY_P4 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 13)', ' #define FXAA_QUALITY_PS 6', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 4.0', ' #define FXAA_QUALITY_P5 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 14)', ' #define FXAA_QUALITY_PS 7', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 4.0', ' #define FXAA_QUALITY_P6 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 15)', ' #define FXAA_QUALITY_PS 8', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 4.0', ' #define FXAA_QUALITY_P7 12.0', '#endif', '', '/*============================================================================', ' FXAA QUALITY - LOW DITHER PRESETS', '============================================================================*/', '#if (FXAA_QUALITY_PRESET == 20)', ' #define FXAA_QUALITY_PS 3', ' #define FXAA_QUALITY_P0 1.5', ' #define FXAA_QUALITY_P1 2.0', ' #define FXAA_QUALITY_P2 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 21)', ' #define FXAA_QUALITY_PS 4', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 22)', ' #define FXAA_QUALITY_PS 5', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 23)', ' #define FXAA_QUALITY_PS 6', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 24)', ' #define FXAA_QUALITY_PS 7', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 3.0', ' #define FXAA_QUALITY_P6 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 25)', ' #define FXAA_QUALITY_PS 8', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 4.0', ' #define FXAA_QUALITY_P7 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 26)', ' #define FXAA_QUALITY_PS 9', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 4.0', ' #define FXAA_QUALITY_P8 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 27)', ' #define FXAA_QUALITY_PS 10', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 2.0', ' #define FXAA_QUALITY_P8 4.0', ' #define FXAA_QUALITY_P9 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 28)', ' #define FXAA_QUALITY_PS 11', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 2.0', ' #define FXAA_QUALITY_P8 2.0', ' #define FXAA_QUALITY_P9 4.0', ' #define FXAA_QUALITY_P10 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 29)', ' #define FXAA_QUALITY_PS 12', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 2.0', ' #define FXAA_QUALITY_P8 2.0', ' #define FXAA_QUALITY_P9 2.0', ' #define FXAA_QUALITY_P10 4.0', ' #define FXAA_QUALITY_P11 8.0', '#endif', '', '/*============================================================================', ' FXAA QUALITY - EXTREME QUALITY', '============================================================================*/', '#if (FXAA_QUALITY_PRESET == 39)', ' #define FXAA_QUALITY_PS 12', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.0', ' #define FXAA_QUALITY_P2 1.0', ' #define FXAA_QUALITY_P3 1.0', ' #define FXAA_QUALITY_P4 1.0', ' #define FXAA_QUALITY_P5 1.5', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 2.0', ' #define FXAA_QUALITY_P8 2.0', ' #define FXAA_QUALITY_P9 2.0', ' #define FXAA_QUALITY_P10 4.0', ' #define FXAA_QUALITY_P11 8.0', '#endif', '', '', '', '/*============================================================================', '', ' API PORTING', '', '============================================================================*/', '#if (FXAA_GLSL_100 == 1) || (FXAA_GLSL_120 == 1) || (FXAA_GLSL_130 == 1)', ' #define FxaaBool bool', ' #define FxaaDiscard discard', ' #define FxaaFloat float', ' #define FxaaFloat2 vec2', ' #define FxaaFloat3 vec3', ' #define FxaaFloat4 vec4', ' #define FxaaHalf float', ' #define FxaaHalf2 vec2', ' #define FxaaHalf3 vec3', ' #define FxaaHalf4 vec4', ' #define FxaaInt2 ivec2', ' #define FxaaSat(x) clamp(x, 0.0, 1.0)', ' #define FxaaTex sampler2D', '#else', ' #define FxaaBool bool', ' #define FxaaDiscard clip(-1)', ' #define FxaaFloat float', ' #define FxaaFloat2 float2', ' #define FxaaFloat3 float3', ' #define FxaaFloat4 float4', ' #define FxaaHalf half', ' #define FxaaHalf2 half2', ' #define FxaaHalf3 half3', ' #define FxaaHalf4 half4', ' #define FxaaSat(x) saturate(x)', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_GLSL_100 == 1)', ' #define FxaaTexTop(t, p) texture2D(t, p, 0.0)', ' #define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r), 0.0)', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_GLSL_120 == 1)', ' // Requires,', ' // #version 120', ' // And at least,', ' // #extension GL_EXT_gpu_shader4 : enable', ' // (or set FXAA_FAST_PIXEL_OFFSET 1 to work like DX9)', ' #define FxaaTexTop(t, p) texture2DLod(t, p, 0.0)', ' #if (FXAA_FAST_PIXEL_OFFSET == 1)', ' #define FxaaTexOff(t, p, o, r) texture2DLodOffset(t, p, 0.0, o)', ' #else', ' #define FxaaTexOff(t, p, o, r) texture2DLod(t, p + (o * r), 0.0)', ' #endif', ' #if (FXAA_GATHER4_ALPHA == 1)', ' // use #extension GL_ARB_gpu_shader5 : enable', ' #define FxaaTexAlpha4(t, p) textureGather(t, p, 3)', ' #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)', ' #define FxaaTexGreen4(t, p) textureGather(t, p, 1)', ' #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)', ' #endif', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_GLSL_130 == 1)', ' // Requires "#version 130" or better', ' #define FxaaTexTop(t, p) textureLod(t, p, 0.0)', ' #define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o)', ' #if (FXAA_GATHER4_ALPHA == 1)', ' // use #extension GL_ARB_gpu_shader5 : enable', ' #define FxaaTexAlpha4(t, p) textureGather(t, p, 3)', ' #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)', ' #define FxaaTexGreen4(t, p) textureGather(t, p, 1)', ' #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)', ' #endif', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_HLSL_3 == 1)', ' #define FxaaInt2 float2', ' #define FxaaTex sampler2D', ' #define FxaaTexTop(t, p) tex2Dlod(t, float4(p, 0.0, 0.0))', ' #define FxaaTexOff(t, p, o, r) tex2Dlod(t, float4(p + (o * r), 0, 0))', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_HLSL_4 == 1)', ' #define FxaaInt2 int2', ' struct FxaaTex { SamplerState smpl; Texture2D tex; };', ' #define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0)', ' #define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o)', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_HLSL_5 == 1)', ' #define FxaaInt2 int2', ' struct FxaaTex { SamplerState smpl; Texture2D tex; };', ' #define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0)', ' #define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o)', ' #define FxaaTexAlpha4(t, p) t.tex.GatherAlpha(t.smpl, p)', ' #define FxaaTexOffAlpha4(t, p, o) t.tex.GatherAlpha(t.smpl, p, o)', ' #define FxaaTexGreen4(t, p) t.tex.GatherGreen(t.smpl, p)', ' #define FxaaTexOffGreen4(t, p, o) t.tex.GatherGreen(t.smpl, p, o)', '#endif', '', '', '/*============================================================================', ' GREEN AS LUMA OPTION SUPPORT FUNCTION', '============================================================================*/', '#if (FXAA_GREEN_AS_LUMA == 0)', ' FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.w; }', '#else', ' FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; }', '#endif', '', '', '', '', '/*============================================================================', '', ' FXAA3 QUALITY - PC', '', '============================================================================*/', '#if (FXAA_PC == 1)', '/*--------------------------------------------------------------------------*/', 'FxaaFloat4 FxaaPixelShader(', ' //', ' // Use noperspective interpolation here (turn off perspective interpolation).', ' // {xy} = center of pixel', ' FxaaFloat2 pos,', ' //', ' // Used only for FXAA Console, and not used on the 360 version.', ' // Use noperspective interpolation here (turn off perspective interpolation).', ' // {xy_} = upper left of pixel', ' // {_zw} = lower right of pixel', ' FxaaFloat4 fxaaConsolePosPos,', ' //', ' // Input color texture.', ' // {rgb_} = color in linear or perceptual color space', ' // if (FXAA_GREEN_AS_LUMA == 0)', ' // {__a} = luma in perceptual color space (not linear)', ' FxaaTex tex,', ' //', ' // Only used on the optimized 360 version of FXAA Console.', ' // For everything but 360, just use the same input here as for "tex".', ' // For 360, same texture, just alias with a 2nd sampler.', ' // This sampler needs to have an exponent bias of -1.', ' FxaaTex fxaaConsole360TexExpBiasNegOne,', ' //', ' // Only used on the optimized 360 version of FXAA Console.', ' // For everything but 360, just use the same input here as for "tex".', ' // For 360, same texture, just alias with a 3nd sampler.', ' // This sampler needs to have an exponent bias of -2.', ' FxaaTex fxaaConsole360TexExpBiasNegTwo,', ' //', ' // Only used on FXAA Quality.', ' // This must be from a constant/uniform.', ' // {x_} = 1.0/screenWidthInPixels', ' // {_y} = 1.0/screenHeightInPixels', ' FxaaFloat2 fxaaQualityRcpFrame,', ' //', ' // Only used on FXAA Console.', ' // This must be from a constant/uniform.', ' // This effects sub-pixel AA quality and inversely sharpness.', ' // Where N ranges between,', ' // N = 0.50 (default)', ' // N = 0.33 (sharper)', ' // {x__} = -N/screenWidthInPixels', ' // {_y_} = -N/screenHeightInPixels', ' // {_z_} = N/screenWidthInPixels', ' // {__w} = N/screenHeightInPixels', ' FxaaFloat4 fxaaConsoleRcpFrameOpt,', ' //', ' // Only used on FXAA Console.', ' // Not used on 360, but used on PS3 and PC.', ' // This must be from a constant/uniform.', ' // {x__} = -2.0/screenWidthInPixels', ' // {_y_} = -2.0/screenHeightInPixels', ' // {_z_} = 2.0/screenWidthInPixels', ' // {__w} = 2.0/screenHeightInPixels', ' FxaaFloat4 fxaaConsoleRcpFrameOpt2,', ' //', ' // Only used on FXAA Console.', ' // Only used on 360 in place of fxaaConsoleRcpFrameOpt2.', ' // This must be from a constant/uniform.', ' // {x__} = 8.0/screenWidthInPixels', ' // {_y_} = 8.0/screenHeightInPixels', ' // {_z_} = -4.0/screenWidthInPixels', ' // {__w} = -4.0/screenHeightInPixels', ' FxaaFloat4 fxaaConsole360RcpFrameOpt2,', ' //', ' // Only used on FXAA Quality.', ' // This used to be the FXAA_QUALITY_SUBPIX define.', ' // It is here now to allow easier tuning.', ' // Choose the amount of sub-pixel aliasing removal.', ' // This can effect sharpness.', ' // 1.00 - upper limit (softer)', ' // 0.75 - default amount of filtering', ' // 0.50 - lower limit (sharper, less sub-pixel aliasing removal)', ' // 0.25 - almost off', ' // 0.00 - completely off', ' FxaaFloat fxaaQualitySubpix,', ' //', ' // Only used on FXAA Quality.', ' // This used to be the FXAA_QUALITY_EDGE_THRESHOLD define.', ' // It is here now to allow easier tuning.', ' // The minimum amount of local contrast required to apply algorithm.', ' // 0.333 - too little (faster)', ' // 0.250 - low quality', ' // 0.166 - default', ' // 0.125 - high quality', ' // 0.063 - overkill (slower)', ' FxaaFloat fxaaQualityEdgeThreshold,', ' //', ' // Only used on FXAA Quality.', ' // This used to be the FXAA_QUALITY_EDGE_THRESHOLD_MIN define.', ' // It is here now to allow easier tuning.', ' // Trims the algorithm from processing darks.', ' // 0.0833 - upper limit (default, the start of visible unfiltered edges)', ' // 0.0625 - high quality (faster)', ' // 0.0312 - visible limit (slower)', ' // Special notes when using FXAA_GREEN_AS_LUMA,', ' // Likely want to set this to zero.', ' // As colors that are mostly not-green', ' // will appear very dark in the green channel!', ' // Tune by looking at mostly non-green content,', ' // then start at zero and increase until aliasing is a problem.', ' FxaaFloat fxaaQualityEdgeThresholdMin,', ' //', ' // Only used on FXAA Console.', ' // This used to be the FXAA_CONSOLE_EDGE_SHARPNESS define.', ' // It is here now to allow easier tuning.', ' // This does not effect PS3, as this needs to be compiled in.', ' // Use FXAA_CONSOLE_PS3_EDGE_SHARPNESS for PS3.', ' // Due to the PS3 being ALU bound,', ' // there are only three safe values here: 2 and 4 and 8.', ' // These options use the shaders ability to a free *|/ by 2|4|8.', ' // For all other platforms can be a non-power of two.', ' // 8.0 is sharper (default!!!)', ' // 4.0 is softer', ' // 2.0 is really soft (good only for vector graphics inputs)', ' FxaaFloat fxaaConsoleEdgeSharpness,', ' //', ' // Only used on FXAA Console.', ' // This used to be the FXAA_CONSOLE_EDGE_THRESHOLD define.', ' // It is here now to allow easier tuning.', ' // This does not effect PS3, as this needs to be compiled in.', ' // Use FXAA_CONSOLE_PS3_EDGE_THRESHOLD for PS3.', ' // Due to the PS3 being ALU bound,', ' // there are only two safe values here: 1/4 and 1/8.', ' // These options use the shaders ability to a free *|/ by 2|4|8.', ' // The console setting has a different mapping than the quality setting.', ' // Other platforms can use other values.', ' // 0.125 leaves less aliasing, but is softer (default!!!)', ' // 0.25 leaves more aliasing, and is sharper', ' FxaaFloat fxaaConsoleEdgeThreshold,', ' //', ' // Only used on FXAA Console.', ' // This used to be the FXAA_CONSOLE_EDGE_THRESHOLD_MIN define.', ' // It is here now to allow easier tuning.', ' // Trims the algorithm from processing darks.', ' // The console setting has a different mapping than the quality setting.', ' // This only applies when FXAA_EARLY_EXIT is 1.', ' // This does not apply to PS3,', ' // PS3 was simplified to avoid more shader instructions.', ' // 0.06 - faster but more aliasing in darks', ' // 0.05 - default', ' // 0.04 - slower and less aliasing in darks', ' // Special notes when using FXAA_GREEN_AS_LUMA,', ' // Likely want to set this to zero.', ' // As colors that are mostly not-green', ' // will appear very dark in the green channel!', ' // Tune by looking at mostly non-green content,', ' // then start at zero and increase until aliasing is a problem.', ' FxaaFloat fxaaConsoleEdgeThresholdMin,', ' //', ' // Extra constants for 360 FXAA Console only.', ' // Use zeros or anything else for other platforms.', ' // These must be in physical constant registers and NOT immediates.', ' // Immediates will result in compiler un-optimizing.', ' // {xyzw} = float4(1.0, -1.0, 0.25, -0.25)', ' FxaaFloat4 fxaaConsole360ConstDir', ') {', '/*--------------------------------------------------------------------------*/', ' FxaaFloat2 posM;', ' posM.x = pos.x;', ' posM.y = pos.y;', ' #if (FXAA_GATHER4_ALPHA == 1)', ' #if (FXAA_DISCARD == 0)', ' FxaaFloat4 rgbyM = FxaaTexTop(tex, posM);', ' #if (FXAA_GREEN_AS_LUMA == 0)', ' #define lumaM rgbyM.w', ' #else', ' #define lumaM rgbyM.y', ' #endif', ' #endif', ' #if (FXAA_GREEN_AS_LUMA == 0)', ' FxaaFloat4 luma4A = FxaaTexAlpha4(tex, posM);', ' FxaaFloat4 luma4B = FxaaTexOffAlpha4(tex, posM, FxaaInt2(-1, -1));', ' #else', ' FxaaFloat4 luma4A = FxaaTexGreen4(tex, posM);', ' FxaaFloat4 luma4B = FxaaTexOffGreen4(tex, posM, FxaaInt2(-1, -1));', ' #endif', ' #if (FXAA_DISCARD == 1)', ' #define lumaM luma4A.w', ' #endif', ' #define lumaE luma4A.z', ' #define lumaS luma4A.x', ' #define lumaSE luma4A.y', ' #define lumaNW luma4B.w', ' #define lumaN luma4B.z', ' #define lumaW luma4B.x', ' #else', ' FxaaFloat4 rgbyM = FxaaTexTop(tex, posM);', ' #if (FXAA_GREEN_AS_LUMA == 0)', ' #define lumaM rgbyM.w', ' #else', ' #define lumaM rgbyM.y', ' #endif', ' #if (FXAA_GLSL_100 == 1)', ' FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 0.0, 1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 1.0, 0.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 0.0,-1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2(-1.0, 0.0), fxaaQualityRcpFrame.xy));', ' #else', ' FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy));', ' #endif', ' #endif', '/*--------------------------------------------------------------------------*/', ' FxaaFloat maxSM = max(lumaS, lumaM);', ' FxaaFloat minSM = min(lumaS, lumaM);', ' FxaaFloat maxESM = max(lumaE, maxSM);', ' FxaaFloat minESM = min(lumaE, minSM);', ' FxaaFloat maxWN = max(lumaN, lumaW);', ' FxaaFloat minWN = min(lumaN, lumaW);', ' FxaaFloat rangeMax = max(maxWN, maxESM);', ' FxaaFloat rangeMin = min(minWN, minESM);', ' FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold;', ' FxaaFloat range = rangeMax - rangeMin;', ' FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled);', ' FxaaBool earlyExit = range < rangeMaxClamped;', '/*--------------------------------------------------------------------------*/', ' if(earlyExit)', ' #if (FXAA_DISCARD == 1)', ' FxaaDiscard;', ' #else', ' return rgbyM;', ' #endif', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_GATHER4_ALPHA == 0)', ' #if (FXAA_GLSL_100 == 1)', ' FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2(-1.0,-1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 1.0, 1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 1.0,-1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2(-1.0, 1.0), fxaaQualityRcpFrame.xy));', ' #else', ' FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));', ' #endif', ' #else', ' FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));', ' #endif', '/*--------------------------------------------------------------------------*/', ' FxaaFloat lumaNS = lumaN + lumaS;', ' FxaaFloat lumaWE = lumaW + lumaE;', ' FxaaFloat subpixRcpRange = 1.0/range;', ' FxaaFloat subpixNSWE = lumaNS + lumaWE;', ' FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS;', ' FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat lumaNESE = lumaNE + lumaSE;', ' FxaaFloat lumaNWNE = lumaNW + lumaNE;', ' FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE;', ' FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat lumaNWSW = lumaNW + lumaSW;', ' FxaaFloat lumaSWSE = lumaSW + lumaSE;', ' FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2);', ' FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2);', ' FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW;', ' FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE;', ' FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4;', ' FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE;', ' FxaaFloat lengthSign = fxaaQualityRcpFrame.x;', ' FxaaBool horzSpan = edgeHorz >= edgeVert;', ' FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE;', '/*--------------------------------------------------------------------------*/', ' if(!horzSpan) lumaN = lumaW;', ' if(!horzSpan) lumaS = lumaE;', ' if(horzSpan) lengthSign = fxaaQualityRcpFrame.y;', ' FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat gradientN = lumaN - lumaM;', ' FxaaFloat gradientS = lumaS - lumaM;', ' FxaaFloat lumaNN = lumaN + lumaM;', ' FxaaFloat lumaSS = lumaS + lumaM;', ' FxaaBool pairN = abs(gradientN) >= abs(gradientS);', ' FxaaFloat gradient = max(abs(gradientN), abs(gradientS));', ' if(pairN) lengthSign = -lengthSign;', ' FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange);', '/*--------------------------------------------------------------------------*/', ' FxaaFloat2 posB;', ' posB.x = posM.x;', ' posB.y = posM.y;', ' FxaaFloat2 offNP;', ' offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;', ' offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;', ' if(!horzSpan) posB.x += lengthSign * 0.5;', ' if( horzSpan) posB.y += lengthSign * 0.5;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat2 posN;', ' posN.x = posB.x - offNP.x * FXAA_QUALITY_P0;', ' posN.y = posB.y - offNP.y * FXAA_QUALITY_P0;', ' FxaaFloat2 posP;', ' posP.x = posB.x + offNP.x * FXAA_QUALITY_P0;', ' posP.y = posB.y + offNP.y * FXAA_QUALITY_P0;', ' FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0;', ' FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN));', ' FxaaFloat subpixE = subpixC * subpixC;', ' FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP));', '/*--------------------------------------------------------------------------*/', ' if(!pairN) lumaNN = lumaSS;', ' FxaaFloat gradientScaled = gradient * 1.0/4.0;', ' FxaaFloat lumaMM = lumaM - lumaNN * 0.5;', ' FxaaFloat subpixF = subpixD * subpixE;', ' FxaaBool lumaMLTZero = lumaMM < 0.0;', '/*--------------------------------------------------------------------------*/', ' lumaEndN -= lumaNN * 0.5;', ' lumaEndP -= lumaNN * 0.5;', ' FxaaBool doneN = abs(lumaEndN) >= gradientScaled;', ' FxaaBool doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P1;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P1;', ' FxaaBool doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P1;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P1;', '/*--------------------------------------------------------------------------*/', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P2;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P2;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P2;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P2;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 3)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P3;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P3;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P3;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P3;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 4)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P4;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P4;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P4;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P4;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 5)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P5;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P5;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P5;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P5;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 6)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P6;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P6;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P6;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P6;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 7)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P7;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P7;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P7;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P7;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 8)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P8;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P8;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P8;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P8;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 9)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P9;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P9;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P9;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P9;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 10)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P10;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P10;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P10;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P10;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 11)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P11;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P11;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P11;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P11;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 12)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P12;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P12;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P12;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P12;', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', '/*--------------------------------------------------------------------------*/', ' FxaaFloat dstN = posM.x - posN.x;', ' FxaaFloat dstP = posP.x - posM.x;', ' if(!horzSpan) dstN = posM.y - posN.y;', ' if(!horzSpan) dstP = posP.y - posM.y;', '/*--------------------------------------------------------------------------*/', ' FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero;', ' FxaaFloat spanLength = (dstP + dstN);', ' FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero;', ' FxaaFloat spanLengthRcp = 1.0/spanLength;', '/*--------------------------------------------------------------------------*/', ' FxaaBool directionN = dstN < dstP;', ' FxaaFloat dst = min(dstN, dstP);', ' FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP;', ' FxaaFloat subpixG = subpixF * subpixF;', ' FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5;', ' FxaaFloat subpixH = subpixG * fxaaQualitySubpix;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0;', ' FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH);', ' if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign;', ' if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign;', ' #if (FXAA_DISCARD == 1)', ' return FxaaTexTop(tex, posM);', ' #else', ' return FxaaFloat4(FxaaTexTop(tex, posM).xyz, lumaM);', ' #endif', '}', '/*==========================================================================*/', '#endif', '', 'void main() {', ' gl_FragColor = FxaaPixelShader(', ' vUv,', ' vec4(0.0),', ' tDiffuse,', ' tDiffuse,', ' tDiffuse,', ' resolution,', ' vec4(0.0),', ' vec4(0.0),', ' vec4(0.0),', ' 0.75,', ' 0.166,', ' 0.0833,', ' 0.0,', ' 0.0,', ' 0.0,', ' vec4(0.0)', ' );', '', ' // TODO avoid querying texture twice for same texel', ' gl_FragColor.a = texture2D(tDiffuse, vUv).a;', '}'].join('\n') }); -/** - * Edge Detection Shader using Frei-Chen filter - * Based on http://rastergrid.com/blog/2011/01/frei-chen-edge-detector - * - * aspect: vec2 of (1/width, 1/height) - */ +if (process.env.NODE_ENV === 'development') { + Object.assign(dragConfigResolver, { + useTouch(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`useTouch\` option has been renamed to \`pointer.touch\`. Use it as in \`{ pointer: { touch: true } }\`.`); + } -({ - uniforms: { - tDiffuse: { - value: null + return NaN; }, - aspect: { - value: new Vector2(512, 512) - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'uniform vec2 aspect;', 'vec2 texel = vec2(1.0 / aspect.x, 1.0 / aspect.y);', 'mat3 G[9];', // hard coded matrix values!!!! as suggested in https://github.com/neilmendoza/ofxPostProcessing/blob/master/src/EdgePass.cpp#L45 - 'const mat3 g0 = mat3( 0.3535533845424652, 0, -0.3535533845424652, 0.5, 0, -0.5, 0.3535533845424652, 0, -0.3535533845424652 );', 'const mat3 g1 = mat3( 0.3535533845424652, 0.5, 0.3535533845424652, 0, 0, 0, -0.3535533845424652, -0.5, -0.3535533845424652 );', 'const mat3 g2 = mat3( 0, 0.3535533845424652, -0.5, -0.3535533845424652, 0, 0.3535533845424652, 0.5, -0.3535533845424652, 0 );', 'const mat3 g3 = mat3( 0.5, -0.3535533845424652, 0, -0.3535533845424652, 0, 0.3535533845424652, 0, 0.3535533845424652, -0.5 );', 'const mat3 g4 = mat3( 0, -0.5, 0, 0.5, 0, 0.5, 0, -0.5, 0 );', 'const mat3 g5 = mat3( -0.5, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5 );', 'const mat3 g6 = mat3( 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.6666666865348816, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204 );', 'const mat3 g7 = mat3( -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, 0.6666666865348816, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408 );', 'const mat3 g8 = mat3( 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408 );', 'void main(void)', '{', ' G[0] = g0,', ' G[1] = g1,', ' G[2] = g2,', ' G[3] = g3,', ' G[4] = g4,', ' G[5] = g5,', ' G[6] = g6,', ' G[7] = g7,', ' G[8] = g8;', ' mat3 I;', ' float cnv[9];', ' vec3 sample;', - /* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */ - ' for (float i=0.0; i<3.0; i++) {', ' for (float j=0.0; j<3.0; j++) {', ' sample = texture2D(tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb;', ' I[int(i)][int(j)] = length(sample);', ' }', ' }', - /* calculate the convolution values for all the masks */ - ' for (int i=0; i<9; i++) {', ' float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);', ' cnv[i] = dp3 * dp3;', ' }', ' float M = (cnv[0] + cnv[1]) + (cnv[2] + cnv[3]);', ' float S = (cnv[4] + cnv[5]) + (cnv[6] + cnv[7]) + (cnv[8] + M);', ' gl_FragColor = vec4(vec3(sqrt(M/S)), 1.0);', '}'].join('\n') -}); -/** - * The god-ray generation shader. - * - * First pass: - * - * The depth map is blurred along radial lines towards the "sun". The - * output is written to a temporary render target (I used a 1/4 sized - * target). - * - * Pass two & three: - * - * The results of the previous pass are re-blurred, each time with a - * decreased distance between samples. - */ + experimental_preventWindowScrollY(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`experimental_preventWindowScrollY\` option has been renamed to \`preventScroll\`.`); + } -({ - uniforms: { - tInput: { - value: null - }, - fStepSize: { - value: 1.0 + return NaN; }, - vSunPositionScreenSpace: { - value: new Vector3() - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#define TAPS_PER_PASS 6.0', 'varying vec2 vUv;', 'uniform sampler2D tInput;', 'uniform vec3 vSunPositionScreenSpace;', 'uniform float fStepSize;', // filter step size - 'void main() {', // delta from current pixel to "sun" position - ' vec2 delta = vSunPositionScreenSpace.xy - vUv;', ' float dist = length( delta );', // Step vector (uv space) - ' vec2 stepv = fStepSize * delta / dist;', // Number of iterations between pixel and sun - ' float iters = dist/fStepSize;', ' vec2 uv = vUv.xy;', ' float col = 0.0;', // This breaks ANGLE in Chrome 22 - // - see http://code.google.com/p/chromium/issues/detail?id=153105 - /* - // Unrolling didnt do much on my hardware (ATI Mobility Radeon 3450), - // so i've just left the loop - "for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {", - // Accumulate samples, making sure we dont walk past the light source. - // The check for uv.y < 1 would not be necessary with "border" UV wrap - // mode, with a black border color. I don't think this is currently - // exposed by three.js. As a result there might be artifacts when the - // sun is to the left, right or bottom of screen as these cases are - // not specifically handled. - " col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );", - " uv += stepv;", - "}", - */ - // Unrolling loop manually makes it work in ANGLE - ' float f = min( 1.0, max( vSunPositionScreenSpace.z / 1000.0, 0.0 ) );', // used to fade out godrays - ' if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', // Should technically be dividing by 'iters', but 'TAPS_PER_PASS' smooths out - // objectionable artifacts, in particular near the sun position. The side - // effect is that the result is darker than it should be around the sun, as - // TAPS_PER_PASS is greater than the number of samples actually accumulated. - // When the result is inverted (in the shader 'godrays_combine', this produces - // a slight bright spot at the position of the sun, even when it is occluded. - ' gl_FragColor = vec4( col/TAPS_PER_PASS );', ' gl_FragColor.a = 1.0;', '}'].join('\n') -}); -/** - * A dodgy sun/sky shader. Makes a bright spot at the sun location. Would be - * cheaper/faster/simpler to implement this as a simple sun sprite. - */ + swipeVelocity(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`swipeVelocity\` option has been renamed to \`swipe.velocity\`. Use it as in \`{ swipe: { velocity: 0.5 } }\`.`); + } -({ - uniforms: { - vSunPositionScreenSpace: { - value: new Vector3() - }, - fAspect: { - value: 1.0 - }, - sunColor: { - value: new Color(0xffee00) + return NaN; }, - bgColor: { - value: new Color(0x000000) - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['varying vec2 vUv;', 'uniform vec3 vSunPositionScreenSpace;', 'uniform float fAspect;', 'uniform vec3 sunColor;', 'uniform vec3 bgColor;', 'void main() {', ' vec2 diff = vUv - vSunPositionScreenSpace.xy;', // Correct for aspect ratio - ' diff.x *= fAspect;', ' float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 );', ' prop = 0.35 * pow( 1.0 - prop, 3.0 );', ' gl_FragColor.xyz = ( vSunPositionScreenSpace.z > 0.0 ) ? mix( sunColor, bgColor, 1.0 - prop ) : bgColor;', ' gl_FragColor.w = 1.0;', '}'].join('\n') -}); -/** - * Normal map shader - * - compute normals from heightmap - */ + swipeDistance(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`swipeDistance\` option has been renamed to \`swipe.distance\`. Use it as in \`{ swipe: { distance: 50 } }\`.`); + } -({ - uniforms: { - heightMap: { - value: null - }, - resolution: { - value: new Vector2(512, 512) - }, - scale: { - value: new Vector2(1, 1) + return NaN; }, - height: { - value: 0.05 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform float height;', 'uniform vec2 resolution;', 'uniform sampler2D heightMap;', 'varying vec2 vUv;', 'void main() {', ' float val = texture2D( heightMap, vUv ).x;', ' float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x;', ' float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x;', ' gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 );', '}'].join('\n') -}); -/** - * Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM) - * - * As mentioned in the video the Sobel operator expects a grayscale image as input. - * - */ + swipeDuration(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`swipeDuration\` option has been renamed to \`swipe.duration\`. Use it as in \`{ swipe: { duration: 250 } }\`.`); + } -({ - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2() + return NaN; } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform vec2 resolution;', 'varying vec2 vUv;', 'void main() {', ' vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y );', // kernel definition (in glsl matrices are filled in column-major order) - ' const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 );', // x direction kernel - ' const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 );', // y direction kernel - // fetch the 3x3 neighbourhood of a fragment - // first column - ' float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r;', ' float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r;', ' float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r;', // second column - ' float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r;', ' float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r;', ' float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r;', // third column - ' float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r;', ' float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r;', ' float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r;', // gradient value in x direction - ' float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 + ', ' Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 + ', ' Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2; ', // gradient value in y direction - ' float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 + ', ' Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 + ', ' Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2; ', // magnitute of the total gradient - ' float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) );', ' gl_FragColor = vec4( vec3( G ), 1 );', '}'].join('\n') -}); - -/** - * ------------------------------------------------------------------------------------------ - * Subsurface Scattering shader - * Based on GDC 2011 – Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look - * https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/ - *------------------------------------------------------------------------------------------ - */ -function replaceAll(string, find, replace) { - return string.split(find).join(replace); + }); } -const meshphong_frag_head = ShaderChunk['meshphong_frag'].slice(0, ShaderChunk['meshphong_frag'].indexOf('void main() {')); -const meshphong_frag_body = ShaderChunk['meshphong_frag'].slice(ShaderChunk['meshphong_frag'].indexOf('void main() {')); -({ - uniforms: UniformsUtils.merge([ShaderLib['phong'].uniforms, { - thicknessMap: { - value: null - }, - thicknessColor: { - value: new Color(0xffffff) - }, - thicknessDistortion: { - value: 0.1 - }, - thicknessAmbient: { - value: 0.0 - }, - thicknessAttenuation: { - value: 0.1 - }, - thicknessPower: { - value: 2.0 - }, - thicknessScale: { - value: 10.0 - } - }]), - vertexShader: ['#define USE_UV', ShaderChunk['meshphong_vert']].join('\n'), - fragmentShader: ['#define USE_UV', '#define SUBSURFACE', meshphong_frag_head, 'uniform sampler2D thicknessMap;', 'uniform float thicknessPower;', 'uniform float thicknessScale;', 'uniform float thicknessDistortion;', 'uniform float thicknessAmbient;', 'uniform float thicknessAttenuation;', 'uniform vec3 thicknessColor;', 'void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in GeometricContext geometry, inout ReflectedLight reflectedLight) {', ' vec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;', ' vec3 scatteringHalf = normalize(directLight.direction + (geometry.normal * thicknessDistortion));', ' float scatteringDot = pow(saturate(dot(geometry.viewDir, -scatteringHalf)), thicknessPower) * thicknessScale;', ' vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;', ' reflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;', '}', meshphong_frag_body.replace('#include ', replaceAll(ShaderChunk['lights_fragment_begin'], 'RE_Direct( directLight, geometry, material, reflectedLight );', ['RE_Direct( directLight, geometry, material, reflectedLight );', '#if defined( SUBSURFACE ) && defined( USE_UV )', ' RE_Direct_Scattering(directLight, vUv, geometry, reflectedLight);', '#endif'].join('\n')))].join('\n') -}); - -/** - * Currently contains: - * - * toon1 - * toon2 - * hatching - * dotted - */ +_objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { + device(_v, _k, { + shared, + pointer: { + touch = false + } = {} + }) { + const sharedConfig = shared; + if (sharedConfig.target && !SUPPORT.touch && SUPPORT.gesture) return 'gesture'; + if (SUPPORT.touch && touch) return 'touch'; -({ - uniforms: { - uDirLightPos: { - value: new Vector3() - }, - uDirLightColor: { - value: new Color(0xeeeeee) - }, - uAmbientLightColor: { - value: new Color(0x050505) - }, - uBaseColor: { - value: new Color(0xffffff) - } - }, - vertexShader: ['varying vec3 vNormal;', 'varying vec3 vRefract;', 'void main() {', ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );', ' vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );', ' vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );', ' vNormal = normalize( normalMatrix * normal );', ' vec3 I = worldPosition.xyz - cameraPosition;', ' vRefract = refract( normalize( I ), worldNormal, 1.02 );', ' gl_Position = projectionMatrix * mvPosition;', '}'].join('\n'), - fragmentShader: ['uniform vec3 uBaseColor;', 'uniform vec3 uDirLightPos;', 'uniform vec3 uDirLightColor;', 'uniform vec3 uAmbientLightColor;', 'varying vec3 vNormal;', 'varying vec3 vRefract;', 'void main() {', ' float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);', ' vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;', ' float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) );', ' intensity += length(lightWeighting) * 0.2;', ' float cameraWeighting = dot( normalize( vNormal ), vRefract );', ' intensity += pow( 1.0 - length( cameraWeighting ), 6.0 );', ' intensity = intensity * 0.2 + 0.3;', ' if ( intensity < 0.50 ) {', ' gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 );', ' } else {', ' gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 );', '}', '}'].join('\n') -}); -({ - uniforms: { - uDirLightPos: { - value: new Vector3() - }, - uDirLightColor: { - value: new Color(0xeeeeee) - }, - uAmbientLightColor: { - value: new Color(0x050505) - }, - uBaseColor: { - value: new Color(0xeeeeee) - }, - uLineColor1: { - value: new Color(0x808080) - }, - uLineColor2: { - value: new Color(0x000000) - }, - uLineColor3: { - value: new Color(0x000000) - }, - uLineColor4: { - value: new Color(0x000000) + if (SUPPORT.touchscreen) { + if (SUPPORT.pointer) return 'pointer'; + if (SUPPORT.touch) return 'touch'; } }, - vertexShader: ['varying vec3 vNormal;', 'void main() {', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', ' vNormal = normalize( normalMatrix * normal );', '}'].join('\n'), - fragmentShader: ['uniform vec3 uBaseColor;', 'uniform vec3 uLineColor1;', 'uniform vec3 uLineColor2;', 'uniform vec3 uLineColor3;', 'uniform vec3 uLineColor4;', 'uniform vec3 uDirLightPos;', 'uniform vec3 uDirLightColor;', 'uniform vec3 uAmbientLightColor;', 'varying vec3 vNormal;', 'void main() {', ' float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4);', ' float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);', ' gl_FragColor = vec4( uBaseColor, 1.0 );', ' if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) {', ' gl_FragColor *= vec4( uLineColor1, 1.0 );', ' }', ' if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) {', ' gl_FragColor *= vec4( uLineColor2, 1.0 );', ' }', '}'].join('\n') -}); -({ - uniforms: { - uDirLightPos: { - value: new Vector3() - }, - uDirLightColor: { - value: new Color(0xeeeeee) - }, - uAmbientLightColor: { - value: new Color(0x050505) - }, - uBaseColor: { - value: new Color(0xffffff) - }, - uLineColor1: { - value: new Color(0x000000) - }, - uLineColor2: { - value: new Color(0x000000) - }, - uLineColor3: { - value: new Color(0x000000) - }, - uLineColor4: { - value: new Color(0x000000) - } + + bounds(_v, _k, { + scaleBounds = {}, + angleBounds = {} + }) { + const _scaleBounds = state => { + const D = assignDefault(call(scaleBounds, state), { + min: -Infinity, + max: Infinity + }); + return [D.min, D.max]; + }; + + const _angleBounds = state => { + const A = assignDefault(call(angleBounds, state), { + min: -Infinity, + max: Infinity + }); + return [A.min, A.max]; + }; + + if (typeof scaleBounds !== 'function' && typeof angleBounds !== 'function') return [_scaleBounds(), _angleBounds()]; + return state => [_scaleBounds(state), _angleBounds(state)]; }, - vertexShader: ['varying vec3 vNormal;', 'void main() {', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', ' vNormal = normalize( normalMatrix * normal );', '}'].join('\n'), - fragmentShader: ['uniform vec3 uBaseColor;', 'uniform vec3 uLineColor1;', 'uniform vec3 uLineColor2;', 'uniform vec3 uLineColor3;', 'uniform vec3 uLineColor4;', 'uniform vec3 uDirLightPos;', 'uniform vec3 uDirLightColor;', 'uniform vec3 uAmbientLightColor;', 'varying vec3 vNormal;', 'void main() {', ' float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);', ' vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;', ' gl_FragColor = vec4( uBaseColor, 1.0 );', ' if ( length(lightWeighting) < 1.00 ) {', ' if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {', ' gl_FragColor = vec4( uLineColor1, 1.0 );', ' }', ' }', ' if ( length(lightWeighting) < 0.75 ) {', ' if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {', ' gl_FragColor = vec4( uLineColor2, 1.0 );', ' }', ' }', ' if ( length(lightWeighting) < 0.50 ) {', ' if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {', ' gl_FragColor = vec4( uLineColor3, 1.0 );', ' }', ' }', ' if ( length(lightWeighting) < 0.3465 ) {', ' if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {', ' gl_FragColor = vec4( uLineColor4, 1.0 );', ' }', ' }', '}'].join('\n') -}); -({ - uniforms: { - uDirLightPos: { - value: new Vector3() - }, - uDirLightColor: { - value: new Color(0xeeeeee) - }, - uAmbientLightColor: { - value: new Color(0x050505) - }, - uBaseColor: { - value: new Color(0xffffff) - }, - uLineColor1: { - value: new Color(0x000000) - } + + threshold(value, _k, config) { + this.lockDirection = config.axis === 'lock'; + const threshold = V.toVector(value, this.lockDirection ? [0.1, 3] : 0); + return threshold; }, - vertexShader: ['varying vec3 vNormal;', 'void main() {', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', ' vNormal = normalize( normalMatrix * normal );', '}'].join('\n'), - fragmentShader: ['uniform vec3 uBaseColor;', 'uniform vec3 uLineColor1;', 'uniform vec3 uLineColor2;', 'uniform vec3 uLineColor3;', 'uniform vec3 uLineColor4;', 'uniform vec3 uDirLightPos;', 'uniform vec3 uDirLightColor;', 'uniform vec3 uAmbientLightColor;', 'varying vec3 vNormal;', 'void main() {', 'float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);', 'vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;', 'gl_FragColor = vec4( uBaseColor, 1.0 );', 'if ( length(lightWeighting) < 1.00 ) {', ' if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) {', ' gl_FragColor = vec4( uLineColor1, 1.0 );', ' }', ' }', ' if ( length(lightWeighting) < 0.50 ) {', ' if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) {', ' gl_FragColor = vec4( uLineColor1, 1.0 );', ' }', ' }', '}'].join('\n') -}); -/** - * Triangle blur shader - * based on glfx.js triangle blur shader - * https://github.com/evanw/glfx.js - * - * A basic blur filter, which convolves the image with a - * pyramid filter. The pyramid filter is separable and is applied as two - * perpendicular triangle filters. - */ + modifierKey(value) { + if (value === undefined) return 'ctrlKey'; + return value; + } -({ - uniforms: { - texture: { - value: null - }, - delta: { - value: new Vector2(1, 1) - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', '#define ITERATIONS 10.0', 'uniform sampler2D texture;', 'uniform vec2 delta;', 'varying vec2 vUv;', 'void main() {', ' vec4 color = vec4( 0.0 );', ' float total = 0.0;', // randomize the lookup values to hide the fixed number of samples - ' float offset = rand( vUv );', ' for ( float t = -ITERATIONS; t <= ITERATIONS; t ++ ) {', ' float percent = ( t + offset - 0.5 ) / ITERATIONS;', ' float weight = 1.0 - abs( percent );', ' color += texture2D( texture, vUv + delta * percent ) * weight;', ' total += weight;', ' }', ' gl_FragColor = color / total;', '}'].join('\n') }); -/** - * Shaders to render 3D volumes using raycasting. - * The applied techniques are based on similar implementations in the Visvis and Vispy projects. - * This is not the only approach, therefore it's marked 1. - */ +_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { + mouseOnly: (value = true) => value +}); -({ - uniforms: { - u_size: { - value: new Vector3(1, 1, 1) - }, - u_renderstyle: { - value: 0 - }, - u_renderthreshold: { - value: 0.5 - }, - u_clim: { - value: new Vector2(1, 1) - }, - u_data: { - value: null - }, - u_cmdata: { - value: null - } - }, - vertexShader: [' varying vec4 v_nearpos;', ' varying vec4 v_farpos;', ' varying vec3 v_position;', ' void main() {', // Prepare transforms to map to "camera view". See also: - // https://threejs.org/docs/#api/renderers/webgl/WebGLProgram - ' mat4 viewtransformf = modelViewMatrix;', ' mat4 viewtransformi = inverse(modelViewMatrix);', // Project local vertex coordinate to camera position. Then do a step - // backward (in cam coords) to the near clipping plane, and project back. Do - // the same for the far clipping plane. This gives us all the information we - // need to calculate the ray and truncate it to the viewing cone. - ' vec4 position4 = vec4(position, 1.0);', ' vec4 pos_in_cam = viewtransformf * position4;', // Intersection of ray and near clipping plane (z = -1 in clip coords) - ' pos_in_cam.z = -pos_in_cam.w;', ' v_nearpos = viewtransformi * pos_in_cam;', // Intersection of ray and far clipping plane (z = +1 in clip coords) - ' pos_in_cam.z = pos_in_cam.w;', ' v_farpos = viewtransformi * pos_in_cam;', // Set varyings and output pos - ' v_position = position;', ' gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4;', ' }'].join('\n'), - fragmentShader: [' precision highp float;', ' precision mediump sampler3D;', ' uniform vec3 u_size;', ' uniform int u_renderstyle;', ' uniform float u_renderthreshold;', ' uniform vec2 u_clim;', ' uniform sampler3D u_data;', ' uniform sampler2D u_cmdata;', ' varying vec3 v_position;', ' varying vec4 v_nearpos;', ' varying vec4 v_farpos;', // The maximum distance through our rendering volume is sqrt(3). - ' const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3', ' const int REFINEMENT_STEPS = 4;', ' const float relative_step_size = 1.0;', ' const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0);', ' const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0);', ' const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0);', ' const float shininess = 40.0;', ' void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);', ' void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);', ' float sample1(vec3 texcoords);', ' vec4 apply_colormap(float val);', ' vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray);', ' void main() {', // Normalize clipping plane info - ' vec3 farpos = v_farpos.xyz / v_farpos.w;', ' vec3 nearpos = v_nearpos.xyz / v_nearpos.w;', // Calculate unit vector pointing in the view direction through this fragment. - ' vec3 view_ray = normalize(nearpos.xyz - farpos.xyz);', // Compute the (negative) distance to the front surface or near clipping plane. - // v_position is the back face of the cuboid, so the initial distance calculated in the dot - // product below is the distance from near clip plane to the back of the cuboid - ' float distance = dot(nearpos - v_position, view_ray);', ' distance = max(distance, min((-0.5 - v_position.x) / view_ray.x,', ' (u_size.x - 0.5 - v_position.x) / view_ray.x));', ' distance = max(distance, min((-0.5 - v_position.y) / view_ray.y,', ' (u_size.y - 0.5 - v_position.y) / view_ray.y));', ' distance = max(distance, min((-0.5 - v_position.z) / view_ray.z,', ' (u_size.z - 0.5 - v_position.z) / view_ray.z));', // Now we have the starting position on the front surface - ' vec3 front = v_position + view_ray * distance;', // Decide how many steps to take - ' int nsteps = int(-distance / relative_step_size + 0.5);', ' if ( nsteps < 1 )', ' discard;', // Get starting location and step vector in texture coordinates - ' vec3 step = ((v_position - front) / u_size) / float(nsteps);', ' vec3 start_loc = front / u_size;', // For testing: show the number of steps. This helps to establish - // whether the rays are correctly oriented - //'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0);', - //'return;', - ' if (u_renderstyle == 0)', ' cast_mip(start_loc, step, nsteps, view_ray);', ' else if (u_renderstyle == 1)', ' cast_iso(start_loc, step, nsteps, view_ray);', ' if (gl_FragColor.a < 0.05)', ' discard;', ' }', ' float sample1(vec3 texcoords) {', ' /* Sample float value from a 3D texture. Assumes intensity data. */', ' return texture(u_data, texcoords.xyz).r;', ' }', ' vec4 apply_colormap(float val) {', ' val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]);', ' return texture2D(u_cmdata, vec2(val, 0.5));', ' }', ' void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {', ' float max_val = -1e6;', ' int max_i = 100;', ' vec3 loc = start_loc;', // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with - // non-constant expression. So we use a hard-coded max, and an additional condition - // inside the loop. - ' for (int iter=0; iter= nsteps)', ' break;', // Sample from the 3D texture - ' float val = sample1(loc);', // Apply MIP operation - ' if (val > max_val) {', ' max_val = val;', ' max_i = iter;', ' }', // Advance location deeper into the volume - ' loc += step;', ' }', // Refine location, gives crispier images - ' vec3 iloc = start_loc + step * (float(max_i) - 0.5);', ' vec3 istep = step / float(REFINEMENT_STEPS);', ' for (int i=0; i= nsteps)', ' break;', // Sample from the 3D texture - ' float val = sample1(loc);', ' if (val > low_threshold) {', // Take the last interval in smaller steps - ' vec3 iloc = loc - 0.5 * step;', ' vec3 istep = step / float(REFINEMENT_STEPS);', ' for (int i=0; i u_renderthreshold) {', ' gl_FragColor = add_lighting(val, iloc, dstep, view_ray);', ' return;', ' }', ' iloc += istep;', ' }', ' }', // Advance location deeper into the volume - ' loc += step;', ' }', ' }', ' vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray)', ' {', // Calculate color by incorporating lighting - // View direction - ' vec3 V = normalize(view_ray);', // calculate normal vector from gradient - ' vec3 N;', ' float val1, val2;', ' val1 = sample1(loc + vec3(-step[0], 0.0, 0.0));', ' val2 = sample1(loc + vec3(+step[0], 0.0, 0.0));', ' N[0] = val1 - val2;', ' val = max(max(val1, val2), val);', ' val1 = sample1(loc + vec3(0.0, -step[1], 0.0));', ' val2 = sample1(loc + vec3(0.0, +step[1], 0.0));', ' N[1] = val1 - val2;', ' val = max(max(val1, val2), val);', ' val1 = sample1(loc + vec3(0.0, 0.0, -step[2]));', ' val2 = sample1(loc + vec3(0.0, 0.0, +step[2]));', ' N[2] = val1 - val2;', ' val = max(max(val1, val2), val);', ' float gm = length(N); // gradient magnitude', ' N = normalize(N);', // Flip normal so it points towards viewer - ' float Nselect = float(dot(N, V) > 0.0);', ' N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N;', // Init colors - ' vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0);', ' vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0);', ' vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0);', // note: could allow multiple lights - ' for (int i=0; i<1; i++)', ' {', // Get light direction (make sure to prevent zero devision) - ' vec3 L = normalize(view_ray); //lightDirs[i];', ' float lightEnabled = float( length(L) > 0.0 );', ' L = normalize(L + (1.0 - lightEnabled));', // Calculate lighting properties - ' float lambertTerm = clamp(dot(N, L), 0.0, 1.0);', ' vec3 H = normalize(L+V); // Halfway vector', ' float specularTerm = pow(max(dot(H, N), 0.0), shininess);', // Calculate mask - ' float mask1 = lightEnabled;', // Calculate colors - ' ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient;', ' diffuse_color += mask1 * lambertTerm;', ' specular_color += mask1 * specularTerm * specular_color;', ' }', // Calculate final color by componing different components - ' vec4 final_color;', ' vec4 color = apply_colormap(val);', ' final_color = color * (ambient_color + diffuse_color) + specular_color;', ' final_color.a = color.a;', ' return final_color;', ' }'].join('\n') +_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { + mouseOnly: (value = true) => value }); /** @@ -163122,7 +91758,7 @@ const subscribeWithSelectorImpl = (fn) => (set, get, api) => { }; const subscribeWithSelector = subscribeWithSelectorImpl; -function n(n){for(var r=arguments.length,t=Array(r>1?r-1:0),e=1;e3?r.i-4:r.i:Array.isArray(n)?1:s(n)?2:v(n)?3:0}function u(n,r){return 2===o(n)?n.has(r):Object.prototype.hasOwnProperty.call(n,r)}function a(n,r){return 2===o(n)?n.get(r):n[r]}function f(n,r,t){var e=o(n);2===e?n.set(r,t):3===e?(n.delete(r),n.add(t)):n[r]=t;}function c(n,r){return n===r?0!==n||1/n==1/r:n!=n&&r!=r}function s(n){return X&&n instanceof Map}function v(n){return q&&n instanceof Set}function p(n){return n.o||n.t}function l(n){if(Array.isArray(n))return Array.prototype.slice.call(n);var r=rn(n);delete r[Q];for(var t=nn(r),e=0;e1&&(n.set=n.add=n.clear=n.delete=h),Object.freeze(n),e&&i$1(n,(function(n,r){return d(r,!0)}),!0),n)}function h(){n(2);}function y(n){return null==n||"object"!=typeof n||Object.isFrozen(n)}function b(r){var t=tn[r];return t||n(18,r),t}function _(){return "production"===process.env.NODE_ENV||U||n(0),U}function j(n,r){r&&(b("Patches"),n.u=[],n.s=[],n.v=r);}function O(n){g(n),n.p.forEach(S),n.p=null;}function g(n){n===U&&(U=n.l);}function w(n){return U={p:[],l:U,h:n,m:!0,_:0}}function S(n){var r=n[Q];0===r.i||1===r.i?r.j():r.O=!0;}function P(r,e){e._=e.p.length;var i=e.p[0],o=void 0!==r&&r!==i;return e.h.g||b("ES5").S(e,r,o),o?(i[Q].P&&(O(e),n(4)),t(r)&&(r=M(e,r),e.l||x(e,r)),e.u&&b("Patches").M(i[Q].t,r,e.u,e.s)):r=M(e,i,[]),O(e),e.u&&e.v(e.u,e.s),r!==H?r:void 0}function M(n,r,t){if(y(r))return r;var e=r[Q];if(!e)return i$1(r,(function(i,o){return A(n,e,r,i,o,t)}),!0),r;if(e.A!==n)return r;if(!e.P)return x(n,e.t,!0),e.t;if(!e.I){e.I=!0,e.A._--;var o=4===e.i||5===e.i?e.o=l(e.k):e.o;i$1(3===e.i?new Set(o):o,(function(r,i){return A(n,e,o,r,i,t)})),x(n,o,!1),t&&n.u&&b("Patches").R(e,t,n.u,n.s);}return e.o}function A(e,i,o,a,c,s){if("production"!==process.env.NODE_ENV&&c===o&&n(5),r(c)){var v=M(e,c,s&&i&&3!==i.i&&!u(i.D,a)?s.concat(a):void 0);if(f(o,a,v),!r(v))return;e.m=!1;}if(t(c)&&!y(c)){if(!e.h.F&&e._<1)return;M(e,c),i&&i.A.l||x(e,c);}}function x(n,r,t){void 0===t&&(t=!1),n.h.F&&n.m&&d(r,t);}function z(n,r){var t=n[Q];return (t?p(t):n)[r]}function I(n,r){if(r in n)for(var t=Object.getPrototypeOf(n);t;){var e=Object.getOwnPropertyDescriptor(t,r);if(e)return e;t=Object.getPrototypeOf(t);}}function k(n){n.P||(n.P=!0,n.l&&k(n.l));}function E(n){n.o||(n.o=l(n.t));}function R(n,r,t){var e=s(r)?b("MapSet").N(r,t):v(r)?b("MapSet").T(r,t):n.g?function(n,r){var t=Array.isArray(n),e={i:t?1:0,A:r?r.A:_(),P:!1,I:!1,D:{},l:r,t:n,k:null,o:null,j:null,C:!1},i=e,o=en;t&&(i=[e],o=on);var u=Proxy.revocable(i,o),a=u.revoke,f=u.proxy;return e.k=f,e.j=a,f}(r,t):b("ES5").J(r,t);return (t?t.A:_()).p.push(e),e}function D(e){return r(e)||n(22,e),function n(r){if(!t(r))return r;var e,u=r[Q],c=o(r);if(u){if(!u.P&&(u.i<4||!b("ES5").K(u)))return u.t;u.I=!0,e=F(r,c),u.I=!1;}else e=F(r,c);return i$1(e,(function(r,t){u&&a(u.t,r)===t||f(e,r,n(t));})),3===c?new Set(e):e}(e)}function F(n,r){switch(r){case 2:return new Map(n);case 3:return Array.from(n)}return l(n)}var G,U,W="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),X="undefined"!=typeof Map,q="undefined"!=typeof Set,B="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,H=W?Symbol.for("immer-nothing"):((G={})["immer-nothing"]=!0,G),L=W?Symbol.for("immer-draftable"):"__$immer_draftable",Q=W?Symbol.for("immer-state"):"__$immer_state",Y={0:"Illegal state",1:"Immer drafts cannot have computed properties",2:"This object has been frozen and should not be mutated",3:function(n){return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+n},4:"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",5:"Immer forbids circular references",6:"The first or second argument to `produce` must be a function",7:"The third argument to `produce` must be a function or undefined",8:"First argument to `createDraft` must be a plain object, an array, or an immerable object",9:"First argument to `finishDraft` must be a draft returned by `createDraft`",10:"The given draft is already finalized",11:"Object.defineProperty() cannot be used on an Immer draft",12:"Object.setPrototypeOf() cannot be used on an Immer draft",13:"Immer only supports deleting array indices",14:"Immer only supports setting array indices and the 'length' property",15:function(n){return "Cannot apply patch, path doesn't resolve: "+n},16:'Sets cannot have "replace" patches.',17:function(n){return "Unsupported patch operation: "+n},18:function(n){return "The plugin for '"+n+"' has not been loaded into Immer. To enable the plugin, import and call `enable"+n+"()` when initializing your application."},20:"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",21:function(n){return "produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '"+n+"'"},22:function(n){return "'current' expects a draft, got: "+n},23:function(n){return "'original' expects a draft, got: "+n},24:"Patching reserved attributes like __proto__, prototype and constructor is not allowed"},Z=""+Object.prototype.constructor,nn="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n))}:Object.getOwnPropertyNames,rn=Object.getOwnPropertyDescriptors||function(n){var r={};return nn(n).forEach((function(t){r[t]=Object.getOwnPropertyDescriptor(n,t);})),r},tn={},en={get:function(n,r){if(r===Q)return n;var e=p(n);if(!u(e,r))return function(n,r,t){var e,i=I(r,t);return i?"value"in i?i.value:null===(e=i.get)||void 0===e?void 0:e.call(n.k):void 0}(n,e,r);var i=e[r];return n.I||!t(i)?i:i===z(n.t,r)?(E(n),n.o[r]=R(n.A.h,i,n)):i},has:function(n,r){return r in p(n)},ownKeys:function(n){return Reflect.ownKeys(p(n))},set:function(n,r,t){var e=I(p(n),r);if(null==e?void 0:e.set)return e.set.call(n.k,t),!0;if(!n.P){var i=z(p(n),r),o=null==i?void 0:i[Q];if(o&&o.t===t)return n.o[r]=t,n.D[r]=!1,!0;if(c(t,i)&&(void 0!==t||u(n.t,r)))return !0;E(n),k(n);}return n.o[r]===t&&"number"!=typeof t&&(void 0!==t||r in n.o)||(n.o[r]=t,n.D[r]=!0,!0)},deleteProperty:function(n,r){return void 0!==z(n.t,r)||r in n.t?(n.D[r]=!1,E(n),k(n)):delete n.D[r],n.o&&delete n.o[r],!0},getOwnPropertyDescriptor:function(n,r){var t=p(n),e=Reflect.getOwnPropertyDescriptor(t,r);return e?{writable:!0,configurable:1!==n.i||"length"!==r,enumerable:e.enumerable,value:t[r]}:e},defineProperty:function(){n(11);},getPrototypeOf:function(n){return Object.getPrototypeOf(n.t)},setPrototypeOf:function(){n(12);}},on={};i$1(en,(function(n,r){on[n]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)};})),on.deleteProperty=function(r,t){return "production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&n(13),on.set.call(this,r,t,void 0)},on.set=function(r,t,e){return "production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&n(14),en.set.call(this,r[0],t,e,r[0])};var un=function(){function e(r){var e=this;this.g=B,this.F=!0,this.produce=function(r,i,o){if("function"==typeof r&&"function"!=typeof i){var u=i;i=r;var a=e;return function(n){var r=this;void 0===n&&(n=u);for(var t=arguments.length,e=Array(t>1?t-1:0),o=1;o1?t-1:0),o=1;o=0;e--){var i=t[e];if(0===i.path.length&&"replace"===i.op){n=i.value;break}}e>-1&&(t=t.slice(e+1));var o=b("Patches").$;return r(n)?o(n,t):this.produce(n,(function(n){return o(n,t)}))},e}(),an=new un,fn=an.produce;an.produceWithPatches.bind(an);an.setAutoFreeze.bind(an);an.setUseProxies.bind(an);an.applyPatches.bind(an);an.createDraft.bind(an);an.finishDraft.bind(an);var produce = fn; +function n(n){for(var r=arguments.length,t=Array(r>1?r-1:0),e=1;e3?r.i-4:r.i:Array.isArray(n)?1:s(n)?2:v(n)?3:0}function u(n,r){return 2===o(n)?n.has(r):Object.prototype.hasOwnProperty.call(n,r)}function a(n,r){return 2===o(n)?n.get(r):n[r]}function f(n,r,t){var e=o(n);2===e?n.set(r,t):3===e?(n.delete(r),n.add(t)):n[r]=t;}function c(n,r){return n===r?0!==n||1/n==1/r:n!=n&&r!=r}function s(n){return X&&n instanceof Map}function v(n){return q&&n instanceof Set}function p(n){return n.o||n.t}function l(n){if(Array.isArray(n))return Array.prototype.slice.call(n);var r=rn(n);delete r[Q];for(var t=nn(r),e=0;e1&&(n.set=n.add=n.clear=n.delete=h),Object.freeze(n),e&&i(n,(function(n,r){return d(r,!0)}),!0),n)}function h(){n(2);}function y(n){return null==n||"object"!=typeof n||Object.isFrozen(n)}function b(r){var t=tn[r];return t||n(18,r),t}function _(){return "production"===process.env.NODE_ENV||U||n(0),U}function j(n,r){r&&(b("Patches"),n.u=[],n.s=[],n.v=r);}function O(n){g(n),n.p.forEach(S),n.p=null;}function g(n){n===U&&(U=n.l);}function w(n){return U={p:[],l:U,h:n,m:!0,_:0}}function S(n){var r=n[Q];0===r.i||1===r.i?r.j():r.O=!0;}function P(r,e){e._=e.p.length;var i=e.p[0],o=void 0!==r&&r!==i;return e.h.g||b("ES5").S(e,r,o),o?(i[Q].P&&(O(e),n(4)),t(r)&&(r=M(e,r),e.l||x(e,r)),e.u&&b("Patches").M(i[Q].t,r,e.u,e.s)):r=M(e,i,[]),O(e),e.u&&e.v(e.u,e.s),r!==H?r:void 0}function M(n,r,t){if(y(r))return r;var e=r[Q];if(!e)return i(r,(function(i,o){return A(n,e,r,i,o,t)}),!0),r;if(e.A!==n)return r;if(!e.P)return x(n,e.t,!0),e.t;if(!e.I){e.I=!0,e.A._--;var o=4===e.i||5===e.i?e.o=l(e.k):e.o;i(3===e.i?new Set(o):o,(function(r,i){return A(n,e,o,r,i,t)})),x(n,o,!1),t&&n.u&&b("Patches").R(e,t,n.u,n.s);}return e.o}function A(e,i,o,a,c,s){if("production"!==process.env.NODE_ENV&&c===o&&n(5),r(c)){var v=M(e,c,s&&i&&3!==i.i&&!u(i.D,a)?s.concat(a):void 0);if(f(o,a,v),!r(v))return;e.m=!1;}if(t(c)&&!y(c)){if(!e.h.F&&e._<1)return;M(e,c),i&&i.A.l||x(e,c);}}function x(n,r,t){void 0===t&&(t=!1),n.h.F&&n.m&&d(r,t);}function z(n,r){var t=n[Q];return (t?p(t):n)[r]}function I(n,r){if(r in n)for(var t=Object.getPrototypeOf(n);t;){var e=Object.getOwnPropertyDescriptor(t,r);if(e)return e;t=Object.getPrototypeOf(t);}}function k(n){n.P||(n.P=!0,n.l&&k(n.l));}function E(n){n.o||(n.o=l(n.t));}function R(n,r,t){var e=s(r)?b("MapSet").N(r,t):v(r)?b("MapSet").T(r,t):n.g?function(n,r){var t=Array.isArray(n),e={i:t?1:0,A:r?r.A:_(),P:!1,I:!1,D:{},l:r,t:n,k:null,o:null,j:null,C:!1},i=e,o=en;t&&(i=[e],o=on);var u=Proxy.revocable(i,o),a=u.revoke,f=u.proxy;return e.k=f,e.j=a,f}(r,t):b("ES5").J(r,t);return (t?t.A:_()).p.push(e),e}function D(e){return r(e)||n(22,e),function n(r){if(!t(r))return r;var e,u=r[Q],c=o(r);if(u){if(!u.P&&(u.i<4||!b("ES5").K(u)))return u.t;u.I=!0,e=F(r,c),u.I=!1;}else e=F(r,c);return i(e,(function(r,t){u&&a(u.t,r)===t||f(e,r,n(t));})),3===c?new Set(e):e}(e)}function F(n,r){switch(r){case 2:return new Map(n);case 3:return Array.from(n)}return l(n)}var G,U,W="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),X="undefined"!=typeof Map,q="undefined"!=typeof Set,B="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,H=W?Symbol.for("immer-nothing"):((G={})["immer-nothing"]=!0,G),L=W?Symbol.for("immer-draftable"):"__$immer_draftable",Q=W?Symbol.for("immer-state"):"__$immer_state",Y={0:"Illegal state",1:"Immer drafts cannot have computed properties",2:"This object has been frozen and should not be mutated",3:function(n){return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+n},4:"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",5:"Immer forbids circular references",6:"The first or second argument to `produce` must be a function",7:"The third argument to `produce` must be a function or undefined",8:"First argument to `createDraft` must be a plain object, an array, or an immerable object",9:"First argument to `finishDraft` must be a draft returned by `createDraft`",10:"The given draft is already finalized",11:"Object.defineProperty() cannot be used on an Immer draft",12:"Object.setPrototypeOf() cannot be used on an Immer draft",13:"Immer only supports deleting array indices",14:"Immer only supports setting array indices and the 'length' property",15:function(n){return "Cannot apply patch, path doesn't resolve: "+n},16:'Sets cannot have "replace" patches.',17:function(n){return "Unsupported patch operation: "+n},18:function(n){return "The plugin for '"+n+"' has not been loaded into Immer. To enable the plugin, import and call `enable"+n+"()` when initializing your application."},20:"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",21:function(n){return "produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '"+n+"'"},22:function(n){return "'current' expects a draft, got: "+n},23:function(n){return "'original' expects a draft, got: "+n},24:"Patching reserved attributes like __proto__, prototype and constructor is not allowed"},Z=""+Object.prototype.constructor,nn="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n))}:Object.getOwnPropertyNames,rn=Object.getOwnPropertyDescriptors||function(n){var r={};return nn(n).forEach((function(t){r[t]=Object.getOwnPropertyDescriptor(n,t);})),r},tn={},en={get:function(n,r){if(r===Q)return n;var e=p(n);if(!u(e,r))return function(n,r,t){var e,i=I(r,t);return i?"value"in i?i.value:null===(e=i.get)||void 0===e?void 0:e.call(n.k):void 0}(n,e,r);var i=e[r];return n.I||!t(i)?i:i===z(n.t,r)?(E(n),n.o[r]=R(n.A.h,i,n)):i},has:function(n,r){return r in p(n)},ownKeys:function(n){return Reflect.ownKeys(p(n))},set:function(n,r,t){var e=I(p(n),r);if(null==e?void 0:e.set)return e.set.call(n.k,t),!0;if(!n.P){var i=z(p(n),r),o=null==i?void 0:i[Q];if(o&&o.t===t)return n.o[r]=t,n.D[r]=!1,!0;if(c(t,i)&&(void 0!==t||u(n.t,r)))return !0;E(n),k(n);}return n.o[r]===t&&"number"!=typeof t&&(void 0!==t||r in n.o)||(n.o[r]=t,n.D[r]=!0,!0)},deleteProperty:function(n,r){return void 0!==z(n.t,r)||r in n.t?(n.D[r]=!1,E(n),k(n)):delete n.D[r],n.o&&delete n.o[r],!0},getOwnPropertyDescriptor:function(n,r){var t=p(n),e=Reflect.getOwnPropertyDescriptor(t,r);return e?{writable:!0,configurable:1!==n.i||"length"!==r,enumerable:e.enumerable,value:t[r]}:e},defineProperty:function(){n(11);},getPrototypeOf:function(n){return Object.getPrototypeOf(n.t)},setPrototypeOf:function(){n(12);}},on={};i(en,(function(n,r){on[n]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)};})),on.deleteProperty=function(r,t){return "production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&n(13),on.set.call(this,r,t,void 0)},on.set=function(r,t,e){return "production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&n(14),en.set.call(this,r[0],t,e,r[0])};var un=function(){function e(r){var e=this;this.g=B,this.F=!0,this.produce=function(r,i,o){if("function"==typeof r&&"function"!=typeof i){var u=i;i=r;var a=e;return function(n){var r=this;void 0===n&&(n=u);for(var t=arguments.length,e=Array(t>1?t-1:0),o=1;o1?t-1:0),o=1;o=0;e--){var i=t[e];if(0===i.path.length&&"replace"===i.op){n=i.value;break}}e>-1&&(t=t.slice(e+1));var o=b("Patches").$;return r(n)?o(n,t):this.produce(n,(function(n){return o(n,t)}))},e}(),an=new un,fn=an.produce;an.produceWithPatches.bind(an);an.setAutoFreeze.bind(an);an.setUseProxies.bind(an);an.applyPatches.bind(an);an.createDraft.bind(an);an.finishDraft.bind(an);var produce = fn; // Credit to Mugen87 while we wait for this to be added to three.js // https://github.com/Mugen87/three.js/blob/3a6d8139367e710a3d4fef274d530dda485f1110/examples/jsm/misc/Timer.js @@ -180758,6 +109394,8 @@ class TransformControls extends Object3D { } + this.isTransformControls = true; + this.visible = false; this.domElement = domElement; this.domElement.style.touchAction = 'none'; // disable touch scroll @@ -180912,7 +109550,15 @@ class TransformControls extends Object3D { this.camera.updateMatrixWorld(); this.camera.matrixWorld.decompose( this.cameraPosition, this.cameraQuaternion, this._cameraScale ); - this.eye.copy( this.cameraPosition ).sub( this.worldPosition ).normalize(); + if ( this.camera.isOrthographicCamera ) { + + this.camera.getWorldDirection( this.eye ); + + } else { + + this.eye.copy( this.cameraPosition ).sub( this.worldPosition ).normalize(); + + } super.updateMatrixWorld( this ); @@ -181350,8 +109996,6 @@ class TransformControls extends Object3D { } -TransformControls.prototype.isTransformControls = true; - // mouse / touch event handlers function getPointer( event ) { @@ -181475,6 +110119,8 @@ class TransformControlsGizmo extends Object3D { super(); + this.isTransformControlsGizmo = true; + this.type = 'TransformControlsGizmo'; // shared materials @@ -182165,8 +110811,6 @@ class TransformControlsGizmo extends Object3D { } -TransformControlsGizmo.prototype.isTransformControlsGizmo = true; - // class TransformControlsPlane extends Mesh { @@ -182178,6 +110822,8 @@ class TransformControlsPlane extends Mesh { new MeshBasicMaterial( { visible: false, wireframe: true, side: DoubleSide, transparent: true, opacity: 0.1, toneMapped: false } ) ); + this.isTransformControlsPlane = true; + this.type = 'TransformControlsPlane'; } @@ -182260,8 +110906,6 @@ class TransformControlsPlane extends Mesh { } -TransformControlsPlane.prototype.isTransformControlsPlane = true; - /* * Box Mesh */ @@ -182282,10 +110926,8 @@ var BOX_GEOM = function BOX_GEOM(params) { x = x === undefined ? boxGeomDefaultDim : x; y = y === undefined ? boxGeomDefaultDim : y; - z = z === undefined ? boxGeomDefaultDim : z; // RoundedBoxGeometry() - // return new RoundedBoxGeometry(x, y, z, 2, 0.05) - - return new BoxGeometry(x, y, z); + z = z === undefined ? boxGeomDefaultDim : z; + return new RoundedBoxGeometry(x, y, z, 2, 0.05); }; /* * Sphere Mesh diff --git a/dist/index.js b/dist/index.js index 942e46c..f2233a3 100644 --- a/dist/index.js +++ b/dist/index.js @@ -4,6 +4,8 @@ Object.defineProperty(exports, '__esModule', { value: true }); var React = require('react'); var ReactDOM = require('react-dom/client'); +var threeStdlib = require('three-stdlib'); +var BufferGeometryUtils = require('three-stdlib/utils/BufferGeometryUtils'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } @@ -46,7 +48,7 @@ function _objectSpread2$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { - _defineProperty$3(target, key, source[key]); + _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); @@ -80,7 +82,7 @@ function _createClass(Constructor, protoProps, staticProps) { return Constructor; } -function _defineProperty$3(obj, key, value) { +function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -228,7 +230,7 @@ function _nonIterableRest() { * Copyright 2010-2022 Three.js Authors * SPDX-License-Identifier: MIT */ -const REVISION = '139'; +const REVISION = '142'; const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; const CullFaceNone = 0; @@ -497,13 +499,7 @@ class EventDispatcher { } -const _lut$1 = []; - -for ( let i = 0; i < 256; i ++ ) { - - _lut$1[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); - -} +const _lut$1 = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ]; let _seed = 1234567; @@ -586,7 +582,7 @@ function pingpong( x, length = 1 ) { } // http://en.wikipedia.org/wiki/Smoothstep -function smoothstep$1( x, min, max ) { +function smoothstep( x, min, max ) { if ( x <= min ) return 0; if ( x >= max ) return 1; @@ -764,7 +760,7 @@ function denormalize$1( value, array ) { } -function normalize$1( value, array ) { +function normalize( value, array ) { switch ( array.constructor ) { @@ -808,7 +804,7 @@ var MathUtils = /*#__PURE__*/Object.freeze({ lerp: lerp, damp: damp, pingpong: pingpong, - smoothstep: smoothstep$1, + smoothstep: smoothstep, smootherstep: smootherstep, randInt: randInt, randFloat: randFloat, @@ -820,7 +816,7 @@ var MathUtils = /*#__PURE__*/Object.freeze({ ceilPowerOfTwo: ceilPowerOfTwo, floorPowerOfTwo: floorPowerOfTwo, setQuaternionFromProperEuler: setQuaternionFromProperEuler, - normalize: normalize$1, + normalize: normalize, denormalize: denormalize$1 }); @@ -828,6 +824,8 @@ class Vector2 { constructor( x = 0, y = 0 ) { + Vector2.prototype.isVector2 = true; + this.x = x; this.y = y; @@ -1305,12 +1303,12 @@ class Vector2 { } -Vector2.prototype.isVector2 = true; - class Matrix3 { constructor() { + Matrix3.prototype.isMatrix3 = true; + this.elements = [ 1, 0, 0, @@ -1643,8 +1641,6 @@ class Matrix3 { } -Matrix3.prototype.isMatrix3 = true; - function arrayNeedsUint32( array ) { // assumes larger values usually on last @@ -1810,6 +1806,12 @@ class Color { constructor( r, g, b ) { + this.isColor = true; + + this.r = 1; + this.g = 1; + this.b = 1; + if ( g === undefined && b === undefined ) { // r is THREE.Color, hex or string @@ -2348,15 +2350,18 @@ class Color { } + *[ Symbol.iterator ]() { + + yield this.r; + yield this.g; + yield this.b; + + } + } Color.NAMES = _colorKeywords; -Color.prototype.isColor = true; -Color.prototype.r = 1; -Color.prototype.g = 1; -Color.prototype.b = 1; - let _canvas; class ImageUtils { @@ -2486,6 +2491,8 @@ class Source { constructor( data = null ) { + this.isSource = true; + this.uuid = generateUUID$1(); this.data = data; @@ -2582,7 +2589,7 @@ function serializeImage( image ) { // images of DataTexture return { - data: Array.prototype.slice.call( image.data ), + data: Array.from( image.data ), width: image.width, height: image.height, type: image.data.constructor.name @@ -2599,8 +2606,6 @@ function serializeImage( image ) { } -Source.prototype.isSource = true; - let textureId = 0; class Texture extends EventDispatcher { @@ -2609,6 +2614,8 @@ class Texture extends EventDispatcher { super(); + this.isTexture = true; + Object.defineProperty( this, 'id', { value: textureId ++ } ); this.uuid = generateUUID$1(); @@ -2889,12 +2896,12 @@ class Texture extends EventDispatcher { Texture.DEFAULT_IMAGE = null; Texture.DEFAULT_MAPPING = UVMapping; -Texture.prototype.isTexture = true; - class Vector4 { constructor( x = 0, y = 0, z = 0, w = 1 ) { + Vector4.prototype.isVector4 = true; + this.x = x; this.y = y; this.z = z; @@ -3552,8 +3559,6 @@ class Vector4 { } -Vector4.prototype.isVector4 = true; - /* In options, we can specify: * Texture parameters for an auto-generated target texture @@ -3565,6 +3570,8 @@ class WebGLRenderTarget extends EventDispatcher { super(); + this.isWebGLRenderTarget = true; + this.width = width; this.height = height; this.depth = 1; @@ -3633,7 +3640,8 @@ class WebGLRenderTarget extends EventDispatcher { // ensure image object is not shared, see #20328 - this.texture.image = Object.assign( {}, source.texture.image ); + const image = Object.assign( {}, source.texture.image ); + this.texture.source = new Source( image ); this.depthBuffer = source.depthBuffer; this.stencilBuffer = source.stencilBuffer; @@ -3654,14 +3662,14 @@ class WebGLRenderTarget extends EventDispatcher { } -WebGLRenderTarget.prototype.isWebGLRenderTarget = true; - class DataArrayTexture extends Texture { constructor( data = null, width = 1, height = 1, depth = 1 ) { super( null ); + this.isDataArrayTexture = true; + this.image = { data, width, height, depth }; this.magFilter = NearestFilter; @@ -3677,14 +3685,14 @@ class DataArrayTexture extends Texture { } -DataArrayTexture.prototype.isDataArrayTexture = true; - class WebGLArrayRenderTarget extends WebGLRenderTarget { constructor( width, height, depth ) { super( width, height ); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; this.texture = new DataArrayTexture( null, width, height, depth ); @@ -3695,8 +3703,6 @@ class WebGLArrayRenderTarget extends WebGLRenderTarget { } -WebGLArrayRenderTarget.prototype.isWebGLArrayRenderTarget = true; - class Data3DTexture extends Texture { constructor( data = null, width = 1, height = 1, depth = 1 ) { @@ -3711,6 +3717,8 @@ class Data3DTexture extends Texture { super( null ); + this.isData3DTexture = true; + this.image = { data, width, height, depth }; this.magFilter = NearestFilter; @@ -3726,14 +3734,14 @@ class Data3DTexture extends Texture { } -Data3DTexture.prototype.isData3DTexture = true; - class WebGL3DRenderTarget extends WebGLRenderTarget { constructor( width, height, depth ) { super( width, height ); + this.isWebGL3DRenderTarget = true; + this.depth = depth; this.texture = new Data3DTexture( null, width, height, depth ); @@ -3744,14 +3752,14 @@ class WebGL3DRenderTarget extends WebGLRenderTarget { } -WebGL3DRenderTarget.prototype.isWebGL3DRenderTarget = true; - class WebGLMultipleRenderTargets extends WebGLRenderTarget { constructor( width, height, count, options = {} ) { super( width, height, options ); + this.isWebGLMultipleRenderTargets = true; + const texture = this.texture; this.texture = []; @@ -3805,13 +3813,15 @@ class WebGLMultipleRenderTargets extends WebGLRenderTarget { this.depthBuffer = source.depthBuffer; this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; + + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); this.texture.length = 0; for ( let i = 0, il = source.texture.length; i < il; i ++ ) { this.texture[ i ] = source.texture[ i ].clone(); + this.texture[ i ].isRenderTargetTexture = true; } @@ -3821,12 +3831,12 @@ class WebGLMultipleRenderTargets extends WebGLRenderTarget { } -WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true; - class Quaternion { constructor( x = 0, y = 0, z = 0, w = 1 ) { + this.isQuaternion = true; + this._x = x; this._y = y; this._z = z; @@ -4505,14 +4515,23 @@ class Quaternion { _onChangeCallback() {} -} + *[ Symbol.iterator ]() { -Quaternion.prototype.isQuaternion = true; + yield this._x; + yield this._y; + yield this._z; + yield this._w; + + } + +} class Vector3 { constructor( x = 0, y = 0, z = 0 ) { + Vector3.prototype.isVector3 = true; + this.x = x; this.y = y; this.z = z; @@ -5255,8 +5274,6 @@ class Vector3 { } -Vector3.prototype.isVector3 = true; - const _vector$c = /*@__PURE__*/ new Vector3(); const _quaternion$4 = /*@__PURE__*/ new Quaternion(); @@ -5264,6 +5281,8 @@ class Box3 { constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { + this.isBox3 = true; + this.min = min; this.max = max; @@ -5729,8 +5748,6 @@ class Box3 { } -Box3.prototype.isBox3 = true; - const _points = [ /*@__PURE__*/ new Vector3(), /*@__PURE__*/ new Vector3(), @@ -6510,6 +6527,8 @@ class Matrix4 { constructor() { + Matrix4.prototype.isMatrix4 = true; + this.elements = [ 1, 0, 0, 0, @@ -7378,8 +7397,6 @@ class Matrix4 { } -Matrix4.prototype.isMatrix4 = true; - const _v1$5 = /*@__PURE__*/ new Vector3(); const _m1$2 = /*@__PURE__*/ new Matrix4(); const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); @@ -7395,6 +7412,8 @@ class Euler { constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) { + this.isEuler = true; + this._x = x; this._y = y; this._z = z; @@ -7683,9 +7702,24 @@ class Euler { _onChangeCallback() {} -} + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._order; + + } + + // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53 -Euler.prototype.isEuler = true; + toVector3() { + + console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' ); + + } + +} Euler.DefaultOrder = 'XYZ'; Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; @@ -7772,6 +7806,8 @@ class Object3D extends EventDispatcher { super(); + this.isObject3D = true; + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); this.uuid = generateUUID$1(); @@ -8660,11 +8696,9 @@ class Object3D extends EventDispatcher { } -Object3D.DefaultUp = new Vector3( 0, 1, 0 ); +Object3D.DefaultUp = /*@__PURE__*/ new Vector3( 0, 1, 0 ); Object3D.DefaultMatrixAutoUpdate = true; -Object3D.prototype.isObject3D = true; - const _v0$1 = /*@__PURE__*/ new Vector3(); const _v1$3 = /*@__PURE__*/ new Vector3(); const _v2$2 = /*@__PURE__*/ new Vector3(); @@ -8969,6 +9003,8 @@ class Material extends EventDispatcher { super(); + this.isMaterial = true; + Object.defineProperty( this, 'id', { value: materialId ++ } ); this.uuid = generateUUID$1(); @@ -8976,8 +9012,6 @@ class Material extends EventDispatcher { this.name = ''; this.type = 'Material'; - this.fog = true; - this.blending = NormalBlending; this.side = FrontSide; this.vertexColors = false; @@ -9181,6 +9215,22 @@ class Material extends EventDispatcher { } + if ( this.iridescence !== undefined ) data.iridescence = this.iridescence; + if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR; + if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + + if ( this.iridescenceMap && this.iridescenceMap.isTexture ) { + + data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid; + + } + + if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) { + + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid; + + } + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid; if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; @@ -9309,6 +9359,8 @@ class Material extends EventDispatcher { if ( this.toneMapped === false ) data.toneMapped = false; + if ( this.fog === false ) data.fog = false; + if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData; // TODO: Copied from Object3D.toJSON @@ -9353,8 +9405,6 @@ class Material extends EventDispatcher { this.name = source.name; - this.fog = source.fog; - this.blending = source.blending; this.side = source.side; this.vertexColors = source.vertexColors; @@ -9442,22 +9492,14 @@ class Material extends EventDispatcher { } -Material.prototype.isMaterial = true; - -Material.fromType = function ( /*type*/ ) { - - // TODO: Behavior added in Materials.js - - return null; - -}; - class MeshBasicMaterial extends Material { constructor( parameters ) { super(); + this.isMeshBasicMaterial = true; + this.type = 'MeshBasicMaterial'; this.color = new Color( 0xffffff ); // emissive @@ -9484,6 +9526,8 @@ class MeshBasicMaterial extends Material { this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; + this.fog = true; + this.setValues( parameters ); } @@ -9516,14 +9560,14 @@ class MeshBasicMaterial extends Material { this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; } } -MeshBasicMaterial.prototype.isMeshBasicMaterial = true; - const _vector$9 = /*@__PURE__*/ new Vector3(); const _vector2$1 = /*@__PURE__*/ new Vector2(); @@ -9537,6 +9581,8 @@ class BufferAttribute { } + this.isBufferAttribute = true; + this.name = ''; this.array = array; @@ -9905,7 +9951,7 @@ class BufferAttribute { const data = { itemSize: this.itemSize, type: this.array.constructor.name, - array: Array.prototype.slice.call( this.array ), + array: Array.from( this.array ), normalized: this.normalized }; @@ -9919,8 +9965,6 @@ class BufferAttribute { } -BufferAttribute.prototype.isBufferAttribute = true; - // class Int8BufferAttribute extends BufferAttribute { @@ -9999,11 +10043,12 @@ class Float16BufferAttribute extends BufferAttribute { super( new Uint16Array( array ), itemSize, normalized ); + this.isFloat16BufferAttribute = true; + } } -Float16BufferAttribute.prototype.isFloat16BufferAttribute = true; class Float32BufferAttribute extends BufferAttribute { @@ -10027,9 +10072,9 @@ class Float64BufferAttribute extends BufferAttribute { let _id$1 = 0; -const _m1$3 = /*@__PURE__*/ new Matrix4(); -const _obj$1 = /*@__PURE__*/ new Object3D(); -const _offset$1 = /*@__PURE__*/ new Vector3(); +const _m1 = /*@__PURE__*/ new Matrix4(); +const _obj = /*@__PURE__*/ new Object3D(); +const _offset = /*@__PURE__*/ new Vector3(); const _box$1 = /*@__PURE__*/ new Box3(); const _boxMorphTargets = /*@__PURE__*/ new Box3(); const _vector$8 = /*@__PURE__*/ new Vector3(); @@ -10040,6 +10085,8 @@ class BufferGeometry extends EventDispatcher { super(); + this.isBufferGeometry = true; + Object.defineProperty( this, 'id', { value: _id$1 ++ } ); this.uuid = generateUUID$1(); @@ -10191,9 +10238,9 @@ class BufferGeometry extends EventDispatcher { applyQuaternion( q ) { - _m1$3.makeRotationFromQuaternion( q ); + _m1.makeRotationFromQuaternion( q ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10203,9 +10250,9 @@ class BufferGeometry extends EventDispatcher { // rotate geometry around world x-axis - _m1$3.makeRotationX( angle ); + _m1.makeRotationX( angle ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10215,9 +10262,9 @@ class BufferGeometry extends EventDispatcher { // rotate geometry around world y-axis - _m1$3.makeRotationY( angle ); + _m1.makeRotationY( angle ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10227,9 +10274,9 @@ class BufferGeometry extends EventDispatcher { // rotate geometry around world z-axis - _m1$3.makeRotationZ( angle ); + _m1.makeRotationZ( angle ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10239,9 +10286,9 @@ class BufferGeometry extends EventDispatcher { // translate geometry - _m1$3.makeTranslation( x, y, z ); + _m1.makeTranslation( x, y, z ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10251,9 +10298,9 @@ class BufferGeometry extends EventDispatcher { // scale geometry - _m1$3.makeScale( x, y, z ); + _m1.makeScale( x, y, z ); - this.applyMatrix4( _m1$3 ); + this.applyMatrix4( _m1 ); return this; @@ -10261,11 +10308,11 @@ class BufferGeometry extends EventDispatcher { lookAt( vector ) { - _obj$1.lookAt( vector ); + _obj.lookAt( vector ); - _obj$1.updateMatrix(); + _obj.updateMatrix(); - this.applyMatrix4( _obj$1.matrix ); + this.applyMatrix4( _obj.matrix ); return this; @@ -10275,9 +10322,9 @@ class BufferGeometry extends EventDispatcher { this.computeBoundingBox(); - this.boundingBox.getCenter( _offset$1 ).negate(); + this.boundingBox.getCenter( _offset ).negate(); - this.translate( _offset$1.x, _offset$1.y, _offset$1.z ); + this.translate( _offset.x, _offset.y, _offset.z ); return this; @@ -10457,8 +10504,8 @@ class BufferGeometry extends EventDispatcher { if ( morphTargetsRelative ) { - _offset$1.fromBufferAttribute( position, j ); - _vector$8.add( _offset$1 ); + _offset.fromBufferAttribute( position, j ); + _vector$8.add( _offset ); } @@ -11140,8 +11187,6 @@ class BufferGeometry extends EventDispatcher { } -BufferGeometry.prototype.isBufferGeometry = true; - const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4(); const _ray$2 = /*@__PURE__*/ new Ray(); const _sphere$3 = /*@__PURE__*/ new Sphere(); @@ -11171,6 +11216,8 @@ class Mesh extends Object3D { super(); + this.isMesh = true; + this.type = 'Mesh'; this.geometry = geometry; @@ -11180,9 +11227,9 @@ class Mesh extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); if ( source.morphTargetInfluences !== undefined ) { @@ -11207,43 +11254,29 @@ class Mesh extends Object3D { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); - - if ( keys.length > 0 ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + if ( keys.length > 0 ) { - if ( morphAttribute !== undefined ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( morphAttribute !== undefined ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - const name = morphAttribute[ m ].name || String( m ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - } else { - - const morphTargets = geometry.morphTargets; - - if ( morphTargets !== undefined && morphTargets.length > 0 ) { - - console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - - } - } } @@ -11280,128 +11313,124 @@ class Mesh extends Object3D { let intersection; - if ( geometry.isBufferGeometry ) { - - const index = geometry.index; - const position = geometry.attributes.position; - const morphPosition = geometry.morphAttributes.position; - const morphTargetsRelative = geometry.morphTargetsRelative; - const uv = geometry.attributes.uv; - const uv2 = geometry.attributes.uv2; - const groups = geometry.groups; - const drawRange = geometry.drawRange; - - if ( index !== null ) { + const index = geometry.index; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + const uv = geometry.attributes.uv; + const uv2 = geometry.attributes.uv2; + const groups = geometry.groups; + const drawRange = geometry.drawRange; - // indexed buffer geometry + if ( index !== null ) { - if ( Array.isArray( material ) ) { + // indexed buffer geometry - for ( let i = 0, il = groups.length; i < il; i ++ ) { + if ( Array.isArray( material ) ) { - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + for ( let i = 0, il = groups.length; i < il; i ++ ) { - const start = Math.max( group.start, drawRange.start ); - const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - for ( let j = start, jl = end; j < jl; j += 3 ) { + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); - const a = index.getX( j ); - const b = index.getX( j + 1 ); - const c = index.getX( j + 2 ); + for ( let j = start, jl = end; j < jl; j += 3 ) { - intersection = checkBufferGeometryIntersection$1( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = index.getX( j ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); - if ( intersection ) { + intersection = checkBufferGeometryIntersection$1( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); } } - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, il = end; i < il; i += 3 ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const a = index.getX( i ); - const b = index.getX( i + 1 ); - const c = index.getX( i + 2 ); + for ( let i = start, il = end; i < il; i += 3 ) { - intersection = checkBufferGeometryIntersection$1( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = index.getX( i ); + const b = index.getX( i + 1 ); + const c = index.getX( i + 2 ); - if ( intersection ) { + intersection = checkBufferGeometryIntersection$1( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); } } - } else if ( position !== undefined ) { + } - // non-indexed buffer geometry + } else if ( position !== undefined ) { - if ( Array.isArray( material ) ) { + // non-indexed buffer geometry - for ( let i = 0, il = groups.length; i < il; i ++ ) { + if ( Array.isArray( material ) ) { - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + for ( let i = 0, il = groups.length; i < il; i ++ ) { - const start = Math.max( group.start, drawRange.start ); - const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - for ( let j = start, jl = end; j < jl; j += 3 ) { + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); - const a = j; - const b = j + 1; - const c = j + 2; + for ( let j = start, jl = end; j < jl; j += 3 ) { - intersection = checkBufferGeometryIntersection$1( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = j; + const b = j + 1; + const c = j + 2; - if ( intersection ) { + intersection = checkBufferGeometryIntersection$1( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); } } - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, il = end; i < il; i += 3 ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); - const a = i; - const b = i + 1; - const c = i + 2; + for ( let i = start, il = end; i < il; i += 3 ) { - intersection = checkBufferGeometryIntersection$1( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = i; + const b = i + 1; + const c = i + 2; - if ( intersection ) { + intersection = checkBufferGeometryIntersection$1( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); } @@ -11409,18 +11438,12 @@ class Mesh extends Object3D { } - } else if ( geometry.isGeometry ) { - - console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - } } } -Mesh.prototype.isMesh = true; - function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) { let intersect; @@ -11789,6 +11812,8 @@ class ShaderMaterial extends Material { super(); + this.isShaderMaterial = true; + this.type = 'ShaderMaterial'; this.defines = {}; @@ -11854,6 +11879,7 @@ class ShaderMaterial extends Material { this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; this.lights = source.lights; this.clipping = source.clipping; @@ -11959,14 +11985,14 @@ class ShaderMaterial extends Material { } -ShaderMaterial.prototype.isShaderMaterial = true; - class Camera extends Object3D { constructor() { super(); + this.isCamera = true; + this.type = 'Camera'; this.matrixWorldInverse = new Matrix4(); @@ -12023,14 +12049,14 @@ class Camera extends Object3D { } -Camera.prototype.isCamera = true; - class PerspectiveCamera extends Camera { constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { super(); + this.isPerspectiveCamera = true; + this.type = 'PerspectiveCamera'; this.fov = fov; @@ -12252,8 +12278,6 @@ class PerspectiveCamera extends Camera { } -PerspectiveCamera.prototype.isPerspectiveCamera = true; - const fov = 90, aspect = 1; class CubeCamera extends Object3D { @@ -12321,11 +12345,9 @@ class CubeCamera extends Object3D { const currentRenderTarget = renderer.getRenderTarget(); - const currentOutputEncoding = renderer.outputEncoding; const currentToneMapping = renderer.toneMapping; const currentXrEnabled = renderer.xr.enabled; - renderer.outputEncoding = LinearEncoding; renderer.toneMapping = NoToneMapping; renderer.xr.enabled = false; @@ -12355,7 +12377,6 @@ class CubeCamera extends Object3D { renderer.setRenderTarget( currentRenderTarget ); - renderer.outputEncoding = currentOutputEncoding; renderer.toneMapping = currentToneMapping; renderer.xr.enabled = currentXrEnabled; @@ -12374,6 +12395,8 @@ class CubeTexture extends Texture { super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.isCubeTexture = true; + this.flipY = false; } @@ -12392,14 +12415,14 @@ class CubeTexture extends Texture { } -CubeTexture.prototype.isCubeTexture = true; - class WebGLCubeRenderTarget extends WebGLRenderTarget { constructor( size, options = {} ) { super( size, size, options ); + this.isWebGLCubeRenderTarget = true; + const image = { width: size, height: size, depth: 1 }; const images = [ image, image, image, image, image, image ]; @@ -12528,8 +12551,6 @@ class WebGLCubeRenderTarget extends WebGLRenderTarget { } -WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true; - const _vector1 = /*@__PURE__*/ new Vector3(); const _vector2 = /*@__PURE__*/ new Vector3(); const _normalMatrix = /*@__PURE__*/ new Matrix3(); @@ -12538,6 +12559,8 @@ class Plane { constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { + this.isPlane = true; + // normal is assumed to be normalized this.normal = normal; @@ -12729,12 +12752,10 @@ class Plane { } -Plane.prototype.isPlane = true; - const _sphere$2 = /*@__PURE__*/ new Sphere(); const _vector$7 = /*@__PURE__*/ new Vector3(); -class Frustum$1 { +class Frustum { constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) { @@ -13229,7 +13250,9 @@ var begin_vertex = "vec3 transformed = vec3( position );"; var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; -var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; +var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\nvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = mix(F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence);\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; + +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\nconst mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n);\nvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n vec3 sqrtF0 = sqrt( fresnel0 );\n return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n}\nvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n}\nfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n}\nvec3 evalSensitivity( float OPD, vec3 shift ) {\n float phase = 2.0 * PI * OPD * 1.0e-9;\n vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( -pow2( phase ) * var );\n xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[0] ) * exp( -4.5282e+09 * pow2( phase ) );\n xyz /= 1.0685e-7;\n vec3 srgb = XYZ_TO_REC709 * xyz;\n return srgb;\n}\nvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n vec3 I;\n float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n if ( cosTheta2Sq < 0.0 ) {\n return vec3( 1.0 );\n }\n float cosTheta2 = sqrt( cosTheta2Sq );\n float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n float R12 = F_Schlick( R0, 1.0, cosTheta1 );\n float R21 = R12;\n float T121 = 1.0 - R12;\n float phi12 = 0.0;\n if ( iridescenceIOR < outsideIOR ) phi12 = PI;\n float phi21 = PI - phi12;\n vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n vec3 phi23 = vec3( 0.0 );\n if ( baseIOR[0] < iridescenceIOR ) phi23[0] = PI;\n if ( baseIOR[1] < iridescenceIOR ) phi23[1] = PI;\n if ( baseIOR[2] < iridescenceIOR ) phi23[2] = PI;\n float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n vec3 phi = vec3( phi21 ) + phi23;\n vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n vec3 r123 = sqrt( R123 );\n vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n vec3 C0 = R12 + Rs;\n I = C0;\n vec3 Cm = Rs - T121;\n for ( int m = 1; m <= 2; ++m ) {\n Cm *= r123;\n vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n I += Cm * Sm;\n }\n return max( I, vec3( 0.0 ) );\n}\n#endif"; var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; @@ -13249,9 +13272,9 @@ var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\ var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; -var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; -var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 ) + 0.5;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; @@ -13305,11 +13328,11 @@ var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; -var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; -var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; -var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; +var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\nfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\nif ( material.iridescenceThickness == 0.0 ) {\n\tmaterial.iridescence = 0.0;\n} else {\n\tmaterial.iridescence = saturate( material.iridescence );\n}\nif ( material.iridescence > 0.0 ) {\n\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; @@ -13361,6 +13384,8 @@ var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 cle var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; @@ -13387,7 +13412,7 @@ var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; -var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif"; +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif"; var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; @@ -13465,7 +13490,7 @@ const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive; const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; -const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; @@ -13493,6 +13518,7 @@ const ShaderChunk = { begin_vertex: begin_vertex, beginnormal_vertex: beginnormal_vertex, bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, bumpmap_pars_fragment: bumpmap_pars_fragment, clipping_planes_fragment: clipping_planes_fragment, clipping_planes_pars_fragment: clipping_planes_pars_fragment, @@ -13558,6 +13584,7 @@ const ShaderChunk = { clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, output_fragment: output_fragment, packing: packing, premultiplied_alpha_fragment: premultiplied_alpha_fragment, @@ -13630,12 +13657,12 @@ const UniformsLib = { common: { - diffuse: { value: new Color( 0xffffff ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, map: { value: null }, - uvTransform: { value: new Matrix3() }, - uv2Transform: { value: new Matrix3() }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + uv2Transform: { value: /*@__PURE__*/ new Matrix3() }, alphaMap: { value: null }, alphaTest: { value: 0 } @@ -13688,7 +13715,7 @@ const UniformsLib = { normalmap: { normalMap: { value: null }, - normalScale: { value: new Vector2( 1, 1 ) } + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } }, @@ -13723,7 +13750,7 @@ const UniformsLib = { fogDensity: { value: 0.00025 }, fogNear: { value: 1 }, fogFar: { value: 2000 }, - fogColor: { value: new Color( 0xffffff ) } + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } }, @@ -13808,27 +13835,27 @@ const UniformsLib = { points: { - diffuse: { value: new Color( 0xffffff ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, size: { value: 1.0 }, scale: { value: 1.0 }, map: { value: null }, alphaMap: { value: null }, alphaTest: { value: 0 }, - uvTransform: { value: new Matrix3() } + uvTransform: { value: /*@__PURE__*/ new Matrix3() } }, sprite: { - diffuse: { value: new Color( 0xffffff ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, - center: { value: new Vector2( 0.5, 0.5 ) }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, rotation: { value: 0.0 }, map: { value: null }, alphaMap: { value: null }, alphaTest: { value: 0 }, - uvTransform: { value: new Matrix3() } + uvTransform: { value: /*@__PURE__*/ new Matrix3() } } @@ -13838,7 +13865,7 @@ const ShaderLib = { basic: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13854,7 +13881,7 @@ const ShaderLib = { lambert: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13864,7 +13891,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) } + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } } ] ), @@ -13875,7 +13902,7 @@ const ShaderLib = { phong: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13888,8 +13915,8 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) }, - specular: { value: new Color( 0x111111 ) }, + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, shininess: { value: 30 } } ] ), @@ -13901,7 +13928,7 @@ const ShaderLib = { standard: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, @@ -13915,7 +13942,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) }, + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, roughness: { value: 1.0 }, metalness: { value: 0.0 }, envMapIntensity: { value: 1 } // temporary @@ -13929,7 +13956,7 @@ const ShaderLib = { toon: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, @@ -13941,7 +13968,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) } + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } } ] ), @@ -13952,7 +13979,7 @@ const ShaderLib = { matcap: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, @@ -13970,7 +13997,7 @@ const ShaderLib = { points: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.points, UniformsLib.fog ] ), @@ -13982,7 +14009,7 @@ const ShaderLib = { dashed: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.fog, { @@ -13999,7 +14026,7 @@ const ShaderLib = { depth: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap ] ), @@ -14011,7 +14038,7 @@ const ShaderLib = { normal: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, @@ -14028,7 +14055,7 @@ const ShaderLib = { sprite: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.sprite, UniformsLib.fog ] ), @@ -14041,7 +14068,7 @@ const ShaderLib = { background: { uniforms: { - uvTransform: { value: new Matrix3() }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, t2D: { value: null }, }, @@ -14049,13 +14076,10 @@ const ShaderLib = { fragmentShader: ShaderChunk.background_frag }, - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ cube: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.envmap, { opacity: { value: 1.0 } @@ -14080,11 +14104,11 @@ const ShaderLib = { distanceRGBA: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap, { - referencePosition: { value: new Vector3() }, + referencePosition: { value: /*@__PURE__*/ new Vector3() }, nearDistance: { value: 1 }, farDistance: { value: 1000 } } @@ -14097,11 +14121,11 @@ const ShaderLib = { shadow: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.lights, UniformsLib.fog, { - color: { value: new Color( 0x00000 ) }, + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, opacity: { value: 1.0 } }, ] ), @@ -14115,31 +14139,37 @@ const ShaderLib = { ShaderLib.physical = { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ ShaderLib.standard.uniforms, { clearcoat: { value: 0 }, clearcoatMap: { value: null }, clearcoatRoughness: { value: 0 }, clearcoatRoughnessMap: { value: null }, - clearcoatNormalScale: { value: new Vector2( 1, 1 ) }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, clearcoatNormalMap: { value: null }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, sheen: { value: 0 }, - sheenColor: { value: new Color( 0x000000 ) }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, sheenColorMap: { value: null }, sheenRoughness: { value: 1 }, sheenRoughnessMap: { value: null }, transmission: { value: 0 }, transmissionMap: { value: null }, - transmissionSamplerSize: { value: new Vector2() }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, transmissionSamplerMap: { value: null }, thickness: { value: 0 }, thicknessMap: { value: null }, attenuationDistance: { value: 0 }, - attenuationColor: { value: new Color( 0x000000 ) }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, specularIntensity: { value: 1 }, specularIntensityMap: { value: null }, - specularColor: { value: new Color( 1, 1, 1 ) }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, specularColorMap: { value: null }, } ] ), @@ -14258,6 +14288,8 @@ function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipli } + boxMesh.layers.enableAll(); + // push to the pre-sorted opaque render list renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); @@ -14318,6 +14350,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipli } + planeMesh.layers.enableAll(); // push to the pre-sorted opaque render list renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); @@ -14391,9 +14424,9 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - updateBuffers = needsUpdate( geometry, index ); + updateBuffers = needsUpdate( object, geometry, program, index ); - if ( updateBuffers ) saveCache( geometry, index ); + if ( updateBuffers ) saveCache( object, geometry, program, index ); } else { @@ -14413,12 +14446,6 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - if ( object.isInstancedMesh === true ) { - - updateBuffers = true; - - } - if ( index !== null ) { attributes.update( index, 34963 ); @@ -14532,25 +14559,40 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - function needsUpdate( geometry, index ) { + function needsUpdate( object, geometry, program, index ) { const cachedAttributes = currentState.attributes; const geometryAttributes = geometry.attributes; let attributesNum = 0; - for ( const key in geometryAttributes ) { + const programAttributes = program.getAttributes(); - const cachedAttribute = cachedAttributes[ key ]; - const geometryAttribute = geometryAttributes[ key ]; + for ( const name in programAttributes ) { - if ( cachedAttribute === undefined ) return true; + const programAttribute = programAttributes[ name ]; - if ( cachedAttribute.attribute !== geometryAttribute ) return true; + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { - if ( cachedAttribute.data !== geometryAttribute.data ) return true; + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; - attributesNum ++; + } + + if ( cachedAttribute === undefined ) return true; + + if ( cachedAttribute.attribute !== geometryAttribute ) return true; + + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; + + attributesNum ++; + + } } @@ -14562,28 +14604,43 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - function saveCache( geometry, index ) { + function saveCache( object, geometry, program, index ) { const cache = {}; const attributes = geometry.attributes; let attributesNum = 0; - for ( const key in attributes ) { + const programAttributes = program.getAttributes(); - const attribute = attributes[ key ]; + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; - const data = {}; - data.attribute = attribute; + if ( programAttribute.location >= 0 ) { - if ( attribute.data ) { + let attribute = attributes[ name ]; - data.data = attribute.data; + if ( attribute === undefined ) { - } + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; + + } - cache[ key ] = data; + const data = {}; + data.attribute = attribute; - attributesNum ++; + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } } @@ -15401,6 +15458,8 @@ class OrthographicCamera extends Camera { super(); + this.isOrthographicCamera = true; + this.type = 'OrthographicCamera'; this.zoom = 1; @@ -15526,8 +15585,6 @@ class OrthographicCamera extends Camera { } -OrthographicCamera.prototype.isOrthographicCamera = true; - const LOD_MIN = 4; // The standard deviations (radians) associated with the extra mips. These are @@ -15540,7 +15597,7 @@ const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; // samples and exit early, but not recompile the shader. const MAX_SAMPLES = 20; -const _flatCamera$1 = /*@__PURE__*/ new OrthographicCamera(); +const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); const _clearColor = /*@__PURE__*/ new Color(); let _oldTarget = null; @@ -15752,7 +15809,7 @@ class PMREMGenerator { _allocateTargets() { const width = 3 * Math.max( this._cubeSize, 16 * 7 ); - const height = 4 * this._cubeSize - 32; + const height = 4 * this._cubeSize; const params = { magFilter: LinearFilter, @@ -15790,7 +15847,7 @@ class PMREMGenerator { _compileMaterial( material ) { const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); - this._renderer.compile( tmpMesh, _flatCamera$1 ); + this._renderer.compile( tmpMesh, _flatCamera ); } @@ -15923,7 +15980,7 @@ class PMREMGenerator { _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); renderer.setRenderTarget( cubeUVRenderTarget ); - renderer.render( mesh, _flatCamera$1 ); + renderer.render( mesh, _flatCamera ); } @@ -16057,7 +16114,7 @@ class PMREMGenerator { _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); renderer.setRenderTarget( targetOut ); - renderer.render( blurMesh, _flatCamera$1 ); + renderer.render( blurMesh, _flatCamera ); } @@ -16093,9 +16150,9 @@ function _createPlanes( lodMax ) { sigmas.push( sigma ); - const texelSize = 1.0 / ( sizeLod - 1 ); - const min = - texelSize / 2; - const max = 1 + texelSize / 2; + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; const cubeFaces = 6; @@ -16969,6 +17026,8 @@ function denormalize( morph, attribute ) { const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array; if ( array instanceof Int8Array ) denominator = 127; + else if ( array instanceof Uint8Array ) denominator = 255; + else if ( array instanceof Uint16Array ) denominator = 65535; else if ( array instanceof Int16Array ) denominator = 32767; else if ( array instanceof Int32Array ) denominator = 2147483647; else console.error( 'THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array ); @@ -17377,10 +17436,10 @@ function WebGLObjects( gl, geometries, attributes, info ) { * */ -const emptyTexture = new Texture(); -const emptyArrayTexture = new DataArrayTexture(); -const empty3dTexture = new Data3DTexture(); -const emptyCubeTexture = new CubeTexture(); +const emptyTexture = /*@__PURE__*/ new Texture(); +const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); +const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); +const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); // --- Utilities --- @@ -17397,7 +17456,7 @@ const mat2array = new Float32Array( 4 ); // Flattening for arrays of vectors and matrices -function flatten$1( array, nBlocks, blockSize ) { +function flatten( array, nBlocks, blockSize ) { const firstElem = array[ 0 ]; @@ -17432,7 +17491,7 @@ function flatten$1( array, nBlocks, blockSize ) { } -function arraysEqual$1( a, b ) { +function arraysEqual( a, b ) { if ( a.length !== b.length ) return false; @@ -17446,7 +17505,7 @@ function arraysEqual$1( a, b ) { } -function copyArray$2( a, b ) { +function copyArray( a, b ) { for ( let i = 0, l = b.length; i < l; i ++ ) { @@ -17517,11 +17576,11 @@ function setValueV2f( gl, v ) { } else { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform2fv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17557,11 +17616,11 @@ function setValueV3f( gl, v ) { } else { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform3fv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17586,11 +17645,11 @@ function setValueV4f( gl, v ) { } else { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform4fv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17605,21 +17664,21 @@ function setValueM2( gl, v ) { if ( elements === undefined ) { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniformMatrix2fv( this.addr, false, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } else { - if ( arraysEqual$1( cache, elements ) ) return; + if ( arraysEqual( cache, elements ) ) return; mat2array.set( elements ); gl.uniformMatrix2fv( this.addr, false, mat2array ); - copyArray$2( cache, elements ); + copyArray( cache, elements ); } @@ -17632,21 +17691,21 @@ function setValueM3( gl, v ) { if ( elements === undefined ) { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniformMatrix3fv( this.addr, false, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } else { - if ( arraysEqual$1( cache, elements ) ) return; + if ( arraysEqual( cache, elements ) ) return; mat3array.set( elements ); gl.uniformMatrix3fv( this.addr, false, mat3array ); - copyArray$2( cache, elements ); + copyArray( cache, elements ); } @@ -17659,21 +17718,21 @@ function setValueM4( gl, v ) { if ( elements === undefined ) { - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniformMatrix4fv( this.addr, false, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } else { - if ( arraysEqual$1( cache, elements ) ) return; + if ( arraysEqual( cache, elements ) ) return; mat4array.set( elements ); gl.uniformMatrix4fv( this.addr, false, mat4array ); - copyArray$2( cache, elements ); + copyArray( cache, elements ); } @@ -17699,11 +17758,11 @@ function setValueV2i( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform2iv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17711,11 +17770,11 @@ function setValueV3i( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform3iv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17723,11 +17782,11 @@ function setValueV4i( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform4iv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17751,11 +17810,11 @@ function setValueV2ui( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform2uiv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17763,11 +17822,11 @@ function setValueV3ui( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform3uiv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17775,11 +17834,11 @@ function setValueV4ui( gl, v ) { const cache = this.cache; - if ( arraysEqual$1( cache, v ) ) return; + if ( arraysEqual( cache, v ) ) return; gl.uniform4uiv( this.addr, v ); - copyArray$2( cache, v ); + copyArray( cache, v ); } @@ -17916,7 +17975,7 @@ function setValueV1fArray( gl, v ) { function setValueV2fArray( gl, v ) { - const data = flatten$1( v, this.size, 2 ); + const data = flatten( v, this.size, 2 ); gl.uniform2fv( this.addr, data ); @@ -17924,7 +17983,7 @@ function setValueV2fArray( gl, v ) { function setValueV3fArray( gl, v ) { - const data = flatten$1( v, this.size, 3 ); + const data = flatten( v, this.size, 3 ); gl.uniform3fv( this.addr, data ); @@ -17932,7 +17991,7 @@ function setValueV3fArray( gl, v ) { function setValueV4fArray( gl, v ) { - const data = flatten$1( v, this.size, 4 ); + const data = flatten( v, this.size, 4 ); gl.uniform4fv( this.addr, data ); @@ -17942,7 +18001,7 @@ function setValueV4fArray( gl, v ) { function setValueM2Array( gl, v ) { - const data = flatten$1( v, this.size, 4 ); + const data = flatten( v, this.size, 4 ); gl.uniformMatrix2fv( this.addr, false, data ); @@ -17950,7 +18009,7 @@ function setValueM2Array( gl, v ) { function setValueM3Array( gl, v ) { - const data = flatten$1( v, this.size, 9 ); + const data = flatten( v, this.size, 9 ); gl.uniformMatrix3fv( this.addr, false, data ); @@ -17958,7 +18017,7 @@ function setValueM3Array( gl, v ) { function setValueM4Array( gl, v ) { - const data = flatten$1( v, this.size, 16 ); + const data = flatten( v, this.size, 16 ); gl.uniformMatrix4fv( this.addr, false, data ); @@ -18143,64 +18202,62 @@ function getPureArraySetter( type ) { // --- Uniform Classes --- -function SingleUniform( id, activeInfo, addr ) { +class SingleUniform { - this.id = id; - this.addr = addr; - this.cache = []; - this.setValue = getSingularSetter( activeInfo.type ); + constructor( id, activeInfo, addr ) { - // this.path = activeInfo.name; // DEBUG + this.id = id; + this.addr = addr; + this.cache = []; + this.setValue = getSingularSetter( activeInfo.type ); -} - -function PureArrayUniform( id, activeInfo, addr ) { + // this.path = activeInfo.name; // DEBUG - this.id = id; - this.addr = addr; - this.cache = []; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); - - // this.path = activeInfo.name; // DEBUG + } } -PureArrayUniform.prototype.updateCache = function ( data ) { +class PureArrayUniform { - const cache = this.cache; + constructor( id, activeInfo, addr ) { - if ( data instanceof Float32Array && cache.length !== data.length ) { + this.id = id; + this.addr = addr; + this.cache = []; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - this.cache = new Float32Array( data.length ); + // this.path = activeInfo.name; // DEBUG } - copyArray$2( cache, data ); +} -}; +class StructuredUniform { -function StructuredUniform( id ) { + constructor( id ) { - this.id = id; + this.id = id; - this.seq = []; - this.map = {}; + this.seq = []; + this.map = {}; -} + } + + setValue( gl, value, textures ) { -StructuredUniform.prototype.setValue = function ( gl, value, textures ) { + const seq = this.seq; - const seq = this.seq; + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); - const u = seq[ i ]; - u.setValue( gl, value[ u.id ], textures ); + } } -}; +} // --- Top-level --- @@ -18277,75 +18334,76 @@ function parseUniform( activeInfo, addr, container ) { // Root Container -function WebGLUniforms( gl, program ) { +class WebGLUniforms { - this.seq = []; - this.map = {}; + constructor( gl, program ) { - const n = gl.getProgramParameter( program, 35718 ); + this.seq = []; + this.map = {}; - for ( let i = 0; i < n; ++ i ) { + const n = gl.getProgramParameter( program, 35718 ); - const info = gl.getActiveUniform( program, i ), - addr = gl.getUniformLocation( program, info.name ); + for ( let i = 0; i < n; ++ i ) { - parseUniform( info, addr, this ); + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); - } + parseUniform( info, addr, this ); -} + } -WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) { + } - const u = this.map[ name ]; + setValue( gl, name, value, textures ) { - if ( u !== undefined ) u.setValue( gl, value, textures ); + const u = this.map[ name ]; -}; + if ( u !== undefined ) u.setValue( gl, value, textures ); -WebGLUniforms.prototype.setOptional = function ( gl, object, name ) { + } - const v = object[ name ]; + setOptional( gl, object, name ) { - if ( v !== undefined ) this.setValue( gl, name, v ); + const v = object[ name ]; -}; + if ( v !== undefined ) this.setValue( gl, name, v ); + } -// Static interface + static upload( gl, seq, values, textures ) { -WebGLUniforms.upload = function ( gl, seq, values, textures ) { + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + const u = seq[ i ], + v = values[ u.id ]; - const u = seq[ i ], - v = values[ u.id ]; + if ( v.needsUpdate !== false ) { - if ( v.needsUpdate !== false ) { + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); - // note: always updating when .needsUpdate is undefined - u.setValue( gl, v.value, textures ); + } } } -}; + static seqWithValue( seq, values ) { + + const r = []; -WebGLUniforms.seqWithValue = function ( seq, values ) { + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - const r = []; + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + } - const u = seq[ i ]; - if ( u.id in values ) r.push( u ); + return r; } - return r; - -}; +} function WebGLShader( gl, type, string ) { @@ -18370,7 +18428,8 @@ function handleSource( string, errorLine ) { for ( let i = from; i < to; i ++ ) { - lines2.push( ( i + 1 ) + ': ' + lines[ i ] ); + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); } @@ -18401,12 +18460,20 @@ function getShaderErrors( gl, shader, type ) { if ( status && errors === '' ) return ''; - const errorLine = parseInt( /ERROR: 0:(\d+)/.exec( errors )[ 1 ] ); + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { - // --enable-privileged-webgl-extension - // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + + } else { + + return errors; + + } } @@ -18728,7 +18795,7 @@ function generateCubeUVSize( parameters ) { if ( imageHeight === null ) return null; - const maxMip = Math.log2( imageHeight / 32 + 1 ) + 3; + const maxMip = Math.log2( imageHeight ) - 2; const texelHeight = 1.0 / imageHeight; @@ -18807,7 +18874,6 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - '#define MAX_BONES ' + parameters.maxBones, ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', @@ -18826,6 +18892,9 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', @@ -18852,7 +18921,6 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', @@ -18982,6 +19050,10 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', @@ -19038,7 +19110,7 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ), - parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n' @@ -19372,8 +19444,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities const isWebGL2 = capabilities.isWebGL2; const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; - const floatVertexTextures = capabilities.floatVertexTextures; - const maxVertexUniforms = capabilities.maxVertexUniforms; const vertexTextures = capabilities.vertexTextures; let precision = capabilities.precision; @@ -19395,42 +19465,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities SpriteMaterial: 'sprite' }; - function getMaxBones( object ) { - - const skeleton = object.skeleton; - const bones = skeleton.bones; - - if ( floatVertexTextures ) { - - return 1024; - - } else { - - // default for when object is not specified - // ( for example when prebuilding shader to be used with multiple objects ) - // - // - leave some extra space for other uniforms - // - limit here is ANGLE's 254 max uniform vectors - // (up to 54 should be safe) - - const nVertexUniforms = maxVertexUniforms; - const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - - const maxBones = Math.min( nVertexMatrices, bones.length ); - - if ( maxBones < bones.length ) { - - console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' ); - return 0; - - } - - return maxBones; - - } - - } - function getParameters( material, lights, shadows, scene, object ) { const fog = scene.fog; @@ -19445,8 +19479,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities // heuristics to create shader parameters according to lights in the scene // (not to blow over maxLights budget) - const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0; - if ( material.precision !== null ) { precision = capabilities.getMaxPrecision( material.precision ); @@ -19498,6 +19530,7 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities const useAlphaTest = material.alphaTest > 0; const useClearcoat = material.clearcoat > 0; + const useIridescence = material.iridescence > 0; const parameters = { @@ -19543,6 +19576,10 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap, clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap, + iridescence: useIridescence, + iridescenceMap: useIridescence && !! material.iridescenceMap, + iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap, + displacementMap: !! material.displacementMap, roughnessMap: !! material.roughnessMap, metalnessMap: !! material.metalnessMap, @@ -19570,11 +19607,11 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ), vertexColors: material.vertexColors, vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, - vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap, - uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap, + vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap, + uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap, fog: !! fog, - useFog: material.fog, + useFog: material.fog === true, fogExp2: ( fog && fog.isFogExp2 ), flatShading: !! material.flatShading, @@ -19582,9 +19619,7 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities sizeAttenuation: material.sizeAttenuation, logarithmicDepthBuffer: logarithmicDepthBuffer, - skinning: object.isSkinnedMesh === true && maxBones > 0, - maxBones: maxBones, - useVertexTexture: floatVertexTextures, + skinning: object.isSkinnedMesh === true, morphTargets: geometry.morphAttributes.position !== undefined, morphNormals: geometry.morphAttributes.normal !== undefined, @@ -19618,7 +19653,8 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities doubleSided: material.side === DoubleSide, flipSided: material.side === BackSide, - depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false, + useDepthPacking: !! material.depthPacking, + depthPacking: material.depthPacking || 0, index0AttributeName: material.index0AttributeName, @@ -19689,7 +19725,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities array.push( parameters.vertexUvs ); array.push( parameters.fogExp2 ); array.push( parameters.sizeAttenuation ); - array.push( parameters.maxBones ); array.push( parameters.morphTargetsCount ); array.push( parameters.morphAttributeCount ); array.push( parameters.numDirLights ); @@ -19704,6 +19739,7 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities array.push( parameters.toneMapping ); array.push( parameters.numClippingPlanes ); array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); } @@ -19747,32 +19783,38 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities _programLayers.enable( 16 ); if ( parameters.clearcoatNormalMap ) _programLayers.enable( 17 ); - if ( parameters.displacementMap ) + if ( parameters.iridescence ) _programLayers.enable( 18 ); - if ( parameters.specularMap ) + if ( parameters.iridescenceMap ) _programLayers.enable( 19 ); - if ( parameters.roughnessMap ) + if ( parameters.iridescenceThicknessMap ) _programLayers.enable( 20 ); - if ( parameters.metalnessMap ) + if ( parameters.displacementMap ) _programLayers.enable( 21 ); - if ( parameters.gradientMap ) + if ( parameters.specularMap ) _programLayers.enable( 22 ); - if ( parameters.alphaMap ) + if ( parameters.roughnessMap ) _programLayers.enable( 23 ); - if ( parameters.alphaTest ) + if ( parameters.metalnessMap ) _programLayers.enable( 24 ); - if ( parameters.vertexColors ) + if ( parameters.gradientMap ) _programLayers.enable( 25 ); - if ( parameters.vertexAlphas ) + if ( parameters.alphaMap ) _programLayers.enable( 26 ); - if ( parameters.vertexUvs ) + if ( parameters.alphaTest ) _programLayers.enable( 27 ); - if ( parameters.vertexTangents ) + if ( parameters.vertexColors ) _programLayers.enable( 28 ); - if ( parameters.uvsVertexOnly ) + if ( parameters.vertexAlphas ) _programLayers.enable( 29 ); - if ( parameters.fog ) + if ( parameters.vertexUvs ) _programLayers.enable( 30 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 31 ); + if ( parameters.uvsVertexOnly ) + _programLayers.enable( 32 ); + if ( parameters.fog ) + _programLayers.enable( 33 ); array.push( _programLayers.mask ); _programLayers.disableAll(); @@ -19785,48 +19827,46 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities _programLayers.enable( 2 ); if ( parameters.skinning ) _programLayers.enable( 3 ); - if ( parameters.useVertexTexture ) - _programLayers.enable( 4 ); if ( parameters.morphTargets ) - _programLayers.enable( 5 ); + _programLayers.enable( 4 ); if ( parameters.morphNormals ) - _programLayers.enable( 6 ); + _programLayers.enable( 5 ); if ( parameters.morphColors ) - _programLayers.enable( 7 ); + _programLayers.enable( 6 ); if ( parameters.premultipliedAlpha ) - _programLayers.enable( 8 ); + _programLayers.enable( 7 ); if ( parameters.shadowMapEnabled ) - _programLayers.enable( 9 ); + _programLayers.enable( 8 ); if ( parameters.physicallyCorrectLights ) - _programLayers.enable( 10 ); + _programLayers.enable( 9 ); if ( parameters.doubleSided ) - _programLayers.enable( 11 ); + _programLayers.enable( 10 ); if ( parameters.flipSided ) + _programLayers.enable( 11 ); + if ( parameters.useDepthPacking ) _programLayers.enable( 12 ); - if ( parameters.depthPacking ) - _programLayers.enable( 13 ); if ( parameters.dithering ) - _programLayers.enable( 14 ); + _programLayers.enable( 13 ); if ( parameters.specularIntensityMap ) - _programLayers.enable( 15 ); + _programLayers.enable( 14 ); if ( parameters.specularColorMap ) - _programLayers.enable( 16 ); + _programLayers.enable( 15 ); if ( parameters.transmission ) - _programLayers.enable( 17 ); + _programLayers.enable( 16 ); if ( parameters.transmissionMap ) - _programLayers.enable( 18 ); + _programLayers.enable( 17 ); if ( parameters.thicknessMap ) - _programLayers.enable( 19 ); + _programLayers.enable( 18 ); if ( parameters.sheen ) - _programLayers.enable( 20 ); + _programLayers.enable( 19 ); if ( parameters.sheenColorMap ) - _programLayers.enable( 21 ); + _programLayers.enable( 20 ); if ( parameters.sheenRoughnessMap ) - _programLayers.enable( 22 ); + _programLayers.enable( 21 ); if ( parameters.decodeVideoTexture ) - _programLayers.enable( 23 ); + _programLayers.enable( 22 ); if ( parameters.opaque ) - _programLayers.enable( 24 ); + _programLayers.enable( 23 ); array.push( _programLayers.mask ); @@ -20731,7 +20771,6 @@ function WebGLLights( extensions, capabilities ) { uniforms.direction.setFromMatrixPosition( light.matrixWorld ); uniforms.direction.transformDirection( viewMatrix ); - uniforms.direction.normalize(); hemiLength ++; @@ -20857,6 +20896,8 @@ class MeshDepthMaterial extends Material { super(); + this.isMeshDepthMaterial = true; + this.type = 'MeshDepthMaterial'; this.depthPacking = BasicDepthPacking; @@ -20872,8 +20913,6 @@ class MeshDepthMaterial extends Material { this.wireframe = false; this.wireframeLinewidth = 1; - this.fog = false; - this.setValues( parameters ); } @@ -20901,14 +20940,14 @@ class MeshDepthMaterial extends Material { } -MeshDepthMaterial.prototype.isMeshDepthMaterial = true; - class MeshDistanceMaterial extends Material { constructor( parameters ) { super(); + this.isMeshDistanceMaterial = true; + this.type = 'MeshDistanceMaterial'; this.referencePosition = new Vector3(); @@ -20923,8 +20962,6 @@ class MeshDistanceMaterial extends Material { this.displacementScale = 1; this.displacementBias = 0; - this.fog = false; - this.setValues( parameters ); } @@ -20951,15 +20988,13 @@ class MeshDistanceMaterial extends Material { } -MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true; - const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; function WebGLShadowMap( _renderer, _objects, _capabilities ) { - let _frustum = new Frustum$1(); + let _frustum = new Frustum(); const _shadowMapSize = new Vector2(), _viewportSize = new Vector2(), @@ -21076,20 +21111,9 @@ function WebGLShadowMap( _renderer, _objects, _capabilities ) { } - if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { - - shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); - shadow.map.texture.name = light.name + '.shadowMap'; - - shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); - - shadow.camera.updateProjectionMatrix(); - - } - if ( shadow.map === null ) { - const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; + const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); shadow.map.texture.name = light.name + '.shadowMap'; @@ -21126,7 +21150,7 @@ function WebGLShadowMap( _renderer, _objects, _capabilities ) { // do blur pass for VSM - if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { VSMPass( shadow, camera ); @@ -21156,6 +21180,12 @@ function WebGLShadowMap( _renderer, _objects, _capabilities ) { } + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + + } + // vertical pass shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; @@ -21192,7 +21222,7 @@ function WebGLShadowMap( _renderer, _objects, _capabilities ) { } - if ( ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) || + if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || ( material.displacementMap && material.displacementScale !== 0 ) || ( material.alphaMap && material.alphaTest > 0 ) ) { @@ -22865,7 +22895,17 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); - if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer ); + + if ( renderTargetProperties.__webglColorRenderbuffer ) { + + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { + + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + } + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); } @@ -23219,7 +23259,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, const mipmaps = texture.mipmaps; const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); - const allocateMemory = ( textureProperties.__version === undefined ); + const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true ); const levels = getMipLevels( texture, image, supportsMips ); if ( texture.isDepthTexture ) { @@ -23269,7 +23309,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); - texture.type = UnsignedShortType; + texture.type = UnsignedIntType; glType = utils.convert( texture.type ); } @@ -23298,13 +23338,17 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, // - if ( useTexStorage && allocateMemory ) { + if ( allocateMemory ) { - state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height ); + if ( useTexStorage ) { - } else { + state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height ); + + } else { + + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + } } @@ -23446,13 +23490,26 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } else if ( texture.isFramebufferTexture ) { - if ( useTexStorage && allocateMemory ) { + if ( allocateMemory ) { - state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); + if ( useTexStorage ) { - } else { + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + } else { + + let width = image.width, height = image.height; + + for ( let i = 0; i < levels; i ++ ) { + + state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null ); + + width >>= 1; + height >>= 1; + + } + + } } @@ -23573,7 +23630,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); - const allocateMemory = ( textureProperties.__version === undefined ); + const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true ); let levels = getMipLevels( texture, image, supportsMips ); setTextureParameters( 34067, texture, supportsMips ); @@ -23843,25 +23900,30 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } else { - // Use the first texture for MRT so far - const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture; + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; - const glFormat = utils.convert( texture.format, texture.encoding ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); - const samples = getRenderTargetSamples( renderTarget ); + for ( let i = 0; i < textures.length; i ++ ) { - if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + const texture = textures[ i ]; - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); - } else if ( useMultisampledRTT( renderTarget ) ) { + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { - multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - } else { + } else if ( useMultisampledRTT( renderTarget ) ) { - _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + + } } @@ -24061,21 +24123,34 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } - } else if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + } - renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); - renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer(); + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer ); + const textures = isMultipleRenderTargets ? texture : [ texture ]; - const glFormat = utils.convert( texture.format, texture.encoding ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); - const samples = getRenderTargetSamples( renderTarget ); - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); - _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); + + _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + _gl.bindRenderbuffer( 36161, null ); if ( renderTarget.depthBuffer ) { @@ -24206,47 +24281,103 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; const width = renderTarget.width; const height = renderTarget.height; let mask = 16384; - const invalidationArray = [ 36064 ]; + const invalidationArray = []; const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); - if ( renderTarget.depthBuffer ) { - - invalidationArray.push( depthStyle ); + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { - } + for ( let i = 0; i < textures.length; i ++ ) { - const renderTargetProperties = properties.get( renderTarget ); - const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null ); - if ( ignoreDepthValues === false ) { + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 ); - if ( renderTarget.depthBuffer ) mask |= 256; - if ( renderTarget.stencilBuffer ) mask |= 1024; + } } state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); - if ( ignoreDepthValues === true ) { + for ( let i = 0; i < textures.length; i ++ ) { - _gl.invalidateFramebuffer( 36008, [ depthStyle ] ); - _gl.invalidateFramebuffer( 36009, [ depthStyle ] ); + invalidationArray.push( 36064 + i ); - } + if ( renderTarget.depthBuffer ) { + + invalidationArray.push( depthStyle ); + + } + + const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; + + if ( ignoreDepthValues === false ) { + + if ( renderTarget.depthBuffer ) mask |= 256; + if ( renderTarget.stencilBuffer ) mask |= 1024; + + } + + if ( isMultipleRenderTargets ) { + + _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + if ( ignoreDepthValues === true ) { + + _gl.invalidateFramebuffer( 36008, [ depthStyle ] ); + _gl.invalidateFramebuffer( 36009, [ depthStyle ] ); + + } + + if ( isMultipleRenderTargets ) { + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 ); - _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); + } + + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); + + if ( supportsInvalidateFramebuffer ) { - if ( supportsInvalidateFramebuffer ) { + _gl.invalidateFramebuffer( 36008, invalidationArray ); + + } - _gl.invalidateFramebuffer( 36008, invalidationArray ); } state.bindFramebuffer( 36008, null ); + state.bindFramebuffer( 36009, null ); + + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 ); + + } + + } + state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer ); } @@ -24610,6 +24741,10 @@ function WebGLUtils( gl, extensions, capabilities ) { } + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) + + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; + } return { convert: convert }; @@ -24622,28 +24757,28 @@ class ArrayCamera extends PerspectiveCamera { super(); + this.isArrayCamera = true; + this.cameras = array; } } -ArrayCamera.prototype.isArrayCamera = true; - class Group extends Object3D { constructor() { super(); + this.isGroup = true; + this.type = 'Group'; } } -Group.prototype.isGroup = true; - const _moveEvent = { type: 'move' }; class WebXRController { @@ -24771,43 +24906,6 @@ class WebXRController { if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { - if ( targetRay !== null ) { - - inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); - - if ( inputPose !== null ) { - - targetRay.matrix.fromArray( inputPose.transform.matrix ); - targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); - - if ( inputPose.linearVelocity ) { - - targetRay.hasLinearVelocity = true; - targetRay.linearVelocity.copy( inputPose.linearVelocity ); - - } else { - - targetRay.hasLinearVelocity = false; - - } - - if ( inputPose.angularVelocity ) { - - targetRay.hasAngularVelocity = true; - targetRay.angularVelocity.copy( inputPose.angularVelocity ); - - } else { - - targetRay.hasAngularVelocity = false; - - } - - this.dispatchEvent( _moveEvent ); - - } - - } - if ( hand && inputSource.hand ) { handPose = true; @@ -24912,6 +25010,51 @@ class WebXRController { } + if ( targetRay !== null ) { + + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + + // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it + if ( inputPose === null && gripPose !== null ) { + + inputPose = gripPose; + + } + + if ( inputPose !== null ) { + + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); + + if ( inputPose.linearVelocity ) { + + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy( inputPose.linearVelocity ); + + } else { + + targetRay.hasLinearVelocity = false; + + } + + if ( inputPose.angularVelocity ) { + + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy( inputPose.angularVelocity ); + + } else { + + targetRay.hasAngularVelocity = false; + + } + + this.dispatchEvent( _moveEvent ); + + } + + } + + } if ( targetRay !== null ) { @@ -24950,26 +25093,26 @@ class DepthTexture extends Texture { } - if ( type === undefined && format === DepthFormat ) type = UnsignedShortType; + if ( type === undefined && format === DepthFormat ) type = UnsignedIntType; if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.isDepthTexture = true; + this.image = { width: width, height: height }; this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; this.flipY = false; - this.generateMipmaps = false; + this.generateMipmaps = false; } } -DepthTexture.prototype.isDepthTexture = true; - class WebXRManager extends EventDispatcher { constructor( renderer, gl ) { @@ -24983,6 +25126,7 @@ class WebXRManager extends EventDispatcher { let referenceSpace = null; let referenceSpaceType = 'local-floor'; + let customReferenceSpace = null; let pose = null; let glBinding = null; @@ -24994,7 +25138,7 @@ class WebXRManager extends EventDispatcher { let newRenderTarget = null; const controllers = []; - const inputSourcesMap = new Map(); + const controllerInputSources = []; // @@ -25071,9 +25215,17 @@ class WebXRManager extends EventDispatcher { function onSessionEvent( event ) { - const controller = inputSourcesMap.get( event.inputSource ); + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); + + if ( controllerIndex === - 1 ) { + + return; + + } + + const controller = controllers[ controllerIndex ]; - if ( controller ) { + if ( controller !== undefined ) { controller.dispatchEvent( { type: event.type, data: event.inputSource } ); @@ -25083,13 +25235,26 @@ class WebXRManager extends EventDispatcher { function onSessionEnd() { - inputSourcesMap.forEach( function ( controller, inputSource ) { + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); - controller.disconnect( inputSource ); + for ( let i = 0; i < controllers.length; i ++ ) { - } ); + const inputSource = controllerInputSources[ i ]; + + if ( inputSource === null ) continue; + + controllerInputSources[ i ] = null; - inputSourcesMap.clear(); + controllers[ i ].disconnect( inputSource ); + + } _currentDepthNear = null; _currentDepthFar = null; @@ -25140,7 +25305,13 @@ class WebXRManager extends EventDispatcher { this.getReferenceSpace = function () { - return referenceSpace; + return customReferenceSpace || referenceSpace; + + }; + + this.setReferenceSpace = function ( space ) { + + customReferenceSpace = space; }; @@ -25225,12 +25396,12 @@ class WebXRManager extends EventDispatcher { glDepthFormat = attributes.stencil ? 35056 : 33190; depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; - depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; } const projectionlayerInit = { - colorFormat: ( renderer.outputEncoding === sRGBEncoding ) ? 35907 : 32856, + colorFormat: 32856, depthFormat: glDepthFormat, scaleFactor: framebufferScaleFactor }; @@ -25263,6 +25434,7 @@ class WebXRManager extends EventDispatcher { // Set foveation to maximum. this.setFoveation( 1.0 ); + customReferenceSpace = null; referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); animation.setContext( session ); @@ -25278,27 +25450,17 @@ class WebXRManager extends EventDispatcher { function onInputSourcesChange( event ) { - const inputSources = session.inputSources; - - // Assign inputSources to available controllers - - for ( let i = 0; i < controllers.length; i ++ ) { - - inputSourcesMap.set( inputSources[ i ], controllers[ i ] ); - - } - // Notify disconnected for ( let i = 0; i < event.removed.length; i ++ ) { const inputSource = event.removed[ i ]; - const controller = inputSourcesMap.get( inputSource ); + const index = controllerInputSources.indexOf( inputSource ); - if ( controller ) { + if ( index >= 0 ) { - controller.dispatchEvent( { type: 'disconnected', data: inputSource } ); - inputSourcesMap.delete( inputSource ); + controllerInputSources[ index ] = null; + controllers[ index ].dispatchEvent( { type: 'disconnected', data: inputSource } ); } @@ -25309,7 +25471,38 @@ class WebXRManager extends EventDispatcher { for ( let i = 0; i < event.added.length; i ++ ) { const inputSource = event.added[ i ]; - const controller = inputSourcesMap.get( inputSource ); + + let controllerIndex = controllerInputSources.indexOf( inputSource ); + + if ( controllerIndex === - 1 ) { + + // Assign input source a controller that currently has no input source + + for ( let i = 0; i < controllers.length; i ++ ) { + + if ( i >= controllerInputSources.length ) { + + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + + } else if ( controllerInputSources[ i ] === null ) { + + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; + + } + + } + + // If all controllers do currently receive input we ignore new ones + + if ( controllerIndex === - 1 ) break; + + } + + const controller = controllers[ controllerIndex ]; if ( controller ) { @@ -25512,7 +25705,7 @@ class WebXRManager extends EventDispatcher { function onAnimationFrame( time, frame ) { - pose = frame.getViewerPose( referenceSpace ); + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); xrFrame = frame; if ( pose !== null ) { @@ -25566,7 +25759,16 @@ class WebXRManager extends EventDispatcher { } - const camera = cameras[ i ]; + let camera = cameras[ i ]; + + if ( camera === undefined ) { + + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; + + } camera.matrix.fromArray( view.transform.matrix ); camera.projectionMatrix.fromArray( view.projectionMatrix ); @@ -25590,14 +25792,16 @@ class WebXRManager extends EventDispatcher { // - const inputSources = session.inputSources; - for ( let i = 0; i < controllers.length; i ++ ) { + const inputSource = controllerInputSources[ i ]; const controller = controllers[ i ]; - const inputSource = inputSources[ i ]; - controller.update( inputSource, frame, referenceSpace ); + if ( inputSource !== null && controller !== undefined ) { + + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); + + } } @@ -25837,10 +26041,12 @@ function WebGLMaterials( renderer, properties ) { // 10. clearcoat map // 11. clearcoat normal map // 12. clearcoat roughnessMap map - // 13. specular intensity map - // 14. specular tint map - // 15. transmission map - // 16. thickness map + // 13. iridescence map + // 14. iridescence thickness map + // 15. specular intensity map + // 16. specular tint map + // 17. transmission map + // 18. thickness map let uvScaleMap; @@ -25892,6 +26098,14 @@ function WebGLMaterials( renderer, properties ) { uvScaleMap = material.clearcoatRoughnessMap; + } else if ( material.iridescenceMap ) { + + uvScaleMap = material.iridescenceMap; + + } else if ( material.iridescenceThicknessMap ) { + + uvScaleMap = material.iridescenceThicknessMap; + } else if ( material.specularIntensityMap ) { uvScaleMap = material.specularIntensityMap; @@ -26199,6 +26413,27 @@ function WebGLMaterials( renderer, properties ) { } + if ( material.iridescence > 0 ) { + + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; + + if ( material.iridescenceMap ) { + + uniforms.iridescenceMap.value = material.iridescenceMap; + + } + + if ( material.iridescenceThicknessMap ) { + + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + + } + + } + if ( material.transmission > 0 ) { uniforms.transmission.value = material.transmission; @@ -26276,6 +26511,8 @@ function createCanvasElement() { function WebGLRenderer( parameters = {} ) { + this.isWebGLRenderer = true; + const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), _context = parameters.context !== undefined ? parameters.context : null, @@ -26289,7 +26526,7 @@ function WebGLRenderer( parameters = {} ) { let _alpha; - if ( parameters.context !== undefined ) { + if ( _context !== null ) { _alpha = _context.getContextAttributes().alpha; @@ -26351,6 +26588,28 @@ function WebGLRenderer( parameters = {} ) { this.toneMapping = NoToneMapping; this.toneMappingExposure = 1.0; + // + + Object.defineProperties( this, { + + // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d + + gammaFactor: { + get: function () { + + console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); + return 2; + + }, + set: function () { + + console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); + + } + } + + } ); + // internal properties const _this = this; @@ -26385,7 +26644,7 @@ function WebGLRenderer( parameters = {} ) { // frustum - const _frustum = new Frustum$1(); + const _frustum = new Frustum(); // clipping @@ -26448,6 +26707,7 @@ function WebGLRenderer( parameters = {} ) { // event listeners must be registered before WebGL context is created, see #12753 _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); if ( _gl === null ) { @@ -26789,6 +27049,7 @@ function WebGLRenderer( parameters = {} ) { _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); renderLists.dispose(); renderStates.dispose(); @@ -26849,6 +27110,12 @@ function WebGLRenderer( parameters = {} ) { } + function onContextCreationError( event ) { + + console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); + + } + function onMaterialDispose( event ) { const material = event.target; @@ -27421,7 +27688,7 @@ function WebGLRenderer( parameters = {} ) { _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, { generateMipmaps: true, - type: utils.convert( HalfFloatType ) !== null ? HalfFloatType : UnsignedByteType, + type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType, minFilter: LinearMipmapLinearFilter, samples: ( isWebGL2 && _antialias === true ) ? 4 : 0 } ); @@ -27723,7 +27990,7 @@ function WebGLRenderer( parameters = {} ) { needsProgramChange = true; - } else if ( material.fog && materialProperties.fog !== fog ) { + } else if ( material.fog === true && materialProperties.fog !== fog ) { needsProgramChange = true; @@ -27895,7 +28162,7 @@ function WebGLRenderer( parameters = {} ) { } else { - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' ); } @@ -27940,7 +28207,7 @@ function WebGLRenderer( parameters = {} ) { // refresh uniforms common to several materials - if ( fog && material.fog ) { + if ( fog && material.fog === true ) { materials.refreshFogUniforms( m_uniforms, fog ); @@ -28227,13 +28494,6 @@ function WebGLRenderer( parameters = {} ) { this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { - if ( texture.isFramebufferTexture !== true ) { - - console.error( 'THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.' ); - return; - - } - const levelScale = Math.pow( 2, - level ); const width = Math.floor( texture.image.width * levelScale ); const height = Math.floor( texture.image.height * levelScale ); @@ -28371,7 +28631,23 @@ function WebGLRenderer( parameters = {} ) { this.initTexture = function ( texture ) { - textures.setTexture2D( texture, 0 ); + if ( texture.isCubeTexture ) { + + textures.setTextureCube( texture, 0 ); + + } else if ( texture.isData3DTexture ) { + + textures.setTexture3D( texture, 0 ); + + } else if ( texture.isDataArrayTexture ) { + + textures.setTexture2DArray( texture, 0 ); + + } else { + + textures.setTexture2D( texture, 0 ); + + } state.unbindTexture(); @@ -28396,8 +28672,6 @@ function WebGLRenderer( parameters = {} ) { } -WebGLRenderer.prototype.isWebGLRenderer = true; - class WebGL1Renderer extends WebGLRenderer {} WebGL1Renderer.prototype.isWebGL1Renderer = true; @@ -28406,6 +28680,8 @@ class FogExp2 { constructor( color, density = 0.00025 ) { + this.isFogExp2 = true; + this.name = ''; this.color = new Color( color ); @@ -28431,12 +28707,12 @@ class FogExp2 { } -FogExp2.prototype.isFogExp2 = true; - class Fog { constructor( color, near = 1, far = 1000 ) { + this.isFog = true; + this.name = ''; this.color = new Color( color ); @@ -28465,14 +28741,14 @@ class Fog { } -Fog.prototype.isFog = true; - class Scene$1 extends Object3D { constructor() { super(); + this.isScene = true; + this.type = 'Scene'; this.background = null; @@ -28520,12 +28796,12 @@ class Scene$1 extends Object3D { } -Scene$1.prototype.isScene = true; - class InterleavedBuffer { constructor( array, stride ) { + this.isInterleavedBuffer = true; + this.array = array; this.stride = stride; this.count = array !== undefined ? array.length / stride : 0; @@ -28644,7 +28920,7 @@ class InterleavedBuffer { if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { - data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) ); + data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) ); } @@ -28661,14 +28937,14 @@ class InterleavedBuffer { } -InterleavedBuffer.prototype.isInterleavedBuffer = true; - const _vector$6 = /*@__PURE__*/ new Vector3(); class InterleavedBufferAttribute { constructor( interleavedBuffer, itemSize, offset, normalized = false ) { + this.isInterleavedBufferAttribute = true; + this.name = ''; this.data = interleavedBuffer; @@ -28841,7 +29117,7 @@ class InterleavedBufferAttribute { if ( data === undefined ) { - console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' ); + console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.' ); const array = []; @@ -28883,7 +29159,7 @@ class InterleavedBufferAttribute { if ( data === undefined ) { - console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' ); + console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.' ); const array = []; @@ -28910,7 +29186,7 @@ class InterleavedBufferAttribute { } else { - // save as true interlaved attribtue + // save as true interleaved attribtue if ( data.interleavedBuffers === undefined ) { @@ -28938,14 +29214,14 @@ class InterleavedBufferAttribute { } -InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true; - class SpriteMaterial extends Material { constructor( parameters ) { super(); + this.isSpriteMaterial = true; + this.type = 'SpriteMaterial'; this.color = new Color( 0xffffff ); @@ -28960,6 +29236,8 @@ class SpriteMaterial extends Material { this.transparent = true; + this.fog = true; + this.setValues( parameters ); } @@ -28978,14 +29256,14 @@ class SpriteMaterial extends Material { this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; } } -SpriteMaterial.prototype.isSpriteMaterial = true; - let _geometry; const _intersectPoint = /*@__PURE__*/ new Vector3(); @@ -29010,6 +29288,8 @@ class Sprite extends Object3D { super(); + this.isSprite = true; + this.type = 'Sprite'; if ( _geometry === undefined ) { @@ -29113,9 +29393,9 @@ class Sprite extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); if ( source.center !== undefined ) this.center.copy( source.center ); @@ -29127,8 +29407,6 @@ class Sprite extends Object3D { } -Sprite.prototype.isSprite = true; - function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { // compute position in camera space @@ -29360,6 +29638,8 @@ class SkinnedMesh extends Mesh { super( geometry, material ); + this.isSkinnedMesh = true; + this.type = 'SkinnedMesh'; this.bindMode = 'attached'; @@ -29368,9 +29648,9 @@ class SkinnedMesh extends Mesh { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.bindMode = source.bindMode; this.bindMatrix.copy( source.bindMatrix ); @@ -29489,28 +29769,28 @@ class SkinnedMesh extends Mesh { } -SkinnedMesh.prototype.isSkinnedMesh = true; - class Bone extends Object3D { constructor() { super(); + this.isBone = true; + this.type = 'Bone'; } } -Bone.prototype.isBone = true; - class DataTexture extends Texture { constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) { super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.isDataTexture = true; + this.image = { data: data, width: width, height: height }; this.generateMipmaps = false; @@ -29521,8 +29801,6 @@ class DataTexture extends Texture { } -DataTexture.prototype.isDataTexture = true; - const _offsetMatrix = /*@__PURE__*/ new Matrix4(); const _identityMatrix = /*@__PURE__*/ new Matrix4(); @@ -29810,6 +30088,8 @@ class InstancedBufferAttribute extends BufferAttribute { super( array, itemSize, normalized ); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; } @@ -29838,14 +30118,12 @@ class InstancedBufferAttribute extends BufferAttribute { } -InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true; - const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4(); const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4(); const _instanceIntersects = []; -const _mesh$1 = /*@__PURE__*/ new Mesh(); +const _mesh = /*@__PURE__*/ new Mesh(); class InstancedMesh extends Mesh { @@ -29853,6 +30131,8 @@ class InstancedMesh extends Mesh { super( geometry, material ); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); this.instanceColor = null; @@ -29862,9 +30142,9 @@ class InstancedMesh extends Mesh { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.instanceMatrix.copy( source.instanceMatrix ); @@ -29893,10 +30173,10 @@ class InstancedMesh extends Mesh { const matrixWorld = this.matrixWorld; const raycastTimes = this.count; - _mesh$1.geometry = this.geometry; - _mesh$1.material = this.material; + _mesh.geometry = this.geometry; + _mesh.material = this.material; - if ( _mesh$1.material === undefined ) return; + if ( _mesh.material === undefined ) return; for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { @@ -29908,9 +30188,9 @@ class InstancedMesh extends Mesh { // the mesh represents this single instance - _mesh$1.matrixWorld = _instanceWorldMatrix; + _mesh.matrixWorld = _instanceWorldMatrix; - _mesh$1.raycast( raycaster, _instanceIntersects ); + _mesh.raycast( raycaster, _instanceIntersects ); // process the result of raycast @@ -29959,14 +30239,14 @@ class InstancedMesh extends Mesh { } -InstancedMesh.prototype.isInstancedMesh = true; - class LineBasicMaterial extends Material { constructor( parameters ) { super(); + this.isLineBasicMaterial = true; + this.type = 'LineBasicMaterial'; this.color = new Color( 0xffffff ); @@ -29975,6 +30255,8 @@ class LineBasicMaterial extends Material { this.linecap = 'round'; this.linejoin = 'round'; + this.fog = true; + this.setValues( parameters ); } @@ -29990,14 +30272,14 @@ class LineBasicMaterial extends Material { this.linecap = source.linecap; this.linejoin = source.linejoin; + this.fog = source.fog; + return this; } } -LineBasicMaterial.prototype.isLineBasicMaterial = true; - const _start$1 = /*@__PURE__*/ new Vector3(); const _end$1 = /*@__PURE__*/ new Vector3(); const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4(); @@ -30010,6 +30292,8 @@ class Line$2 extends Object3D { super(); + this.isLine = true; + this.type = 'Line'; this.geometry = geometry; @@ -30019,9 +30303,9 @@ class Line$2 extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.material = source.material; this.geometry = source.geometry; @@ -30034,36 +30318,28 @@ class Line$2 extends Object3D { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - // we assume non-indexed geometry - - if ( geometry.index === null ) { + // we assume non-indexed geometry - const positionAttribute = geometry.attributes.position; - const lineDistances = [ 0 ]; + if ( geometry.index === null ) { - for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [ 0 ]; - _start$1.fromBufferAttribute( positionAttribute, i - 1 ); - _end$1.fromBufferAttribute( positionAttribute, i ); + for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { - lineDistances[ i ] = lineDistances[ i - 1 ]; - lineDistances[ i ] += _start$1.distanceTo( _end$1 ); + _start$1.fromBufferAttribute( positionAttribute, i - 1 ); + _end$1.fromBufferAttribute( positionAttribute, i ); - } - - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); - - } else { - - console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _start$1.distanceTo( _end$1 ); } - } else if ( geometry.isGeometry ) { + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { - console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); } @@ -30102,91 +30378,83 @@ class Line$2 extends Object3D { const interRay = new Vector3(); const step = this.isLineSegments ? 2 : 1; - if ( geometry.isBufferGeometry ) { - - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; - - if ( index !== null ) { + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; - const start = Math.max( 0, drawRange.start ); - const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + if ( index !== null ) { - for ( let i = start, l = end - 1; i < l; i += step ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const a = index.getX( i ); - const b = index.getX( i + 1 ); + for ( let i = start, l = end - 1; i < l; i += step ) { - vStart.fromBufferAttribute( positionAttribute, a ); - vEnd.fromBufferAttribute( positionAttribute, b ); + const a = index.getX( i ); + const b = index.getX( i + 1 ); - const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + vStart.fromBufferAttribute( positionAttribute, a ); + vEnd.fromBufferAttribute( positionAttribute, b ); - if ( distSq > localThresholdSq ) continue; + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + if ( distSq > localThresholdSq ) continue; - const distance = raycaster.ray.origin.distanceTo( interRay ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - if ( distance < raycaster.near || distance > raycaster.far ) continue; + const distance = raycaster.ray.origin.distanceTo( interRay ); - intersects.push( { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + intersects.push( { - } ); + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - } + } ); - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, l = end - 1; i < l; i += step ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); - vStart.fromBufferAttribute( positionAttribute, i ); - vEnd.fromBufferAttribute( positionAttribute, i + 1 ); + for ( let i = start, l = end - 1; i < l; i += step ) { - const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + vStart.fromBufferAttribute( positionAttribute, i ); + vEnd.fromBufferAttribute( positionAttribute, i + 1 ); - if ( distSq > localThresholdSq ) continue; + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + if ( distSq > localThresholdSq ) continue; - const distance = raycaster.ray.origin.distanceTo( interRay ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - if ( distance < raycaster.near || distance > raycaster.far ) continue; + const distance = raycaster.ray.origin.distanceTo( interRay ); - intersects.push( { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + intersects.push( { - } ); + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - } + } ); } - } else if ( geometry.isGeometry ) { - - console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - } } @@ -30195,51 +30463,35 @@ class Line$2 extends Object3D { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); - - if ( keys.length > 0 ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + if ( keys.length > 0 ) { - if ( morphAttribute !== undefined ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( morphAttribute !== undefined ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - const name = morphAttribute[ m ].name || String( m ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - } else { - - const morphTargets = geometry.morphTargets; - - if ( morphTargets !== undefined && morphTargets.length > 0 ) { - - console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); - - } - } } } -Line$2.prototype.isLine = true; - const _start = /*@__PURE__*/ new Vector3(); const _end = /*@__PURE__*/ new Vector3(); @@ -30249,6 +30501,8 @@ class LineSegments extends Line$2 { super( geometry, material ); + this.isLineSegments = true; + this.type = 'LineSegments'; } @@ -30257,36 +30511,28 @@ class LineSegments extends Line$2 { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { + // we assume non-indexed geometry - // we assume non-indexed geometry + if ( geometry.index === null ) { - if ( geometry.index === null ) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; - const positionAttribute = geometry.attributes.position; - const lineDistances = []; + for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { - for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { - - _start.fromBufferAttribute( positionAttribute, i ); - _end.fromBufferAttribute( positionAttribute, i + 1 ); - - lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; - lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); - - } + _start.fromBufferAttribute( positionAttribute, i ); + _end.fromBufferAttribute( positionAttribute, i + 1 ); - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); - - } else { - - console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); } - } else if ( geometry.isGeometry ) { + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { - console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); } @@ -30296,28 +30542,28 @@ class LineSegments extends Line$2 { } -LineSegments.prototype.isLineSegments = true; - class LineLoop extends Line$2 { constructor( geometry, material ) { super( geometry, material ); + this.isLineLoop = true; + this.type = 'LineLoop'; } } -LineLoop.prototype.isLineLoop = true; - class PointsMaterial extends Material { constructor( parameters ) { super(); + this.isPointsMaterial = true; + this.type = 'PointsMaterial'; this.color = new Color( 0xffffff ); @@ -30329,6 +30575,8 @@ class PointsMaterial extends Material { this.size = 1; this.sizeAttenuation = true; + this.fog = true; + this.setValues( parameters ); } @@ -30346,14 +30594,14 @@ class PointsMaterial extends Material { this.size = source.size; this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; } } -PointsMaterial.prototype.isPointsMaterial = true; - const _inverseMatrix = /*@__PURE__*/ new Matrix4(); const _ray = /*@__PURE__*/ new Ray(); const _sphere = /*@__PURE__*/ new Sphere(); @@ -30365,6 +30613,8 @@ class Points extends Object3D { super(); + this.isPoints = true; + this.type = 'Points'; this.geometry = geometry; @@ -30374,9 +30624,9 @@ class Points extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.material = source.material; this.geometry = source.geometry; @@ -30410,46 +30660,38 @@ class Points extends Object3D { const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); const localThresholdSq = localThreshold * localThreshold; - if ( geometry.isBufferGeometry ) { - - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; - - if ( index !== null ) { + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; - const start = Math.max( 0, drawRange.start ); - const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + if ( index !== null ) { - for ( let i = start, il = end; i < il; i ++ ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const a = index.getX( i ); + for ( let i = start, il = end; i < il; i ++ ) { - _position$2.fromBufferAttribute( positionAttribute, a ); + const a = index.getX( i ); - testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + _position$2.fromBufferAttribute( positionAttribute, a ); - } + testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, l = end; i < l; i ++ ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); - _position$2.fromBufferAttribute( positionAttribute, i ); + for ( let i = start, l = end; i < l; i ++ ) { - testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + _position$2.fromBufferAttribute( positionAttribute, i ); - } + testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); } - } else { - - console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - } } @@ -30458,51 +30700,35 @@ class Points extends Object3D { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); - - if ( keys.length > 0 ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + if ( keys.length > 0 ) { - if ( morphAttribute !== undefined ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( morphAttribute !== undefined ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - const name = morphAttribute[ m ].name || String( m ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - } else { - - const morphTargets = geometry.morphTargets; - - if ( morphTargets !== undefined && morphTargets.length > 0 ) { - - console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); - - } - } } } -Points.prototype.isPoints = true; - function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { const rayPointDistanceSq = _ray.distanceSqToPoint( point ); @@ -30539,6 +30765,8 @@ class VideoTexture extends Texture { super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.isVideoTexture = true; + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; @@ -30582,14 +30810,14 @@ class VideoTexture extends Texture { } -VideoTexture.prototype.isVideoTexture = true; - class FramebufferTexture extends Texture { constructor( width, height, format ) { super( { width, height } ); + this.isFramebufferTexture = true; + this.format = format; this.magFilter = NearestFilter; @@ -30603,14 +30831,14 @@ class FramebufferTexture extends Texture { } -FramebufferTexture.prototype.isFramebufferTexture = true; - class CompressedTexture extends Texture { constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.isCompressedTexture = true; + this.image = { width: width, height: height }; this.mipmaps = mipmaps; @@ -30628,22 +30856,20 @@ class CompressedTexture extends Texture { } -CompressedTexture.prototype.isCompressedTexture = true; - class CanvasTexture extends Texture { constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.isCanvasTexture = true; + this.needsUpdate = true; } } -CanvasTexture.prototype.isCanvasTexture = true; - /** * Extensible curve object. * @@ -31059,6 +31285,8 @@ class EllipseCurve extends Curve { super(); + this.isEllipseCurve = true; + this.type = 'EllipseCurve'; this.aX = aX; @@ -31203,22 +31431,20 @@ class EllipseCurve extends Curve { } -EllipseCurve.prototype.isEllipseCurve = true; - class ArcCurve extends EllipseCurve { constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + this.isArcCurve = true; + this.type = 'ArcCurve'; } } -ArcCurve.prototype.isArcCurve = true; - /** * Centripetal CatmullRom Curve - which is useful for avoiding * cusps and self-intersections in non-uniform catmull rom curves. @@ -31296,8 +31522,10 @@ function CubicPoly() { // -const tmp = new Vector3(); -const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly(); +const tmp = /*@__PURE__*/ new Vector3(); +const px = /*@__PURE__*/ new CubicPoly(); +const py = /*@__PURE__*/ new CubicPoly(); +const pz = /*@__PURE__*/ new CubicPoly(); class CatmullRomCurve3 extends Curve { @@ -31305,6 +31533,8 @@ class CatmullRomCurve3 extends Curve { super(); + this.isCatmullRomCurve3 = true; + this.type = 'CatmullRomCurve3'; this.points = points; @@ -31466,8 +31696,6 @@ class CatmullRomCurve3 extends Curve { } -CatmullRomCurve3.prototype.isCatmullRomCurve3 = true; - /** * Bezier Curves formulas obtained from * https://en.wikipedia.org/wiki/B%C3%A9zier_curve @@ -31552,6 +31780,8 @@ class CubicBezierCurve extends Curve { super(); + this.isCubicBezierCurve = true; + this.type = 'CubicBezierCurve'; this.v0 = v0; @@ -31617,14 +31847,14 @@ class CubicBezierCurve extends Curve { } -CubicBezierCurve.prototype.isCubicBezierCurve = true; - class CubicBezierCurve3 extends Curve { constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { super(); + this.isCubicBezierCurve3 = true; + this.type = 'CubicBezierCurve3'; this.v0 = v0; @@ -31691,14 +31921,14 @@ class CubicBezierCurve3 extends Curve { } -CubicBezierCurve3.prototype.isCubicBezierCurve3 = true; - class LineCurve extends Curve { constructor( v1 = new Vector2(), v2 = new Vector2() ) { super(); + this.isLineCurve = true; + this.type = 'LineCurve'; this.v1 = v1; @@ -31777,17 +32007,16 @@ class LineCurve extends Curve { } -LineCurve.prototype.isLineCurve = true; - class LineCurve3 extends Curve { constructor( v1 = new Vector3(), v2 = new Vector3() ) { super(); - this.type = 'LineCurve3'; this.isLineCurve3 = true; + this.type = 'LineCurve3'; + this.v1 = v1; this.v2 = v2; @@ -31855,6 +32084,8 @@ class QuadraticBezierCurve extends Curve { super(); + this.isQuadraticBezierCurve = true; + this.type = 'QuadraticBezierCurve'; this.v0 = v0; @@ -31916,14 +32147,14 @@ class QuadraticBezierCurve extends Curve { } -QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true; - class QuadraticBezierCurve3 extends Curve { constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { super(); + this.isQuadraticBezierCurve3 = true; + this.type = 'QuadraticBezierCurve3'; this.v0 = v0; @@ -31986,14 +32217,14 @@ class QuadraticBezierCurve3 extends Curve { } -QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true; - class SplineCurve extends Curve { constructor( points = [] ) { super(); + this.isSplineCurve = true; + this.type = 'SplineCurve'; this.points = points; @@ -32078,8 +32309,6 @@ class SplineCurve extends Curve { } -SplineCurve.prototype.isSplineCurve = true; - var Curves = /*#__PURE__*/Object.freeze({ __proto__: null, ArcCurve: ArcCurve, @@ -32341,11 +32570,12 @@ class CurvePath extends Curve { } -class Path$1 extends CurvePath { +class Path extends CurvePath { constructor( points ) { super(); + this.type = 'Path'; this.currentPoint = new Vector2(); @@ -32701,7 +32931,7 @@ class CapsuleGeometry extends LatheGeometry { constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) { - const path = new Path$1(); + const path = new Path(); path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 ); path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 ); @@ -33471,10 +33701,10 @@ class DodecahedronGeometry extends PolyhedronGeometry { } -const _v0 = new Vector3(); -const _v1$1 = new Vector3(); -const _normal = new Vector3(); -const _triangle = new Triangle(); +const _v0 = /*@__PURE__*/ new Vector3(); +const _v1$1 = /*@__PURE__*/ new Vector3(); +const _normal = /*@__PURE__*/ new Vector3(); +const _triangle = /*@__PURE__*/ new Triangle(); class EdgesGeometry extends BufferGeometry { @@ -33605,7 +33835,7 @@ class EdgesGeometry extends BufferGeometry { } -class Shape extends Path$1 { +class Shape extends Path { constructor( points ) { @@ -33692,7 +33922,7 @@ class Shape extends Path$1 { for ( let i = 0, l = json.holes.length; i < l; i ++ ) { const hole = json.holes[ i ]; - this.holes.push( new Path$1().fromJSON( hole ) ); + this.holes.push( new Path().fromJSON( hole ) ); } @@ -33767,7 +33997,7 @@ function linkedList( data, start, end, dim, clockwise ) { } - if ( last && equals$1( last, last.next ) ) { + if ( last && equals( last, last.next ) ) { removeNode( last ); last = last.next; @@ -33790,7 +34020,7 @@ function filterPoints( start, end ) { again = false; - if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { removeNode( p ); p = end = p.prev; @@ -33969,7 +34199,7 @@ function cureLocalIntersections( start, triangles, dim ) { const a = p.prev, b = p.next.next; - if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { triangles.push( a.i / dim ); triangles.push( p.i / dim ); @@ -34298,7 +34528,7 @@ function isValidDiagonal( a, b ) { return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors - equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case } @@ -34310,7 +34540,7 @@ function area( p, q, r ) { } // check if two points are equal -function equals$1( p1, p2 ) { +function equals( p1, p2 ) { return p1.x === p2.x && p1.y === p2.y; @@ -34319,10 +34549,10 @@ function equals$1( p1, p2 ) { // check if two segments intersect function intersects( p1, q1, p2, q2 ) { - const o1 = sign$1( area( p1, q1, p2 ) ); - const o2 = sign$1( area( p1, q1, q2 ) ); - const o3 = sign$1( area( p2, q2, p1 ) ); - const o4 = sign$1( area( p2, q2, q1 ) ); + const o1 = sign( area( p1, q1, p2 ) ); + const o2 = sign( area( p1, q1, q2 ) ); + const o3 = sign( area( p2, q2, p1 ) ); + const o4 = sign( area( p2, q2, q1 ) ); if ( o1 !== o2 && o3 !== o4 ) return true; // general case @@ -34342,7 +34572,7 @@ function onSegment( p, q, r ) { } -function sign$1( num ) { +function sign( num ) { return num > 0 ? 1 : num < 0 ? - 1 : 0; @@ -34397,8 +34627,8 @@ function middleInside( a, b ) { // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon( a, b ) { - const a2 = new Node$1( a.i, a.x, a.y ), - b2 = new Node$1( b.i, b.x, b.y ), + const a2 = new Node( a.i, a.x, a.y ), + b2 = new Node( b.i, b.x, b.y ), an = a.next, bp = b.prev; @@ -34421,7 +34651,7 @@ function splitPolygon( a, b ) { // create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode( i, x, y, last ) { - const p = new Node$1( i, x, y ); + const p = new Node( i, x, y ); if ( ! last ) { @@ -34451,7 +34681,7 @@ function removeNode( p ) { } -function Node$1( i, x, y ) { +function Node( i, x, y ) { // vertex index in coordinates array this.i = i; @@ -35374,6 +35604,8 @@ function toJSON$1( shapes, options, data ) { } + data.options = Object.assign( {}, options ); + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); return data; @@ -36511,11 +36743,15 @@ class ShadowMaterial extends Material { super(); + this.isShadowMaterial = true; + this.type = 'ShadowMaterial'; this.color = new Color( 0x000000 ); this.transparent = true; + this.fog = true; + this.setValues( parameters ); } @@ -36526,34 +36762,36 @@ class ShadowMaterial extends Material { this.color.copy( source.color ); + this.fog = source.fog; + return this; } } -ShadowMaterial.prototype.isShadowMaterial = true; - class RawShaderMaterial extends ShaderMaterial { constructor( parameters ) { super( parameters ); + this.isRawShaderMaterial = true; + this.type = 'RawShaderMaterial'; } } -RawShaderMaterial.prototype.isRawShaderMaterial = true; - class MeshStandardMaterial extends Material { constructor( parameters ) { super(); + this.isMeshStandardMaterial = true; + this.defines = { 'STANDARD': '' }; this.type = 'MeshStandardMaterial'; @@ -36601,6 +36839,8 @@ class MeshStandardMaterial extends Material { this.flatShading = false; + this.fog = true; + this.setValues( parameters ); } @@ -36654,20 +36894,22 @@ class MeshStandardMaterial extends Material { this.flatShading = source.flatShading; + this.fog = source.fog; + return this; } } -MeshStandardMaterial.prototype.isMeshStandardMaterial = true; - class MeshPhysicalMaterial extends MeshStandardMaterial { constructor( parameters ) { super(); + this.isMeshPhysicalMaterial = true; + this.defines = { 'STANDARD': '', @@ -36698,6 +36940,11 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { } } ); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [ 100, 400 ]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color( 0x000000 ); this.sheenColorMap = null; this.sheenRoughness = 1.0; @@ -36717,6 +36964,7 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { this._sheen = 0.0; this._clearcoat = 0; + this._iridescence = 0; this._transmission = 0; this.setValues( parameters ); @@ -36759,6 +37007,24 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { } + get iridescence() { + + return this._iridescence; + + } + + set iridescence( value ) { + + if ( this._iridescence > 0 !== value > 0 ) { + + this.version ++; + + } + + this._iridescence = value; + + } + get transmission() { return this._transmission; @@ -36797,6 +37063,12 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; this.sheenColor.copy( source.sheenColor ); this.sheenColorMap = source.sheenColorMap; @@ -36822,14 +37094,14 @@ class MeshPhysicalMaterial extends MeshStandardMaterial { } -MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; - class MeshPhongMaterial extends Material { constructor( parameters ) { super(); + this.isMeshPhongMaterial = true; + this.type = 'MeshPhongMaterial'; this.color = new Color( 0xffffff ); // diffuse @@ -36875,6 +37147,8 @@ class MeshPhongMaterial extends Material { this.flatShading = false; + this.fog = true; + this.setValues( parameters ); } @@ -36926,20 +37200,22 @@ class MeshPhongMaterial extends Material { this.flatShading = source.flatShading; + this.fog = source.fog; + return this; } } -MeshPhongMaterial.prototype.isMeshPhongMaterial = true; - class MeshToonMaterial extends Material { constructor( parameters ) { super(); + this.isMeshToonMaterial = true; + this.defines = { 'TOON': '' }; this.type = 'MeshToonMaterial'; @@ -36977,6 +37253,8 @@ class MeshToonMaterial extends Material { this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; + this.fog = true; + this.setValues( parameters ); } @@ -37018,20 +37296,22 @@ class MeshToonMaterial extends Material { this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; } } -MeshToonMaterial.prototype.isMeshToonMaterial = true; - class MeshNormalMaterial extends Material { constructor( parameters ) { super(); + this.isMeshNormalMaterial = true; + this.type = 'MeshNormalMaterial'; this.bumpMap = null; @@ -37048,8 +37328,6 @@ class MeshNormalMaterial extends Material { this.wireframe = false; this.wireframeLinewidth = 1; - this.fog = false; - this.flatShading = false; this.setValues( parameters ); @@ -37082,14 +37360,14 @@ class MeshNormalMaterial extends Material { } -MeshNormalMaterial.prototype.isMeshNormalMaterial = true; - class MeshLambertMaterial extends Material { constructor( parameters ) { super(); + this.isMeshLambertMaterial = true; + this.type = 'MeshLambertMaterial'; this.color = new Color( 0xffffff ); // diffuse @@ -37120,6 +37398,8 @@ class MeshLambertMaterial extends Material { this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; + this.fog = true; + this.setValues( parameters ); } @@ -37156,20 +37436,22 @@ class MeshLambertMaterial extends Material { this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; } } -MeshLambertMaterial.prototype.isMeshLambertMaterial = true; - class MeshMatcapMaterial extends Material { constructor( parameters ) { super(); + this.isMeshMatcapMaterial = true; + this.defines = { 'MATCAP': '' }; this.type = 'MeshMatcapMaterial'; @@ -37195,6 +37477,8 @@ class MeshMatcapMaterial extends Material { this.flatShading = false; + this.fog = true; + this.setValues( parameters ); } @@ -37227,20 +37511,22 @@ class MeshMatcapMaterial extends Material { this.flatShading = source.flatShading; + this.fog = source.fog; + return this; } } -MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true; - class LineDashedMaterial extends LineBasicMaterial { constructor( parameters ) { super(); + this.isLineDashedMaterial = true; + this.type = 'LineDashedMaterial'; this.scale = 1; @@ -37265,35 +37551,6 @@ class LineDashedMaterial extends LineBasicMaterial { } -LineDashedMaterial.prototype.isLineDashedMaterial = true; - -const materialLib = { - ShadowMaterial, - SpriteMaterial, - RawShaderMaterial, - ShaderMaterial, - PointsMaterial, - MeshPhysicalMaterial, - MeshStandardMaterial, - MeshPhongMaterial, - MeshToonMaterial, - MeshNormalMaterial, - MeshLambertMaterial, - MeshDepthMaterial, - MeshDistanceMaterial, - MeshBasicMaterial, - MeshMatcapMaterial, - LineDashedMaterial, - LineBasicMaterial, - Material -}; - -Material.fromType = function ( type ) { - - return new materialLib[ type ](); - -}; - const AnimationUtils = { // same as Array.prototype.slice, but also works on typed arrays @@ -37715,7 +37972,7 @@ class Interpolant { i1 = pp.length; this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + return this.copySampleValue_( i1 - 1 ); } @@ -37763,7 +38020,7 @@ class Interpolant { // before start this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + return this.copySampleValue_( 0 ); } @@ -37820,7 +38077,7 @@ class Interpolant { if ( t0 === undefined ) { this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + return this.copySampleValue_( 0 ); } @@ -37828,7 +38085,7 @@ class Interpolant { i1 = pp.length; this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + return this.copySampleValue_( i1 - 1 ); } @@ -37886,11 +38143,6 @@ class Interpolant { } -// ALIAS DEFINITIONS - -Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_; -Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_; - /** * Fast and simple cubic spline interpolant. * @@ -40083,6 +40335,8 @@ class Light extends Object3D { super(); + this.isLight = true; + this.type = 'Light'; this.color = new Color( color ); @@ -40096,9 +40350,9 @@ class Light extends Object3D { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.color.copy( source.color ); this.intensity = source.intensity; @@ -40129,14 +40383,14 @@ class Light extends Object3D { } -Light.prototype.isLight = true; - class HemisphereLight extends Light { constructor( skyColor, groundColor, intensity ) { super( skyColor, intensity ); + this.isHemisphereLight = true; + this.type = 'HemisphereLight'; this.position.copy( Object3D.DefaultUp ); @@ -40146,9 +40400,9 @@ class HemisphereLight extends Light { } - copy( source ) { + copy( source, recursive ) { - Light.prototype.copy.call( this, source ); + super.copy( source, recursive ); this.groundColor.copy( source.groundColor ); @@ -40158,8 +40412,6 @@ class HemisphereLight extends Light { } -HemisphereLight.prototype.isHemisphereLight = true; - const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); const _lookTarget$1 = /*@__PURE__*/ new Vector3(); @@ -40184,7 +40436,7 @@ class LightShadow { this.autoUpdate = true; this.needsUpdate = false; - this._frustum = new Frustum$1(); + this._frustum = new Frustum(); this._frameExtents = new Vector2( 1, 1 ); this._viewportCount = 1; @@ -40307,6 +40559,8 @@ class SpotLightShadow extends LightShadow { super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + this.isSpotLightShadow = true; + this.focus = 1; } @@ -40344,14 +40598,14 @@ class SpotLightShadow extends LightShadow { } -SpotLightShadow.prototype.isSpotLightShadow = true; - class SpotLight extends Light { constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) { super( color, intensity ); + this.isSpotLight = true; + this.type = 'SpotLight'; this.position.copy( Object3D.DefaultUp ); @@ -40389,9 +40643,9 @@ class SpotLight extends Light { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.distance = source.distance; this.angle = source.angle; @@ -40408,8 +40662,6 @@ class SpotLight extends Light { } -SpotLight.prototype.isSpotLight = true; - const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); const _lightPositionWorld = /*@__PURE__*/ new Vector3(); const _lookTarget = /*@__PURE__*/ new Vector3(); @@ -40420,6 +40672,8 @@ class PointLightShadow extends LightShadow { super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + this.isPointLightShadow = true; + this._frameExtents = new Vector2( 4, 2 ); this._viewportCount = 6; @@ -40496,14 +40750,14 @@ class PointLightShadow extends LightShadow { } -PointLightShadow.prototype.isPointLightShadow = true; - class PointLight extends Light { constructor( color, intensity, distance = 0, decay = 1 ) { super( color, intensity ); + this.isPointLight = true; + this.type = 'PointLight'; this.distance = distance; @@ -40534,9 +40788,9 @@ class PointLight extends Light { } - copy( source ) { + copy( source, recursive ) { - super.copy( source ); + super.copy( source, recursive ); this.distance = source.distance; this.decay = source.decay; @@ -40549,26 +40803,26 @@ class PointLight extends Light { } -PointLight.prototype.isPointLight = true; - class DirectionalLightShadow extends LightShadow { constructor() { super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + this.isDirectionalLightShadow = true; + } } -DirectionalLightShadow.prototype.isDirectionalLightShadow = true; - class DirectionalLight$1 extends Light { constructor( color, intensity ) { super( color, intensity ); + this.isDirectionalLight = true; + this.type = 'DirectionalLight'; this.position.copy( Object3D.DefaultUp ); @@ -40599,28 +40853,28 @@ class DirectionalLight$1 extends Light { } -DirectionalLight$1.prototype.isDirectionalLight = true; - class AmbientLight$1 extends Light { constructor( color, intensity ) { super( color, intensity ); + this.isAmbientLight = true; + this.type = 'AmbientLight'; } } -AmbientLight$1.prototype.isAmbientLight = true; - class RectAreaLight extends Light { constructor( color, intensity, width = 10, height = 10 ) { super( color, intensity ); + this.isRectAreaLight = true; + this.type = 'RectAreaLight'; this.width = width; @@ -40666,8 +40920,6 @@ class RectAreaLight extends Light { } -RectAreaLight.prototype.isRectAreaLight = true; - /** * Primary reference: * https://graphics.stanford.edu/papers/envmap/envmap.pdf @@ -40682,6 +40934,8 @@ class SphericalHarmonics3 { constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; for ( let i = 0; i < 9; i ++ ) { @@ -40906,14 +41160,14 @@ class SphericalHarmonics3 { } -SphericalHarmonics3.prototype.isSphericalHarmonics3 = true; - class LightProbe extends Light { constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { super( undefined, intensity ); + this.isLightProbe = true; + this.sh = sh; } @@ -40949,8 +41203,6 @@ class LightProbe extends Light { } -LightProbe.prototype.isLightProbe = true; - class MaterialLoader extends Loader { constructor( manager ) { @@ -41010,7 +41262,7 @@ class MaterialLoader extends Loader { } - const material = Material.fromType( json.type ); + const material = MaterialLoader.createMaterialFromType( json.type ); if ( json.uuid !== undefined ) material.uuid = json.uuid; if ( json.name !== undefined ) material.name = json.name; @@ -41027,6 +41279,9 @@ class MaterialLoader extends Loader { if ( json.shininess !== undefined ) material.shininess = json.shininess; if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; + if ( json.iridescence !== undefined ) material.iridescence = json.iridescence; + if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR; + if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange; if ( json.transmission !== undefined ) material.transmission = json.transmission; if ( json.thickness !== undefined ) material.thickness = json.thickness; if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance; @@ -41227,6 +41482,9 @@ class MaterialLoader extends Loader { if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); + if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap ); + if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap ); + if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap ); if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap ); @@ -41244,6 +41502,33 @@ class MaterialLoader extends Loader { } + static createMaterialFromType( type ) { + + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + + return new materialLib[ type ](); + + } + } class LoaderUtils { @@ -41326,6 +41611,8 @@ class InstancedBufferGeometry extends BufferGeometry { super(); + this.isInstancedBufferGeometry = true; + this.type = 'InstancedBufferGeometry'; this.instanceCount = Infinity; @@ -41361,8 +41648,6 @@ class InstancedBufferGeometry extends BufferGeometry { } -InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true; - class BufferGeometryLoader extends Loader { constructor( manager ) { @@ -41682,7 +41967,7 @@ class ObjectLoader extends Loader { for ( const uuid in images ) { - if ( images[ uuid ] instanceof HTMLImageElement ) { + if ( images[ uuid ].data instanceof HTMLImageElement ) { hasImages = true; break; @@ -42640,6 +42925,8 @@ class ImageBitmapLoader extends Loader { super( manager ); + this.isImageBitmapLoader = true; + if ( typeof createImageBitmap === 'undefined' ) { console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); @@ -42727,8 +43014,6 @@ class ImageBitmapLoader extends Loader { } -ImageBitmapLoader.prototype.isImageBitmapLoader = true; - let _context; const AudioContext = { @@ -42813,6 +43098,8 @@ class HemisphereLightProbe extends LightProbe { super( undefined, intensity ); + this.isHemisphereLightProbe = true; + const color1 = new Color().set( skyColor ); const color2 = new Color().set( groundColor ); @@ -42830,14 +43117,14 @@ class HemisphereLightProbe extends LightProbe { } -HemisphereLightProbe.prototype.isHemisphereLightProbe = true; - class AmbientLightProbe extends LightProbe { constructor( color, intensity = 1 ) { super( undefined, intensity ); + this.isAmbientLightProbe = true; + const color1 = new Color().set( color ); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); @@ -42847,8 +43134,6 @@ class AmbientLightProbe extends LightProbe { } -AmbientLightProbe.prototype.isAmbientLightProbe = true; - const _eyeRight = /*@__PURE__*/ new Matrix4(); const _eyeLeft = /*@__PURE__*/ new Matrix4(); const _projectionMatrix = /*@__PURE__*/ new Matrix4(); @@ -44033,18 +44318,18 @@ const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must // be matched to parse the rest of the track name. -const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); +const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. -const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); +const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); // Object on target node, and accessor. May not contain reserved // characters. Accessor may contain any character except closing bracket. -const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); +const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); // Property and accessor. May not contain reserved characters. Accessor may // contain any non-bracket characters. -const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); +const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); const _trackRe = new RegExp( '' + '^' @@ -44595,26 +44880,16 @@ class PropertyBinding { } - if ( targetObject.geometry.isBufferGeometry ) { + if ( ! targetObject.geometry.morphAttributes ) { - if ( ! targetObject.geometry.morphAttributes ) { - - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); - return; - - } - - if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { - - propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; - - } + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); + return; + } - } else { + if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this ); - return; + propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; } @@ -44755,6 +45030,8 @@ class AnimationObjectGroup { constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID$1(); // cached objects followed by the active ones @@ -45103,8 +45380,6 @@ class AnimationObjectGroup { } -AnimationObjectGroup.prototype.isAnimationObjectGroup = true; - class AnimationAction { constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { @@ -45799,6 +46074,9 @@ class AnimationAction { } +const _controlInterpolantsResultBuffer = /*@__PURE__*/ new Float32Array( 1 ); + + class AnimationMixer extends EventDispatcher { constructor( root ) { @@ -46271,7 +46549,7 @@ class AnimationMixer extends EventDispatcher { interpolant = new LinearInterpolant( new Float32Array( 2 ), new Float32Array( 2 ), - 1, this._controlInterpolantsResultBuffer ); + 1, _controlInterpolantsResultBuffer ); interpolant.__cacheIndex = lastActiveIndex; interpolants[ lastActiveIndex ] = interpolant; @@ -46556,8 +46834,6 @@ class AnimationMixer extends EventDispatcher { } -AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 ); - class Uniform { constructor( value ) { @@ -46587,6 +46863,8 @@ class InstancedInterleavedBuffer extends InterleavedBuffer { super( array, stride ); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; } @@ -46624,12 +46902,12 @@ class InstancedInterleavedBuffer extends InterleavedBuffer { } -InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true; - class GLBufferAttribute { constructor( buffer, type, itemSize, elementSize, count ) { + this.isGLBufferAttribute = true; + this.buffer = buffer; this.type = type; this.itemSize = itemSize; @@ -46681,8 +46959,6 @@ class GLBufferAttribute { } -GLBufferAttribute.prototype.isGLBufferAttribute = true; - class Raycaster { constructor( origin, direction, near = 0, far = Infinity ) { @@ -46938,6 +47214,8 @@ class Box2 { constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { + this.isBox2 = true; + this.min = min; this.max = max; @@ -47130,8 +47408,6 @@ class Box2 { } -Box2.prototype.isBox2 = true; - const _startP = /*@__PURE__*/ new Vector3(); const _startEnd = /*@__PURE__*/ new Vector3(); @@ -47366,9 +47642,10 @@ class SkeletonHelper extends LineSegments { super( geometry, material ); - this.type = 'SkeletonHelper'; this.isSkeletonHelper = true; + this.type = 'SkeletonHelper'; + this.root = object; this.bones = bones; @@ -47813,72 +48090,64 @@ class CameraHelper extends LineSegments { const pointMap = {}; - // colors - - const colorFrustum = new Color( 0xffaa00 ); - const colorCone = new Color( 0xff0000 ); - const colorUp = new Color( 0x00aaff ); - const colorTarget = new Color( 0xffffff ); - const colorCross = new Color( 0x333333 ); - // near - addLine( 'n1', 'n2', colorFrustum ); - addLine( 'n2', 'n4', colorFrustum ); - addLine( 'n4', 'n3', colorFrustum ); - addLine( 'n3', 'n1', colorFrustum ); + addLine( 'n1', 'n2' ); + addLine( 'n2', 'n4' ); + addLine( 'n4', 'n3' ); + addLine( 'n3', 'n1' ); // far - addLine( 'f1', 'f2', colorFrustum ); - addLine( 'f2', 'f4', colorFrustum ); - addLine( 'f4', 'f3', colorFrustum ); - addLine( 'f3', 'f1', colorFrustum ); + addLine( 'f1', 'f2' ); + addLine( 'f2', 'f4' ); + addLine( 'f4', 'f3' ); + addLine( 'f3', 'f1' ); // sides - addLine( 'n1', 'f1', colorFrustum ); - addLine( 'n2', 'f2', colorFrustum ); - addLine( 'n3', 'f3', colorFrustum ); - addLine( 'n4', 'f4', colorFrustum ); + addLine( 'n1', 'f1' ); + addLine( 'n2', 'f2' ); + addLine( 'n3', 'f3' ); + addLine( 'n4', 'f4' ); // cone - addLine( 'p', 'n1', colorCone ); - addLine( 'p', 'n2', colorCone ); - addLine( 'p', 'n3', colorCone ); - addLine( 'p', 'n4', colorCone ); + addLine( 'p', 'n1' ); + addLine( 'p', 'n2' ); + addLine( 'p', 'n3' ); + addLine( 'p', 'n4' ); // up - addLine( 'u1', 'u2', colorUp ); - addLine( 'u2', 'u3', colorUp ); - addLine( 'u3', 'u1', colorUp ); + addLine( 'u1', 'u2' ); + addLine( 'u2', 'u3' ); + addLine( 'u3', 'u1' ); // target - addLine( 'c', 't', colorTarget ); - addLine( 'p', 'c', colorCross ); + addLine( 'c', 't' ); + addLine( 'p', 'c' ); // cross - addLine( 'cn1', 'cn2', colorCross ); - addLine( 'cn3', 'cn4', colorCross ); + addLine( 'cn1', 'cn2' ); + addLine( 'cn3', 'cn4' ); - addLine( 'cf1', 'cf2', colorCross ); - addLine( 'cf3', 'cf4', colorCross ); + addLine( 'cf1', 'cf2' ); + addLine( 'cf3', 'cf4' ); - function addLine( a, b, color ) { + function addLine( a, b ) { - addPoint( a, color ); - addPoint( b, color ); + addPoint( a ); + addPoint( b ); } - function addPoint( id, color ) { + function addPoint( id ) { vertices.push( 0, 0, 0 ); - colors.push( color.r, color.g, color.b ); + colors.push( 0, 0, 0 ); if ( pointMap[ id ] === undefined ) { @@ -47907,6 +48176,73 @@ class CameraHelper extends LineSegments { this.update(); + // colors + + const colorFrustum = new Color( 0xffaa00 ); + const colorCone = new Color( 0xff0000 ); + const colorUp = new Color( 0x00aaff ); + const colorTarget = new Color( 0xffffff ); + const colorCross = new Color( 0x333333 ); + + this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross ); + + } + + setColors( frustum, cone, up, target, cross ) { + + const geometry = this.geometry; + + const colorAttribute = geometry.getAttribute( 'color' ); + + // near + + colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2 + colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4 + colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3 + colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1 + + // far + + colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2 + colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4 + colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3 + colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1 + + // sides + + colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1 + colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2 + colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3 + colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4 + + // cone + + colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1 + colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2 + colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3 + colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4 + + // up + + colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2 + colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3 + colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1 + + // target + + colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t + colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c + + // cross + + colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2 + colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4 + + colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2 + colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4 + + colorAttribute.needsUpdate = true; + } update() { @@ -48079,9 +48415,9 @@ class BoxHelper extends LineSegments { } - copy( source ) { + copy( source, recursive ) { - LineSegments.prototype.copy.call( this, source ); + super.copy( source, recursive ); this.object = source.object; @@ -48349,7 +48685,7 @@ class ShapePath { moveTo( x, y ) { - this.currentPath = new Path$1(); + this.currentPath = new Path(); this.subPaths.push( this.currentPath ); this.currentPath.moveTo( x, y ); @@ -48623,100277 +48959,28577 @@ class ShapePath { // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf -class DataUtils { - - // float32 to float16 - - static toHalfFloat( val ) { - - if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); - - val = clamp( val, - 65504, 65504 ); - - _floatView[ 0 ] = val; - const f = _uint32View[ 0 ]; - const e = ( f >> 23 ) & 0x1ff; - return _baseTable[ e ] + ( ( f & 0x007fffff ) >> _shiftTable[ e ] ); - - } - - // float16 to float32 - - static fromHalfFloat( val ) { - - const m = val >> 10; - _uint32View[ 0 ] = _mantissaTable[ _offsetTable[ m ] + ( val & 0x3ff ) ] + _exponentTable[ m ]; - return _floatView[ 0 ]; - - } - -} - -// float32 to float16 helpers - -const _buffer = new ArrayBuffer( 4 ); -const _floatView = new Float32Array( _buffer ); -const _uint32View = new Uint32Array( _buffer ); - -const _baseTable = new Uint32Array( 512 ); -const _shiftTable = new Uint32Array( 512 ); - -for ( let i = 0; i < 256; ++ i ) { - - const e = i - 127; - - // very small number (0, -0) - - if ( e < - 27 ) { - - _baseTable[ i ] = 0x0000; - _baseTable[ i | 0x100 ] = 0x8000; - _shiftTable[ i ] = 24; - _shiftTable[ i | 0x100 ] = 24; - - // small number (denorm) - - } else if ( e < - 14 ) { - - _baseTable[ i ] = 0x0400 >> ( - e - 14 ); - _baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; - _shiftTable[ i ] = - e - 1; - _shiftTable[ i | 0x100 ] = - e - 1; - - // normal number - - } else if ( e <= 15 ) { - - _baseTable[ i ] = ( e + 15 ) << 10; - _baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; - _shiftTable[ i ] = 13; - _shiftTable[ i | 0x100 ] = 13; - - // large number (Infinity, -Infinity) - - } else if ( e < 128 ) { - - _baseTable[ i ] = 0x7c00; - _baseTable[ i | 0x100 ] = 0xfc00; - _shiftTable[ i ] = 24; - _shiftTable[ i | 0x100 ] = 24; - - // stay (NaN, Infinity, -Infinity) - - } else { - - _baseTable[ i ] = 0x7c00; - _baseTable[ i | 0x100 ] = 0xfc00; - _shiftTable[ i ] = 13; - _shiftTable[ i | 0x100 ] = 13; - - } - -} - -// float16 to float32 helpers +const { + floatView: _floatView, + uint32View: _uint32View, + baseTable: _baseTable, + shiftTable: _shiftTable, + mantissaTable: _mantissaTable, + exponentTable: _exponentTable, + offsetTable: _offsetTable +} = /*@__PURE__*/ _generateTables(); -const _mantissaTable = new Uint32Array( 2048 ); -const _exponentTable = new Uint32Array( 64 ); -const _offsetTable = new Uint32Array( 64 ); +function _generateTables() { -for ( let i = 1; i < 1024; ++ i ) { + // float32 to float16 helpers - let m = i << 13; // zero pad mantissa bits - let e = 0; // zero exponent + const buffer = new ArrayBuffer( 4 ); + const floatView = new Float32Array( buffer ); + const uint32View = new Uint32Array( buffer ); - // normalized - while ( ( m & 0x00800000 ) === 0 ) { + const baseTable = new Uint32Array( 512 ); + const shiftTable = new Uint32Array( 512 ); - m <<= 1; - e -= 0x00800000; // decrement exponent + for ( let i = 0; i < 256; ++ i ) { - } + const e = i - 127; - m &= ~ 0x00800000; // clear leading 1 bit - e += 0x38800000; // adjust bias + // very small number (0, -0) - _mantissaTable[ i ] = m | e; + if ( e < - 27 ) { -} + baseTable[ i ] = 0x0000; + baseTable[ i | 0x100 ] = 0x8000; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; -for ( let i = 1024; i < 2048; ++ i ) { + // small number (denorm) - _mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); + } else if ( e < - 14 ) { -} + baseTable[ i ] = 0x0400 >> ( - e - 14 ); + baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; + shiftTable[ i ] = - e - 1; + shiftTable[ i | 0x100 ] = - e - 1; -for ( let i = 1; i < 31; ++ i ) { + // normal number - _exponentTable[ i ] = i << 23; + } else if ( e <= 15 ) { -} + baseTable[ i ] = ( e + 15 ) << 10; + baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; -_exponentTable[ 31 ] = 0x47800000; -_exponentTable[ 32 ] = 0x80000000; -for ( let i = 33; i < 63; ++ i ) { + // large number (Infinity, -Infinity) - _exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); + } else if ( e < 128 ) { -} + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; -_exponentTable[ 63 ] = 0xc7800000; + // stay (NaN, Infinity, -Infinity) -for ( let i = 1; i < 64; ++ i ) { + } else { - if ( i !== 32 ) { + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; - _offsetTable[ i ] = 1024; + } } -} - -const LineStrip = 0; -const LinePieces = 1; -const NoColors = 0; -const FaceColors = 1; -const VertexColors = 2; - -function MeshFaceMaterial( materials ) { - - console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' ); - return materials; + // float16 to float32 helpers -} - -function MultiMaterial( materials = [] ) { + const mantissaTable = new Uint32Array( 2048 ); + const exponentTable = new Uint32Array( 64 ); + const offsetTable = new Uint32Array( 64 ); - console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' ); - materials.isMultiMaterial = true; - materials.materials = materials; - materials.clone = function () { + for ( let i = 1; i < 1024; ++ i ) { - return materials.slice(); - - }; + let m = i << 13; // zero pad mantissa bits + let e = 0; // zero exponent - return materials; + // normalized + while ( ( m & 0x00800000 ) === 0 ) { -} + m <<= 1; + e -= 0x00800000; // decrement exponent -class PointCloud extends Points { + } - constructor( geometry, material ) { + m &= ~ 0x00800000; // clear leading 1 bit + e += 0x38800000; // adjust bias - console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); - super( geometry, material ); + mantissaTable[ i ] = m | e; } -} - -class Particle extends Sprite { - - constructor( material ) { + for ( let i = 1024; i < 2048; ++ i ) { - console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' ); - super( material ); + mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); } -} - -class ParticleSystem extends Points { - - constructor( geometry, material ) { + for ( let i = 1; i < 31; ++ i ) { - console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); - super( geometry, material ); + exponentTable[ i ] = i << 23; } -} - -class PointCloudMaterial extends PointsMaterial { + exponentTable[ 31 ] = 0x47800000; + exponentTable[ 32 ] = 0x80000000; - constructor( parameters ) { + for ( let i = 33; i < 63; ++ i ) { - console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); - super( parameters ); + exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); } -} - -class ParticleBasicMaterial extends PointsMaterial { - - constructor( parameters ) { - - console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); - super( parameters ); - - } + exponentTable[ 63 ] = 0xc7800000; -} + for ( let i = 1; i < 64; ++ i ) { -class ParticleSystemMaterial extends PointsMaterial { + if ( i !== 32 ) { - constructor( parameters ) { + offsetTable[ i ] = 1024; - console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); - super( parameters ); + } } -} - -class Vertex extends Vector3 { - - constructor( x, y, z ) { - - console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); - super( x, y, z ); - - } + return { + floatView: floatView, + uint32View: uint32View, + baseTable: baseTable, + shiftTable: shiftTable, + mantissaTable: mantissaTable, + exponentTable: exponentTable, + offsetTable: offsetTable, + }; } -// - -class DynamicBufferAttribute extends BufferAttribute { - - constructor( array, itemSize ) { - - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' ); - super( array, itemSize ); - this.setUsage( DynamicDrawUsage ); - - } - -} +// float32 to float16 -class Int8Attribute extends Int8BufferAttribute { +function toHalfFloat( val ) { - constructor( array, itemSize ) { + if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); - console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' ); - super( array, itemSize ); + val = clamp( val, - 65504, 65504 ); - } + _floatView[ 0 ] = val; + const f = _uint32View[ 0 ]; + const e = ( f >> 23 ) & 0x1ff; + return _baseTable[ e ] + ( ( f & 0x007fffff ) >> _shiftTable[ e ] ); } -class Uint8Attribute extends Uint8BufferAttribute { +// float16 to float32 - constructor( array, itemSize ) { +function fromHalfFloat( val ) { - console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' ); - super( array, itemSize ); - - } + const m = val >> 10; + _uint32View[ 0 ] = _mantissaTable[ _offsetTable[ m ] + ( val & 0x3ff ) ] + _exponentTable[ m ]; + return _floatView[ 0 ]; } -class Uint8ClampedAttribute extends Uint8ClampedBufferAttribute { - - constructor( array, itemSize ) { - - console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' ); - super( array, itemSize ); - - } +var DataUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + toHalfFloat: toHalfFloat, + fromHalfFloat: fromHalfFloat +}); -} +// r133, c5bb5434555a3c3ddd784944a0a124f996fc721b -class Int16Attribute extends Int16BufferAttribute { +class ParametricGeometry extends BufferGeometry { - constructor( array, itemSize ) { + constructor() { - console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' ); - super( array, itemSize ); + console.error( 'THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js' ); + super(); } } -class Uint16Attribute extends Uint16BufferAttribute { - - constructor( array, itemSize ) { +// r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92 - console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' ); - super( array, itemSize ); - - } - -} - -class Int32Attribute extends Int32BufferAttribute { +class TextGeometry extends BufferGeometry { - constructor( array, itemSize ) { + constructor() { - console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' ); - super( array, itemSize ); + console.error( 'THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js' ); + super(); } } -class Uint32Attribute extends Uint32BufferAttribute { - - constructor( array, itemSize ) { +// r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92 - console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' ); - super( array, itemSize ); +function FontLoader() { - } + console.error( 'THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js' ); } -class Float32Attribute extends Float32BufferAttribute { - - constructor( array, itemSize ) { +// r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92 - console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' ); - super( array, itemSize ); +function Font() { - } + console.error( 'THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js' ); } -class Float64Attribute extends Float64BufferAttribute { +// r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0 - constructor( array, itemSize ) { - - console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' ); - super( array, itemSize ); +function ImmediateRenderObject() { - } + console.error( 'THREE.ImmediateRenderObject has been removed.' ); } -// - -Curve.create = function ( construct, getPoint ) { - - console.log( 'THREE.Curve.create() has been deprecated' ); - - construct.prototype = Object.create( Curve.prototype ); - construct.prototype.constructor = construct; - construct.prototype.getPoint = getPoint; - - return construct; - -}; - -// - -Path$1.prototype.fromPoints = function ( points ) { - - console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' ); - return this.setFromPoints( points ); - -}; - -// +// r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17 -class AxisHelper extends AxesHelper { +class WebGLMultisampleRenderTarget extends WebGLRenderTarget { - constructor( size ) { + constructor( width, height, options ) { - console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' ); - super( size ); + console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' ); + super( width, height, options ); + this.samples = 4; } } -class BoundingBoxHelper extends BoxHelper { +// r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce - constructor( object, color ) { - - console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' ); - super( object, color ); - - } - -} - -class EdgesHelper extends LineSegments { +class DataTexture2DArray extends DataArrayTexture { - constructor( object, hex ) { + constructor( data, width, height, depth ) { - console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' ); - super( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' ); + super( data, width, height, depth ); } } -GridHelper.prototype.setColors = function () { - - console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); - -}; - -SkeletonHelper.prototype.update = function () { - - console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' ); - -}; +// r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce -class WireframeHelper extends LineSegments { +class DataTexture3D extends Data3DTexture { - constructor( object, hex ) { + constructor( data, width, height, depth ) { - console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' ); - super( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' ); + super( data, width, height, depth ); } } -// - -Loader.prototype.extractUrlBase = function ( url ) { - - console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' ); - return LoaderUtils.extractUrlBase( url ); - -}; - -Loader.Handlers = { - - add: function ( /* regex, loader */ ) { - - console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' ); - - }, - - get: function ( /* file */ ) { - - console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' ); - - } - -}; - -class XHRLoader extends FileLoader { +if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - constructor( manager ) { + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { + revision: REVISION, + } } ) ); - console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' ); - super( manager ); +} - } +if ( typeof window !== 'undefined' ) { -} + if ( window.__THREE__ ) { -class BinaryTextureLoader extends DataTextureLoader { + console.warn( 'WARNING: Multiple instances of Three.js being imported.' ); - constructor( manager ) { + } else { - console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' ); - super( manager ); + window.__THREE__ = REVISION; } } -// - -Box2.prototype.center = function ( optionalTarget ) { - - console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); - -}; - -Box2.prototype.empty = function () { - - console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - -}; - -Box2.prototype.isIntersectionBox = function ( box ) { - - console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - -}; - -Box2.prototype.size = function ( optionalTarget ) { - - console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); - -}; - -// - -Box3.prototype.center = function ( optionalTarget ) { - - console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); - -}; - -Box3.prototype.empty = function () { - - console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - -}; - -Box3.prototype.isIntersectionBox = function ( box ) { - - console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - -}; - -Box3.prototype.isIntersectionSphere = function ( sphere ) { - - console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); - -}; - -Box3.prototype.size = function ( optionalTarget ) { - - console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); - -}; - -// - -Euler.prototype.toVector3 = function () { - - console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' ); - -}; - - -// - -Sphere.prototype.empty = function () { - - console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - -}; - -// - -Frustum$1.prototype.setFromMatrix = function ( m ) { - - console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' ); - return this.setFromProjectionMatrix( m ); - -}; - -// - -Line3.prototype.center = function ( optionalTarget ) { - - console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); - -}; - -// - -Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) { - - console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' ); - return this.toArray( array, offset ); - -}; - -Matrix3.prototype.multiplyVector3 = function ( vector ) { - - console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); - -}; - -Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) { - - console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); - -}; - -Matrix3.prototype.applyToBufferAttribute = function ( attribute ) { - - console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' ); - return attribute.applyMatrix3( this ); - -}; - -Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) { - - console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' ); - -}; - -Matrix3.prototype.getInverse = function ( matrix ) { - - console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' ); - return this.copy( matrix ).invert(); - -}; - -// - -Matrix4.prototype.extractPosition = function ( m ) { - - console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); - -}; - -Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) { - - console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' ); - return this.toArray( array, offset ); - -}; - -Matrix4.prototype.getPosition = function () { - - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - return new Vector3().setFromMatrixColumn( this, 3 ); - -}; - -Matrix4.prototype.setRotationFromQuaternion = function ( q ) { - - console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); - return this.makeRotationFromQuaternion( q ); - -}; - -Matrix4.prototype.multiplyToArray = function () { - - console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' ); - -}; - -Matrix4.prototype.multiplyVector3 = function ( vector ) { - - console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - -}; - -Matrix4.prototype.multiplyVector4 = function ( vector ) { - - console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - -}; - -Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) { - - console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); - -}; - -Matrix4.prototype.rotateAxis = function ( v ) { - - console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); - v.transformDirection( this ); - -}; - -Matrix4.prototype.crossVector = function ( vector ) { - - console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - -}; - -Matrix4.prototype.translate = function () { - - console.error( 'THREE.Matrix4: .translate() has been removed.' ); - -}; - -Matrix4.prototype.rotateX = function () { - - console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); - -}; - -Matrix4.prototype.rotateY = function () { - - console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); - -}; - -Matrix4.prototype.rotateZ = function () { - - console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); - -}; - -Matrix4.prototype.rotateByAxis = function () { - - console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); - -}; - -Matrix4.prototype.applyToBufferAttribute = function ( attribute ) { - - console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' ); - return attribute.applyMatrix4( this ); - -}; - -Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) { - - console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' ); - -}; - -Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) { - - console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' ); - return this.makePerspective( left, right, top, bottom, near, far ); - -}; - -Matrix4.prototype.getInverse = function ( matrix ) { - - console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' ); - return this.copy( matrix ).invert(); - -}; - -// - -Plane.prototype.isIntersectionLine = function ( line ) { - - console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); - return this.intersectsLine( line ); - -}; - -// - -Quaternion.prototype.multiplyVector3 = function ( vector ) { - - console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); - -}; - -Quaternion.prototype.inverse = function ( ) { - - console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' ); - return this.invert(); - -}; - -// - -Ray.prototype.isIntersectionBox = function ( box ) { - - console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - -}; - -Ray.prototype.isIntersectionPlane = function ( plane ) { - - console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); - return this.intersectsPlane( plane ); - -}; - -Ray.prototype.isIntersectionSphere = function ( sphere ) { - - console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); - -}; - -// - -Triangle.prototype.area = function () { - - console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' ); - return this.getArea(); - -}; - -Triangle.prototype.barycoordFromPoint = function ( point, target ) { - - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return this.getBarycoord( point, target ); - -}; - -Triangle.prototype.midpoint = function ( target ) { - - console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' ); - return this.getMidpoint( target ); - -}; - -Triangle.prototypenormal = function ( target ) { - - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return this.getNormal( target ); - -}; - -Triangle.prototype.plane = function ( target ) { - - console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' ); - return this.getPlane( target ); - -}; - -Triangle.barycoordFromPoint = function ( point, a, b, c, target ) { - - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return Triangle.getBarycoord( point, a, b, c, target ); - -}; - -Triangle.normal = function ( a, b, c, target ) { - - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return Triangle.getNormal( a, b, c, target ); - -}; - -// - -Shape.prototype.extractAllPoints = function ( divisions ) { - - console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' ); - return this.extractPoints( divisions ); - -}; - -Shape.prototype.extrude = function ( options ) { - - console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' ); - return new ExtrudeGeometry( this, options ); - -}; - -Shape.prototype.makeGeometry = function ( options ) { - - console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' ); - return new ShapeGeometry( this, options ); - -}; - -// - -Vector2.prototype.fromAttribute = function ( attribute, index, offset ) { - - console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); - -}; - -Vector2.prototype.distanceToManhattan = function ( v ) { - - console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); - -}; - -Vector2.prototype.lengthManhattan = function () { - - console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); - -}; - -// - -Vector3.prototype.setEulerFromRotationMatrix = function () { - - console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); - -}; - -Vector3.prototype.setEulerFromQuaternion = function () { - - console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); - -}; - -Vector3.prototype.getPositionFromMatrix = function ( m ) { - - console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); - return this.setFromMatrixPosition( m ); - -}; - -Vector3.prototype.getScaleFromMatrix = function ( m ) { - - console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); - return this.setFromMatrixScale( m ); - -}; - -Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) { - - console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); - return this.setFromMatrixColumn( matrix, index ); - -}; - -Vector3.prototype.applyProjection = function ( m ) { - - console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' ); - return this.applyMatrix4( m ); - -}; - -Vector3.prototype.fromAttribute = function ( attribute, index, offset ) { - - console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); - -}; - -Vector3.prototype.distanceToManhattan = function ( v ) { - - console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); - -}; - -Vector3.prototype.lengthManhattan = function () { - - console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); - -}; - -// - -Vector4.prototype.fromAttribute = function ( attribute, index, offset ) { - - console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); - -}; - -Vector4.prototype.lengthManhattan = function () { - - console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); - -}; - -// - -Object3D.prototype.getChildByName = function ( name ) { - - console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name ); - -}; - -Object3D.prototype.renderDepth = function () { - - console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); - -}; - -Object3D.prototype.translate = function ( distance, axis ) { - - console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); - return this.translateOnAxis( axis, distance ); - -}; - -Object3D.prototype.getWorldRotation = function () { - - console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' ); - -}; - -Object3D.prototype.applyMatrix = function ( matrix ) { - - console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' ); - return this.applyMatrix4( matrix ); - -}; - -Object.defineProperties( Object3D.prototype, { - - eulerOrder: { - get: function () { - - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - return this.rotation.order; - - }, - set: function ( value ) { - - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - this.rotation.order = value; - - } - }, - useQuaternion: { - get: function () { - - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - - }, - set: function () { - - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - - } - } - -} ); - -Mesh.prototype.setDrawMode = function () { - - console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); - -}; - -Object.defineProperties( Mesh.prototype, { - - drawMode: { - get: function () { - - console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' ); - return TrianglesDrawMode; - - }, - set: function () { - - console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); - - } - } - -} ); - -SkinnedMesh.prototype.initBones = function () { - - console.error( 'THREE.SkinnedMesh: initBones() has been removed.' ); - -}; - -// - -PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { - - console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' + - 'Use .setFocalLength and .filmGauge for a photographic setup.' ); - - if ( filmGauge !== undefined ) this.filmGauge = filmGauge; - this.setFocalLength( focalLength ); - -}; - -// - -Object.defineProperties( Light.prototype, { - onlyShadow: { - set: function () { - - console.warn( 'THREE.Light: .onlyShadow has been removed.' ); - - } - }, - shadowCameraFov: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); - this.shadow.camera.fov = value; - - } - }, - shadowCameraLeft: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); - this.shadow.camera.left = value; - - } - }, - shadowCameraRight: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); - this.shadow.camera.right = value; - - } - }, - shadowCameraTop: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); - this.shadow.camera.top = value; - - } - }, - shadowCameraBottom: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); - this.shadow.camera.bottom = value; - - } - }, - shadowCameraNear: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); - this.shadow.camera.near = value; - - } - }, - shadowCameraFar: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); - this.shadow.camera.far = value; - - } - }, - shadowCameraVisible: { - set: function () { - - console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); - - } - }, - shadowBias: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); - this.shadow.bias = value; - - } - }, - shadowDarkness: { - set: function () { - - console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); - - } - }, - shadowMapWidth: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); - this.shadow.mapSize.width = value; - - } - }, - shadowMapHeight: { - set: function ( value ) { - - console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); - this.shadow.mapSize.height = value; - - } - } -} ); - -// - -Object.defineProperties( BufferAttribute.prototype, { - - length: { - get: function () { - - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' ); - return this.array.length; - - } - }, - dynamic: { - get: function () { - - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - return this.usage === DynamicDrawUsage; - - }, - set: function ( /* value */ ) { - - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - this.setUsage( DynamicDrawUsage ); - - } - } - -} ); - -BufferAttribute.prototype.setDynamic = function ( value ) { - - console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); - return this; - -}; - -BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) { - - console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' ); - -}, - -BufferAttribute.prototype.setArray = function ( /* array */ ) { - - console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); - -}; - -// - -BufferGeometry.prototype.addIndex = function ( index ) { - - console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); - this.setIndex( index ); - -}; - -BufferGeometry.prototype.addAttribute = function ( name, attribute ) { - - console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' ); - - if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) { - - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - - return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); - - } - - if ( name === 'index' ) { - - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); - - return this; - - } - - return this.setAttribute( name, attribute ); - -}; - -BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) { - - if ( indexOffset !== undefined ) { - - console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); - - } - - console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); - this.addGroup( start, count ); - -}; - -BufferGeometry.prototype.clearDrawCalls = function () { - - console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); - this.clearGroups(); - -}; - -BufferGeometry.prototype.computeOffsets = function () { - - console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); - -}; - -BufferGeometry.prototype.removeAttribute = function ( name ) { - - console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' ); - - return this.deleteAttribute( name ); - -}; - -BufferGeometry.prototype.applyMatrix = function ( matrix ) { - - console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' ); - return this.applyMatrix4( matrix ); - -}; - -Object.defineProperties( BufferGeometry.prototype, { - - drawcalls: { - get: function () { - - console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); - return this.groups; - - } - }, - offsets: { - get: function () { - - console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); - return this.groups; - - } - } - -} ); - -InterleavedBuffer.prototype.setDynamic = function ( value ) { - - console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); - return this; - -}; - -InterleavedBuffer.prototype.setArray = function ( /* array */ ) { - - console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); - -}; - -// - -ExtrudeGeometry.prototype.getArrays = function () { - - console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' ); - -}; - -ExtrudeGeometry.prototype.addShapeList = function () { - - console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' ); - -}; - -ExtrudeGeometry.prototype.addShape = function () { - - console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' ); - -}; - -// - -Scene$1.prototype.dispose = function () { - - console.error( 'THREE.Scene: .dispose() has been removed.' ); - -}; - -// - -Uniform.prototype.onUpdate = function () { - - console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' ); - return this; - -}; - -// - -Object.defineProperties( Material.prototype, { - - wrapAround: { - get: function () { - - console.warn( 'THREE.Material: .wrapAround has been removed.' ); - - }, - set: function () { - - console.warn( 'THREE.Material: .wrapAround has been removed.' ); - - } - }, - - overdraw: { - get: function () { - - console.warn( 'THREE.Material: .overdraw has been removed.' ); - - }, - set: function () { - - console.warn( 'THREE.Material: .overdraw has been removed.' ); - - } - }, - - wrapRGB: { - get: function () { - - console.warn( 'THREE.Material: .wrapRGB has been removed.' ); - return new Color(); - - } - }, - - shading: { - get: function () { - - console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - - }, - set: function ( value ) { - - console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - this.flatShading = ( value === FlatShading ); - - } - }, - - stencilMask: { - get: function () { - - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - return this.stencilFuncMask; - - }, - set: function ( value ) { - - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - this.stencilFuncMask = value; - - } - }, - - vertexTangents: { - get: function () { - - console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' ); - - }, - set: function () { - - console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' ); - - } - }, - -} ); - -Object.defineProperties( ShaderMaterial.prototype, { - - derivatives: { - get: function () { - - console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - return this.extensions.derivatives; - - }, - set: function ( value ) { - - console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - this.extensions.derivatives = value; - - } - } - -} ); - -// - -WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) { - - console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' ); - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); - -}; - -WebGLRenderer.prototype.animate = function ( callback ) { - - console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' ); - this.setAnimationLoop( callback ); - -}; - -WebGLRenderer.prototype.getCurrentRenderTarget = function () { - - console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' ); - return this.getRenderTarget(); - -}; - -WebGLRenderer.prototype.getMaxAnisotropy = function () { - - console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' ); - return this.capabilities.getMaxAnisotropy(); - -}; - -WebGLRenderer.prototype.getPrecision = function () { - - console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' ); - return this.capabilities.precision; - -}; - -WebGLRenderer.prototype.resetGLState = function () { - - console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' ); - return this.state.reset(); - -}; - -WebGLRenderer.prototype.supportsFloatTextures = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); - return this.extensions.get( 'OES_texture_float' ); - -}; - -WebGLRenderer.prototype.supportsHalfFloatTextures = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); - return this.extensions.get( 'OES_texture_half_float' ); - -}; - -WebGLRenderer.prototype.supportsStandardDerivatives = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); - return this.extensions.get( 'OES_standard_derivatives' ); - -}; - -WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); - -}; - -WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - -}; - -WebGLRenderer.prototype.supportsBlendMinMax = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); - return this.extensions.get( 'EXT_blend_minmax' ); - -}; - -WebGLRenderer.prototype.supportsVertexTextures = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' ); - return this.capabilities.vertexTextures; - -}; - -WebGLRenderer.prototype.supportsInstancedArrays = function () { - - console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); - return this.extensions.get( 'ANGLE_instanced_arrays' ); - -}; - -WebGLRenderer.prototype.enableScissorTest = function ( boolean ) { - - console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); - this.setScissorTest( boolean ); - -}; - -WebGLRenderer.prototype.initMaterial = function () { - - console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); - -}; - -WebGLRenderer.prototype.addPrePlugin = function () { - - console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); - -}; - -WebGLRenderer.prototype.addPostPlugin = function () { - - console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); - -}; - -WebGLRenderer.prototype.updateShadowMap = function () { - - console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); - -}; - -WebGLRenderer.prototype.setFaceCulling = function () { - - console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' ); - -}; - -WebGLRenderer.prototype.allocTextureUnit = function () { - - console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' ); - -}; - -WebGLRenderer.prototype.setTexture = function () { - - console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' ); - -}; - -WebGLRenderer.prototype.setTexture2D = function () { - - console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' ); - -}; - -WebGLRenderer.prototype.setTextureCube = function () { - - console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' ); - -}; - -WebGLRenderer.prototype.getActiveMipMapLevel = function () { - - console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' ); - return this.getActiveMipmapLevel(); - -}; - -Object.defineProperties( WebGLRenderer.prototype, { - - shadowMapEnabled: { - get: function () { - - return this.shadowMap.enabled; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); - this.shadowMap.enabled = value; - - } - }, - shadowMapType: { - get: function () { - - return this.shadowMap.type; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); - this.shadowMap.type = value; - - } - }, - shadowMapCullFace: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; - - }, - set: function ( /* value */ ) { - - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); - - } - }, - context: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' ); - return this.getContext(); - - } - }, - vr: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' ); - return this.xr; - - } - }, - gammaInput: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); - return false; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); - - } - }, - gammaOutput: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); - return false; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); - this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding; - - } - }, - toneMappingWhitePoint: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' ); - return 1.0; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' ); - - } - }, - gammaFactor: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); - return 2; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); - - } - } -} ); - -Object.defineProperties( WebGLShadowMap.prototype, { - - cullFace: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; - - }, - set: function ( /* cullFace */ ) { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); - - } - }, - renderReverseSided: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); - return undefined; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); - - } - }, - renderSingleSided: { - get: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); - return undefined; - - }, - set: function () { - - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); - - } - } - -} ); - -class WebGLRenderTargetCube extends WebGLCubeRenderTarget { - - constructor( width, height, options ) { - - console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' ); - super( width, options ); - - } - -} - -// - -Object.defineProperties( WebGLRenderTarget.prototype, { - - wrapS: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - return this.texture.wrapS; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - this.texture.wrapS = value; - - } - }, - wrapT: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - return this.texture.wrapT; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - this.texture.wrapT = value; - - } - }, - magFilter: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - return this.texture.magFilter; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - this.texture.magFilter = value; - - } - }, - minFilter: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - return this.texture.minFilter; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - this.texture.minFilter = value; - - } - }, - anisotropy: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - return this.texture.anisotropy; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - this.texture.anisotropy = value; - - } - }, - offset: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - return this.texture.offset; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - this.texture.offset = value; - - } - }, - repeat: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - return this.texture.repeat; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - this.texture.repeat = value; - - } - }, - format: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - return this.texture.format; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - this.texture.format = value; - - } - }, - type: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - return this.texture.type; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - this.texture.type = value; - - } - }, - generateMipmaps: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - return this.texture.generateMipmaps; - - }, - set: function ( value ) { - - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - this.texture.generateMipmaps = value; - - } - } - -} ); - -// - -Audio.prototype.load = function ( file ) { - - console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' ); - const scope = this; - const audioLoader = new AudioLoader(); - audioLoader.load( file, function ( buffer ) { - - scope.setBuffer( buffer ); - - } ); - return this; - -}; - - -AudioAnalyser.prototype.getData = function () { - - console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); - return this.getFrequencyData(); - -}; - -// - -CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) { - - console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' ); - return this.update( renderer, scene ); - -}; - -CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) { - - console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' ); - return this.renderTarget.clear( renderer, color, depth, stencil ); - -}; - -ImageUtils.crossOrigin = undefined; - -ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) { - - console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); - - const loader = new TextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); - - const texture = loader.load( url, onLoad, undefined, onError ); - - if ( mapping ) texture.mapping = mapping; - - return texture; - -}; - -ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) { - - console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); - - const loader = new CubeTextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); - - const texture = loader.load( urls, onLoad, undefined, onError ); - - if ( mapping ) texture.mapping = mapping; - - return texture; - -}; - -ImageUtils.loadCompressedTexture = function () { - - console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); - -}; - -ImageUtils.loadCompressedTextureCube = function () { - - console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); - -}; - -// - -function CanvasRenderer() { - - console.error( 'THREE.CanvasRenderer has been removed' ); - -} - -// - -function JSONLoader() { - - console.error( 'THREE.JSONLoader has been removed.' ); - -} - -// - -const SceneUtils = { - - createMultiMaterialObject: function ( /* geometry, materials */ ) { - - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); - - }, - - detach: function ( /* child, parent, scene */ ) { - - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); - - }, - - attach: function ( /* child, scene, parent */ ) { - - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); - - } - -}; - -// - -function LensFlare() { - - console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' ); - -} - -// - -class ParametricGeometry extends BufferGeometry { - - constructor() { - - console.error( 'THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js' ); - super(); - - } - -} - -class TextGeometry extends BufferGeometry { - - constructor() { - - console.error( 'THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js' ); - super(); - - } - -} - -function FontLoader() { - - console.error( 'THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js' ); - -} - -function Font$2() { - - console.error( 'THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js' ); - -} - -function ImmediateRenderObject() { - - console.error( 'THREE.ImmediateRenderObject has been removed.' ); - -} - -class WebGLMultisampleRenderTarget extends WebGLRenderTarget { - - constructor( width, height, options ) { - - console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' ); - super( width, height, options ); - this.samples = 4; - - } - -} - -class DataTexture2DArray extends DataArrayTexture { - - constructor( data, width, height, depth ) { - - console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' ); - super( data, width, height, depth ); - - } - -} - -class DataTexture3D extends Data3DTexture { - - constructor( data, width, height, depth ) { - - console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' ); - super( data, width, height, depth ); - - } - -} - -if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - - __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { - revision: REVISION, - } } ) ); - -} - -if ( typeof window !== 'undefined' ) { - - if ( window.__THREE__ ) { - - console.warn( 'WARNING: Multiple instances of Three.js being imported.' ); - - } else { - - window.__THREE__ = REVISION; - - } - -} - -var THREE = /*#__PURE__*/Object.freeze({ - __proto__: null, - ACESFilmicToneMapping: ACESFilmicToneMapping, - AddEquation: AddEquation, - AddOperation: AddOperation, - AdditiveAnimationBlendMode: AdditiveAnimationBlendMode, - AdditiveBlending: AdditiveBlending, - AlphaFormat: AlphaFormat, - AlwaysDepth: AlwaysDepth, - AlwaysStencilFunc: AlwaysStencilFunc, - AmbientLight: AmbientLight$1, - AmbientLightProbe: AmbientLightProbe, - AnimationClip: AnimationClip, - AnimationLoader: AnimationLoader, - AnimationMixer: AnimationMixer, - AnimationObjectGroup: AnimationObjectGroup, - AnimationUtils: AnimationUtils, - ArcCurve: ArcCurve, - ArrayCamera: ArrayCamera, - ArrowHelper: ArrowHelper, - Audio: Audio, - AudioAnalyser: AudioAnalyser, - AudioContext: AudioContext, - AudioListener: AudioListener, - AudioLoader: AudioLoader, - AxesHelper: AxesHelper, - AxisHelper: AxisHelper, - BackSide: BackSide, - BasicDepthPacking: BasicDepthPacking, - BasicShadowMap: BasicShadowMap, - BinaryTextureLoader: BinaryTextureLoader, - Bone: Bone, - BooleanKeyframeTrack: BooleanKeyframeTrack, - BoundingBoxHelper: BoundingBoxHelper, - Box2: Box2, - Box3: Box3, - Box3Helper: Box3Helper, - BoxBufferGeometry: BoxGeometry, - BoxGeometry: BoxGeometry, - BoxHelper: BoxHelper, - BufferAttribute: BufferAttribute, - BufferGeometry: BufferGeometry, - BufferGeometryLoader: BufferGeometryLoader, - ByteType: ByteType, - Cache: Cache, - Camera: Camera, - CameraHelper: CameraHelper, - CanvasRenderer: CanvasRenderer, - CanvasTexture: CanvasTexture, - CapsuleBufferGeometry: CapsuleGeometry, - CapsuleGeometry: CapsuleGeometry, - CatmullRomCurve3: CatmullRomCurve3, - CineonToneMapping: CineonToneMapping, - CircleBufferGeometry: CircleGeometry, - CircleGeometry: CircleGeometry, - ClampToEdgeWrapping: ClampToEdgeWrapping, - Clock: Clock, - Color: Color, - ColorKeyframeTrack: ColorKeyframeTrack, - ColorManagement: ColorManagement, - CompressedTexture: CompressedTexture, - CompressedTextureLoader: CompressedTextureLoader, - ConeBufferGeometry: ConeGeometry, - ConeGeometry: ConeGeometry, - CubeCamera: CubeCamera, - CubeReflectionMapping: CubeReflectionMapping, - CubeRefractionMapping: CubeRefractionMapping, - CubeTexture: CubeTexture, - CubeTextureLoader: CubeTextureLoader, - CubeUVReflectionMapping: CubeUVReflectionMapping, - CubicBezierCurve: CubicBezierCurve, - CubicBezierCurve3: CubicBezierCurve3, - CubicInterpolant: CubicInterpolant, - CullFaceBack: CullFaceBack, - CullFaceFront: CullFaceFront, - CullFaceFrontBack: CullFaceFrontBack, - CullFaceNone: CullFaceNone, - Curve: Curve, - CurvePath: CurvePath, - CustomBlending: CustomBlending, - CustomToneMapping: CustomToneMapping, - CylinderBufferGeometry: CylinderGeometry, - CylinderGeometry: CylinderGeometry, - Cylindrical: Cylindrical, - Data3DTexture: Data3DTexture, - DataArrayTexture: DataArrayTexture, - DataTexture: DataTexture, - DataTexture2DArray: DataTexture2DArray, - DataTexture3D: DataTexture3D, - DataTextureLoader: DataTextureLoader, - DataUtils: DataUtils, - DecrementStencilOp: DecrementStencilOp, - DecrementWrapStencilOp: DecrementWrapStencilOp, - DefaultLoadingManager: DefaultLoadingManager, - DepthFormat: DepthFormat, - DepthStencilFormat: DepthStencilFormat, - DepthTexture: DepthTexture, - DirectionalLight: DirectionalLight$1, - DirectionalLightHelper: DirectionalLightHelper, - DiscreteInterpolant: DiscreteInterpolant, - DodecahedronBufferGeometry: DodecahedronGeometry, - DodecahedronGeometry: DodecahedronGeometry, - DoubleSide: DoubleSide, - DstAlphaFactor: DstAlphaFactor, - DstColorFactor: DstColorFactor, - DynamicBufferAttribute: DynamicBufferAttribute, - DynamicCopyUsage: DynamicCopyUsage, - DynamicDrawUsage: DynamicDrawUsage, - DynamicReadUsage: DynamicReadUsage, - EdgesGeometry: EdgesGeometry, - EdgesHelper: EdgesHelper, - EllipseCurve: EllipseCurve, - EqualDepth: EqualDepth, - EqualStencilFunc: EqualStencilFunc, - EquirectangularReflectionMapping: EquirectangularReflectionMapping, - EquirectangularRefractionMapping: EquirectangularRefractionMapping, - Euler: Euler, - EventDispatcher: EventDispatcher, - ExtrudeBufferGeometry: ExtrudeGeometry, - ExtrudeGeometry: ExtrudeGeometry, - FaceColors: FaceColors, - FileLoader: FileLoader, - FlatShading: FlatShading, - Float16BufferAttribute: Float16BufferAttribute, - Float32Attribute: Float32Attribute, - Float32BufferAttribute: Float32BufferAttribute, - Float64Attribute: Float64Attribute, - Float64BufferAttribute: Float64BufferAttribute, - FloatType: FloatType, - Fog: Fog, - FogExp2: FogExp2, - Font: Font$2, - FontLoader: FontLoader, - FramebufferTexture: FramebufferTexture, - FrontSide: FrontSide, - Frustum: Frustum$1, - GLBufferAttribute: GLBufferAttribute, - GLSL1: GLSL1, - GLSL3: GLSL3, - GreaterDepth: GreaterDepth, - GreaterEqualDepth: GreaterEqualDepth, - GreaterEqualStencilFunc: GreaterEqualStencilFunc, - GreaterStencilFunc: GreaterStencilFunc, - GridHelper: GridHelper, - Group: Group, - HalfFloatType: HalfFloatType, - HemisphereLight: HemisphereLight, - HemisphereLightHelper: HemisphereLightHelper, - HemisphereLightProbe: HemisphereLightProbe, - IcosahedronBufferGeometry: IcosahedronGeometry, - IcosahedronGeometry: IcosahedronGeometry, - ImageBitmapLoader: ImageBitmapLoader, - ImageLoader: ImageLoader, - ImageUtils: ImageUtils, - ImmediateRenderObject: ImmediateRenderObject, - IncrementStencilOp: IncrementStencilOp, - IncrementWrapStencilOp: IncrementWrapStencilOp, - InstancedBufferAttribute: InstancedBufferAttribute, - InstancedBufferGeometry: InstancedBufferGeometry, - InstancedInterleavedBuffer: InstancedInterleavedBuffer, - InstancedMesh: InstancedMesh, - Int16Attribute: Int16Attribute, - Int16BufferAttribute: Int16BufferAttribute, - Int32Attribute: Int32Attribute, - Int32BufferAttribute: Int32BufferAttribute, - Int8Attribute: Int8Attribute, - Int8BufferAttribute: Int8BufferAttribute, - IntType: IntType, - InterleavedBuffer: InterleavedBuffer, - InterleavedBufferAttribute: InterleavedBufferAttribute, - Interpolant: Interpolant, - InterpolateDiscrete: InterpolateDiscrete, - InterpolateLinear: InterpolateLinear, - InterpolateSmooth: InterpolateSmooth, - InvertStencilOp: InvertStencilOp, - JSONLoader: JSONLoader, - KeepStencilOp: KeepStencilOp, - KeyframeTrack: KeyframeTrack, - LOD: LOD, - LatheBufferGeometry: LatheGeometry, - LatheGeometry: LatheGeometry, - Layers: Layers, - LensFlare: LensFlare, - LessDepth: LessDepth, - LessEqualDepth: LessEqualDepth, - LessEqualStencilFunc: LessEqualStencilFunc, - LessStencilFunc: LessStencilFunc, - Light: Light, - LightProbe: LightProbe, - Line: Line$2, - Line3: Line3, - LineBasicMaterial: LineBasicMaterial, - LineCurve: LineCurve, - LineCurve3: LineCurve3, - LineDashedMaterial: LineDashedMaterial, - LineLoop: LineLoop, - LinePieces: LinePieces, - LineSegments: LineSegments, - LineStrip: LineStrip, - LinearEncoding: LinearEncoding, - LinearFilter: LinearFilter, - LinearInterpolant: LinearInterpolant, - LinearMipMapLinearFilter: LinearMipMapLinearFilter, - LinearMipMapNearestFilter: LinearMipMapNearestFilter, - LinearMipmapLinearFilter: LinearMipmapLinearFilter, - LinearMipmapNearestFilter: LinearMipmapNearestFilter, - LinearSRGBColorSpace: LinearSRGBColorSpace, - LinearToneMapping: LinearToneMapping, - Loader: Loader, - LoaderUtils: LoaderUtils, - LoadingManager: LoadingManager, - LoopOnce: LoopOnce, - LoopPingPong: LoopPingPong, - LoopRepeat: LoopRepeat, - LuminanceAlphaFormat: LuminanceAlphaFormat, - LuminanceFormat: LuminanceFormat, - MOUSE: MOUSE, - Material: Material, - MaterialLoader: MaterialLoader, - Math: MathUtils, - MathUtils: MathUtils, - Matrix3: Matrix3, - Matrix4: Matrix4, - MaxEquation: MaxEquation, - Mesh: Mesh, - MeshBasicMaterial: MeshBasicMaterial, - MeshDepthMaterial: MeshDepthMaterial, - MeshDistanceMaterial: MeshDistanceMaterial, - MeshFaceMaterial: MeshFaceMaterial, - MeshLambertMaterial: MeshLambertMaterial, - MeshMatcapMaterial: MeshMatcapMaterial, - MeshNormalMaterial: MeshNormalMaterial, - MeshPhongMaterial: MeshPhongMaterial, - MeshPhysicalMaterial: MeshPhysicalMaterial, - MeshStandardMaterial: MeshStandardMaterial, - MeshToonMaterial: MeshToonMaterial, - MinEquation: MinEquation, - MirroredRepeatWrapping: MirroredRepeatWrapping, - MixOperation: MixOperation, - MultiMaterial: MultiMaterial, - MultiplyBlending: MultiplyBlending, - MultiplyOperation: MultiplyOperation, - NearestFilter: NearestFilter, - NearestMipMapLinearFilter: NearestMipMapLinearFilter, - NearestMipMapNearestFilter: NearestMipMapNearestFilter, - NearestMipmapLinearFilter: NearestMipmapLinearFilter, - NearestMipmapNearestFilter: NearestMipmapNearestFilter, - NeverDepth: NeverDepth, - NeverStencilFunc: NeverStencilFunc, - NoBlending: NoBlending, - NoColorSpace: NoColorSpace, - NoColors: NoColors, - NoToneMapping: NoToneMapping, - NormalAnimationBlendMode: NormalAnimationBlendMode, - NormalBlending: NormalBlending, - NotEqualDepth: NotEqualDepth, - NotEqualStencilFunc: NotEqualStencilFunc, - NumberKeyframeTrack: NumberKeyframeTrack, - Object3D: Object3D, - ObjectLoader: ObjectLoader, - ObjectSpaceNormalMap: ObjectSpaceNormalMap, - OctahedronBufferGeometry: OctahedronGeometry, - OctahedronGeometry: OctahedronGeometry, - OneFactor: OneFactor, - OneMinusDstAlphaFactor: OneMinusDstAlphaFactor, - OneMinusDstColorFactor: OneMinusDstColorFactor, - OneMinusSrcAlphaFactor: OneMinusSrcAlphaFactor, - OneMinusSrcColorFactor: OneMinusSrcColorFactor, - OrthographicCamera: OrthographicCamera, - PCFShadowMap: PCFShadowMap, - PCFSoftShadowMap: PCFSoftShadowMap, - PMREMGenerator: PMREMGenerator, - ParametricGeometry: ParametricGeometry, - Particle: Particle, - ParticleBasicMaterial: ParticleBasicMaterial, - ParticleSystem: ParticleSystem, - ParticleSystemMaterial: ParticleSystemMaterial, - Path: Path$1, - PerspectiveCamera: PerspectiveCamera, - Plane: Plane, - PlaneBufferGeometry: PlaneGeometry, - PlaneGeometry: PlaneGeometry, - PlaneHelper: PlaneHelper, - PointCloud: PointCloud, - PointCloudMaterial: PointCloudMaterial, - PointLight: PointLight, - PointLightHelper: PointLightHelper, - Points: Points, - PointsMaterial: PointsMaterial, - PolarGridHelper: PolarGridHelper, - PolyhedronBufferGeometry: PolyhedronGeometry, - PolyhedronGeometry: PolyhedronGeometry, - PositionalAudio: PositionalAudio, - PropertyBinding: PropertyBinding, - PropertyMixer: PropertyMixer, - QuadraticBezierCurve: QuadraticBezierCurve, - QuadraticBezierCurve3: QuadraticBezierCurve3, - Quaternion: Quaternion, - QuaternionKeyframeTrack: QuaternionKeyframeTrack, - QuaternionLinearInterpolant: QuaternionLinearInterpolant, - REVISION: REVISION, - RGBADepthPacking: RGBADepthPacking, - RGBAFormat: RGBAFormat, - RGBAIntegerFormat: RGBAIntegerFormat, - RGBA_ASTC_10x10_Format: RGBA_ASTC_10x10_Format, - RGBA_ASTC_10x5_Format: RGBA_ASTC_10x5_Format, - RGBA_ASTC_10x6_Format: RGBA_ASTC_10x6_Format, - RGBA_ASTC_10x8_Format: RGBA_ASTC_10x8_Format, - RGBA_ASTC_12x10_Format: RGBA_ASTC_12x10_Format, - RGBA_ASTC_12x12_Format: RGBA_ASTC_12x12_Format, - RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format, - RGBA_ASTC_5x4_Format: RGBA_ASTC_5x4_Format, - RGBA_ASTC_5x5_Format: RGBA_ASTC_5x5_Format, - RGBA_ASTC_6x5_Format: RGBA_ASTC_6x5_Format, - RGBA_ASTC_6x6_Format: RGBA_ASTC_6x6_Format, - RGBA_ASTC_8x5_Format: RGBA_ASTC_8x5_Format, - RGBA_ASTC_8x6_Format: RGBA_ASTC_8x6_Format, - RGBA_ASTC_8x8_Format: RGBA_ASTC_8x8_Format, - RGBA_BPTC_Format: RGBA_BPTC_Format, - RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format, - RGBA_PVRTC_2BPPV1_Format: RGBA_PVRTC_2BPPV1_Format, - RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format, - RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format, - RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format, - RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format, - RGBFormat: RGBFormat, - RGB_ETC1_Format: RGB_ETC1_Format, - RGB_ETC2_Format: RGB_ETC2_Format, - RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format, - RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format, - RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format, - RGFormat: RGFormat, - RGIntegerFormat: RGIntegerFormat, - RawShaderMaterial: RawShaderMaterial, - Ray: Ray, - Raycaster: Raycaster, - RectAreaLight: RectAreaLight, - RedFormat: RedFormat, - RedIntegerFormat: RedIntegerFormat, - ReinhardToneMapping: ReinhardToneMapping, - RepeatWrapping: RepeatWrapping, - ReplaceStencilOp: ReplaceStencilOp, - ReverseSubtractEquation: ReverseSubtractEquation, - RingBufferGeometry: RingGeometry, - RingGeometry: RingGeometry, - SRGBColorSpace: SRGBColorSpace, - Scene: Scene$1, - SceneUtils: SceneUtils, - ShaderChunk: ShaderChunk, - ShaderLib: ShaderLib, - ShaderMaterial: ShaderMaterial, - ShadowMaterial: ShadowMaterial, - Shape: Shape, - ShapeBufferGeometry: ShapeGeometry, - ShapeGeometry: ShapeGeometry, - ShapePath: ShapePath, - ShapeUtils: ShapeUtils, - ShortType: ShortType, - Skeleton: Skeleton, - SkeletonHelper: SkeletonHelper, - SkinnedMesh: SkinnedMesh, - SmoothShading: SmoothShading, - Source: Source, - Sphere: Sphere, - SphereBufferGeometry: SphereGeometry, - SphereGeometry: SphereGeometry, - Spherical: Spherical, - SphericalHarmonics3: SphericalHarmonics3, - SplineCurve: SplineCurve, - SpotLight: SpotLight, - SpotLightHelper: SpotLightHelper, - Sprite: Sprite, - SpriteMaterial: SpriteMaterial, - SrcAlphaFactor: SrcAlphaFactor, - SrcAlphaSaturateFactor: SrcAlphaSaturateFactor, - SrcColorFactor: SrcColorFactor, - StaticCopyUsage: StaticCopyUsage, - StaticDrawUsage: StaticDrawUsage, - StaticReadUsage: StaticReadUsage, - StereoCamera: StereoCamera, - StreamCopyUsage: StreamCopyUsage, - StreamDrawUsage: StreamDrawUsage, - StreamReadUsage: StreamReadUsage, - StringKeyframeTrack: StringKeyframeTrack, - SubtractEquation: SubtractEquation, - SubtractiveBlending: SubtractiveBlending, - TOUCH: TOUCH, - TangentSpaceNormalMap: TangentSpaceNormalMap, - TetrahedronBufferGeometry: TetrahedronGeometry, - TetrahedronGeometry: TetrahedronGeometry, - TextGeometry: TextGeometry, - Texture: Texture, - TextureLoader: TextureLoader, - TorusBufferGeometry: TorusGeometry, - TorusGeometry: TorusGeometry, - TorusKnotBufferGeometry: TorusKnotGeometry, - TorusKnotGeometry: TorusKnotGeometry, - Triangle: Triangle, - TriangleFanDrawMode: TriangleFanDrawMode, - TriangleStripDrawMode: TriangleStripDrawMode, - TrianglesDrawMode: TrianglesDrawMode, - TubeBufferGeometry: TubeGeometry, - TubeGeometry: TubeGeometry, - UVMapping: UVMapping, - Uint16Attribute: Uint16Attribute, - Uint16BufferAttribute: Uint16BufferAttribute, - Uint32Attribute: Uint32Attribute, - Uint32BufferAttribute: Uint32BufferAttribute, - Uint8Attribute: Uint8Attribute, - Uint8BufferAttribute: Uint8BufferAttribute, - Uint8ClampedAttribute: Uint8ClampedAttribute, - Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute, - Uniform: Uniform, - UniformsLib: UniformsLib, - UniformsUtils: UniformsUtils, - UnsignedByteType: UnsignedByteType, - UnsignedInt248Type: UnsignedInt248Type, - UnsignedIntType: UnsignedIntType, - UnsignedShort4444Type: UnsignedShort4444Type, - UnsignedShort5551Type: UnsignedShort5551Type, - UnsignedShortType: UnsignedShortType, - VSMShadowMap: VSMShadowMap, - Vector2: Vector2, - Vector3: Vector3, - Vector4: Vector4, - VectorKeyframeTrack: VectorKeyframeTrack, - Vertex: Vertex, - VertexColors: VertexColors, - VideoTexture: VideoTexture, - WebGL1Renderer: WebGL1Renderer, - WebGL3DRenderTarget: WebGL3DRenderTarget, - WebGLArrayRenderTarget: WebGLArrayRenderTarget, - WebGLCubeRenderTarget: WebGLCubeRenderTarget, - WebGLMultipleRenderTargets: WebGLMultipleRenderTargets, - WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget, - WebGLRenderTarget: WebGLRenderTarget, - WebGLRenderTargetCube: WebGLRenderTargetCube, - WebGLRenderer: WebGLRenderer, - WebGLUtils: WebGLUtils, - WireframeGeometry: WireframeGeometry, - WireframeHelper: WireframeHelper, - WrapAroundEnding: WrapAroundEnding, - XHRLoader: XHRLoader, - ZeroCurvatureEnding: ZeroCurvatureEnding, - ZeroFactor: ZeroFactor, - ZeroSlopeEnding: ZeroSlopeEnding, - ZeroStencilOp: ZeroStencilOp, - _SRGBAFormat: _SRGBAFormat, - sRGBEncoding: sRGBEncoding -}); - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -var constants$1 = {exports: {}}; - -var reactReconcilerConstants_production_min = {}; - -/** - * @license React - * react-reconciler-constants.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredReactReconcilerConstants_production_min; - -function requireReactReconcilerConstants_production_min () { - if (hasRequiredReactReconcilerConstants_production_min) return reactReconcilerConstants_production_min; - hasRequiredReactReconcilerConstants_production_min = 1; -reactReconcilerConstants_production_min.ConcurrentRoot=1;reactReconcilerConstants_production_min.ContinuousEventPriority=4;reactReconcilerConstants_production_min.DefaultEventPriority=16;reactReconcilerConstants_production_min.DiscreteEventPriority=1;reactReconcilerConstants_production_min.IdleEventPriority=536870912;reactReconcilerConstants_production_min.LegacyRoot=0; - return reactReconcilerConstants_production_min; -} - -var reactReconcilerConstants_development = {}; - -/** - * @license React - * react-reconciler-constants.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredReactReconcilerConstants_development; - -function requireReactReconcilerConstants_development () { - if (hasRequiredReactReconcilerConstants_development) return reactReconcilerConstants_development; - hasRequiredReactReconcilerConstants_development = 1; - - if (process.env.NODE_ENV !== "production") { - (function() { - - var SyncLane = - /* */ - 1; - var InputContinuousLane = - /* */ - 4; - var DefaultLane = - /* */ - 16; - var IdleLane = - /* */ - 536870912; - - var DiscreteEventPriority = SyncLane; - var ContinuousEventPriority = InputContinuousLane; - var DefaultEventPriority = DefaultLane; - var IdleEventPriority = IdleLane; - - var LegacyRoot = 0; - var ConcurrentRoot = 1; - - reactReconcilerConstants_development.ConcurrentRoot = ConcurrentRoot; - reactReconcilerConstants_development.ContinuousEventPriority = ContinuousEventPriority; - reactReconcilerConstants_development.DefaultEventPriority = DefaultEventPriority; - reactReconcilerConstants_development.DiscreteEventPriority = DiscreteEventPriority; - reactReconcilerConstants_development.IdleEventPriority = IdleEventPriority; - reactReconcilerConstants_development.LegacyRoot = LegacyRoot; - })(); - } - return reactReconcilerConstants_development; -} - -(function (module) { - - if (process.env.NODE_ENV === 'production') { - module.exports = requireReactReconcilerConstants_production_min(); - } else { - module.exports = requireReactReconcilerConstants_development(); - } -} (constants$1)); - -function createStore$3(createState) { - let state; - const listeners = /* @__PURE__ */ new Set(); - const setState = (partial, replace) => { - const nextState = typeof partial === "function" ? partial(state) : partial; - if (nextState !== state) { - const previousState = state; - state = replace ? nextState : Object.assign({}, state, nextState); - listeners.forEach((listener) => listener(state, previousState)); - } - }; - const getState = () => state; - const subscribeWithSelector = (listener, selector = getState, equalityFn = Object.is) => { - console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware"); - let currentSlice = selector(state); - function listenerToAdd() { - const nextSlice = selector(state); - if (!equalityFn(currentSlice, nextSlice)) { - const previousSlice = currentSlice; - listener(currentSlice = nextSlice, previousSlice); - } - } - listeners.add(listenerToAdd); - return () => listeners.delete(listenerToAdd); - }; - const subscribe = (listener, selector, equalityFn) => { - if (selector || equalityFn) { - return subscribeWithSelector(listener, selector, equalityFn); - } - listeners.add(listener); - return () => listeners.delete(listener); - }; - const destroy = () => listeners.clear(); - const api = { setState, getState, subscribe, destroy }; - state = createState(setState, getState, api); - return api; -} - -const isSSR$3 = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); -const useIsomorphicLayoutEffect$2 = isSSR$3 ? React.useEffect : React.useLayoutEffect; -function create$4(createState) { - const api = typeof createState === "function" ? createStore$3(createState) : createState; - const useStore = (selector = api.getState, equalityFn = Object.is) => { - const [, forceUpdate] = React.useReducer((c) => c + 1, 0); - const state = api.getState(); - const stateRef = React.useRef(state); - const selectorRef = React.useRef(selector); - const equalityFnRef = React.useRef(equalityFn); - const erroredRef = React.useRef(false); - const currentSliceRef = React.useRef(); - if (currentSliceRef.current === void 0) { - currentSliceRef.current = selector(state); - } - let newStateSlice; - let hasNewStateSlice = false; - if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) { - newStateSlice = selector(state); - hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice); - } - useIsomorphicLayoutEffect$2(() => { - if (hasNewStateSlice) { - currentSliceRef.current = newStateSlice; - } - stateRef.current = state; - selectorRef.current = selector; - equalityFnRef.current = equalityFn; - erroredRef.current = false; - }); - const stateBeforeSubscriptionRef = React.useRef(state); - useIsomorphicLayoutEffect$2(() => { - const listener = () => { - try { - const nextState = api.getState(); - const nextStateSlice = selectorRef.current(nextState); - if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) { - stateRef.current = nextState; - currentSliceRef.current = nextStateSlice; - forceUpdate(); - } - } catch (error) { - erroredRef.current = true; - forceUpdate(); - } - }; - const unsubscribe = api.subscribe(listener); - if (api.getState() !== stateBeforeSubscriptionRef.current) { - listener(); - } - return unsubscribe; - }, []); - const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current; - React.useDebugValue(sliceToReturn); - return sliceToReturn; - }; - Object.assign(useStore, api); - useStore[Symbol.iterator] = function() { - console.warn("[useStore, api] = create() is deprecated and will be removed in v4"); - const items = [useStore, api]; - return { - next() { - const done = items.length <= 0; - return { value: items.shift(), done }; - } - }; - }; - return useStore; -} - -var reactReconciler = {exports: {}}; - -var scheduler$1 = {exports: {}}; - -var scheduler_production_min = {}; - -/** - * @license React - * scheduler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredScheduler_production_min; - -function requireScheduler_production_min () { - if (hasRequiredScheduler_production_min) return scheduler_production_min; - hasRequiredScheduler_production_min = 1; - (function (exports) { -function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} - function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; - "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} - function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; - function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; - exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; -} (scheduler_production_min)); - return scheduler_production_min; -} - -var scheduler_development = {}; - -/** - * @license React - * scheduler.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredScheduler_development; - -function requireScheduler_development () { - if (hasRequiredScheduler_development) return scheduler_development; - hasRequiredScheduler_development = 1; - (function (exports) { - - if (process.env.NODE_ENV !== "production") { - (function() { - - /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ - if ( - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === - 'function' - ) { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); - } - var enableSchedulerDebugging = false; - var enableProfiling = false; - var frameYieldMs = 5; - - function push(heap, node) { - var index = heap.length; - heap.push(node); - siftUp(heap, node, index); - } - function peek(heap) { - return heap.length === 0 ? null : heap[0]; - } - function pop(heap) { - if (heap.length === 0) { - return null; - } - - var first = heap[0]; - var last = heap.pop(); - - if (last !== first) { - heap[0] = last; - siftDown(heap, last, 0); - } - - return first; - } - - function siftUp(heap, node, i) { - var index = i; - - while (index > 0) { - var parentIndex = index - 1 >>> 1; - var parent = heap[parentIndex]; - - if (compare(parent, node) > 0) { - // The parent is larger. Swap positions. - heap[parentIndex] = node; - heap[index] = parent; - index = parentIndex; - } else { - // The parent is smaller. Exit. - return; - } - } - } - - function siftDown(heap, node, i) { - var index = i; - var length = heap.length; - var halfLength = length >>> 1; - - while (index < halfLength) { - var leftIndex = (index + 1) * 2 - 1; - var left = heap[leftIndex]; - var rightIndex = leftIndex + 1; - var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. - - if (compare(left, node) < 0) { - if (rightIndex < length && compare(right, left) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - heap[index] = left; - heap[leftIndex] = node; - index = leftIndex; - } - } else if (rightIndex < length && compare(right, node) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - // Neither child is smaller. Exit. - return; - } - } - } - - function compare(a, b) { - // Compare sort index first, then task id. - var diff = a.sortIndex - b.sortIndex; - return diff !== 0 ? diff : a.id - b.id; - } - - // TODO: Use symbols? - var ImmediatePriority = 1; - var UserBlockingPriority = 2; - var NormalPriority = 3; - var LowPriority = 4; - var IdlePriority = 5; - - function markTaskErrored(task, ms) { - } - - /* eslint-disable no-var */ - - var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; - - if (hasPerformanceNow) { - var localPerformance = performance; - - exports.unstable_now = function () { - return localPerformance.now(); - }; - } else { - var localDate = Date; - var initialTime = localDate.now(); - - exports.unstable_now = function () { - return localDate.now() - initialTime; - }; - } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. - // Math.pow(2, 30) - 1 - // 0b111111111111111111111111111111 - - - var maxSigned31BitInt = 1073741823; // Times out immediately - - var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out - - var USER_BLOCKING_PRIORITY_TIMEOUT = 250; - var NORMAL_PRIORITY_TIMEOUT = 5000; - var LOW_PRIORITY_TIMEOUT = 10000; // Never times out - - var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap - - var taskQueue = []; - var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. - - var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. - var currentTask = null; - var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. - - var isPerformingWork = false; - var isHostCallbackScheduled = false; - var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. - - var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; - var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; - var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom - - typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; - - function advanceTimers(currentTime) { - // Check for tasks that are no longer delayed and add them to the queue. - var timer = peek(timerQueue); - - while (timer !== null) { - if (timer.callback === null) { - // Timer was cancelled. - pop(timerQueue); - } else if (timer.startTime <= currentTime) { - // Timer fired. Transfer to the task queue. - pop(timerQueue); - timer.sortIndex = timer.expirationTime; - push(taskQueue, timer); - } else { - // Remaining timers are pending. - return; - } - - timer = peek(timerQueue); - } - } - - function handleTimeout(currentTime) { - isHostTimeoutScheduled = false; - advanceTimers(currentTime); - - if (!isHostCallbackScheduled) { - if (peek(taskQueue) !== null) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } else { - var firstTimer = peek(timerQueue); - - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - } - } - } - - function flushWork(hasTimeRemaining, initialTime) { - - - isHostCallbackScheduled = false; - - if (isHostTimeoutScheduled) { - // We scheduled a timeout but it's no longer needed. Cancel it. - isHostTimeoutScheduled = false; - cancelHostTimeout(); - } - - isPerformingWork = true; - var previousPriorityLevel = currentPriorityLevel; - - try { - var currentTime; if (enableProfiling) ; else { - // No catch in prod code path. - return workLoop(hasTimeRemaining, initialTime); - } - } finally { - currentTask = null; - currentPriorityLevel = previousPriorityLevel; - isPerformingWork = false; - } - } - - function workLoop(hasTimeRemaining, initialTime) { - var currentTime = initialTime; - advanceTimers(currentTime); - currentTask = peek(taskQueue); - - while (currentTask !== null && !(enableSchedulerDebugging )) { - if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { - // This currentTask hasn't expired, and we've reached the deadline. - break; - } - - var callback = currentTask.callback; - - if (typeof callback === 'function') { - currentTask.callback = null; - currentPriorityLevel = currentTask.priorityLevel; - var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; - - var continuationCallback = callback(didUserCallbackTimeout); - currentTime = exports.unstable_now(); - - if (typeof continuationCallback === 'function') { - currentTask.callback = continuationCallback; - } else { - - if (currentTask === peek(taskQueue)) { - pop(taskQueue); - } - } - - advanceTimers(currentTime); - } else { - pop(taskQueue); - } - - currentTask = peek(taskQueue); - } // Return whether there's additional work - - - if (currentTask !== null) { - return true; - } else { - var firstTimer = peek(timerQueue); - - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - - return false; - } - } - - function unstable_runWithPriority(priorityLevel, eventHandler) { - switch (priorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - case LowPriority: - case IdlePriority: - break; - - default: - priorityLevel = NormalPriority; - } - - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - - function unstable_next(eventHandler) { - var priorityLevel; - - switch (currentPriorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - // Shift down to normal priority - priorityLevel = NormalPriority; - break; - - default: - // Anything lower than normal priority should remain at the current level. - priorityLevel = currentPriorityLevel; - break; - } - - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - - function unstable_wrapCallback(callback) { - var parentPriorityLevel = currentPriorityLevel; - return function () { - // This is a fork of runWithPriority, inlined for performance. - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = parentPriorityLevel; - - try { - return callback.apply(this, arguments); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - }; - } - - function unstable_scheduleCallback(priorityLevel, callback, options) { - var currentTime = exports.unstable_now(); - var startTime; - - if (typeof options === 'object' && options !== null) { - var delay = options.delay; - - if (typeof delay === 'number' && delay > 0) { - startTime = currentTime + delay; - } else { - startTime = currentTime; - } - } else { - startTime = currentTime; - } - - var timeout; - - switch (priorityLevel) { - case ImmediatePriority: - timeout = IMMEDIATE_PRIORITY_TIMEOUT; - break; - - case UserBlockingPriority: - timeout = USER_BLOCKING_PRIORITY_TIMEOUT; - break; - - case IdlePriority: - timeout = IDLE_PRIORITY_TIMEOUT; - break; - - case LowPriority: - timeout = LOW_PRIORITY_TIMEOUT; - break; - - case NormalPriority: - default: - timeout = NORMAL_PRIORITY_TIMEOUT; - break; - } - - var expirationTime = startTime + timeout; - var newTask = { - id: taskIdCounter++, - callback: callback, - priorityLevel: priorityLevel, - startTime: startTime, - expirationTime: expirationTime, - sortIndex: -1 - }; - - if (startTime > currentTime) { - // This is a delayed task. - newTask.sortIndex = startTime; - push(timerQueue, newTask); - - if (peek(taskQueue) === null && newTask === peek(timerQueue)) { - // All tasks are delayed, and this is the task with the earliest delay. - if (isHostTimeoutScheduled) { - // Cancel an existing timeout. - cancelHostTimeout(); - } else { - isHostTimeoutScheduled = true; - } // Schedule a timeout. - - - requestHostTimeout(handleTimeout, startTime - currentTime); - } - } else { - newTask.sortIndex = expirationTime; - push(taskQueue, newTask); - // wait until the next time we yield. - - - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - - return newTask; - } - - function unstable_pauseExecution() { - } - - function unstable_continueExecution() { - - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - - function unstable_getFirstCallbackNode() { - return peek(taskQueue); - } - - function unstable_cancelCallback(task) { - // remove from the queue because you can't remove arbitrary nodes from an - // array based heap, only the first one.) - - - task.callback = null; - } - - function unstable_getCurrentPriorityLevel() { - return currentPriorityLevel; - } - - var isMessageLoopRunning = false; - var scheduledHostCallback = null; - var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main - // thread, like user events. By default, it yields multiple times per frame. - // It does not attempt to align with frame boundaries, since most tasks don't - // need to be frame aligned; for those that do, use requestAnimationFrame. - - var frameInterval = frameYieldMs; - var startTime = -1; - - function shouldYieldToHost() { - var timeElapsed = exports.unstable_now() - startTime; - - if (timeElapsed < frameInterval) { - // The main thread has only been blocked for a really short amount of time; - // smaller than a single frame. Don't yield yet. - return false; - } // The main thread has been blocked for a non-negligible amount of time. We - - - return true; - } - - function requestPaint() { - - } - - function forceFrameRate(fps) { - if (fps < 0 || fps > 125) { - // Using console['error'] to evade Babel and ESLint - console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); - return; - } - - if (fps > 0) { - frameInterval = Math.floor(1000 / fps); - } else { - // reset the framerate - frameInterval = frameYieldMs; - } - } - - var performWorkUntilDeadline = function () { - if (scheduledHostCallback !== null) { - var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread - // has been blocked. - - startTime = currentTime; - var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the - // error can be observed. - // - // Intentionally not using a try-catch, since that makes some debugging - // techniques harder. Instead, if `scheduledHostCallback` errors, then - // `hasMoreWork` will remain true, and we'll continue the work loop. - - var hasMoreWork = true; - - try { - hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); - } finally { - if (hasMoreWork) { - // If there's more work, schedule the next message event at the end - // of the preceding one. - schedulePerformWorkUntilDeadline(); - } else { - isMessageLoopRunning = false; - scheduledHostCallback = null; - } - } - } else { - isMessageLoopRunning = false; - } // Yielding to the browser will give it a chance to paint, so we can - }; - - var schedulePerformWorkUntilDeadline; - - if (typeof localSetImmediate === 'function') { - // Node.js and old IE. - // There's a few reasons for why we prefer setImmediate. - // - // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. - // (Even though this is a DOM fork of the Scheduler, you could get here - // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) - // https://github.com/facebook/react/issues/20756 - // - // But also, it runs earlier which is the semantic we want. - // If other browsers ever implement it, it's better to use it. - // Although both of these would be inferior to native scheduling. - schedulePerformWorkUntilDeadline = function () { - localSetImmediate(performWorkUntilDeadline); - }; - } else if (typeof MessageChannel !== 'undefined') { - // DOM and Worker environments. - // We prefer MessageChannel because of the 4ms setTimeout clamping. - var channel = new MessageChannel(); - var port = channel.port2; - channel.port1.onmessage = performWorkUntilDeadline; - - schedulePerformWorkUntilDeadline = function () { - port.postMessage(null); - }; - } else { - // We should only fallback here in non-browser environments. - schedulePerformWorkUntilDeadline = function () { - localSetTimeout(performWorkUntilDeadline, 0); - }; - } - - function requestHostCallback(callback) { - scheduledHostCallback = callback; - - if (!isMessageLoopRunning) { - isMessageLoopRunning = true; - schedulePerformWorkUntilDeadline(); - } - } - - function requestHostTimeout(callback, ms) { - taskTimeoutID = localSetTimeout(function () { - callback(exports.unstable_now()); - }, ms); - } - - function cancelHostTimeout() { - localClearTimeout(taskTimeoutID); - taskTimeoutID = -1; - } - - var unstable_requestPaint = requestPaint; - var unstable_Profiling = null; - - exports.unstable_IdlePriority = IdlePriority; - exports.unstable_ImmediatePriority = ImmediatePriority; - exports.unstable_LowPriority = LowPriority; - exports.unstable_NormalPriority = NormalPriority; - exports.unstable_Profiling = unstable_Profiling; - exports.unstable_UserBlockingPriority = UserBlockingPriority; - exports.unstable_cancelCallback = unstable_cancelCallback; - exports.unstable_continueExecution = unstable_continueExecution; - exports.unstable_forceFrameRate = forceFrameRate; - exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; - exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; - exports.unstable_next = unstable_next; - exports.unstable_pauseExecution = unstable_pauseExecution; - exports.unstable_requestPaint = unstable_requestPaint; - exports.unstable_runWithPriority = unstable_runWithPriority; - exports.unstable_scheduleCallback = unstable_scheduleCallback; - exports.unstable_shouldYield = shouldYieldToHost; - exports.unstable_wrapCallback = unstable_wrapCallback; - /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ - if ( - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === - 'function' - ) { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); - } - - })(); - } -} (scheduler_development)); - return scheduler_development; -} - -(function (module) { - - if (process.env.NODE_ENV === 'production') { - module.exports = requireScheduler_production_min(); - } else { - module.exports = requireScheduler_development(); - } -} (scheduler$1)); - -/** - * @license React - * react-reconciler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var reactReconciler_production_min; -var hasRequiredReactReconciler_production_min; - -function requireReactReconciler_production_min () { - if (hasRequiredReactReconciler_production_min) return reactReconciler_production_min; - hasRequiredReactReconciler_production_min = 1; - reactReconciler_production_min = function $$$reconciler($$$hostConfig) { - var exports = {}; -var aa=React__default["default"],ba=scheduler$1.exports,ca=Object.assign;function n(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;ch||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{bc=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?ac(a):""}var dc=Object.prototype.hasOwnProperty,ec=[],fc=-1;function gc(a){return {current:a}} - function x(a){0>fc||(a.current=ec[fc],ec[fc]=null,fc--);}function y(a,b){fc++;ec[fc]=a.current;a.current=b;}var hc={},A=gc(hc),B=gc(!1),ic=hc;function jc(a,b){var c=a.type.contextTypes;if(!c)return hc;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} - function C(a){a=a.childContextTypes;return null!==a&&void 0!==a}function kc(){x(B);x(A);}function lc(a,b,c){if(A.current!==hc)throw Error(n(168));y(A,b);y(B,c);}function mc(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(n(108,xa(a)||"Unknown",e));return ca({},c,d)} - function nc(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||hc;ic=A.current;y(A,a);y(B,B.current);return !0}function oc(a,b,c){var d=a.stateNode;if(!d)throw Error(n(169));c?(a=mc(a,b,ic),d.__reactInternalMemoizedMergedChildContext=a,x(B),x(A),y(A,a)):x(B);y(B,c);}var qc=Math.clz32?Math.clz32:pc,rc=Math.log,sc=Math.LN2;function pc(a){a>>>=0;return 0===a?32:31-(rc(a)/sc|0)|0}var tc=64,uc=4194304; - function vc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; - default:return a}}function wc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=vc(h):(f&=g,0!==f&&(d=vc(f)));}else g=c&~e,0!==g?d=vc(g):0!==f&&(d=vc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}function Bc(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-qc(b);a[b]=c;} - function Cc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0>=g;e-=g;Nd=1<<32-qc(b)+e|c<u?(t=w,w=null):t=w.sibling;var q=r(e,w,h[u],k);if(null===q){null===w&&(w=t);break}a&&w&&null===q.alternate&&b(e,w);g=f(q,g,u);null===m?l=q:m.sibling=q;m=q;w=t;}if(u===h.length)return c(e,w),I&&Pd(e,u),l;if(null===w){for(;uu?(q=m,m=null):q=m.sibling;var V=r(e,m,t.value,k);if(null===V){null===m&&(m=q);break}a&&m&&null===V.alternate&&b(e,m);g=f(V,g,u);null===w?l=V:w.sibling=V;w=V;m=q;}if(t.done)return c(e, - m),I&&Pd(e,u),l;if(null===m){for(;!t.done;u++,t=h.next())t=v(e,t.value,k),null!==t&&(g=f(t,g,u),null===w?l=t:w.sibling=t,w=t);I&&Pd(e,u);return l}for(m=d(e,m);!t.done;u++,t=h.next())t=z(m,e,u,t.value,k),null!==t&&(a&&null!==t.alternate&&m.delete(null===t.key?u:t.key),g=f(t,g,u),null===w?l=t:w.sibling=t,w=t);a&&m.forEach(function(a){return b(e,a)});I&&Pd(e,u);return l}function da(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ia&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!== - f){switch(f.$$typeof){case fa:a:{for(var k=f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ia){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===ra&&he(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=fe(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===ia?(d=ne(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=le(f.type,f.key,f.props,null,a.mode,h),h.ref=fe(a,d,f),h.return= - a,a=h);}return g(a);case ha:a:{for(l=f.key;null!==d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=me(f,a.mode,h);d.return=a;a=d;}return g(a);case ra:return l=f._init,da(a,d,l(f._payload),h)}if(Ea(f))return q(a,d,f,h);if(ua(f))return N(a,d,f,h);ge(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&& - 6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=ke(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return da}var oe=ie(!0),pe=ie(!1),qe={},re=gc(qe),se=gc(qe),te=gc(qe);function ue(a){if(a===qe)throw Error(n(174));return a}function ve(a,b){y(te,b);y(se,a);y(re,qe);a=Ga(b);x(re);y(re,a);}function we(){x(re);x(se);x(te);}function xe(a){var b=ue(te.current),c=ue(re.current);b=Ha(c,a.type,b);c!==b&&(y(se,a),y(re,b));}function ye(a){se.current===a&&(x(re),x(se));}var J=gc(0); - function ze(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||Ib(c)||Jb(c)))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Ae=[]; - function Be(){for(var a=0;ac?c:4;a(!0);var d=De.transition;De.transition={};try{a(!1),b();}finally{D=c,De.transition=d;}}function rf(){return Re().memoizedState}function sf(a,b,c){var d=zd(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};tf(a)?uf(b,c):(vf(a,b,c),c=H(),a=Ad(a,d,c),null!==a&&wf(a,b,d));} - function df(a,b,c){var d=zd(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(tf(a))uf(b,e);else {vf(a,b,e);var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(Rc(h,g))return}catch(k){}finally{}c=H();a=Ad(a,d,c);null!==a&&wf(a,b,d);}}function tf(a){var b=a.alternate;return a===K||null!==b&&b===K} - function uf(a,b){Ge=Fe=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function vf(a,b,c){null!==F&&0!==(a.mode&1)&&0===(G&2)?(a=b.interleaved,null===a?(c.next=c,null===md?md=[b]:md.push(b)):(c.next=a.next,a.next=c),b.interleaved=c):(a=b.pending,null===a?c.next=c:(c.next=a.next,a.next=c),b.pending=c);}function wf(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Dc(a,c);}} - var Oe={readContext:ld,useCallback:O,useContext:O,useEffect:O,useImperativeHandle:O,useInsertionEffect:O,useLayoutEffect:O,useMemo:O,useReducer:O,useRef:O,useState:O,useDebugValue:O,useDeferredValue:O,useTransition:O,useMutableSource:O,useSyncExternalStore:O,useId:O,unstable_isNewReconciler:!1},Le={readContext:ld,useCallback:function(a,b){Qe().memoizedState=[a,void 0===b?null:b];return a},useContext:ld,useEffect:hf,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ff(4194308, - 4,lf.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ff(4194308,4,a,b)},useInsertionEffect:function(a,b){return ff(4,2,a,b)},useMemo:function(a,b){var c=Qe();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Qe();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=sf.bind(null,K,a);return [d.memoizedState,a]},useRef:function(a){var b= - Qe();a={current:a};return b.memoizedState=a},useState:cf,useDebugValue:nf,useDeferredValue:function(a){var b=cf(a),c=b[0],d=b[1];hf(function(){var b=De.transition;De.transition={};try{d(a);}finally{De.transition=b;}},[a]);return c},useTransition:function(){var a=cf(!1),b=a[0];a=qf.bind(null,a[1]);Qe().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=K,e=Qe();if(I){if(void 0===c)throw Error(n(407));c=c();}else {c=b();if(null===F)throw Error(n(349)); - 0!==(Ee&30)||af(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;hf(Ye.bind(null,d,f,a),[a]);d.flags|=2048;Ze(9,$e.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Qe(),b=F.identifierPrefix;if(I){var c=Od;var d=Nd;c=(d&~(1<<32-qc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=He++;0Uf&&(b.flags|=128,d=!0,Qf(e,!1),b.lanes=4194304);}else {if(!d)if(a=ze(f),null!==a){if(b.flags|=128,d=!0,a=a.updateQueue,null!==a&&(b.updateQueue=a,b.flags|=4),Qf(e,!0),null===e.tail&&"hidden"===e.tailMode&&!f.alternate&&!I)return P(b),null}else 2*E()-e.renderingStartTime>Uf&&1073741824!==c&&(b.flags|=128,d=!0,Qf(e,!1),b.lanes=4194304);e.isBackwards?(f.sibling=b.child,b.child=f):(a=e.last,null!==a?a.sibling=f:b.child=f,e.last=f);}if(null!== - e.tail)return b=e.tail,e.rendering=b,e.tail=b.sibling,e.renderingStartTime=E(),b.sibling=null,a=J.current,y(J,d?a&1|2:a&1),b;P(b);return null;case 22:case 23:return Vf(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(Wf&1073741824)&&(P(b),Ua&&b.subtreeFlags&6&&(b.flags|=8192)):P(b),null;case 24:return null;case 25:return null}throw Error(n(156,b.tag));}var Xf=ea.ReactCurrentOwner,kd=!1; - function R(a,b,c,d){b.child=null===a?pe(b,null,c,d):oe(b,a.child,c,d);}function Yf(a,b,c,d,e){c=c.render;var f=b.ref;jd(b,e);d=Ke(a,b,c,d,f,e);c=Pe();if(null!==a&&!kd)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zf(a,b,e);I&&c&&Rd(b);b.flags|=1;R(a,b,d,e);return b.child} - function $f(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!ag(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,bg(a,b,f,d,e);a=le(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Zc;if(c(g,d)&&a.ref===b.ref)return Zf(a,b,e)}b.flags|=1;a=je(f,d);a.ref=b.ref;a.return=b;return b.child=a} - function bg(a,b,c,d,e){if(null!==a&&Zc(a.memoizedProps,d)&&a.ref===b.ref)if(kd=!1,0!==(a.lanes&e))0!==(a.flags&131072)&&(kd=!0);else return b.lanes=a.lanes,Zf(a,b,e);return cg(a,b,c,d,e)} - function dg(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null},y(eg,Wf),Wf|=c;else if(0!==(c&1073741824))b.memoizedState={baseLanes:0,cachePool:null},d=null!==f?f.baseLanes:c,y(eg,Wf),Wf|=d;else return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null},b.updateQueue=null,y(eg,Wf),Wf|=a,null;else null!==f?(d=f.baseLanes|c,b.memoizedState=null): - d=c,y(eg,Wf),Wf|=d;R(a,b,e,c);return b.child}function fg(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152;}function cg(a,b,c,d,e){var f=C(c)?ic:A.current;f=jc(b,f);jd(b,e);c=Ke(a,b,c,d,f,e);d=Pe();if(null!==a&&!kd)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zf(a,b,e);I&&d&&Rd(b);b.flags|=1;R(a,b,c,e);return b.child} - function gg(a,b,c,d,e){if(C(c)){var f=!0;nc(b);}else f=!1;jd(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),Dd(b,c,d),Fd(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=ld(l):(l=C(c)?ic:A.current,l=jc(b,l));var m=c.getDerivedStateFromProps,v="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;v||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!== - typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Ed(b,g,d,l);nd=!1;var r=b.memoizedState;g.state=r;ud(b,d,g,e);k=b.memoizedState;h!==d||r!==k||B.current||nd?("function"===typeof m&&(yd(b,c,m,d),k=b.memoizedState),(h=nd||Cd(b,c,h,d,r,k,l))?(v||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&& - (b.flags|=4194308)):("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1);}else {g=b.stateNode;pd(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:ad(b.type,h);g.props=l;v=b.pendingProps;r=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=ld(k):(k=C(c)?ic:A.current,k=jc(b,k));var z=c.getDerivedStateFromProps;(m="function"===typeof z||"function"=== - typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==v||r!==k)&&Ed(b,g,d,k);nd=!1;r=b.memoizedState;g.state=r;ud(b,d,g,e);var q=b.memoizedState;h!==v||r!==q||B.current||nd?("function"===typeof z&&(yd(b,c,z,d),q=b.memoizedState),(l=nd||Cd(b,c,l,d,r,q,k)||!1)?(m||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d, - q,k),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,q,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=q),g.props=d,g.state=q,g.context=k,d=l):("function"!== - typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1);}return hg(a,b,c,d,f,e)} - function hg(a,b,c,d,e,f){fg(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&oc(b,c,!1),Zf(a,b,f);d=b.stateNode;Xf.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=oe(b,a.child,null,f),b.child=oe(b,null,h,f)):R(a,b,h,f);b.memoizedState=d.state;e&&oc(b,c,!0);return b.child}function ig(a){var b=a.stateNode;b.pendingContext?lc(a,b.pendingContext,b.pendingContext!==b.context):b.context&&lc(a,b.context,!1);ve(a,b.containerInfo);} - function jg(a,b,c,d,e){de();ee(e);b.flags|=256;R(a,b,c,d);return b.child}var kg={dehydrated:null,treeContext:null,retryLane:0};function lg(a){return {baseLanes:a,cachePool:null}} - function mg(a,b,c){var d=b.pendingProps,e=J.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;y(J,e&1);if(null===a){ae(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:Jb(a)?b.lanes=8:b.lanes=1073741824,null;e=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,e={mode:"hidden",children:e},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=e): - f=ng(e,d,0,null),a=ne(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=lg(c),b.memoizedState=kg,a):og(b,e)}e=a.memoizedState;if(null!==e){h=e.dehydrated;if(null!==h){if(g){if(b.flags&256)return b.flags&=-257,pg(a,b,c,Error(n(422)));if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=ng({mode:"visible",children:d.children},e,0,null);f=ne(f,e,c,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&oe(b,a.child, - null,c);b.child.memoizedState=lg(c);b.memoizedState=kg;return f}if(0===(b.mode&1))b=pg(a,b,c,null);else if(Jb(h))b=pg(a,b,c,Error(n(419)));else if(d=0!==(c&a.childLanes),kd||d){d=F;if(null!==d){switch(c&-c){case 4:f=2;break;case 16:f=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:f=32;break;case 536870912:f= - 268435456;break;default:f=0;}d=0!==(f&(d.suspendedLanes|c))?0:f;0!==d&&d!==e.retryLane&&(e.retryLane=d,Ad(a,d,-1));}Tf();b=pg(a,b,c,Error(n(421)));}else Ib(h)?(b.flags|=128,b.child=a.child,b=qg.bind(null,a),Kb(h,b),b=null):(c=e.treeContext,p&&(Ud=Ob(h),Td=b,I=!0,Wd=null,Vd=!1,null!==c&&(Kd[Ld++]=Nd,Kd[Ld++]=Od,Kd[Ld++]=Md,Nd=c.id,Od=c.overflow,Md=b)),b=og(b,b.pendingProps.children),b.flags|=4096);return b}if(f)return d=rg(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState= - null===e?lg(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kg,d;c=sg(a,b,d.children,c);b.memoizedState=null;return c}if(f)return d=rg(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState=null===e?lg(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kg,d;c=sg(a,b,d.children,c);b.memoizedState=null;return c} - function og(a,b){b=ng({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function sg(a,b,c,d){var e=a.child;a=e.sibling;c=je(e,{mode:"visible",children:c});0===(b.mode&1)&&(c.lanes=d);c.return=b;c.sibling=null;null!==a&&(d=b.deletions,null===d?(b.deletions=[a],b.flags|=16):d.push(a));return b.child=c} - function rg(a,b,c,d,e){var f=b.mode;a=a.child;var g=a.sibling,h={mode:"hidden",children:c};0===(f&1)&&b.child!==a?(c=b.child,c.childLanes=0,c.pendingProps=h,b.deletions=null):(c=je(a,h),c.subtreeFlags=a.subtreeFlags&14680064);null!==g?d=je(g,d):(d=ne(d,f,e,null),d.flags|=2);d.return=b;c.return=b;c.sibling=d;b.child=c;return d}function pg(a,b,c,d){null!==d&&ee(d);oe(b,a.child,null,c);a=og(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a} - function tg(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);id(a.return,b,c);}function ug(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e);} - function vg(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;R(a,b,d.children,c);d=J.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else {if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&tg(a,c,b);else if(19===a.tag)tg(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return;}a.sibling.return=a.return;a=a.sibling;}d&=1;}y(J,d);if(0===(b.mode&1))b.memoizedState= - null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===ze(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);ug(b,!1,e,c,f);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===ze(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a;}ug(b,!0,c,null,f);break;case "together":ug(b,!1,null,null,void 0);break;default:b.memoizedState=null;}return b.child} - function Zf(a,b,c){null!==a&&(b.dependencies=a.dependencies);vd|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(n(153));if(null!==b.child){a=b.child;c=je(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=je(a,a.pendingProps),c.return=b;c.sibling=null;}return b.child} - function wg(a,b,c){switch(b.tag){case 3:ig(b);de();break;case 5:xe(b);break;case 1:C(b.type)&&nc(b);break;case 4:ve(b,b.stateNode.containerInfo);break;case 10:gd(b,b.type._context,b.memoizedProps.value);break;case 13:var d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return y(J,J.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return mg(a,b,c);y(J,J.current&1);a=Zf(a,b,c);return null!==a?a.sibling:null}y(J,J.current&1);break;case 19:d=0!==(c&b.childLanes);if(0!==(a.flags&128)){if(d)return vg(a, - b,c);b.flags|=128;}var e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);y(J,J.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,dg(a,b,c)}return Zf(a,b,c)} - function xg(a,b){Sd(b);switch(b.tag){case 1:return C(b.type)&&kc(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return we(),x(B),x(A),Be(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return ye(b),null;case 13:x(J);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(n(340));de();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return x(J),null;case 4:return we(),null;case 10:return hd(b.type._context),null;case 22:case 23:return Vf(), - null;case 24:return null;default:return null}}var yg=!1,zg=!1,Ag="function"===typeof WeakSet?WeakSet:Set,S=null;function Bg(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){T(a,b,d);}else c.current=null;}function Cg(a,b,c){try{c();}catch(d){T(a,b,d);}}var Dg=!1; - function Eg(a,b){Ia(a.containerInfo);for(S=b;null!==S;)if(a=S,b=a.child,0!==(a.subtreeFlags&1028)&&null!==b)b.return=a,S=b;else for(;null!==S;){a=S;try{var c=a.alternate;if(0!==(a.flags&1024))switch(a.tag){case 0:case 11:case 15:break;case 1:if(null!==c){var d=c.memoizedProps,e=c.memoizedState,f=a.stateNode,g=f.getSnapshotBeforeUpdate(a.elementType===a.type?d:ad(a.type,d),e);f.__reactInternalSnapshotBeforeUpdate=g;}break;case 3:Ua&&xb(a.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break; - default:throw Error(n(163));}}catch(h){T(a,a.return,h);}b=a.sibling;if(null!==b){b.return=a.return;S=b;break}S=a.return;}c=Dg;Dg=!1;return c}function Fg(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Cg(b,c,f);}e=e.next;}while(e!==d)}}function Gg(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}} - function Hg(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=Fa(c);break;default:a=c;}"function"===typeof b?b(a):b.current=a;}} - function Ig(a,b,c){if(Oc&&"function"===typeof Oc.onCommitFiberUnmount)try{Oc.onCommitFiberUnmount(Nc,b);}catch(g){}switch(b.tag){case 0:case 11:case 14:case 15:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var d=a=a.next;do{var e=d,f=e.destroy;e=e.tag;void 0!==f&&(0!==(e&2)?Cg(b,c,f):0!==(e&4)&&Cg(b,c,f));d=d.next;}while(d!==a)}break;case 1:Bg(b,c);a=b.stateNode;if("function"===typeof a.componentWillUnmount)try{a.props=b.memoizedProps,a.state=b.memoizedState,a.componentWillUnmount();}catch(g){T(b, - c,g);}break;case 5:Bg(b,c);break;case 4:Ua?Jg(a,b,c):Va&&Va&&(b=b.stateNode.containerInfo,c=zb(b),Cb(b,c));}}function Kg(a,b,c){for(var d=b;;)if(Ig(a,d,c),null===d.child||Ua&&4===d.tag){if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;}d.sibling.return=d.return;d=d.sibling;}else d.child.return=d,d=d.child;} - function Lg(a){var b=a.alternate;null!==b&&(a.alternate=null,Lg(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&Za(b));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Mg(a){return 5===a.tag||3===a.tag||4===a.tag} - function Ng(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Mg(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}} - function Og(a){if(Ua){a:{for(var b=a.return;null!==b;){if(Mg(b))break a;b=b.return;}throw Error(n(160));}var c=b;switch(c.tag){case 5:b=c.stateNode;c.flags&32&&(sb(b),c.flags&=-33);c=Ng(a);Pg(a,c,b);break;case 3:case 4:b=c.stateNode.containerInfo;c=Ng(a);Qg(a,c,b);break;default:throw Error(n(161));}}}function Qg(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?pb(c,a,b):kb(c,a);else if(4!==d&&(a=a.child,null!==a))for(Qg(a,b,c),a=a.sibling;null!==a;)Qg(a,b,c),a=a.sibling;} - function Pg(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?ob(c,a,b):jb(c,a);else if(4!==d&&(a=a.child,null!==a))for(Pg(a,b,c),a=a.sibling;null!==a;)Pg(a,b,c),a=a.sibling;} - function Jg(a,b,c){for(var d=b,e=!1,f,g;;){if(!e){e=d.return;a:for(;;){if(null===e)throw Error(n(160));f=e.stateNode;switch(e.tag){case 5:g=!1;break a;case 3:f=f.containerInfo;g=!0;break a;case 4:f=f.containerInfo;g=!0;break a}e=e.return;}e=!0;}if(5===d.tag||6===d.tag)Kg(a,d,c),g?rb(f,d.stateNode):qb(f,d.stateNode);else if(18===d.tag)g?Wb(f,d.stateNode):Vb(f,d.stateNode);else if(4===d.tag){if(null!==d.child){f=d.stateNode.containerInfo;g=!0;d.child.return=d;d=d.child;continue}}else if(Ig(a,d,c),null!== - d.child){d.child.return=d;d=d.child;continue}if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;4===d.tag&&(e=!1);}d.sibling.return=d.return;d=d.sibling;}} - function Rg(a,b){if(Ua){switch(b.tag){case 0:case 11:case 14:case 15:Fg(3,b,b.return);Gg(3,b);Fg(5,b,b.return);return;case 1:return;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps;a=null!==a?a.memoizedProps:d;var e=b.type,f=b.updateQueue;b.updateQueue=null;null!==f&&nb(c,f,e,a,d,b);}return;case 6:if(null===b.stateNode)throw Error(n(162));c=b.memoizedProps;lb(b.stateNode,null!==a?a.memoizedProps:c,c);return;case 3:p&&null!==a&&a.memoizedState.isDehydrated&&Tb(b.stateNode.containerInfo);return; - case 12:return;case 13:Sg(b);return;case 19:Sg(b);return;case 17:return}throw Error(n(163));}switch(b.tag){case 0:case 11:case 14:case 15:Fg(3,b,b.return);Gg(3,b);Fg(5,b,b.return);return;case 12:return;case 13:Sg(b);return;case 19:Sg(b);return;case 3:p&&null!==a&&a.memoizedState.isDehydrated&&Tb(b.stateNode.containerInfo);break;case 22:case 23:return}a:if(Va){switch(b.tag){case 1:case 5:case 6:break a;case 3:case 4:b=b.stateNode;Cb(b.containerInfo,b.pendingChildren);break a}throw Error(n(163));}} - function Sg(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Ag);b.forEach(function(b){var d=Tg.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}} - function Ug(a,b){for(S=b;null!==S;){b=S;var c=b.deletions;if(null!==c)for(var d=0;d";case bh:return ":has("+(ih(a)||"")+")";case ch:return '[role="'+a.value+'"]';case eh:return '"'+a.value+'"';case dh:return '[data-testname="'+a.value+'"]';default:throw Error(n(365));}} - function jh(a,b){var c=[];a=[a,0];for(var d=0;de&&(e=g);d&=~f;}d=e;d=E()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lh(d/1960))-d;if(10a?16:a;if(null===uh)var d=!1;else {a=uh;uh=null;vh=0;if(0!==(G&6))throw Error(n(331));var e=G;G|=4;for(S=a.current;null!==S;){var f=S,g=f.child;if(0!==(S.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kE()-Vg?Ih(a,0):qh|=c);Z(a,b);}function Vh(a,b){0===b&&(0===(a.mode&1)?b=1:(b=uc,uc<<=1,0===(uc&130023424)&&(uc=4194304)));var c=H();a=Ah(a,b);null!==a&&(Bc(a,b,c),Z(a,c));}function qg(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Vh(a,c);} - function Tg(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(n(314));}null!==d&&d.delete(b);Vh(a,c);}var Sh; - Sh=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||B.current)kd=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return kd=!1,wg(a,b,c);kd=0!==(a.flags&131072)?!0:!1;}else kd=!1,I&&0!==(b.flags&1048576)&&Qd(b,Jd,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;var e=jc(b,A.current);jd(b,c);e=Ke(null,b,d,a,e,c);var f=Pe();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof? - (b.tag=1,b.memoizedState=null,b.updateQueue=null,C(d)?(f=!0,nc(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,od(b),e.updater=Bd,b.stateNode=e,e._reactInternals=b,Fd(b,d,a,c),b=hg(null,b,d,!0,f,c)):(b.tag=0,I&&f&&Rd(b),R(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Wh(d);a=ad(d,a);switch(e){case 0:b=cg(null,b,d,a,c);break a;case 1:b=gg(null,b,d, - a,c);break a;case 11:b=Yf(null,b,d,a,c);break a;case 14:b=$f(null,b,d,ad(d.type,a),c);break a}throw Error(n(306,d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),cg(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),gg(a,b,d,e,c);case 3:a:{ig(b);if(null===a)throw Error(n(387));d=b.pendingProps;f=b.memoizedState;e=f.element;pd(a,b);ud(b,d,null,c);var g=b.memoizedState;d=g.element;if(p&&f.isDehydrated)if(f={element:d,isDehydrated:!1, - cache:g.cache,transitions:g.transitions},b.updateQueue.baseState=f,b.memoizedState=f,b.flags&256){e=Error(n(423));b=jg(a,b,d,c,e);break a}else if(d!==e){e=Error(n(424));b=jg(a,b,d,c,e);break a}else for(p&&(Ud=Nb(b.stateNode.containerInfo),Td=b,I=!0,Wd=null,Vd=!1),c=pe(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {de();if(d===e){b=Zf(a,b,c);break a}R(a,b,d,c);}b=b.child;}return b;case 5:return xe(b),null===a&&ae(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children, - Oa(d,e)?g=null:null!==f&&Oa(d,f)&&(b.flags|=32),fg(a,b),R(a,b,g,c),b.child;case 6:return null===a&&ae(b),null;case 13:return mg(a,b,c);case 4:return ve(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=oe(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),Yf(a,b,d,e,c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:return R(a,b,b.pendingProps.children,c),b.child;case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d= - b.type._context;e=b.pendingProps;f=b.memoizedProps;g=e.value;gd(b,d,g);if(null!==f)if(Rc(f.value,g)){if(f.children===e.children&&!B.current){b=Zf(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=qd(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|= - c);id(f.return,c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(n(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);id(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}R(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,jd(b,c),e=ld(e),d=d(e),b.flags|= - 1,R(a,b,d,c),b.child;case 14:return d=b.type,e=ad(d,b.pendingProps),e=ad(d.type,e),$f(a,b,d,e,c);case 15:return bg(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),b.tag=1,C(d)?(a=!0,nc(b)):a=!1,jd(b,c),Dd(b,d,e),Fd(b,d,e,c),hg(null,b,d,!0,a,c);case 19:return vg(a,b,c);case 22:return dg(a,b,c)}throw Error(n(156,b.tag));};function Dh(a,b){return Fc(a,b)} - function Xh(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Yd(a,b,c,d){return new Xh(a,b,c,d)}function ag(a){a=a.prototype;return !(!a||!a.isReactComponent)} - function Wh(a){if("function"===typeof a)return ag(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===na)return 11;if(a===qa)return 14}return 2} - function je(a,b){var c=a.alternate;null===c?(c=Yd(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; - c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} - function le(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)ag(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ia:return ne(c.children,e,f,b);case ja:g=8;e|=8;break;case ka:return a=Yd(12,c,b,e|2),a.elementType=ka,a.lanes=f,a;case oa:return a=Yd(13,c,b,e),a.elementType=oa,a.lanes=f,a;case pa:return a=Yd(19,c,b,e),a.elementType=pa,a.lanes=f,a;case sa:return ng(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case la:g=10;break a;case ma:g=9;break a;case na:g=11; - break a;case qa:g=14;break a;case ra:g=16;d=null;break a}throw Error(n(130,null==a?a:typeof a,""));}b=Yd(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function ne(a,b,c,d){a=Yd(7,a,d,b);a.lanes=c;return a}function ng(a,b,c,d){a=Yd(22,a,d,b);a.elementType=sa;a.lanes=c;a.stateNode={};return a}function ke(a,b,c){a=Yd(6,a,null,b);a.lanes=c;return a} - function me(a,b,c){b=Yd(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} - function Yh(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=Sa;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=Ac(0);this.expirationTimes=Ac(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=Ac(0);this.identifierPrefix=d;this.onRecoverableError=e;p&&(this.mutableSourceEagerHydrationData= - null);}function Zh(a,b,c,d,e,f,g,h,k){a=new Yh(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Yd(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null};od(f);return a} - function $h(a){if(!a)return hc;a=a._reactInternals;a:{if(ya(a)!==a||1!==a.tag)throw Error(n(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(C(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return;}while(null!==b);throw Error(n(171));}if(1===a.tag){var c=a.type;if(C(c))return mc(a,c,b)}return b} - function ai(a){var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(n(188));a=Object.keys(a).join(",");throw Error(n(268,a));}a=Ba(b);return null===a?null:a.stateNode}function bi(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c=l&&f>=v&&e<=m&&g<=r){a.splice(b,1);break}else if(!(d!==l||c.width!==k.width||rg)){v>f&&(k.height+=v-f,k.y=f);re)){l>d&&(k.width+= - l-d,k.x=d);mc&&(c=g)),g ")+"\n\nNo matching component was found for:\n ")+a.join(" > ")}return null}; - exports.getPublicRootInstance=function(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return Fa(a.child.stateNode);default:return a.child.stateNode}}; - exports.injectIntoDevTools=function(a){a={bundleType:a.bundleType,version:a.version,rendererPackageName:a.rendererPackageName,rendererConfig:a.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ea.ReactCurrentDispatcher,findHostInstanceByFiber:di,findFiberByHostInstance:a.findFiberByHostInstance|| - ei,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.0.0-fc46dba67-20220329"};if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)a=!1;else {var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)a=!0;else {try{Nc=b.inject(a),Oc=b;}catch(c){}a=b.checkDCE?!0:!1;}}return a};exports.isAlreadyRendering=function(){return !1}; - exports.observeVisibleRects=function(a,b,c,d){if(!bb)throw Error(n(363));a=kh(a,b);var e=ib(a,c,d).disconnect;return {disconnect:function(){e();}}};exports.registerMutableSourceForHydration=function(a,b){var c=b._getVersion;c=c(b._source);null==a.mutableSourceEagerHydrationData?a.mutableSourceEagerHydrationData=[b,c]:a.mutableSourceEagerHydrationData.push(b,c);};exports.runWithPriority=function(a,b){var c=D;try{return D=a,b()}finally{D=c;}};exports.shouldError=function(){return null}; - exports.shouldSuspend=function(){return !1};exports.updateContainer=function(a,b,c,d){var e=b.current,f=H(),g=zd(e);c=$h(c);null===b.context?b.context=c:b.pendingContext=c;b=qd(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);rd(e,b);a=Ad(e,g,f);null!==a&&sd(a,e,g);return g}; - - return exports; - }; - return reactReconciler_production_min; -} - -var reactReconciler_development = {exports: {}}; - -/** - * @license React - * react-reconciler.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredReactReconciler_development; - -function requireReactReconciler_development () { - if (hasRequiredReactReconciler_development) return reactReconciler_development.exports; - hasRequiredReactReconciler_development = 1; - - if (process.env.NODE_ENV !== "production") { - reactReconciler_development.exports = function $$$reconciler($$$hostConfig) { - var exports = {}; - - var React = React__default["default"]; - var Scheduler = scheduler$1.exports; - - var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - - var suppressWarning = false; - function setSuppressWarning(newSuppressWarning) { - { - suppressWarning = newSuppressWarning; - } - } // In DEV, calls to console.warn and console.error get replaced - // by calls to these methods by a Babel plugin. - // - // In PROD (or in packages without access to React internals), - // they are left as they are instead. - - function warn(format) { - { - if (!suppressWarning) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - printWarning('warn', format, args); - } - } - } - function error(format) { - { - if (!suppressWarning) { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - printWarning('error', format, args); - } - } - } - - function printWarning(level, format, args) { - // When changing this logic, you might want to also - // update consoleWithStackDev.www.js as well. - { - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - - if (stack !== '') { - format += '%s'; - args = args.concat([stack]); - } // eslint-disable-next-line react-internal/safe-string-coercion - - - var argsWithFormat = args.map(function (item) { - return String(item); - }); // Careful: RN currently depends on this prefix - - argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it - // breaks IE9: https://github.com/facebook/react/issues/13610 - // eslint-disable-next-line react-internal/no-production-logging - - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - - var assign = Object.assign; - - /** - * `ReactInstanceMap` maintains a mapping from a public facing stateful - * instance (key) and the internal representation (value). This allows public - * methods to accept the user facing instance as an argument and map them back - * to internal methods. - * - * Note that this module is currently shared and assumed to be stateless. - * If this becomes an actual Map, that will break. - */ - function get(key) { - return key._reactInternals; - } - function set(key, value) { - key._reactInternals = value; - } - - // ----------------------------------------------------------------------------- - var enablePersistentOffscreenHostContainer = false; // ----------------------------------------------------------------------------- - // the react-reconciler package. - - var enableNewReconciler = false; // Support legacy Primer support on internal FB www - - var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics. - - var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber - - var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz - var warnAboutStringRefs = false; // ----------------------------------------------------------------------------- - // Debugging and DevTools - // ----------------------------------------------------------------------------- - // Adds user timing marks for e.g. state updates, suspense, and work loop stuff, - // for an experimental timeline tool. - - var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState - - var enableProfilerTimer = true; // Record durations for commit and passive effects phases. - - var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update". - - var FunctionComponent = 0; - var ClassComponent = 1; - var IndeterminateComponent = 2; // Before we know whether it is function or class - - var HostRoot = 3; // Root of a host tree. Could be nested inside another node. - - var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. - - var HostComponent = 5; - var HostText = 6; - var Fragment = 7; - var Mode = 8; - var ContextConsumer = 9; - var ContextProvider = 10; - var ForwardRef = 11; - var Profiler = 12; - var SuspenseComponent = 13; - var MemoComponent = 14; - var SimpleMemoComponent = 15; - var LazyComponent = 16; - var IncompleteClassComponent = 17; - var DehydratedFragment = 18; - var SuspenseListComponent = 19; - var ScopeComponent = 21; - var OffscreenComponent = 22; - var LegacyHiddenComponent = 23; - var CacheComponent = 24; - var TracingMarkerComponent = 25; - - // ATTENTION - // When adding new symbols to this file, - // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' - // The Symbol used to tag the ReactElement-like types. - var REACT_ELEMENT_TYPE = Symbol.for('react.element'); - var REACT_PORTAL_TYPE = Symbol.for('react.portal'); - var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); - var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); - var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); - var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); - var REACT_CONTEXT_TYPE = Symbol.for('react.context'); - var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); - var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); - var REACT_MEMO_TYPE = Symbol.for('react.memo'); - var REACT_LAZY_TYPE = Symbol.for('react.lazy'); - var REACT_SCOPE_TYPE = Symbol.for('react.scope'); - var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); - var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); - var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); - var REACT_CACHE_TYPE = Symbol.for('react.cache'); - var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker'); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = '@@iterator'; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== 'object') { - return null; - } - - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - - if (typeof maybeIterator === 'function') { - return maybeIterator; - } - - return null; - } - - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - - if (displayName) { - return displayName; - } - - var functionName = innerType.displayName || innerType.name || ''; - return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; - } // Keep in sync with react-reconciler/getComponentNameFromFiber - - - function getContextName(type) { - return type.displayName || 'Context'; - } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. - - - function getComponentNameFromType(type) { - if (type == null) { - // Host root, text node or just invalid type. - return null; - } - - { - if (typeof type.tag === 'number') { - error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); - } - } - - if (typeof type === 'function') { - return type.displayName || type.name || null; - } - - if (typeof type === 'string') { - return type; - } - - switch (type) { - case REACT_FRAGMENT_TYPE: - return 'Fragment'; - - case REACT_PORTAL_TYPE: - return 'Portal'; - - case REACT_PROFILER_TYPE: - return 'Profiler'; - - case REACT_STRICT_MODE_TYPE: - return 'StrictMode'; - - case REACT_SUSPENSE_TYPE: - return 'Suspense'; - - case REACT_SUSPENSE_LIST_TYPE: - return 'SuspenseList'; - - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + '.Consumer'; - - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + '.Provider'; - - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, 'ForwardRef'); - - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - - if (outerName !== null) { - return outerName; - } - - return getComponentNameFromType(type.type) || 'Memo'; - - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - return getComponentNameFromType(init(payload)); - } catch (x) { - return null; - } - } - - // eslint-disable-next-line no-fallthrough - } - } - - return null; - } - - function getWrappedName$1(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ''; - return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); - } // Keep in sync with shared/getComponentNameFromType - - - function getContextName$1(type) { - return type.displayName || 'Context'; - } - - function getComponentNameFromFiber(fiber) { - var tag = fiber.tag, - type = fiber.type; - - switch (tag) { - case CacheComponent: - return 'Cache'; - - case ContextConsumer: - var context = type; - return getContextName$1(context) + '.Consumer'; - - case ContextProvider: - var provider = type; - return getContextName$1(provider._context) + '.Provider'; - - case DehydratedFragment: - return 'DehydratedFragment'; - - case ForwardRef: - return getWrappedName$1(type, type.render, 'ForwardRef'); - - case Fragment: - return 'Fragment'; - - case HostComponent: - // Host component type is the display name (e.g. "div", "View") - return type; - - case HostPortal: - return 'Portal'; - - case HostRoot: - return 'Root'; - - case HostText: - return 'Text'; - - case LazyComponent: - // Name comes from the type in this case; we don't have a tag. - return getComponentNameFromType(type); - - case Mode: - if (type === REACT_STRICT_MODE_TYPE) { - // Don't be less specific than shared/getComponentNameFromType - return 'StrictMode'; - } - - return 'Mode'; - - case OffscreenComponent: - return 'Offscreen'; - - case Profiler: - return 'Profiler'; - - case ScopeComponent: - return 'Scope'; - - case SuspenseComponent: - return 'Suspense'; - - case SuspenseListComponent: - return 'SuspenseList'; - - case TracingMarkerComponent: - return 'TracingMarker'; - // The display name for this tags come from the user-provided type: - - case ClassComponent: - case FunctionComponent: - case IncompleteClassComponent: - case IndeterminateComponent: - case MemoComponent: - case SimpleMemoComponent: - if (typeof type === 'function') { - return type.displayName || type.name || null; - } - - if (typeof type === 'string') { - return type; - } - - break; - - } - - return null; - } - - // Don't change these two values. They're used by React Dev Tools. - var NoFlags = - /* */ - 0; - var PerformedWork = - /* */ - 1; // You can change the rest (and add more). - - var Placement = - /* */ - 2; - var Update = - /* */ - 4; - var PlacementAndUpdate = - /* */ - Placement | Update; - var ChildDeletion = - /* */ - 16; - var ContentReset = - /* */ - 32; - var Callback = - /* */ - 64; - var DidCapture = - /* */ - 128; - var ForceClientRender = - /* */ - 256; - var Ref = - /* */ - 512; - var Snapshot = - /* */ - 1024; - var Passive = - /* */ - 2048; - var Hydrating = - /* */ - 4096; - var HydratingAndUpdate = - /* */ - Hydrating | Update; - var Visibility = - /* */ - 8192; - var StoreConsistency = - /* */ - 16384; - var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit) - - var HostEffectMask = - /* */ - 32767; // These are not really side effects, but we still reuse this field. - - var Incomplete = - /* */ - 32768; - var ShouldCapture = - /* */ - 65536; - var ForceUpdateForLegacySuspense = - /* */ - 131072; - var Forked = - /* */ - 1048576; // Static tags describe aspects of a fiber that are not specific to a render, - // e.g. a fiber uses a passive effect (even if there are no updates on this particular render). - // This enables us to defer more work in the unmount case, - // since we can defer traversing the tree during layout to look for Passive effects, - // and instead rely on the static flag as a signal that there may be cleanup work. - - var RefStatic = - /* */ - 2097152; - var LayoutStatic = - /* */ - 4194304; - var PassiveStatic = - /* */ - 8388608; // These flags allow us to traverse to fibers that have effects on mount - // without traversing the entire tree after every commit for - // double invoking - - var MountLayoutDev = - /* */ - 16777216; - var MountPassiveDev = - /* */ - 33554432; // Groups of flags that are used in the commit phase to skip over trees that - // don't contain effects, by checking subtreeFlags. - - var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility - // flag logic (see #20043) - Update | Snapshot | ( 0); - var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; - var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask - - var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones. - // This allows certain concepts to persist without recalculating them, - // e.g. whether a subtree contains passive effects or portals. - - var StaticMask = LayoutStatic | PassiveStatic | RefStatic; - - var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; - function getNearestMountedFiber(fiber) { - var node = fiber; - var nearestMounted = fiber; - - if (!fiber.alternate) { - // If there is no alternate, this might be a new tree that isn't inserted - // yet. If it is, then it will have a pending insertion effect on it. - var nextNode = node; - - do { - node = nextNode; - - if ((node.flags & (Placement | Hydrating)) !== NoFlags) { - // This is an insertion or in-progress hydration. The nearest possible - // mounted fiber is the parent but we need to continue to figure out - // if that one is still mounted. - nearestMounted = node.return; - } - - nextNode = node.return; - } while (nextNode); - } else { - while (node.return) { - node = node.return; - } - } - - if (node.tag === HostRoot) { - // TODO: Check if this was a nested HostRoot when used with - // renderContainerIntoSubtree. - return nearestMounted; - } // If we didn't hit the root, that means that we're in an disconnected tree - // that has been unmounted. - - - return null; - } - function isFiberMounted(fiber) { - return getNearestMountedFiber(fiber) === fiber; - } - function isMounted(component) { - { - var owner = ReactCurrentOwner.current; - - if (owner !== null && owner.tag === ClassComponent) { - var ownerFiber = owner; - var instance = ownerFiber.stateNode; - - if (!instance._warnedAboutRefsInRender) { - error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component'); - } - - instance._warnedAboutRefsInRender = true; - } - } - - var fiber = get(component); - - if (!fiber) { - return false; - } - - return getNearestMountedFiber(fiber) === fiber; - } - - function assertIsMounted(fiber) { - if (getNearestMountedFiber(fiber) !== fiber) { - throw new Error('Unable to find node on an unmounted component.'); - } - } - - function findCurrentFiberUsingSlowPath(fiber) { - var alternate = fiber.alternate; - - if (!alternate) { - // If there is no alternate, then we only need to check if it is mounted. - var nearestMounted = getNearestMountedFiber(fiber); - - if (nearestMounted === null) { - throw new Error('Unable to find node on an unmounted component.'); - } - - if (nearestMounted !== fiber) { - return null; - } - - return fiber; - } // If we have two possible branches, we'll walk backwards up to the root - // to see what path the root points to. On the way we may hit one of the - // special cases and we'll deal with them. - - - var a = fiber; - var b = alternate; - - while (true) { - var parentA = a.return; - - if (parentA === null) { - // We're at the root. - break; - } - - var parentB = parentA.alternate; - - if (parentB === null) { - // There is no alternate. This is an unusual case. Currently, it only - // happens when a Suspense component is hidden. An extra fragment fiber - // is inserted in between the Suspense fiber and its children. Skip - // over this extra fragment fiber and proceed to the next parent. - var nextParent = parentA.return; - - if (nextParent !== null) { - a = b = nextParent; - continue; - } // If there's no parent, we're at the root. - - - break; - } // If both copies of the parent fiber point to the same child, we can - // assume that the child is current. This happens when we bailout on low - // priority: the bailed out fiber's child reuses the current child. - - - if (parentA.child === parentB.child) { - var child = parentA.child; - - while (child) { - if (child === a) { - // We've determined that A is the current branch. - assertIsMounted(parentA); - return fiber; - } - - if (child === b) { - // We've determined that B is the current branch. - assertIsMounted(parentA); - return alternate; - } - - child = child.sibling; - } // We should never have an alternate for any mounting node. So the only - // way this could possibly happen is if this was unmounted, if at all. - - - throw new Error('Unable to find node on an unmounted component.'); - } - - if (a.return !== b.return) { - // The return pointer of A and the return pointer of B point to different - // fibers. We assume that return pointers never criss-cross, so A must - // belong to the child set of A.return, and B must belong to the child - // set of B.return. - a = parentA; - b = parentB; - } else { - // The return pointers point to the same fiber. We'll have to use the - // default, slow path: scan the child sets of each parent alternate to see - // which child belongs to which set. - // - // Search parent A's child set - var didFindChild = false; - var _child = parentA.child; - - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentA; - b = parentB; - break; - } - - if (_child === b) { - didFindChild = true; - b = parentA; - a = parentB; - break; - } - - _child = _child.sibling; - } - - if (!didFindChild) { - // Search parent B's child set - _child = parentB.child; - - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentB; - b = parentA; - break; - } - - if (_child === b) { - didFindChild = true; - b = parentB; - a = parentA; - break; - } - - _child = _child.sibling; - } - - if (!didFindChild) { - throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.'); - } - } - } - - if (a.alternate !== b) { - throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.'); - } - } // If the root is not a host container, we're in a disconnected tree. I.e. - // unmounted. - - - if (a.tag !== HostRoot) { - throw new Error('Unable to find node on an unmounted component.'); - } - - if (a.stateNode.current === a) { - // We've determined that A is the current branch. - return fiber; - } // Otherwise B has to be current branch. - - - return alternate; - } - function findCurrentHostFiber(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null; - } - - function findCurrentHostFiberImpl(node) { - // Next we'll drill down this component to find the first HostComponent/Text. - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } - - var child = node.child; - - while (child !== null) { - var match = findCurrentHostFiberImpl(child); - - if (match !== null) { - return match; - } - - child = child.sibling; - } - - return null; - } - - function findCurrentHostFiberWithNoPortals(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null; - } - - function findCurrentHostFiberWithNoPortalsImpl(node) { - // Next we'll drill down this component to find the first HostComponent/Text. - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } - - var child = node.child; - - while (child !== null) { - if (child.tag !== HostPortal) { - var match = findCurrentHostFiberWithNoPortalsImpl(child); - - if (match !== null) { - return match; - } - } - - child = child.sibling; - } - - return null; - } - - var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare - - function isArray(a) { - return isArrayImpl(a); - } - - // This is a host config that's used for the `react-reconciler` package on npm. - // It is only used by third-party renderers. - // - // Its API lets you pass the host config as an argument. - // However, inside the `react-reconciler` we treat host config as a module. - // This file is a shim between two worlds. - // - // It works because the `react-reconciler` bundle is wrapped in something like: - // - // module.exports = function ($$$config) { - // /* reconciler code */ - // } - // - // So `$$$config` looks like a global variable, but it's - // really an argument to a top-level wrapping function. - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - // eslint-disable-line no-undef - var getPublicInstance = $$$hostConfig.getPublicInstance; - var getRootHostContext = $$$hostConfig.getRootHostContext; - var getChildHostContext = $$$hostConfig.getChildHostContext; - var prepareForCommit = $$$hostConfig.prepareForCommit; - var resetAfterCommit = $$$hostConfig.resetAfterCommit; - var createInstance = $$$hostConfig.createInstance; - var appendInitialChild = $$$hostConfig.appendInitialChild; - var finalizeInitialChildren = $$$hostConfig.finalizeInitialChildren; - var prepareUpdate = $$$hostConfig.prepareUpdate; - var shouldSetTextContent = $$$hostConfig.shouldSetTextContent; - var createTextInstance = $$$hostConfig.createTextInstance; - var scheduleTimeout = $$$hostConfig.scheduleTimeout; - var cancelTimeout = $$$hostConfig.cancelTimeout; - var noTimeout = $$$hostConfig.noTimeout; - $$$hostConfig.now; - var isPrimaryRenderer = $$$hostConfig.isPrimaryRenderer; - var warnsIfNotActing = $$$hostConfig.warnsIfNotActing; - var supportsMutation = $$$hostConfig.supportsMutation; - var supportsPersistence = $$$hostConfig.supportsPersistence; - var supportsHydration = $$$hostConfig.supportsHydration; - var getInstanceFromNode = $$$hostConfig.getInstanceFromNode; - $$$hostConfig.beforeActiveInstanceBlur; - $$$hostConfig.afterActiveInstanceBlur; - var preparePortalMount = $$$hostConfig.preparePortalMount; - $$$hostConfig.preparePortalMount; - $$$hostConfig.getInstanceFromScope; - var getCurrentEventPriority = $$$hostConfig.getCurrentEventPriority; - var detachDeletedInstance = $$$hostConfig.detachDeletedInstance; // ------------------- - // Microtasks - // (optional) - // ------------------- - - var supportsMicrotasks = $$$hostConfig.supportsMicrotasks; - var scheduleMicrotask = $$$hostConfig.scheduleMicrotask; // ------------------- - // Test selectors - // (optional) - // ------------------- - - var supportsTestSelectors = $$$hostConfig.supportsTestSelectors; - var findFiberRoot = $$$hostConfig.findFiberRoot; - var getBoundingRect = $$$hostConfig.getBoundingRect; - var getTextContent = $$$hostConfig.getTextContent; - var isHiddenSubtree = $$$hostConfig.isHiddenSubtree; - var matchAccessibilityRole = $$$hostConfig.matchAccessibilityRole; - var setFocusIfFocusable = $$$hostConfig.setFocusIfFocusable; - var setupIntersectionObserver = $$$hostConfig.setupIntersectionObserver; // ------------------- - // Mutation - // (optional) - // ------------------- - - var appendChild = $$$hostConfig.appendChild; - var appendChildToContainer = $$$hostConfig.appendChildToContainer; - var commitTextUpdate = $$$hostConfig.commitTextUpdate; - var commitMount = $$$hostConfig.commitMount; - var commitUpdate = $$$hostConfig.commitUpdate; - var insertBefore = $$$hostConfig.insertBefore; - var insertInContainerBefore = $$$hostConfig.insertInContainerBefore; - var removeChild = $$$hostConfig.removeChild; - var removeChildFromContainer = $$$hostConfig.removeChildFromContainer; - var resetTextContent = $$$hostConfig.resetTextContent; - var hideInstance = $$$hostConfig.hideInstance; - var hideTextInstance = $$$hostConfig.hideTextInstance; - var unhideInstance = $$$hostConfig.unhideInstance; - var unhideTextInstance = $$$hostConfig.unhideTextInstance; - var clearContainer = $$$hostConfig.clearContainer; // ------------------- - // Persistence - // (optional) - // ------------------- - - var cloneInstance = $$$hostConfig.cloneInstance; - var createContainerChildSet = $$$hostConfig.createContainerChildSet; - var appendChildToContainerChildSet = $$$hostConfig.appendChildToContainerChildSet; - var finalizeContainerChildren = $$$hostConfig.finalizeContainerChildren; - var replaceContainerChildren = $$$hostConfig.replaceContainerChildren; - $$$hostConfig.getOffscreenContainerType; - var getOffscreenContainerProps = $$$hostConfig.getOffscreenContainerProps; - var cloneHiddenInstance = $$$hostConfig.cloneHiddenInstance; - var cloneHiddenTextInstance = $$$hostConfig.cloneHiddenTextInstance; // ------------------- - // Hydration - // (optional) - // ------------------- - - var canHydrateInstance = $$$hostConfig.canHydrateInstance; - var canHydrateTextInstance = $$$hostConfig.canHydrateTextInstance; - var canHydrateSuspenseInstance = $$$hostConfig.canHydrateSuspenseInstance; - var isSuspenseInstancePending = $$$hostConfig.isSuspenseInstancePending; - var isSuspenseInstanceFallback = $$$hostConfig.isSuspenseInstanceFallback; - var registerSuspenseInstanceRetry = $$$hostConfig.registerSuspenseInstanceRetry; - var getNextHydratableSibling = $$$hostConfig.getNextHydratableSibling; - var getFirstHydratableChild = $$$hostConfig.getFirstHydratableChild; - var getFirstHydratableChildWithinContainer = $$$hostConfig.getFirstHydratableChildWithinContainer; - var getFirstHydratableChildWithinSuspenseInstance = $$$hostConfig.getFirstHydratableChildWithinSuspenseInstance; - var hydrateInstance = $$$hostConfig.hydrateInstance; - var hydrateTextInstance = $$$hostConfig.hydrateTextInstance; - var hydrateSuspenseInstance = $$$hostConfig.hydrateSuspenseInstance; - var getNextHydratableInstanceAfterSuspenseInstance = $$$hostConfig.getNextHydratableInstanceAfterSuspenseInstance; - var commitHydratedContainer = $$$hostConfig.commitHydratedContainer; - var commitHydratedSuspenseInstance = $$$hostConfig.commitHydratedSuspenseInstance; - var clearSuspenseBoundary = $$$hostConfig.clearSuspenseBoundary; - var clearSuspenseBoundaryFromContainer = $$$hostConfig.clearSuspenseBoundaryFromContainer; - var shouldDeleteUnhydratedTailInstances = $$$hostConfig.shouldDeleteUnhydratedTailInstances; - var didNotMatchHydratedContainerTextInstance = $$$hostConfig.didNotMatchHydratedContainerTextInstance; - var didNotMatchHydratedTextInstance = $$$hostConfig.didNotMatchHydratedTextInstance; - var didNotHydrateInstanceWithinContainer = $$$hostConfig.didNotHydrateInstanceWithinContainer; - var didNotHydrateInstanceWithinSuspenseInstance = $$$hostConfig.didNotHydrateInstanceWithinSuspenseInstance; - var didNotHydrateInstance = $$$hostConfig.didNotHydrateInstance; - var didNotFindHydratableInstanceWithinContainer = $$$hostConfig.didNotFindHydratableInstanceWithinContainer; - var didNotFindHydratableTextInstanceWithinContainer = $$$hostConfig.didNotFindHydratableTextInstanceWithinContainer; - var didNotFindHydratableSuspenseInstanceWithinContainer = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinContainer; - var didNotFindHydratableInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableInstanceWithinSuspenseInstance; - var didNotFindHydratableTextInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableTextInstanceWithinSuspenseInstance; - var didNotFindHydratableSuspenseInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinSuspenseInstance; - var didNotFindHydratableInstance = $$$hostConfig.didNotFindHydratableInstance; - var didNotFindHydratableTextInstance = $$$hostConfig.didNotFindHydratableTextInstance; - var didNotFindHydratableSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstance; - var errorHydratingContainer = $$$hostConfig.errorHydratingContainer; - - // Helpers to patch console.logs to avoid logging during side-effect free - // replaying on render function. This currently only patches the object - // lazily which won't cover if the log function was extracted eagerly. - // We could also eagerly patch the method. - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - - function disabledLog() {} - - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 - - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - /* eslint-enable react-internal/no-production-logging */ - } - - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - /* eslint-enable react-internal/no-production-logging */ - } - - if (disabledDepth < 0) { - error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); - } - } - } - - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ''; - } - } // We use the prefix to ensure our stacks line up with native stack frames. - - - return '\n' + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - - { - var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - - function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if ( !fn || reentry) { - return ''; - } - - { - var frame = componentFrameCache.get(fn); - - if (frame !== undefined) { - return frame; - } - } - - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. - - Error.prepareStackTrace = undefined; - var previousDispatcher; - - { - previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function - // for warnings. - - ReactCurrentDispatcher.current = null; - disableLogs(); - } - - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error(); - }; // $FlowFixMe - - - Object.defineProperty(Fake.prototype, 'props', { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error(); - } - }); - - if (typeof Reflect === 'object' && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - - fn(); - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === 'string') { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sample.stack.split('\n'); - var controlLines = control.stack.split('\n'); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c--; - } - - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s--; - c--; // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. - - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" - // but we have a user-provided "displayName" - // splice it in to make the stack more readable. - - - if (fn.displayName && _frame.includes('')) { - _frame = _frame.replace('', fn.displayName); - } - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, _frame); - } - } // Return the line we found. - - - return _frame; - } - } while (s >= 1 && c >= 0); - } - - break; - } - } - } - } finally { - reentry = false; - - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - - Error.prepareStackTrace = previousPrepareStackTrace; - } // Fallback to just using the name if we couldn't make it throw. - - - var name = fn ? fn.displayName || fn.name : ''; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, syntheticFrame); - } - } - - return syntheticFrame; - } - - function describeClassComponentFrame(ctor, source, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - - function shouldConstruct(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - - if (type == null) { - return ''; - } - - if (typeof type === 'function') { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - - if (typeof type === 'string') { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame('Suspense'); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame('SuspenseList'); - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) {} - } - } - } - - return ''; - } - - var hasOwnProperty = Object.prototype.hasOwnProperty; - - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } - } - - function checkPropTypes(typeSpecs, values, location, componentName, element) { - { - // $FlowFixMe This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== 'function') { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); - err.name = 'Invariant Violation'; - throw err; - } - - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); - - setCurrentlyValidatingElement(null); - } - - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error('Failed %s type: %s', location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } - } - - var valueStack = []; - var fiberStack; - - { - fiberStack = []; - } - - var index = -1; - - function createCursor(defaultValue) { - return { - current: defaultValue - }; - } - - function pop(cursor, fiber) { - if (index < 0) { - { - error('Unexpected pop.'); - } - - return; - } - - { - if (fiber !== fiberStack[index]) { - error('Unexpected Fiber popped.'); - } - } - - cursor.current = valueStack[index]; - valueStack[index] = null; - - { - fiberStack[index] = null; - } - - index--; - } - - function push(cursor, value, fiber) { - index++; - valueStack[index] = cursor.current; - - { - fiberStack[index] = fiber; - } - - cursor.current = value; - } - - var warnedAboutMissingGetChildContext; - - { - warnedAboutMissingGetChildContext = {}; - } - - var emptyContextObject = {}; - - { - Object.freeze(emptyContextObject); - } // A cursor to the current merged context object on the stack. - - - var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. - - var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. - // We use this to get access to the parent context after we have already - // pushed the next context provider, and now need to merge their contexts. - - var previousContext = emptyContextObject; - - function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) { - { - if (didPushOwnContextIfProvider && isContextProvider(Component)) { - // If the fiber is a context provider itself, when we read its context - // we may have already pushed its own child context on the stack. A context - // provider should not "see" its own child context. Therefore we read the - // previous (parent) context instead for a context provider. - return previousContext; - } - - return contextStackCursor.current; - } - } - - function cacheContext(workInProgress, unmaskedContext, maskedContext) { - { - var instance = workInProgress.stateNode; - instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; - instance.__reactInternalMemoizedMaskedChildContext = maskedContext; - } - } - - function getMaskedContext(workInProgress, unmaskedContext) { - { - var type = workInProgress.type; - var contextTypes = type.contextTypes; - - if (!contextTypes) { - return emptyContextObject; - } // Avoid recreating masked context unless unmasked context has changed. - // Failing to do this will result in unnecessary calls to componentWillReceiveProps. - // This may trigger infinite loops if componentWillReceiveProps calls setState. - - - var instance = workInProgress.stateNode; - - if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { - return instance.__reactInternalMemoizedMaskedChildContext; - } - - var context = {}; - - for (var key in contextTypes) { - context[key] = unmaskedContext[key]; - } - - { - var name = getComponentNameFromFiber(workInProgress) || 'Unknown'; - checkPropTypes(contextTypes, context, 'context', name); - } // Cache unmasked context so we can avoid recreating masked context unless necessary. - // Context is created before the class component is instantiated so check for instance. - - - if (instance) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return context; - } - } - - function hasContextChanged() { - { - return didPerformWorkStackCursor.current; - } - } - - function isContextProvider(type) { - { - var childContextTypes = type.childContextTypes; - return childContextTypes !== null && childContextTypes !== undefined; - } - } - - function popContext(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } - } - - function popTopLevelContextObject(fiber) { - { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } - } - - function pushTopLevelContextObject(fiber, context, didChange) { - { - if (contextStackCursor.current !== emptyContextObject) { - throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - push(contextStackCursor, context, fiber); - push(didPerformWorkStackCursor, didChange, fiber); - } - } - - function processChildContext(fiber, type, parentContext) { - { - var instance = fiber.stateNode; - var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. - // It has only been added in Fiber to match the (unintentional) behavior in Stack. - - if (typeof instance.getChildContext !== 'function') { - { - var componentName = getComponentNameFromFiber(fiber) || 'Unknown'; - - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; - - error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); - } - } - - return parentContext; - } - - var childContext = instance.getChildContext(); - - for (var contextKey in childContext) { - if (!(contextKey in childContextTypes)) { - throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); - } - } - - { - var name = getComponentNameFromFiber(fiber) || 'Unknown'; - checkPropTypes(childContextTypes, childContext, 'child context', name); - } - - return assign({}, parentContext, childContext); - } - } - - function pushContextProvider(workInProgress) { - { - var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. - // If the instance does not exist yet, we will push null at first, - // and replace it on the stack later when invalidating the context. - - var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later. - // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. - - previousContext = contextStackCursor.current; - push(contextStackCursor, memoizedMergedChildContext, workInProgress); - push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress); - return true; - } - } - - function invalidateContextProvider(workInProgress, type, didChange) { - { - var instance = workInProgress.stateNode; - - if (!instance) { - throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - if (didChange) { - // Merge parent and own context. - // Skip this if we're not updating due to sCU. - // This avoids unnecessarily recomputing memoized values. - var mergedContext = processChildContext(workInProgress, type, previousContext); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. - // It is important to unwind the context in the reverse order. - - pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. - - push(contextStackCursor, mergedContext, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } else { - pop(didPerformWorkStackCursor, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } - } - } - - function findCurrentUnmaskedContext(fiber) { - { - // Currently this is only used with renderSubtreeIntoContainer; not sure if it - // makes sense elsewhere - if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { - throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var node = fiber; - - do { - switch (node.tag) { - case HostRoot: - return node.stateNode.context; - - case ClassComponent: - { - var Component = node.type; - - if (isContextProvider(Component)) { - return node.stateNode.__reactInternalMemoizedMergedChildContext; - } - - break; - } - } - - node = node.return; - } while (node !== null); - - throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - } - - var LegacyRoot = 0; - var ConcurrentRoot = 1; - - var NoMode = - /* */ - 0; // TODO: Remove ConcurrentMode by reading from the root tag instead - - var ConcurrentMode = - /* */ - 1; - var ProfileMode = - /* */ - 2; - var StrictLegacyMode = - /* */ - 8; - var StrictEffectsMode = - /* */ - 16; - - // TODO: This is pretty well supported by browsers. Maybe we can drop it. - var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. - // Based on: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 - - var log = Math.log; - var LN2 = Math.LN2; - - function clz32Fallback(x) { - var asUint = x >>> 0; - - if (asUint === 0) { - return 32; - } - - return 31 - (log(asUint) / LN2 | 0) | 0; - } - - // If those values are changed that package should be rebuilt and redeployed. - - var TotalLanes = 31; - var NoLanes = - /* */ - 0; - var NoLane = - /* */ - 0; - var SyncLane = - /* */ - 1; - var InputContinuousHydrationLane = - /* */ - 2; - var InputContinuousLane = - /* */ - 4; - var DefaultHydrationLane = - /* */ - 8; - var DefaultLane = - /* */ - 16; - var TransitionHydrationLane = - /* */ - 32; - var TransitionLanes = - /* */ - 4194240; - var TransitionLane1 = - /* */ - 64; - var TransitionLane2 = - /* */ - 128; - var TransitionLane3 = - /* */ - 256; - var TransitionLane4 = - /* */ - 512; - var TransitionLane5 = - /* */ - 1024; - var TransitionLane6 = - /* */ - 2048; - var TransitionLane7 = - /* */ - 4096; - var TransitionLane8 = - /* */ - 8192; - var TransitionLane9 = - /* */ - 16384; - var TransitionLane10 = - /* */ - 32768; - var TransitionLane11 = - /* */ - 65536; - var TransitionLane12 = - /* */ - 131072; - var TransitionLane13 = - /* */ - 262144; - var TransitionLane14 = - /* */ - 524288; - var TransitionLane15 = - /* */ - 1048576; - var TransitionLane16 = - /* */ - 2097152; - var RetryLanes = - /* */ - 130023424; - var RetryLane1 = - /* */ - 4194304; - var RetryLane2 = - /* */ - 8388608; - var RetryLane3 = - /* */ - 16777216; - var RetryLane4 = - /* */ - 33554432; - var RetryLane5 = - /* */ - 67108864; - var SomeRetryLane = RetryLane1; - var SelectiveHydrationLane = - /* */ - 134217728; - var NonIdleLanes = - /* */ - 268435455; - var IdleHydrationLane = - /* */ - 268435456; - var IdleLane = - /* */ - 536870912; - var OffscreenLane = - /* */ - 1073741824; // This function is used for the experimental timeline (react-devtools-timeline) - // It should be kept in sync with the Lanes values above. - - function getLabelForLane(lane) { - { - if (lane & SyncLane) { - return 'Sync'; - } - - if (lane & InputContinuousHydrationLane) { - return 'InputContinuousHydration'; - } - - if (lane & InputContinuousLane) { - return 'InputContinuous'; - } - - if (lane & DefaultHydrationLane) { - return 'DefaultHydration'; - } - - if (lane & DefaultLane) { - return 'Default'; - } - - if (lane & TransitionHydrationLane) { - return 'TransitionHydration'; - } - - if (lane & TransitionLanes) { - return 'Transition'; - } - - if (lane & RetryLanes) { - return 'Retry'; - } - - if (lane & SelectiveHydrationLane) { - return 'SelectiveHydration'; - } - - if (lane & IdleHydrationLane) { - return 'IdleHydration'; - } - - if (lane & IdleLane) { - return 'Idle'; - } - - if (lane & OffscreenLane) { - return 'Offscreen'; - } - } - } - var NoTimestamp = -1; - var nextTransitionLane = TransitionLane1; - var nextRetryLane = RetryLane1; - - function getHighestPriorityLanes(lanes) { - switch (getHighestPriorityLane(lanes)) { - case SyncLane: - return SyncLane; - - case InputContinuousHydrationLane: - return InputContinuousHydrationLane; - - case InputContinuousLane: - return InputContinuousLane; - - case DefaultHydrationLane: - return DefaultHydrationLane; - - case DefaultLane: - return DefaultLane; - - case TransitionHydrationLane: - return TransitionHydrationLane; - - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - return lanes & TransitionLanes; - - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - case RetryLane5: - return lanes & RetryLanes; - - case SelectiveHydrationLane: - return SelectiveHydrationLane; - - case IdleHydrationLane: - return IdleHydrationLane; - - case IdleLane: - return IdleLane; - - case OffscreenLane: - return OffscreenLane; - - default: - { - error('Should have found matching lanes. This is a bug in React.'); - } // This shouldn't be reachable, but as a fallback, return the entire bitmask. - - - return lanes; - } - } - - function getNextLanes(root, wipLanes) { - // Early bailout if there's no pending work left. - var pendingLanes = root.pendingLanes; - - if (pendingLanes === NoLanes) { - return NoLanes; - } - - var nextLanes = NoLanes; - var suspendedLanes = root.suspendedLanes; - var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished, - // even if the work is suspended. - - var nonIdlePendingLanes = pendingLanes & NonIdleLanes; - - if (nonIdlePendingLanes !== NoLanes) { - var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; - - if (nonIdleUnblockedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); - } else { - var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; - - if (nonIdlePingedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); - } - } - } else { - // The only remaining work is Idle. - var unblockedLanes = pendingLanes & ~suspendedLanes; - - if (unblockedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(unblockedLanes); - } else { - if (pingedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(pingedLanes); - } - } - } - - if (nextLanes === NoLanes) { - // This should only be reachable if we're suspended - // TODO: Consider warning in this path if a fallback timer is not scheduled. - return NoLanes; - } // If we're already in the middle of a render, switching lanes will interrupt - // it and we'll lose our progress. We should only do this if the new lanes are - // higher priority. - - - if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't - // bother waiting until the root is complete. - (wipLanes & suspendedLanes) === NoLanes) { - var nextLane = getHighestPriorityLane(nextLanes); - var wipLane = getHighestPriorityLane(wipLanes); - - if ( // Tests whether the next lane is equal or lower priority than the wip - // one. This works because the bits decrease in priority as you go left. - nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The - // only difference between default updates and transition updates is that - // default updates do not support refresh transitions. - nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) { - // Keep working on the existing in-progress tree. Do not interrupt. - return wipLanes; - } - } - - if ((nextLanes & InputContinuousLane) !== NoLanes) { - // When updates are sync by default, we entangle continuous priority updates - // and default updates, so they render in the same batch. The only reason - // they use separate lanes is because continuous updates should interrupt - // transitions, but default updates should not. - nextLanes |= pendingLanes & DefaultLane; - } // Check for entangled lanes and add them to the batch. - // - // A lane is said to be entangled with another when it's not allowed to render - // in a batch that does not also include the other lane. Typically we do this - // when multiple updates have the same source, and we only want to respond to - // the most recent event from that source. - // - // Note that we apply entanglements *after* checking for partial work above. - // This means that if a lane is entangled during an interleaved event while - // it's already rendering, we won't interrupt it. This is intentional, since - // entanglement is usually "best effort": we'll try our best to render the - // lanes in the same batch, but it's not worth throwing out partially - // completed work in order to do it. - // TODO: Reconsider this. The counter-argument is that the partial work - // represents an intermediate state, which we don't want to show to the user. - // And by spending extra time finishing it, we're increasing the amount of - // time it takes to show the final state, which is what they are actually - // waiting for. - // - // For those exceptions where entanglement is semantically important, like - // useMutableSource, we should ensure that there is no partial work at the - // time we apply the entanglement. - - - var entangledLanes = root.entangledLanes; - - if (entangledLanes !== NoLanes) { - var entanglements = root.entanglements; - var lanes = nextLanes & entangledLanes; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - nextLanes |= entanglements[index]; - lanes &= ~lane; - } - } - - return nextLanes; - } - function getMostRecentEventTime(root, lanes) { - var eventTimes = root.eventTimes; - var mostRecentEventTime = NoTimestamp; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - var eventTime = eventTimes[index]; - - if (eventTime > mostRecentEventTime) { - mostRecentEventTime = eventTime; - } - - lanes &= ~lane; - } - - return mostRecentEventTime; - } - - function computeExpirationTime(lane, currentTime) { - switch (lane) { - case SyncLane: - case InputContinuousHydrationLane: - case InputContinuousLane: - // User interactions should expire slightly more quickly. - // - // NOTE: This is set to the corresponding constant as in Scheduler.js. - // When we made it larger, a product metric in www regressed, suggesting - // there's a user interaction that's being starved by a series of - // synchronous updates. If that theory is correct, the proper solution is - // to fix the starvation. However, this scenario supports the idea that - // expiration times are an important safeguard when starvation - // does happen. - return currentTime + 250; - - case DefaultHydrationLane: - case DefaultLane: - case TransitionHydrationLane: - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - return currentTime + 5000; - - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - case RetryLane5: - // TODO: Retries should be allowed to expire if they are CPU bound for - // too long, but when I made this change it caused a spike in browser - // crashes. There must be some other underlying bug; not super urgent but - // ideally should figure out why and fix it. Unfortunately we don't have - // a repro for the crashes, only detected via production metrics. - return NoTimestamp; - - case SelectiveHydrationLane: - case IdleHydrationLane: - case IdleLane: - case OffscreenLane: - // Anything idle priority or lower should never expire. - return NoTimestamp; - - default: - { - error('Should have found matching lanes. This is a bug in React.'); - } - - return NoTimestamp; - } - } - - function markStarvedLanesAsExpired(root, currentTime) { - // TODO: This gets called every time we yield. We can optimize by storing - // the earliest expiration time on the root. Then use that to quickly bail out - // of this function. - var pendingLanes = root.pendingLanes; - var suspendedLanes = root.suspendedLanes; - var pingedLanes = root.pingedLanes; - var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their - // expiration time. If so, we'll assume the update is being starved and mark - // it as expired to force it to finish. - - var lanes = pendingLanes; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - var expirationTime = expirationTimes[index]; - - if (expirationTime === NoTimestamp) { - // Found a pending lane with no expiration time. If it's not suspended, or - // if it's pinged, assume it's CPU-bound. Compute a new expiration time - // using the current time. - if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) { - // Assumes timestamps are monotonically increasing. - expirationTimes[index] = computeExpirationTime(lane, currentTime); - } - } else if (expirationTime <= currentTime) { - // This lane expired - root.expiredLanes |= lane; - } - - lanes &= ~lane; - } - } // This returns the highest priority pending lanes regardless of whether they - // are suspended. - - function getHighestPriorityPendingLanes(root) { - return getHighestPriorityLanes(root.pendingLanes); - } - function getLanesToRetrySynchronouslyOnError(root) { - var everythingButOffscreen = root.pendingLanes & ~OffscreenLane; - - if (everythingButOffscreen !== NoLanes) { - return everythingButOffscreen; - } - - if (everythingButOffscreen & OffscreenLane) { - return OffscreenLane; - } - - return NoLanes; - } - function includesSyncLane(lanes) { - return (lanes & SyncLane) !== NoLanes; - } - function includesNonIdleWork(lanes) { - return (lanes & NonIdleLanes) !== NoLanes; - } - function includesOnlyRetries(lanes) { - return (lanes & RetryLanes) === lanes; - } - function includesOnlyTransitions(lanes) { - return (lanes & TransitionLanes) === lanes; - } - function includesBlockingLane(root, lanes) { - - var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane; - return (lanes & SyncDefaultLanes) !== NoLanes; - } - function includesExpiredLane(root, lanes) { - // This is a separate check from includesBlockingLane because a lane can - // expire after a render has already started. - return (lanes & root.expiredLanes) !== NoLanes; - } - function isTransitionLane(lane) { - return (lane & TransitionLanes) !== 0; - } - function claimNextTransitionLane() { - // Cycle through the lanes, assigning each new transition to the next lane. - // In most cases, this means every transition gets its own lane, until we - // run out of lanes and cycle back to the beginning. - var lane = nextTransitionLane; - nextTransitionLane <<= 1; - - if ((nextTransitionLane & TransitionLanes) === 0) { - nextTransitionLane = TransitionLane1; - } - - return lane; - } - function claimNextRetryLane() { - var lane = nextRetryLane; - nextRetryLane <<= 1; - - if ((nextRetryLane & RetryLanes) === 0) { - nextRetryLane = RetryLane1; - } - - return lane; - } - function getHighestPriorityLane(lanes) { - return lanes & -lanes; - } - function pickArbitraryLane(lanes) { - // This wrapper function gets inlined. Only exists so to communicate that it - // doesn't matter which bit is selected; you can pick any bit without - // affecting the algorithms where its used. Here I'm using - // getHighestPriorityLane because it requires the fewest operations. - return getHighestPriorityLane(lanes); - } - - function pickArbitraryLaneIndex(lanes) { - return 31 - clz32(lanes); - } - - function laneToIndex(lane) { - return pickArbitraryLaneIndex(lane); - } - - function includesSomeLane(a, b) { - return (a & b) !== NoLanes; - } - function isSubsetOfLanes(set, subset) { - return (set & subset) === subset; - } - function mergeLanes(a, b) { - return a | b; - } - function removeLanes(set, subset) { - return set & ~subset; - } - function intersectLanes(a, b) { - return a & b; - } // Seems redundant, but it changes the type from a single lane (used for - // updates) to a group of lanes (used for flushing work). - - function laneToLanes(lane) { - return lane; - } - function higherPriorityLane(a, b) { - // This works because the bit ranges decrease in priority as you go left. - return a !== NoLane && a < b ? a : b; - } - function createLaneMap(initial) { - // Intentionally pushing one by one. - // https://v8.dev/blog/elements-kinds#avoid-creating-holes - var laneMap = []; - - for (var i = 0; i < TotalLanes; i++) { - laneMap.push(initial); - } - - return laneMap; - } - function markRootUpdated(root, updateLane, eventTime) { - root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update - // could unblock them. Clear the suspended lanes so that we can try rendering - // them again. - // - // TODO: We really only need to unsuspend only lanes that are in the - // `subtreeLanes` of the updated fiber, or the update lanes of the return - // path. This would exclude suspended updates in an unrelated sibling tree, - // since there's no way for this update to unblock it. - // - // We don't do this if the incoming update is idle, because we never process - // idle updates until after all the regular updates have finished; there's no - // way it could unblock a transition. - - if (updateLane !== IdleLane) { - root.suspendedLanes = NoLanes; - root.pingedLanes = NoLanes; - } - - var eventTimes = root.eventTimes; - var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most - // recent event, and we assume time is monotonically increasing. - - eventTimes[index] = eventTime; - } - function markRootSuspended(root, suspendedLanes) { - root.suspendedLanes |= suspendedLanes; - root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times. - - var expirationTimes = root.expirationTimes; - var lanes = suspendedLanes; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - expirationTimes[index] = NoTimestamp; - lanes &= ~lane; - } - } - function markRootPinged(root, pingedLanes, eventTime) { - root.pingedLanes |= root.suspendedLanes & pingedLanes; - } - function markRootFinished(root, remainingLanes) { - var noLongerPendingLanes = root.pendingLanes & ~remainingLanes; - root.pendingLanes = remainingLanes; // Let's try everything again - - root.suspendedLanes = 0; - root.pingedLanes = 0; - root.expiredLanes &= remainingLanes; - root.mutableReadLanes &= remainingLanes; - root.entangledLanes &= remainingLanes; - var entanglements = root.entanglements; - var eventTimes = root.eventTimes; - var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work - - var lanes = noLongerPendingLanes; - - while (lanes > 0) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - entanglements[index] = NoLanes; - eventTimes[index] = NoTimestamp; - expirationTimes[index] = NoTimestamp; - lanes &= ~lane; - } - } - function markRootEntangled(root, entangledLanes) { - // In addition to entangling each of the given lanes with each other, we also - // have to consider _transitive_ entanglements. For each lane that is already - // entangled with *any* of the given lanes, that lane is now transitively - // entangled with *all* the given lanes. - // - // Translated: If C is entangled with A, then entangling A with B also - // entangles C with B. - // - // If this is hard to grasp, it might help to intentionally break this - // function and look at the tests that fail in ReactTransition-test.js. Try - // commenting out one of the conditions below. - var rootEntangledLanes = root.entangledLanes |= entangledLanes; - var entanglements = root.entanglements; - var lanes = rootEntangledLanes; - - while (lanes) { - var index = pickArbitraryLaneIndex(lanes); - var lane = 1 << index; - - if ( // Is this one of the newly entangled lanes? - lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes? - entanglements[index] & entangledLanes) { - entanglements[index] |= entangledLanes; - } - - lanes &= ~lane; - } - } - function getBumpedLaneForHydration(root, renderLanes) { - var renderLane = getHighestPriorityLane(renderLanes); - var lane; - - switch (renderLane) { - case InputContinuousLane: - lane = InputContinuousHydrationLane; - break; - - case DefaultLane: - lane = DefaultHydrationLane; - break; - - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - case RetryLane5: - lane = TransitionHydrationLane; - break; - - case IdleLane: - lane = IdleHydrationLane; - break; - - default: - // Everything else is already either a hydration lane, or shouldn't - // be retried at a hydration lane. - lane = NoLane; - break; - } // Check if the lane we chose is suspended. If so, that indicates that we - // already attempted and failed to hydrate at that level. Also check if we're - // already rendering that lane, which is rare but could happen. - - - if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) { - // Give up trying to hydrate and fall back to client render. - return NoLane; - } - - return lane; - } - function addFiberToLanesMap(root, fiber, lanes) { - - if (!isDevToolsPresent) { - return; - } - - var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - - while (lanes > 0) { - var index = laneToIndex(lanes); - var lane = 1 << index; - var updaters = pendingUpdatersLaneMap[index]; - updaters.add(fiber); - lanes &= ~lane; - } - } - function movePendingFibersToMemoized(root, lanes) { - - if (!isDevToolsPresent) { - return; - } - - var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - var memoizedUpdaters = root.memoizedUpdaters; - - while (lanes > 0) { - var index = laneToIndex(lanes); - var lane = 1 << index; - var updaters = pendingUpdatersLaneMap[index]; - - if (updaters.size > 0) { - updaters.forEach(function (fiber) { - var alternate = fiber.alternate; - - if (alternate === null || !memoizedUpdaters.has(alternate)) { - memoizedUpdaters.add(fiber); - } - }); - updaters.clear(); - } - - lanes &= ~lane; - } - } - - var DiscreteEventPriority = SyncLane; - var ContinuousEventPriority = InputContinuousLane; - var DefaultEventPriority = DefaultLane; - var IdleEventPriority = IdleLane; - var currentUpdatePriority = NoLane; - function getCurrentUpdatePriority() { - return currentUpdatePriority; - } - function setCurrentUpdatePriority(newPriority) { - currentUpdatePriority = newPriority; - } - function runWithPriority(priority, fn) { - var previousPriority = currentUpdatePriority; - - try { - currentUpdatePriority = priority; - return fn(); - } finally { - currentUpdatePriority = previousPriority; - } - } - function higherEventPriority(a, b) { - return a !== 0 && a < b ? a : b; - } - function lowerEventPriority(a, b) { - return a === 0 || a > b ? a : b; - } - function isHigherEventPriority(a, b) { - return a !== 0 && a < b; - } - function lanesToEventPriority(lanes) { - var lane = getHighestPriorityLane(lanes); - - if (!isHigherEventPriority(DiscreteEventPriority, lane)) { - return DiscreteEventPriority; - } - - if (!isHigherEventPriority(ContinuousEventPriority, lane)) { - return ContinuousEventPriority; - } - - if (includesNonIdleWork(lane)) { - return DefaultEventPriority; - } - - return IdleEventPriority; - } - - // This module only exists as an ESM wrapper around the external CommonJS - var scheduleCallback = Scheduler.unstable_scheduleCallback; - var cancelCallback = Scheduler.unstable_cancelCallback; - var shouldYield = Scheduler.unstable_shouldYield; - var requestPaint = Scheduler.unstable_requestPaint; - var now$1 = Scheduler.unstable_now; - var ImmediatePriority = Scheduler.unstable_ImmediatePriority; - var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; - var NormalPriority = Scheduler.unstable_NormalPriority; - var IdlePriority = Scheduler.unstable_IdlePriority; - // this doesn't actually exist on the scheduler, but it *does* - // on scheduler/unstable_mock, which we'll need for internal testing - var unstable_yieldValue = Scheduler.unstable_yieldValue; - var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue; - - var rendererID = null; - var injectedHook = null; - var injectedProfilingHooks = null; - var hasLoggedError = false; - var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined'; - function injectInternals(internals) { - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { - // No DevTools - return false; - } - - var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; - - if (hook.isDisabled) { - // This isn't a real property on the hook, but it can be set to opt out - // of DevTools integration and associated warnings and logs. - // https://github.com/facebook/react/issues/3877 - return true; - } - - if (!hook.supportsFiber) { - { - error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools'); - } // DevTools exists, even though it doesn't support Fiber. - - - return true; - } - - try { - if (enableSchedulingProfiler) { - // Conditionally inject these hooks only if Timeline profiler is supported by this build. - // This gives DevTools a way to feature detect that isn't tied to version number - // (since profiling and timeline are controlled by different feature flags). - internals = assign({}, internals, { - getLaneLabelMap: getLaneLabelMap, - injectProfilingHooks: injectProfilingHooks - }); - } - - rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. - - injectedHook = hook; - } catch (err) { - // Catch all errors because it is unsafe to throw during initialization. - { - error('React instrumentation encountered an error: %s.', err); - } - } - - if (hook.checkDCE) { - // This is the real DevTools. - return true; - } else { - // This is likely a hook installed by Fast Refresh runtime. - return false; - } - } - function onScheduleRoot(root, children) { - { - if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') { - try { - injectedHook.onScheduleFiberRoot(rendererID, root, children); - } catch (err) { - if ( !hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - function onCommitRoot(root, eventPriority) { - if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { - try { - var didError = (root.current.flags & DidCapture) === DidCapture; - - if (enableProfilerTimer) { - var schedulerPriority; - - switch (eventPriority) { - case DiscreteEventPriority: - schedulerPriority = ImmediatePriority; - break; - - case ContinuousEventPriority: - schedulerPriority = UserBlockingPriority; - break; - - case DefaultEventPriority: - schedulerPriority = NormalPriority; - break; - - case IdleEventPriority: - schedulerPriority = IdlePriority; - break; - - default: - schedulerPriority = NormalPriority; - break; - } - - injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError); - } - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - function onPostCommitRoot(root) { - if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') { - try { - injectedHook.onPostCommitFiberRoot(rendererID, root); - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - function onCommitUnmount(fiber) { - if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') { - try { - injectedHook.onCommitFiberUnmount(rendererID, fiber); - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - function setIsStrictModeForDevtools(newIsStrictMode) { - { - if (typeof unstable_yieldValue === 'function') { - // We're in a test because Scheduler.unstable_yieldValue only exists - // in SchedulerMock. To reduce the noise in strict mode tests, - // suppress warnings and disable scheduler yielding during the double render - unstable_setDisableYieldValue(newIsStrictMode); - setSuppressWarning(newIsStrictMode); - } - - if (injectedHook && typeof injectedHook.setStrictMode === 'function') { - try { - injectedHook.setStrictMode(rendererID, newIsStrictMode); - } catch (err) { - { - if (!hasLoggedError) { - hasLoggedError = true; - - error('React instrumentation encountered an error: %s', err); - } - } - } - } - } - } // Profiler API hooks - - function injectProfilingHooks(profilingHooks) { - injectedProfilingHooks = profilingHooks; - } - - function getLaneLabelMap() { - { - var map = new Map(); - var lane = 1; - - for (var index = 0; index < TotalLanes; index++) { - var label = getLabelForLane(lane); - map.set(lane, label); - lane *= 2; - } - - return map; - } - } - - function markCommitStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') { - injectedProfilingHooks.markCommitStarted(lanes); - } - } - } - function markCommitStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') { - injectedProfilingHooks.markCommitStopped(); - } - } - } - function markComponentRenderStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') { - injectedProfilingHooks.markComponentRenderStarted(fiber); - } - } - } - function markComponentRenderStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') { - injectedProfilingHooks.markComponentRenderStopped(); - } - } - } - function markComponentPassiveEffectMountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') { - injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); - } - } - } - function markComponentPassiveEffectMountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') { - injectedProfilingHooks.markComponentPassiveEffectMountStopped(); - } - } - } - function markComponentPassiveEffectUnmountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') { - injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); - } - } - } - function markComponentPassiveEffectUnmountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') { - injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); - } - } - } - function markComponentLayoutEffectMountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') { - injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); - } - } - } - function markComponentLayoutEffectMountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') { - injectedProfilingHooks.markComponentLayoutEffectMountStopped(); - } - } - } - function markComponentLayoutEffectUnmountStarted(fiber) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') { - injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); - } - } - } - function markComponentLayoutEffectUnmountStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') { - injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); - } - } - } - function markComponentErrored(fiber, thrownValue, lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') { - injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); - } - } - } - function markComponentSuspended(fiber, wakeable, lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') { - injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); - } - } - } - function markLayoutEffectsStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') { - injectedProfilingHooks.markLayoutEffectsStarted(lanes); - } - } - } - function markLayoutEffectsStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') { - injectedProfilingHooks.markLayoutEffectsStopped(); - } - } - } - function markPassiveEffectsStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') { - injectedProfilingHooks.markPassiveEffectsStarted(lanes); - } - } - } - function markPassiveEffectsStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') { - injectedProfilingHooks.markPassiveEffectsStopped(); - } - } - } - function markRenderStarted(lanes) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') { - injectedProfilingHooks.markRenderStarted(lanes); - } - } - } - function markRenderYielded() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') { - injectedProfilingHooks.markRenderYielded(); - } - } - } - function markRenderStopped() { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') { - injectedProfilingHooks.markRenderStopped(); - } - } - } - function markRenderScheduled(lane) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') { - injectedProfilingHooks.markRenderScheduled(lane); - } - } - } - function markForceUpdateScheduled(fiber, lane) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') { - injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); - } - } - } - function markStateUpdateScheduled(fiber, lane) { - { - if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') { - injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); - } - } - } - - /** - * inlined Object.is polyfill to avoid requiring consumers ship their own - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - */ - function is(x, y) { - return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare - ; - } - - var objectIs = typeof Object.is === 'function' ? Object.is : is; - - var syncQueue = null; - var includesLegacySyncCallbacks = false; - var isFlushingSyncQueue = false; - function scheduleSyncCallback(callback) { - // Push this callback into an internal queue. We'll flush these either in - // the next tick, or earlier if something calls `flushSyncCallbackQueue`. - if (syncQueue === null) { - syncQueue = [callback]; - } else { - // Push onto existing queue. Don't need to schedule a callback because - // we already scheduled one when we created the queue. - syncQueue.push(callback); - } - } - function scheduleLegacySyncCallback(callback) { - includesLegacySyncCallbacks = true; - scheduleSyncCallback(callback); - } - function flushSyncCallbacksOnlyInLegacyMode() { - // Only flushes the queue if there's a legacy sync callback scheduled. - // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So - // it might make more sense for the queue to be a list of roots instead of a - // list of generic callbacks. Then we can have two: one for legacy roots, one - // for concurrent roots. And this method would only flush the legacy ones. - if (includesLegacySyncCallbacks) { - flushSyncCallbacks(); - } - } - function flushSyncCallbacks() { - if (!isFlushingSyncQueue && syncQueue !== null) { - // Prevent re-entrance. - isFlushingSyncQueue = true; - var i = 0; - var previousUpdatePriority = getCurrentUpdatePriority(); - - try { - var isSync = true; - var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this - // queue is in the render or commit phases. - - setCurrentUpdatePriority(DiscreteEventPriority); - - for (; i < queue.length; i++) { - var callback = queue[i]; - - do { - callback = callback(isSync); - } while (callback !== null); - } - - syncQueue = null; - includesLegacySyncCallbacks = false; - } catch (error) { - // If something throws, leave the remaining callbacks on the queue. - if (syncQueue !== null) { - syncQueue = syncQueue.slice(i + 1); - } // Resume flushing in the next tick - - - scheduleCallback(ImmediatePriority, flushSyncCallbacks); - throw error; - } finally { - setCurrentUpdatePriority(previousUpdatePriority); - isFlushingSyncQueue = false; - } - } - - return null; - } - - // This is imported by the event replaying implementation in React DOM. It's - // in a separate file to break a circular dependency between the renderer and - // the reconciler. - function isRootDehydrated(root) { - var currentState = root.current.memoizedState; - return currentState.isDehydrated; - } - - var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; - var NoTransition = null; - function requestCurrentTransition() { - return ReactCurrentBatchConfig.transition; - } - - /** - * Performs equality by iterating through keys on an object and returning false - * when any key has values which are not strictly equal between the arguments. - * Returns true when the values of all keys are strictly equal. - */ - - function shallowEqual(objA, objB) { - if (objectIs(objA, objB)) { - return true; - } - - if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { - return false; - } - - var keysA = Object.keys(objA); - var keysB = Object.keys(objB); - - if (keysA.length !== keysB.length) { - return false; - } // Test for A's keys different from B. - - - for (var i = 0; i < keysA.length; i++) { - var currentKey = keysA[i]; - - if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) { - return false; - } - } - - return true; - } - - function describeFiber(fiber) { - fiber._debugOwner ? fiber._debugOwner.type : null ; - fiber._debugSource ; - - switch (fiber.tag) { - case HostComponent: - return describeBuiltInComponentFrame(fiber.type); - - case LazyComponent: - return describeBuiltInComponentFrame('Lazy'); - - case SuspenseComponent: - return describeBuiltInComponentFrame('Suspense'); - - case SuspenseListComponent: - return describeBuiltInComponentFrame('SuspenseList'); - - case FunctionComponent: - case IndeterminateComponent: - case SimpleMemoComponent: - return describeFunctionComponentFrame(fiber.type); - - case ForwardRef: - return describeFunctionComponentFrame(fiber.type.render); - - case ClassComponent: - return describeClassComponentFrame(fiber.type); - - default: - return ''; - } - } - - function getStackByFiberInDevAndProd(workInProgress) { - try { - var info = ''; - var node = workInProgress; - - do { - info += describeFiber(node); - node = node.return; - } while (node); - - return info; - } catch (x) { - return '\nError generating stack: ' + x.message + '\n' + x.stack; - } - } - - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - var current = null; - var isRendering = false; - function getCurrentFiberOwnerNameInDevOrNull() { - { - if (current === null) { - return null; - } - - var owner = current._debugOwner; - - if (owner !== null && typeof owner !== 'undefined') { - return getComponentNameFromFiber(owner); - } - } - - return null; - } - - function getCurrentFiberStackInDev() { - { - if (current === null) { - return ''; - } // Safe because if current fiber exists, we are reconciling, - // and it is guaranteed to be the work-in-progress version. - - - return getStackByFiberInDevAndProd(current); - } - } - - function resetCurrentFiber() { - { - ReactDebugCurrentFrame$1.getCurrentStack = null; - current = null; - isRendering = false; - } - } - function setCurrentFiber(fiber) { - { - ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev; - current = fiber; - isRendering = false; - } - } - function setIsRendering(rendering) { - { - isRendering = rendering; - } - } - - var ReactStrictModeWarnings = { - recordUnsafeLifecycleWarnings: function (fiber, instance) {}, - flushPendingUnsafeLifecycleWarnings: function () {}, - recordLegacyContextWarning: function (fiber, instance) {}, - flushLegacyContextWarning: function () {}, - discardPendingWarnings: function () {} - }; - - { - var findStrictRoot = function (fiber) { - var maybeStrictRoot = null; - var node = fiber; - - while (node !== null) { - if (node.mode & StrictLegacyMode) { - maybeStrictRoot = node; - } - - node = node.return; - } - - return maybeStrictRoot; - }; - - var setToSortedString = function (set) { - var array = []; - set.forEach(function (value) { - array.push(value); - }); - return array.sort().join(', '); - }; - - var pendingComponentWillMountWarnings = []; - var pendingUNSAFE_ComponentWillMountWarnings = []; - var pendingComponentWillReceivePropsWarnings = []; - var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - var pendingComponentWillUpdateWarnings = []; - var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. - - var didWarnAboutUnsafeLifecycles = new Set(); - - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) { - // Dedupe strategy: Warn once per component. - if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { - return; - } - - if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components. - instance.componentWillMount.__suppressDeprecationWarning !== true) { - pendingComponentWillMountWarnings.push(fiber); - } - - if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') { - pendingUNSAFE_ComponentWillMountWarnings.push(fiber); - } - - if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { - pendingComponentWillReceivePropsWarnings.push(fiber); - } - - if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); - } - - if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { - pendingComponentWillUpdateWarnings.push(fiber); - } - - if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') { - pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); - } - }; - - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () { - // We do an initial pass to gather component names - var componentWillMountUniqueNames = new Set(); - - if (pendingComponentWillMountWarnings.length > 0) { - pendingComponentWillMountWarnings.forEach(function (fiber) { - componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillMountWarnings = []; - } - - var UNSAFE_componentWillMountUniqueNames = new Set(); - - if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { - pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) { - UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillMountWarnings = []; - } - - var componentWillReceivePropsUniqueNames = new Set(); - - if (pendingComponentWillReceivePropsWarnings.length > 0) { - pendingComponentWillReceivePropsWarnings.forEach(function (fiber) { - componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillReceivePropsWarnings = []; - } - - var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); - - if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { - pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) { - UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - } - - var componentWillUpdateUniqueNames = new Set(); - - if (pendingComponentWillUpdateWarnings.length > 0) { - pendingComponentWillUpdateWarnings.forEach(function (fiber) { - componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillUpdateWarnings = []; - } - - var UNSAFE_componentWillUpdateUniqueNames = new Set(); - - if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { - pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) { - UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillUpdateWarnings = []; - } // Finally, we flush all the warnings - // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' - - - if (UNSAFE_componentWillMountUniqueNames.size > 0) { - var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); - - error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames); - } - - if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { - var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames); - - error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames); - } - - if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { - var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames); - - error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2); - } - - if (componentWillMountUniqueNames.size > 0) { - var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); - - warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3); - } - - if (componentWillReceivePropsUniqueNames.size > 0) { - var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames); - - warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4); - } - - if (componentWillUpdateUniqueNames.size > 0) { - var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); - - warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5); - } - }; - - var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. - - var didWarnAboutLegacyContext = new Set(); - - ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) { - var strictRoot = findStrictRoot(fiber); - - if (strictRoot === null) { - error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - - return; - } // Dedup strategy: Warn once per component. - - - if (didWarnAboutLegacyContext.has(fiber.type)) { - return; - } - - var warningsForRoot = pendingLegacyContextWarning.get(strictRoot); - - if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') { - if (warningsForRoot === undefined) { - warningsForRoot = []; - pendingLegacyContextWarning.set(strictRoot, warningsForRoot); - } - - warningsForRoot.push(fiber); - } - }; - - ReactStrictModeWarnings.flushLegacyContextWarning = function () { - pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) { - if (fiberArray.length === 0) { - return; - } - - var firstFiber = fiberArray[0]; - var uniqueNames = new Set(); - fiberArray.forEach(function (fiber) { - uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutLegacyContext.add(fiber.type); - }); - var sortedNames = setToSortedString(uniqueNames); - - try { - setCurrentFiber(firstFiber); - - error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames); - } finally { - resetCurrentFiber(); - } - }); - }; - - ReactStrictModeWarnings.discardPendingWarnings = function () { - pendingComponentWillMountWarnings = []; - pendingUNSAFE_ComponentWillMountWarnings = []; - pendingComponentWillReceivePropsWarnings = []; - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - pendingComponentWillUpdateWarnings = []; - pendingUNSAFE_ComponentWillUpdateWarnings = []; - pendingLegacyContextWarning = new Map(); - }; - } - - /* - * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol - * and Temporal.* types. See https://github.com/facebook/react/pull/22064. - * - * The functions in this module will throw an easier-to-understand, - * easier-to-debug exception with a clear errors message message explaining the - * problem. (Instead of a confusing exception thrown inside the implementation - * of the `value` object). - */ - // $FlowFixMe only called in DEV, so void return is not possible. - function typeName(value) { - { - // toStringTag is needed for namespaced types like Temporal.Instant - var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; - return type; - } - } // $FlowFixMe only called in DEV, so void return is not possible. - - - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e) { - return true; - } - } - } - - function testStringCoercion(value) { - // If you ended up here by following an exception call stack, here's what's - // happened: you supplied an object or symbol value to React (as a prop, key, - // DOM attribute, CSS property, string ref, etc.) and when React tried to - // coerce it to a string using `'' + value`, an exception was thrown. - // - // The most common types that will cause this exception are `Symbol` instances - // and Temporal objects like `Temporal.Instant`. But any object that has a - // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this - // exception. (Library authors do this to prevent users from using built-in - // numeric operators like `+` or comparison operators like `>=` because custom - // methods are needed to perform accurate arithmetic or comparison.) - // - // To fix the problem, coerce this object or symbol value to a string before - // passing it to React. The most reliable way is usually `String(value)`. - // - // To find which value is throwing, check the browser or debugger console. - // Before this exception was thrown, there should be `console.error` output - // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the - // problem and how that type was used: key, atrribute, input value prop, etc. - // In most cases, this console output also shows the component and its - // ancestor components where the exception happened. - // - // eslint-disable-next-line react-internal/safe-string-coercion - return '' + value; - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); - - return testStringCoercion(value); // throw (to help callers find troubleshooting comments) - } - } - } - function checkPropStringCoercion(value, propName) { - { - if (willCoercionThrow(value)) { - error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); - - return testStringCoercion(value); // throw (to help callers find troubleshooting comments) - } - } - } - - function resolveDefaultProps(Component, baseProps) { - if (Component && Component.defaultProps) { - // Resolve default props. Taken from ReactElement - var props = assign({}, baseProps); - var defaultProps = Component.defaultProps; - - for (var propName in defaultProps) { - if (props[propName] === undefined) { - props[propName] = defaultProps[propName]; - } - } - - return props; - } - - return baseProps; - } - - var valueCursor = createCursor(null); - var rendererSigil; - - { - // Use this to detect multiple renderers using the same context - rendererSigil = {}; - } - - var currentlyRenderingFiber = null; - var lastContextDependency = null; - var lastFullyObservedContext = null; - var isDisallowedContextReadInDEV = false; - function resetContextDependencies() { - // This is called right before React yields execution, to ensure `readContext` - // cannot be called outside the render phase. - currentlyRenderingFiber = null; - lastContextDependency = null; - lastFullyObservedContext = null; - - { - isDisallowedContextReadInDEV = false; - } - } - function enterDisallowedContextReadInDEV() { - { - isDisallowedContextReadInDEV = true; - } - } - function exitDisallowedContextReadInDEV() { - { - isDisallowedContextReadInDEV = false; - } - } - function pushProvider(providerFiber, context, nextValue) { - if (isPrimaryRenderer) { - push(valueCursor, context._currentValue, providerFiber); - context._currentValue = nextValue; - - { - if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { - error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); - } - - context._currentRenderer = rendererSigil; - } - } else { - push(valueCursor, context._currentValue2, providerFiber); - context._currentValue2 = nextValue; - - { - if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { - error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); - } - - context._currentRenderer2 = rendererSigil; - } - } - } - function popProvider(context, providerFiber) { - var currentValue = valueCursor.current; - pop(valueCursor, providerFiber); - - if (isPrimaryRenderer) { - { - context._currentValue = currentValue; - } - } else { - { - context._currentValue2 = currentValue; - } - } - } - function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { - // Update the child lanes of all the ancestors, including the alternates. - var node = parent; - - while (node !== null) { - var alternate = node.alternate; - - if (!isSubsetOfLanes(node.childLanes, renderLanes)) { - node.childLanes = mergeLanes(node.childLanes, renderLanes); - - if (alternate !== null) { - alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); - } - } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) { - alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); - } - - if (node === propagationRoot) { - break; - } - - node = node.return; - } - - { - if (node !== propagationRoot) { - error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - } - } - function propagateContextChange(workInProgress, context, renderLanes) { - { - propagateContextChange_eager(workInProgress, context, renderLanes); - } - } - - function propagateContextChange_eager(workInProgress, context, renderLanes) { - - var fiber = workInProgress.child; - - if (fiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - fiber.return = workInProgress; - } - - while (fiber !== null) { - var nextFiber = void 0; // Visit this fiber. - - var list = fiber.dependencies; - - if (list !== null) { - nextFiber = fiber.child; - var dependency = list.firstContext; - - while (dependency !== null) { - // Check if the context matches. - if (dependency.context === context) { - // Match! Schedule an update on this fiber. - if (fiber.tag === ClassComponent) { - // Schedule a force update on the work-in-progress. - var lane = pickArbitraryLane(renderLanes); - var update = createUpdate(NoTimestamp, lane); - update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the - // update to the current fiber, too, which means it will persist even if - // this render is thrown away. Since it's a race condition, not sure it's - // worth fixing. - // Inlined `enqueueUpdate` to remove interleaved update check - - var updateQueue = fiber.updateQueue; - - if (updateQueue === null) ; else { - var sharedQueue = updateQueue.shared; - var pending = sharedQueue.pending; - - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - - sharedQueue.pending = update; - } - } - - fiber.lanes = mergeLanes(fiber.lanes, renderLanes); - var alternate = fiber.alternate; - - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes); - } - - scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too. - - list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the - // dependency list. - - break; - } - - dependency = dependency.next; - } - } else if (fiber.tag === ContextProvider) { - // Don't scan deeper if this is a matching provider - nextFiber = fiber.type === workInProgress.type ? null : fiber.child; - } else if ( fiber.tag === DehydratedFragment) { - // If a dehydrated suspense boundary is in this subtree, we don't know - // if it will have any context consumers in it. The best we can do is - // mark it as having updates. - var parentSuspense = fiber.return; - - if (parentSuspense === null) { - throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.'); - } - - parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); - var _alternate = parentSuspense.alternate; - - if (_alternate !== null) { - _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes); - } // This is intentionally passing this fiber as the parent - // because we want to schedule this fiber as having work - // on its children. We'll use the childLanes on - // this fiber to indicate that a context has changed. - - - scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress); - nextFiber = fiber.sibling; - } else { - // Traverse down. - nextFiber = fiber.child; - } - - if (nextFiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - nextFiber.return = fiber; - } else { - // No child. Traverse to next sibling. - nextFiber = fiber; - - while (nextFiber !== null) { - if (nextFiber === workInProgress) { - // We're back to the root of this subtree. Exit. - nextFiber = null; - break; - } - - var sibling = nextFiber.sibling; - - if (sibling !== null) { - // Set the return pointer of the sibling to the work-in-progress fiber. - sibling.return = nextFiber.return; - nextFiber = sibling; - break; - } // No more siblings. Traverse up. - - - nextFiber = nextFiber.return; - } - } - - fiber = nextFiber; - } - } - function prepareToReadContext(workInProgress, renderLanes) { - currentlyRenderingFiber = workInProgress; - lastContextDependency = null; - lastFullyObservedContext = null; - var dependencies = workInProgress.dependencies; - - if (dependencies !== null) { - { - var firstContext = dependencies.firstContext; - - if (firstContext !== null) { - if (includesSomeLane(dependencies.lanes, renderLanes)) { - // Context list has a pending update. Mark that this fiber performed work. - markWorkInProgressReceivedUpdate(); - } // Reset the work-in-progress list - - - dependencies.firstContext = null; - } - } - } - } - function readContext(context) { - { - // This warning would fire if you read context inside a Hook like useMemo. - // Unlike the class check below, it's not enforced in production for perf. - if (isDisallowedContextReadInDEV) { - error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); - } - } - - var value = isPrimaryRenderer ? context._currentValue : context._currentValue2; - - if (lastFullyObservedContext === context) ; else { - var contextItem = { - context: context, - memoizedValue: value, - next: null - }; - - if (lastContextDependency === null) { - if (currentlyRenderingFiber === null) { - throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); - } // This is the first dependency for this component. Create a new list. - - - lastContextDependency = contextItem; - currentlyRenderingFiber.dependencies = { - lanes: NoLanes, - firstContext: contextItem - }; - } else { - // Append a new context item. - lastContextDependency = lastContextDependency.next = contextItem; - } - } - - return value; - } - - // An array of all update queues that received updates during the current - // render. When this render exits, either because it finishes or because it is - // interrupted, the interleaved updates will be transferred onto the main part - // of the queue. - var interleavedQueues = null; - function pushInterleavedQueue(queue) { - if (interleavedQueues === null) { - interleavedQueues = [queue]; - } else { - interleavedQueues.push(queue); - } - } - function enqueueInterleavedUpdates() { - // Transfer the interleaved updates onto the main queue. Each queue has a - // `pending` field and an `interleaved` field. When they are not null, they - // point to the last node in a circular linked list. We need to append the - // interleaved list to the end of the pending list by joining them into a - // single, circular list. - if (interleavedQueues !== null) { - for (var i = 0; i < interleavedQueues.length; i++) { - var queue = interleavedQueues[i]; - var lastInterleavedUpdate = queue.interleaved; - - if (lastInterleavedUpdate !== null) { - queue.interleaved = null; - var firstInterleavedUpdate = lastInterleavedUpdate.next; - var lastPendingUpdate = queue.pending; - - if (lastPendingUpdate !== null) { - var firstPendingUpdate = lastPendingUpdate.next; - lastPendingUpdate.next = firstInterleavedUpdate; - lastInterleavedUpdate.next = firstPendingUpdate; - } - - queue.pending = lastInterleavedUpdate; - } - } - - interleavedQueues = null; - } - } - - var UpdateState = 0; - var ReplaceState = 1; - var ForceUpdate = 2; - var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. - // It should only be read right after calling `processUpdateQueue`, via - // `checkHasForceUpdateAfterProcessing`. - - var hasForceUpdate = false; - var didWarnUpdateInsideUpdate; - var currentlyProcessingQueue; - - { - didWarnUpdateInsideUpdate = false; - currentlyProcessingQueue = null; - } - - function initializeUpdateQueue(fiber) { - var queue = { - baseState: fiber.memoizedState, - firstBaseUpdate: null, - lastBaseUpdate: null, - shared: { - pending: null, - interleaved: null, - lanes: NoLanes - }, - effects: null - }; - fiber.updateQueue = queue; - } - function cloneUpdateQueue(current, workInProgress) { - // Clone the update queue from current. Unless it's already a clone. - var queue = workInProgress.updateQueue; - var currentQueue = current.updateQueue; - - if (queue === currentQueue) { - var clone = { - baseState: currentQueue.baseState, - firstBaseUpdate: currentQueue.firstBaseUpdate, - lastBaseUpdate: currentQueue.lastBaseUpdate, - shared: currentQueue.shared, - effects: currentQueue.effects - }; - workInProgress.updateQueue = clone; - } - } - function createUpdate(eventTime, lane) { - var update = { - eventTime: eventTime, - lane: lane, - tag: UpdateState, - payload: null, - callback: null, - next: null - }; - return update; - } - function enqueueUpdate(fiber, update, lane) { - var updateQueue = fiber.updateQueue; - - if (updateQueue === null) { - // Only occurs if the fiber has been unmounted. - return; - } - - var sharedQueue = updateQueue.shared; - - if (isInterleavedUpdate(fiber)) { - var interleaved = sharedQueue.interleaved; - - if (interleaved === null) { - // This is the first update. Create a circular list. - update.next = update; // At the end of the current render, this queue's interleaved updates will - // be transferred to the pending queue. - - pushInterleavedQueue(sharedQueue); - } else { - update.next = interleaved.next; - interleaved.next = update; - } - - sharedQueue.interleaved = update; - } else { - var pending = sharedQueue.pending; - - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - - sharedQueue.pending = update; - } - - { - if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) { - error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); - - didWarnUpdateInsideUpdate = true; - } - } - } - function entangleTransitions(root, fiber, lane) { - var updateQueue = fiber.updateQueue; - - if (updateQueue === null) { - // Only occurs if the fiber has been unmounted. - return; - } - - var sharedQueue = updateQueue.shared; - - if (isTransitionLane(lane)) { - var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must - // have finished. We can remove them from the shared queue, which represents - // a superset of the actually pending lanes. In some cases we may entangle - // more than we need to, but that's OK. In fact it's worse if we *don't* - // entangle when we should. - - queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. - - var newQueueLanes = mergeLanes(queueLanes, lane); - sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if - // the lane finished since the last time we entangled it. So we need to - // entangle it again, just to be sure. - - markRootEntangled(root, newQueueLanes); - } - } - function enqueueCapturedUpdate(workInProgress, capturedUpdate) { - // Captured updates are updates that are thrown by a child during the render - // phase. They should be discarded if the render is aborted. Therefore, - // we should only put them on the work-in-progress queue, not the current one. - var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone. - - var current = workInProgress.alternate; - - if (current !== null) { - var currentQueue = current.updateQueue; - - if (queue === currentQueue) { - // The work-in-progress queue is the same as current. This happens when - // we bail out on a parent fiber that then captures an error thrown by - // a child. Since we want to append the update only to the work-in - // -progress queue, we need to clone the updates. We usually clone during - // processUpdateQueue, but that didn't happen in this case because we - // skipped over the parent when we bailed out. - var newFirst = null; - var newLast = null; - var firstBaseUpdate = queue.firstBaseUpdate; - - if (firstBaseUpdate !== null) { - // Loop through the updates and clone them. - var update = firstBaseUpdate; - - do { - var clone = { - eventTime: update.eventTime, - lane: update.lane, - tag: update.tag, - payload: update.payload, - callback: update.callback, - next: null - }; - - if (newLast === null) { - newFirst = newLast = clone; - } else { - newLast.next = clone; - newLast = clone; - } - - update = update.next; - } while (update !== null); // Append the captured update the end of the cloned list. - - - if (newLast === null) { - newFirst = newLast = capturedUpdate; - } else { - newLast.next = capturedUpdate; - newLast = capturedUpdate; - } - } else { - // There are no base updates. - newFirst = newLast = capturedUpdate; - } - - queue = { - baseState: currentQueue.baseState, - firstBaseUpdate: newFirst, - lastBaseUpdate: newLast, - shared: currentQueue.shared, - effects: currentQueue.effects - }; - workInProgress.updateQueue = queue; - return; - } - } // Append the update to the end of the list. - - - var lastBaseUpdate = queue.lastBaseUpdate; - - if (lastBaseUpdate === null) { - queue.firstBaseUpdate = capturedUpdate; - } else { - lastBaseUpdate.next = capturedUpdate; - } - - queue.lastBaseUpdate = capturedUpdate; - } - - function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) { - switch (update.tag) { - case ReplaceState: - { - var payload = update.payload; - - if (typeof payload === 'function') { - // Updater function - { - enterDisallowedContextReadInDEV(); - } - - var nextState = payload.call(instance, prevState, nextProps); - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - payload.call(instance, prevState, nextProps); - } finally { - setIsStrictModeForDevtools(false); - } - } - - exitDisallowedContextReadInDEV(); - } - - return nextState; - } // State object - - - return payload; - } - - case CaptureUpdate: - { - workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture; - } - // Intentional fallthrough - - case UpdateState: - { - var _payload = update.payload; - var partialState; - - if (typeof _payload === 'function') { - // Updater function - { - enterDisallowedContextReadInDEV(); - } - - partialState = _payload.call(instance, prevState, nextProps); - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - _payload.call(instance, prevState, nextProps); - } finally { - setIsStrictModeForDevtools(false); - } - } - - exitDisallowedContextReadInDEV(); - } - } else { - // Partial state object - partialState = _payload; - } - - if (partialState === null || partialState === undefined) { - // Null and undefined are treated as no-ops. - return prevState; - } // Merge the partial state and the previous state. - - - return assign({}, prevState, partialState); - } - - case ForceUpdate: - { - hasForceUpdate = true; - return prevState; - } - } - - return prevState; - } - - function processUpdateQueue(workInProgress, props, instance, renderLanes) { - // This is always non-null on a ClassComponent or HostRoot - var queue = workInProgress.updateQueue; - hasForceUpdate = false; - - { - currentlyProcessingQueue = queue.shared; - } - - var firstBaseUpdate = queue.firstBaseUpdate; - var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue. - - var pendingQueue = queue.shared.pending; - - if (pendingQueue !== null) { - queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first - // and last so that it's non-circular. - - var lastPendingUpdate = pendingQueue; - var firstPendingUpdate = lastPendingUpdate.next; - lastPendingUpdate.next = null; // Append pending updates to base queue - - if (lastBaseUpdate === null) { - firstBaseUpdate = firstPendingUpdate; - } else { - lastBaseUpdate.next = firstPendingUpdate; - } - - lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then - // we need to transfer the updates to that queue, too. Because the base - // queue is a singly-linked list with no cycles, we can append to both - // lists and take advantage of structural sharing. - // TODO: Pass `current` as argument - - var current = workInProgress.alternate; - - if (current !== null) { - // This is always non-null on a ClassComponent or HostRoot - var currentQueue = current.updateQueue; - var currentLastBaseUpdate = currentQueue.lastBaseUpdate; - - if (currentLastBaseUpdate !== lastBaseUpdate) { - if (currentLastBaseUpdate === null) { - currentQueue.firstBaseUpdate = firstPendingUpdate; - } else { - currentLastBaseUpdate.next = firstPendingUpdate; - } - - currentQueue.lastBaseUpdate = lastPendingUpdate; - } - } - } // These values may change as we process the queue. - - - if (firstBaseUpdate !== null) { - // Iterate through the list of updates to compute the result. - var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes - // from the original lanes. - - var newLanes = NoLanes; - var newBaseState = null; - var newFirstBaseUpdate = null; - var newLastBaseUpdate = null; - var update = firstBaseUpdate; - - do { - var updateLane = update.lane; - var updateEventTime = update.eventTime; - - if (!isSubsetOfLanes(renderLanes, updateLane)) { - // Priority is insufficient. Skip this update. If this is the first - // skipped update, the previous update/state is the new base - // update/state. - var clone = { - eventTime: updateEventTime, - lane: updateLane, - tag: update.tag, - payload: update.payload, - callback: update.callback, - next: null - }; - - if (newLastBaseUpdate === null) { - newFirstBaseUpdate = newLastBaseUpdate = clone; - newBaseState = newState; - } else { - newLastBaseUpdate = newLastBaseUpdate.next = clone; - } // Update the remaining priority in the queue. - - - newLanes = mergeLanes(newLanes, updateLane); - } else { - // This update does have sufficient priority. - if (newLastBaseUpdate !== null) { - var _clone = { - eventTime: updateEventTime, - // This update is going to be committed so we never want uncommit - // it. Using NoLane works because 0 is a subset of all bitmasks, so - // this will never be skipped by the check above. - lane: NoLane, - tag: update.tag, - payload: update.payload, - callback: update.callback, - next: null - }; - newLastBaseUpdate = newLastBaseUpdate.next = _clone; - } // Process this update. - - - newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance); - var callback = update.callback; - - if (callback !== null && // If the update was already committed, we should not queue its - // callback again. - update.lane !== NoLane) { - workInProgress.flags |= Callback; - var effects = queue.effects; - - if (effects === null) { - queue.effects = [update]; - } else { - effects.push(update); - } - } - } - - update = update.next; - - if (update === null) { - pendingQueue = queue.shared.pending; - - if (pendingQueue === null) { - break; - } else { - // An update was scheduled from inside a reducer. Add the new - // pending updates to the end of the list and keep processing. - var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we - // unravel them when transferring them to the base queue. - - var _firstPendingUpdate = _lastPendingUpdate.next; - _lastPendingUpdate.next = null; - update = _firstPendingUpdate; - queue.lastBaseUpdate = _lastPendingUpdate; - queue.shared.pending = null; - } - } - } while (true); - - if (newLastBaseUpdate === null) { - newBaseState = newState; - } - - queue.baseState = newBaseState; - queue.firstBaseUpdate = newFirstBaseUpdate; - queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to - // process them during this render, but we do need to track which lanes - // are remaining. - - var lastInterleaved = queue.shared.interleaved; - - if (lastInterleaved !== null) { - var interleaved = lastInterleaved; - - do { - newLanes = mergeLanes(newLanes, interleaved.lane); - interleaved = interleaved.next; - } while (interleaved !== lastInterleaved); - } else if (firstBaseUpdate === null) { - // `queue.lanes` is used for entangling transitions. We can set it back to - // zero once the queue is empty. - queue.shared.lanes = NoLanes; - } // Set the remaining expiration time to be whatever is remaining in the queue. - // This should be fine because the only two other things that contribute to - // expiration time are props and context. We're already in the middle of the - // begin phase by the time we start processing the queue, so we've already - // dealt with the props. Context in components that specify - // shouldComponentUpdate is tricky; but we'll have to account for - // that regardless. - - - markSkippedUpdateLanes(newLanes); - workInProgress.lanes = newLanes; - workInProgress.memoizedState = newState; - } - - { - currentlyProcessingQueue = null; - } - } - - function callCallback(callback, context) { - if (typeof callback !== 'function') { - throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback)); - } - - callback.call(context); - } - - function resetHasForceUpdateBeforeProcessing() { - hasForceUpdate = false; - } - function checkHasForceUpdateAfterProcessing() { - return hasForceUpdate; - } - function commitUpdateQueue(finishedWork, finishedQueue, instance) { - // Commit the effects - var effects = finishedQueue.effects; - finishedQueue.effects = null; - - if (effects !== null) { - for (var i = 0; i < effects.length; i++) { - var effect = effects[i]; - var callback = effect.callback; - - if (callback !== null) { - effect.callback = null; - callCallback(callback, instance); - } - } - } - } - - var fakeInternalInstance = {}; // React.Component uses a shared frozen object by default. - // We'll use it to determine whether we need to initialize legacy refs. - - var emptyRefsObject = new React.Component().refs; - var didWarnAboutStateAssignmentForComponent; - var didWarnAboutUninitializedState; - var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; - var didWarnAboutLegacyLifecyclesAndDerivedState; - var didWarnAboutUndefinedDerivedState; - var warnOnUndefinedDerivedState; - var warnOnInvalidCallback; - var didWarnAboutDirectlyAssigningPropsToState; - var didWarnAboutContextTypeAndContextTypes; - var didWarnAboutInvalidateContextType; - - { - didWarnAboutStateAssignmentForComponent = new Set(); - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - didWarnAboutDirectlyAssigningPropsToState = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutContextTypeAndContextTypes = new Set(); - didWarnAboutInvalidateContextType = new Set(); - var didWarnOnInvalidCallback = new Set(); - - warnOnInvalidCallback = function (callback, callerName) { - if (callback === null || typeof callback === 'function') { - return; - } - - var key = callerName + '_' + callback; - - if (!didWarnOnInvalidCallback.has(key)) { - didWarnOnInvalidCallback.add(key); - - error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); - } - }; - - warnOnUndefinedDerivedState = function (type, partialState) { - if (partialState === undefined) { - var componentName = getComponentNameFromType(type) || 'Component'; - - if (!didWarnAboutUndefinedDerivedState.has(componentName)) { - didWarnAboutUndefinedDerivedState.add(componentName); - - error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); - } - } - }; // This is so gross but it's at least non-critical and can be removed if - // it causes problems. This is meant to give a nicer error message for - // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, - // ...)) which otherwise throws a "_processChildContext is not a function" - // exception. - - - Object.defineProperty(fakeInternalInstance, '_processChildContext', { - enumerable: false, - value: function () { - throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).'); - } - }); - Object.freeze(fakeInternalInstance); - } - - function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) { - var prevState = workInProgress.memoizedState; - var partialState = getDerivedStateFromProps(nextProps, prevState); - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - // Invoke the function an extra time to help detect side-effects. - partialState = getDerivedStateFromProps(nextProps, prevState); - } finally { - setIsStrictModeForDevtools(false); - } - } - - warnOnUndefinedDerivedState(ctor, partialState); - } // Merge the partial state and the previous state. - - - var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); - workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the - // base state. - - if (workInProgress.lanes === NoLanes) { - // Queue is always non-null for classes - var updateQueue = workInProgress.updateQueue; - updateQueue.baseState = memoizedState; - } - } - - var classComponentUpdater = { - isMounted: isMounted, - enqueueSetState: function (inst, payload, callback) { - var fiber = get(inst); - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - var update = createUpdate(eventTime, lane); - update.payload = payload; - - if (callback !== undefined && callback !== null) { - { - warnOnInvalidCallback(callback, 'setState'); - } - - update.callback = callback; - } - - enqueueUpdate(fiber, update); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitions(root, fiber, lane); - } - - { - markStateUpdateScheduled(fiber, lane); - } - }, - enqueueReplaceState: function (inst, payload, callback) { - var fiber = get(inst); - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - var update = createUpdate(eventTime, lane); - update.tag = ReplaceState; - update.payload = payload; - - if (callback !== undefined && callback !== null) { - { - warnOnInvalidCallback(callback, 'replaceState'); - } - - update.callback = callback; - } - - enqueueUpdate(fiber, update); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitions(root, fiber, lane); - } - - { - markStateUpdateScheduled(fiber, lane); - } - }, - enqueueForceUpdate: function (inst, callback) { - var fiber = get(inst); - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - var update = createUpdate(eventTime, lane); - update.tag = ForceUpdate; - - if (callback !== undefined && callback !== null) { - { - warnOnInvalidCallback(callback, 'forceUpdate'); - } - - update.callback = callback; - } - - enqueueUpdate(fiber, update); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitions(root, fiber, lane); - } - - { - markForceUpdateScheduled(fiber, lane); - } - } - }; - - function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) { - var instance = workInProgress.stateNode; - - if (typeof instance.shouldComponentUpdate === 'function') { - var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - // Invoke the function an extra time to help detect side-effects. - shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); - } finally { - setIsStrictModeForDevtools(false); - } - } - - if (shouldUpdate === undefined) { - error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component'); - } - } - - return shouldUpdate; - } - - if (ctor.prototype && ctor.prototype.isPureReactComponent) { - return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); - } - - return true; - } - - function checkClassInstance(workInProgress, ctor, newProps) { - var instance = workInProgress.stateNode; - - { - var name = getComponentNameFromType(ctor) || 'Component'; - var renderPresent = instance.render; - - if (!renderPresent) { - if (ctor.prototype && typeof ctor.prototype.render === 'function') { - error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); - } else { - error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); - } - } - - if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { - error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); - } - - if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { - error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); - } - - if (instance.propTypes) { - error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); - } - - if (instance.contextType) { - error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); - } - - { - if (instance.contextTypes) { - error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); - } - - if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { - didWarnAboutContextTypeAndContextTypes.add(ctor); - - error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); - } - } - - if (typeof instance.componentShouldUpdate === 'function') { - error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); - } - - if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { - error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); - } - - if (typeof instance.componentDidUnmount === 'function') { - error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); - } - - if (typeof instance.componentDidReceiveProps === 'function') { - error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); - } - - if (typeof instance.componentWillRecieveProps === 'function') { - error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); - } - - if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { - error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); - } - - var hasMutatedProps = instance.props !== newProps; - - if (instance.props !== undefined && hasMutatedProps) { - error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); - } - - if (instance.defaultProps) { - error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); - } - - if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - - error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); - } - - if (typeof instance.getDerivedStateFromProps === 'function') { - error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); - } - - if (typeof instance.getDerivedStateFromError === 'function') { - error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); - } - - if (typeof ctor.getSnapshotBeforeUpdate === 'function') { - error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); - } - - var _state = instance.state; - - if (_state && (typeof _state !== 'object' || isArray(_state))) { - error('%s.state: must be set to an object or null', name); - } - - if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { - error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); - } - } - } - - function adoptClassInstance(workInProgress, instance) { - instance.updater = classComponentUpdater; - workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates - - set(instance, workInProgress); - - { - instance._reactInternalInstance = fakeInternalInstance; - } - } - - function constructClassInstance(workInProgress, ctor, props) { - var isLegacyContextConsumer = false; - var unmaskedContext = emptyContextObject; - var context = emptyContextObject; - var contextType = ctor.contextType; - - { - if ('contextType' in ctor) { - var isValid = // Allow null for conditional declaration - contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a - - if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { - didWarnAboutInvalidateContextType.add(ctor); - var addendum = ''; - - if (contextType === undefined) { - addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; - } else if (typeof contextType !== 'object') { - addendum = ' However, it is set to a ' + typeof contextType + '.'; - } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { - addendum = ' Did you accidentally pass the Context.Provider instead?'; - } else if (contextType._context !== undefined) { - // - addendum = ' Did you accidentally pass the Context.Consumer instead?'; - } else { - addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; - } - - error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); - } - } - } - - if (typeof contextType === 'object' && contextType !== null) { - context = readContext(contextType); - } else { - unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - var contextTypes = ctor.contextTypes; - isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined; - context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; - } - - var instance = new ctor(props, context); // Instantiate twice to help detect side-effects. - - { - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - instance = new ctor(props, context); // eslint-disable-line no-new - } finally { - setIsStrictModeForDevtools(false); - } - } - } - - var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null; - adoptClassInstance(workInProgress, instance); - - { - if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { - var componentName = getComponentNameFromType(ctor) || 'Component'; - - if (!didWarnAboutUninitializedState.has(componentName)) { - didWarnAboutUninitializedState.add(componentName); - - error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); - } - } // If new component APIs are defined, "unsafe" lifecycles won't be called. - // Warn about these lifecycles if they are present. - // Don't warn about react-lifecycles-compat polyfilled methods though. - - - if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { - var foundWillMountName = null; - var foundWillReceivePropsName = null; - var foundWillUpdateName = null; - - if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { - foundWillMountName = 'componentWillMount'; - } else if (typeof instance.UNSAFE_componentWillMount === 'function') { - foundWillMountName = 'UNSAFE_componentWillMount'; - } - - if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { - foundWillReceivePropsName = 'componentWillReceiveProps'; - } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; - } - - if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { - foundWillUpdateName = 'componentWillUpdate'; - } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { - foundWillUpdateName = 'UNSAFE_componentWillUpdate'; - } - - if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { - var _componentName = getComponentNameFromType(ctor) || 'Component'; - - var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; - - if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { - didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); - - error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); - } - } - } - } // Cache unmasked context so we can avoid recreating masked context unless necessary. - // ReactFiberContext usually updates this cache but can't for newly-created instances. - - - if (isLegacyContextConsumer) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return instance; - } - - function callComponentWillMount(workInProgress, instance) { - var oldState = instance.state; - - if (typeof instance.componentWillMount === 'function') { - instance.componentWillMount(); - } - - if (typeof instance.UNSAFE_componentWillMount === 'function') { - instance.UNSAFE_componentWillMount(); - } - - if (oldState !== instance.state) { - { - error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component'); - } - - classComponentUpdater.enqueueReplaceState(instance, instance.state, null); - } - } - - function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) { - var oldState = instance.state; - - if (typeof instance.componentWillReceiveProps === 'function') { - instance.componentWillReceiveProps(newProps, nextContext); - } - - if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); - } - - if (instance.state !== oldState) { - { - var componentName = getComponentNameFromFiber(workInProgress) || 'Component'; - - if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { - didWarnAboutStateAssignmentForComponent.add(componentName); - - error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName); - } - } - - classComponentUpdater.enqueueReplaceState(instance, instance.state, null); - } - } // Invokes the mount life-cycles on a previously never rendered instance. - - - function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { - { - checkClassInstance(workInProgress, ctor, newProps); - } - - var instance = workInProgress.stateNode; - instance.props = newProps; - instance.state = workInProgress.memoizedState; - instance.refs = emptyRefsObject; - initializeUpdateQueue(workInProgress); - var contextType = ctor.contextType; - - if (typeof contextType === 'object' && contextType !== null) { - instance.context = readContext(contextType); - } else { - var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - instance.context = getMaskedContext(workInProgress, unmaskedContext); - } - - { - if (instance.state === newProps) { - var componentName = getComponentNameFromType(ctor) || 'Component'; - - if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { - didWarnAboutDirectlyAssigningPropsToState.add(componentName); - - error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); - } - } - - if (workInProgress.mode & StrictLegacyMode) { - ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance); - } - - { - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance); - } - } - - instance.state = workInProgress.memoizedState; - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - - if (typeof getDerivedStateFromProps === 'function') { - applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); - instance.state = workInProgress.memoizedState; - } // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - - - if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { - callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's - // process them now. - - processUpdateQueue(workInProgress, newProps, instance, renderLanes); - instance.state = workInProgress.memoizedState; - } - - if (typeof instance.componentDidMount === 'function') { - var fiberFlags = Update; - - { - fiberFlags |= LayoutStatic; - } - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - - workInProgress.flags |= fiberFlags; - } - } - - function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) { - var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; - instance.props = oldProps; - var oldContext = instance.context; - var contextType = ctor.contextType; - var nextContext = emptyContextObject; - - if (typeof contextType === 'object' && contextType !== null) { - nextContext = readContext(contextType); - } else { - var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext); - } - - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what - // ever the previously attempted to render - not the "current". However, - // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { - if (oldProps !== newProps || oldContext !== nextContext) { - callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); - } - } - - resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; - var newState = instance.state = oldState; - processUpdateQueue(workInProgress, newProps, instance, renderLanes); - newState = workInProgress.memoizedState; - - if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidMount === 'function') { - var fiberFlags = Update; - - { - fiberFlags |= LayoutStatic; - } - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - - workInProgress.flags |= fiberFlags; - } - - return false; - } - - if (typeof getDerivedStateFromProps === 'function') { - applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); - newState = workInProgress.memoizedState; - } - - var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext); - - if (shouldUpdate) { - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { - if (typeof instance.componentWillMount === 'function') { - instance.componentWillMount(); - } - - if (typeof instance.UNSAFE_componentWillMount === 'function') { - instance.UNSAFE_componentWillMount(); - } - } - - if (typeof instance.componentDidMount === 'function') { - var _fiberFlags = Update; - - { - _fiberFlags |= LayoutStatic; - } - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - _fiberFlags |= MountLayoutDev; - } - - workInProgress.flags |= _fiberFlags; - } - } else { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidMount === 'function') { - var _fiberFlags2 = Update; - - { - _fiberFlags2 |= LayoutStatic; - } - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - _fiberFlags2 |= MountLayoutDev; - } - - workInProgress.flags |= _fiberFlags2; - } // If shouldComponentUpdate returned false, we should still update the - // memoized state to indicate that this work can be reused. - - - workInProgress.memoizedProps = newProps; - workInProgress.memoizedState = newState; - } // Update the existing instance's state, props, and context pointers even - // if shouldComponentUpdate returns false. - - - instance.props = newProps; - instance.state = newState; - instance.context = nextContext; - return shouldUpdate; - } // Invokes the update life-cycles and returns false if it shouldn't rerender. - - - function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) { - var instance = workInProgress.stateNode; - cloneUpdateQueue(current, workInProgress); - var unresolvedOldProps = workInProgress.memoizedProps; - var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps); - instance.props = oldProps; - var unresolvedNewProps = workInProgress.pendingProps; - var oldContext = instance.context; - var contextType = ctor.contextType; - var nextContext = emptyContextObject; - - if (typeof contextType === 'object' && contextType !== null) { - nextContext = readContext(contextType); - } else { - var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); - } - - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what - // ever the previously attempted to render - not the "current". However, - // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { - if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { - callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); - } - } - - resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; - var newState = instance.state = oldState; - processUpdateQueue(workInProgress, newProps, instance, renderLanes); - newState = workInProgress.memoizedState; - - if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation )) { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.flags |= Update; - } - } - - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.flags |= Snapshot; - } - } - - return false; - } - - if (typeof getDerivedStateFromProps === 'function') { - applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); - newState = workInProgress.memoizedState; - } - - var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice, - // both before and after `shouldComponentUpdate` has been called. Not ideal, - // but I'm loath to refactor this function. This only happens for memoized - // components so it's not that common. - enableLazyContextPropagation ; - - if (shouldUpdate) { - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) { - if (typeof instance.componentWillUpdate === 'function') { - instance.componentWillUpdate(newProps, newState, nextContext); - } - - if (typeof instance.UNSAFE_componentWillUpdate === 'function') { - instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); - } - } - - if (typeof instance.componentDidUpdate === 'function') { - workInProgress.flags |= Update; - } - - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - workInProgress.flags |= Snapshot; - } - } else { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.flags |= Update; - } - } - - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.flags |= Snapshot; - } - } // If shouldComponentUpdate returned false, we should still update the - // memoized props/state to indicate that this work can be reused. - - - workInProgress.memoizedProps = newProps; - workInProgress.memoizedState = newState; - } // Update the existing instance's state, props, and context pointers even - // if shouldComponentUpdate returns false. - - - instance.props = newProps; - instance.state = newState; - instance.context = nextContext; - return shouldUpdate; - } - - // TODO: Use the unified fiber stack module instead of this local one? - // Intentionally not using it yet to derisk the initial implementation, because - // the way we push/pop these values is a bit unusual. If there's a mistake, I'd - // rather the ids be wrong than crash the whole reconciler. - var forkStack = []; - var forkStackIndex = 0; - var treeForkProvider = null; - var treeForkCount = 0; - var idStack = []; - var idStackIndex = 0; - var treeContextProvider = null; - var treeContextId = 1; - var treeContextOverflow = ''; - function isForkedChild(workInProgress) { - warnIfNotHydrating(); - return (workInProgress.flags & Forked) !== NoFlags; - } - function getForksAtLevel(workInProgress) { - warnIfNotHydrating(); - return treeForkCount; - } - function getTreeId() { - var overflow = treeContextOverflow; - var idWithLeadingBit = treeContextId; - var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); - return id.toString(32) + overflow; - } - function pushTreeFork(workInProgress, totalChildren) { - // This is called right after we reconcile an array (or iterator) of child - // fibers, because that's the only place where we know how many children in - // the whole set without doing extra work later, or storing addtional - // information on the fiber. - // - // That's why this function is separate from pushTreeId — it's called during - // the render phase of the fork parent, not the child, which is where we push - // the other context values. - // - // In the Fizz implementation this is much simpler because the child is - // rendered in the same callstack as the parent. - // - // It might be better to just add a `forks` field to the Fiber type. It would - // make this module simpler. - warnIfNotHydrating(); - forkStack[forkStackIndex++] = treeForkCount; - forkStack[forkStackIndex++] = treeForkProvider; - treeForkProvider = workInProgress; - treeForkCount = totalChildren; - } - function pushTreeId(workInProgress, totalChildren, index) { - warnIfNotHydrating(); - idStack[idStackIndex++] = treeContextId; - idStack[idStackIndex++] = treeContextOverflow; - idStack[idStackIndex++] = treeContextProvider; - treeContextProvider = workInProgress; - var baseIdWithLeadingBit = treeContextId; - var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part - // of the id; we use it to account for leading 0s. - - var baseLength = getBitLength(baseIdWithLeadingBit) - 1; - var baseId = baseIdWithLeadingBit & ~(1 << baseLength); - var slot = index + 1; - var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into - // consideration the leading 1 we use to mark the end of the sequence. - - if (length > 30) { - // We overflowed the bitwise-safe range. Fall back to slower algorithm. - // This branch assumes the length of the base id is greater than 5; it won't - // work for smaller ids, because you need 5 bits per character. - // - // We encode the id in multiple steps: first the base id, then the - // remaining digits. - // - // Each 5 bit sequence corresponds to a single base 32 character. So for - // example, if the current id is 23 bits long, we can convert 20 of those - // bits into a string of 4 characters, with 3 bits left over. - // - // First calculate how many bits in the base id represent a complete - // sequence of characters. - var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. - - var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. - - var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. - - var restOfBaseId = baseId >> numberOfOverflowBits; - var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because - // we made more room, this time it won't overflow. - - var restOfLength = getBitLength(totalChildren) + restOfBaseLength; - var restOfNewBits = slot << restOfBaseLength; - var id = restOfNewBits | restOfBaseId; - var overflow = newOverflow + baseOverflow; - treeContextId = 1 << restOfLength | id; - treeContextOverflow = overflow; - } else { - // Normal path - var newBits = slot << baseLength; - - var _id = newBits | baseId; - - var _overflow = baseOverflow; - treeContextId = 1 << length | _id; - treeContextOverflow = _overflow; - } - } - function pushMaterializedTreeId(workInProgress) { - warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear - // in its children. - - var returnFiber = workInProgress.return; - - if (returnFiber !== null) { - var numberOfForks = 1; - var slotIndex = 0; - pushTreeFork(workInProgress, numberOfForks); - pushTreeId(workInProgress, numberOfForks, slotIndex); - } - } - - function getBitLength(number) { - return 32 - clz32(number); - } - - function getLeadingBit(id) { - return 1 << getBitLength(id) - 1; - } - - function popTreeContext(workInProgress) { - // Restore the previous values. - // This is a bit more complicated than other context-like modules in Fiber - // because the same Fiber may appear on the stack multiple times and for - // different reasons. We have to keep popping until the work-in-progress is - // no longer at the top of the stack. - while (workInProgress === treeForkProvider) { - treeForkProvider = forkStack[--forkStackIndex]; - forkStack[forkStackIndex] = null; - treeForkCount = forkStack[--forkStackIndex]; - forkStack[forkStackIndex] = null; - } - - while (workInProgress === treeContextProvider) { - treeContextProvider = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - treeContextOverflow = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - treeContextId = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - } - } - function getSuspendedTreeContext() { - warnIfNotHydrating(); - - if (treeContextProvider !== null) { - return { - id: treeContextId, - overflow: treeContextOverflow - }; - } else { - return null; - } - } - function restoreSuspendedTreeContext(workInProgress, suspendedContext) { - warnIfNotHydrating(); - idStack[idStackIndex++] = treeContextId; - idStack[idStackIndex++] = treeContextOverflow; - idStack[idStackIndex++] = treeContextProvider; - treeContextId = suspendedContext.id; - treeContextOverflow = suspendedContext.overflow; - treeContextProvider = workInProgress; - } - - function warnIfNotHydrating() { - { - if (!getIsHydrating()) { - error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.'); - } - } - } - - // This may have been an insertion or a hydration. - - var hydrationParentFiber = null; - var nextHydratableInstance = null; - var isHydrating = false; - var didSuspend = false; // Hydration errors that were thrown inside this boundary - - var hydrationErrors = null; - - function warnIfHydrating() { - { - if (isHydrating) { - error('We should not be hydrating here. This is a bug in React. Please file a bug.'); - } - } - } - - function markDidSuspendWhileHydratingDEV() { - { - didSuspend = true; - } - } - - function enterHydrationState(fiber) { - if (!supportsHydration) { - return false; - } - - var parentInstance = fiber.stateNode.containerInfo; - nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); - hydrationParentFiber = fiber; - isHydrating = true; - hydrationErrors = null; - didSuspend = false; - return true; - } - - function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) { - if (!supportsHydration) { - return false; - } - - nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); - hydrationParentFiber = fiber; - isHydrating = true; - hydrationErrors = null; - didSuspend = false; - - if (treeContext !== null) { - restoreSuspendedTreeContext(fiber, treeContext); - } - - return true; - } - - function warnUnhydratedInstance(returnFiber, instance) { - { - switch (returnFiber.tag) { - case HostRoot: - didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance); - break; - - case HostComponent: - didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance); - break; - - case SuspenseComponent: - var suspenseState = returnFiber.memoizedState; - if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance); - break; - } - } - } - - function deleteHydratableInstance(returnFiber, instance) { - warnUnhydratedInstance(returnFiber, instance); - var childToDelete = createFiberFromHostInstanceForDeletion(); - childToDelete.stateNode = instance; - childToDelete.return = returnFiber; - var deletions = returnFiber.deletions; - - if (deletions === null) { - returnFiber.deletions = [childToDelete]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(childToDelete); - } - } - - function warnNonhydratedInstance(returnFiber, fiber) { - { - if (didSuspend) { - // Inside a boundary that already suspended. We're currently rendering the - // siblings of a suspended node. The mismatch may be due to the missing - // data, so it's probably a false positive. - return; - } - - switch (returnFiber.tag) { - case HostRoot: - { - var parentContainer = returnFiber.stateNode.containerInfo; - - switch (fiber.tag) { - case HostComponent: - var type = fiber.type; - var props = fiber.pendingProps; - didNotFindHydratableInstanceWithinContainer(parentContainer, type, props); - break; - - case HostText: - var text = fiber.pendingProps; - didNotFindHydratableTextInstanceWithinContainer(parentContainer, text); - break; - - case SuspenseComponent: - didNotFindHydratableSuspenseInstanceWithinContainer(parentContainer); - break; - } - - break; - } - - case HostComponent: - { - var parentType = returnFiber.type; - var parentProps = returnFiber.memoizedProps; - var parentInstance = returnFiber.stateNode; - - switch (fiber.tag) { - case HostComponent: - var _type = fiber.type; - var _props = fiber.pendingProps; - didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props); - break; - - case HostText: - var _text = fiber.pendingProps; - didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text); - break; - - case SuspenseComponent: - didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance); - break; - } - - break; - } - - case SuspenseComponent: - { - var suspenseState = returnFiber.memoizedState; - var _parentInstance = suspenseState.dehydrated; - if (_parentInstance !== null) switch (fiber.tag) { - case HostComponent: - var _type2 = fiber.type; - var _props2 = fiber.pendingProps; - didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2, _props2); - break; - - case HostText: - var _text2 = fiber.pendingProps; - didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2); - break; - - case SuspenseComponent: - didNotFindHydratableSuspenseInstanceWithinSuspenseInstance(_parentInstance); - break; - } - break; - } - - default: - return; - } - } - } - - function insertNonHydratedInstance(returnFiber, fiber) { - fiber.flags = fiber.flags & ~Hydrating | Placement; - warnNonhydratedInstance(returnFiber, fiber); - } - - function tryHydrate(fiber, nextInstance) { - switch (fiber.tag) { - case HostComponent: - { - var type = fiber.type; - var props = fiber.pendingProps; - var instance = canHydrateInstance(nextInstance, type, props); - - if (instance !== null) { - fiber.stateNode = instance; - hydrationParentFiber = fiber; - nextHydratableInstance = getFirstHydratableChild(instance); - return true; - } - - return false; - } - - case HostText: - { - var text = fiber.pendingProps; - var textInstance = canHydrateTextInstance(nextInstance, text); - - if (textInstance !== null) { - fiber.stateNode = textInstance; - hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate. - - nextHydratableInstance = null; - return true; - } - - return false; - } - - case SuspenseComponent: - { - { - var suspenseInstance = canHydrateSuspenseInstance(nextInstance); - - if (suspenseInstance !== null) { - var suspenseState = { - dehydrated: suspenseInstance, - treeContext: getSuspendedTreeContext(), - retryLane: OffscreenLane - }; - fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. - // This simplifies the code for getHostSibling and deleting nodes, - // since it doesn't have to consider all Suspense boundaries and - // check if they're dehydrated ones or not. - - var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); - dehydratedFragment.return = fiber; - fiber.child = dehydratedFragment; - hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into - // it during the first pass. Instead, we'll reenter it later. - - nextHydratableInstance = null; - return true; - } - } - - return false; - } - - default: - return false; - } - } - - function shouldClientRenderOnMismatch(fiber) { - return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags; - } - - function throwOnHydrationMismatch(fiber) { - throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.'); - } - - function tryToClaimNextHydratableInstance(fiber) { - if (!isHydrating) { - return; - } - - var nextInstance = nextHydratableInstance; - - if (!nextInstance) { - if (shouldClientRenderOnMismatch(fiber)) { - warnNonhydratedInstance(hydrationParentFiber, fiber); - throwOnHydrationMismatch(); - } // Nothing to hydrate. Make it an insertion. - - - insertNonHydratedInstance(hydrationParentFiber, fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } - - var firstAttemptedInstance = nextInstance; - - if (!tryHydrate(fiber, nextInstance)) { - if (shouldClientRenderOnMismatch(fiber)) { - warnNonhydratedInstance(hydrationParentFiber, fiber); - throwOnHydrationMismatch(); - } // If we can't hydrate this instance let's try the next one. - // We use this as a heuristic. It's based on intuition and not data so it - // might be flawed or unnecessary. - - - nextInstance = getNextHydratableSibling(firstAttemptedInstance); - var prevHydrationParentFiber = hydrationParentFiber; - - if (!nextInstance || !tryHydrate(fiber, nextInstance)) { - // Nothing to hydrate. Make it an insertion. - insertNonHydratedInstance(hydrationParentFiber, fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } // We matched the next one, we'll now assume that the first one was - // superfluous and we'll delete it. Since we can't eagerly delete it - // we'll have to schedule a deletion. To do that, this node needs a dummy - // fiber associated with it. - - - deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); - } - } - - function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { - if (!supportsHydration) { - throw new Error('Expected prepareToHydrateHostInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var instance = fiber.stateNode; - var shouldWarnIfMismatchDev = !didSuspend; - var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component. - - fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there - // is a new ref we mark this as an update. - - if (updatePayload !== null) { - return true; - } - - return false; - } - - function prepareToHydrateHostTextInstance(fiber) { - if (!supportsHydration) { - throw new Error('Expected prepareToHydrateHostTextInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var textInstance = fiber.stateNode; - var textContent = fiber.memoizedProps; - var shouldWarnIfMismatchDev = !didSuspend; - var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber, shouldWarnIfMismatchDev); - - if (shouldUpdate) { - // We assume that prepareToHydrateHostTextInstance is called in a context where the - // hydration parent is the parent host component of this host text. - var returnFiber = hydrationParentFiber; - - if (returnFiber !== null) { - var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; - - switch (returnFiber.tag) { - case HostRoot: - { - var parentContainer = returnFiber.stateNode.containerInfo; - didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode); - break; - } - - case HostComponent: - { - var parentType = returnFiber.type; - var parentProps = returnFiber.memoizedProps; - var parentInstance = returnFiber.stateNode; - didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode); - break; - } - } - } - } - - return shouldUpdate; - } - - function prepareToHydrateHostSuspenseInstance(fiber) { - if (!supportsHydration) { - throw new Error('Expected prepareToHydrateHostSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var suspenseState = fiber.memoizedState; - var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; - - if (!suspenseInstance) { - throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - hydrateSuspenseInstance(suspenseInstance, fiber); - } - - function skipPastDehydratedSuspenseInstance(fiber) { - if (!supportsHydration) { - throw new Error('Expected skipPastDehydratedSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - var suspenseState = fiber.memoizedState; - var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; - - if (!suspenseInstance) { - throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); - } - - function popToNextHostParent(fiber) { - var parent = fiber.return; - - while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) { - parent = parent.return; - } - - hydrationParentFiber = parent; - } - - function popHydrationState(fiber) { - if (!supportsHydration) { - return false; - } - - if (fiber !== hydrationParentFiber) { - // We're deeper than the current hydration context, inside an inserted - // tree. - return false; - } - - if (!isHydrating) { - // If we're not currently hydrating but we're in a hydration context, then - // we were an insertion and now need to pop up reenter hydration of our - // siblings. - popToNextHostParent(fiber); - isHydrating = true; - return false; - } // If we have any remaining hydratable nodes, we need to delete them now. - // We only do this deeper than head and body since they tend to have random - // other nodes in them. We also ignore components with pure text content in - // side of them. We also don't delete anything inside the root container. - - - if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) { - var nextInstance = nextHydratableInstance; - - if (nextInstance) { - if (shouldClientRenderOnMismatch(fiber)) { - warnIfUnhydratedTailNodes(fiber); - throwOnHydrationMismatch(); - } else { - while (nextInstance) { - deleteHydratableInstance(fiber, nextInstance); - nextInstance = getNextHydratableSibling(nextInstance); - } - } - } - } - - popToNextHostParent(fiber); - - if (fiber.tag === SuspenseComponent) { - nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); - } else { - nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; - } - - return true; - } - - function hasUnhydratedTailNodes() { - return isHydrating && nextHydratableInstance !== null; - } - - function warnIfUnhydratedTailNodes(fiber) { - var nextInstance = nextHydratableInstance; - - while (nextInstance) { - warnUnhydratedInstance(fiber, nextInstance); - nextInstance = getNextHydratableSibling(nextInstance); - } - } - - function resetHydrationState() { - if (!supportsHydration) { - return; - } - - hydrationParentFiber = null; - nextHydratableInstance = null; - isHydrating = false; - didSuspend = false; - } - - function upgradeHydrationErrorsToRecoverable() { - if (hydrationErrors !== null) { - // Successfully completed a forced client render. The errors that occurred - // during the hydration attempt are now recovered. We will log them in - // commit phase, once the entire tree has finished. - queueRecoverableErrors(hydrationErrors); - hydrationErrors = null; - } - } - - function getIsHydrating() { - return isHydrating; - } - - function queueHydrationError(error) { - if (hydrationErrors === null) { - hydrationErrors = [error]; - } else { - hydrationErrors.push(error); - } - } - - var didWarnAboutMaps; - var didWarnAboutGenerators; - var didWarnAboutStringRefs; - var ownerHasKeyUseWarning; - var ownerHasFunctionTypeWarning; - - var warnForMissingKey = function (child, returnFiber) {}; - - { - didWarnAboutMaps = false; - didWarnAboutGenerators = false; - didWarnAboutStringRefs = {}; - /** - * Warn if there's no key explicitly set on dynamic arrays of children or - * object keys are not valid. This allows us to keep track of children between - * updates. - */ - - ownerHasKeyUseWarning = {}; - ownerHasFunctionTypeWarning = {}; - - warnForMissingKey = function (child, returnFiber) { - if (child === null || typeof child !== 'object') { - return; - } - - if (!child._store || child._store.validated || child.key != null) { - return; - } - - if (typeof child._store !== 'object') { - throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - } - - child._store.validated = true; - var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; - - if (ownerHasKeyUseWarning[componentName]) { - return; - } - - ownerHasKeyUseWarning[componentName] = true; - - error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.'); - }; - } - - function coerceRef(returnFiber, current, element) { - var mixedRef = element.ref; - - if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') { - { - // TODO: Clean this up once we turn on the string ref warning for - // everyone, because the strict mode case will no longer be relevant - if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs - // because these cannot be automatically converted to an arrow function - // using a codemod. Therefore, we don't have to warn about string refs again. - !(element._owner && element._self && element._owner.stateNode !== element._self)) { - var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; - - if (!didWarnAboutStringRefs[componentName]) { - { - error('A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', mixedRef); - } - - didWarnAboutStringRefs[componentName] = true; - } - } - } - - if (element._owner) { - var owner = element._owner; - var inst; - - if (owner) { - var ownerFiber = owner; - - if (ownerFiber.tag !== ClassComponent) { - throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref'); - } - - inst = ownerFiber.stateNode; - } - - if (!inst) { - throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.'); - } // Assigning this to a const so Flow knows it won't change in the closure - - - var resolvedInst = inst; - - { - checkPropStringCoercion(mixedRef, 'ref'); - } - - var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref - - if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) { - return current.ref; - } - - var ref = function (value) { - var refs = resolvedInst.refs; - - if (refs === emptyRefsObject) { - // This is a lazy pooled frozen object, so we need to initialize. - refs = resolvedInst.refs = {}; - } - - if (value === null) { - delete refs[stringRef]; - } else { - refs[stringRef] = value; - } - }; - - ref._stringRef = stringRef; - return ref; - } else { - if (typeof mixedRef !== 'string') { - throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.'); - } - - if (!element._owner) { - throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.'); - } - } - } - - return mixedRef; - } - - function throwOnInvalidObjectType(returnFiber, newChild) { - var childString = Object.prototype.toString.call(newChild); - throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); - } - - function warnOnFunctionType(returnFiber) { - { - var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; - - if (ownerHasFunctionTypeWarning[componentName]) { - return; - } - - ownerHasFunctionTypeWarning[componentName] = true; - - error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.'); - } - } - - function resolveLazy(lazyType) { - var payload = lazyType._payload; - var init = lazyType._init; - return init(payload); - } // This wrapper function exists because I expect to clone the code in each path - // to be able to optimize each path individually by branching early. This needs - // a compiler or we can do it manually. Helpers that don't need this branching - // live outside of this function. - - - function ChildReconciler(shouldTrackSideEffects) { - function deleteChild(returnFiber, childToDelete) { - if (!shouldTrackSideEffects) { - // Noop. - return; - } - - var deletions = returnFiber.deletions; - - if (deletions === null) { - returnFiber.deletions = [childToDelete]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(childToDelete); - } - } - - function deleteRemainingChildren(returnFiber, currentFirstChild) { - if (!shouldTrackSideEffects) { - // Noop. - return null; - } // TODO: For the shouldClone case, this could be micro-optimized a bit by - // assuming that after the first child we've already added everything. - - - var childToDelete = currentFirstChild; - - while (childToDelete !== null) { - deleteChild(returnFiber, childToDelete); - childToDelete = childToDelete.sibling; - } - - return null; - } - - function mapRemainingChildren(returnFiber, currentFirstChild) { - // Add the remaining children to a temporary map so that we can find them by - // keys quickly. Implicit (null) keys get added to this set with their index - // instead. - var existingChildren = new Map(); - var existingChild = currentFirstChild; - - while (existingChild !== null) { - if (existingChild.key !== null) { - existingChildren.set(existingChild.key, existingChild); - } else { - existingChildren.set(existingChild.index, existingChild); - } - - existingChild = existingChild.sibling; - } - - return existingChildren; - } - - function useFiber(fiber, pendingProps) { - // We currently set sibling to null and index to 0 here because it is easy - // to forget to do before returning it. E.g. for the single child case. - var clone = createWorkInProgress(fiber, pendingProps); - clone.index = 0; - clone.sibling = null; - return clone; - } - - function placeChild(newFiber, lastPlacedIndex, newIndex) { - newFiber.index = newIndex; - - if (!shouldTrackSideEffects) { - // During hydration, the useId algorithm needs to know which fibers are - // part of a list of children (arrays, iterators). - newFiber.flags |= Forked; - return lastPlacedIndex; - } - - var current = newFiber.alternate; - - if (current !== null) { - var oldIndex = current.index; - - if (oldIndex < lastPlacedIndex) { - // This is a move. - newFiber.flags |= Placement; - return lastPlacedIndex; - } else { - // This item can stay in place. - return oldIndex; - } - } else { - // This is an insertion. - newFiber.flags |= Placement; - return lastPlacedIndex; - } - } - - function placeSingleChild(newFiber) { - // This is simpler for the single child case. We only need to do a - // placement for inserting new children. - if (shouldTrackSideEffects && newFiber.alternate === null) { - newFiber.flags |= Placement; - } - - return newFiber; - } - - function updateTextNode(returnFiber, current, textContent, lanes) { - if (current === null || current.tag !== HostText) { - // Insert - var created = createFiberFromText(textContent, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } else { - // Update - var existing = useFiber(current, textContent); - existing.return = returnFiber; - return existing; - } - } - - function updateElement(returnFiber, current, element, lanes) { - var elementType = element.type; - - if (elementType === REACT_FRAGMENT_TYPE) { - return updateFragment(returnFiber, current, element.props.children, lanes, element.key); - } - - if (current !== null) { - if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path: - isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type. - // We need to do this after the Hot Reloading check above, - // because hot reloading has different semantics than prod because - // it doesn't resuspend. So we can't let the call below suspend. - typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) { - // Move based on index - var existing = useFiber(current, element.props); - existing.ref = coerceRef(returnFiber, current, element); - existing.return = returnFiber; - - { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - - return existing; - } - } // Insert - - - var created = createFiberFromElement(element, returnFiber.mode, lanes); - created.ref = coerceRef(returnFiber, current, element); - created.return = returnFiber; - return created; - } - - function updatePortal(returnFiber, current, portal, lanes) { - if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) { - // Insert - var created = createFiberFromPortal(portal, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } else { - // Update - var existing = useFiber(current, portal.children || []); - existing.return = returnFiber; - return existing; - } - } - - function updateFragment(returnFiber, current, fragment, lanes, key) { - if (current === null || current.tag !== Fragment) { - // Insert - var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key); - created.return = returnFiber; - return created; - } else { - // Update - var existing = useFiber(current, fragment); - existing.return = returnFiber; - return existing; - } - } - - function createChild(returnFiber, newChild, lanes) { - if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { - // Text nodes don't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - var created = createFiberFromText('' + newChild, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - { - var _created = createFiberFromElement(newChild, returnFiber.mode, lanes); - - _created.ref = coerceRef(returnFiber, null, newChild); - _created.return = returnFiber; - return _created; - } - - case REACT_PORTAL_TYPE: - { - var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes); - - _created2.return = returnFiber; - return _created2; - } - - case REACT_LAZY_TYPE: - { - { - var payload = newChild._payload; - var init = newChild._init; - return createChild(returnFiber, init(payload), lanes); - } - } - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null); - - _created3.return = returnFiber; - return _created3; - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - return null; - } - - function updateSlot(returnFiber, oldFiber, newChild, lanes) { - // Update the fiber if the keys match, otherwise return null. - var key = oldFiber !== null ? oldFiber.key : null; - - if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { - // Text nodes don't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - if (key !== null) { - return null; - } - - return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - { - if (newChild.key === key) { - return updateElement(returnFiber, oldFiber, newChild, lanes); - } else { - return null; - } - } - - case REACT_PORTAL_TYPE: - { - if (newChild.key === key) { - return updatePortal(returnFiber, oldFiber, newChild, lanes); - } else { - return null; - } - } - - case REACT_LAZY_TYPE: - { - { - var payload = newChild._payload; - var init = newChild._init; - return updateSlot(returnFiber, oldFiber, init(payload), lanes); - } - } - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - if (key !== null) { - return null; - } - - return updateFragment(returnFiber, oldFiber, newChild, lanes, null); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - return null; - } - - function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) { - if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { - // Text nodes don't have keys, so we neither have to check the old nor - // new node for the key. If both are text nodes, they match. - var matchedFiber = existingChildren.get(newIdx) || null; - return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - { - var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; - - return updateElement(returnFiber, _matchedFiber, newChild, lanes); - } - - case REACT_PORTAL_TYPE: - { - var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; - - return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); - } - - case REACT_LAZY_TYPE: - { - var payload = newChild._payload; - var init = newChild._init; - return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes); - } - - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - var _matchedFiber3 = existingChildren.get(newIdx) || null; - - return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - return null; - } - /** - * Warns if there is a duplicate or missing key - */ - - - function warnOnInvalidKey(child, knownKeys, returnFiber) { - { - if (typeof child !== 'object' || child === null) { - return knownKeys; - } - - switch (child.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - warnForMissingKey(child, returnFiber); - var key = child.key; - - if (typeof key !== 'string') { - break; - } - - if (knownKeys === null) { - knownKeys = new Set(); - knownKeys.add(key); - break; - } - - if (!knownKeys.has(key)) { - knownKeys.add(key); - break; - } - - error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key); - - break; - - case REACT_LAZY_TYPE: - { - var payload = child._payload; - var init = child._init; - warnOnInvalidKey(init(payload), knownKeys, returnFiber); - break; - } - } - } - - return knownKeys; - } - - function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) { - // This algorithm can't optimize by searching from both ends since we - // don't have backpointers on fibers. I'm trying to see how far we can get - // with that model. If it ends up not being worth the tradeoffs, we can - // add it later. - // Even with a two ended optimization, we'd want to optimize for the case - // where there are few changes and brute force the comparison instead of - // going for the Map. It'd like to explore hitting that path first in - // forward-only mode and only go for the Map once we notice that we need - // lots of look ahead. This doesn't handle reversal as well as two ended - // search but that's unusual. Besides, for the two ended optimization to - // work on Iterables, we'd need to copy the whole set. - // In this first iteration, we'll just live with hitting the bad case - // (adding everything to a Map) in for every insert/move. - // If you change this code, also update reconcileChildrenIterator() which - // uses the same algorithm. - { - // First, validate keys. - var knownKeys = null; - - for (var i = 0; i < newChildren.length; i++) { - var child = newChildren[i]; - knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); - } - } - - var resultingFirstChild = null; - var previousNewFiber = null; - var oldFiber = currentFirstChild; - var lastPlacedIndex = 0; - var newIdx = 0; - var nextOldFiber = null; - - for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - - var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes); - - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - - break; - } - - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (newIdx === newChildren.length) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - - if (getIsHydrating()) { - var numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; newIdx < newChildren.length; newIdx++) { - var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes); - - if (_newFiber === null) { - continue; - } - - lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = _newFiber; - } else { - previousNewFiber.sibling = _newFiber; - } - - previousNewFiber = _newFiber; - } - - if (getIsHydrating()) { - var _numberOfForks = newIdx; - pushTreeFork(returnFiber, _numberOfForks); - } - - return resultingFirstChild; - } // Add all children to a key map for quick lookups. - - - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - - for (; newIdx < newChildren.length; newIdx++) { - var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes); - - if (_newFiber2 !== null) { - if (shouldTrackSideEffects) { - if (_newFiber2.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key); - } - } - - lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - resultingFirstChild = _newFiber2; - } else { - previousNewFiber.sibling = _newFiber2; - } - - previousNewFiber = _newFiber2; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(function (child) { - return deleteChild(returnFiber, child); - }); - } - - if (getIsHydrating()) { - var _numberOfForks2 = newIdx; - pushTreeFork(returnFiber, _numberOfForks2); - } - - return resultingFirstChild; - } - - function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) { - // This is the same implementation as reconcileChildrenArray(), - // but using the iterator instead. - var iteratorFn = getIteratorFn(newChildrenIterable); - - if (typeof iteratorFn !== 'function') { - throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.'); - } - - { - // We don't support rendering Generators because it's a mutation. - // See https://github.com/facebook/react/issues/12995 - if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag - newChildrenIterable[Symbol.toStringTag] === 'Generator') { - if (!didWarnAboutGenerators) { - error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); - } - - didWarnAboutGenerators = true; - } // Warn about using Maps as children - - - if (newChildrenIterable.entries === iteratorFn) { - if (!didWarnAboutMaps) { - error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); - } - - didWarnAboutMaps = true; - } // First, validate keys. - // We'll get a different iterator later for the main pass. - - - var _newChildren = iteratorFn.call(newChildrenIterable); - - if (_newChildren) { - var knownKeys = null; - - var _step = _newChildren.next(); - - for (; !_step.done; _step = _newChildren.next()) { - var child = _step.value; - knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); - } - } - } - - var newChildren = iteratorFn.call(newChildrenIterable); - - if (newChildren == null) { - throw new Error('An iterable object provided no iterator.'); - } - - var resultingFirstChild = null; - var previousNewFiber = null; - var oldFiber = currentFirstChild; - var lastPlacedIndex = 0; - var newIdx = 0; - var nextOldFiber = null; - var step = newChildren.next(); - - for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - - var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); - - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - - break; - } - - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (step.done) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - - if (getIsHydrating()) { - var numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber3 = createChild(returnFiber, step.value, lanes); - - if (_newFiber3 === null) { - continue; - } - - lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = _newFiber3; - } else { - previousNewFiber.sibling = _newFiber3; - } - - previousNewFiber = _newFiber3; - } - - if (getIsHydrating()) { - var _numberOfForks3 = newIdx; - pushTreeFork(returnFiber, _numberOfForks3); - } - - return resultingFirstChild; - } // Add all children to a key map for quick lookups. - - - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - - for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes); - - if (_newFiber4 !== null) { - if (shouldTrackSideEffects) { - if (_newFiber4.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key); - } - } - - lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); - - if (previousNewFiber === null) { - resultingFirstChild = _newFiber4; - } else { - previousNewFiber.sibling = _newFiber4; - } - - previousNewFiber = _newFiber4; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(function (child) { - return deleteChild(returnFiber, child); - }); - } - - if (getIsHydrating()) { - var _numberOfForks4 = newIdx; - pushTreeFork(returnFiber, _numberOfForks4); - } - - return resultingFirstChild; - } - - function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) { - // There's no need to check for keys on text nodes since we don't have a - // way to define them. - if (currentFirstChild !== null && currentFirstChild.tag === HostText) { - // We already have an existing node so let's just update it and delete - // the rest. - deleteRemainingChildren(returnFiber, currentFirstChild.sibling); - var existing = useFiber(currentFirstChild, textContent); - existing.return = returnFiber; - return existing; - } // The existing first child is not a text node so we need to create one - // and delete the existing ones. - - - deleteRemainingChildren(returnFiber, currentFirstChild); - var created = createFiberFromText(textContent, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } - - function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) { - var key = element.key; - var child = currentFirstChild; - - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - var elementType = element.type; - - if (elementType === REACT_FRAGMENT_TYPE) { - if (child.tag === Fragment) { - deleteRemainingChildren(returnFiber, child.sibling); - var existing = useFiber(child, element.props.children); - existing.return = returnFiber; - - { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - - return existing; - } - } else { - if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path: - isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type. - // We need to do this after the Hot Reloading check above, - // because hot reloading has different semantics than prod because - // it doesn't resuspend. So we can't let the call below suspend. - typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) { - deleteRemainingChildren(returnFiber, child.sibling); - - var _existing = useFiber(child, element.props); - - _existing.ref = coerceRef(returnFiber, child, element); - _existing.return = returnFiber; - - { - _existing._debugSource = element._source; - _existing._debugOwner = element._owner; - } - - return _existing; - } - } // Didn't match. - - - deleteRemainingChildren(returnFiber, child); - break; - } else { - deleteChild(returnFiber, child); - } - - child = child.sibling; - } - - if (element.type === REACT_FRAGMENT_TYPE) { - var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key); - created.return = returnFiber; - return created; - } else { - var _created4 = createFiberFromElement(element, returnFiber.mode, lanes); - - _created4.ref = coerceRef(returnFiber, currentFirstChild, element); - _created4.return = returnFiber; - return _created4; - } - } - - function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) { - var key = portal.key; - var child = currentFirstChild; - - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { - deleteRemainingChildren(returnFiber, child.sibling); - var existing = useFiber(child, portal.children || []); - existing.return = returnFiber; - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - break; - } - } else { - deleteChild(returnFiber, child); - } - - child = child.sibling; - } - - var created = createFiberFromPortal(portal, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } // This API will tag the children with the side-effect of the reconciliation - // itself. They will be added to the side-effect list as we pass through the - // children and the parent. - - - function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) { - // This function is not recursive. - // If the top level item is an array, we treat it as a set of children, - // not as a fragment. Nested arrays on the other hand will be treated as - // fragment nodes. Recursion happens at the normal flow. - // Handle top level unkeyed fragments as if they were arrays. - // This leads to an ambiguity between <>{[...]} and <>.... - // We treat the ambiguous cases above the same. - var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; - - if (isUnkeyedTopLevelFragment) { - newChild = newChild.props.children; - } // Handle object types - - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes)); - - case REACT_PORTAL_TYPE: - return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes)); - - case REACT_LAZY_TYPE: - { - var payload = newChild._payload; - var init = newChild._init; // TODO: This function is supposed to be non-recursive. - - return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes); - } - - } - - if (isArray(newChild)) { - return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes); - } - - if (getIteratorFn(newChild)) { - return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { - return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes)); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } // Remaining cases are all treated as empty. - - - return deleteRemainingChildren(returnFiber, currentFirstChild); - } - - return reconcileChildFibers; - } - - var reconcileChildFibers = ChildReconciler(true); - var mountChildFibers = ChildReconciler(false); - function cloneChildFibers(current, workInProgress) { - if (current !== null && workInProgress.child !== current.child) { - throw new Error('Resuming work not yet implemented.'); - } - - if (workInProgress.child === null) { - return; - } - - var currentChild = workInProgress.child; - var newChild = createWorkInProgress(currentChild, currentChild.pendingProps); - workInProgress.child = newChild; - newChild.return = workInProgress; - - while (currentChild.sibling !== null) { - currentChild = currentChild.sibling; - newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps); - newChild.return = workInProgress; - } - - newChild.sibling = null; - } // Reset a workInProgress child set to prepare it for a second pass. - - function resetChildFibers(workInProgress, lanes) { - var child = workInProgress.child; - - while (child !== null) { - resetWorkInProgress(child, lanes); - child = child.sibling; - } - } - - var NO_CONTEXT = {}; - var contextStackCursor$1 = createCursor(NO_CONTEXT); - var contextFiberStackCursor = createCursor(NO_CONTEXT); - var rootInstanceStackCursor = createCursor(NO_CONTEXT); - - function requiredContext(c) { - if (c === NO_CONTEXT) { - throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.'); - } - - return c; - } - - function getRootHostContainer() { - var rootInstance = requiredContext(rootInstanceStackCursor.current); - return rootInstance; - } - - function pushHostContainer(fiber, nextRootInstance) { - // Push current root instance onto the stack; - // This allows us to reset root when portals are popped. - push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - - push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. - // However, we can't just call getRootHostContext() and push it because - // we'd have a different number of entries on the stack depending on - // whether getRootHostContext() throws somewhere in renderer code or not. - // So we push an empty value first. This lets us safely unwind on errors. - - push(contextStackCursor$1, NO_CONTEXT, fiber); - var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. - - pop(contextStackCursor$1, fiber); - push(contextStackCursor$1, nextRootContext, fiber); - } - - function popHostContainer(fiber) { - pop(contextStackCursor$1, fiber); - pop(contextFiberStackCursor, fiber); - pop(rootInstanceStackCursor, fiber); - } - - function getHostContext() { - var context = requiredContext(contextStackCursor$1.current); - return context; - } - - function pushHostContext(fiber) { - var rootInstance = requiredContext(rootInstanceStackCursor.current); - var context = requiredContext(contextStackCursor$1.current); - var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique. - - if (context === nextContext) { - return; - } // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - - - push(contextFiberStackCursor, fiber, fiber); - push(contextStackCursor$1, nextContext, fiber); - } - - function popHostContext(fiber) { - // Do not pop unless this Fiber provided the current context. - // pushHostContext() only pushes Fibers that provide unique contexts. - if (contextFiberStackCursor.current !== fiber) { - return; - } - - pop(contextStackCursor$1, fiber); - pop(contextFiberStackCursor, fiber); - } - - var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is - // inherited deeply down the subtree. The upper bits only affect - // this immediate suspense boundary and gets reset each new - // boundary or suspense list. - - var SubtreeSuspenseContextMask = 1; // Subtree Flags: - // InvisibleParentSuspenseContext indicates that one of our parent Suspense - // boundaries is not currently showing visible main content. - // Either because it is already showing a fallback or is not mounted at all. - // We can use this to determine if it is desirable to trigger a fallback at - // the parent. If not, then we might need to trigger undesirable boundaries - // and/or suspend the commit to avoid hiding the parent content. - - var InvisibleParentSuspenseContext = 1; // Shallow Flags: - // ForceSuspenseFallback can be used by SuspenseList to force newly added - // items into their fallback state during one of the render passes. - - var ForceSuspenseFallback = 2; - var suspenseStackCursor = createCursor(DefaultSuspenseContext); - function hasSuspenseContext(parentContext, flag) { - return (parentContext & flag) !== 0; - } - function setDefaultShallowSuspenseContext(parentContext) { - return parentContext & SubtreeSuspenseContextMask; - } - function setShallowSuspenseContext(parentContext, shallowContext) { - return parentContext & SubtreeSuspenseContextMask | shallowContext; - } - function addSubtreeSuspenseContext(parentContext, subtreeContext) { - return parentContext | subtreeContext; - } - function pushSuspenseContext(fiber, newContext) { - push(suspenseStackCursor, newContext, fiber); - } - function popSuspenseContext(fiber) { - pop(suspenseStackCursor, fiber); - } - - function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { - // If it was the primary children that just suspended, capture and render the - // fallback. Otherwise, don't capture and bubble to the next boundary. - var nextState = workInProgress.memoizedState; - - if (nextState !== null) { - if (nextState.dehydrated !== null) { - // A dehydrated boundary always captures. - return true; - } - - return false; - } - - workInProgress.memoizedProps; // Regular boundaries always capture. - - { - return true; - } // If it's a boundary we should avoid, then we prefer to bubble up to the - } - function findFirstSuspended(row) { - var node = row; - - while (node !== null) { - if (node.tag === SuspenseComponent) { - var state = node.memoizedState; - - if (state !== null) { - var dehydrated = state.dehydrated; - - if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) { - return node; - } - } - } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't - // keep track of whether it suspended or not. - node.memoizedProps.revealOrder !== undefined) { - var didSuspend = (node.flags & DidCapture) !== NoFlags; - - if (didSuspend) { - return node; - } - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === row) { - return null; - } - - while (node.sibling === null) { - if (node.return === null || node.return === row) { - return null; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - - return null; - } - - var NoFlags$1 = - /* */ - 0; // Represents whether effect should fire. - - var HasEffect = - /* */ - 1; // Represents the phase in which the effect (not the clean-up) fires. - - var Insertion = - /* */ - 2; - var Layout = - /* */ - 4; - var Passive$1 = - /* */ - 8; - - // and should be reset before starting a new render. - // This tracks which mutable sources need to be reset after a render. - - var workInProgressSources = []; - function resetWorkInProgressVersions() { - for (var i = 0; i < workInProgressSources.length; i++) { - var mutableSource = workInProgressSources[i]; - - if (isPrimaryRenderer) { - mutableSource._workInProgressVersionPrimary = null; - } else { - mutableSource._workInProgressVersionSecondary = null; - } - } - - workInProgressSources.length = 0; - } - // This ensures that the version used for server rendering matches the one - // that is eventually read during hydration. - // If they don't match there's a potential tear and a full deopt render is required. - - function registerMutableSourceForHydration(root, mutableSource) { - var getVersion = mutableSource._getVersion; - var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished. - // Retaining it forever may interfere with GC. - - if (root.mutableSourceEagerHydrationData == null) { - root.mutableSourceEagerHydrationData = [mutableSource, version]; - } else { - root.mutableSourceEagerHydrationData.push(mutableSource, version); - } - } - - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, - ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; - var didWarnAboutMismatchedHooksForComponent; - var didWarnUncachedGetSnapshot; - - { - didWarnAboutMismatchedHooksForComponent = new Set(); - } - - // These are set right before calling the component. - var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from - // the work-in-progress hook. - - var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The - // current hook list is the list that belongs to the current fiber. The - // work-in-progress hook list is a new list that will be added to the - // work-in-progress fiber. - - var currentHook = null; - var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This - // does not get reset if we do another render pass; only when we're completely - // finished evaluating this component. This is an optimization so we know - // whether we need to clear render phase updates after a throw. - - var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This - // gets reset after each attempt. - // TODO: Maybe there's some way to consolidate this with - // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`. - - var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component. - - var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during - // hydration). This counter is global, so client ids are not stable across - // render attempts. - - var globalClientIdCounter = 0; - var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook - - var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. - // The list stores the order of hooks used during the initial render (mount). - // Subsequent renders (updates) reference this list. - - var hookTypesDev = null; - var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore - // the dependencies for Hooks that need them (e.g. useEffect or useMemo). - // When true, such Hooks will always be "remounted". Only used during hot reload. - - var ignorePreviousDependencies = false; - - function mountHookTypesDev() { - { - var hookName = currentHookNameInDev; - - if (hookTypesDev === null) { - hookTypesDev = [hookName]; - } else { - hookTypesDev.push(hookName); - } - } - } - - function updateHookTypesDev() { - { - var hookName = currentHookNameInDev; - - if (hookTypesDev !== null) { - hookTypesUpdateIndexDev++; - - if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { - warnOnHookMismatchInDev(hookName); - } - } - } - } - - function checkDepsAreArrayDev(deps) { - { - if (deps !== undefined && deps !== null && !isArray(deps)) { - // Verify deps, but only on mount to avoid extra checks. - // It's unlikely their type would change as usually you define them inline. - error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps); - } - } - } - - function warnOnHookMismatchInDev(currentHookName) { - { - var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1); - - if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { - didWarnAboutMismatchedHooksForComponent.add(componentName); - - if (hookTypesDev !== null) { - var table = ''; - var secondColumnStart = 30; - - for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { - var oldHookName = hookTypesDev[i]; - var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; - var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up - // lol @ IE not supporting String#repeat - - while (row.length < secondColumnStart) { - row += ' '; - } - - row += newHookName + '\n'; - table += row; - } - - error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table); - } - } - } - } - - function throwInvalidHookError() { - throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); - } - - function areHookInputsEqual(nextDeps, prevDeps) { - { - if (ignorePreviousDependencies) { - // Only true when this component is being hot reloaded. - return false; - } - } - - if (prevDeps === null) { - { - error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); - } - - return false; - } - - { - // Don't bother comparing lengths in prod because these arrays should be - // passed inline. - if (nextDeps.length !== prevDeps.length) { - error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]"); - } - } - - for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - if (objectIs(nextDeps[i], prevDeps[i])) { - continue; - } - - return false; - } - - return true; - } - - function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) { - renderLanes = nextRenderLanes; - currentlyRenderingFiber$1 = workInProgress; - - { - hookTypesDev = current !== null ? current._debugHookTypes : null; - hookTypesUpdateIndexDev = -1; // Used for hot reloading: - - ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; - } - - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - workInProgress.lanes = NoLanes; // The following should have already been reset - // currentHook = null; - // workInProgressHook = null; - // didScheduleRenderPhaseUpdate = false; - // localIdCounter = 0; - // TODO Warn if no hooks are used at all during mount, then some are used during update. - // Currently we will identify the update render as a mount because memoizedState === null. - // This is tricky because it's valid for certain types of components (e.g. React.lazy) - // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used. - // Non-stateful hooks (e.g. context) don't get added to memoizedState, - // so memoizedState would be null during updates and mounts. - - { - if (current !== null && current.memoizedState !== null) { - ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; - } else if (hookTypesDev !== null) { - // This dispatcher handles an edge case where a component is updating, - // but no stateful hooks have been used. - // We want to match the production code behavior (which will use HooksDispatcherOnMount), - // but with the extra DEV validation to ensure hooks ordering hasn't changed. - // This dispatcher does that. - ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; - } else { - ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; - } - } - - var children = Component(props, secondArg); // Check if there was a render phase update - - if (didScheduleRenderPhaseUpdateDuringThisPass) { - // Keep rendering in a loop for as long as render phase updates continue to - // be scheduled. Use a counter to prevent infinite loops. - var numberOfReRenders = 0; - - do { - didScheduleRenderPhaseUpdateDuringThisPass = false; - localIdCounter = 0; - - if (numberOfReRenders >= RE_RENDER_LIMIT) { - throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); - } - - numberOfReRenders += 1; - - { - // Even when hot reloading, allow dependencies to stabilize - // after first render to prevent infinite render phase updates. - ignorePreviousDependencies = false; - } // Start over from the beginning of the list - - - currentHook = null; - workInProgressHook = null; - workInProgress.updateQueue = null; - - { - // Also validate hook order for cascading updates. - hookTypesUpdateIndexDev = -1; - } - - ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ; - children = Component(props, secondArg); - } while (didScheduleRenderPhaseUpdateDuringThisPass); - } // We can assume the previous dispatcher is always this one, since we set it - // at the beginning of the render phase and there's no re-entrance. - - - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - - { - workInProgress._debugHookTypes = hookTypesDev; - } // This check uses currentHook so that it works the same in DEV and prod bundles. - // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. - - - var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; - renderLanes = NoLanes; - currentlyRenderingFiber$1 = null; - currentHook = null; - workInProgressHook = null; - - { - currentHookNameInDev = null; - hookTypesDev = null; - hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last - // render. If this fires, it suggests that we incorrectly reset the static - // flags in some other part of the codebase. This has happened before, for - // example, in the SuspenseList implementation. - - if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird - // and creates false positives. To make this work in legacy mode, we'd - // need to mark fibers that commit in an incomplete state, somehow. For - // now I'll disable the warning that most of the bugs that would trigger - // it are either exclusive to concurrent mode or exist in both. - (current.mode & ConcurrentMode) !== NoMode) { - error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.'); - } - } - - didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook - // localIdCounter = 0; - - if (didRenderTooFewHooks) { - throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.'); - } - - return children; - } - function checkDidRenderIdHook() { - // This should be called immediately after every renderWithHooks call. - // Conceptually, it's part of the return value of renderWithHooks; it's only a - // separate function to avoid using an array tuple. - var didRenderIdHook = localIdCounter !== 0; - localIdCounter = 0; - return didRenderIdHook; - } - function bailoutHooks(current, workInProgress, lanes) { - workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the - // complete phase (bubbleProperties). - - if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { - workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update); - } else { - workInProgress.flags &= ~(Passive | Update); - } - - current.lanes = removeLanes(current.lanes, lanes); - } - function resetHooksAfterThrow() { - // We can assume the previous dispatcher is always this one, since we set it - // at the beginning of the render phase and there's no re-entrance. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - - if (didScheduleRenderPhaseUpdate) { - // There were render phase updates. These are only valid for this render - // phase, which we are now aborting. Remove the updates from the queues so - // they do not persist to the next render. Do not remove updates from hooks - // that weren't processed. - // - // Only reset the updates from the queue if it has a clone. If it does - // not have a clone, that means it wasn't processed, and the updates were - // scheduled before we entered the render phase. - var hook = currentlyRenderingFiber$1.memoizedState; - - while (hook !== null) { - var queue = hook.queue; - - if (queue !== null) { - queue.pending = null; - } - - hook = hook.next; - } - - didScheduleRenderPhaseUpdate = false; - } - - renderLanes = NoLanes; - currentlyRenderingFiber$1 = null; - currentHook = null; - workInProgressHook = null; - - { - hookTypesDev = null; - hookTypesUpdateIndexDev = -1; - currentHookNameInDev = null; - isUpdatingOpaqueValueInRenderPhase = false; - } - - didScheduleRenderPhaseUpdateDuringThisPass = false; - localIdCounter = 0; - } - - function mountWorkInProgressHook() { - var hook = { - memoizedState: null, - baseState: null, - baseQueue: null, - queue: null, - next: null - }; - - if (workInProgressHook === null) { - // This is the first hook in the list - currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook; - } else { - // Append to the end of the list - workInProgressHook = workInProgressHook.next = hook; - } - - return workInProgressHook; - } - - function updateWorkInProgressHook() { - // This function is used both for updates and for re-renders triggered by a - // render phase update. It assumes there is either a current hook we can - // clone, or a work-in-progress hook from a previous render pass that we can - // use as a base. When we reach the end of the base list, we must switch to - // the dispatcher used for mounts. - var nextCurrentHook; - - if (currentHook === null) { - var current = currentlyRenderingFiber$1.alternate; - - if (current !== null) { - nextCurrentHook = current.memoizedState; - } else { - nextCurrentHook = null; - } - } else { - nextCurrentHook = currentHook.next; - } - - var nextWorkInProgressHook; - - if (workInProgressHook === null) { - nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState; - } else { - nextWorkInProgressHook = workInProgressHook.next; - } - - if (nextWorkInProgressHook !== null) { - // There's already a work-in-progress. Reuse it. - workInProgressHook = nextWorkInProgressHook; - nextWorkInProgressHook = workInProgressHook.next; - currentHook = nextCurrentHook; - } else { - // Clone from the current hook. - if (nextCurrentHook === null) { - throw new Error('Rendered more hooks than during the previous render.'); - } - - currentHook = nextCurrentHook; - var newHook = { - memoizedState: currentHook.memoizedState, - baseState: currentHook.baseState, - baseQueue: currentHook.baseQueue, - queue: currentHook.queue, - next: null - }; - - if (workInProgressHook === null) { - // This is the first hook in the list. - currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook; - } else { - // Append to the end of the list. - workInProgressHook = workInProgressHook.next = newHook; - } - } - - return workInProgressHook; - } - - function createFunctionComponentUpdateQueue() { - return { - lastEffect: null, - stores: null - }; - } - - function basicStateReducer(state, action) { - // $FlowFixMe: Flow doesn't like mixed types - return typeof action === 'function' ? action(state) : action; - } - - function mountReducer(reducer, initialArg, init) { - var hook = mountWorkInProgressHook(); - var initialState; - - if (init !== undefined) { - initialState = init(initialArg); - } else { - initialState = initialArg; - } - - hook.memoizedState = hook.baseState = initialState; - var queue = { - pending: null, - interleaved: null, - lanes: NoLanes, - dispatch: null, - lastRenderedReducer: reducer, - lastRenderedState: initialState - }; - hook.queue = queue; - var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue); - return [hook.memoizedState, dispatch]; - } - - function updateReducer(reducer, initialArg, init) { - var hook = updateWorkInProgressHook(); - var queue = hook.queue; - - if (queue === null) { - throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); - } - - queue.lastRenderedReducer = reducer; - var current = currentHook; // The last rebase update that is NOT part of the base state. - - var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet. - - var pendingQueue = queue.pending; - - if (pendingQueue !== null) { - // We have new updates that haven't been processed yet. - // We'll add them to the base queue. - if (baseQueue !== null) { - // Merge the pending queue and the base queue. - var baseFirst = baseQueue.next; - var pendingFirst = pendingQueue.next; - baseQueue.next = pendingFirst; - pendingQueue.next = baseFirst; - } - - { - if (current.baseQueue !== baseQueue) { - // Internal invariant that should never happen, but feasibly could in - // the future if we implement resuming, or some form of that. - error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.'); - } - } - - current.baseQueue = baseQueue = pendingQueue; - queue.pending = null; - } - - if (baseQueue !== null) { - // We have a queue to process. - var first = baseQueue.next; - var newState = current.baseState; - var newBaseState = null; - var newBaseQueueFirst = null; - var newBaseQueueLast = null; - var update = first; - - do { - var updateLane = update.lane; - - if (!isSubsetOfLanes(renderLanes, updateLane)) { - // Priority is insufficient. Skip this update. If this is the first - // skipped update, the previous update/state is the new base - // update/state. - var clone = { - lane: updateLane, - action: update.action, - hasEagerState: update.hasEagerState, - eagerState: update.eagerState, - next: null - }; - - if (newBaseQueueLast === null) { - newBaseQueueFirst = newBaseQueueLast = clone; - newBaseState = newState; - } else { - newBaseQueueLast = newBaseQueueLast.next = clone; - } // Update the remaining priority in the queue. - // TODO: Don't need to accumulate this. Instead, we can remove - // renderLanes from the original lanes. - - - currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane); - markSkippedUpdateLanes(updateLane); - } else { - // This update does have sufficient priority. - if (newBaseQueueLast !== null) { - var _clone = { - // This update is going to be committed so we never want uncommit - // it. Using NoLane works because 0 is a subset of all bitmasks, so - // this will never be skipped by the check above. - lane: NoLane, - action: update.action, - hasEagerState: update.hasEagerState, - eagerState: update.eagerState, - next: null - }; - newBaseQueueLast = newBaseQueueLast.next = _clone; - } // Process this update. - - - if (update.hasEagerState) { - // If this update is a state update (not a reducer) and was processed eagerly, - // we can use the eagerly computed state - newState = update.eagerState; - } else { - var action = update.action; - newState = reducer(newState, action); - } - } - - update = update.next; - } while (update !== null && update !== first); - - if (newBaseQueueLast === null) { - newBaseState = newState; - } else { - newBaseQueueLast.next = newBaseQueueFirst; - } // Mark that the fiber performed work, but only if the new state is - // different from the current state. - - - if (!objectIs(newState, hook.memoizedState)) { - markWorkInProgressReceivedUpdate(); - } - - hook.memoizedState = newState; - hook.baseState = newBaseState; - hook.baseQueue = newBaseQueueLast; - queue.lastRenderedState = newState; - } // Interleaved updates are stored on a separate queue. We aren't going to - // process them during this render, but we do need to track which lanes - // are remaining. - - - var lastInterleaved = queue.interleaved; - - if (lastInterleaved !== null) { - var interleaved = lastInterleaved; - - do { - var interleavedLane = interleaved.lane; - currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane); - markSkippedUpdateLanes(interleavedLane); - interleaved = interleaved.next; - } while (interleaved !== lastInterleaved); - } else if (baseQueue === null) { - // `queue.lanes` is used for entangling transitions. We can set it back to - // zero once the queue is empty. - queue.lanes = NoLanes; - } - - var dispatch = queue.dispatch; - return [hook.memoizedState, dispatch]; - } - - function rerenderReducer(reducer, initialArg, init) { - var hook = updateWorkInProgressHook(); - var queue = hook.queue; - - if (queue === null) { - throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); - } - - queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous - // work-in-progress hook. - - var dispatch = queue.dispatch; - var lastRenderPhaseUpdate = queue.pending; - var newState = hook.memoizedState; - - if (lastRenderPhaseUpdate !== null) { - // The queue doesn't persist past this render pass. - queue.pending = null; - var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; - var update = firstRenderPhaseUpdate; - - do { - // Process this render phase update. We don't have to check the - // priority because it will always be the same as the current - // render's. - var action = update.action; - newState = reducer(newState, action); - update = update.next; - } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is - // different from the current state. - - - if (!objectIs(newState, hook.memoizedState)) { - markWorkInProgressReceivedUpdate(); - } - - hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to - // the base state unless the queue is empty. - // TODO: Not sure if this is the desired semantics, but it's what we - // do for gDSFP. I can't remember why. - - if (hook.baseQueue === null) { - hook.baseState = newState; - } - - queue.lastRenderedState = newState; - } - - return [newState, dispatch]; - } - - function mountMutableSource(source, getSnapshot, subscribe) { - { - return undefined; - } - } - - function updateMutableSource(source, getSnapshot, subscribe) { - { - return undefined; - } - } - - function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - var fiber = currentlyRenderingFiber$1; - var hook = mountWorkInProgressHook(); - var nextSnapshot; - var isHydrating = getIsHydrating(); - - if (isHydrating) { - if (getServerSnapshot === undefined) { - throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); - } - - nextSnapshot = getServerSnapshot(); - - { - if (!didWarnUncachedGetSnapshot) { - if (nextSnapshot !== getServerSnapshot()) { - error('The result of getServerSnapshot should be cached to avoid an infinite loop'); - - didWarnUncachedGetSnapshot = true; - } - } - } - } else { - nextSnapshot = getSnapshot(); - - { - if (!didWarnUncachedGetSnapshot) { - var cachedSnapshot = getSnapshot(); - - if (!objectIs(nextSnapshot, cachedSnapshot)) { - error('The result of getSnapshot should be cached to avoid an infinite loop'); - - didWarnUncachedGetSnapshot = true; - } - } - } // Unless we're rendering a blocking lane, schedule a consistency check. - // Right before committing, we will walk the tree and check if any of the - // stores were mutated. - // - // We won't do this if we're hydrating server-rendered content, because if - // the content is stale, it's already visible anyway. Instead we'll patch - // it up in a passive effect. - - - var root = getWorkInProgressRoot(); - - if (root === null) { - throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); - } - - if (!includesBlockingLane(root, renderLanes)) { - pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); - } - } // Read the current snapshot from the store on every render. This breaks the - // normal rules of React, and only works because store updates are - // always synchronous. - - - hook.memoizedState = nextSnapshot; - var inst = { - value: nextSnapshot, - getSnapshot: getSnapshot - }; - hook.queue = inst; // Schedule an effect to subscribe to the store. - - mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update - // this whenever subscribe, getSnapshot, or value changes. Because there's no - // clean-up function, and we track the deps correctly, we can call pushEffect - // directly, without storing any additional state. For the same reason, we - // don't need to set a static flag, either. - // TODO: We can move this to the passive phase once we add a pre-commit - // consistency check. See the next comment. - - fiber.flags |= Passive; - pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); - return nextSnapshot; - } - - function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - var fiber = currentlyRenderingFiber$1; - var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the - // normal rules of React, and only works because store updates are - // always synchronous. - - var nextSnapshot = getSnapshot(); - - { - if (!didWarnUncachedGetSnapshot) { - var cachedSnapshot = getSnapshot(); - - if (!objectIs(nextSnapshot, cachedSnapshot)) { - error('The result of getSnapshot should be cached to avoid an infinite loop'); - - didWarnUncachedGetSnapshot = true; - } - } - } - - var prevSnapshot = hook.memoizedState; - var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot); - - if (snapshotChanged) { - hook.memoizedState = nextSnapshot; - markWorkInProgressReceivedUpdate(); - } - - var inst = hook.queue; - updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the - // commit phase if there was an interleaved mutation. In concurrent mode - // this can happen all the time, but even in synchronous mode, an earlier - // effect may have mutated the store. - - if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by - // checking whether we scheduled a subscription effect above. - workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) { - fiber.flags |= Passive; - pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check. - // Right before committing, we will walk the tree and check if any of the - // stores were mutated. - - var root = getWorkInProgressRoot(); - - if (root === null) { - throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); - } - - if (!includesBlockingLane(root, renderLanes)) { - pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); - } - } - - return nextSnapshot; - } - - function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) { - fiber.flags |= StoreConsistency; - var check = { - getSnapshot: getSnapshot, - value: renderedSnapshot - }; - var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; - - if (componentUpdateQueue === null) { - componentUpdateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; - componentUpdateQueue.stores = [check]; - } else { - var stores = componentUpdateQueue.stores; - - if (stores === null) { - componentUpdateQueue.stores = [check]; - } else { - stores.push(check); - } - } - } - - function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) { - // These are updated in the passive phase - inst.value = nextSnapshot; - inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could - // have been in an event that fired before the passive effects, or it could - // have been in a layout effect. In that case, we would have used the old - // snapsho and getSnapshot values to bail out. We need to check one more time. - - if (checkIfSnapshotChanged(inst)) { - // Force a re-render. - forceStoreRerender(fiber); - } - } - - function subscribeToStore(fiber, inst, subscribe) { - var handleStoreChange = function () { - // The store changed. Check if the snapshot changed since the last time we - // read from the store. - if (checkIfSnapshotChanged(inst)) { - // Force a re-render. - forceStoreRerender(fiber); - } - }; // Subscribe to the store and return a clean-up function. - - - return subscribe(handleStoreChange); - } - - function checkIfSnapshotChanged(inst) { - var latestGetSnapshot = inst.getSnapshot; - var prevValue = inst.value; - - try { - var nextValue = latestGetSnapshot(); - return !objectIs(prevValue, nextValue); - } catch (error) { - return true; - } - } - - function forceStoreRerender(fiber) { - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - - function mountState(initialState) { - var hook = mountWorkInProgressHook(); - - if (typeof initialState === 'function') { - // $FlowFixMe: Flow doesn't like mixed types - initialState = initialState(); - } - - hook.memoizedState = hook.baseState = initialState; - var queue = { - pending: null, - interleaved: null, - lanes: NoLanes, - dispatch: null, - lastRenderedReducer: basicStateReducer, - lastRenderedState: initialState - }; - hook.queue = queue; - var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue); - return [hook.memoizedState, dispatch]; - } - - function updateState(initialState) { - return updateReducer(basicStateReducer); - } - - function rerenderState(initialState) { - return rerenderReducer(basicStateReducer); - } - - function pushEffect(tag, create, destroy, deps) { - var effect = { - tag: tag, - create: create, - destroy: destroy, - deps: deps, - // Circular - next: null - }; - var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; - - if (componentUpdateQueue === null) { - componentUpdateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; - componentUpdateQueue.lastEffect = effect.next = effect; - } else { - var lastEffect = componentUpdateQueue.lastEffect; - - if (lastEffect === null) { - componentUpdateQueue.lastEffect = effect.next = effect; - } else { - var firstEffect = lastEffect.next; - lastEffect.next = effect; - effect.next = firstEffect; - componentUpdateQueue.lastEffect = effect; - } - } - - return effect; - } - - function mountRef(initialValue) { - var hook = mountWorkInProgressHook(); - - { - var _ref2 = { - current: initialValue - }; - hook.memoizedState = _ref2; - return _ref2; - } - } - - function updateRef(initialValue) { - var hook = updateWorkInProgressHook(); - return hook.memoizedState; - } - - function mountEffectImpl(fiberFlags, hookFlags, create, deps) { - var hook = mountWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - currentlyRenderingFiber$1.flags |= fiberFlags; - hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps); - } - - function updateEffectImpl(fiberFlags, hookFlags, create, deps) { - var hook = updateWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - var destroy = undefined; - - if (currentHook !== null) { - var prevEffect = currentHook.memoizedState; - destroy = prevEffect.destroy; - - if (nextDeps !== null) { - var prevDeps = prevEffect.deps; - - if (areHookInputsEqual(nextDeps, prevDeps)) { - hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps); - return; - } - } - } - - currentlyRenderingFiber$1.flags |= fiberFlags; - hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps); - } - - function mountEffect(create, deps) { - if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { - return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps); - } else { - return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps); - } - } - - function updateEffect(create, deps) { - return updateEffectImpl(Passive, Passive$1, create, deps); - } - - function mountInsertionEffect(create, deps) { - return mountEffectImpl(Update, Insertion, create, deps); - } - - function updateInsertionEffect(create, deps) { - return updateEffectImpl(Update, Insertion, create, deps); - } - - function mountLayoutEffect(create, deps) { - var fiberFlags = Update; - - { - fiberFlags |= LayoutStatic; - } - - if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - - return mountEffectImpl(fiberFlags, Layout, create, deps); - } - - function updateLayoutEffect(create, deps) { - return updateEffectImpl(Update, Layout, create, deps); - } - - function imperativeHandleEffect(create, ref) { - if (typeof ref === 'function') { - var refCallback = ref; - - var _inst = create(); - - refCallback(_inst); - return function () { - refCallback(null); - }; - } else if (ref !== null && ref !== undefined) { - var refObject = ref; - - { - if (!refObject.hasOwnProperty('current')) { - error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}'); - } - } - - var _inst2 = create(); - - refObject.current = _inst2; - return function () { - refObject.current = null; - }; - } - } - - function mountImperativeHandle(ref, create, deps) { - { - if (typeof create !== 'function') { - error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); - } - } // TODO: If deps are provided, should we skip comparing the ref itself? - - - var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - var fiberFlags = Update; - - { - fiberFlags |= LayoutStatic; - } - - if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - - return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); - } - - function updateImperativeHandle(ref, create, deps) { - { - if (typeof create !== 'function') { - error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); - } - } // TODO: If deps are provided, should we skip comparing the ref itself? - - - var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); - } - - function mountDebugValue(value, formatterFn) {// This hook is normally a no-op. - // The react-debug-hooks package injects its own implementation - // so that e.g. DevTools can display custom hook values. - } - - var updateDebugValue = mountDebugValue; - - function mountCallback(callback, deps) { - var hook = mountWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - hook.memoizedState = [callback, nextDeps]; - return callback; - } - - function updateCallback(callback, deps) { - var hook = updateWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - var prevState = hook.memoizedState; - - if (prevState !== null) { - if (nextDeps !== null) { - var prevDeps = prevState[1]; - - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } - } - - hook.memoizedState = [callback, nextDeps]; - return callback; - } - - function mountMemo(nextCreate, deps) { - var hook = mountWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - var nextValue = nextCreate(); - hook.memoizedState = [nextValue, nextDeps]; - return nextValue; - } - - function updateMemo(nextCreate, deps) { - var hook = updateWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - var prevState = hook.memoizedState; - - if (prevState !== null) { - // Assume these are defined. If they're not, areHookInputsEqual will warn. - if (nextDeps !== null) { - var prevDeps = prevState[1]; - - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } - } - - var nextValue = nextCreate(); - hook.memoizedState = [nextValue, nextDeps]; - return nextValue; - } - - function mountDeferredValue(value) { - var _mountState = mountState(value), - prevValue = _mountState[0], - setValue = _mountState[1]; - - mountEffect(function () { - var prevTransition = ReactCurrentBatchConfig$1.transition; - ReactCurrentBatchConfig$1.transition = {}; - - try { - setValue(value); - } finally { - ReactCurrentBatchConfig$1.transition = prevTransition; - } - }, [value]); - return prevValue; - } - - function updateDeferredValue(value) { - var _updateState = updateState(), - prevValue = _updateState[0], - setValue = _updateState[1]; - - updateEffect(function () { - var prevTransition = ReactCurrentBatchConfig$1.transition; - ReactCurrentBatchConfig$1.transition = {}; - - try { - setValue(value); - } finally { - ReactCurrentBatchConfig$1.transition = prevTransition; - } - }, [value]); - return prevValue; - } - - function rerenderDeferredValue(value) { - var _rerenderState = rerenderState(), - prevValue = _rerenderState[0], - setValue = _rerenderState[1]; - - updateEffect(function () { - var prevTransition = ReactCurrentBatchConfig$1.transition; - ReactCurrentBatchConfig$1.transition = {}; - - try { - setValue(value); - } finally { - ReactCurrentBatchConfig$1.transition = prevTransition; - } - }, [value]); - return prevValue; - } - - function startTransition(setPending, callback, options) { - var previousPriority = getCurrentUpdatePriority(); - setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); - setPending(true); - var prevTransition = ReactCurrentBatchConfig$1.transition; - ReactCurrentBatchConfig$1.transition = {}; - var currentTransition = ReactCurrentBatchConfig$1.transition; - - { - ReactCurrentBatchConfig$1.transition._updatedFibers = new Set(); - } - - try { - setPending(false); - callback(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$1.transition = prevTransition; - - { - if (prevTransition === null && currentTransition._updatedFibers) { - var updatedFibersCount = currentTransition._updatedFibers.size; - - if (updatedFibersCount > 10) { - warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); - } - - currentTransition._updatedFibers.clear(); - } - } - } - } - - function mountTransition() { - var _mountState2 = mountState(false), - isPending = _mountState2[0], - setPending = _mountState2[1]; // The `start` method never changes. - - - var start = startTransition.bind(null, setPending); - var hook = mountWorkInProgressHook(); - hook.memoizedState = start; - return [isPending, start]; - } - - function updateTransition() { - var _updateState2 = updateState(), - isPending = _updateState2[0]; - - var hook = updateWorkInProgressHook(); - var start = hook.memoizedState; - return [isPending, start]; - } - - function rerenderTransition() { - var _rerenderState2 = rerenderState(), - isPending = _rerenderState2[0]; - - var hook = updateWorkInProgressHook(); - var start = hook.memoizedState; - return [isPending, start]; - } - - var isUpdatingOpaqueValueInRenderPhase = false; - function getIsUpdatingOpaqueValueInRenderPhaseInDEV() { - { - return isUpdatingOpaqueValueInRenderPhase; - } - } - - function mountId() { - var hook = mountWorkInProgressHook(); - var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we - // should do this in Fiber, too? Deferring this decision for now because - // there's no other place to store the prefix except for an internal field on - // the public createRoot object, which the fiber tree does not currently have - // a reference to. - - var identifierPrefix = root.identifierPrefix; - var id; - - if (getIsHydrating()) { - var treeId = getTreeId(); // Use a captial R prefix for server-generated ids. - - id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end - // that represents the position of this useId hook among all the useId - // hooks for this fiber. - - var localId = localIdCounter++; - - if (localId > 0) { - id += 'H' + localId.toString(32); - } - - id += ':'; - } else { - // Use a lowercase r prefix for client-generated ids. - var globalClientId = globalClientIdCounter++; - id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':'; - } - - hook.memoizedState = id; - return id; - } - - function updateId() { - var hook = updateWorkInProgressHook(); - var id = hook.memoizedState; - return id; - } - - function dispatchReducerAction(fiber, queue, action) { - { - if (typeof arguments[3] === 'function') { - error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); - } - } - - var lane = requestUpdateLane(fiber); - var update = { - lane: lane, - action: action, - hasEagerState: false, - eagerState: null, - next: null - }; - - if (isRenderPhaseUpdate(fiber)) { - enqueueRenderPhaseUpdate(queue, update); - } else { - enqueueUpdate$1(fiber, queue, update); - var eventTime = requestEventTime(); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitionUpdate(root, queue, lane); - } - } - - markUpdateInDevTools(fiber, lane); - } - - function dispatchSetState(fiber, queue, action) { - { - if (typeof arguments[3] === 'function') { - error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); - } - } - - var lane = requestUpdateLane(fiber); - var update = { - lane: lane, - action: action, - hasEagerState: false, - eagerState: null, - next: null - }; - - if (isRenderPhaseUpdate(fiber)) { - enqueueRenderPhaseUpdate(queue, update); - } else { - enqueueUpdate$1(fiber, queue, update); - var alternate = fiber.alternate; - - if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) { - // The queue is currently empty, which means we can eagerly compute the - // next state before entering the render phase. If the new state is the - // same as the current state, we may be able to bail out entirely. - var lastRenderedReducer = queue.lastRenderedReducer; - - if (lastRenderedReducer !== null) { - var prevDispatcher; - - { - prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - } - - try { - var currentState = queue.lastRenderedState; - var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute - // it, on the update object. If the reducer hasn't changed by the - // time we enter the render phase, then the eager state can be used - // without calling the reducer again. - - update.hasEagerState = true; - update.eagerState = eagerState; - - if (objectIs(eagerState, currentState)) { - // Fast path. We can bail out without scheduling React to re-render. - // It's still possible that we'll need to rebase this update later, - // if the component re-renders for a different reason and by that - // time the reducer has changed. - return; - } - } catch (error) {// Suppress the error. It will throw again in the render phase. - } finally { - { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - } - } - } - - var eventTime = requestEventTime(); - var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - - if (root !== null) { - entangleTransitionUpdate(root, queue, lane); - } - } - - markUpdateInDevTools(fiber, lane); - } - - function isRenderPhaseUpdate(fiber) { - var alternate = fiber.alternate; - return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1; - } - - function enqueueRenderPhaseUpdate(queue, update) { - // This is a render phase update. Stash it in a lazily-created map of - // queue -> linked list of updates. After this render pass, we'll restart - // and apply the stashed updates on top of the work-in-progress hook. - didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; - var pending = queue.pending; - - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - - queue.pending = update; - } - - function enqueueUpdate$1(fiber, queue, update, lane) { - if (isInterleavedUpdate(fiber)) { - var interleaved = queue.interleaved; - - if (interleaved === null) { - // This is the first update. Create a circular list. - update.next = update; // At the end of the current render, this queue's interleaved updates will - // be transferred to the pending queue. - - pushInterleavedQueue(queue); - } else { - update.next = interleaved.next; - interleaved.next = update; - } - - queue.interleaved = update; - } else { - var pending = queue.pending; - - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - - queue.pending = update; - } - } - - function entangleTransitionUpdate(root, queue, lane) { - if (isTransitionLane(lane)) { - var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they - // must have finished. We can remove them from the shared queue, which - // represents a superset of the actually pending lanes. In some cases we - // may entangle more than we need to, but that's OK. In fact it's worse if - // we *don't* entangle when we should. - - queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. - - var newQueueLanes = mergeLanes(queueLanes, lane); - queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if - // the lane finished since the last time we entangled it. So we need to - // entangle it again, just to be sure. - - markRootEntangled(root, newQueueLanes); - } - } - - function markUpdateInDevTools(fiber, lane, action) { - - { - markStateUpdateScheduled(fiber, lane); - } - } - - var ContextOnlyDispatcher = { - readContext: readContext, - useCallback: throwInvalidHookError, - useContext: throwInvalidHookError, - useEffect: throwInvalidHookError, - useImperativeHandle: throwInvalidHookError, - useInsertionEffect: throwInvalidHookError, - useLayoutEffect: throwInvalidHookError, - useMemo: throwInvalidHookError, - useReducer: throwInvalidHookError, - useRef: throwInvalidHookError, - useState: throwInvalidHookError, - useDebugValue: throwInvalidHookError, - useDeferredValue: throwInvalidHookError, - useTransition: throwInvalidHookError, - useMutableSource: throwInvalidHookError, - useSyncExternalStore: throwInvalidHookError, - useId: throwInvalidHookError, - unstable_isNewReconciler: enableNewReconciler - }; - - var HooksDispatcherOnMountInDEV = null; - var HooksDispatcherOnMountWithHookTypesInDEV = null; - var HooksDispatcherOnUpdateInDEV = null; - var HooksDispatcherOnRerenderInDEV = null; - var InvalidNestedHooksDispatcherOnMountInDEV = null; - var InvalidNestedHooksDispatcherOnUpdateInDEV = null; - var InvalidNestedHooksDispatcherOnRerenderInDEV = null; - - { - var warnInvalidContextAccess = function () { - error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); - }; - - var warnInvalidHookAccess = function () { - error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); - }; - - HooksDispatcherOnMountInDEV = { - readContext: function (context) { - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - mountHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - mountHookTypesDev(); - return mountRef(initialValue); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - mountHookTypesDev(); - return mountDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - mountHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - mountHookTypesDev(); - return mountTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - mountHookTypesDev(); - return mountMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - mountHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - mountHookTypesDev(); - return mountId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - HooksDispatcherOnMountWithHookTypesInDEV = { - readContext: function (context) { - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - updateHookTypesDev(); - return mountCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - updateHookTypesDev(); - return mountEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - updateHookTypesDev(); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - updateHookTypesDev(); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - updateHookTypesDev(); - return mountLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - updateHookTypesDev(); - return mountRef(initialValue); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - updateHookTypesDev(); - return mountDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - updateHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - updateHookTypesDev(); - return mountTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - updateHookTypesDev(); - return mountMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - updateHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - updateHookTypesDev(); - return mountId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - HooksDispatcherOnUpdateInDEV = { - readContext: function (context) { - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - updateHookTypesDev(); - return updateRef(); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - updateHookTypesDev(); - return updateDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - updateHookTypesDev(); - return updateTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - HooksDispatcherOnRerenderInDEV = { - readContext: function (context) { - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - - try { - return rerenderReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - updateHookTypesDev(); - return updateRef(); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - - try { - return rerenderState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - updateHookTypesDev(); - return rerenderDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - updateHookTypesDev(); - return rerenderTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - InvalidNestedHooksDispatcherOnMountInDEV = { - readContext: function (context) { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - warnInvalidHookAccess(); - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - warnInvalidHookAccess(); - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountRef(initialValue); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - warnInvalidHookAccess(); - mountHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - InvalidNestedHooksDispatcherOnUpdateInDEV = { - readContext: function (context) { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateRef(); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - - InvalidNestedHooksDispatcherOnRerenderInDEV = { - readContext: function (context) { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback: function (callback, deps) { - currentHookNameInDev = 'useCallback'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext: function (context) { - currentHookNameInDev = 'useContext'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return readContext(context); - }, - useEffect: function (create, deps) { - currentHookNameInDev = 'useEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle: function (ref, create, deps) { - currentHookNameInDev = 'useImperativeHandle'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect: function (create, deps) { - currentHookNameInDev = 'useInsertionEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect: function (create, deps) { - currentHookNameInDev = 'useLayoutEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo: function (create, deps) { - currentHookNameInDev = 'useMemo'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useReducer: function (reducer, initialArg, init) { - currentHookNameInDev = 'useReducer'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return rerenderReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useRef: function (initialValue) { - currentHookNameInDev = 'useRef'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateRef(); - }, - useState: function (initialState) { - currentHookNameInDev = 'useState'; - warnInvalidHookAccess(); - updateHookTypesDev(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - - try { - return rerenderState(initialState); - } finally { - ReactCurrentDispatcher$1.current = prevDispatcher; - } - }, - useDebugValue: function (value, formatterFn) { - currentHookNameInDev = 'useDebugValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDebugValue(); - }, - useDeferredValue: function (value) { - currentHookNameInDev = 'useDeferredValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return rerenderDeferredValue(value); - }, - useTransition: function () { - currentHookNameInDev = 'useTransition'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return rerenderTransition(); - }, - useMutableSource: function (source, getSnapshot, subscribe) { - currentHookNameInDev = 'useMutableSource'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateMutableSource(); - }, - useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { - currentHookNameInDev = 'useSyncExternalStore'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot); - }, - useId: function () { - currentHookNameInDev = 'useId'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateId(); - }, - unstable_isNewReconciler: enableNewReconciler - }; - } - - var now$2 = Scheduler.unstable_now; - var commitTime = 0; - var layoutEffectStartTime = -1; - var profilerStartTime = -1; - var passiveEffectStartTime = -1; - /** - * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect). - * - * The overall sequence is: - * 1. render - * 2. commit (and call `onRender`, `onCommit`) - * 3. check for nested updates - * 4. flush passive effects (and call `onPostCommit`) - * - * Nested updates are identified in step 3 above, - * but step 4 still applies to the work that was just committed. - * We use two flags to track nested updates then: - * one tracks whether the upcoming update is a nested update, - * and the other tracks whether the current update was a nested update. - * The first value gets synced to the second at the start of the render phase. - */ - - var currentUpdateIsNested = false; - var nestedUpdateScheduled = false; - - function isCurrentUpdateNested() { - return currentUpdateIsNested; - } - - function markNestedUpdateScheduled() { - { - nestedUpdateScheduled = true; - } - } - - function resetNestedUpdateFlag() { - { - currentUpdateIsNested = false; - nestedUpdateScheduled = false; - } - } - - function syncNestedUpdateFlag() { - { - currentUpdateIsNested = nestedUpdateScheduled; - nestedUpdateScheduled = false; - } - } - - function getCommitTime() { - return commitTime; - } - - function recordCommitTime() { - - commitTime = now$2(); - } - - function startProfilerTimer(fiber) { - - profilerStartTime = now$2(); - - if (fiber.actualStartTime < 0) { - fiber.actualStartTime = now$2(); - } - } - - function stopProfilerTimerIfRunning(fiber) { - - profilerStartTime = -1; - } - - function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { - - if (profilerStartTime >= 0) { - var elapsedTime = now$2() - profilerStartTime; - fiber.actualDuration += elapsedTime; - - if (overrideBaseTime) { - fiber.selfBaseDuration = elapsedTime; - } - - profilerStartTime = -1; - } - } - - function recordLayoutEffectDuration(fiber) { - - if (layoutEffectStartTime >= 0) { - var elapsedTime = now$2() - layoutEffectStartTime; - layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor - // Or the root (for the DevTools Profiler to read) - - var parentFiber = fiber.return; - - while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - root.effectDuration += elapsedTime; - return; - - case Profiler: - var parentStateNode = parentFiber.stateNode; - parentStateNode.effectDuration += elapsedTime; - return; - } - - parentFiber = parentFiber.return; - } - } - } - - function recordPassiveEffectDuration(fiber) { - - if (passiveEffectStartTime >= 0) { - var elapsedTime = now$2() - passiveEffectStartTime; - passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor - // Or the root (for the DevTools Profiler to read) - - var parentFiber = fiber.return; - - while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - - if (root !== null) { - root.passiveEffectDuration += elapsedTime; - } - - return; - - case Profiler: - var parentStateNode = parentFiber.stateNode; - - if (parentStateNode !== null) { - // Detached fibers have their state node cleared out. - // In this case, the return pointer is also cleared out, - // so we won't be able to report the time spent in this Profiler's subtree. - parentStateNode.passiveEffectDuration += elapsedTime; - } - - return; - } - - parentFiber = parentFiber.return; - } - } - } - - function startLayoutEffectTimer() { - - layoutEffectStartTime = now$2(); - } - - function startPassiveEffectTimer() { - - passiveEffectStartTime = now$2(); - } - - function transferActualDuration(fiber) { - // Transfer time spent rendering these children so we don't lose it - // after we rerender. This is used as a helper in special cases - // where we should count the work of multiple passes. - var child = fiber.child; - - while (child) { - fiber.actualDuration += child.actualDuration; - child = child.sibling; - } - } - - function createCapturedValue(value, source) { - // If the value is an error, call this function immediately after it is thrown - // so the stack is accurate. - return { - value: value, - source: source, - stack: getStackByFiberInDevAndProd(source) - }; - } - - // This module is forked in different environments. - // By default, return `true` to log errors to the console. - // Forks can return `false` if this isn't desirable. - function showErrorDialog(boundary, errorInfo) { - return true; - } - - function logCapturedError(boundary, errorInfo) { - try { - var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging. - // This enables renderers like ReactNative to better manage redbox behavior. - - if (logError === false) { - return; - } - - var error = errorInfo.value; - - if (true) { - var source = errorInfo.source; - var stack = errorInfo.stack; - var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling - // `preventDefault()` in window `error` handler. - // We record this information as an expando on the error. - - if (error != null && error._suppressLogging) { - if (boundary.tag === ClassComponent) { - // The error is recoverable and was silenced. - // Ignore it and don't print the stack addendum. - // This is handy for testing error boundaries without noise. - return; - } // The error is fatal. Since the silencing might have - // been accidental, we'll surface it anyway. - // However, the browser would have silenced the original error - // so we'll print it first, and then print the stack addendum. - - - console['error'](error); // Don't transform to our wrapper - // For a more detailed description of this block, see: - // https://github.com/facebook/react/pull/13384 - } - - var componentName = source ? getComponentNameFromFiber(source) : null; - var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:'; - var errorBoundaryMessage; - - if (boundary.tag === HostRoot) { - errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.'; - } else { - var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous'; - errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + "."); - } - - var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. - // We don't include the original error message and JS stack because the browser - // has already printed it. Even if the application swallows the error, it is still - // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. - - console['error'](combinedMessage); // Don't transform to our wrapper - } - } catch (e) { - // This method must not throw, or React internal state will get messed up. - // If console.error is overridden, or logCapturedError() shows a dialog that throws, - // we want to report this error outside of the normal stack as a last resort. - // https://github.com/facebook/react/issues/13188 - setTimeout(function () { - throw e; - }); - } - } - - var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map; - - function createRootErrorUpdate(fiber, errorInfo, lane) { - var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null. - - update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property - // being called "element". - - update.payload = { - element: null - }; - var error = errorInfo.value; - - update.callback = function () { - onUncaughtError(error); - logCapturedError(fiber, errorInfo); - }; - - return update; - } - - function createClassErrorUpdate(fiber, errorInfo, lane) { - var update = createUpdate(NoTimestamp, lane); - update.tag = CaptureUpdate; - var getDerivedStateFromError = fiber.type.getDerivedStateFromError; - - if (typeof getDerivedStateFromError === 'function') { - var error$1 = errorInfo.value; - - update.payload = function () { - return getDerivedStateFromError(error$1); - }; - - update.callback = function () { - { - markFailedErrorBoundaryForHotReloading(fiber); - } - - logCapturedError(fiber, errorInfo); - }; - } - - var inst = fiber.stateNode; - - if (inst !== null && typeof inst.componentDidCatch === 'function') { - update.callback = function callback() { - { - markFailedErrorBoundaryForHotReloading(fiber); - } - - logCapturedError(fiber, errorInfo); - - if (typeof getDerivedStateFromError !== 'function') { - // To preserve the preexisting retry behavior of error boundaries, - // we keep track of which ones already failed during this batch. - // This gets reset before we yield back to the browser. - // TODO: Warn in strict mode if getDerivedStateFromError is - // not defined. - markLegacyErrorBoundaryAsFailed(this); - } - - var error$1 = errorInfo.value; - var stack = errorInfo.stack; - this.componentDidCatch(error$1, { - componentStack: stack !== null ? stack : '' - }); - - { - if (typeof getDerivedStateFromError !== 'function') { - // If componentDidCatch is the only error boundary method defined, - // then it needs to call setState to recover from errors. - // If no state update is scheduled then the boundary will swallow the error. - if (!includesSomeLane(fiber.lanes, SyncLane)) { - error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown'); - } - } - } - }; - } - - return update; - } - - function attachPingListener(root, wakeable, lanes) { - // Attach a ping listener - // - // The data might resolve before we have a chance to commit the fallback. Or, - // in the case of a refresh, we'll never commit a fallback. So we need to - // attach a listener now. When it resolves ("pings"), we can decide whether to - // try rendering the tree again. - // - // Only attach a listener if one does not already exist for the lanes - // we're currently rendering (which acts like a "thread ID" here). - // - // We only need to do this in concurrent mode. Legacy Suspense always - // commits fallbacks synchronously, so there are no pings. - var pingCache = root.pingCache; - var threadIDs; - - if (pingCache === null) { - pingCache = root.pingCache = new PossiblyWeakMap$1(); - threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } else { - threadIDs = pingCache.get(wakeable); - - if (threadIDs === undefined) { - threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } - } - - if (!threadIDs.has(lanes)) { - // Memoize using the thread ID to prevent redundant listeners. - threadIDs.add(lanes); - var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes); - - { - if (isDevToolsPresent) { - // If we have pending work still, restore the original updaters - restorePendingUpdaters(root, lanes); - } - } - - wakeable.then(ping, ping); - } - } - - function attachRetryListener(suspenseBoundary, root, wakeable, lanes) { - // Retry listener - // - // If the fallback does commit, we need to attach a different type of - // listener. This one schedules an update on the Suspense boundary to turn - // the fallback state off. - // - // Stash the wakeable on the boundary fiber so we can access it in the - // commit phase. - // - // When the wakeable resolves, we'll attempt to render the boundary - // again ("retry"). - var wakeables = suspenseBoundary.updateQueue; - - if (wakeables === null) { - var updateQueue = new Set(); - updateQueue.add(wakeable); - suspenseBoundary.updateQueue = updateQueue; - } else { - wakeables.add(wakeable); - } - } - - function resetSuspendedComponent(sourceFiber, rootRenderLanes) { - // A legacy mode Suspense quirk, only relevant to hook components. - - - var tag = sourceFiber.tag; - - if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) { - var currentSource = sourceFiber.alternate; - - if (currentSource) { - sourceFiber.updateQueue = currentSource.updateQueue; - sourceFiber.memoizedState = currentSource.memoizedState; - sourceFiber.lanes = currentSource.lanes; - } else { - sourceFiber.updateQueue = null; - sourceFiber.memoizedState = null; - } - } - } - - function getNearestSuspenseBoundaryToCapture(returnFiber) { - var node = returnFiber; - - do { - if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) { - return node; - } // This boundary already captured during this render. Continue to the next - // boundary. - - - node = node.return; - } while (node !== null); - - return null; - } - - function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) { - // This marks a Suspense boundary so that when we're unwinding the stack, - // it captures the suspended "exception" and does a second (fallback) pass. - if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { - // Legacy Mode Suspense - // - // If the boundary is in legacy mode, we should *not* - // suspend the commit. Pretend as if the suspended component rendered - // null and keep rendering. When the Suspense boundary completes, - // we'll do a second pass to render the fallback. - if (suspenseBoundary === returnFiber) { - // Special case where we suspended while reconciling the children of - // a Suspense boundary's inner Offscreen wrapper fiber. This happens - // when a React.lazy component is a direct child of a - // Suspense boundary. - // - // Suspense boundaries are implemented as multiple fibers, but they - // are a single conceptual unit. The legacy mode behavior where we - // pretend the suspended fiber committed as `null` won't work, - // because in this case the "suspended" fiber is the inner - // Offscreen wrapper. - // - // Because the contents of the boundary haven't started rendering - // yet (i.e. nothing in the tree has partially rendered) we can - // switch to the regular, concurrent mode behavior: mark the - // boundary with ShouldCapture and enter the unwind phase. - suspenseBoundary.flags |= ShouldCapture; - } else { - suspenseBoundary.flags |= DidCapture; - sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete. - // But we shouldn't call any lifecycle methods or callbacks. Remove - // all lifecycle effect tags. - - sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); - - if (supportsPersistence && enablePersistentOffscreenHostContainer) { - // Another legacy Suspense quirk. In persistent mode, if this is the - // initial mount, override the props of the host container to hide - // its contents. - var currentSuspenseBoundary = suspenseBoundary.alternate; - - if (currentSuspenseBoundary === null) { - var offscreenFiber = suspenseBoundary.child; - var offscreenContainer = offscreenFiber.child; - - if (offscreenContainer !== null) { - var children = offscreenContainer.memoizedProps.children; - var containerProps = getOffscreenContainerProps('hidden', children); - offscreenContainer.pendingProps = containerProps; - offscreenContainer.memoizedProps = containerProps; - } - } - } - - if (sourceFiber.tag === ClassComponent) { - var currentSourceFiber = sourceFiber.alternate; - - if (currentSourceFiber === null) { - // This is a new mount. Change the tag so it's not mistaken for a - // completed class component. For example, we should not call - // componentWillUnmount if it is deleted. - sourceFiber.tag = IncompleteClassComponent; - } else { - // When we try rendering again, we should not reuse the current fiber, - // since it's known to be in an inconsistent state. Use a force update to - // prevent a bail out. - var update = createUpdate(NoTimestamp, SyncLane); - update.tag = ForceUpdate; - enqueueUpdate(sourceFiber, update); - } - } // The source fiber did not complete. Mark it with Sync priority to - // indicate that it still has pending work. - - - sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); - } - - return suspenseBoundary; - } // Confirmed that the boundary is in a concurrent mode tree. Continue - // with the normal suspend path. - // - // After this we'll use a set of heuristics to determine whether this - // render pass will run to completion or restart or "suspend" the commit. - // The actual logic for this is spread out in different places. - // - // This first principle is that if we're going to suspend when we complete - // a root, then we should also restart if we get an update or ping that - // might unsuspend it, and vice versa. The only reason to suspend is - // because you think you might want to restart before committing. However, - // it doesn't make sense to restart only while in the period we're suspended. - // - // Restarting too aggressively is also not good because it starves out any - // intermediate loading state. So we use heuristics to determine when. - // Suspense Heuristics - // - // If nothing threw a Promise or all the same fallbacks are already showing, - // then don't suspend/restart. - // - // If this is an initial render of a new tree of Suspense boundaries and - // those trigger a fallback, then don't suspend/restart. We want to ensure - // that we can show the initial loading state as quickly as possible. - // - // If we hit a "Delayed" case, such as when we'd switch from content back into - // a fallback, then we should always suspend/restart. Transitions apply - // to this case. If none is defined, JND is used instead. - // - // If we're already showing a fallback and it gets "retried", allowing us to show - // another level, but there's still an inner boundary that would show a fallback, - // then we suspend/restart for 500ms since the last time we showed a fallback - // anywhere in the tree. This effectively throttles progressive loading into a - // consistent train of commits. This also gives us an opportunity to restart to - // get to the completed state slightly earlier. - // - // If there's ambiguity due to batching it's resolved in preference of: - // 1) "delayed", 2) "initial render", 3) "retry". - // - // We want to ensure that a "busy" state doesn't get force committed. We want to - // ensure that new initial loading states can commit as soon as possible. - - - suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in - // the begin phase to prevent an early bailout. - - suspenseBoundary.lanes = rootRenderLanes; - return suspenseBoundary; - } - - function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) { - // The source fiber did not complete. - sourceFiber.flags |= Incomplete; - - { - if (isDevToolsPresent) { - // If we have pending work still, restore the original updaters - restorePendingUpdaters(root, rootRenderLanes); - } - } - - if (value !== null && typeof value === 'object' && typeof value.then === 'function') { - // This is a wakeable. The component suspended. - var wakeable = value; - resetSuspendedComponent(sourceFiber); - - - var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); - - if (suspenseBoundary !== null) { - suspenseBoundary.flags &= ~ForceClientRender; - markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always - // commits fallbacks synchronously, so there are no pings. - - if (suspenseBoundary.mode & ConcurrentMode) { - attachPingListener(root, wakeable, rootRenderLanes); - } - - attachRetryListener(suspenseBoundary, root, wakeable); - return; - } else { - // No boundary was found. Unless this is a sync update, this is OK. - // We can suspend and wait for more data to arrive. - if (!includesSyncLane(rootRenderLanes)) { - // This is not a sync update. Suspend. Since we're not activating a - // Suspense boundary, this will unwind all the way to the root without - // performing a second pass to render a fallback. (This is arguably how - // refresh transitions should work, too, since we're not going to commit - // the fallbacks anyway.) - // - // This case also applies to initial hydration. - attachPingListener(root, wakeable, rootRenderLanes); - renderDidSuspendDelayIfPossible(); - return; - } // This is a sync/discrete update. We treat this case like an error - // because discrete renders are expected to produce a complete tree - // synchronously to maintain consistency with external state. - - - var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path. - // The error will be caught by the nearest suspense boundary. - - value = uncaughtSuspenseError; - } - } else { - // This is a regular error, not a Suspense wakeable. - if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { - markDidSuspendWhileHydratingDEV(); - - var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by - // discarding the dehydrated content and switching to a client render. - // Instead of surfacing the error, find the nearest Suspense boundary - // and render it again without hydration. - - - if (_suspenseBoundary !== null) { - if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) { - // Set a flag to indicate that we should try rendering the normal - // children again, not the fallback. - _suspenseBoundary.flags |= ForceClientRender; - } - - markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should - // still log it so it can be fixed. - - queueHydrationError(value); - return; - } - } - } // We didn't find a boundary that could handle this type of exception. Start - // over and traverse parent path again, this time treating the exception - // as an error. - - - renderDidError(value); - value = createCapturedValue(value, sourceFiber); - var workInProgress = returnFiber; - - do { - switch (workInProgress.tag) { - case HostRoot: - { - var _errorInfo = value; - workInProgress.flags |= ShouldCapture; - var lane = pickArbitraryLane(rootRenderLanes); - workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); - var update = createRootErrorUpdate(workInProgress, _errorInfo, lane); - enqueueCapturedUpdate(workInProgress, update); - return; - } - - case ClassComponent: - // Capture and retry - var errorInfo = value; - var ctor = workInProgress.type; - var instance = workInProgress.stateNode; - - if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) { - workInProgress.flags |= ShouldCapture; - - var _lane = pickArbitraryLane(rootRenderLanes); - - workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state - - var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane); - - enqueueCapturedUpdate(workInProgress, _update); - return; - } - - break; - } - - workInProgress = workInProgress.return; - } while (workInProgress !== null); - } - - function getSuspendedCache() { - { - return null; - } // This function is called when a Suspense boundary suspends. It returns the - } - - function markUpdate(workInProgress) { - // Tag the fiber with an update effect. This turns a Placement into - // a PlacementAndUpdate. - workInProgress.flags |= Update; - } - - function markRef(workInProgress) { - workInProgress.flags |= Ref; - - { - workInProgress.flags |= RefStatic; - } - } - - function hadNoMutationsEffects(current, completedWork) { - var didBailout = current !== null && current.child === completedWork.child; - - if (didBailout) { - return true; - } - - if ((completedWork.flags & ChildDeletion) !== NoFlags) { - return false; - } // TODO: If we move the `hadNoMutationsEffects` call after `bubbleProperties` - // then we only have to check the `completedWork.subtreeFlags`. - - - var child = completedWork.child; - - while (child !== null) { - if ((child.flags & MutationMask) !== NoFlags || (child.subtreeFlags & MutationMask) !== NoFlags) { - return false; - } - - child = child.sibling; - } - - return true; - } - - var appendAllChildren; - var updateHostContainer; - var updateHostComponent; - var updateHostText; - - if (supportsMutation) { - // Mutation mode - appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - var node = workInProgress.child; - - while (node !== null) { - if (node.tag === HostComponent || node.tag === HostText) { - appendInitialChild(parent, node.stateNode); - } else if (node.tag === HostPortal) ; else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === workInProgress) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - }; - - updateHostContainer = function (current, workInProgress) {// Noop - }; - - updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) { - // If we have an alternate, that means this is an update and we need to - // schedule a side-effect to do the updates. - var oldProps = current.memoizedProps; - - if (oldProps === newProps) { - // In mutation mode, this is sufficient for a bailout because - // we won't touch this node even if children changed. - return; - } // If we get updated because one of our children updated, we don't - // have newProps so we'll have to reuse them. - // TODO: Split the update API as separate for the props vs. children. - // Even better would be if children weren't special cased at all tho. - - - var instance = workInProgress.stateNode; - var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host - // component is hitting the resume path. Figure out why. Possibly - // related to `hidden`. - - var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component. - - workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there - // is a new ref we mark this as an update. All the work is done in commitWork. - - if (updatePayload) { - markUpdate(workInProgress); - } - }; - - updateHostText = function (current, workInProgress, oldText, newText) { - // If the text differs, mark it as an update. All the work in done in commitWork. - if (oldText !== newText) { - markUpdate(workInProgress); - } - }; - } else if (supportsPersistence) { - // Persistent host tree mode - appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - var node = workInProgress.child; - - while (node !== null) { - // eslint-disable-next-line no-labels - if (node.tag === HostComponent) { - var instance = node.stateNode; - - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - var props = node.memoizedProps; - var type = node.type; - instance = cloneHiddenInstance(instance, type, props, node); - } - - appendInitialChild(parent, instance); - } else if (node.tag === HostText) { - var _instance = node.stateNode; - - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - var text = node.memoizedProps; - _instance = cloneHiddenTextInstance(_instance, text, node); - } - - appendInitialChild(parent, _instance); - } else if (node.tag === HostPortal) ; else if (node.tag === OffscreenComponent && node.memoizedState !== null) { - // The children in this boundary are hidden. Toggle their visibility - // before appending. - var child = node.child; - - if (child !== null) { - child.return = node; - } - - { - appendAllChildren(parent, node, true, true); - } - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } // $FlowFixMe This is correct but Flow is confused by the labeled break. - - - node = node; - - if (node === workInProgress) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - }; // An unfortunate fork of appendAllChildren because we have two different parent types. - - - var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - var node = workInProgress.child; - - while (node !== null) { - // eslint-disable-next-line no-labels - if (node.tag === HostComponent) { - var instance = node.stateNode; - - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - var props = node.memoizedProps; - var type = node.type; - instance = cloneHiddenInstance(instance, type, props, node); - } - - appendChildToContainerChildSet(containerChildSet, instance); - } else if (node.tag === HostText) { - var _instance2 = node.stateNode; - - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - var text = node.memoizedProps; - _instance2 = cloneHiddenTextInstance(_instance2, text, node); - } - - appendChildToContainerChildSet(containerChildSet, _instance2); - } else if (node.tag === HostPortal) ; else if (node.tag === OffscreenComponent && node.memoizedState !== null) { - // The children in this boundary are hidden. Toggle their visibility - // before appending. - var child = node.child; - - if (child !== null) { - child.return = node; - } - - { - appendAllChildrenToContainer(containerChildSet, node, true, true); - } - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } // $FlowFixMe This is correct but Flow is confused by the labeled break. - - - node = node; - - if (node === workInProgress) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - }; - - updateHostContainer = function (current, workInProgress) { - var portalOrRoot = workInProgress.stateNode; - var childrenUnchanged = hadNoMutationsEffects(current, workInProgress); - - if (childrenUnchanged) ; else { - var container = portalOrRoot.containerInfo; - var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set. - - appendAllChildrenToContainer(newChildSet, workInProgress, false, false); - portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container. - - markUpdate(workInProgress); - finalizeContainerChildren(container, newChildSet); - } - }; - - updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) { - var currentInstance = current.stateNode; - var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates. - // This guarantees that we can reuse all of them. - - var childrenUnchanged = hadNoMutationsEffects(current, workInProgress); - - if (childrenUnchanged && oldProps === newProps) { - // No changes, just reuse the existing instance. - // Note that this might release a previous clone. - workInProgress.stateNode = currentInstance; - return; - } - - var recyclableInstance = workInProgress.stateNode; - var currentHostContext = getHostContext(); - var updatePayload = null; - - if (oldProps !== newProps) { - updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext); - } - - if (childrenUnchanged && updatePayload === null) { - // No changes, just reuse the existing instance. - // Note that this might release a previous clone. - workInProgress.stateNode = currentInstance; - return; - } - - var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance); - - if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) { - markUpdate(workInProgress); - } - - workInProgress.stateNode = newInstance; - - if (childrenUnchanged) { - // If there are no other effects in this tree, we need to flag this node as having one. - // Even though we're not going to use it for anything. - // Otherwise parents won't know that there are new children to propagate upwards. - markUpdate(workInProgress); - } else { - // If children might have changed, we have to add them all to the set. - appendAllChildren(newInstance, workInProgress, false, false); - } - }; - - updateHostText = function (current, workInProgress, oldText, newText) { - if (oldText !== newText) { - // If the text content differs, we'll create a new text instance for it. - var rootContainerInstance = getRootHostContainer(); - var currentHostContext = getHostContext(); - workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress); // We'll have to mark it as having an effect, even though we won't use the effect for anything. - // This lets the parents know that at least one of their children has changed. - - markUpdate(workInProgress); - } else { - workInProgress.stateNode = current.stateNode; - } - }; - } else { - // No host operations - updateHostContainer = function (current, workInProgress) {// Noop - }; - - updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) {// Noop - }; - - updateHostText = function (current, workInProgress, oldText, newText) {// Noop - }; - } - - function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { - if (getIsHydrating()) { - // If we're hydrating, we should consume as many items as we can - // so we don't leave any behind. - return; - } - - switch (renderState.tailMode) { - case 'hidden': - { - // Any insertions at the end of the tail list after this point - // should be invisible. If there are already mounted boundaries - // anything before them are not considered for collapsing. - // Therefore we need to go through the whole tail to find if - // there are any. - var tailNode = renderState.tail; - var lastTailNode = null; - - while (tailNode !== null) { - if (tailNode.alternate !== null) { - lastTailNode = tailNode; - } - - tailNode = tailNode.sibling; - } // Next we're simply going to delete all insertions after the - // last rendered item. - - - if (lastTailNode === null) { - // All remaining items in the tail are insertions. - renderState.tail = null; - } else { - // Detach the insertion after the last node that was already - // inserted. - lastTailNode.sibling = null; - } - - break; - } - - case 'collapsed': - { - // Any insertions at the end of the tail list after this point - // should be invisible. If there are already mounted boundaries - // anything before them are not considered for collapsing. - // Therefore we need to go through the whole tail to find if - // there are any. - var _tailNode = renderState.tail; - var _lastTailNode = null; - - while (_tailNode !== null) { - if (_tailNode.alternate !== null) { - _lastTailNode = _tailNode; - } - - _tailNode = _tailNode.sibling; - } // Next we're simply going to delete all insertions after the - // last rendered item. - - - if (_lastTailNode === null) { - // All remaining items in the tail are insertions. - if (!hasRenderedATailFallback && renderState.tail !== null) { - // We suspended during the head. We want to show at least one - // row at the tail. So we'll keep on and cut off the rest. - renderState.tail.sibling = null; - } else { - renderState.tail = null; - } - } else { - // Detach the insertion after the last node that was already - // inserted. - _lastTailNode.sibling = null; - } - - break; - } - } - } - - function bubbleProperties(completedWork) { - var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child; - var newChildLanes = NoLanes; - var subtreeFlags = NoFlags; - - if (!didBailout) { - // Bubble up the earliest expiration time. - if ( (completedWork.mode & ProfileMode) !== NoMode) { - // In profiling mode, resetChildExpirationTime is also used to reset - // profiler durations. - var actualDuration = completedWork.actualDuration; - var treeBaseDuration = completedWork.selfBaseDuration; - var child = completedWork.child; - - while (child !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes)); - subtreeFlags |= child.subtreeFlags; - subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will - // only be updated if work is done on the fiber (i.e. it doesn't bailout). - // When work is done, it should bubble to the parent's actualDuration. If - // the fiber has not been cloned though, (meaning no work was done), then - // this value will reflect the amount of time spent working on a previous - // render. In that case it should not bubble. We determine whether it was - // cloned by comparing the child pointer. - - actualDuration += child.actualDuration; - treeBaseDuration += child.treeBaseDuration; - child = child.sibling; - } - - completedWork.actualDuration = actualDuration; - completedWork.treeBaseDuration = treeBaseDuration; - } else { - var _child = completedWork.child; - - while (_child !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes)); - subtreeFlags |= _child.subtreeFlags; - subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code - // smell because it assumes the commit phase is never concurrent with - // the render phase. Will address during refactor to alternate model. - - _child.return = completedWork; - _child = _child.sibling; - } - } - - completedWork.subtreeFlags |= subtreeFlags; - } else { - // Bubble up the earliest expiration time. - if ( (completedWork.mode & ProfileMode) !== NoMode) { - // In profiling mode, resetChildExpirationTime is also used to reset - // profiler durations. - var _treeBaseDuration = completedWork.selfBaseDuration; - var _child2 = completedWork.child; - - while (_child2 !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, - // so we should bubble those up even during a bailout. All the other - // flags have a lifetime only of a single render + commit, so we should - // ignore them. - - subtreeFlags |= _child2.subtreeFlags & StaticMask; - subtreeFlags |= _child2.flags & StaticMask; - _treeBaseDuration += _child2.treeBaseDuration; - _child2 = _child2.sibling; - } - - completedWork.treeBaseDuration = _treeBaseDuration; - } else { - var _child3 = completedWork.child; - - while (_child3 !== null) { - newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, - // so we should bubble those up even during a bailout. All the other - // flags have a lifetime only of a single render + commit, so we should - // ignore them. - - subtreeFlags |= _child3.subtreeFlags & StaticMask; - subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code - // smell because it assumes the commit phase is never concurrent with - // the render phase. Will address during refactor to alternate model. - - _child3.return = completedWork; - _child3 = _child3.sibling; - } - } - - completedWork.subtreeFlags |= subtreeFlags; - } - - completedWork.childLanes = newChildLanes; - return didBailout; - } - - function completeWork(current, workInProgress, renderLanes) { - var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing - // to the current tree provider fiber is just as fast and less error-prone. - // Ideally we would have a special version of the work loop only - // for hydration. - - popTreeContext(workInProgress); - - switch (workInProgress.tag) { - case IndeterminateComponent: - case LazyComponent: - case SimpleMemoComponent: - case FunctionComponent: - case ForwardRef: - case Fragment: - case Mode: - case Profiler: - case ContextConsumer: - case MemoComponent: - bubbleProperties(workInProgress); - return null; - - case ClassComponent: - { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - popContext(workInProgress); - } - - bubbleProperties(workInProgress); - return null; - } - - case HostRoot: - { - var fiberRoot = workInProgress.stateNode; - - popHostContainer(workInProgress); - popTopLevelContextObject(workInProgress); - resetWorkInProgressVersions(); - - if (fiberRoot.pendingContext) { - fiberRoot.context = fiberRoot.pendingContext; - fiberRoot.pendingContext = null; - } - - if (current === null || current.child === null) { - // If we hydrated, pop so that we can delete any remaining children - // that weren't hydrated. - var wasHydrated = popHydrationState(workInProgress); - - if (wasHydrated) { - // If we hydrated, then we'll need to schedule an update for - // the commit side-effects on the root. - markUpdate(workInProgress); - } else { - if (current !== null) { - var prevState = current.memoizedState; - - if ( // Check if this is a client root - !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error) - (workInProgress.flags & ForceClientRender) !== NoFlags) { - // Schedule an effect to clear this container at the start of the - // next commit. This handles the case of React rendering into a - // container with previous children. It's also safe to do for - // updates too, because current.child would only be null if the - // previous render was null (so the container would already - // be empty). - workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been - // recoverable errors during first hydration attempt. If so, add - // them to a queue so we can log them in the commit phase. - - upgradeHydrationErrorsToRecoverable(); - } - } - } - } - - updateHostContainer(current, workInProgress); - bubbleProperties(workInProgress); - return null; - } - - case HostComponent: - { - popHostContext(workInProgress); - var rootContainerInstance = getRootHostContainer(); - var type = workInProgress.type; - - if (current !== null && workInProgress.stateNode != null) { - updateHostComponent(current, workInProgress, type, newProps, rootContainerInstance); - - if (current.ref !== workInProgress.ref) { - markRef(workInProgress); - } - } else { - if (!newProps) { - if (workInProgress.stateNode === null) { - throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); - } // This can happen when we abort work. - - - bubbleProperties(workInProgress); - return null; - } - - var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context - // "stack" as the parent. Then append children as we go in beginWork - // or completeWork depending on whether we want to add them top->down or - // bottom->up. Top->down is faster in IE11. - - var _wasHydrated = popHydrationState(workInProgress); - - if (_wasHydrated) { - // TODO: Move this and createInstance step into the beginPhase - // to consolidate. - if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) { - // If changes to the hydrated node need to be applied at the - // commit-phase we mark this as such. - markUpdate(workInProgress); - } - } else { - var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress); - appendAllChildren(instance, workInProgress, false, false); - workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount. - // (eg DOM renderer supports auto-focus for certain elements). - // Make sure such renderers get scheduled for later work. - - if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) { - markUpdate(workInProgress); - } - } - - if (workInProgress.ref !== null) { - // If there is a ref on a host node we need to schedule a callback - markRef(workInProgress); - } - } - - bubbleProperties(workInProgress); - return null; - } - - case HostText: - { - var newText = newProps; - - if (current && workInProgress.stateNode != null) { - var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need - // to schedule a side-effect to do the updates. - - updateHostText(current, workInProgress, oldText, newText); - } else { - if (typeof newText !== 'string') { - if (workInProgress.stateNode === null) { - throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); - } // This can happen when we abort work. - - } - - var _rootContainerInstance = getRootHostContainer(); - - var _currentHostContext = getHostContext(); - - var _wasHydrated2 = popHydrationState(workInProgress); - - if (_wasHydrated2) { - if (prepareToHydrateHostTextInstance(workInProgress)) { - markUpdate(workInProgress); - } - } else { - workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress); - } - } - - bubbleProperties(workInProgress); - return null; - } - - case SuspenseComponent: - { - popSuspenseContext(workInProgress); - var nextState = workInProgress.memoizedState; - - { - if ( hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) { - warnIfUnhydratedTailNodes(workInProgress); - resetHydrationState(); - workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture; - return workInProgress; - } - - if (nextState !== null && nextState.dehydrated !== null) { - // We might be inside a hydration state the first time we're picking up this - // Suspense boundary, and also after we've reentered it for further hydration. - var _wasHydrated3 = popHydrationState(workInProgress); - - if (current === null) { - if (!_wasHydrated3) { - throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.'); - } - - prepareToHydrateHostSuspenseInstance(workInProgress); - bubbleProperties(workInProgress); - - { - if ((workInProgress.mode & ProfileMode) !== NoMode) { - var isTimedOutSuspense = nextState !== null; - - if (isTimedOutSuspense) { - // Don't count time spent in a timed out Suspense subtree as part of the base duration. - var primaryChildFragment = workInProgress.child; - - if (primaryChildFragment !== null) { - // $FlowFixMe Flow doesn't support type casting in combination with the -= operator - workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration; - } - } - } - } - - return null; - } else { - // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration - // state since we're now exiting out of it. popHydrationState doesn't do that for us. - resetHydrationState(); - - if ((workInProgress.flags & DidCapture) === NoFlags) { - // This boundary did not suspend so it's now hydrated and unsuspended. - workInProgress.memoizedState = null; - } // If nothing suspended, we need to schedule an effect to mark this boundary - // as having hydrated so events know that they're free to be invoked. - // It's also a signal to replay events and the suspense callback. - // If something suspended, schedule an effect to attach retry listeners. - // So we might as well always mark this. - - - workInProgress.flags |= Update; - bubbleProperties(workInProgress); - - { - if ((workInProgress.mode & ProfileMode) !== NoMode) { - var _isTimedOutSuspense = nextState !== null; - - if (_isTimedOutSuspense) { - // Don't count time spent in a timed out Suspense subtree as part of the base duration. - var _primaryChildFragment = workInProgress.child; - - if (_primaryChildFragment !== null) { - // $FlowFixMe Flow doesn't support type casting in combination with the -= operator - workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration; - } - } - } - } - - return null; - } - } // Successfully completed this tree. If this was a forced client render, - // there may have been recoverable errors during first hydration - // attempt. If so, add them to a queue so we can log them in the - // commit phase. - - - upgradeHydrationErrorsToRecoverable(); - } - - if ((workInProgress.flags & DidCapture) !== NoFlags) { - // Something suspended. Re-render with the fallback children. - workInProgress.lanes = renderLanes; // Do not reset the effect list. - - if ( (workInProgress.mode & ProfileMode) !== NoMode) { - transferActualDuration(workInProgress); - } // Don't bubble properties in this case. - - - return workInProgress; - } - - var nextDidTimeout = nextState !== null; - var prevDidTimeout = false; - - if (current === null) { - popHydrationState(workInProgress); - } else { - var _prevState = current.memoizedState; - prevDidTimeout = _prevState !== null; - } - // an effect to toggle the subtree's visibility. When we switch from - // fallback -> primary, the inner Offscreen fiber schedules this effect - // as part of its normal complete phase. But when we switch from - // primary -> fallback, the inner Offscreen fiber does not have a complete - // phase. So we need to schedule its effect here. - // - // We also use this flag to connect/disconnect the effects, but the same - // logic applies: when re-connecting, the Offscreen fiber's complete - // phase will handle scheduling the effect. It's only when the fallback - // is active that we have to do anything special. - - - if (nextDidTimeout && !prevDidTimeout) { - var _offscreenFiber = workInProgress.child; - _offscreenFiber.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything - // in the concurrent tree already suspended during this render. - // This is a known bug. - - if ((workInProgress.mode & ConcurrentMode) !== NoMode) { - // TODO: Move this back to throwException because this is too late - // if this is a large tree which is common for initial loads. We - // don't know if we should restart a render or not until we get - // this marker, and this is too late. - // If this render already had a ping or lower pri updates, - // and this is the first time we know we're going to suspend we - // should be able to immediately restart from within throwException. - var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback); - - if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) { - // If this was in an invisible tree or a new render, then showing - // this boundary is ok. - renderDidSuspend(); - } else { - // Otherwise, we're going to have to hide content so we should - // suspend for longer if possible. - renderDidSuspendDelayIfPossible(); - } - } - } - - var wakeables = workInProgress.updateQueue; - - if (wakeables !== null) { - // Schedule an effect to attach a retry listener to the promise. - // TODO: Move to passive phase - workInProgress.flags |= Update; - } - - bubbleProperties(workInProgress); - - { - if ((workInProgress.mode & ProfileMode) !== NoMode) { - if (nextDidTimeout) { - // Don't count time spent in a timed out Suspense subtree as part of the base duration. - var _primaryChildFragment2 = workInProgress.child; - - if (_primaryChildFragment2 !== null) { - // $FlowFixMe Flow doesn't support type casting in combination with the -= operator - workInProgress.treeBaseDuration -= _primaryChildFragment2.treeBaseDuration; - } - } - } - } - - return null; - } - - case HostPortal: - popHostContainer(workInProgress); - updateHostContainer(current, workInProgress); - - if (current === null) { - preparePortalMount(workInProgress.stateNode.containerInfo); - } - - bubbleProperties(workInProgress); - return null; - - case ContextProvider: - // Pop provider fiber - var context = workInProgress.type._context; - popProvider(context, workInProgress); - bubbleProperties(workInProgress); - return null; - - case IncompleteClassComponent: - { - // Same as class component case. I put it down here so that the tags are - // sequential to ensure this switch is compiled to a jump table. - var _Component = workInProgress.type; - - if (isContextProvider(_Component)) { - popContext(workInProgress); - } - - bubbleProperties(workInProgress); - return null; - } - - case SuspenseListComponent: - { - popSuspenseContext(workInProgress); - var renderState = workInProgress.memoizedState; - - if (renderState === null) { - // We're running in the default, "independent" mode. - // We don't do anything in this mode. - bubbleProperties(workInProgress); - return null; - } - - var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags; - var renderedTail = renderState.rendering; - - if (renderedTail === null) { - // We just rendered the head. - if (!didSuspendAlready) { - // This is the first pass. We need to figure out if anything is still - // suspended in the rendered set. - // If new content unsuspended, but there's still some content that - // didn't. Then we need to do a second pass that forces everything - // to keep showing their fallbacks. - // We might be suspended if something in this render pass suspended, or - // something in the previous committed pass suspended. Otherwise, - // there's no chance so we can skip the expensive call to - // findFirstSuspended. - var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags); - - if (!cannotBeSuspended) { - var row = workInProgress.child; - - while (row !== null) { - var suspended = findFirstSuspended(row); - - if (suspended !== null) { - didSuspendAlready = true; - workInProgress.flags |= DidCapture; - cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as - // part of the second pass. In that case nothing will subscribe to - // its thenables. Instead, we'll transfer its thenables to the - // SuspenseList so that it can retry if they resolve. - // There might be multiple of these in the list but since we're - // going to wait for all of them anyway, it doesn't really matter - // which ones gets to ping. In theory we could get clever and keep - // track of how many dependencies remain but it gets tricky because - // in the meantime, we can add/remove/change items and dependencies. - // We might bail out of the loop before finding any but that - // doesn't matter since that means that the other boundaries that - // we did find already has their listeners attached. - - var newThenables = suspended.updateQueue; - - if (newThenables !== null) { - workInProgress.updateQueue = newThenables; - workInProgress.flags |= Update; - } // Rerender the whole list, but this time, we'll force fallbacks - // to stay in place. - // Reset the effect flags before doing the second pass since that's now invalid. - // Reset the child fibers to their original state. - - - workInProgress.subtreeFlags = NoFlags; - resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately - // rerender the children. - - pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case. - - return workInProgress.child; - } - - row = row.sibling; - } - } - - if (renderState.tail !== null && now$1() > getRenderTargetTime()) { - // We have already passed our CPU deadline but we still have rows - // left in the tail. We'll just give up further attempts to render - // the main content and only render fallbacks. - workInProgress.flags |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this - // to get it started back up to attempt the next item. While in terms - // of priority this work has the same priority as this current render, - // it's not part of the same transition once the transition has - // committed. If it's sync, we still want to yield so that it can be - // painted. Conceptually, this is really the same as pinging. - // We can use any RetryLane even if it's the one currently rendering - // since we're leaving it behind on this node. - - workInProgress.lanes = SomeRetryLane; - } - } else { - cutOffTailIfNeeded(renderState, false); - } // Next we're going to render the tail. - - } else { - // Append the rendered row to the child list. - if (!didSuspendAlready) { - var _suspended = findFirstSuspended(renderedTail); - - if (_suspended !== null) { - workInProgress.flags |= DidCapture; - didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't - // get lost if this row ends up dropped during a second pass. - - var _newThenables = _suspended.updateQueue; - - if (_newThenables !== null) { - workInProgress.updateQueue = _newThenables; - workInProgress.flags |= Update; - } - - cutOffTailIfNeeded(renderState, true); // This might have been modified. - - if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating. - ) { - // We're done. - bubbleProperties(workInProgress); - return null; - } - } else if ( // The time it took to render last row is greater than the remaining - // time we have to render. So rendering one more row would likely - // exceed it. - now$1() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) { - // We have now passed our CPU deadline and we'll just give up further - // attempts to render the main content and only render fallbacks. - // The assumption is that this is usually faster. - workInProgress.flags |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this - // to get it started back up to attempt the next item. While in terms - // of priority this work has the same priority as this current render, - // it's not part of the same transition once the transition has - // committed. If it's sync, we still want to yield so that it can be - // painted. Conceptually, this is really the same as pinging. - // We can use any RetryLane even if it's the one currently rendering - // since we're leaving it behind on this node. - - workInProgress.lanes = SomeRetryLane; - } - } - - if (renderState.isBackwards) { - // The effect list of the backwards tail will have been added - // to the end. This breaks the guarantee that life-cycles fire in - // sibling order but that isn't a strong guarantee promised by React. - // Especially since these might also just pop in during future commits. - // Append to the beginning of the list. - renderedTail.sibling = workInProgress.child; - workInProgress.child = renderedTail; - } else { - var previousSibling = renderState.last; - - if (previousSibling !== null) { - previousSibling.sibling = renderedTail; - } else { - workInProgress.child = renderedTail; - } - - renderState.last = renderedTail; - } - } - - if (renderState.tail !== null) { - // We still have tail rows to render. - // Pop a row. - var next = renderState.tail; - renderState.rendering = next; - renderState.tail = next.sibling; - renderState.renderingStartTime = now$1(); - next.sibling = null; // Restore the context. - // TODO: We can probably just avoid popping it instead and only - // setting it the first time we go from not suspended to suspended. - - var suspenseContext = suspenseStackCursor.current; - - if (didSuspendAlready) { - suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); - } else { - suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - } - - pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. - // Don't bubble properties in this case. - - return next; - } - - bubbleProperties(workInProgress); - return null; - } - - case ScopeComponent: - { - - break; - } - - case OffscreenComponent: - case LegacyHiddenComponent: - { - popRenderLanes(workInProgress); - var _nextState = workInProgress.memoizedState; - var nextIsHidden = _nextState !== null; - - if (current !== null) { - var _prevState2 = current.memoizedState; - var prevIsHidden = _prevState2 !== null; - - if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding — it only pre-renders. - !enableLegacyHidden )) { - workInProgress.flags |= Visibility; - } - } - - if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) { - bubbleProperties(workInProgress); - } else { - // Don't bubble properties for hidden children unless we're rendering - // at offscreen priority. - if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) { - bubbleProperties(workInProgress); - - if (supportsMutation) { - // Check if there was an insertion or update in the hidden subtree. - // If so, we need to hide those nodes in the commit phase, so - // schedule a visibility effect. - if ( workInProgress.subtreeFlags & (Placement | Update)) { - workInProgress.flags |= Visibility; - } - } - } - } - - return null; - } - - case CacheComponent: - { - - return null; - } - - case TracingMarkerComponent: - { - - return null; - } - } - - throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); - } - - var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; - var didReceiveUpdate = false; - var didWarnAboutBadClass; - var didWarnAboutModulePatternComponent; - var didWarnAboutContextTypeOnFunctionComponent; - var didWarnAboutGetDerivedStateOnFunctionComponent; - var didWarnAboutFunctionRefs; - var didWarnAboutReassigningProps; - var didWarnAboutRevealOrder; - var didWarnAboutTailOptions; - - { - didWarnAboutBadClass = {}; - didWarnAboutModulePatternComponent = {}; - didWarnAboutContextTypeOnFunctionComponent = {}; - didWarnAboutGetDerivedStateOnFunctionComponent = {}; - didWarnAboutFunctionRefs = {}; - didWarnAboutReassigningProps = false; - didWarnAboutRevealOrder = {}; - didWarnAboutTailOptions = {}; - } - - function reconcileChildren(current, workInProgress, nextChildren, renderLanes) { - if (current === null) { - // If this is a fresh new component that hasn't been rendered yet, we - // won't update its child set by applying minimal side-effects. Instead, - // we will add them all to the child before it gets rendered. That means - // we can optimize this reconciliation pass by not tracking side-effects. - workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); - } else { - // If the current child is the same as the work in progress, it means that - // we haven't yet started any work on these children. Therefore, we use - // the clone algorithm to create a copy of all the current children. - // If we had any progressed work already, that is invalid at this point so - // let's throw it out. - workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes); - } - } - - function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) { - // This function is fork of reconcileChildren. It's used in cases where we - // want to reconcile without matching against the existing set. This has the - // effect of all current children being unmounted; even if the type and key - // are the same, the old child is unmounted and a new child is created. - // - // To do this, we're going to go through the reconcile algorithm twice. In - // the first pass, we schedule a deletion for all the current children by - // passing null. - workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we - // pass null in place of where we usually pass the current child set. This has - // the effect of remounting all children regardless of whether their - // identities match. - - workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); - } - - function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) { - // TODO: current can be non-null here even if the component - // hasn't yet mounted. This happens after the first render suspends. - // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes(innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(Component)); - } - } - } - - var render = Component.render; - var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent - - var nextChildren; - var hasId; - prepareToReadContext(workInProgress, renderLanes); - - { - markComponentRenderStarted(workInProgress); - } - - { - ReactCurrentOwner$1.current = workInProgress; - setIsRendering(true); - nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); - hasId = checkDidRenderIdHook(); - - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); - hasId = checkDidRenderIdHook(); - } finally { - setIsStrictModeForDevtools(false); - } - } - - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } - - if (current !== null && !didReceiveUpdate) { - bailoutHooks(current, workInProgress, renderLanes); - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { - if (current === null) { - var type = Component.type; - - if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. - Component.defaultProps === undefined) { - var resolvedType = type; - - { - resolvedType = resolveFunctionForHotReloading(type); - } // If this is a plain function component without default props, - // and with only the default shallow comparison, we upgrade it - // to a SimpleMemoComponent to allow fast path updates. - - - workInProgress.tag = SimpleMemoComponent; - workInProgress.type = resolvedType; - - { - validateFunctionComponentInDev(workInProgress, type); - } - - return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes); - } - - { - var innerPropTypes = type.propTypes; - - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes(innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(type)); - } - } - - var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes); - child.ref = workInProgress.ref; - child.return = workInProgress; - workInProgress.child = child; - return child; - } - - { - var _type = Component.type; - var _innerPropTypes = _type.propTypes; - - if (_innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes(_innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(_type)); - } - } - - var currentChild = current.child; // This is always exactly one child - - var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); - - if (!hasScheduledUpdateOrContext) { - // This will be the props with resolved defaultProps, - // unlike current.memoizedProps which will be the unresolved ones. - var prevProps = currentChild.memoizedProps; // Default to shallow comparison - - var compare = Component.compare; - compare = compare !== null ? compare : shallowEqual; - - if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) { - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - var newChild = createWorkInProgress(currentChild, nextProps); - newChild.ref = workInProgress.ref; - newChild.return = workInProgress; - workInProgress.child = newChild; - return newChild; - } - - function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { - // TODO: current can be non-null here even if the component - // hasn't yet mounted. This happens when the inner render suspends. - // We'll need to figure out if this is fine or can cause issues. - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var outerMemoType = workInProgress.elementType; - - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - var lazyComponent = outerMemoType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - outerMemoType = init(payload); - } catch (x) { - outerMemoType = null; - } // Inner propTypes will be validated in the function component path. - - - var outerPropTypes = outerMemoType && outerMemoType.propTypes; - - if (outerPropTypes) { - checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - 'prop', getComponentNameFromType(outerMemoType)); - } - } - } - } - - if (current !== null) { - var prevProps = current.memoizedProps; - - if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload. - workInProgress.type === current.type )) { - didReceiveUpdate = false; - - if (!checkScheduledUpdateOrContext(current, renderLanes)) { - // The pending lanes were cleared at the beginning of beginWork. We're - // about to bail out, but there might be other lanes that weren't - // included in the current render. Usually, the priority level of the - // remaining updates is accumulated during the evaluation of the - // component (i.e. when processing the update queue). But since since - // we're bailing out early *without* evaluating the component, we need - // to account for it here, too. Reset to the value of the current fiber. - // NOTE: This only applies to SimpleMemoComponent, not MemoComponent, - // because a MemoComponent fiber does not have hooks or an update queue; - // rather, it wraps around an inner component, which may or may not - // contains hooks. - // TODO: Move the reset at in beginWork out of the common path so that - // this is no longer necessary. - workInProgress.lanes = current.lanes; - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { - // This is a special case that only exists for legacy mode. - // See https://github.com/facebook/react/pull/19216. - didReceiveUpdate = true; - } - } - } - - return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes); - } - - function updateOffscreenComponent(current, workInProgress, renderLanes) { - var nextProps = workInProgress.pendingProps; - var nextChildren = nextProps.children; - var prevState = current !== null ? current.memoizedState : null; - - if (nextProps.mode === 'hidden' || enableLegacyHidden ) { - // Rendering a hidden tree. - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - // In legacy sync mode, don't defer the subtree. Render it now. - var nextState = { - baseLanes: NoLanes, - cachePool: null - }; - workInProgress.memoizedState = nextState; - - pushRenderLanes(workInProgress, renderLanes); - } else if (!includesSomeLane(renderLanes, OffscreenLane)) { - var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out - // and resume this tree later. - - var nextBaseLanes; - - if (prevState !== null) { - var prevBaseLanes = prevState.baseLanes; - nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes); - } else { - nextBaseLanes = renderLanes; - } // Schedule this fiber to re-render at offscreen priority. Then bailout. - - - workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane); - var _nextState = { - baseLanes: nextBaseLanes, - cachePool: spawnedCachePool - }; - workInProgress.memoizedState = _nextState; - workInProgress.updateQueue = null; - // to avoid a push/pop misalignment. - - - pushRenderLanes(workInProgress, nextBaseLanes); - - return null; - } else { - // This is the second render. The surrounding visible content has already - // committed. Now we resume rendering the hidden tree. - // Rendering at offscreen, so we can clear the base lanes. - var _nextState2 = { - baseLanes: NoLanes, - cachePool: null - }; - workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out. - - var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes; - - pushRenderLanes(workInProgress, subtreeRenderLanes); - } - } else { - // Rendering a visible tree. - var _subtreeRenderLanes; - - if (prevState !== null) { - // We're going from hidden -> visible. - _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes); - - - workInProgress.memoizedState = null; - } else { - // We weren't previously hidden, and we still aren't, so there's nothing - // special to do. Need to push to the stack regardless, though, to avoid - // a push/pop misalignment. - _subtreeRenderLanes = renderLanes; - } - - pushRenderLanes(workInProgress, _subtreeRenderLanes); - } - - { - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - } - - function updateFragment(current, workInProgress, renderLanes) { - var nextChildren = workInProgress.pendingProps; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateMode(current, workInProgress, renderLanes) { - var nextChildren = workInProgress.pendingProps.children; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateProfiler(current, workInProgress, renderLanes) { - { - workInProgress.flags |= Update; - - { - // Reset effect durations for the next eventual effect phase. - // These are reset during render to allow the DevTools commit hook a chance to read them, - var stateNode = workInProgress.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - } - - var nextProps = workInProgress.pendingProps; - var nextChildren = nextProps.children; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function markRef$1(current, workInProgress) { - var ref = workInProgress.ref; - - if (current === null && ref !== null || current !== null && current.ref !== ref) { - // Schedule a Ref effect - workInProgress.flags |= Ref; - - { - workInProgress.flags |= RefStatic; - } - } - } - - function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) { - { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes(innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(Component)); - } - } - } - - var context; - - { - var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); - context = getMaskedContext(workInProgress, unmaskedContext); - } - - var nextChildren; - var hasId; - prepareToReadContext(workInProgress, renderLanes); - - { - markComponentRenderStarted(workInProgress); - } - - { - ReactCurrentOwner$1.current = workInProgress; - setIsRendering(true); - nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); - hasId = checkDidRenderIdHook(); - - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); - hasId = checkDidRenderIdHook(); - } finally { - setIsStrictModeForDevtools(false); - } - } - - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } - - if (current !== null && !didReceiveUpdate) { - bailoutHooks(current, workInProgress, renderLanes); - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) { - { - // This is used by DevTools to force a boundary to error. - switch (shouldError(workInProgress)) { - case false: - { - var _instance = workInProgress.stateNode; - var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack. - // Is there a better way to do this? - - var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context); - var state = tempInstance.state; - - _instance.updater.enqueueSetState(_instance, state, null); - - break; - } - - case true: - { - workInProgress.flags |= DidCapture; - workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes - - var error$1 = new Error('Simulated error coming from DevTools'); - var lane = pickArbitraryLane(renderLanes); - workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state - - var update = createClassErrorUpdate(workInProgress, createCapturedValue(error$1, workInProgress), lane); - enqueueCapturedUpdate(workInProgress, update); - break; - } - } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - var innerPropTypes = Component.propTypes; - - if (innerPropTypes) { - checkPropTypes(innerPropTypes, nextProps, // Resolved props - 'prop', getComponentNameFromType(Component)); - } - } - } // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - - - var hasContext; - - if (isContextProvider(Component)) { - hasContext = true; - pushContextProvider(workInProgress); - } else { - hasContext = false; - } - - prepareToReadContext(workInProgress, renderLanes); - var instance = workInProgress.stateNode; - var shouldUpdate; - - if (instance === null) { - if (current !== null) { - // A class component without an instance only mounts if it suspended - // inside a non-concurrent tree, in an inconsistent state. We want to - // treat it like a new mount, even though an empty version of it already - // committed. Disconnect the alternate pointers. - current.alternate = null; - workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - - workInProgress.flags |= Placement; - } // In the initial pass we might need to construct the instance. - - - constructClassInstance(workInProgress, Component, nextProps); - mountClassInstance(workInProgress, Component, nextProps, renderLanes); - shouldUpdate = true; - } else if (current === null) { - // In a resume, we'll already have an instance we can reuse. - shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes); - } else { - shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes); - } - - var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes); - - { - var inst = workInProgress.stateNode; - - if (shouldUpdate && inst.props !== nextProps) { - if (!didWarnAboutReassigningProps) { - error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component'); - } - - didWarnAboutReassigningProps = true; - } - } - - return nextUnitOfWork; - } - - function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) { - // Refs should update even if shouldComponentUpdate returns false - markRef$1(current, workInProgress); - var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags; - - if (!shouldUpdate && !didCaptureError) { - // Context providers should defer to sCU for rendering - if (hasContext) { - invalidateContextProvider(workInProgress, Component, false); - } - - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - var instance = workInProgress.stateNode; // Rerender - - ReactCurrentOwner$1.current = workInProgress; - var nextChildren; - - if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') { - // If we captured an error, but getDerivedStateFromError is not defined, - // unmount all the children. componentDidCatch will schedule an update to - // re-render a fallback. This is temporary until we migrate everyone to - // the new API. - // TODO: Warn in a future release. - nextChildren = null; - - { - stopProfilerTimerIfRunning(); - } - } else { - { - markComponentRenderStarted(workInProgress); - } - - { - setIsRendering(true); - nextChildren = instance.render(); - - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - instance.render(); - } finally { - setIsStrictModeForDevtools(false); - } - } - - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - - if (current !== null && didCaptureError) { - // If we're recovering from an error, reconcile without reusing any of - // the existing children. Conceptually, the normal children and the children - // that are shown on error are two different sets, so we shouldn't reuse - // normal children even if their identities match. - forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes); - } else { - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } // Memoize state using the values we just used to render. - // TODO: Restructure so we never read values from the instance. - - - workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. - - if (hasContext) { - invalidateContextProvider(workInProgress, Component, true); - } - - return workInProgress.child; - } - - function pushHostRootContext(workInProgress) { - var root = workInProgress.stateNode; - - if (root.pendingContext) { - pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context); - } else if (root.context) { - // Should always be set - pushTopLevelContextObject(workInProgress, root.context, false); - } - - pushHostContainer(workInProgress, root.containerInfo); - } - - function updateHostRoot(current, workInProgress, renderLanes) { - pushHostRootContext(workInProgress); - - if (current === null) { - throw new Error('Should have a current fiber. This is a bug in React.'); - } - - var nextProps = workInProgress.pendingProps; - var prevState = workInProgress.memoizedState; - var prevChildren = prevState.element; - cloneUpdateQueue(current, workInProgress); - processUpdateQueue(workInProgress, nextProps, null, renderLanes); - var nextState = workInProgress.memoizedState; - workInProgress.stateNode; - // being called "element". - - - var nextChildren = nextState.element; - - if (supportsHydration && prevState.isDehydrated) { - // This is a hydration root whose shell has not yet hydrated. We should - // attempt to hydrate. - // Flip isDehydrated to false to indicate that when this render - // finishes, the root will no longer be dehydrated. - var overrideState = { - element: nextChildren, - isDehydrated: false, - cache: nextState.cache, - transitions: nextState.transitions - }; - var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't - // have reducer functions so it doesn't need rebasing. - - updateQueue.baseState = overrideState; - workInProgress.memoizedState = overrideState; - - if (workInProgress.flags & ForceClientRender) { - // Something errored during a previous attempt to hydrate the shell, so we - // forced a client render. - var recoverableError = new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'); - return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError); - } else if (nextChildren !== prevChildren) { - var _recoverableError = new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'); - - return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError); - } else { - // The outermost shell has not hydrated yet. Start hydrating. - enterHydrationState(workInProgress); - - var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); - workInProgress.child = child; - var node = child; - - while (node) { - // Mark each child as hydrating. This is a fast path to know whether this - // tree is part of a hydrating tree. This is used to determine if a child - // node has fully mounted yet, and for scheduling event replaying. - // Conceptually this is similar to Placement in that a new subtree is - // inserted into the React tree here. It just happens to not need DOM - // mutations because it already exists. - node.flags = node.flags & ~Placement | Hydrating; - node = node.sibling; - } - } - } else { - // Root is not dehydrated. Either this is a client-only root, or it - // already hydrated. - resetHydrationState(); - - if (nextChildren === prevChildren) { - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } - - return workInProgress.child; - } - - function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) { - // Revert to client rendering. - resetHydrationState(); - queueHydrationError(recoverableError); - workInProgress.flags |= ForceClientRender; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateHostComponent$1(current, workInProgress, renderLanes) { - pushHostContext(workInProgress); - - if (current === null) { - tryToClaimNextHydratableInstance(workInProgress); - } - - var type = workInProgress.type; - var nextProps = workInProgress.pendingProps; - var prevProps = current !== null ? current.memoizedProps : null; - var nextChildren = nextProps.children; - var isDirectTextChild = shouldSetTextContent(type, nextProps); - - if (isDirectTextChild) { - // We special case a direct text child of a host node. This is a common - // case. We won't handle it as a reified child. We will instead handle - // this in the host environment that also has access to this prop. That - // avoids allocating another HostText fiber and traversing it. - nextChildren = null; - } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { - // If we're switching from a direct text child to a normal child, or to - // empty, we need to schedule the text content to be reset. - workInProgress.flags |= ContentReset; - } - - markRef$1(current, workInProgress); - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; - } - - function updateHostText$1(current, workInProgress) { - if (current === null) { - tryToClaimNextHydratableInstance(workInProgress); - } // Nothing to do here. This is terminal. We'll do the completion step - // immediately after. - - - return null; - } - - function mountLazyComponent(_current, workInProgress, elementType, renderLanes) { - if (_current !== null) { - // A lazy component only mounts if it suspended inside a non- - // concurrent tree, in an inconsistent state. We want to treat it like - // a new mount, even though an empty version of it already committed. - // Disconnect the alternate pointers. - _current.alternate = null; - workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - - workInProgress.flags |= Placement; - } - - var props = workInProgress.pendingProps; - var lazyComponent = elementType; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - var Component = init(payload); // Store the unwrapped component in the type. - - workInProgress.type = Component; - var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component); - var resolvedProps = resolveDefaultProps(Component, props); - var child; - - switch (resolvedTag) { - case FunctionComponent: - { - { - validateFunctionComponentInDev(workInProgress, Component); - workInProgress.type = Component = resolveFunctionForHotReloading(Component); - } - - child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes); - return child; - } - - case ClassComponent: - { - { - workInProgress.type = Component = resolveClassForHotReloading(Component); - } - - child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes); - return child; - } - - case ForwardRef: - { - { - workInProgress.type = Component = resolveForwardRefForHotReloading(Component); - } - - child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes); - return child; - } - - case MemoComponent: - { - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = Component.propTypes; - - if (outerPropTypes) { - checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only - 'prop', getComponentNameFromType(Component)); - } - } - } - - child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too - renderLanes); - return child; - } - } - - var hint = ''; - - { - if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) { - hint = ' Did you wrap a component in React.lazy() more than once?'; - } - } // This message intentionally doesn't mention ForwardRef or MemoComponent - // because the fact that it's a separate type of work is an - // implementation detail. - - - throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint)); - } - - function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) { - if (_current !== null) { - // An incomplete component only mounts if it suspended inside a non- - // concurrent tree, in an inconsistent state. We want to treat it like - // a new mount, even though an empty version of it already committed. - // Disconnect the alternate pointers. - _current.alternate = null; - workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - - workInProgress.flags |= Placement; - } // Promote the fiber to a class and try rendering again. - - - workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` - // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - - var hasContext; - - if (isContextProvider(Component)) { - hasContext = true; - pushContextProvider(workInProgress); - } else { - hasContext = false; - } - - prepareToReadContext(workInProgress, renderLanes); - constructClassInstance(workInProgress, Component, nextProps); - mountClassInstance(workInProgress, Component, nextProps, renderLanes); - return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); - } - - function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) { - if (_current !== null) { - // An indeterminate component only mounts if it suspended inside a non- - // concurrent tree, in an inconsistent state. We want to treat it like - // a new mount, even though an empty version of it already committed. - // Disconnect the alternate pointers. - _current.alternate = null; - workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - - workInProgress.flags |= Placement; - } - - var props = workInProgress.pendingProps; - var context; - - { - var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); - context = getMaskedContext(workInProgress, unmaskedContext); - } - - prepareToReadContext(workInProgress, renderLanes); - var value; - var hasId; - - { - markComponentRenderStarted(workInProgress); - } - - { - if (Component.prototype && typeof Component.prototype.render === 'function') { - var componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutBadClass[componentName]) { - error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); - - didWarnAboutBadClass[componentName] = true; - } - } - - if (workInProgress.mode & StrictLegacyMode) { - ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null); - } - - setIsRendering(true); - ReactCurrentOwner$1.current = workInProgress; - value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); - hasId = checkDidRenderIdHook(); - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - - { - // Support for module components is deprecated and is removed behind a flag. - // Whether or not it would crash later, we want to show a good message in DEV first. - if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { - var _componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutModulePatternComponent[_componentName]) { - error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); - - didWarnAboutModulePatternComponent[_componentName] = true; - } - } - } - - if ( // Run these checks in production only if the flag is off. - // Eventually we'll delete this branch altogether. - typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { - { - var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutModulePatternComponent[_componentName2]) { - error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); - - didWarnAboutModulePatternComponent[_componentName2] = true; - } - } // Proceed under the assumption that this is a class instance - - - workInProgress.tag = ClassComponent; // Throw out any hooks that were used. - - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - - var hasContext = false; - - if (isContextProvider(Component)) { - hasContext = true; - pushContextProvider(workInProgress); - } else { - hasContext = false; - } - - workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; - initializeUpdateQueue(workInProgress); - adoptClassInstance(workInProgress, value); - mountClassInstance(workInProgress, Component, props, renderLanes); - return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); - } else { - // Proceed under the assumption that this is a function component - workInProgress.tag = FunctionComponent; - - { - - if ( workInProgress.mode & StrictLegacyMode) { - setIsStrictModeForDevtools(true); - - try { - value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); - hasId = checkDidRenderIdHook(); - } finally { - setIsStrictModeForDevtools(false); - } - } - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } - - reconcileChildren(null, workInProgress, value, renderLanes); - - { - validateFunctionComponentInDev(workInProgress, Component); - } - - return workInProgress.child; - } - } - - function validateFunctionComponentInDev(workInProgress, Component) { - { - if (Component) { - if (Component.childContextTypes) { - error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); - } - } - - if (workInProgress.ref !== null) { - var info = ''; - var ownerName = getCurrentFiberOwnerNameInDevOrNull(); - - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - - var warningKey = ownerName || ''; - var debugSource = workInProgress._debugSource; - - if (debugSource) { - warningKey = debugSource.fileName + ':' + debugSource.lineNumber; - } - - if (!didWarnAboutFunctionRefs[warningKey]) { - didWarnAboutFunctionRefs[warningKey] = true; - - error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info); - } - } - - if (typeof Component.getDerivedStateFromProps === 'function') { - var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { - error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); - - didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; - } - } - - if (typeof Component.contextType === 'object' && Component.contextType !== null) { - var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { - error('%s: Function components do not support contextType.', _componentName4); - - didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; - } - } - } - } - - var SUSPENDED_MARKER = { - dehydrated: null, - treeContext: null, - retryLane: NoLane - }; - - function mountSuspenseOffscreenState(renderLanes) { - return { - baseLanes: renderLanes, - cachePool: getSuspendedCache() - }; - } - - function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) { - var cachePool = null; - - return { - baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes), - cachePool: cachePool - }; - } // TODO: Probably should inline this back - - - function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) { - // If we're already showing a fallback, there are cases where we need to - // remain on that fallback regardless of whether the content has resolved. - // For example, SuspenseList coordinates when nested content appears. - if (current !== null) { - var suspenseState = current.memoizedState; - - if (suspenseState === null) { - // Currently showing content. Don't hide it, even if ForceSuspenseFallback - // is true. More precise name might be "ForceRemainSuspenseFallback". - // Note: This is a factoring smell. Can't remain on a fallback if there's - // no fallback to remain on. - return false; - } - } // Not currently showing content. Consult the Suspense context. - - - return hasSuspenseContext(suspenseContext, ForceSuspenseFallback); - } - - function getRemainingWorkInPrimaryTree(current, renderLanes) { - // TODO: Should not remove render lanes that were pinged during this render - return removeLanes(current.childLanes, renderLanes); - } - - function updateSuspenseComponent(current, workInProgress, renderLanes) { - var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. - - { - if (shouldSuspend(workInProgress)) { - workInProgress.flags |= DidCapture; - } - } - - var suspenseContext = suspenseStackCursor.current; - var showFallback = false; - var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags; - - if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) { - // Something in this boundary's subtree already suspended. Switch to - // rendering the fallback children. - showFallback = true; - workInProgress.flags &= ~DidCapture; - } else { - // Attempting the main content - if (current === null || current.memoizedState !== null) { - // This is a new mount or this boundary is already showing a fallback state. - // Mark this subtree context as having at least one invisible parent that could - // handle the fallback state. - // Avoided boundaries are not considered since they cannot handle preferred fallback states. - { - suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext); - } - } - } - - suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense - // boundary's children. This involves some custom reconciliation logic. Two - // main reasons this is so complicated. - // - // First, Legacy Mode has different semantics for backwards compatibility. The - // primary tree will commit in an inconsistent state, so when we do the - // second pass to render the fallback, we do some exceedingly, uh, clever - // hacks to make that not totally break. Like transferring effects and - // deletions from hidden tree. In Concurrent Mode, it's much simpler, - // because we bailout on the primary tree completely and leave it in its old - // state, no effects. Same as what we do for Offscreen (except that - // Offscreen doesn't have the first render pass). - // - // Second is hydration. During hydration, the Suspense fiber has a slightly - // different layout, where the child points to a dehydrated fragment, which - // contains the DOM rendered by the server. - // - // Third, even if you set all that aside, Suspense is like error boundaries in - // that we first we try to render one tree, and if that fails, we render again - // and switch to a different tree. Like a try/catch block. So we have to track - // which branch we're currently rendering. Ideally we would model this using - // a stack. - - if (current === null) { - // Initial mount - // If we're currently hydrating, try to hydrate this boundary. - tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. - - { - var suspenseState = workInProgress.memoizedState; - - if (suspenseState !== null) { - var dehydrated = suspenseState.dehydrated; - - if (dehydrated !== null) { - return mountDehydratedSuspenseComponent(workInProgress, dehydrated); - } - } - } - - var nextPrimaryChildren = nextProps.children; - var nextFallbackChildren = nextProps.fallback; - - if (showFallback) { - var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes); - var primaryChildFragment = workInProgress.child; - primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes); - workInProgress.memoizedState = SUSPENDED_MARKER; - return fallbackFragment; - } else { - return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren); - } - } else { - // This is an update. - // If the current fiber has a SuspenseState, that means it's already showing - // a fallback. - var prevState = current.memoizedState; - - if (prevState !== null) { - // The current tree is already showing a fallback - // Special path for hydration - { - var _dehydrated = prevState.dehydrated; - - if (_dehydrated !== null) { - if (!didSuspend) { - return updateDehydratedSuspenseComponent(current, workInProgress, _dehydrated, prevState, renderLanes); - } else if (workInProgress.flags & ForceClientRender) { - // Something errored during hydration. Try again without hydrating. - workInProgress.flags &= ~ForceClientRender; - return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.')); - } else if (workInProgress.memoizedState !== null) { - // Something suspended and we should still be in dehydrated mode. - // Leave the existing child in place. - workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there - // but the normal suspense pass doesn't. - - workInProgress.flags |= DidCapture; - return null; - } else { - // Suspended but we should no longer be in dehydrated mode. - // Therefore we now have to render the fallback. - var _nextPrimaryChildren = nextProps.children; - var _nextFallbackChildren = nextProps.fallback; - var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes); - var _primaryChildFragment2 = workInProgress.child; - _primaryChildFragment2.memoizedState = mountSuspenseOffscreenState(renderLanes); - workInProgress.memoizedState = SUSPENDED_MARKER; - return fallbackChildFragment; - } - } - } - - if (showFallback) { - var _nextFallbackChildren2 = nextProps.fallback; - var _nextPrimaryChildren2 = nextProps.children; - - var _fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren2, _nextFallbackChildren2, renderLanes); - - var _primaryChildFragment3 = workInProgress.child; - var prevOffscreenState = current.child.memoizedState; - _primaryChildFragment3.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes); - _primaryChildFragment3.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); - workInProgress.memoizedState = SUSPENDED_MARKER; - return _fallbackChildFragment; - } else { - var _nextPrimaryChildren3 = nextProps.children; - - var _primaryChildFragment4 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren3, renderLanes); - - workInProgress.memoizedState = null; - return _primaryChildFragment4; - } - } else { - // The current tree is not already showing a fallback. - if (showFallback) { - // Timed out. - var _nextFallbackChildren3 = nextProps.fallback; - var _nextPrimaryChildren4 = nextProps.children; - - var _fallbackChildFragment2 = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren4, _nextFallbackChildren3, renderLanes); - - var _primaryChildFragment5 = workInProgress.child; - var _prevOffscreenState = current.child.memoizedState; - _primaryChildFragment5.memoizedState = _prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(_prevOffscreenState, renderLanes); - _primaryChildFragment5.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); // Skip the primary children, and continue working on the - // fallback children. - - workInProgress.memoizedState = SUSPENDED_MARKER; - return _fallbackChildFragment2; - } else { - // Still haven't timed out. Continue rendering the children, like we - // normally do. - var _nextPrimaryChildren5 = nextProps.children; - - var _primaryChildFragment6 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren5, renderLanes); - - workInProgress.memoizedState = null; - return _primaryChildFragment6; - } - } - } - } - - function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) { - var mode = workInProgress.mode; - var primaryChildProps = { - mode: 'visible', - children: primaryChildren - }; - var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); - primaryChildFragment.return = workInProgress; - workInProgress.child = primaryChildFragment; - return primaryChildFragment; - } - - function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) { - var mode = workInProgress.mode; - var progressedPrimaryFragment = workInProgress.child; - var primaryChildProps = { - mode: 'hidden', - children: primaryChildren - }; - var primaryChildFragment; - var fallbackChildFragment; - - if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) { - // In legacy mode, we commit the primary tree as if it successfully - // completed, even though it's in an inconsistent state. - primaryChildFragment = progressedPrimaryFragment; - primaryChildFragment.childLanes = NoLanes; - primaryChildFragment.pendingProps = primaryChildProps; - - if ( workInProgress.mode & ProfileMode) { - // Reset the durations from the first pass so they aren't included in the - // final amounts. This seems counterintuitive, since we're intentionally - // not measuring part of the render phase, but this makes it match what we - // do in Concurrent Mode. - primaryChildFragment.actualDuration = 0; - primaryChildFragment.actualStartTime = -1; - primaryChildFragment.selfBaseDuration = 0; - primaryChildFragment.treeBaseDuration = 0; - } - - fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); - } else { - primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); - fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); - } - - primaryChildFragment.return = workInProgress; - fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress.child = primaryChildFragment; - return fallbackChildFragment; - } - - function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) { - // The props argument to `createFiberFromOffscreen` is `any` typed, so we use - // this wrapper function to constrain it. - return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); - } - - function updateWorkInProgressOffscreenFiber(current, offscreenProps) { - // The props argument to `createWorkInProgress` is `any` typed, so we use this - // wrapper function to constrain it. - return createWorkInProgress(current, offscreenProps); - } - - function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) { - var currentPrimaryChildFragment = current.child; - var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; - var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, { - mode: 'visible', - children: primaryChildren - }); - - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - primaryChildFragment.lanes = renderLanes; - } - - primaryChildFragment.return = workInProgress; - primaryChildFragment.sibling = null; - - if (currentFallbackChildFragment !== null) { - // Delete the fallback child fragment - var deletions = workInProgress.deletions; - - if (deletions === null) { - workInProgress.deletions = [currentFallbackChildFragment]; - workInProgress.flags |= ChildDeletion; - } else { - deletions.push(currentFallbackChildFragment); - } - } - - workInProgress.child = primaryChildFragment; - return primaryChildFragment; - } - - function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { - var mode = workInProgress.mode; - var currentPrimaryChildFragment = current.child; - var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; - var primaryChildProps = { - mode: 'hidden', - children: primaryChildren - }; - var primaryChildFragment; - - if ( // In legacy mode, we commit the primary tree as if it successfully - // completed, even though it's in an inconsistent state. - (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was - // already cloned. In legacy mode, the only case where this isn't true is - // when DevTools forces us to display a fallback; we skip the first render - // pass entirely and go straight to rendering the fallback. (In Concurrent - // Mode, SuspenseList can also trigger this scenario, but this is a legacy- - // only codepath.) - workInProgress.child !== currentPrimaryChildFragment) { - var progressedPrimaryFragment = workInProgress.child; - primaryChildFragment = progressedPrimaryFragment; - primaryChildFragment.childLanes = NoLanes; - primaryChildFragment.pendingProps = primaryChildProps; - - if ( workInProgress.mode & ProfileMode) { - // Reset the durations from the first pass so they aren't included in the - // final amounts. This seems counterintuitive, since we're intentionally - // not measuring part of the render phase, but this makes it match what we - // do in Concurrent Mode. - primaryChildFragment.actualDuration = 0; - primaryChildFragment.actualStartTime = -1; - primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; - primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; - } - // However, since we're going to remain on the fallback, we no longer want - // to delete it. - - - workInProgress.deletions = null; - } else { - primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); - // (We don't do this in legacy mode, because in legacy mode we don't re-use - // the current tree; see previous branch.) - - - primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; - } - - var fallbackChildFragment; - - if (currentFallbackChildFragment !== null) { - fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren); - } else { - fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already - // mounted but this is a new fiber. - - fallbackChildFragment.flags |= Placement; - } - - fallbackChildFragment.return = workInProgress; - primaryChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress.child = primaryChildFragment; - return fallbackChildFragment; - } - - function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) { - // Falling back to client rendering. Because this has performance - // implications, it's considered a recoverable error, even though the user - // likely won't observe anything wrong with the UI. - // - // The error is passed in as an argument to enforce that every caller provide - // a custom message, or explicitly opt out (currently the only path that opts - // out is legacy mode; every concurrent path provides an error). - if (recoverableError !== null) { - queueHydrationError(recoverableError); - } // This will add the old fiber to the deletion list - - - reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated. - - var nextProps = workInProgress.pendingProps; - var primaryChildren = nextProps.children; - var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already - // mounted but this is a new fiber. - - primaryChildFragment.flags |= Placement; - workInProgress.memoizedState = null; - return primaryChildFragment; - } - - function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { - var fiberMode = workInProgress.mode; - var primaryChildProps = { - mode: 'visible', - children: primaryChildren - }; - var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode); - var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense - // boundary) already mounted but this is a new fiber. - - fallbackChildFragment.flags |= Placement; - primaryChildFragment.return = workInProgress; - fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress.child = primaryChildFragment; - - if ((workInProgress.mode & ConcurrentMode) !== NoMode) { - // We will have dropped the effect list which contains the - // deletion. We need to reconcile to delete the current child. - reconcileChildFibers(workInProgress, current.child, null, renderLanes); - } - - return fallbackChildFragment; - } - - function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) { - // During the first pass, we'll bail out and not drill into the children. - // Instead, we'll leave the content in place and try to hydrate it later. - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - { - error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, )' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.'); - } - - workInProgress.lanes = laneToLanes(SyncLane); - } else if (isSuspenseInstanceFallback(suspenseInstance)) { - // This is a client-only boundary. Since we won't get any content from the server - // for this, we need to schedule that at a higher priority based on when it would - // have timed out. In theory we could render it in this pass but it would have the - // wrong priority associated with it and will prevent hydration of parent path. - // Instead, we'll leave work left on it to render it in a separate commit. - // TODO This time should be the time at which the server rendered response that is - // a parent to this boundary was displayed. However, since we currently don't have - // a protocol to transfer that time, we'll just estimate it by using the current - // time. This will mean that Suspense timeouts are slightly shifted to later than - // they should be. - // Schedule a normal pri update to render this content. - workInProgress.lanes = laneToLanes(DefaultHydrationLane); - } else { - // We'll continue hydrating the rest at offscreen priority since we'll already - // be showing the right content coming from the server, it is no rush. - workInProgress.lanes = laneToLanes(OffscreenLane); - } - - return null; - } - - function updateDehydratedSuspenseComponent(current, workInProgress, suspenseInstance, suspenseState, renderLanes) { - // We should never be hydrating at this point because it is the first pass, - // but after we've already committed once. - warnIfHydrating(); - - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument - // required — every concurrent mode path that causes hydration to - // de-opt to client rendering should have an error message. - null); - } - - if (isSuspenseInstanceFallback(suspenseInstance)) { - // This boundary is in a permanent fallback state. In this case, we'll never - // get an update and we'll never be able to hydrate the final content. Let's just try the - // client side render instead. - return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: The server should serialize the error message so we can log it - // here on the client. Or, in production, a hash/id that corresponds to - // the error. - new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.')); - } - // any context has changed, we need to treat is as if the input might have changed. - - - var hasContextChanged = includesSomeLane(renderLanes, current.childLanes); - - if (didReceiveUpdate || hasContextChanged) { - // This boundary has changed since the first render. This means that we are now unable to - // hydrate it. We might still be able to hydrate it using a higher priority lane. - var root = getWorkInProgressRoot(); - - if (root !== null) { - var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes); - - if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) { - // Intentionally mutating since this render will get interrupted. This - // is one of the very rare times where we mutate the current tree - // during the render phase. - suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render - - var eventTime = NoTimestamp; - scheduleUpdateOnFiber(current, attemptHydrationAtLane, eventTime); - } - } // If we have scheduled higher pri work above, this will probably just abort the render - // since we now have higher priority work, but in case it doesn't, we need to prepare to - // render something, if we time out. Even if that requires us to delete everything and - // skip hydration. - // Delay having to do this as long as the suspense timeout allows us. - - - renderDidSuspendDelayIfPossible(); - return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.')); - } else if (isSuspenseInstancePending(suspenseInstance)) { - // This component is still pending more data from the server, so we can't hydrate its - // content. We treat it as if this component suspended itself. It might seem as if - // we could just try to render it client-side instead. However, this will perform a - // lot of unnecessary work and is unlikely to complete since it often will suspend - // on missing data anyway. Additionally, the server might be able to render more - // than we can on the client yet. In that case we'd end up with more fallback states - // on the client than if we just leave it alone. If the server times out or errors - // these should update this boundary to the permanent Fallback state instead. - // Mark it as having captured (i.e. suspended). - workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. - - workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result. - - var retry = retryDehydratedSuspenseBoundary.bind(null, current); - registerSuspenseInstanceRetry(suspenseInstance, retry); - return null; - } else { - // This is the first attempt. - reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext); - var nextProps = workInProgress.pendingProps; - var primaryChildren = nextProps.children; - var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this - // tree is part of a hydrating tree. This is used to determine if a child - // node has fully mounted yet, and for scheduling event replaying. - // Conceptually this is similar to Placement in that a new subtree is - // inserted into the React tree here. It just happens to not need DOM - // mutations because it already exists. - - primaryChildFragment.flags |= Hydrating; - return primaryChildFragment; - } - } - - function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) { - fiber.lanes = mergeLanes(fiber.lanes, renderLanes); - var alternate = fiber.alternate; - - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes); - } - - scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot); - } - - function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) { - // Mark any Suspense boundaries with fallbacks as having work to do. - // If they were previously forced into fallbacks, they may now be able - // to unblock. - var node = firstChild; - - while (node !== null) { - if (node.tag === SuspenseComponent) { - var state = node.memoizedState; - - if (state !== null) { - scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); - } - } else if (node.tag === SuspenseListComponent) { - // If the tail is hidden there might not be an Suspense boundaries - // to schedule work on. In this case we have to schedule it on the - // list itself. - // We don't have to traverse to the children of the list since - // the list will propagate the change when it rerenders. - scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === workInProgress) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - - function findLastContentRow(firstChild) { - // This is going to find the last row among these children that is already - // showing content on the screen, as opposed to being in fallback state or - // new. If a row has multiple Suspense boundaries, any of them being in the - // fallback state, counts as the whole row being in a fallback state. - // Note that the "rows" will be workInProgress, but any nested children - // will still be current since we haven't rendered them yet. The mounted - // order may not be the same as the new order. We use the new order. - var row = firstChild; - var lastContentRow = null; - - while (row !== null) { - var currentRow = row.alternate; // New rows can't be content rows. - - if (currentRow !== null && findFirstSuspended(currentRow) === null) { - lastContentRow = row; - } - - row = row.sibling; - } - - return lastContentRow; - } - - function validateRevealOrder(revealOrder) { - { - if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) { - didWarnAboutRevealOrder[revealOrder] = true; - - if (typeof revealOrder === 'string') { - switch (revealOrder.toLowerCase()) { - case 'together': - case 'forwards': - case 'backwards': - { - error('"%s" is not a valid value for revealOrder on . ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase()); - - break; - } - - case 'forward': - case 'backward': - { - error('"%s" is not a valid value for revealOrder on . ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase()); - - break; - } - - default: - error('"%s" is not a supported revealOrder on . ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); - - break; - } - } else { - error('%s is not a supported value for revealOrder on . ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); - } - } - } - } - - function validateTailOptions(tailMode, revealOrder) { - { - if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) { - if (tailMode !== 'collapsed' && tailMode !== 'hidden') { - didWarnAboutTailOptions[tailMode] = true; - - error('"%s" is not a supported value for tail on . ' + 'Did you mean "collapsed" or "hidden"?', tailMode); - } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') { - didWarnAboutTailOptions[tailMode] = true; - - error(' is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode); - } - } - } - } - - function validateSuspenseListNestedChild(childSlot, index) { - { - var isAnArray = isArray(childSlot); - var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function'; - - if (isAnArray || isIterable) { - var type = isAnArray ? 'array' : 'iterable'; - - error('A nested %s was passed to row #%s in . Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + ' ... ' + '{%s} ... ' + '', type, index, type); - - return false; - } - } - - return true; - } - - function validateSuspenseListChildren(children, revealOrder) { - { - if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) { - if (isArray(children)) { - for (var i = 0; i < children.length; i++) { - if (!validateSuspenseListNestedChild(children[i], i)) { - return; - } - } - } else { - var iteratorFn = getIteratorFn(children); - - if (typeof iteratorFn === 'function') { - var childrenIterator = iteratorFn.call(children); - - if (childrenIterator) { - var step = childrenIterator.next(); - var _i = 0; - - for (; !step.done; step = childrenIterator.next()) { - if (!validateSuspenseListNestedChild(step.value, _i)) { - return; - } - - _i++; - } - } - } else { - error('A single row was passed to a . ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder); - } - } - } - } - } - - function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) { - var renderState = workInProgress.memoizedState; - - if (renderState === null) { - workInProgress.memoizedState = { - isBackwards: isBackwards, - rendering: null, - renderingStartTime: 0, - last: lastContentRow, - tail: tail, - tailMode: tailMode - }; - } else { - // We can reuse the existing object from previous renders. - renderState.isBackwards = isBackwards; - renderState.rendering = null; - renderState.renderingStartTime = 0; - renderState.last = lastContentRow; - renderState.tail = tail; - renderState.tailMode = tailMode; - } - } // This can end up rendering this component multiple passes. - // The first pass splits the children fibers into two sets. A head and tail. - // We first render the head. If anything is in fallback state, we do another - // pass through beginWork to rerender all children (including the tail) with - // the force suspend context. If the first render didn't have anything in - // in fallback state. Then we render each row in the tail one-by-one. - // That happens in the completeWork phase without going back to beginWork. - - - function updateSuspenseListComponent(current, workInProgress, renderLanes) { - var nextProps = workInProgress.pendingProps; - var revealOrder = nextProps.revealOrder; - var tailMode = nextProps.tail; - var newChildren = nextProps.children; - validateRevealOrder(revealOrder); - validateTailOptions(tailMode, revealOrder); - validateSuspenseListChildren(newChildren, revealOrder); - reconcileChildren(current, workInProgress, newChildren, renderLanes); - var suspenseContext = suspenseStackCursor.current; - var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback); - - if (shouldForceFallback) { - suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); - workInProgress.flags |= DidCapture; - } else { - var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags; - - if (didSuspendBefore) { - // If we previously forced a fallback, we need to schedule work - // on any nested boundaries to let them know to try to render - // again. This is the same as context updating. - propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes); - } - - suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - } - - pushSuspenseContext(workInProgress, suspenseContext); - - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - // In legacy mode, SuspenseList doesn't work so we just - // use make it a noop by treating it as the default revealOrder. - workInProgress.memoizedState = null; - } else { - switch (revealOrder) { - case 'forwards': - { - var lastContentRow = findLastContentRow(workInProgress.child); - var tail; - - if (lastContentRow === null) { - // The whole list is part of the tail. - // TODO: We could fast path by just rendering the tail now. - tail = workInProgress.child; - workInProgress.child = null; - } else { - // Disconnect the tail rows after the content row. - // We're going to render them separately later. - tail = lastContentRow.sibling; - lastContentRow.sibling = null; - } - - initSuspenseListRenderState(workInProgress, false, // isBackwards - tail, lastContentRow, tailMode); - break; - } - - case 'backwards': - { - // We're going to find the first row that has existing content. - // At the same time we're going to reverse the list of everything - // we pass in the meantime. That's going to be our tail in reverse - // order. - var _tail = null; - var row = workInProgress.child; - workInProgress.child = null; - - while (row !== null) { - var currentRow = row.alternate; // New rows can't be content rows. - - if (currentRow !== null && findFirstSuspended(currentRow) === null) { - // This is the beginning of the main content. - workInProgress.child = row; - break; - } - - var nextRow = row.sibling; - row.sibling = _tail; - _tail = row; - row = nextRow; - } // TODO: If workInProgress.child is null, we can continue on the tail immediately. - - - initSuspenseListRenderState(workInProgress, true, // isBackwards - _tail, null, // last - tailMode); - break; - } - - case 'together': - { - initSuspenseListRenderState(workInProgress, false, // isBackwards - null, // tail - null, // last - undefined); - break; - } - - default: - { - // The default reveal order is the same as not having - // a boundary. - workInProgress.memoizedState = null; - } - } - } - - return workInProgress.child; - } - - function updatePortalComponent(current, workInProgress, renderLanes) { - pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); - var nextChildren = workInProgress.pendingProps; - - if (current === null) { - // Portals are special because we don't append the children during mount - // but at commit. Therefore we need to track insertions which the normal - // flow doesn't do during mount. This doesn't happen at the root because - // the root always starts with a "current" with a null child. - // TODO: Consider unifying this with how the root works. - workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); - } else { - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } - - return workInProgress.child; - } - - var hasWarnedAboutUsingNoValuePropOnContextProvider = false; - - function updateContextProvider(current, workInProgress, renderLanes) { - var providerType = workInProgress.type; - var context = providerType._context; - var newProps = workInProgress.pendingProps; - var oldProps = workInProgress.memoizedProps; - var newValue = newProps.value; - - { - if (!('value' in newProps)) { - if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { - hasWarnedAboutUsingNoValuePropOnContextProvider = true; - - error('The `value` prop is required for the ``. Did you misspell it or forget to pass it?'); - } - } - - var providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider'); - } - } - - pushProvider(workInProgress, context, newValue); - - { - if (oldProps !== null) { - var oldValue = oldProps.value; - - if (objectIs(oldValue, newValue)) { - // No change. Bailout early if children are the same. - if (oldProps.children === newProps.children && !hasContextChanged()) { - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - } else { - // The context value changed. Search for matching consumers and schedule - // them to update. - propagateContextChange(workInProgress, context, renderLanes); - } - } - } - - var newChildren = newProps.children; - reconcileChildren(current, workInProgress, newChildren, renderLanes); - return workInProgress.child; - } - - var hasWarnedAboutUsingContextAsConsumer = false; - - function updateContextConsumer(current, workInProgress, renderLanes) { - var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In - // DEV mode, we create a separate object for Context.Consumer that acts - // like a proxy to Context. This proxy object adds unnecessary code in PROD - // so we use the old behaviour (Context.Consumer references Context) to - // reduce size and overhead. The separate object references context via - // a property called "_context", which also gives us the ability to check - // in DEV mode if this property exists or not and warn if it does not. - - { - if (context._context === undefined) { - // This may be because it's a Context (rather than a Consumer). - // Or it may be because it's older React where they're the same thing. - // We only want to warn if we're sure it's a new React. - if (context !== context.Consumer) { - if (!hasWarnedAboutUsingContextAsConsumer) { - hasWarnedAboutUsingContextAsConsumer = true; - - error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); - } - } - } else { - context = context._context; - } - } - - var newProps = workInProgress.pendingProps; - var render = newProps.children; - - { - if (typeof render !== 'function') { - error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); - } - } - - prepareToReadContext(workInProgress, renderLanes); - var newValue = readContext(context); - - { - markComponentRenderStarted(workInProgress); - } - - var newChildren; - - { - ReactCurrentOwner$1.current = workInProgress; - setIsRendering(true); - newChildren = render(newValue); - setIsRendering(false); - } - - { - markComponentRenderStopped(); - } // React DevTools reads this flag. - - - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, newChildren, renderLanes); - return workInProgress.child; - } - - function markWorkInProgressReceivedUpdate() { - didReceiveUpdate = true; - } - - function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) { - if (current !== null) { - // Reuse previous dependencies - workInProgress.dependencies = current.dependencies; - } - - { - // Don't update "base" render times for bailouts. - stopProfilerTimerIfRunning(); - } - - markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work. - - if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { - // The children don't have any work either. We can skip them. - // TODO: Once we add back resuming, we should check if the children are - // a work-in-progress set. If so, we need to transfer their effects. - { - return null; - } - } // This fiber doesn't have work, but its subtree does. Clone the child - // fibers and continue. - - - cloneChildFibers(current, workInProgress); - return workInProgress.child; - } - - function remountFiber(current, oldWorkInProgress, newWorkInProgress) { - { - var returnFiber = oldWorkInProgress.return; - - if (returnFiber === null) { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('Cannot swap the root fiber.'); - } // Disconnect from the old current. - // It will get deleted. - - - current.alternate = null; - oldWorkInProgress.alternate = null; // Connect to the new tree. - - newWorkInProgress.index = oldWorkInProgress.index; - newWorkInProgress.sibling = oldWorkInProgress.sibling; - newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. - - if (oldWorkInProgress === returnFiber.child) { - returnFiber.child = newWorkInProgress; - } else { - var prevSibling = returnFiber.child; - - if (prevSibling === null) { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('Expected parent to have a child.'); - } - - while (prevSibling.sibling !== oldWorkInProgress) { - prevSibling = prevSibling.sibling; - - if (prevSibling === null) { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('Expected to find the previous sibling.'); - } - } - - prevSibling.sibling = newWorkInProgress; - } // Delete the old fiber and place the new one. - // Since the old fiber is disconnected, we have to schedule it manually. - - - var deletions = returnFiber.deletions; - - if (deletions === null) { - returnFiber.deletions = [current]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(current); - } - - newWorkInProgress.flags |= Placement; // Restart work from the new fiber. - - return newWorkInProgress; - } - } - - function checkScheduledUpdateOrContext(current, renderLanes) { - // Before performing an early bailout, we must check if there are pending - // updates or context. - var updateLanes = current.lanes; - - if (includesSomeLane(updateLanes, renderLanes)) { - return true; - } // No pending update, but because context is propagated lazily, we need - - return false; - } - - function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) { - // This fiber does not have any pending work. Bailout without entering - // the begin phase. There's still some bookkeeping we that needs to be done - // in this optimized path, mostly pushing stuff onto the stack. - switch (workInProgress.tag) { - case HostRoot: - pushHostRootContext(workInProgress); - workInProgress.stateNode; - - resetHydrationState(); - break; - - case HostComponent: - pushHostContext(workInProgress); - break; - - case ClassComponent: - { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - pushContextProvider(workInProgress); - } - - break; - } - - case HostPortal: - pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); - break; - - case ContextProvider: - { - var newValue = workInProgress.memoizedProps.value; - var context = workInProgress.type._context; - pushProvider(workInProgress, context, newValue); - break; - } - - case Profiler: - { - // Profiler should only call onRender when one of its descendants actually rendered. - var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); - - if (hasChildWork) { - workInProgress.flags |= Update; - } - - { - // Reset effect durations for the next eventual effect phase. - // These are reset during render to allow the DevTools commit hook a chance to read them, - var stateNode = workInProgress.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - } - - break; - - case SuspenseComponent: - { - var state = workInProgress.memoizedState; - - if (state !== null) { - { - if (state.dehydrated !== null) { - pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has - // been unsuspended it has committed as a resolved Suspense component. - // If it needs to be retried, it should have work scheduled on it. - - workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we - // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork. - - return null; - } - } // If this boundary is currently timed out, we need to decide - // whether to retry the primary children, or to skip over it and - // go straight to the fallback. Check the priority of the primary - // child fragment. - - - var primaryChildFragment = workInProgress.child; - var primaryChildLanes = primaryChildFragment.childLanes; - - if (includesSomeLane(renderLanes, primaryChildLanes)) { - // The primary children have pending work. Use the normal path - // to attempt to render the primary children again. - return updateSuspenseComponent(current, workInProgress, renderLanes); - } else { - // The primary child fragment does not have pending work marked - // on it - pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient - // priority. Bailout. - - var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - - if (child !== null) { - // The fallback children have pending work. Skip over the - // primary children and work on the fallback. - return child.sibling; - } else { - // Note: We can return `null` here because we already checked - // whether there were nested context consumers, via the call to - // `bailoutOnAlreadyFinishedWork` above. - return null; - } - } - } else { - pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); - } - - break; - } - - case SuspenseListComponent: - { - var didSuspendBefore = (current.flags & DidCapture) !== NoFlags; - - var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); - - if (didSuspendBefore) { - if (_hasChildWork) { - // If something was in fallback state last time, and we have all the - // same children then we're still in progressive loading state. - // Something might get unblocked by state updates or retries in the - // tree which will affect the tail. So we need to use the normal - // path to compute the correct tail. - return updateSuspenseListComponent(current, workInProgress, renderLanes); - } // If none of the children had any work, that means that none of - // them got retried so they'll still be blocked in the same way - // as before. We can fast bail out. - - - workInProgress.flags |= DidCapture; - } // If nothing suspended before and we're rendering the same children, - // then the tail doesn't matter. Anything new that suspends will work - // in the "together" mode, so we can continue from the state we had. - - - var renderState = workInProgress.memoizedState; - - if (renderState !== null) { - // Reset to the "together" mode in case we've started a different - // update in the past but didn't complete it. - renderState.rendering = null; - renderState.tail = null; - renderState.lastEffect = null; - } - - pushSuspenseContext(workInProgress, suspenseStackCursor.current); - - if (_hasChildWork) { - break; - } else { - // If none of the children had any work, that means that none of - // them got retried so they'll still be blocked in the same way - // as before. We can fast bail out. - return null; - } - } - - case OffscreenComponent: - case LegacyHiddenComponent: - { - // Need to check if the tree still needs to be deferred. This is - // almost identical to the logic used in the normal update path, - // so we'll just enter that. The only difference is we'll bail out - // at the next level instead of this one, because the child props - // have not changed. Which is fine. - // TODO: Probably should refactor `beginWork` to split the bailout - // path from the normal path. I'm tempted to do a labeled break here - // but I won't :) - workInProgress.lanes = NoLanes; - return updateOffscreenComponent(current, workInProgress, renderLanes); - } - } - - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - function beginWork(current, workInProgress, renderLanes) { - { - if (workInProgress._debugNeedsRemount && current !== null) { - // This will restart the begin phase with a new fiber. - return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes)); - } - } - - if (current !== null) { - var oldProps = current.memoizedProps; - var newProps = workInProgress.pendingProps; - - if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload: - workInProgress.type !== current.type )) { - // If props or context changed, mark the fiber as having performed work. - // This may be unset if the props are determined to be equal later (memo). - didReceiveUpdate = true; - } else { - // Neither props nor legacy context changes. Check if there's a pending - // update or context change. - var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); - - if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there - // may not be work scheduled on `current`, so we check for this flag. - (workInProgress.flags & DidCapture) === NoFlags) { - // No pending updates or context. Bail out now. - didReceiveUpdate = false; - return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes); - } - - if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { - // This is a special case that only exists for legacy mode. - // See https://github.com/facebook/react/pull/19216. - didReceiveUpdate = true; - } else { - // An update was scheduled on this fiber, but there are no new props - // nor legacy context. Set this to false. If an update queue or context - // consumer produces a changed value, it will set this to true. Otherwise, - // the component will assume the children have not changed and bail out. - didReceiveUpdate = false; - } - } - } else { - didReceiveUpdate = false; - - if (getIsHydrating() && isForkedChild(workInProgress)) { - // Check if this child belongs to a list of muliple children in - // its parent. - // - // In a true multi-threaded implementation, we would render children on - // parallel threads. This would represent the beginning of a new render - // thread for this subtree. - // - // We only use this for id generation during hydration, which is why the - // logic is located in this special branch. - var slotIndex = workInProgress.index; - var numberOfForks = getForksAtLevel(); - pushTreeId(workInProgress, numberOfForks, slotIndex); - } - } // Before entering the begin phase, clear pending update priority. - // TODO: This assumes that we're about to evaluate the component and process - // the update queue. However, there's an exception: SimpleMemoComponent - // sometimes bails out later in the begin phase. This indicates that we should - // move this assignment out of the common path and into each branch. - - - workInProgress.lanes = NoLanes; - - switch (workInProgress.tag) { - case IndeterminateComponent: - { - return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes); - } - - case LazyComponent: - { - var elementType = workInProgress.elementType; - return mountLazyComponent(current, workInProgress, elementType, renderLanes); - } - - case FunctionComponent: - { - var Component = workInProgress.type; - var unresolvedProps = workInProgress.pendingProps; - var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); - return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes); - } - - case ClassComponent: - { - var _Component = workInProgress.type; - var _unresolvedProps = workInProgress.pendingProps; - - var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps); - - return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes); - } - - case HostRoot: - return updateHostRoot(current, workInProgress, renderLanes); - - case HostComponent: - return updateHostComponent$1(current, workInProgress, renderLanes); - - case HostText: - return updateHostText$1(current, workInProgress); - - case SuspenseComponent: - return updateSuspenseComponent(current, workInProgress, renderLanes); - - case HostPortal: - return updatePortalComponent(current, workInProgress, renderLanes); - - case ForwardRef: - { - var type = workInProgress.type; - var _unresolvedProps2 = workInProgress.pendingProps; - - var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); - - return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes); - } - - case Fragment: - return updateFragment(current, workInProgress, renderLanes); - - case Mode: - return updateMode(current, workInProgress, renderLanes); - - case Profiler: - return updateProfiler(current, workInProgress, renderLanes); - - case ContextProvider: - return updateContextProvider(current, workInProgress, renderLanes); - - case ContextConsumer: - return updateContextConsumer(current, workInProgress, renderLanes); - - case MemoComponent: - { - var _type2 = workInProgress.type; - var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. - - var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); - - { - if (workInProgress.type !== workInProgress.elementType) { - var outerPropTypes = _type2.propTypes; - - if (outerPropTypes) { - checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only - 'prop', getComponentNameFromType(_type2)); - } - } - } - - _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); - return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes); - } - - case SimpleMemoComponent: - { - return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes); - } - - case IncompleteClassComponent: - { - var _Component2 = workInProgress.type; - var _unresolvedProps4 = workInProgress.pendingProps; - - var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4); - - return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes); - } - - case SuspenseListComponent: - { - return updateSuspenseListComponent(current, workInProgress, renderLanes); - } - - case ScopeComponent: - { - - break; - } - - case OffscreenComponent: - { - return updateOffscreenComponent(current, workInProgress, renderLanes); - } - } - - throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); - } - - function unwindWork(current, workInProgress, renderLanes) { - // Note: This intentionally doesn't check if we're hydrating because comparing - // to the current tree provider fiber is just as fast and less error-prone. - // Ideally we would have a special version of the work loop only - // for hydration. - popTreeContext(workInProgress); - - switch (workInProgress.tag) { - case ClassComponent: - { - var Component = workInProgress.type; - - if (isContextProvider(Component)) { - popContext(workInProgress); - } - - var flags = workInProgress.flags; - - if (flags & ShouldCapture) { - workInProgress.flags = flags & ~ShouldCapture | DidCapture; - - if ( (workInProgress.mode & ProfileMode) !== NoMode) { - transferActualDuration(workInProgress); - } - - return workInProgress; - } - - return null; - } - - case HostRoot: - { - - popHostContainer(workInProgress); - popTopLevelContextObject(workInProgress); - resetWorkInProgressVersions(); - var _flags = workInProgress.flags; - - if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) { - // There was an error during render that wasn't captured by a suspense - // boundary. Do a second pass on the root to unmount the children. - workInProgress.flags = _flags & ~ShouldCapture | DidCapture; - return workInProgress; - } // We unwound to the root without completing it. Exit. - - - return null; - } - - case HostComponent: - { - // TODO: popHydrationState - popHostContext(workInProgress); - return null; - } - - case SuspenseComponent: - { - popSuspenseContext(workInProgress); - - { - var suspenseState = workInProgress.memoizedState; - - if (suspenseState !== null && suspenseState.dehydrated !== null) { - if (workInProgress.alternate === null) { - throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.'); - } - - resetHydrationState(); - } - } - - var _flags2 = workInProgress.flags; - - if (_flags2 & ShouldCapture) { - workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary. - - if ( (workInProgress.mode & ProfileMode) !== NoMode) { - transferActualDuration(workInProgress); - } - - return workInProgress; - } - - return null; - } - - case SuspenseListComponent: - { - popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been - // caught by a nested boundary. If not, it should bubble through. - - return null; - } - - case HostPortal: - popHostContainer(workInProgress); - return null; - - case ContextProvider: - var context = workInProgress.type._context; - popProvider(context, workInProgress); - return null; - - case OffscreenComponent: - case LegacyHiddenComponent: - popRenderLanes(workInProgress); - - return null; - - case CacheComponent: - - return null; - - default: - return null; - } - } - - function unwindInterruptedWork(current, interruptedWork, renderLanes) { - // Note: This intentionally doesn't check if we're hydrating because comparing - // to the current tree provider fiber is just as fast and less error-prone. - // Ideally we would have a special version of the work loop only - // for hydration. - popTreeContext(interruptedWork); - - switch (interruptedWork.tag) { - case ClassComponent: - { - var childContextTypes = interruptedWork.type.childContextTypes; - - if (childContextTypes !== null && childContextTypes !== undefined) { - popContext(interruptedWork); - } - - break; - } - - case HostRoot: - { - - popHostContainer(interruptedWork); - popTopLevelContextObject(interruptedWork); - resetWorkInProgressVersions(); - break; - } - - case HostComponent: - { - popHostContext(interruptedWork); - break; - } - - case HostPortal: - popHostContainer(interruptedWork); - break; - - case SuspenseComponent: - popSuspenseContext(interruptedWork); - break; - - case SuspenseListComponent: - popSuspenseContext(interruptedWork); - break; - - case ContextProvider: - var context = interruptedWork.type._context; - popProvider(context, interruptedWork); - break; - - case OffscreenComponent: - case LegacyHiddenComponent: - popRenderLanes(interruptedWork); - - break; - } - } - - function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) { - var funcArgs = Array.prototype.slice.call(arguments, 3); - - try { - func.apply(context, funcArgs); - } catch (error) { - this.onError(error); - } - } - - var invokeGuardedCallbackImpl = invokeGuardedCallbackProd; - - { - // In DEV mode, we swap out invokeGuardedCallback for a special version - // that plays more nicely with the browser's DevTools. The idea is to preserve - // "Pause on exceptions" behavior. Because React wraps all user-provided - // functions in invokeGuardedCallback, and the production version of - // invokeGuardedCallback uses a try-catch, all user exceptions are treated - // like caught exceptions, and the DevTools won't pause unless the developer - // takes the extra step of enabling pause on caught exceptions. This is - // unintuitive, though, because even though React has caught the error, from - // the developer's perspective, the error is uncaught. - // - // To preserve the expected "Pause on exceptions" behavior, we don't use a - // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake - // DOM node, and call the user-provided callback from inside an event handler - // for that fake event. If the callback throws, the error is "captured" using - // a global event handler. But because the error happens in a different - // event loop context, it does not interrupt the normal program flow. - // Effectively, this gives us try-catch behavior without actually using - // try-catch. Neat! - // Check that the browser supports the APIs we need to implement our special - // DEV version of invokeGuardedCallback - if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { - var fakeNode = document.createElement('react'); - - invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) { - // If document doesn't exist we know for sure we will crash in this method - // when we call document.createEvent(). However this can cause confusing - // errors: https://github.com/facebook/create-react-app/issues/3482 - // So we preemptively throw with a better message instead. - if (typeof document === 'undefined' || document === null) { - throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.'); - } - - var evt = document.createEvent('Event'); - var didCall = false; // Keeps track of whether the user-provided callback threw an error. We - // set this to true at the beginning, then set it to false right after - // calling the function. If the function errors, `didError` will never be - // set to false. This strategy works even if the browser is flaky and - // fails to call our global error handler, because it doesn't rely on - // the error event at all. - - var didError = true; // Keeps track of the value of window.event so that we can reset it - // during the callback to let user code access window.event in the - // browsers that support it. - - var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event - // dispatching: https://github.com/facebook/react/issues/13688 - - var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); - - function restoreAfterDispatch() { - // We immediately remove the callback from event listeners so that - // nested `invokeGuardedCallback` calls do not clash. Otherwise, a - // nested call would trigger the fake event handlers of any call higher - // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the - // window.event assignment in both IE <= 10 as they throw an error - // "Member not found" in strict mode, and in Firefox which does not - // support window.event. - - if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) { - window.event = windowEvent; - } - } // Create an event handler for our fake event. We will synchronously - // dispatch our fake event using `dispatchEvent`. Inside the handler, we - // call the user-provided callback. - - - var funcArgs = Array.prototype.slice.call(arguments, 3); - - function callCallback() { - didCall = true; - restoreAfterDispatch(); - func.apply(context, funcArgs); - didError = false; - } // Create a global error event handler. We use this to capture the value - // that was thrown. It's possible that this error handler will fire more - // than once; for example, if non-React code also calls `dispatchEvent` - // and a handler for that event throws. We should be resilient to most of - // those cases. Even if our error event handler fires more than once, the - // last error event is always used. If the callback actually does error, - // we know that the last error event is the correct one, because it's not - // possible for anything else to have happened in between our callback - // erroring and the code that follows the `dispatchEvent` call below. If - // the callback doesn't error, but the error event was fired, we know to - // ignore it because `didError` will be false, as described above. - - - var error; // Use this to track whether the error event is ever called. - - var didSetError = false; - var isCrossOriginError = false; - - function handleWindowError(event) { - error = event.error; - didSetError = true; - - if (error === null && event.colno === 0 && event.lineno === 0) { - isCrossOriginError = true; - } - - if (event.defaultPrevented) { - // Some other error handler has prevented default. - // Browsers silence the error report if this happens. - // We'll remember this to later decide whether to log it or not. - if (error != null && typeof error === 'object') { - try { - error._suppressLogging = true; - } catch (inner) {// Ignore. - } - } - } - } // Create a fake event type. - - - var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers - - window.addEventListener('error', handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function - // errors, it will trigger our global error handler. - - evt.initEvent(evtType, false, false); - fakeNode.dispatchEvent(evt); - - if (windowEventDescriptor) { - Object.defineProperty(window, 'event', windowEventDescriptor); - } - - if (didCall && didError) { - if (!didSetError) { - // The callback errored, but the error event never fired. - // eslint-disable-next-line react-internal/prod-error-codes - error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); - } else if (isCrossOriginError) { - // eslint-disable-next-line react-internal/prod-error-codes - error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.'); - } - - this.onError(error); - } // Remove our event listeners - - - window.removeEventListener('error', handleWindowError); - - if (!didCall) { - // Something went really wrong, and our event was not dispatched. - // https://github.com/facebook/react/issues/16734 - // https://github.com/facebook/react/issues/16585 - // Fall back to the production implementation. - restoreAfterDispatch(); - return invokeGuardedCallbackProd.apply(this, arguments); - } - }; - } - } - - var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; - - var hasError = false; - var caughtError = null; // Used by event system to capture/rethrow the first error. - var reporter = { - onError: function (error) { - hasError = true; - caughtError = error; - } - }; - /** - * Call a function while guarding against errors that happens within it. - * Returns an error if it throws, otherwise null. - * - * In production, this is implemented using a try-catch. The reason we don't - * use a try-catch directly is so that we can swap out a different - * implementation in DEV mode. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - - function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = false; - caughtError = null; - invokeGuardedCallbackImpl$1.apply(reporter, arguments); - } - function hasCaughtError() { - return hasError; - } - function clearCaughtError() { - if (hasError) { - var error = caughtError; - hasError = false; - caughtError = null; - return error; - } else { - throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.'); - } - } - - var didWarnAboutUndefinedSnapshotBeforeUpdate = null; - - { - didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); - } // Used during the commit phase to track the state of the Offscreen component stack. - // Allows us to avoid traversing the return path to find the nearest Offscreen ancestor. - // Only used when enableSuspenseLayoutEffectSemantics is enabled. - - - var offscreenSubtreeIsHidden = false; - var offscreenSubtreeWasHidden = false; - var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; - var nextEffect = null; // Used for Profiling builds to track updaters. - - var inProgressLanes = null; - var inProgressRoot = null; - - function reportUncaughtErrorInDEV(error) { - // Wrapping each small part of the commit phase into a guarded - // callback is a bit too slow (https://github.com/facebook/react/pull/21666). - // But we rely on it to surface errors to DEV tools like overlays - // (https://github.com/facebook/react/issues/21712). - // As a compromise, rethrow only caught errors in a guard. - { - invokeGuardedCallback(null, function () { - throw error; - }); - clearCaughtError(); - } - } - - var callComponentWillUnmountWithTimer = function (current, instance) { - instance.props = current.memoizedProps; - instance.state = current.memoizedState; - - if ( current.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - instance.componentWillUnmount(); - } finally { - recordLayoutEffectDuration(current); - } - } else { - instance.componentWillUnmount(); - } - }; // Capture errors so they don't interrupt mounting. - - - function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) { - try { - commitHookEffectListMount(Layout, current); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } // Capture errors so they don't interrupt unmounting. - - - function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) { - try { - callComponentWillUnmountWithTimer(current, instance); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } // Capture errors so they don't interrupt mounting. - - - function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) { - try { - instance.componentDidMount(); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } // Capture errors so they don't interrupt mounting. - - - function safelyAttachRef(current, nearestMountedAncestor) { - try { - commitAttachRef(current); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } - - function safelyDetachRef(current, nearestMountedAncestor) { - var ref = current.ref; - - if (ref !== null) { - if (typeof ref === 'function') { - var retVal; - - try { - if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - retVal = ref(null); - } finally { - recordLayoutEffectDuration(current); - } - } else { - retVal = ref(null); - } - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - - { - if (typeof retVal === 'function') { - error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current)); - } - } - } else { - ref.current = null; - } - } - } - - function safelyCallDestroy(current, nearestMountedAncestor, destroy) { - try { - destroy(); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - } - var shouldFireAfterActiveInstanceBlur = false; - function commitBeforeMutationEffects(root, firstChild) { - prepareForCommit(root.containerInfo); - nextEffect = firstChild; - commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber - - var shouldFire = shouldFireAfterActiveInstanceBlur; - shouldFireAfterActiveInstanceBlur = false; - return shouldFire; - } - - function commitBeforeMutationEffects_begin() { - while (nextEffect !== null) { - var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur. - - var child = fiber.child; - - if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) { - ensureCorrectReturnPointer(child, fiber); - nextEffect = child; - } else { - commitBeforeMutationEffects_complete(); - } - } - } - - function commitBeforeMutationEffects_complete() { - while (nextEffect !== null) { - var fiber = nextEffect; - setCurrentFiber(fiber); - - try { - commitBeforeMutationEffectsOnFiber(fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitBeforeMutationEffectsOnFiber(finishedWork) { - var current = finishedWork.alternate; - var flags = finishedWork.flags; - - if ((flags & Snapshot) !== NoFlags) { - setCurrentFiber(finishedWork); - - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - break; - } - - case ClassComponent: - { - if (current !== null) { - var prevProps = current.memoizedProps; - var prevState = current.memoizedState; - var instance = finishedWork.stateNode; // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - - if (instance.state !== finishedWork.memoizedState) { - error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - } - } - - var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState); - - { - var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; - - if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { - didWarnSet.add(finishedWork.type); - - error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork)); - } - } - - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - - break; - } - - case HostRoot: - { - if (supportsMutation) { - var root = finishedWork.stateNode; - clearContainer(root.containerInfo); - } - - break; - } - - case HostComponent: - case HostText: - case HostPortal: - case IncompleteClassComponent: - // Nothing to do for these component types - break; - - default: - { - throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); - } - } - - resetCurrentFiber(); - } - } - - function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) { - var updateQueue = finishedWork.updateQueue; - var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - var effect = firstEffect; - - do { - if ((effect.tag & flags) === flags) { - // Unmount - var destroy = effect.destroy; - effect.destroy = undefined; - - if (destroy !== undefined) { - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectUnmountStarted(finishedWork); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectUnmountStarted(finishedWork); - } - } - - safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); - - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectUnmountStopped(); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectUnmountStopped(); - } - } - } - } - - effect = effect.next; - } while (effect !== firstEffect); - } - } - - function commitHookEffectListMount(flags, finishedWork) { - var updateQueue = finishedWork.updateQueue; - var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - var effect = firstEffect; - - do { - if ((effect.tag & flags) === flags) { - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectMountStarted(finishedWork); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectMountStarted(finishedWork); - } - } // Mount - - - var create = effect.create; - effect.destroy = create(); - - { - if ((flags & Passive$1) !== NoFlags$1) { - markComponentPassiveEffectMountStopped(); - } else if ((flags & Layout) !== NoFlags$1) { - markComponentLayoutEffectMountStopped(); - } - } - - { - var destroy = effect.destroy; - - if (destroy !== undefined && typeof destroy !== 'function') { - var hookName = void 0; - - if ((effect.tag & Layout) !== NoFlags) { - hookName = 'useLayoutEffect'; - } else if ((effect.tag & Insertion) !== NoFlags) { - hookName = 'useInsertionEffect'; - } else { - hookName = 'useEffect'; - } - - var addendum = void 0; - - if (destroy === null) { - addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).'; - } else if (typeof destroy.then === 'function') { - addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching'; - } else { - addendum = ' You returned: ' + destroy; - } - - error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum); - } - } - } - - effect = effect.next; - } while (effect !== firstEffect); - } - } - - function commitPassiveEffectDurations(finishedRoot, finishedWork) { - { - // Only Profilers with work in their subtree will have an Update effect scheduled. - if ((finishedWork.flags & Update) !== NoFlags) { - switch (finishedWork.tag) { - case Profiler: - { - var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration; - var _finishedWork$memoize = finishedWork.memoizedProps, - id = _finishedWork$memoize.id, - onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase. - // It does not get reset until the start of the next commit phase. - - var commitTime = getCommitTime(); - var phase = finishedWork.alternate === null ? 'mount' : 'update'; - - { - if (isCurrentUpdateNested()) { - phase = 'nested-update'; - } - } - - if (typeof onPostCommit === 'function') { - onPostCommit(id, phase, passiveEffectDuration, commitTime); - } // Bubble times to the next nearest ancestor Profiler. - // After we process that Profiler, we'll bubble further up. - - - var parentFiber = finishedWork.return; - - outer: while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - root.passiveEffectDuration += passiveEffectDuration; - break outer; - - case Profiler: - var parentStateNode = parentFiber.stateNode; - parentStateNode.passiveEffectDuration += passiveEffectDuration; - break outer; - } - - parentFiber = parentFiber.return; - } - - break; - } - } - } - } - } - - function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) { - if ((finishedWork.flags & LayoutMask) !== NoFlags) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( !offscreenSubtreeWasHidden) { - // At this point layout effects have already been destroyed (during mutation phase). - // This is done to prevent sibling component effects from interfering with each other, - // e.g. a destroy function in one component should never override a ref set - // by a create function in another component during the same commit. - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListMount(Layout | HasEffect, finishedWork); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - commitHookEffectListMount(Layout | HasEffect, finishedWork); - } - } - - break; - } - - case ClassComponent: - { - var instance = finishedWork.stateNode; - - if (finishedWork.flags & Update) { - if (!offscreenSubtreeWasHidden) { - if (current === null) { - // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - - if (instance.state !== finishedWork.memoizedState) { - error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - } - } - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - instance.componentDidMount(); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - instance.componentDidMount(); - } - } else { - var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps); - var prevState = current.memoizedState; // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - - if (instance.state !== finishedWork.memoizedState) { - error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - } - } - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); - } - } - } - } // TODO: I think this is now always non-null by the time it reaches the - // commit phase. Consider removing the type check. - - - var updateQueue = finishedWork.updateQueue; - - if (updateQueue !== null) { - { - if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { - if (instance.props !== finishedWork.memoizedProps) { - error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - - if (instance.state !== finishedWork.memoizedState) { - error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); - } - } - } // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - - - commitUpdateQueue(finishedWork, updateQueue, instance); - } - - break; - } - - case HostRoot: - { - // TODO: I think this is now always non-null by the time it reaches the - // commit phase. Consider removing the type check. - var _updateQueue = finishedWork.updateQueue; - - if (_updateQueue !== null) { - var _instance = null; - - if (finishedWork.child !== null) { - switch (finishedWork.child.tag) { - case HostComponent: - _instance = getPublicInstance(finishedWork.child.stateNode); - break; - - case ClassComponent: - _instance = finishedWork.child.stateNode; - break; - } - } - - commitUpdateQueue(finishedWork, _updateQueue, _instance); - } - - break; - } - - case HostComponent: - { - var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted - // (eg DOM renderer may schedule auto-focus for inputs and form controls). - // These effects should only be committed when components are first mounted, - // aka when there is no current/alternate. - - if (current === null && finishedWork.flags & Update) { - var type = finishedWork.type; - var props = finishedWork.memoizedProps; - commitMount(_instance2, type, props, finishedWork); - } - - break; - } - - case HostText: - { - // We have no life-cycles associated with text. - break; - } - - case HostPortal: - { - // We have no life-cycles associated with portals. - break; - } - - case Profiler: - { - { - var _finishedWork$memoize2 = finishedWork.memoizedProps, - onCommit = _finishedWork$memoize2.onCommit, - onRender = _finishedWork$memoize2.onRender; - var effectDuration = finishedWork.stateNode.effectDuration; - var commitTime = getCommitTime(); - var phase = current === null ? 'mount' : 'update'; - - { - if (isCurrentUpdateNested()) { - phase = 'nested-update'; - } - } - - if (typeof onRender === 'function') { - onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime); - } - - { - if (typeof onCommit === 'function') { - onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime); - } // Schedule a passive effect for this Profiler to call onPostCommit hooks. - // This effect should be scheduled even if there is no onPostCommit callback for this Profiler, - // because the effect is also where times bubble to parent Profilers. - - - enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor. - // Do not reset these values until the next render so DevTools has a chance to read them first. - - var parentFiber = finishedWork.return; - - outer: while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - var root = parentFiber.stateNode; - root.effectDuration += effectDuration; - break outer; - - case Profiler: - var parentStateNode = parentFiber.stateNode; - parentStateNode.effectDuration += effectDuration; - break outer; - } - - parentFiber = parentFiber.return; - } - } - } - - break; - } - - case SuspenseComponent: - { - commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); - break; - } - - case SuspenseListComponent: - case IncompleteClassComponent: - case ScopeComponent: - case OffscreenComponent: - case LegacyHiddenComponent: - { - break; - } - - default: - throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); - } - } - - if ( !offscreenSubtreeWasHidden) { - { - if (finishedWork.flags & Ref) { - commitAttachRef(finishedWork); - } - } - } - } - - function reappearLayoutEffectsOnFiber(node) { - // Turn on layout effects in a tree that previously disappeared. - // TODO (Offscreen) Check: flags & LayoutStatic - switch (node.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( node.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - safelyCallCommitHookLayoutEffectListMount(node, node.return); - } finally { - recordLayoutEffectDuration(node); - } - } else { - safelyCallCommitHookLayoutEffectListMount(node, node.return); - } - - break; - } - - case ClassComponent: - { - var instance = node.stateNode; - - if (typeof instance.componentDidMount === 'function') { - safelyCallComponentDidMount(node, node.return, instance); - } - - safelyAttachRef(node, node.return); - break; - } - - case HostComponent: - { - safelyAttachRef(node, node.return); - break; - } - } - } - - function hideOrUnhideAllChildren(finishedWork, isHidden) { - // Only hide or unhide the top-most host nodes. - var hostSubtreeRoot = null; - - if (supportsMutation) { - // We only have the top Fiber that was inserted but we need to recurse down its - // children to find all the terminal nodes. - var node = finishedWork; - - while (true) { - if (node.tag === HostComponent) { - if (hostSubtreeRoot === null) { - hostSubtreeRoot = node; - var instance = node.stateNode; - - if (isHidden) { - hideInstance(instance); - } else { - unhideInstance(node.stateNode, node.memoizedProps); - } - } - } else if (node.tag === HostText) { - if (hostSubtreeRoot === null) { - var _instance3 = node.stateNode; - - if (isHidden) { - hideTextInstance(_instance3); - } else { - unhideTextInstance(_instance3, node.memoizedProps); - } - } - } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === finishedWork) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === finishedWork) { - return; - } - - if (hostSubtreeRoot === node) { - hostSubtreeRoot = null; - } - - node = node.return; - } - - if (hostSubtreeRoot === node) { - hostSubtreeRoot = null; - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - } - - function commitAttachRef(finishedWork) { - var ref = finishedWork.ref; - - if (ref !== null) { - var instance = finishedWork.stateNode; - var instanceToUse; - - switch (finishedWork.tag) { - case HostComponent: - instanceToUse = getPublicInstance(instance); - break; - - default: - instanceToUse = instance; - } // Moved outside to ensure DCE works with this flag - - if (typeof ref === 'function') { - var retVal; - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - retVal = ref(instanceToUse); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - retVal = ref(instanceToUse); - } - - { - if (typeof retVal === 'function') { - error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork)); - } - } - } else { - { - if (!ref.hasOwnProperty('current')) { - error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork)); - } - } - - ref.current = instanceToUse; - } - } - } - - function commitDetachRef(current) { - var currentRef = current.ref; - - if (currentRef !== null) { - if (typeof currentRef === 'function') { - if ( current.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - currentRef(null); - } finally { - recordLayoutEffectDuration(current); - } - } else { - currentRef(null); - } - } else { - currentRef.current = null; - } - } - } // User-originating errors (lifecycles and refs) should not interrupt - // deletion, so don't let them throw. Host-originating errors should - // interrupt deletion, so it's okay - - - function commitUnmount(finishedRoot, current, nearestMountedAncestor) { - onCommitUnmount(current); - - switch (current.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: - { - var updateQueue = current.updateQueue; - - if (updateQueue !== null) { - var lastEffect = updateQueue.lastEffect; - - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - var effect = firstEffect; - - do { - var _effect = effect, - destroy = _effect.destroy, - tag = _effect.tag; - - if (destroy !== undefined) { - if ((tag & Insertion) !== NoFlags$1) { - safelyCallDestroy(current, nearestMountedAncestor, destroy); - } else if ((tag & Layout) !== NoFlags$1) { - { - markComponentLayoutEffectUnmountStarted(current); - } - - if ( current.mode & ProfileMode) { - startLayoutEffectTimer(); - safelyCallDestroy(current, nearestMountedAncestor, destroy); - recordLayoutEffectDuration(current); - } else { - safelyCallDestroy(current, nearestMountedAncestor, destroy); - } - - { - markComponentLayoutEffectUnmountStopped(); - } - } - } - - effect = effect.next; - } while (effect !== firstEffect); - } - } - - return; - } - - case ClassComponent: - { - safelyDetachRef(current, nearestMountedAncestor); - var instance = current.stateNode; - - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance); - } - - return; - } - - case HostComponent: - { - safelyDetachRef(current, nearestMountedAncestor); - return; - } - - case HostPortal: - { - // TODO: this is recursive. - // We are also not using this parent because - // the portal will get pushed immediately. - if (supportsMutation) { - unmountHostComponents(finishedRoot, current, nearestMountedAncestor); - } else if (supportsPersistence) { - emptyPortalContainer(current); - } - - return; - } - - case DehydratedFragment: - { - - return; - } - - case ScopeComponent: - { - - return; - } - } - } - - function commitNestedUnmounts(finishedRoot, root, nearestMountedAncestor) { - // While we're inside a removed host node we don't want to call - // removeChild on the inner nodes because they're removed by the top - // call anyway. We also want to call componentWillUnmount on all - // composites before this host node is removed from the tree. Therefore - // we do an inner loop while we're still inside the host node. - var node = root; - - while (true) { - commitUnmount(finishedRoot, node, nearestMountedAncestor); // Visit children because they may contain more composite or host nodes. - // Skip portals because commitUnmount() currently visits them recursively. - - if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above. - // If we don't use mutation we drill down into portals here instead. - !supportsMutation || node.tag !== HostPortal)) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === root) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === root) { - return; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - - function detachFiberMutation(fiber) { - // Cut off the return pointer to disconnect it from the tree. - // This enables us to detect and warn against state updates on an unmounted component. - // It also prevents events from bubbling from within disconnected components. - // - // Ideally, we should also clear the child pointer of the parent alternate to let this - // get GC:ed but we don't know which for sure which parent is the current - // one so we'll settle for GC:ing the subtree of this child. - // This child itself will be GC:ed when the parent updates the next time. - // - // Note that we can't clear child or sibling pointers yet. - // They're needed for passive effects and for findDOMNode. - // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects). - // - // Don't reset the alternate yet, either. We need that so we can detach the - // alternate's fields in the passive phase. Clearing the return pointer is - // sufficient for findDOMNode semantics. - var alternate = fiber.alternate; - - if (alternate !== null) { - alternate.return = null; - } - - fiber.return = null; - } - - function detachFiberAfterEffects(fiber) { - var alternate = fiber.alternate; - - if (alternate !== null) { - fiber.alternate = null; - detachFiberAfterEffects(alternate); - } // Note: Defensively using negation instead of < in case - // `deletedTreeCleanUpLevel` is undefined. - - - { - // Clear cyclical Fiber fields. This level alone is designed to roughly - // approximate the planned Fiber refactor. In that world, `setState` will be - // bound to a special "instance" object instead of a Fiber. The Instance - // object will not have any of these fields. It will only be connected to - // the fiber tree via a single link at the root. So if this level alone is - // sufficient to fix memory issues, that bodes well for our plans. - fiber.child = null; - fiber.deletions = null; - fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host - // tree, which has its own pointers to children, parents, and siblings. - // The other host nodes also point back to fibers, so we should detach that - // one, too. - - if (fiber.tag === HostComponent) { - var hostInstance = fiber.stateNode; - - if (hostInstance !== null) { - detachDeletedInstance(hostInstance); - } - } - - fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We - // already disconnect the `return` pointer at the root of the deleted - // subtree (in `detachFiberMutation`). Besides, `return` by itself is not - // cyclical — it's only cyclical when combined with `child`, `sibling`, and - // `alternate`. But we'll clear it in the next level anyway, just in case. - - { - fiber._debugOwner = null; - } - - { - // Theoretically, nothing in here should be necessary, because we already - // disconnected the fiber from the tree. So even if something leaks this - // particular fiber, it won't leak anything else - // - // The purpose of this branch is to be super aggressive so we can measure - // if there's any difference in memory impact. If there is, that could - // indicate a React leak we don't know about. - fiber.return = null; - fiber.dependencies = null; - fiber.memoizedProps = null; - fiber.memoizedState = null; - fiber.pendingProps = null; - fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead. - - fiber.updateQueue = null; - } - } - } - - function emptyPortalContainer(current) { - if (!supportsPersistence) { - return; - } - - var portal = current.stateNode; - var containerInfo = portal.containerInfo; - var emptyChildSet = createContainerChildSet(containerInfo); - replaceContainerChildren(containerInfo, emptyChildSet); - } - - function commitContainer(finishedWork) { - if (!supportsPersistence) { - return; - } - - switch (finishedWork.tag) { - case ClassComponent: - case HostComponent: - case HostText: - { - return; - } - - case HostRoot: - case HostPortal: - { - var portalOrRoot = finishedWork.stateNode; - var containerInfo = portalOrRoot.containerInfo, - pendingChildren = portalOrRoot.pendingChildren; - replaceContainerChildren(containerInfo, pendingChildren); - return; - } - } - - throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); - } - - function getHostParentFiber(fiber) { - var parent = fiber.return; - - while (parent !== null) { - if (isHostParent(parent)) { - return parent; - } - - parent = parent.return; - } - - throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.'); - } - - function isHostParent(fiber) { - return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; - } - - function getHostSibling(fiber) { - // We're going to search forward into the tree until we find a sibling host - // node. Unfortunately, if multiple insertions are done in a row we have to - // search past them. This leads to exponential search for the next sibling. - // TODO: Find a more efficient way to do this. - var node = fiber; - - siblings: while (true) { - // If we didn't find anything, let's try the next sibling. - while (node.sibling === null) { - if (node.return === null || isHostParent(node.return)) { - // If we pop out of the root or hit the parent the fiber we are the - // last sibling. - return null; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - - while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) { - // If it is not host node and, we might have a host node inside it. - // Try to search down until we find one. - if (node.flags & Placement) { - // If we don't have a child, try the siblings instead. - continue siblings; - } // If we don't have a child, try the siblings instead. - // We also skip portals because they are not part of this host tree. - - - if (node.child === null || node.tag === HostPortal) { - continue siblings; - } else { - node.child.return = node; - node = node.child; - } - } // Check if this host node is stable or about to be placed. - - - if (!(node.flags & Placement)) { - // Found it! - return node.stateNode; - } - } - } - - function commitPlacement(finishedWork) { - if (!supportsMutation) { - return; - } // Recursively insert all host nodes into the parent. - - - var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. - - switch (parentFiber.tag) { - case HostComponent: - { - var parent = parentFiber.stateNode; - - if (parentFiber.flags & ContentReset) { - // Reset the text content of the parent before doing any insertions - resetTextContent(parent); // Clear ContentReset from the effect tag - - parentFiber.flags &= ~ContentReset; - } - - var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its - // children to find all the terminal nodes. - - insertOrAppendPlacementNode(finishedWork, before, parent); - break; - } - - case HostRoot: - case HostPortal: - { - var _parent = parentFiber.stateNode.containerInfo; - - var _before = getHostSibling(finishedWork); - - insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent); - break; - } - // eslint-disable-next-line-no-fallthrough - - default: - throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.'); - } - } - - function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { - var tag = node.tag; - var isHost = tag === HostComponent || tag === HostText; - - if (isHost) { - var stateNode = node.stateNode; - - if (before) { - insertInContainerBefore(parent, stateNode, before); - } else { - appendChildToContainer(parent, stateNode); - } - } else if (tag === HostPortal) ; else { - var child = node.child; - - if (child !== null) { - insertOrAppendPlacementNodeIntoContainer(child, before, parent); - var sibling = child.sibling; - - while (sibling !== null) { - insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); - sibling = sibling.sibling; - } - } - } - } - - function insertOrAppendPlacementNode(node, before, parent) { - var tag = node.tag; - var isHost = tag === HostComponent || tag === HostText; - - if (isHost) { - var stateNode = node.stateNode; - - if (before) { - insertBefore(parent, stateNode, before); - } else { - appendChild(parent, stateNode); - } - } else if (tag === HostPortal) ; else { - var child = node.child; - - if (child !== null) { - insertOrAppendPlacementNode(child, before, parent); - var sibling = child.sibling; - - while (sibling !== null) { - insertOrAppendPlacementNode(sibling, before, parent); - sibling = sibling.sibling; - } - } - } - } - - function unmountHostComponents(finishedRoot, current, nearestMountedAncestor) { - // We only have the top Fiber that was deleted but we need to recurse down its - // children to find all the terminal nodes. - var node = current; // Each iteration, currentParent is populated with node's host parent if not - // currentParentIsValid. - - var currentParentIsValid = false; // Note: these two variables *must* always be updated together. - - var currentParent; - var currentParentIsContainer; - - while (true) { - if (!currentParentIsValid) { - var parent = node.return; - - findParent: while (true) { - if (parent === null) { - throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.'); - } - - var parentStateNode = parent.stateNode; - - switch (parent.tag) { - case HostComponent: - currentParent = parentStateNode; - currentParentIsContainer = false; - break findParent; - - case HostRoot: - currentParent = parentStateNode.containerInfo; - currentParentIsContainer = true; - break findParent; - - case HostPortal: - currentParent = parentStateNode.containerInfo; - currentParentIsContainer = true; - break findParent; - } - - parent = parent.return; - } - - currentParentIsValid = true; - } - - if (node.tag === HostComponent || node.tag === HostText) { - commitNestedUnmounts(finishedRoot, node, nearestMountedAncestor); // After all the children have unmounted, it is now safe to remove the - // node from the tree. - - if (currentParentIsContainer) { - removeChildFromContainer(currentParent, node.stateNode); - } else { - removeChild(currentParent, node.stateNode); - } // Don't visit children because we already visited them. - - } else if ( node.tag === DehydratedFragment) { - - - if (currentParentIsContainer) { - clearSuspenseBoundaryFromContainer(currentParent, node.stateNode); - } else { - clearSuspenseBoundary(currentParent, node.stateNode); - } - } else if (node.tag === HostPortal) { - if (node.child !== null) { - // When we go into a portal, it becomes the parent to remove from. - // We will reassign it back when we pop the portal on the way up. - currentParent = node.stateNode.containerInfo; - currentParentIsContainer = true; // Visit children because portals might contain host components. - - node.child.return = node; - node = node.child; - continue; - } - } else { - commitUnmount(finishedRoot, node, nearestMountedAncestor); // Visit children because we may find more host components below. - - if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - } - - if (node === current) { - return; - } - - while (node.sibling === null) { - if (node.return === null || node.return === current) { - return; - } - - node = node.return; - - if (node.tag === HostPortal) { - // When we go out of the portal, we need to restore the parent. - // Since we don't keep a stack of them, we will search for it. - currentParentIsValid = false; - } - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - - function commitDeletion(finishedRoot, current, nearestMountedAncestor) { - if (supportsMutation) { - // Recursively delete all host nodes from the parent. - // Detach refs and call componentWillUnmount() on the whole subtree. - unmountHostComponents(finishedRoot, current, nearestMountedAncestor); - } else { - // Detach refs and call componentWillUnmount() on the whole subtree. - commitNestedUnmounts(finishedRoot, current, nearestMountedAncestor); - } - - detachFiberMutation(current); - } - - function commitWork(current, finishedWork) { - if (!supportsMutation) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: - { - commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); - commitHookEffectListMount(Insertion | HasEffect, finishedWork); // Layout effects are destroyed during the mutation phase so that all - // destroy functions for all fibers are called before any create functions. - // This prevents sibling component effects from interfering with each other, - // e.g. a destroy function in one component should never override a ref set - // by a create function in another component during the same commit. - // TODO: Check if we're inside an Offscreen subtree that disappeared - // during this commit. If so, we would have already unmounted its - // layout hooks. (However, since we null out the `destroy` function - // right before calling it, the behavior is already correct, so this - // would mostly be for modeling purposes.) - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } - - return; - } - - case Profiler: - { - return; - } - - case SuspenseComponent: - { - commitSuspenseCallback(finishedWork); - attachSuspenseRetryListeners(finishedWork); - return; - } - - case SuspenseListComponent: - { - attachSuspenseRetryListeners(finishedWork); - return; - } - - case HostRoot: - { - if (supportsHydration) { - if (current !== null) { - var prevRootState = current.memoizedState; - - if (prevRootState.isDehydrated) { - var root = finishedWork.stateNode; - commitHydratedContainer(root.containerInfo); - } - } - } - - break; - } - - case OffscreenComponent: - case LegacyHiddenComponent: - { - return; - } - } - - commitContainer(finishedWork); - return; - } - - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: - { - commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); - commitHookEffectListMount(Insertion | HasEffect, finishedWork); // Layout effects are destroyed during the mutation phase so that all - // destroy functions for all fibers are called before any create functions. - // This prevents sibling component effects from interfering with each other, - // e.g. a destroy function in one component should never override a ref set - // by a create function in another component during the same commit. - - if ( finishedWork.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); - } - - return; - } - - case ClassComponent: - { - return; - } - - case HostComponent: - { - var instance = finishedWork.stateNode; - - if (instance != null) { - // Commit the work prepared earlier. - var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps - // as the newProps. The updatePayload will contain the real change in - // this case. - - var oldProps = current !== null ? current.memoizedProps : newProps; - var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. - - var updatePayload = finishedWork.updateQueue; - finishedWork.updateQueue = null; - - if (updatePayload !== null) { - commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork); - } - } - - return; - } - - case HostText: - { - if (finishedWork.stateNode === null) { - throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.'); - } - - var textInstance = finishedWork.stateNode; - var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps - // as the newProps. The updatePayload will contain the real change in - // this case. - - var oldText = current !== null ? current.memoizedProps : newText; - commitTextUpdate(textInstance, oldText, newText); - return; - } - - case HostRoot: - { - if (supportsHydration) { - if (current !== null) { - var _prevRootState = current.memoizedState; - - if (_prevRootState.isDehydrated) { - var _root = finishedWork.stateNode; - commitHydratedContainer(_root.containerInfo); - } - } - } - - return; - } - - case Profiler: - { - return; - } - - case SuspenseComponent: - { - commitSuspenseCallback(finishedWork); - attachSuspenseRetryListeners(finishedWork); - return; - } - - case SuspenseListComponent: - { - attachSuspenseRetryListeners(finishedWork); - return; - } - - case IncompleteClassComponent: - { - return; - } - } - - throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); - } - - function commitSuspenseCallback(finishedWork) { - // TODO: Move this to passive phase - finishedWork.memoizedState; - } - - function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { - if (!supportsHydration) { - return; - } - - var newState = finishedWork.memoizedState; - - if (newState === null) { - var current = finishedWork.alternate; - - if (current !== null) { - var prevState = current.memoizedState; - - if (prevState !== null) { - var suspenseInstance = prevState.dehydrated; - - if (suspenseInstance !== null) { - commitHydratedSuspenseInstance(suspenseInstance); - } - } - } - } - } - - function attachSuspenseRetryListeners(finishedWork) { - // If this boundary just timed out, then it will have a set of wakeables. - // For each wakeable, attach a listener so that when it resolves, React - // attempts to re-render the boundary in the primary (pre-timeout) state. - var wakeables = finishedWork.updateQueue; - - if (wakeables !== null) { - finishedWork.updateQueue = null; - var retryCache = finishedWork.stateNode; - - if (retryCache === null) { - retryCache = finishedWork.stateNode = new PossiblyWeakSet(); - } - - wakeables.forEach(function (wakeable) { - // Memoize using the boundary fiber to prevent redundant listeners. - var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - - if (!retryCache.has(wakeable)) { - retryCache.add(wakeable); - - { - if (isDevToolsPresent) { - if (inProgressLanes !== null && inProgressRoot !== null) { - // If we have pending work still, associate the original updaters with it. - restorePendingUpdaters(inProgressRoot, inProgressLanes); - } else { - throw Error('Expected finished root and lanes to be set. This is a bug in React.'); - } - } - } - - wakeable.then(retry, retry); - } - }); - } - } // This function detects when a Suspense boundary goes from visible to hidden. - - function commitResetTextContent(current) { - if (!supportsMutation) { - return; - } - - resetTextContent(current.stateNode); - } - - function commitMutationEffects(root, firstChild, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - nextEffect = firstChild; - commitMutationEffects_begin(root, committedLanes); - inProgressLanes = null; - inProgressRoot = null; - } - - function commitMutationEffects_begin(root, lanes) { - while (nextEffect !== null) { - var fiber = nextEffect; // TODO: Should wrap this in flags check, too, as optimization - - var deletions = fiber.deletions; - - if (deletions !== null) { - for (var i = 0; i < deletions.length; i++) { - var childToDelete = deletions[i]; - - try { - commitDeletion(root, childToDelete, fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(childToDelete, fiber, error); - } - } - } - - var child = fiber.child; - - if ((fiber.subtreeFlags & MutationMask) !== NoFlags && child !== null) { - ensureCorrectReturnPointer(child, fiber); - nextEffect = child; - } else { - commitMutationEffects_complete(root, lanes); - } - } - } - - function commitMutationEffects_complete(root, lanes) { - while (nextEffect !== null) { - var fiber = nextEffect; - setCurrentFiber(fiber); - - try { - commitMutationEffectsOnFiber(fiber, root, lanes); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitMutationEffectsOnFiber(finishedWork, root, lanes) { - // TODO: The factoring of this phase could probably be improved. Consider - // switching on the type of work before checking the flags. That's what - // we do in all the other phases. I think this one is only different - // because of the shared reconciliation logic below. - var flags = finishedWork.flags; - - if (flags & ContentReset) { - commitResetTextContent(finishedWork); - } - - if (flags & Ref) { - var current = finishedWork.alternate; - - if (current !== null) { - commitDetachRef(current); - } - } - - if (flags & Visibility) { - switch (finishedWork.tag) { - case SuspenseComponent: - { - var newState = finishedWork.memoizedState; - var isHidden = newState !== null; - - if (isHidden) { - var _current = finishedWork.alternate; - var wasHidden = _current !== null && _current.memoizedState !== null; - - if (!wasHidden) { - // TODO: Move to passive phase - markCommitTimeOfFallback(); - } - } - - break; - } - - case OffscreenComponent: - { - var _newState = finishedWork.memoizedState; - - var _isHidden = _newState !== null; - - var _current2 = finishedWork.alternate; - - var _wasHidden = _current2 !== null && _current2.memoizedState !== null; - - var offscreenBoundary = finishedWork; - - if (supportsMutation) { - // TODO: This needs to run whenever there's an insertion or update - // inside a hidden Offscreen tree. - hideOrUnhideAllChildren(offscreenBoundary, _isHidden); - } - - { - if (_isHidden) { - if (!_wasHidden) { - if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) { - nextEffect = offscreenBoundary; - var offscreenChild = offscreenBoundary.child; - - while (offscreenChild !== null) { - nextEffect = offscreenChild; - disappearLayoutEffects_begin(offscreenChild); - offscreenChild = offscreenChild.sibling; - } - } - } - } - - break; - } - } - } - } // The following switch statement is only concerned about placement, - // updates, and deletions. To avoid needing to add a case for every possible - // bitmap value, we remove the secondary effects from the effect tag and - // switch on that value. - - - var primaryFlags = flags & (Placement | Update | Hydrating); - - switch (primaryFlags) { - case Placement: - { - commitPlacement(finishedWork); // Clear the "placement" from effect tag so that we know that this is - // inserted, before any life-cycles like componentDidMount gets called. - // TODO: findDOMNode doesn't rely on this any more but isMounted does - // and isMounted is deprecated anyway so we should be able to kill this. - - finishedWork.flags &= ~Placement; - break; - } - - case PlacementAndUpdate: - { - // Placement - commitPlacement(finishedWork); // Clear the "placement" from effect tag so that we know that this is - // inserted, before any life-cycles like componentDidMount gets called. - - finishedWork.flags &= ~Placement; // Update - - var _current3 = finishedWork.alternate; - commitWork(_current3, finishedWork); - break; - } - - case Hydrating: - { - finishedWork.flags &= ~Hydrating; - break; - } - - case HydratingAndUpdate: - { - finishedWork.flags &= ~Hydrating; // Update - - var _current4 = finishedWork.alternate; - commitWork(_current4, finishedWork); - break; - } - - case Update: - { - var _current5 = finishedWork.alternate; - commitWork(_current5, finishedWork); - break; - } - } - } - - function commitLayoutEffects(finishedWork, root, committedLanes) { - inProgressLanes = committedLanes; - inProgressRoot = root; - nextEffect = finishedWork; - commitLayoutEffects_begin(finishedWork, root, committedLanes); - inProgressLanes = null; - inProgressRoot = null; - } - - function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) { - // Suspense layout effects semantics don't change for legacy roots. - var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode; - - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - - if ( fiber.tag === OffscreenComponent && isModernRoot) { - // Keep track of the current Offscreen stack's state. - var isHidden = fiber.memoizedState !== null; - var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; - - if (newOffscreenSubtreeIsHidden) { - // The Offscreen tree is hidden. Skip over its layout effects. - commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); - continue; - } else { - // TODO (Offscreen) Also check: subtreeFlags & LayoutMask - var current = fiber.alternate; - var wasHidden = current !== null && current.memoizedState !== null; - var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; - var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; - var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root. - - offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; - - if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { - // This is the root of a reappearing boundary. Turn its layout effects - // back on. - nextEffect = fiber; - reappearLayoutEffects_begin(fiber); - } - - var child = firstChild; - - while (child !== null) { - nextEffect = child; - commitLayoutEffects_begin(child, // New root; bubble back up to here and stop. - root, committedLanes); - child = child.sibling; - } // Restore Offscreen state and resume in our-progress traversal. - - - nextEffect = fiber; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); - continue; - } - } - - if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) { - ensureCorrectReturnPointer(firstChild, fiber); - nextEffect = firstChild; - } else { - commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); - } - } - } - - function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) { - while (nextEffect !== null) { - var fiber = nextEffect; - - if ((fiber.flags & LayoutMask) !== NoFlags) { - var current = fiber.alternate; - setCurrentFiber(fiber); - - try { - commitLayoutEffectOnFiber(root, current, fiber, committedLanes); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - } - - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function disappearLayoutEffects_begin(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) - - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: - { - if ( fiber.mode & ProfileMode) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount(Layout, fiber, fiber.return); - } finally { - recordLayoutEffectDuration(fiber); - } - } else { - commitHookEffectListUnmount(Layout, fiber, fiber.return); - } - - break; - } - - case ClassComponent: - { - // TODO (Offscreen) Check: flags & RefStatic - safelyDetachRef(fiber, fiber.return); - var instance = fiber.stateNode; - - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount(fiber, fiber.return, instance); - } - - break; - } - - case HostComponent: - { - safelyDetachRef(fiber, fiber.return); - break; - } - - case OffscreenComponent: - { - // Check if this is a - var isHidden = fiber.memoizedState !== null; - - if (isHidden) { - // Nested Offscreen tree is already hidden. Don't disappear - // its effects. - disappearLayoutEffects_complete(subtreeRoot); - continue; - } - - break; - } - } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic - - - if (firstChild !== null) { - firstChild.return = fiber; - nextEffect = firstChild; - } else { - disappearLayoutEffects_complete(subtreeRoot); - } - } - } - - function disappearLayoutEffects_complete(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function reappearLayoutEffects_begin(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - - if (fiber.tag === OffscreenComponent) { - var isHidden = fiber.memoizedState !== null; - - if (isHidden) { - // Nested Offscreen tree is still hidden. Don't re-appear its effects. - reappearLayoutEffects_complete(subtreeRoot); - continue; - } - } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic - - - if (firstChild !== null) { - // This node may have been reused from a previous render, so we can't - // assume its return pointer is correct. - firstChild.return = fiber; - nextEffect = firstChild; - } else { - reappearLayoutEffects_complete(subtreeRoot); - } - } - } - - function reappearLayoutEffects_complete(subtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic - - setCurrentFiber(fiber); - - try { - reappearLayoutEffectsOnFiber(fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - // This node may have been reused from a previous render, so we can't - // assume its return pointer is correct. - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitPassiveMountEffects(root, finishedWork) { - nextEffect = finishedWork; - commitPassiveMountEffects_begin(finishedWork, root); - } - - function commitPassiveMountEffects_begin(subtreeRoot, root) { - while (nextEffect !== null) { - var fiber = nextEffect; - var firstChild = fiber.child; - - if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { - ensureCorrectReturnPointer(firstChild, fiber); - nextEffect = firstChild; - } else { - commitPassiveMountEffects_complete(subtreeRoot, root); - } - } - } - - function commitPassiveMountEffects_complete(subtreeRoot, root) { - while (nextEffect !== null) { - var fiber = nextEffect; - - if ((fiber.flags & Passive) !== NoFlags) { - setCurrentFiber(fiber); - - try { - commitPassiveMountOnFiber(root, fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - resetCurrentFiber(); - } - - if (fiber === subtreeRoot) { - nextEffect = null; - return; - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitPassiveMountOnFiber(finishedRoot, finishedWork) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( finishedWork.mode & ProfileMode) { - startPassiveEffectTimer(); - - try { - commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); - } finally { - recordPassiveEffectDuration(finishedWork); - } - } else { - commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); - } - - break; - } - } - } - - function commitPassiveUnmountEffects(firstChild) { - nextEffect = firstChild; - commitPassiveUnmountEffects_begin(); - } - - function commitPassiveUnmountEffects_begin() { - while (nextEffect !== null) { - var fiber = nextEffect; - var child = fiber.child; - - if ((nextEffect.flags & ChildDeletion) !== NoFlags) { - var deletions = fiber.deletions; - - if (deletions !== null) { - for (var i = 0; i < deletions.length; i++) { - var fiberToDelete = deletions[i]; - nextEffect = fiberToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber); - } - - { - // A fiber was deleted from this parent fiber, but it's still part of - // the previous (alternate) parent fiber's list of children. Because - // children are a linked list, an earlier sibling that's still alive - // will be connected to the deleted fiber via its `alternate`: - // - // live fiber - // --alternate--> previous live fiber - // --sibling--> deleted fiber - // - // We can't disconnect `alternate` on nodes that haven't been deleted - // yet, but we can disconnect the `sibling` and `child` pointers. - var previousFiber = fiber.alternate; - - if (previousFiber !== null) { - var detachedChild = previousFiber.child; - - if (detachedChild !== null) { - previousFiber.child = null; - - do { - var detachedSibling = detachedChild.sibling; - detachedChild.sibling = null; - detachedChild = detachedSibling; - } while (detachedChild !== null); - } - } - } - - nextEffect = fiber; - } - } - - if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { - ensureCorrectReturnPointer(child, fiber); - nextEffect = child; - } else { - commitPassiveUnmountEffects_complete(); - } - } - } - - function commitPassiveUnmountEffects_complete() { - while (nextEffect !== null) { - var fiber = nextEffect; - - if ((fiber.flags & Passive) !== NoFlags) { - setCurrentFiber(fiber); - commitPassiveUnmountOnFiber(fiber); - resetCurrentFiber(); - } - - var sibling = fiber.sibling; - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, fiber.return); - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } - } - - function commitPassiveUnmountOnFiber(finishedWork) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( finishedWork.mode & ProfileMode) { - startPassiveEffectTimer(); - commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); - recordPassiveEffectDuration(finishedWork); - } else { - commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); - } - - break; - } - } - } - - function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) { - while (nextEffect !== null) { - var fiber = nextEffect; // Deletion effects fire in parent -> child order - // TODO: Check if fiber has a PassiveStatic flag - - setCurrentFiber(fiber); - commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); - resetCurrentFiber(); - var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we - // do this, still need to handle `deletedTreeCleanUpLevel` correctly.) - - if (child !== null) { - ensureCorrectReturnPointer(child, fiber); - nextEffect = child; - } else { - commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot); - } - } - } - - function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) { - while (nextEffect !== null) { - var fiber = nextEffect; - var sibling = fiber.sibling; - var returnFiber = fiber.return; - - { - // Recursively traverse the entire deleted tree and clean up fiber fields. - // This is more aggressive than ideal, and the long term goal is to only - // have to detach the deleted tree at the root. - detachFiberAfterEffects(fiber); - - if (fiber === deletedSubtreeRoot) { - nextEffect = null; - return; - } - } - - if (sibling !== null) { - ensureCorrectReturnPointer(sibling, returnFiber); - nextEffect = sibling; - return; - } - - nextEffect = returnFiber; - } - } - - function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) { - switch (current.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - if ( current.mode & ProfileMode) { - startPassiveEffectTimer(); - commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); - recordPassiveEffectDuration(current); - } else { - commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); - } - - break; - } - } - } - - var didWarnWrongReturnPointer = false; - - function ensureCorrectReturnPointer(fiber, expectedReturnFiber) { - { - if (!didWarnWrongReturnPointer && fiber.return !== expectedReturnFiber) { - didWarnWrongReturnPointer = true; - - error('Internal React error: Return pointer is inconsistent ' + 'with parent.'); - } - } // TODO: Remove this assignment once we're confident that it won't break - // anything, by checking the warning logs for the above invariant - - - fiber.return = expectedReturnFiber; - } // TODO: Reuse reappearLayoutEffects traversal here? - - - function invokeLayoutEffectMountInDEV(fiber) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - try { - commitHookEffectListMount(Layout | HasEffect, fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - break; - } - - case ClassComponent: - { - var instance = fiber.stateNode; - - try { - instance.componentDidMount(); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - break; - } - } - } - } - - function invokePassiveEffectMountInDEV(fiber) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - try { - commitHookEffectListMount(Passive$1 | HasEffect, fiber); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - break; - } - } - } - } - - function invokeLayoutEffectUnmountInDEV(fiber) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - try { - commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - - break; - } - - case ClassComponent: - { - var instance = fiber.stateNode; - - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount(fiber, fiber.return, instance); - } - - break; - } - } - } - } - - function invokePassiveEffectUnmountInDEV(fiber) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - try { - commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); - } catch (error) { - reportUncaughtErrorInDEV(error); - captureCommitPhaseError(fiber, fiber.return, error); - } - } - } - } - } - - var COMPONENT_TYPE = 0; - var HAS_PSEUDO_CLASS_TYPE = 1; - var ROLE_TYPE = 2; - var TEST_NAME_TYPE = 3; - var TEXT_TYPE = 4; - - if (typeof Symbol === 'function' && Symbol.for) { - var symbolFor = Symbol.for; - COMPONENT_TYPE = symbolFor('selector.component'); - HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class'); - ROLE_TYPE = symbolFor('selector.role'); - TEST_NAME_TYPE = symbolFor('selector.test_id'); - TEXT_TYPE = symbolFor('selector.text'); - } - - function createComponentSelector(component) { - return { - $$typeof: COMPONENT_TYPE, - value: component - }; - } - function createHasPseudoClassSelector(selectors) { - return { - $$typeof: HAS_PSEUDO_CLASS_TYPE, - value: selectors - }; - } - function createRoleSelector(role) { - return { - $$typeof: ROLE_TYPE, - value: role - }; - } - function createTextSelector(text) { - return { - $$typeof: TEXT_TYPE, - value: text - }; - } - function createTestNameSelector(id) { - return { - $$typeof: TEST_NAME_TYPE, - value: id - }; - } - - function findFiberRootForHostRoot(hostRoot) { - var maybeFiber = getInstanceFromNode(hostRoot); - - if (maybeFiber != null) { - if (typeof maybeFiber.memoizedProps['data-testname'] !== 'string') { - throw new Error('Invalid host root specified. Should be either a React container or a node with a testname attribute.'); - } - - return maybeFiber; - } else { - var fiberRoot = findFiberRoot(hostRoot); - - if (fiberRoot === null) { - throw new Error('Could not find React container within specified host subtree.'); - } // The Flow type for FiberRoot is a little funky. - // createFiberRoot() cheats this by treating the root as :any and adding stateNode lazily. - - - return fiberRoot.stateNode.current; - } - } - - function matchSelector(fiber, selector) { - switch (selector.$$typeof) { - case COMPONENT_TYPE: - if (fiber.type === selector.value) { - return true; - } - - break; - - case HAS_PSEUDO_CLASS_TYPE: - return hasMatchingPaths(fiber, selector.value); - - case ROLE_TYPE: - if (fiber.tag === HostComponent) { - var node = fiber.stateNode; - - if (matchAccessibilityRole(node, selector.value)) { - return true; - } - } - - break; - - case TEXT_TYPE: - if (fiber.tag === HostComponent || fiber.tag === HostText) { - var textContent = getTextContent(fiber); - - if (textContent !== null && textContent.indexOf(selector.value) >= 0) { - return true; - } - } - - break; - - case TEST_NAME_TYPE: - if (fiber.tag === HostComponent) { - var dataTestID = fiber.memoizedProps['data-testname']; - - if (typeof dataTestID === 'string' && dataTestID.toLowerCase() === selector.value.toLowerCase()) { - return true; - } - } - - break; - - default: - throw new Error('Invalid selector type specified.'); - } - - return false; - } - - function selectorToString(selector) { - switch (selector.$$typeof) { - case COMPONENT_TYPE: - var displayName = getComponentNameFromType(selector.value) || 'Unknown'; - return "<" + displayName + ">"; - - case HAS_PSEUDO_CLASS_TYPE: - return ":has(" + (selectorToString(selector) || '') + ")"; - - case ROLE_TYPE: - return "[role=\"" + selector.value + "\"]"; - - case TEXT_TYPE: - return "\"" + selector.value + "\""; - - case TEST_NAME_TYPE: - return "[data-testname=\"" + selector.value + "\"]"; - - default: - throw new Error('Invalid selector type specified.'); - } - } - - function findPaths(root, selectors) { - var matchingFibers = []; - var stack = [root, 0]; - var index = 0; - - while (index < stack.length) { - var fiber = stack[index++]; - var selectorIndex = stack[index++]; - var selector = selectors[selectorIndex]; - - if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { - continue; - } else { - while (selector != null && matchSelector(fiber, selector)) { - selectorIndex++; - selector = selectors[selectorIndex]; - } - } - - if (selectorIndex === selectors.length) { - matchingFibers.push(fiber); - } else { - var child = fiber.child; - - while (child !== null) { - stack.push(child, selectorIndex); - child = child.sibling; - } - } - } - - return matchingFibers; - } // Same as findPaths but with eager bailout on first match - - - function hasMatchingPaths(root, selectors) { - var stack = [root, 0]; - var index = 0; - - while (index < stack.length) { - var fiber = stack[index++]; - var selectorIndex = stack[index++]; - var selector = selectors[selectorIndex]; - - if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { - continue; - } else { - while (selector != null && matchSelector(fiber, selector)) { - selectorIndex++; - selector = selectors[selectorIndex]; - } - } - - if (selectorIndex === selectors.length) { - return true; - } else { - var child = fiber.child; - - while (child !== null) { - stack.push(child, selectorIndex); - child = child.sibling; - } - } - } - - return false; - } - - function findAllNodes(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var root = findFiberRootForHostRoot(hostRoot); - var matchingFibers = findPaths(root, selectors); - var instanceRoots = []; - var stack = Array.from(matchingFibers); - var index = 0; - - while (index < stack.length) { - var node = stack[index++]; - - if (node.tag === HostComponent) { - if (isHiddenSubtree(node)) { - continue; - } - - instanceRoots.push(node.stateNode); - } else { - var child = node.child; - - while (child !== null) { - stack.push(child); - child = child.sibling; - } - } - } - - return instanceRoots; - } - function getFindAllNodesFailureDescription(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var root = findFiberRootForHostRoot(hostRoot); - var maxSelectorIndex = 0; - var matchedNames = []; // The logic of this loop should be kept in sync with findPaths() - - var stack = [root, 0]; - var index = 0; - - while (index < stack.length) { - var fiber = stack[index++]; - var selectorIndex = stack[index++]; - var selector = selectors[selectorIndex]; - - if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { - continue; - } else if (matchSelector(fiber, selector)) { - matchedNames.push(selectorToString(selector)); - selectorIndex++; - - if (selectorIndex > maxSelectorIndex) { - maxSelectorIndex = selectorIndex; - } - } - - if (selectorIndex < selectors.length) { - var child = fiber.child; - - while (child !== null) { - stack.push(child, selectorIndex); - child = child.sibling; - } - } - } - - if (maxSelectorIndex < selectors.length) { - var unmatchedNames = []; - - for (var i = maxSelectorIndex; i < selectors.length; i++) { - unmatchedNames.push(selectorToString(selectors[i])); - } - - return 'findAllNodes was able to match part of the selector:\n' + (" " + matchedNames.join(' > ') + "\n\n") + 'No matching component was found for:\n' + (" " + unmatchedNames.join(' > ')); - } - - return null; - } - function findBoundingRects(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var instanceRoots = findAllNodes(hostRoot, selectors); - var boundingRects = []; - - for (var i = 0; i < instanceRoots.length; i++) { - boundingRects.push(getBoundingRect(instanceRoots[i])); - } - - for (var _i = boundingRects.length - 1; _i > 0; _i--) { - var targetRect = boundingRects[_i]; - var targetLeft = targetRect.x; - var targetRight = targetLeft + targetRect.width; - var targetTop = targetRect.y; - var targetBottom = targetTop + targetRect.height; - - for (var j = _i - 1; j >= 0; j--) { - if (_i !== j) { - var otherRect = boundingRects[j]; - var otherLeft = otherRect.x; - var otherRight = otherLeft + otherRect.width; - var otherTop = otherRect.y; - var otherBottom = otherTop + otherRect.height; // Merging all rects to the minimums set would be complicated, - // but we can handle the most common cases: - // 1. completely overlapping rects - // 2. adjacent rects that are the same width or height (e.g. items in a list) - // - // Even given the above constraints, - // we still won't end up with the fewest possible rects without doing multiple passes, - // but it's good enough for this purpose. - - if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) { - // Complete overlapping rects; remove the inner one. - boundingRects.splice(_i, 1); - break; - } else if (targetLeft === otherLeft && targetRect.width === otherRect.width && !(otherBottom < targetTop) && !(otherTop > targetBottom)) { - // Adjacent vertical rects; merge them. - if (otherTop > targetTop) { - otherRect.height += otherTop - targetTop; - otherRect.y = targetTop; - } - - if (otherBottom < targetBottom) { - otherRect.height = targetBottom - otherTop; - } - - boundingRects.splice(_i, 1); - break; - } else if (targetTop === otherTop && targetRect.height === otherRect.height && !(otherRight < targetLeft) && !(otherLeft > targetRight)) { - // Adjacent horizontal rects; merge them. - if (otherLeft > targetLeft) { - otherRect.width += otherLeft - targetLeft; - otherRect.x = targetLeft; - } - - if (otherRight < targetRight) { - otherRect.width = targetRight - otherLeft; - } - - boundingRects.splice(_i, 1); - break; - } - } - } - } - - return boundingRects; - } - function focusWithin(hostRoot, selectors) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var root = findFiberRootForHostRoot(hostRoot); - var matchingFibers = findPaths(root, selectors); - var stack = Array.from(matchingFibers); - var index = 0; - - while (index < stack.length) { - var fiber = stack[index++]; - - if (isHiddenSubtree(fiber)) { - continue; - } - - if (fiber.tag === HostComponent) { - var node = fiber.stateNode; - - if (setFocusIfFocusable(node)) { - return true; - } - } - - var child = fiber.child; - - while (child !== null) { - stack.push(child); - child = child.sibling; - } - } - - return false; - } - var commitHooks = []; - function onCommitRoot$1() { - if (supportsTestSelectors) { - commitHooks.forEach(function (commitHook) { - return commitHook(); - }); - } - } - function observeVisibleRects(hostRoot, selectors, callback, options) { - if (!supportsTestSelectors) { - throw new Error('Test selector API is not supported by this renderer.'); - } - - var instanceRoots = findAllNodes(hostRoot, selectors); - - var _setupIntersectionObs = setupIntersectionObserver(instanceRoots, callback, options), - disconnect = _setupIntersectionObs.disconnect, - observe = _setupIntersectionObs.observe, - unobserve = _setupIntersectionObs.unobserve; // When React mutates the host environment, we may need to change what we're listening to. - - - var commitHook = function () { - var nextInstanceRoots = findAllNodes(hostRoot, selectors); - instanceRoots.forEach(function (target) { - if (nextInstanceRoots.indexOf(target) < 0) { - unobserve(target); - } - }); - nextInstanceRoots.forEach(function (target) { - if (instanceRoots.indexOf(target) < 0) { - observe(target); - } - }); - }; - - commitHooks.push(commitHook); - return { - disconnect: function () { - // Stop listening for React mutations: - var index = commitHooks.indexOf(commitHook); - - if (index >= 0) { - commitHooks.splice(index, 1); - } // Disconnect the host observer: - - - disconnect(); - } - }; - } - - var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; - function isLegacyActEnvironment(fiber) { - { - // Legacy mode. We preserve the behavior of React 17's act. It assumes an - // act environment whenever `jest` is defined, but you can still turn off - // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly - // to false. - var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global - typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest - - var jestIsDefined = typeof jest !== 'undefined'; - return warnsIfNotActing && jestIsDefined && isReactActEnvironmentGlobal !== false; - } - } - function isConcurrentActEnvironment() { - { - var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global - typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; - - if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { - // TODO: Include link to relevant documentation page. - error('The current testing environment is not configured to support ' + 'act(...)'); - } - - return isReactActEnvironmentGlobal; - } - } - - var ceil = Math.ceil; - var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, - ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, - ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig, - ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue; - var NoContext = - /* */ - 0; - var BatchedContext = - /* */ - 1; - var RenderContext = - /* */ - 2; - var CommitContext = - /* */ - 4; - var RootInProgress = 0; - var RootFatalErrored = 1; - var RootErrored = 2; - var RootSuspended = 3; - var RootSuspendedWithDelay = 4; - var RootCompleted = 5; - var RootDidNotComplete = 6; // Describes where we are in the React execution stack - - var executionContext = NoContext; // The root we're working on - - var workInProgressRoot = null; // The fiber we're working on - - var workInProgress = null; // The lanes we're rendering - - var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree - // This is a superset of the lanes we started working on at the root. The only - // case where it's different from `workInProgressRootRenderLanes` is when we - // enter a subtree that is hidden and needs to be unhidden: Suspense and - // Offscreen component. - // - // Most things in the work loop should deal with workInProgressRootRenderLanes. - // Most things in begin/complete phases should deal with subtreeRenderLanes. - - var subtreeRenderLanes = NoLanes; - var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc. - - var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown - - var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's - // includes unprocessed updates, not work in bailed out children. - - var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render. - - var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event). - - var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase. - - var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI. - // We will log them once the tree commits. - - var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train - // model where we don't commit new loading states in too quick succession. - - var globalMostRecentFallbackTime = 0; - var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering - // more and prefer CPU suspense heuristics instead. - - var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU - // suspense heuristics and opt out of rendering more content. - - var RENDER_TIMEOUT_MS = 500; - - function resetRenderTimer() { - workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS; - } - - function getRenderTargetTime() { - return workInProgressRootRenderTargetTime; - } - var hasUncaughtError = false; - var firstUncaughtError = null; - var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true; - var rootDoesHavePassiveEffects = false; - var rootWithPendingPassiveEffects = null; - var pendingPassiveEffectsLanes = NoLanes; - var pendingPassiveProfilerEffects = []; - - var NESTED_UPDATE_LIMIT = 50; - var nestedUpdateCount = 0; - var rootWithNestedUpdates = null; - var NESTED_PASSIVE_UPDATE_LIMIT = 50; - var nestedPassiveUpdateCount = 0; // If two updates are scheduled within the same event, we should treat their - // event times as simultaneous, even if the actual clock time has advanced - // between the first and second call. - - var currentEventTime = NoTimestamp; - var currentEventTransitionLane = NoLanes; - function getWorkInProgressRoot() { - return workInProgressRoot; - } - function requestEventTime() { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - // We're inside React, so it's fine to read the actual time. - return now$1(); - } // We're not inside React, so we may be in the middle of a browser event. - - - if (currentEventTime !== NoTimestamp) { - // Use the same start time for all updates until we enter React again. - return currentEventTime; - } // This is the first update since React yielded. Compute a new start time. - - - currentEventTime = now$1(); - return currentEventTime; - } - function requestUpdateLane(fiber) { - // Special cases - var mode = fiber.mode; - - if ((mode & ConcurrentMode) === NoMode) { - return SyncLane; - } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { - // This is a render phase update. These are not officially supported. The - // old behavior is to give this the same "thread" (lanes) as - // whatever is currently rendering. So if you call `setState` on a component - // that happens later in the same render, it will flush. Ideally, we want to - // remove the special case and treat them as if they came from an - // interleaved event. Regardless, this pattern is not officially supported. - // This behavior is only a fallback. The flag only exists until we can roll - // out the setState warning, since existing code might accidentally rely on - // the current behavior. - return pickArbitraryLane(workInProgressRootRenderLanes); - } - - var isTransition = requestCurrentTransition() !== NoTransition; - - if (isTransition) { - if ( ReactCurrentBatchConfig$2.transition !== null) { - var transition = ReactCurrentBatchConfig$2.transition; - - if (!transition._updatedFibers) { - transition._updatedFibers = new Set(); - } - - transition._updatedFibers.add(fiber); - } // The algorithm for assigning an update to a lane should be stable for all - // updates at the same priority within the same event. To do this, the - // inputs to the algorithm must be the same. - // - // The trick we use is to cache the first of each of these inputs within an - // event. Then reset the cached values once we can be sure the event is - // over. Our heuristic for that is whenever we enter a concurrent work loop. - - - if (currentEventTransitionLane === NoLane) { - // All transitions within the same event are assigned the same lane. - currentEventTransitionLane = claimNextTransitionLane(); - } - - return currentEventTransitionLane; - } // Updates originating inside certain React methods, like flushSync, have - // their priority set by tracking it with a context variable. - // - // The opaque type returned by the host config is internally a lane, so we can - // use that directly. - // TODO: Move this type conversion to the event priority module. - - - var updateLane = getCurrentUpdatePriority(); - - if (updateLane !== NoLane) { - return updateLane; - } // This update originated outside React. Ask the host environment for an - // appropriate priority, based on the type of event. - // - // The opaque type returned by the host config is internally a lane, so we can - // use that directly. - // TODO: Move this type conversion to the event priority module. - - - var eventLane = getCurrentEventPriority(); - return eventLane; - } - - function requestRetryLane(fiber) { - // This is a fork of `requestUpdateLane` designed specifically for Suspense - // "retries" — a special update that attempts to flip a Suspense boundary - // from its placeholder state to its primary/resolved state. - // Special cases - var mode = fiber.mode; - - if ((mode & ConcurrentMode) === NoMode) { - return SyncLane; - } - - return claimNextRetryLane(); - } - - function scheduleUpdateOnFiber(fiber, lane, eventTime) { - checkForNestedUpdates(); - var root = markUpdateLaneFromFiberToRoot(fiber, lane); - - if (root === null) { - return null; - } // Mark that the root has a pending update. - - - markRootUpdated(root, lane, eventTime); - - if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) { - // This update was dispatched during the render phase. This is a mistake - // if the update originates from user space (with the exception of local - // hook updates, which are handled differently and don't reach this - // function), but there are some internal React features that use this as - // an implementation detail, like selective hydration. - warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase - } else { - // This is a normal update, scheduled from outside the render phase. For - // example, during an input event. - { - if (isDevToolsPresent) { - addFiberToLanesMap(root, fiber, lane); - } - } - - warnIfUpdatesNotWrappedWithActDEV(fiber); - - if (root === workInProgressRoot) { - // TODO: Consolidate with `isInterleavedUpdate` check - // Received an update to a tree that's in the middle of rendering. Mark - // that there was an interleaved update work on this root. Unless the - // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render - // phase update. In that case, we don't treat render phase updates as if - // they were interleaved, for backwards compat reasons. - if ( (executionContext & RenderContext) === NoContext) { - workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); - } - - if (workInProgressRootExitStatus === RootSuspendedWithDelay) { - // The root already suspended with a delay, which means this render - // definitely won't finish. Since we have a new update, let's mark it as - // suspended now, right before marking the incoming update. This has the - // effect of interrupting the current render and switching to the update. - // TODO: Make sure this doesn't override pings that happen while we've - // already started rendering. - markRootSuspended$1(root, workInProgressRootRenderLanes); - } - } - - ensureRootIsScheduled(root, eventTime); - - if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. - !( ReactCurrentActQueue$1.isBatchingLegacy)) { - // Flush the synchronous work now, unless we're already working or inside - // a batch. This is intentionally inside scheduleUpdateOnFiber instead of - // scheduleCallbackForFiber to preserve the ability to schedule a callback - // without immediately flushing it. We only do this for user-initiated - // updates, to preserve historical behavior of legacy mode. - resetRenderTimer(); - flushSyncCallbacksOnlyInLegacyMode(); - } - } - - return root; - } - function scheduleInitialHydrationOnRoot(root, lane, eventTime) { - // This is a special fork of scheduleUpdateOnFiber that is only used to - // schedule the initial hydration of a root that has just been created. Most - // of the stuff in scheduleUpdateOnFiber can be skipped. - // - // The main reason for this separate path, though, is to distinguish the - // initial children from subsequent updates. In fully client-rendered roots - // (createRoot instead of hydrateRoot), all top-level renders are modeled as - // updates, but hydration roots are special because the initial render must - // match what was rendered on the server. - var current = root.current; - current.lanes = lane; - markRootUpdated(root, lane, eventTime); - ensureRootIsScheduled(root, eventTime); - } // This is split into a separate function so we can mark a fiber with pending - // work without treating it as a typical update that originates from an event; - // e.g. retrying a Suspense boundary isn't an update, but it does schedule work - // on a fiber. - - function markUpdateLaneFromFiberToRoot(sourceFiber, lane) { - // Update the source fiber's lanes - sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); - var alternate = sourceFiber.alternate; - - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, lane); - } - - { - if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) { - warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); - } - } // Walk the parent path to the root and update the child lanes. - - - var node = sourceFiber; - var parent = sourceFiber.return; - - while (parent !== null) { - parent.childLanes = mergeLanes(parent.childLanes, lane); - alternate = parent.alternate; - - if (alternate !== null) { - alternate.childLanes = mergeLanes(alternate.childLanes, lane); - } else { - { - if ((parent.flags & (Placement | Hydrating)) !== NoFlags) { - warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); - } - } - } - - node = parent; - parent = parent.return; - } - - if (node.tag === HostRoot) { - var root = node.stateNode; - return root; - } else { - return null; - } - } - - function isInterleavedUpdate(fiber, lane) { - return (// TODO: Optimize slightly by comparing to root that fiber belongs to. - // Requires some refactoring. Not a big deal though since it's rare for - // concurrent apps to have more than a single root. - workInProgressRoot !== null && (fiber.mode & ConcurrentMode) !== NoMode && ( // If this is a render phase update (i.e. UNSAFE_componentWillReceiveProps), - // then don't treat this as an interleaved update. This pattern is - // accompanied by a warning but we haven't fully deprecated it yet. We can - // remove once the deferRenderPhaseUpdateToNextBatch flag is enabled. - (executionContext & RenderContext) === NoContext) - ); - } // Use this function to schedule a task for a root. There's only one task per - // root; if a task was already scheduled, we'll check to make sure the priority - // of the existing task is the same as the priority of the next level that the - // root has work on. This function is called on every update, and right before - // exiting a task. - - function ensureRootIsScheduled(root, currentTime) { - var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as - // expired so we know to work on those next. - - markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority. - - var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); - - if (nextLanes === NoLanes) { - // Special case: There's nothing to work on. - if (existingCallbackNode !== null) { - cancelCallback$1(existingCallbackNode); - } - - root.callbackNode = null; - root.callbackPriority = NoLane; - return; - } // We use the highest priority lane to represent the priority of the callback. - - - var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it. - - var existingCallbackPriority = root.callbackPriority; - - if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a - // Scheduler task, rather than an `act` task, cancel it and re-scheduled - // on the `act` queue. - !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { - { - // If we're going to re-use an existing task, it needs to exist. - // Assume that discrete update microtasks are non-cancellable and null. - // TODO: Temporary until we confirm this warning is not fired. - if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) { - error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.'); - } - } // The priority hasn't changed. We can reuse the existing task. Exit. - - - return; - } - - if (existingCallbackNode != null) { - // Cancel the existing callback. We'll schedule a new one below. - cancelCallback$1(existingCallbackNode); - } // Schedule a new callback. - - - var newCallbackNode; - - if (newCallbackPriority === SyncLane) { - // Special case: Sync React callbacks are scheduled on a special - // internal queue - if (root.tag === LegacyRoot) { - if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) { - ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; - } - - scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); - } else { - scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); - } - - if (supportsMicrotasks) { - // Flush the queue in a microtask. - if ( ReactCurrentActQueue$1.current !== null) { - // Inside `act`, use our internal `act` queue so that these get flushed - // at the end of the current scope even when using the sync version - // of `act`. - ReactCurrentActQueue$1.current.push(flushSyncCallbacks); - } else { - scheduleMicrotask(function () { - // In Safari, appending an iframe forces microtasks to run. - // https://github.com/facebook/react/issues/22459 - // We don't support running callbacks in the middle of render - // or commit so we need to check against that. - if (executionContext === NoContext) { - // It's only safe to do this conditionally because we always - // check for pending work before we exit the task. - flushSyncCallbacks(); - } - }); - } - } else { - // Flush the queue in an Immediate task. - scheduleCallback$1(ImmediatePriority, flushSyncCallbacks); - } - - newCallbackNode = null; - } else { - var schedulerPriorityLevel; - - switch (lanesToEventPriority(nextLanes)) { - case DiscreteEventPriority: - schedulerPriorityLevel = ImmediatePriority; - break; - - case ContinuousEventPriority: - schedulerPriorityLevel = UserBlockingPriority; - break; - - case DefaultEventPriority: - schedulerPriorityLevel = NormalPriority; - break; - - case IdleEventPriority: - schedulerPriorityLevel = IdlePriority; - break; - - default: - schedulerPriorityLevel = NormalPriority; - break; - } - - newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root)); - } - - root.callbackPriority = newCallbackPriority; - root.callbackNode = newCallbackNode; - } // This is the entry point for every concurrent task, i.e. anything that - // goes through Scheduler. - - - function performConcurrentWorkOnRoot(root, didTimeout) { - { - resetNestedUpdateFlag(); - } // Since we know we're in a React event, we can clear the current - // event time. The next update will compute a new event time. - - - currentEventTime = NoTimestamp; - currentEventTransitionLane = NoLanes; - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Should not already be working.'); - } // Flush any pending passive effects before deciding which lanes to work on, - // in case they schedule additional work. - - - var originalCallbackNode = root.callbackNode; - var didFlushPassiveEffects = flushPassiveEffects(); - - if (didFlushPassiveEffects) { - // Something in the passive effect phase may have canceled the current task. - // Check if the task node for this root was changed. - if (root.callbackNode !== originalCallbackNode) { - // The current task was canceled. Exit. We don't need to call - // `ensureRootIsScheduled` because the check above implies either that - // there's a new task, or that there's no remaining work on this root. - return null; - } - } // Determine the next lanes to work on, using the fields stored - // on the root. - - - var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); - - if (lanes === NoLanes) { - // Defensive coding. This is never expected to happen. - return null; - } // We disable time-slicing in some cases: if the work has been CPU-bound - // for too long ("expired" work, to prevent starvation), or we're in - // sync-updates-by-default mode. - // TODO: We only check `didTimeout` defensively, to account for a Scheduler - // bug we're still investigating. Once the bug in Scheduler is fixed, - // we can remove this, since we track expiration ourselves. - - - var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout); - var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes); - - if (exitStatus !== RootInProgress) { - if (exitStatus === RootErrored) { - // If something threw an error, try rendering one more time. We'll - // render synchronously to block concurrent data mutations, and we'll - // includes all pending updates are included. If it still fails after - // the second attempt, we'll give up and commit the resulting tree. - var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - - if (errorRetryLanes !== NoLanes) { - lanes = errorRetryLanes; - exitStatus = recoverFromConcurrentError(root, errorRetryLanes); - } - } - - if (exitStatus === RootFatalErrored) { - var fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended$1(root, lanes); - ensureRootIsScheduled(root, now$1()); - throw fatalError; - } - - if (exitStatus === RootDidNotComplete) { - // The render unwound without completing the tree. This happens in special - // cases where need to exit the current render without producing a - // consistent tree or committing. - // - // This should only happen during a concurrent render, not a discrete or - // synchronous update. We should have already checked for this when we - // unwound the stack. - markRootSuspended$1(root, lanes); - } else { - // The render completed. - // Check if this render may have yielded to a concurrent event, and if so, - // confirm that any newly rendered stores are consistent. - // TODO: It's possible that even a concurrent render may never have yielded - // to the main thread, if it was fast enough, or if it expired. We could - // skip the consistency check in that case, too. - var renderWasConcurrent = !includesBlockingLane(root, lanes); - var finishedWork = root.current.alternate; - - if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { - // A store was mutated in an interleaved event. Render again, - // synchronously, to block further mutations. - exitStatus = renderRootSync(root, lanes); // We need to check again if something threw - - if (exitStatus === RootErrored) { - var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - - if (_errorRetryLanes !== NoLanes) { - lanes = _errorRetryLanes; - exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any - // concurrent events. - } - } - - if (exitStatus === RootFatalErrored) { - var _fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended$1(root, lanes); - ensureRootIsScheduled(root, now$1()); - throw _fatalError; - } - } // We now have a consistent tree. The next step is either to commit it, - // or, if something suspended, wait to commit it after a timeout. - - - root.finishedWork = finishedWork; - root.finishedLanes = lanes; - finishConcurrentRender(root, exitStatus, lanes); - } - } - - ensureRootIsScheduled(root, now$1()); - - if (root.callbackNode === originalCallbackNode) { - // The task node scheduled for this root is the same one that's - // currently executed. Need to return a continuation. - return performConcurrentWorkOnRoot.bind(null, root); - } - - return null; - } - - function recoverFromConcurrentError(root, errorRetryLanes) { - // If an error occurred during hydration, discard server response and fall - // back to client side render. - // Before rendering again, save the errors from the previous attempt. - var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; - - if (isRootDehydrated(root)) { - // The shell failed to hydrate. Set a flag to force a client rendering - // during the next attempt. To do this, we call prepareFreshStack now - // to create the root work-in-progress fiber. This is a bit weird in terms - // of factoring, because it relies on renderRootSync not calling - // prepareFreshStack again in the call below, which happens because the - // root and lanes haven't changed. - // - // TODO: I think what we should do is set ForceClientRender inside - // throwException, like we do for nested Suspense boundaries. The reason - // it's here instead is so we can switch to the synchronous work loop, too. - // Something to consider for a future refactor. - var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); - rootWorkInProgress.flags |= ForceClientRender; - - { - errorHydratingContainer(root.containerInfo); - } - } - - var exitStatus = renderRootSync(root, errorRetryLanes); - - if (exitStatus !== RootErrored) { - // Successfully finished rendering on retry - // The errors from the failed first attempt have been recovered. Add - // them to the collection of recoverable errors. We'll log them in the - // commit phase. - var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; - workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors - // from the first attempt, to preserve the causal sequence. - - if (errorsFromSecondAttempt !== null) { - queueRecoverableErrors(errorsFromSecondAttempt); - } - } - - return exitStatus; - } - - function queueRecoverableErrors(errors) { - if (workInProgressRootRecoverableErrors === null) { - workInProgressRootRecoverableErrors = errors; - } else { - workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); - } - } - - function finishConcurrentRender(root, exitStatus, lanes) { - switch (exitStatus) { - case RootInProgress: - case RootFatalErrored: - { - throw new Error('Root did not complete. This is a bug in React.'); - } - // Flow knows about invariant, so it complains if I add a break - // statement, but eslint doesn't know about invariant, so it complains - // if I do. eslint-disable-next-line no-fallthrough - - case RootErrored: - { - // We should have already attempted to retry this tree. If we reached - // this point, it errored again. Commit it. - commitRoot(root, workInProgressRootRecoverableErrors); - break; - } - - case RootSuspended: - { - markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we - // should immediately commit it or wait a bit. - - if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope - !shouldForceFlushFallbacksInDEV()) { - // This render only included retries, no updates. Throttle committing - // retries so that we don't show too many loading states too quickly. - var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now$1(); // Don't bother with a very short suspense time. - - if (msUntilTimeout > 10) { - var nextLanes = getNextLanes(root, NoLanes); - - if (nextLanes !== NoLanes) { - // There's additional work on this root. - break; - } - - var suspendedLanes = root.suspendedLanes; - - if (!isSubsetOfLanes(suspendedLanes, lanes)) { - // We should prefer to render the fallback of at the last - // suspended level. Ping the last suspended level to try - // rendering it again. - // FIXME: What if the suspended lanes are Idle? Should not restart. - requestEventTime(); - markRootPinged(root, suspendedLanes); - break; - } // The render is suspended, it hasn't timed out, and there's no - // lower priority work to do. Instead of committing the fallback - // immediately, wait for more data to arrive. - - - root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors), msUntilTimeout); - break; - } - } // The work expired. Commit immediately. - - - commitRoot(root, workInProgressRootRecoverableErrors); - break; - } - - case RootSuspendedWithDelay: - { - markRootSuspended$1(root, lanes); - - if (includesOnlyTransitions(lanes)) { - // This is a transition, so we should exit without committing a - // placeholder and without scheduling a timeout. Delay indefinitely - // until we receive more data. - break; - } - - if (!shouldForceFlushFallbacksInDEV()) { - // This is not a transition, but we did trigger an avoided state. - // Schedule a placeholder to display after a short delay, using the Just - // Noticeable Difference. - // TODO: Is the JND optimization worth the added complexity? If this is - // the only reason we track the event time, then probably not. - // Consider removing. - var mostRecentEventTime = getMostRecentEventTime(root, lanes); - var eventTimeMs = mostRecentEventTime; - var timeElapsedMs = now$1() - eventTimeMs; - - var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time. - - - if (_msUntilTimeout > 10) { - // Instead of committing the fallback immediately, wait for more data - // to arrive. - root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors), _msUntilTimeout); - break; - } - } // Commit the placeholder. - - - commitRoot(root, workInProgressRootRecoverableErrors); - break; - } - - case RootCompleted: - { - // The work completed. Ready to commit. - commitRoot(root, workInProgressRootRecoverableErrors); - break; - } - - default: - { - throw new Error('Unknown root exit status.'); - } - } - } - - function isRenderConsistentWithExternalStores(finishedWork) { - // Search the rendered tree for external store reads, and check whether the - // stores were mutated in a concurrent event. Intentionally using an iterative - // loop instead of recursion so we can exit early. - var node = finishedWork; - - while (true) { - if (node.flags & StoreConsistency) { - var updateQueue = node.updateQueue; - - if (updateQueue !== null) { - var checks = updateQueue.stores; - - if (checks !== null) { - for (var i = 0; i < checks.length; i++) { - var check = checks[i]; - var getSnapshot = check.getSnapshot; - var renderedValue = check.value; - - try { - if (!objectIs(getSnapshot(), renderedValue)) { - // Found an inconsistent store. - return false; - } - } catch (error) { - // If `getSnapshot` throws, return `false`. This will schedule - // a re-render, and the error will be rethrown during render. - return false; - } - } - } - } - } - - var child = node.child; - - if (node.subtreeFlags & StoreConsistency && child !== null) { - child.return = node; - node = child; - continue; - } - - if (node === finishedWork) { - return true; - } - - while (node.sibling === null) { - if (node.return === null || node.return === finishedWork) { - return true; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } // Flow doesn't know this is unreachable, but eslint does - // eslint-disable-next-line no-unreachable - - - return true; - } - - function markRootSuspended$1(root, suspendedLanes) { - // When suspending, we should always exclude lanes that were pinged or (more - // rarely, since we try to avoid it) updated during the render phase. - // TODO: Lol maybe there's a better way to factor this besides this - // obnoxiously named function :) - suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); - suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); - markRootSuspended(root, suspendedLanes); - } // This is the entry point for synchronous tasks that don't go - // through Scheduler - - - function performSyncWorkOnRoot(root) { - { - syncNestedUpdateFlag(); - } - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Should not already be working.'); - } - - flushPassiveEffects(); - var lanes = getNextLanes(root, NoLanes); - - if (!includesSomeLane(lanes, SyncLane)) { - // There's no remaining sync work left. - ensureRootIsScheduled(root, now$1()); - return null; - } - - var exitStatus = renderRootSync(root, lanes); - - if (root.tag !== LegacyRoot && exitStatus === RootErrored) { - // If something threw an error, try rendering one more time. We'll render - // synchronously to block concurrent data mutations, and we'll includes - // all pending updates are included. If it still fails after the second - // attempt, we'll give up and commit the resulting tree. - var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - - if (errorRetryLanes !== NoLanes) { - lanes = errorRetryLanes; - exitStatus = recoverFromConcurrentError(root, errorRetryLanes); - } - } - - if (exitStatus === RootFatalErrored) { - var fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended$1(root, lanes); - ensureRootIsScheduled(root, now$1()); - throw fatalError; - } - - if (exitStatus === RootDidNotComplete) { - throw new Error('Root did not complete. This is a bug in React.'); - } // We now have a consistent tree. Because this is a sync render, we - // will commit it even if something suspended. - - - var finishedWork = root.current.alternate; - root.finishedWork = finishedWork; - root.finishedLanes = lanes; - commitRoot(root, workInProgressRootRecoverableErrors); // Before exiting, make sure there's a callback scheduled for the next - // pending level. - - ensureRootIsScheduled(root, now$1()); - return null; - } - - function flushRoot(root, lanes) { - if (lanes !== NoLanes) { - markRootEntangled(root, mergeLanes(lanes, SyncLane)); - ensureRootIsScheduled(root, now$1()); - - if ((executionContext & (RenderContext | CommitContext)) === NoContext) { - resetRenderTimer(); - flushSyncCallbacks(); - } - } - } - function deferredUpdates(fn) { - var previousPriority = getCurrentUpdatePriority(); - var prevTransition = ReactCurrentBatchConfig$2.transition; - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DefaultEventPriority); - return fn(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - } - } - function batchedUpdates(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer - // most batchedUpdates-like method. - - if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. - !( ReactCurrentActQueue$1.isBatchingLegacy)) { - resetRenderTimer(); - flushSyncCallbacksOnlyInLegacyMode(); - } - } - } - function discreteUpdates(fn, a, b, c, d) { - var previousPriority = getCurrentUpdatePriority(); - var prevTransition = ReactCurrentBatchConfig$2.transition; - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - return fn(a, b, c, d); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - - if (executionContext === NoContext) { - resetRenderTimer(); - } - } - } // Overload the definition to the two valid signatures. - // Warning, this opts-out of checking the function body. - - // eslint-disable-next-line no-redeclare - function flushSync(fn) { - // In legacy mode, we flush pending passive effects at the beginning of the - // next event, not at the end of the previous one. - if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { - flushPassiveEffects(); - } - - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - var prevTransition = ReactCurrentBatchConfig$2.transition; - var previousPriority = getCurrentUpdatePriority(); - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - - if (fn) { - return fn(); - } else { - return undefined; - } - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. - // Note that this will happen even if batchedUpdates is higher up - // the stack. - - if ((executionContext & (RenderContext | CommitContext)) === NoContext) { - flushSyncCallbacks(); - } - } - } - function isAlreadyRendering() { - // Used by the renderer to print a warning if certain APIs are called from - // the wrong context. - return (executionContext & (RenderContext | CommitContext)) !== NoContext; - } - function flushControlled(fn) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - var prevTransition = ReactCurrentBatchConfig$2.transition; - var previousPriority = getCurrentUpdatePriority(); - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - fn(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - executionContext = prevExecutionContext; - - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - resetRenderTimer(); - flushSyncCallbacks(); - } - } - } - function pushRenderLanes(fiber, lanes) { - push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); - subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); - } - function popRenderLanes(fiber) { - subtreeRenderLanes = subtreeRenderLanesCursor.current; - pop(subtreeRenderLanesCursor, fiber); - } - - function prepareFreshStack(root, lanes) { - root.finishedWork = null; - root.finishedLanes = NoLanes; - var timeoutHandle = root.timeoutHandle; - - if (timeoutHandle !== noTimeout) { - // The root previous suspended and scheduled a timeout to commit a fallback - // state. Now that we have additional work, cancel the timeout. - root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above - - cancelTimeout(timeoutHandle); - } - - if (workInProgress !== null) { - var interruptedWork = workInProgress.return; - - while (interruptedWork !== null) { - var current = interruptedWork.alternate; - unwindInterruptedWork(current, interruptedWork); - interruptedWork = interruptedWork.return; - } - } - - workInProgressRoot = root; - var rootWorkInProgress = createWorkInProgress(root.current, null); - workInProgress = rootWorkInProgress; - workInProgressRootRenderLanes = subtreeRenderLanes = lanes; - workInProgressRootExitStatus = RootInProgress; - workInProgressRootFatalError = null; - workInProgressRootSkippedLanes = NoLanes; - workInProgressRootInterleavedUpdatedLanes = NoLanes; - workInProgressRootPingedLanes = NoLanes; - workInProgressRootConcurrentErrors = null; - workInProgressRootRecoverableErrors = null; - enqueueInterleavedUpdates(); - - { - ReactStrictModeWarnings.discardPendingWarnings(); - } - - return rootWorkInProgress; - } - - function handleError(root, thrownValue) { - do { - var erroredWork = workInProgress; - - try { - // Reset module-level state that was set during the render phase. - resetContextDependencies(); - resetHooksAfterThrow(); - resetCurrentFiber(); // TODO: I found and added this missing line while investigating a - // separate issue. Write a regression test using string refs. - - ReactCurrentOwner$2.current = null; - - if (erroredWork === null || erroredWork.return === null) { - // Expected to be working on a non-root fiber. This is a fatal error - // because there's no ancestor that can handle it; the root is - // supposed to capture all errors that weren't caught by an error - // boundary. - workInProgressRootExitStatus = RootFatalErrored; - workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next - // sibling, or the parent if there are no siblings. But since the root - // has no siblings nor a parent, we set it to null. Usually this is - // handled by `completeUnitOfWork` or `unwindWork`, but since we're - // intentionally not calling those, we need set it here. - // TODO: Consider calling `unwindWork` to pop the contexts. - - workInProgress = null; - return; - } - - if (enableProfilerTimer && erroredWork.mode & ProfileMode) { - // Record the time spent rendering before an error was thrown. This - // avoids inaccurate Profiler durations in the case of a - // suspended render. - stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); - } - - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - - if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') { - var wakeable = thrownValue; - markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes); - } else { - markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes); - } - } - - throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); - completeUnitOfWork(erroredWork); - } catch (yetAnotherThrownValue) { - // Something in the return path also threw. - thrownValue = yetAnotherThrownValue; - - if (workInProgress === erroredWork && erroredWork !== null) { - // If this boundary has already errored, then we had trouble processing - // the error. Bubble it to the next boundary. - erroredWork = erroredWork.return; - workInProgress = erroredWork; - } else { - erroredWork = workInProgress; - } - - continue; - } // Return to the normal work loop. - - - return; - } while (true); - } - - function pushDispatcher() { - var prevDispatcher = ReactCurrentDispatcher$2.current; - ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; - - if (prevDispatcher === null) { - // The React isomorphic package does not include a default dispatcher. - // Instead the first renderer will lazily attach one, in order to give - // nicer error messages. - return ContextOnlyDispatcher; - } else { - return prevDispatcher; - } - } - - function popDispatcher(prevDispatcher) { - ReactCurrentDispatcher$2.current = prevDispatcher; - } - - function markCommitTimeOfFallback() { - globalMostRecentFallbackTime = now$1(); - } - function markSkippedUpdateLanes(lane) { - workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes); - } - function renderDidSuspend() { - if (workInProgressRootExitStatus === RootInProgress) { - workInProgressRootExitStatus = RootSuspended; - } - } - function renderDidSuspendDelayIfPossible() { - if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) { - workInProgressRootExitStatus = RootSuspendedWithDelay; - } // Check if there are updates that we skipped tree that might have unblocked - // this render. - - - if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { - // Mark the current render as suspended so that we switch to working on - // the updates that were skipped. Usually we only suspend at the end of - // the render phase. - // TODO: We should probably always mark the root as suspended immediately - // (inside this function), since by suspending at the end of the render - // phase introduces a potential mistake where we suspend lanes that were - // pinged or updated while we were rendering. - markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); - } - } - function renderDidError(error) { - if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { - workInProgressRootExitStatus = RootErrored; - } - - if (workInProgressRootConcurrentErrors === null) { - workInProgressRootConcurrentErrors = [error]; - } else { - workInProgressRootConcurrentErrors.push(error); - } - } // Called during render to determine if anything has suspended. - // Returns false if we're not sure. - - function renderHasNotSuspendedYet() { - // If something errored or completed, we can't really be sure, - // so those are false. - return workInProgressRootExitStatus === RootInProgress; - } - - function renderRootSync(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - - if (memoizedUpdaters.size > 0) { - restorePendingUpdaters(root, workInProgressRootRenderLanes); - memoizedUpdaters.clear(); - } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. - // If we bailout on this work, we'll move them back (like above). - // It's important to move them now in case the work spawns more work at the same priority with different updaters. - // That way we can keep the current update and future updates separate. - - - movePendingFibersToMemoized(root, lanes); - } - } - prepareFreshStack(root, lanes); - } - - { - markRenderStarted(lanes); - } - - do { - try { - workLoopSync(); - break; - } catch (thrownValue) { - handleError(root, thrownValue); - } - } while (true); - - resetContextDependencies(); - executionContext = prevExecutionContext; - popDispatcher(prevDispatcher); - - if (workInProgress !== null) { - // This is a sync render, so we should have finished the whole tree. - throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.'); - } - - { - markRenderStopped(); - } // Set this to null to indicate there's no in-progress render. - - - workInProgressRoot = null; - workInProgressRootRenderLanes = NoLanes; - return workInProgressRootExitStatus; - } // The work loop is an extremely hot path. Tell Closure not to inline it. - - /** @noinline */ - - - function workLoopSync() { - // Already timed out, so perform work without checking if we need to yield. - while (workInProgress !== null) { - performUnitOfWork(workInProgress); - } - } - - function renderRootConcurrent(root, lanes) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - - if (memoizedUpdaters.size > 0) { - restorePendingUpdaters(root, workInProgressRootRenderLanes); - memoizedUpdaters.clear(); - } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. - // If we bailout on this work, we'll move them back (like above). - // It's important to move them now in case the work spawns more work at the same priority with different updaters. - // That way we can keep the current update and future updates separate. - - - movePendingFibersToMemoized(root, lanes); - } - } - resetRenderTimer(); - prepareFreshStack(root, lanes); - } - - { - markRenderStarted(lanes); - } - - do { - try { - workLoopConcurrent(); - break; - } catch (thrownValue) { - handleError(root, thrownValue); - } - } while (true); - - resetContextDependencies(); - popDispatcher(prevDispatcher); - executionContext = prevExecutionContext; - - - if (workInProgress !== null) { - // Still work remaining. - { - markRenderYielded(); - } - - return RootInProgress; - } else { - // Completed the tree. - { - markRenderStopped(); - } // Set this to null to indicate there's no in-progress render. - - - workInProgressRoot = null; - workInProgressRootRenderLanes = NoLanes; // Return the final exit status. - - return workInProgressRootExitStatus; - } - } - /** @noinline */ - - - function workLoopConcurrent() { - // Perform work until Scheduler asks us to yield - while (workInProgress !== null && !shouldYield()) { - performUnitOfWork(workInProgress); - } - } - - function performUnitOfWork(unitOfWork) { - // The current, flushed, state of this fiber is the alternate. Ideally - // nothing should rely on this, but relying on it here means that we don't - // need an additional field on the work in progress. - var current = unitOfWork.alternate; - setCurrentFiber(unitOfWork); - var next; - - if ( (unitOfWork.mode & ProfileMode) !== NoMode) { - startProfilerTimer(unitOfWork); - next = beginWork$1(current, unitOfWork, subtreeRenderLanes); - stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); - } else { - next = beginWork$1(current, unitOfWork, subtreeRenderLanes); - } - - resetCurrentFiber(); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - - if (next === null) { - // If this doesn't spawn new work, complete the current work. - completeUnitOfWork(unitOfWork); - } else { - workInProgress = next; - } - - ReactCurrentOwner$2.current = null; - } - - function completeUnitOfWork(unitOfWork) { - // Attempt to complete the current unit of work, then move to the next - // sibling. If there are no more siblings, return to the parent fiber. - var completedWork = unitOfWork; - - do { - // The current, flushed, state of this fiber is the alternate. Ideally - // nothing should rely on this, but relying on it here means that we don't - // need an additional field on the work in progress. - var current = completedWork.alternate; - var returnFiber = completedWork.return; // Check if the work completed or if something threw. - - if ((completedWork.flags & Incomplete) === NoFlags) { - setCurrentFiber(completedWork); - var next = void 0; - - if ( (completedWork.mode & ProfileMode) === NoMode) { - next = completeWork(current, completedWork, subtreeRenderLanes); - } else { - startProfilerTimer(completedWork); - next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error. - - stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); - } - - resetCurrentFiber(); - - if (next !== null) { - // Completing this fiber spawned new work. Work on that next. - workInProgress = next; - return; - } - } else { - // This fiber did not complete because something threw. Pop values off - // the stack without entering the complete phase. If this is a boundary, - // capture values if possible. - var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes. - - - if (_next !== null) { - // If completing this work spawned new work, do that next. We'll come - // back here again. - // Since we're restarting, remove anything that is not a host effect - // from the effect tag. - _next.flags &= HostEffectMask; - workInProgress = _next; - return; - } - - if ( (completedWork.mode & ProfileMode) !== NoMode) { - // Record the render duration for the fiber that errored. - stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing. - - var actualDuration = completedWork.actualDuration; - var child = completedWork.child; - - while (child !== null) { - actualDuration += child.actualDuration; - child = child.sibling; - } - - completedWork.actualDuration = actualDuration; - } - - if (returnFiber !== null) { - // Mark the parent fiber as incomplete and clear its subtree flags. - returnFiber.flags |= Incomplete; - returnFiber.subtreeFlags = NoFlags; - returnFiber.deletions = null; - } else { - // We've unwound all the way to the root. - workInProgressRootExitStatus = RootDidNotComplete; - workInProgress = null; - return; - } - } - - var siblingFiber = completedWork.sibling; - - if (siblingFiber !== null) { - // If there is more work to do in this returnFiber, do that next. - workInProgress = siblingFiber; - return; - } // Otherwise, return to the parent - - - completedWork = returnFiber; // Update the next thing we're working on in case something throws. - - workInProgress = completedWork; - } while (completedWork !== null); // We've reached the root. - - - if (workInProgressRootExitStatus === RootInProgress) { - workInProgressRootExitStatus = RootCompleted; - } - } - - function commitRoot(root, recoverableErrors) { - // TODO: This no longer makes any sense. We already wrap the mutation and - // layout phases. Should be able to remove. - var previousUpdateLanePriority = getCurrentUpdatePriority(); - var prevTransition = ReactCurrentBatchConfig$2.transition; - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - commitRootImpl(root, recoverableErrors, previousUpdateLanePriority); - } finally { - ReactCurrentBatchConfig$2.transition = prevTransition; - setCurrentUpdatePriority(previousUpdateLanePriority); - } - - return null; - } - - function commitRootImpl(root, recoverableErrors, renderPriorityLevel) { - do { - // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which - // means `flushPassiveEffects` will sometimes result in additional - // passive effects. So we need to keep flushing in a loop until there are - // no more pending effects. - // TODO: Might be better if `flushPassiveEffects` did not automatically - // flush synchronous work at the end, to avoid factoring hazards like this. - flushPassiveEffects(); - } while (rootWithPendingPassiveEffects !== null); - - flushRenderPhaseStrictModeWarningsInDEV(); - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Should not already be working.'); - } - - var finishedWork = root.finishedWork; - var lanes = root.finishedLanes; - - { - markCommitStarted(lanes); - } - - if (finishedWork === null) { - - { - markCommitStopped(); - } - - return null; - } else { - { - if (lanes === NoLanes) { - error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.'); - } - } - } - - root.finishedWork = null; - root.finishedLanes = NoLanes; - - if (finishedWork === root.current) { - throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.'); - } // commitRoot never returns a continuation; it always finishes synchronously. - // So we can clear these now to allow a new callback to be scheduled. - - - root.callbackNode = null; - root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first - // pending time is whatever is left on the root fiber. - - var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); - markRootFinished(root, remainingLanes); - - if (root === workInProgressRoot) { - // We can reset these now that they are finished. - workInProgressRoot = null; - workInProgress = null; - workInProgressRootRenderLanes = NoLanes; - } // If there are pending passive effects, schedule a callback to process them. - // Do this as early as possible, so it is queued before anything else that - // might get scheduled in the commit phase. (See #16714.) - // TODO: Delete all other places that schedule the passive effect callback - // They're redundant. - - - if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { - if (!rootDoesHavePassiveEffects) { - rootDoesHavePassiveEffects = true; - scheduleCallback$1(NormalPriority, function () { - flushPassiveEffects(); // This render triggered passive effects: release the root cache pool - // *after* passive effects fire to avoid freeing a cache pool that may - // be referenced by a node in the tree (HostRoot, Cache boundary etc) - - return null; - }); - } - } // Check if there are any effects in the whole tree. - // TODO: This is left over from the effect list implementation, where we had - // to check for the existence of `firstEffect` to satisfy Flow. I think the - // only other reason this optimization exists is because it affects profiling. - // Reconsider whether this is necessary. - - - var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; - var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; - - if (subtreeHasEffects || rootHasEffect) { - var prevTransition = ReactCurrentBatchConfig$2.transition; - ReactCurrentBatchConfig$2.transition = null; - var previousPriority = getCurrentUpdatePriority(); - setCurrentUpdatePriority(DiscreteEventPriority); - var prevExecutionContext = executionContext; - executionContext |= CommitContext; // Reset this to null before calling lifecycles - - ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass - // of the effect list for each phase: all mutation effects come before all - // layout effects, and so on. - // The first phase a "before mutation" phase. We use this phase to read the - // state of the host tree right before we mutate it. This is where - // getSnapshotBeforeUpdate is called. - - commitBeforeMutationEffects(root, finishedWork); - - { - // Mark the current commit time to be shared by all Profilers in this - // batch. This enables them to be grouped later. - recordCommitTime(); - } - - - commitMutationEffects(root, finishedWork, lanes); - - resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after - // the mutation phase, so that the previous tree is still current during - // componentWillUnmount, but before the layout phase, so that the finished - // work is current during componentDidMount/Update. - - root.current = finishedWork; // The next phase is the layout phase, where we call effects that read - - { - markLayoutEffectsStarted(lanes); - } - - commitLayoutEffects(finishedWork, root, lanes); - - { - markLayoutEffectsStopped(); - } - // opportunity to paint. - - - requestPaint(); - executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value. - - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; - } else { - // No effects. - root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were - // no effects. - // TODO: Maybe there's a better way to report this. - - { - recordCommitTime(); - } - } - - var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; - - if (rootDoesHavePassiveEffects) { - // This commit has passive effects. Stash a reference to them. But don't - // schedule a callback until after flushing layout work. - rootDoesHavePassiveEffects = false; - rootWithPendingPassiveEffects = root; - pendingPassiveEffectsLanes = lanes; - } // Read this again, since an effect might have updated it - - - remainingLanes = root.pendingLanes; // Check if there's remaining work on this root - // TODO: This is part of the `componentDidCatch` implementation. Its purpose - // is to detect whether something might have called setState inside - // `componentDidCatch`. The mechanism is known to be flawed because `setState` - // inside `componentDidCatch` is itself flawed — that's why we recommend - // `getDerivedStateFromError` instead. However, it could be improved by - // checking if remainingLanes includes Sync work, instead of whether there's - // any work remaining at all (which would also include stuff like Suspense - // retries or transitions). It's been like this for a while, though, so fixing - // it probably isn't that urgent. - - if (remainingLanes === NoLanes) { - // If there's no remaining work, we can clear the set of already failed - // error boundaries. - legacyErrorBoundariesThatAlreadyFailed = null; - } - - { - if (!rootDidHavePassiveEffects) { - commitDoubleInvokeEffectsInDEV(root.current, false); - } - } - - onCommitRoot(finishedWork.stateNode, renderPriorityLevel); - - { - if (isDevToolsPresent) { - root.memoizedUpdaters.clear(); - } - } - - { - onCommitRoot$1(); - } // Always call this before exiting `commitRoot`, to ensure that any - // additional work on this root is scheduled. - - - ensureRootIsScheduled(root, now$1()); - - if (recoverableErrors !== null) { - // There were errors during this render, but recovered from them without - // needing to surface it to the UI. We log them here. - var onRecoverableError = root.onRecoverableError; - - for (var i = 0; i < recoverableErrors.length; i++) { - var recoverableError = recoverableErrors[i]; - onRecoverableError(recoverableError); - } - } - - if (hasUncaughtError) { - hasUncaughtError = false; - var error$1 = firstUncaughtError; - firstUncaughtError = null; - throw error$1; - } // If the passive effects are the result of a discrete render, flush them - // synchronously at the end of the current task so that the result is - // immediately observable. Otherwise, we assume that they are not - // order-dependent and do not need to be observed by external systems, so we - // can wait until after paint. - // TODO: We can optimize this by not scheduling the callback earlier. Since we - // currently schedule the callback in multiple places, will wait until those - // are consolidated. - - - if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) { - flushPassiveEffects(); - } // Read this again, since a passive effect might have updated it - - - remainingLanes = root.pendingLanes; - - if (includesSomeLane(remainingLanes, SyncLane)) { - { - markNestedUpdateScheduled(); - } // Count the number of times the root synchronously re-renders without - // finishing. If there are too many, it indicates an infinite update loop. - - - if (root === rootWithNestedUpdates) { - nestedUpdateCount++; - } else { - nestedUpdateCount = 0; - rootWithNestedUpdates = root; - } - } else { - nestedUpdateCount = 0; - } // If layout work was scheduled, flush it now. - - - flushSyncCallbacks(); - - { - markCommitStopped(); - } - - return null; - } - - function flushPassiveEffects() { - // Returns whether passive effects were flushed. - // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should - // probably just combine the two functions. I believe they were only separate - // in the first place because we used to wrap it with - // `Scheduler.runWithPriority`, which accepts a function. But now we track the - // priority within React itself, so we can mutate the variable directly. - if (rootWithPendingPassiveEffects !== null) { - var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); - var priority = lowerEventPriority(DefaultEventPriority, renderPriority); - var prevTransition = ReactCurrentBatchConfig$2.transition; - var previousPriority = getCurrentUpdatePriority(); - - try { - ReactCurrentBatchConfig$2.transition = null; - setCurrentUpdatePriority(priority); - return flushPassiveEffectsImpl(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig$2.transition = prevTransition; // Once passive effects have run for the tree - giving components a - } - } - - return false; - } - function enqueuePendingPassiveProfilerEffect(fiber) { - { - pendingPassiveProfilerEffects.push(fiber); - - if (!rootDoesHavePassiveEffects) { - rootDoesHavePassiveEffects = true; - scheduleCallback$1(NormalPriority, function () { - flushPassiveEffects(); - return null; - }); - } - } - } - - function flushPassiveEffectsImpl() { - if (rootWithPendingPassiveEffects === null) { - return false; - } - - var root = rootWithPendingPassiveEffects; - var lanes = pendingPassiveEffectsLanes; - rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects. - // Figure out why and fix it. It's not causing any known issues (probably - // because it's only used for profiling), but it's a refactor hazard. - - pendingPassiveEffectsLanes = NoLanes; - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Cannot flush passive effects while already rendering.'); - } - - { - markPassiveEffectsStarted(lanes); - } - - var prevExecutionContext = executionContext; - executionContext |= CommitContext; - commitPassiveUnmountEffects(root.current); - commitPassiveMountEffects(root, root.current); // TODO: Move to commitPassiveMountEffects - - { - var profilerEffects = pendingPassiveProfilerEffects; - pendingPassiveProfilerEffects = []; - - for (var i = 0; i < profilerEffects.length; i++) { - var _fiber = profilerEffects[i]; - commitPassiveEffectDurations(root, _fiber); - } - } - - { - markPassiveEffectsStopped(); - } - - { - commitDoubleInvokeEffectsInDEV(root.current, true); - } - - executionContext = prevExecutionContext; - flushSyncCallbacks(); // If additional passive effects were scheduled, increment a counter. If this - // exceeds the limit, we'll fire a warning. - - nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1; // TODO: Move to commitPassiveMountEffects - - onPostCommitRoot(root); - - { - var stateNode = root.current.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - - return true; - } - - function isAlreadyFailedLegacyErrorBoundary(instance) { - return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); - } - function markLegacyErrorBoundaryAsFailed(instance) { - if (legacyErrorBoundariesThatAlreadyFailed === null) { - legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); - } else { - legacyErrorBoundariesThatAlreadyFailed.add(instance); - } - } - - function prepareToThrowUncaughtError(error) { - if (!hasUncaughtError) { - hasUncaughtError = true; - firstUncaughtError = error; - } - } - - var onUncaughtError = prepareToThrowUncaughtError; - - function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { - var errorInfo = createCapturedValue(error, sourceFiber); - var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); - enqueueUpdate(rootFiber, update); - var eventTime = requestEventTime(); - var root = markUpdateLaneFromFiberToRoot(rootFiber, SyncLane); - - if (root !== null) { - markRootUpdated(root, SyncLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - } - - function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { - if (sourceFiber.tag === HostRoot) { - // Error was thrown at the root. There is no parent, so the root - // itself should capture it. - captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1); - return; - } - - var fiber = null; - - { - fiber = nearestMountedAncestor; - } - - while (fiber !== null) { - if (fiber.tag === HostRoot) { - captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1); - return; - } else if (fiber.tag === ClassComponent) { - var ctor = fiber.type; - var instance = fiber.stateNode; - - if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) { - var errorInfo = createCapturedValue(error$1, sourceFiber); - var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); - enqueueUpdate(fiber, update); - var eventTime = requestEventTime(); - var root = markUpdateLaneFromFiberToRoot(fiber, SyncLane); - - if (root !== null) { - markRootUpdated(root, SyncLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - - return; - } - } - - fiber = fiber.return; - } - - { - // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning - // will fire for errors that are thrown by destroy functions inside deleted - // trees. What it should instead do is propagate the error to the parent of - // the deleted tree. In the meantime, do not add this warning to the - // allowlist; this is only for our internal use. - error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1); - } - } - function pingSuspendedRoot(root, wakeable, pingedLanes) { - var pingCache = root.pingCache; - - if (pingCache !== null) { - // The wakeable resolved, so we no longer need to memoize, because it will - // never be thrown again. - pingCache.delete(wakeable); - } - - var eventTime = requestEventTime(); - markRootPinged(root, pingedLanes); - warnIfSuspenseResolutionNotWrappedWithActDEV(root); - - if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { - // Received a ping at the same priority level at which we're currently - // rendering. We might want to restart this render. This should mirror - // the logic of whether or not a root suspends once it completes. - // TODO: If we're rendering sync either due to Sync, Batched or expired, - // we should probably never restart. - // If we're suspended with delay, or if it's a retry, we'll always suspend - // so we can always restart. - if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now$1() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { - // Restart from the root. - prepareFreshStack(root, NoLanes); - } else { - // Even though we can't restart right now, we might get an - // opportunity later. So we mark this render as having a ping. - workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); - } - } - - ensureRootIsScheduled(root, eventTime); - } - - function retryTimedOutBoundary(boundaryFiber, retryLane) { - // The boundary fiber (a Suspense component or SuspenseList component) - // previously was rendered in its fallback state. One of the promises that - // suspended it has resolved, which means at least part of the tree was - // likely unblocked. Try rendering again, at a new lanes. - if (retryLane === NoLane) { - // TODO: Assign this to `suspenseState.retryLane`? to avoid - // unnecessary entanglement? - retryLane = requestRetryLane(boundaryFiber); - } // TODO: Special case idle priority? - - - var eventTime = requestEventTime(); - var root = markUpdateLaneFromFiberToRoot(boundaryFiber, retryLane); - - if (root !== null) { - markRootUpdated(root, retryLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - } - - function retryDehydratedSuspenseBoundary(boundaryFiber) { - var suspenseState = boundaryFiber.memoizedState; - var retryLane = NoLane; - - if (suspenseState !== null) { - retryLane = suspenseState.retryLane; - } - - retryTimedOutBoundary(boundaryFiber, retryLane); - } - function resolveRetryWakeable(boundaryFiber, wakeable) { - var retryLane = NoLane; // Default - - var retryCache; - - { - switch (boundaryFiber.tag) { - case SuspenseComponent: - retryCache = boundaryFiber.stateNode; - var suspenseState = boundaryFiber.memoizedState; - - if (suspenseState !== null) { - retryLane = suspenseState.retryLane; - } - - break; - - case SuspenseListComponent: - retryCache = boundaryFiber.stateNode; - break; - - default: - throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.'); - } - } - - if (retryCache !== null) { - // The wakeable resolved, so we no longer need to memoize, because it will - // never be thrown again. - retryCache.delete(wakeable); - } - - retryTimedOutBoundary(boundaryFiber, retryLane); - } // Computes the next Just Noticeable Difference (JND) boundary. - // The theory is that a person can't tell the difference between small differences in time. - // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable - // difference in the experience. However, waiting for longer might mean that we can avoid - // showing an intermediate loading state. The longer we have already waited, the harder it - // is to tell small differences in time. Therefore, the longer we've already waited, - // the longer we can wait additionally. At some point we have to give up though. - // We pick a train model where the next boundary commits at a consistent schedule. - // These particular numbers are vague estimates. We expect to adjust them based on research. - - function jnd(timeElapsed) { - return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960; - } - - function checkForNestedUpdates() { - if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { - nestedUpdateCount = 0; - rootWithNestedUpdates = null; - throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.'); - } - - { - if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { - nestedPassiveUpdateCount = 0; - - error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.'); - } - } - } - - function flushRenderPhaseStrictModeWarningsInDEV() { - { - ReactStrictModeWarnings.flushLegacyContextWarning(); - - { - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); - } - } - } - - function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) { - { - // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects - // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level. - // Maybe not a big deal since this is DEV only behavior. - setCurrentFiber(fiber); - invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); - - if (hasPassiveEffects) { - invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); - } - - invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); - - if (hasPassiveEffects) { - invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); - } - - resetCurrentFiber(); - } - } - - function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) { - { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - var current = firstChild; - var subtreeRoot = null; - - while (current !== null) { - var primarySubtreeFlag = current.subtreeFlags & fiberFlags; - - if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) { - current = current.child; - } else { - if ((current.flags & fiberFlags) !== NoFlags) { - invokeEffectFn(current); - } - - if (current.sibling !== null) { - current = current.sibling; - } else { - current = subtreeRoot = current.return; - } - } - } - } - } - - var didWarnStateUpdateForNotYetMountedComponent = null; - - function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { - { - if ((executionContext & RenderContext) !== NoContext) { - // We let the other warning about render phase updates deal with this one. - return; - } - - if (!(fiber.mode & ConcurrentMode)) { - return; - } - - var tag = fiber.tag; - - if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) { - // Only warn for user-defined components, not internal ones like Suspense. - return; - } // We show the whole stack but dedupe on the top component's name because - // the problematic code almost always lies inside that component. - - - var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent'; - - if (didWarnStateUpdateForNotYetMountedComponent !== null) { - if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { - return; - } - - didWarnStateUpdateForNotYetMountedComponent.add(componentName); - } else { - didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]); - } - - var previousFiber = current; - - try { - setCurrentFiber(fiber); - - error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.'); - } finally { - if (previousFiber) { - setCurrentFiber(fiber); - } else { - resetCurrentFiber(); - } - } - } - } - - var beginWork$1; - - { - var dummyFiber = null; - - beginWork$1 = function (current, unitOfWork, lanes) { - // If a component throws an error, we replay it again in a synchronously - // dispatched event, so that the debugger will treat it as an uncaught - // error See ReactErrorUtils for more information. - // Before entering the begin phase, copy the work-in-progress onto a dummy - // fiber. If beginWork throws, we'll use this to reset the state. - var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); - - try { - return beginWork(current, unitOfWork, lanes); - } catch (originalError) { - if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') { - // Don't replay promises. Treat everything else like an error. - throw originalError; - } // Keep this code in sync with handleError; any changes here must have - // corresponding changes there. - - - resetContextDependencies(); - resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the - // same fiber again. - // Unwind the failed stack frame - - unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber. - - assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); - - if ( unitOfWork.mode & ProfileMode) { - // Reset the profiler timer. - startProfilerTimer(unitOfWork); - } // Run beginWork again. - - - invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes); - - if (hasCaughtError()) { - var replayError = clearCaughtError(); - - if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) { - // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. - originalError._suppressLogging = true; - } - } // We always throw the original error in case the second render pass is not idempotent. - // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. - - - throw originalError; - } - }; - } - - var didWarnAboutUpdateInRender = false; - var didWarnAboutUpdateInRenderForAnotherComponent; - - { - didWarnAboutUpdateInRenderForAnotherComponent = new Set(); - } - - function warnAboutRenderPhaseUpdatesInDEV(fiber) { - { - if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) { - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: - { - var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed. - - var dedupeKey = renderingComponentName; - - if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { - didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); - var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown'; - - error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName); - } - - break; - } - - case ClassComponent: - { - if (!didWarnAboutUpdateInRender) { - error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.'); - - didWarnAboutUpdateInRender = true; - } - - break; - } - } - } - } - } - - function restorePendingUpdaters(root, lanes) { - { - if (isDevToolsPresent) { - var memoizedUpdaters = root.memoizedUpdaters; - memoizedUpdaters.forEach(function (schedulingFiber) { - addFiberToLanesMap(root, schedulingFiber, lanes); - }); // This function intentionally does not clear memoized updaters. - // Those may still be relevant to the current commit - // and a future one (e.g. Suspense). - } - } - } - var fakeActCallbackNode = {}; - - function scheduleCallback$1(priorityLevel, callback) { - { - // If we're currently inside an `act` scope, bypass Scheduler and push to - // the `act` queue instead. - var actQueue = ReactCurrentActQueue$1.current; - - if (actQueue !== null) { - actQueue.push(callback); - return fakeActCallbackNode; - } else { - return scheduleCallback(priorityLevel, callback); - } - } - } - - function cancelCallback$1(callbackNode) { - if ( callbackNode === fakeActCallbackNode) { - return; - } // In production, always call Scheduler. This function will be stripped out. - - - return cancelCallback(callbackNode); - } - - function shouldForceFlushFallbacksInDEV() { - // Never force flush in production. This function should get stripped out. - return ReactCurrentActQueue$1.current !== null; - } - - function warnIfUpdatesNotWrappedWithActDEV(fiber) { - { - if (fiber.mode & ConcurrentMode) { - if (!isConcurrentActEnvironment()) { - // Not in an act environment. No need to warn. - return; - } - } else { - // Legacy mode has additional cases where we suppress a warning. - if (!isLegacyActEnvironment()) { - // Not in an act environment. No need to warn. - return; - } - - if (executionContext !== NoContext) { - // Legacy mode doesn't warn if the update is batched, i.e. - // batchedUpdates or flushSync. - return; - } - - if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { - // For backwards compatibility with pre-hooks code, legacy mode only - // warns for updates that originate from a hook. - return; - } - } - - if (ReactCurrentActQueue$1.current === null) { - var previousFiber = current; - - try { - setCurrentFiber(fiber); - - error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber)); - } finally { - if (previousFiber) { - setCurrentFiber(fiber); - } else { - resetCurrentFiber(); - } - } - } - } - } - - function warnIfSuspenseResolutionNotWrappedWithActDEV(root) { - { - if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) { - error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + ' /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act'); - } - } - } - - /* eslint-disable react-internal/prod-error-codes */ - var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. - - var failedBoundaries = null; - var setRefreshHandler = function (handler) { - { - resolveFamily = handler; - } - }; - function resolveFunctionForHotReloading(type) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return type; - } - - var family = resolveFamily(type); - - if (family === undefined) { - return type; - } // Use the latest known implementation. - - - return family.current; - } - } - function resolveClassForHotReloading(type) { - // No implementation differences. - return resolveFunctionForHotReloading(type); - } - function resolveForwardRefForHotReloading(type) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return type; - } - - var family = resolveFamily(type); - - if (family === undefined) { - // Check if we're dealing with a real forwardRef. Don't want to crash early. - if (type !== null && type !== undefined && typeof type.render === 'function') { - // ForwardRef is special because its resolved .type is an object, - // but it's possible that we only have its inner render function in the map. - // If that inner render function is different, we'll build a new forwardRef type. - var currentRender = resolveFunctionForHotReloading(type.render); - - if (type.render !== currentRender) { - var syntheticType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render: currentRender - }; - - if (type.displayName !== undefined) { - syntheticType.displayName = type.displayName; - } - - return syntheticType; - } - } - - return type; - } // Use the latest known implementation. - - - return family.current; - } - } - function isCompatibleFamilyForHotReloading(fiber, element) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return false; - } - - var prevType = fiber.elementType; - var nextType = element.type; // If we got here, we know types aren't === equal. - - var needsCompareFamilies = false; - var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null; - - switch (fiber.tag) { - case ClassComponent: - { - if (typeof nextType === 'function') { - needsCompareFamilies = true; - } - - break; - } - - case FunctionComponent: - { - if (typeof nextType === 'function') { - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - // We don't know the inner type yet. - // We're going to assume that the lazy inner type is stable, - // and so it is sufficient to avoid reconciling it away. - // We're not going to unwrap or actually use the new lazy type. - needsCompareFamilies = true; - } - - break; - } - - case ForwardRef: - { - if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - needsCompareFamilies = true; - } - - break; - } - - case MemoComponent: - case SimpleMemoComponent: - { - if ($$typeofNextType === REACT_MEMO_TYPE) { - // TODO: if it was but can no longer be simple, - // we shouldn't set this. - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - needsCompareFamilies = true; - } - - break; - } - - default: - return false; - } // Check if both types have a family and it's the same one. - - - if (needsCompareFamilies) { - // Note: memo() and forwardRef() we'll compare outer rather than inner type. - // This means both of them need to be registered to preserve state. - // If we unwrapped and compared the inner types for wrappers instead, - // then we would risk falsely saying two separate memo(Foo) - // calls are equivalent because they wrap the same Foo function. - var prevFamily = resolveFamily(prevType); - - if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { - return true; - } - } - - return false; - } - } - function markFailedErrorBoundaryForHotReloading(fiber) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return; - } - - if (typeof WeakSet !== 'function') { - return; - } - - if (failedBoundaries === null) { - failedBoundaries = new WeakSet(); - } - - failedBoundaries.add(fiber); - } - } - var scheduleRefresh = function (root, update) { - { - if (resolveFamily === null) { - // Hot reloading is disabled. - return; - } - - var staleFamilies = update.staleFamilies, - updatedFamilies = update.updatedFamilies; - flushPassiveEffects(); - flushSync(function () { - scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies); - }); - } - }; - var scheduleRoot = function (root, element) { - { - if (root.context !== emptyContextObject) { - // Super edge case: root has a legacy _renderSubtree context - // but we don't know the parentComponent so we can't pass it. - // Just ignore. We'll delete this with _renderSubtree code path later. - return; - } - - flushPassiveEffects(); - flushSync(function () { - updateContainer(element, root, null, null); - }); - } - }; - - function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { - { - var alternate = fiber.alternate, - child = fiber.child, - sibling = fiber.sibling, - tag = fiber.tag, - type = fiber.type; - var candidateType = null; - - switch (tag) { - case FunctionComponent: - case SimpleMemoComponent: - case ClassComponent: - candidateType = type; - break; - - case ForwardRef: - candidateType = type.render; - break; - } - - if (resolveFamily === null) { - throw new Error('Expected resolveFamily to be set during hot reload.'); - } - - var needsRender = false; - var needsRemount = false; - - if (candidateType !== null) { - var family = resolveFamily(candidateType); - - if (family !== undefined) { - if (staleFamilies.has(family)) { - needsRemount = true; - } else if (updatedFamilies.has(family)) { - if (tag === ClassComponent) { - needsRemount = true; - } else { - needsRender = true; - } - } - } - } - - if (failedBoundaries !== null) { - if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) { - needsRemount = true; - } - } - - if (needsRemount) { - fiber._debugNeedsRemount = true; - } - - if (needsRemount || needsRender) { - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - - if (child !== null && !needsRemount) { - scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); - } - - if (sibling !== null) { - scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); - } - } - } - - var findHostInstancesForRefresh = function (root, families) { - { - var hostInstances = new Set(); - var types = new Set(families.map(function (family) { - return family.current; - })); - findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances); - return hostInstances; - } - }; - - function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { - { - var child = fiber.child, - sibling = fiber.sibling, - tag = fiber.tag, - type = fiber.type; - var candidateType = null; - - switch (tag) { - case FunctionComponent: - case SimpleMemoComponent: - case ClassComponent: - candidateType = type; - break; - - case ForwardRef: - candidateType = type.render; - break; - } - - var didMatch = false; - - if (candidateType !== null) { - if (types.has(candidateType)) { - didMatch = true; - } - } - - if (didMatch) { - // We have a match. This only drills down to the closest host components. - // There's no need to search deeper because for the purpose of giving - // visual feedback, "flashing" outermost parent rectangles is sufficient. - findHostInstancesForFiberShallowly(fiber, hostInstances); - } else { - // If there's no match, maybe there will be one further down in the child tree. - if (child !== null) { - findHostInstancesForMatchingFibersRecursively(child, types, hostInstances); - } - } - - if (sibling !== null) { - findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); - } - } - } - - function findHostInstancesForFiberShallowly(fiber, hostInstances) { - { - var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances); - - if (foundHostInstances) { - return; - } // If we didn't find any host children, fallback to closest host parent. - - - var node = fiber; - - while (true) { - switch (node.tag) { - case HostComponent: - hostInstances.add(node.stateNode); - return; - - case HostPortal: - hostInstances.add(node.stateNode.containerInfo); - return; - - case HostRoot: - hostInstances.add(node.stateNode.containerInfo); - return; - } - - if (node.return === null) { - throw new Error('Expected to reach root first.'); - } - - node = node.return; - } - } - } - - function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { - { - var node = fiber; - var foundHostInstances = false; - - while (true) { - if (node.tag === HostComponent) { - // We got a match. - foundHostInstances = true; - hostInstances.add(node.stateNode); // There may still be more, so keep searching. - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === fiber) { - return foundHostInstances; - } - - while (node.sibling === null) { - if (node.return === null || node.return === fiber) { - return foundHostInstances; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } - } - - return false; - } - - var hasBadMapPolyfill; - - { - hasBadMapPolyfill = false; - - try { - var nonExtensibleObject = Object.preventExtensions({}); - /* eslint-disable no-new */ - - new Map([[nonExtensibleObject, null]]); - new Set([nonExtensibleObject]); - /* eslint-enable no-new */ - } catch (e) { - // TODO: Consider warning about bad polyfills - hasBadMapPolyfill = true; - } - } - - function FiberNode(tag, pendingProps, key, mode) { - // Instance - this.tag = tag; - this.key = key; - this.elementType = null; - this.type = null; - this.stateNode = null; // Fiber - - this.return = null; - this.child = null; - this.sibling = null; - this.index = 0; - this.ref = null; - this.pendingProps = pendingProps; - this.memoizedProps = null; - this.updateQueue = null; - this.memoizedState = null; - this.dependencies = null; - this.mode = mode; // Effects - - this.flags = NoFlags; - this.subtreeFlags = NoFlags; - this.deletions = null; - this.lanes = NoLanes; - this.childLanes = NoLanes; - this.alternate = null; - - { - // Note: The following is done to avoid a v8 performance cliff. - // - // Initializing the fields below to smis and later updating them with - // double values will cause Fibers to end up having separate shapes. - // This behavior/bug has something to do with Object.preventExtension(). - // Fortunately this only impacts DEV builds. - // Unfortunately it makes React unusably slow for some applications. - // To work around this, initialize the fields below with doubles. - // - // Learn more about this here: - // https://github.com/facebook/react/issues/14365 - // https://bugs.chromium.org/p/v8/issues/detail?id=8538 - this.actualDuration = Number.NaN; - this.actualStartTime = Number.NaN; - this.selfBaseDuration = Number.NaN; - this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. - // This won't trigger the performance cliff mentioned above, - // and it simplifies other profiler code (including DevTools). - - this.actualDuration = 0; - this.actualStartTime = -1; - this.selfBaseDuration = 0; - this.treeBaseDuration = 0; - } - - { - // This isn't directly used but is handy for debugging internals: - this._debugSource = null; - this._debugOwner = null; - this._debugNeedsRemount = false; - this._debugHookTypes = null; - - if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { - Object.preventExtensions(this); - } - } - } // This is a constructor function, rather than a POJO constructor, still - // please ensure we do the following: - // 1) Nobody should add any instance methods on this. Instance methods can be - // more difficult to predict when they get optimized and they are almost - // never inlined properly in static compilers. - // 2) Nobody should rely on `instanceof Fiber` for type testing. We should - // always know when it is a fiber. - // 3) We might want to experiment with using numeric keys since they are easier - // to optimize in a non-JIT environment. - // 4) We can easily go from a constructor to a createFiber object literal if that - // is faster. - // 5) It should be easy to port this to a C struct and keep a C implementation - // compatible. - - - var createFiber = function (tag, pendingProps, key, mode) { - // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors - return new FiberNode(tag, pendingProps, key, mode); - }; - - function shouldConstruct$1(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - - function isSimpleFunctionComponent(type) { - return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined; - } - function resolveLazyComponentTag(Component) { - if (typeof Component === 'function') { - return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent; - } else if (Component !== undefined && Component !== null) { - var $$typeof = Component.$$typeof; - - if ($$typeof === REACT_FORWARD_REF_TYPE) { - return ForwardRef; - } - - if ($$typeof === REACT_MEMO_TYPE) { - return MemoComponent; - } - } - - return IndeterminateComponent; - } // This is used to create an alternate fiber to do work on. - - function createWorkInProgress(current, pendingProps) { - var workInProgress = current.alternate; - - if (workInProgress === null) { - // We use a double buffering pooling technique because we know that we'll - // only ever need at most two versions of a tree. We pool the "other" unused - // node that we're free to reuse. This is lazily created to avoid allocating - // extra objects for things that are never updated. It also allow us to - // reclaim the extra memory if needed. - workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode); - workInProgress.elementType = current.elementType; - workInProgress.type = current.type; - workInProgress.stateNode = current.stateNode; - - { - // DEV-only fields - workInProgress._debugSource = current._debugSource; - workInProgress._debugOwner = current._debugOwner; - workInProgress._debugHookTypes = current._debugHookTypes; - } - - workInProgress.alternate = current; - current.alternate = workInProgress; - } else { - workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type. - - workInProgress.type = current.type; // We already have an alternate. - // Reset the effect tag. - - workInProgress.flags = NoFlags; // The effects are no longer valid. - - workInProgress.subtreeFlags = NoFlags; - workInProgress.deletions = null; - - { - // We intentionally reset, rather than copy, actualDuration & actualStartTime. - // This prevents time from endlessly accumulating in new commits. - // This has the downside of resetting values for different priority renders, - // But works for yielding (the common case) and should support resuming. - workInProgress.actualDuration = 0; - workInProgress.actualStartTime = -1; - } - } // Reset all effects except static ones. - // Static effects are not specific to a render. - - - workInProgress.flags = current.flags & StaticMask; - workInProgress.childLanes = current.childLanes; - workInProgress.lanes = current.lanes; - workInProgress.child = current.child; - workInProgress.memoizedProps = current.memoizedProps; - workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so - // it cannot be shared with the current fiber. - - var currentDependencies = current.dependencies; - workInProgress.dependencies = currentDependencies === null ? null : { - lanes: currentDependencies.lanes, - firstContext: currentDependencies.firstContext - }; // These will be overridden during the parent's reconciliation - - workInProgress.sibling = current.sibling; - workInProgress.index = current.index; - workInProgress.ref = current.ref; - - { - workInProgress.selfBaseDuration = current.selfBaseDuration; - workInProgress.treeBaseDuration = current.treeBaseDuration; - } - - { - workInProgress._debugNeedsRemount = current._debugNeedsRemount; - - switch (workInProgress.tag) { - case IndeterminateComponent: - case FunctionComponent: - case SimpleMemoComponent: - workInProgress.type = resolveFunctionForHotReloading(current.type); - break; - - case ClassComponent: - workInProgress.type = resolveClassForHotReloading(current.type); - break; - - case ForwardRef: - workInProgress.type = resolveForwardRefForHotReloading(current.type); - break; - } - } - - return workInProgress; - } // Used to reuse a Fiber for a second pass. - - function resetWorkInProgress(workInProgress, renderLanes) { - // This resets the Fiber to what createFiber or createWorkInProgress would - // have set the values to before during the first pass. Ideally this wouldn't - // be necessary but unfortunately many code paths reads from the workInProgress - // when they should be reading from current and writing to workInProgress. - // We assume pendingProps, index, key, ref, return are still untouched to - // avoid doing another reconciliation. - // Reset the effect flags but keep any Placement tags, since that's something - // that child fiber is setting, not the reconciliation. - workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid. - - var current = workInProgress.alternate; - - if (current === null) { - // Reset to createFiber's initial values. - workInProgress.childLanes = NoLanes; - workInProgress.lanes = renderLanes; - workInProgress.child = null; - workInProgress.subtreeFlags = NoFlags; - workInProgress.memoizedProps = null; - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - workInProgress.dependencies = null; - workInProgress.stateNode = null; - - { - // Note: We don't reset the actualTime counts. It's useful to accumulate - // actual time across multiple render passes. - workInProgress.selfBaseDuration = 0; - workInProgress.treeBaseDuration = 0; - } - } else { - // Reset to the cloned values that createWorkInProgress would've. - workInProgress.childLanes = current.childLanes; - workInProgress.lanes = current.lanes; - workInProgress.child = current.child; - workInProgress.subtreeFlags = NoFlags; - workInProgress.deletions = null; - workInProgress.memoizedProps = current.memoizedProps; - workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type. - - workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so - // it cannot be shared with the current fiber. - - var currentDependencies = current.dependencies; - workInProgress.dependencies = currentDependencies === null ? null : { - lanes: currentDependencies.lanes, - firstContext: currentDependencies.firstContext - }; - - { - // Note: We don't reset the actualTime counts. It's useful to accumulate - // actual time across multiple render passes. - workInProgress.selfBaseDuration = current.selfBaseDuration; - workInProgress.treeBaseDuration = current.treeBaseDuration; - } - } - - return workInProgress; - } - function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { - var mode; - - if (tag === ConcurrentRoot) { - mode = ConcurrentMode; - - if (isStrictMode === true) { - mode |= StrictLegacyMode; - - { - mode |= StrictEffectsMode; - } - } - } else { - mode = NoMode; - } - - if ( isDevToolsPresent) { - // Always collect profile timings when DevTools are present. - // This enables DevTools to start capturing timing at any point– - // Without some nodes in the tree having empty base times. - mode |= ProfileMode; - } - - return createFiber(HostRoot, null, null, mode); - } - function createFiberFromTypeAndProps(type, // React$ElementType - key, pendingProps, owner, mode, lanes) { - var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. - - var resolvedType = type; - - if (typeof type === 'function') { - if (shouldConstruct$1(type)) { - fiberTag = ClassComponent; - - { - resolvedType = resolveClassForHotReloading(resolvedType); - } - } else { - { - resolvedType = resolveFunctionForHotReloading(resolvedType); - } - } - } else if (typeof type === 'string') { - fiberTag = HostComponent; - } else { - getTag: switch (type) { - case REACT_FRAGMENT_TYPE: - return createFiberFromFragment(pendingProps.children, mode, lanes, key); - - case REACT_STRICT_MODE_TYPE: - fiberTag = Mode; - mode |= StrictLegacyMode; - - if ( (mode & ConcurrentMode) !== NoMode) { - // Strict effects should never run on legacy roots - mode |= StrictEffectsMode; - } - - break; - - case REACT_PROFILER_TYPE: - return createFiberFromProfiler(pendingProps, mode, lanes, key); - - case REACT_SUSPENSE_TYPE: - return createFiberFromSuspense(pendingProps, mode, lanes, key); - - case REACT_SUSPENSE_LIST_TYPE: - return createFiberFromSuspenseList(pendingProps, mode, lanes, key); - - case REACT_OFFSCREEN_TYPE: - return createFiberFromOffscreen(pendingProps, mode, lanes, key); - - case REACT_LEGACY_HIDDEN_TYPE: - - // eslint-disable-next-line no-fallthrough - - case REACT_SCOPE_TYPE: - - // eslint-disable-next-line no-fallthrough - - case REACT_CACHE_TYPE: - - // eslint-disable-next-line no-fallthrough - - case REACT_TRACING_MARKER_TYPE: - - // eslint-disable-next-line no-fallthrough - - case REACT_DEBUG_TRACING_MODE_TYPE: - - // eslint-disable-next-line no-fallthrough - - default: - { - if (typeof type === 'object' && type !== null) { - switch (type.$$typeof) { - case REACT_PROVIDER_TYPE: - fiberTag = ContextProvider; - break getTag; - - case REACT_CONTEXT_TYPE: - // This is a consumer - fiberTag = ContextConsumer; - break getTag; - - case REACT_FORWARD_REF_TYPE: - fiberTag = ForwardRef; - - { - resolvedType = resolveForwardRefForHotReloading(resolvedType); - } - - break getTag; - - case REACT_MEMO_TYPE: - fiberTag = MemoComponent; - break getTag; - - case REACT_LAZY_TYPE: - fiberTag = LazyComponent; - resolvedType = null; - break getTag; - } - } - - var info = ''; - - { - if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { - info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; - } - - var ownerName = owner ? getComponentNameFromFiber(owner) : null; - - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - } - - throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); - } - } - } - - var fiber = createFiber(fiberTag, pendingProps, key, mode); - fiber.elementType = type; - fiber.type = resolvedType; - fiber.lanes = lanes; - - { - fiber._debugOwner = owner; - } - - return fiber; - } - function createFiberFromElement(element, mode, lanes) { - var owner = null; - - { - owner = element._owner; - } - - var type = element.type; - var key = element.key; - var pendingProps = element.props; - var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes); - - { - fiber._debugSource = element._source; - fiber._debugOwner = element._owner; - } - - return fiber; - } - function createFiberFromFragment(elements, mode, lanes, key) { - var fiber = createFiber(Fragment, elements, key, mode); - fiber.lanes = lanes; - return fiber; - } - - function createFiberFromProfiler(pendingProps, mode, lanes, key) { - { - if (typeof pendingProps.id !== 'string') { - error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id); - } - } - - var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); - fiber.elementType = REACT_PROFILER_TYPE; - fiber.lanes = lanes; - - { - fiber.stateNode = { - effectDuration: 0, - passiveEffectDuration: 0 - }; - } - - return fiber; - } - - function createFiberFromSuspense(pendingProps, mode, lanes, key) { - var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); - fiber.elementType = REACT_SUSPENSE_TYPE; - fiber.lanes = lanes; - return fiber; - } - function createFiberFromSuspenseList(pendingProps, mode, lanes, key) { - var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); - fiber.elementType = REACT_SUSPENSE_LIST_TYPE; - fiber.lanes = lanes; - return fiber; - } - function createFiberFromOffscreen(pendingProps, mode, lanes, key) { - var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); - fiber.elementType = REACT_OFFSCREEN_TYPE; - fiber.lanes = lanes; - var primaryChildInstance = {}; - fiber.stateNode = primaryChildInstance; - return fiber; - } - function createFiberFromText(content, mode, lanes) { - var fiber = createFiber(HostText, content, null, mode); - fiber.lanes = lanes; - return fiber; - } - function createFiberFromHostInstanceForDeletion() { - var fiber = createFiber(HostComponent, null, null, NoMode); - fiber.elementType = 'DELETED'; - return fiber; - } - function createFiberFromDehydratedFragment(dehydratedNode) { - var fiber = createFiber(DehydratedFragment, null, null, NoMode); - fiber.stateNode = dehydratedNode; - return fiber; - } - function createFiberFromPortal(portal, mode, lanes) { - var pendingProps = portal.children !== null ? portal.children : []; - var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); - fiber.lanes = lanes; - fiber.stateNode = { - containerInfo: portal.containerInfo, - pendingChildren: null, - // Used by persistent updates - implementation: portal.implementation - }; - return fiber; - } // Used for stashing WIP properties to replay failed work in DEV. - - function assignFiberPropertiesInDEV(target, source) { - if (target === null) { - // This Fiber's initial properties will always be overwritten. - // We only use a Fiber to ensure the same hidden class so DEV isn't slow. - target = createFiber(IndeterminateComponent, null, null, NoMode); - } // This is intentionally written as a list of all properties. - // We tried to use Object.assign() instead but this is called in - // the hottest path, and Object.assign() was too slow: - // https://github.com/facebook/react/issues/12502 - // This code is DEV-only so size is not a concern. - - - target.tag = source.tag; - target.key = source.key; - target.elementType = source.elementType; - target.type = source.type; - target.stateNode = source.stateNode; - target.return = source.return; - target.child = source.child; - target.sibling = source.sibling; - target.index = source.index; - target.ref = source.ref; - target.pendingProps = source.pendingProps; - target.memoizedProps = source.memoizedProps; - target.updateQueue = source.updateQueue; - target.memoizedState = source.memoizedState; - target.dependencies = source.dependencies; - target.mode = source.mode; - target.flags = source.flags; - target.subtreeFlags = source.subtreeFlags; - target.deletions = source.deletions; - target.lanes = source.lanes; - target.childLanes = source.childLanes; - target.alternate = source.alternate; - - { - target.actualDuration = source.actualDuration; - target.actualStartTime = source.actualStartTime; - target.selfBaseDuration = source.selfBaseDuration; - target.treeBaseDuration = source.treeBaseDuration; - } - - target._debugSource = source._debugSource; - target._debugOwner = source._debugOwner; - target._debugNeedsRemount = source._debugNeedsRemount; - target._debugHookTypes = source._debugHookTypes; - return target; - } - - function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) { - this.tag = tag; - this.containerInfo = containerInfo; - this.pendingChildren = null; - this.current = null; - this.pingCache = null; - this.finishedWork = null; - this.timeoutHandle = noTimeout; - this.context = null; - this.pendingContext = null; - this.callbackNode = null; - this.callbackPriority = NoLane; - this.eventTimes = createLaneMap(NoLanes); - this.expirationTimes = createLaneMap(NoTimestamp); - this.pendingLanes = NoLanes; - this.suspendedLanes = NoLanes; - this.pingedLanes = NoLanes; - this.expiredLanes = NoLanes; - this.mutableReadLanes = NoLanes; - this.finishedLanes = NoLanes; - this.entangledLanes = NoLanes; - this.entanglements = createLaneMap(NoLanes); - this.identifierPrefix = identifierPrefix; - this.onRecoverableError = onRecoverableError; - - if (supportsHydration) { - this.mutableSourceEagerHydrationData = null; - } - - { - this.effectDuration = 0; - this.passiveEffectDuration = 0; - } - - { - this.memoizedUpdaters = new Set(); - var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = []; - - for (var _i = 0; _i < TotalLanes; _i++) { - pendingUpdatersLaneMap.push(new Set()); - } - } - - { - switch (tag) { - case ConcurrentRoot: - this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()'; - break; - - case LegacyRoot: - this._debugRootType = hydrate ? 'hydrate()' : 'render()'; - break; - } - } - } - - function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the - // host config, but because they are passed in at runtime, we have to thread - // them through the root constructor. Perhaps we should put them all into a - // single type, like a DynamicHostConfig that is defined by the renderer. - identifierPrefix, onRecoverableError, transitionCallbacks) { - var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); - // stateNode is any. - - - var uninitializedFiber = createHostRootFiber(tag, isStrictMode); - root.current = uninitializedFiber; - uninitializedFiber.stateNode = root; - - { - var _initialState = { - element: initialChildren, - isDehydrated: hydrate, - cache: null, - // not enabled yet - transitions: null - }; - uninitializedFiber.memoizedState = _initialState; - } - - initializeUpdateQueue(uninitializedFiber); - return root; - } - - var ReactVersion = '18.0.0-fc46dba67-20220329'; - - function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation. - implementation) { - var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - - { - checkKeyStringCoercion(key); - } - - return { - // This tag allow us to uniquely identify this as a React Portal - $$typeof: REACT_PORTAL_TYPE, - key: key == null ? null : '' + key, - children: children, - containerInfo: containerInfo, - implementation: implementation - }; - } - - var didWarnAboutNestedUpdates; - var didWarnAboutFindNodeInStrictMode; - - { - didWarnAboutNestedUpdates = false; - didWarnAboutFindNodeInStrictMode = {}; - } - - function getContextForSubtree(parentComponent) { - if (!parentComponent) { - return emptyContextObject; - } - - var fiber = get(parentComponent); - var parentContext = findCurrentUnmaskedContext(fiber); - - if (fiber.tag === ClassComponent) { - var Component = fiber.type; - - if (isContextProvider(Component)) { - return processChildContext(fiber, Component, parentContext); - } - } - - return parentContext; - } - - function findHostInstance(component) { - var fiber = get(component); - - if (fiber === undefined) { - if (typeof component.render === 'function') { - throw new Error('Unable to find node on an unmounted component.'); - } else { - var keys = Object.keys(component).join(','); - throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); - } - } - - var hostFiber = findCurrentHostFiber(fiber); - - if (hostFiber === null) { - return null; - } - - return hostFiber.stateNode; - } - - function findHostInstanceWithWarning(component, methodName) { - { - var fiber = get(component); - - if (fiber === undefined) { - if (typeof component.render === 'function') { - throw new Error('Unable to find node on an unmounted component.'); - } else { - var keys = Object.keys(component).join(','); - throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); - } - } - - var hostFiber = findCurrentHostFiber(fiber); - - if (hostFiber === null) { - return null; - } - - if (hostFiber.mode & StrictLegacyMode) { - var componentName = getComponentNameFromFiber(fiber) || 'Component'; - - if (!didWarnAboutFindNodeInStrictMode[componentName]) { - didWarnAboutFindNodeInStrictMode[componentName] = true; - var previousFiber = current; - - try { - setCurrentFiber(hostFiber); - - if (fiber.mode & StrictLegacyMode) { - error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); - } else { - error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); - } - } finally { - // Ideally this should reset to previous but this shouldn't be called in - // render and there's another warning for that anyway. - if (previousFiber) { - setCurrentFiber(previousFiber); - } else { - resetCurrentFiber(); - } - } - } - } - - return hostFiber.stateNode; - } - } - - function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { - var hydrate = false; - var initialChildren = null; - return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); - } - function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode. - callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { - var hydrate = true; - var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor - - root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from - // a regular update because the initial render must match was was rendered - // on the server. - // NOTE: This update intentionally doesn't have a payload. We're only using - // the update to schedule work on the root fiber (and, for legacy roots, to - // enqueue the callback if one is provided). - - var current = root.current; - var eventTime = requestEventTime(); - var lane = requestUpdateLane(current); - var update = createUpdate(eventTime, lane); - update.callback = callback !== undefined && callback !== null ? callback : null; - enqueueUpdate(current, update); - scheduleInitialHydrationOnRoot(root, lane, eventTime); - return root; - } - function updateContainer(element, container, parentComponent, callback) { - { - onScheduleRoot(container, element); - } - - var current$1 = container.current; - var eventTime = requestEventTime(); - var lane = requestUpdateLane(current$1); - - { - markRenderScheduled(lane); - } - - var context = getContextForSubtree(parentComponent); - - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - - { - if (isRendering && current !== null && !didWarnAboutNestedUpdates) { - didWarnAboutNestedUpdates = true; - - error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown'); - } - } - - var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property - // being called "element". - - update.payload = { - element: element - }; - callback = callback === undefined ? null : callback; - - if (callback !== null) { - { - if (typeof callback !== 'function') { - error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback); - } - } - - update.callback = callback; - } - - enqueueUpdate(current$1, update); - var root = scheduleUpdateOnFiber(current$1, lane, eventTime); - - if (root !== null) { - entangleTransitions(root, current$1, lane); - } - - return lane; - } - function getPublicRootInstance(container) { - var containerFiber = container.current; - - if (!containerFiber.child) { - return null; - } - - switch (containerFiber.child.tag) { - case HostComponent: - return getPublicInstance(containerFiber.child.stateNode); - - default: - return containerFiber.child.stateNode; - } - } - function attemptSynchronousHydration(fiber) { - switch (fiber.tag) { - case HostRoot: - var root = fiber.stateNode; - - if (isRootDehydrated(root)) { - // Flush the first scheduled "update". - var lanes = getHighestPriorityPendingLanes(root); - flushRoot(root, lanes); - } - - break; - - case SuspenseComponent: - var eventTime = requestEventTime(); - flushSync(function () { - return scheduleUpdateOnFiber(fiber, SyncLane, eventTime); - }); // If we're still blocked after this, we need to increase - // the priority of any promises resolving within this - // boundary so that they next attempt also has higher pri. - - var retryLane = SyncLane; - markRetryLaneIfNotHydrated(fiber, retryLane); - break; - } - } - - function markRetryLaneImpl(fiber, retryLane) { - var suspenseState = fiber.memoizedState; - - if (suspenseState !== null && suspenseState.dehydrated !== null) { - suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane); - } - } // Increases the priority of thenables when they resolve within this boundary. - - - function markRetryLaneIfNotHydrated(fiber, retryLane) { - markRetryLaneImpl(fiber, retryLane); - var alternate = fiber.alternate; - - if (alternate) { - markRetryLaneImpl(alternate, retryLane); - } - } - - function attemptContinuousHydration(fiber) { - if (fiber.tag !== SuspenseComponent) { - // We ignore HostRoots here because we can't increase - // their priority and they should not suspend on I/O, - // since you have to wrap anything that might suspend in - // Suspense. - return; - } - - var eventTime = requestEventTime(); - var lane = SelectiveHydrationLane; - scheduleUpdateOnFiber(fiber, lane, eventTime); - markRetryLaneIfNotHydrated(fiber, lane); - } - function attemptHydrationAtCurrentPriority(fiber) { - if (fiber.tag !== SuspenseComponent) { - // We ignore HostRoots here because we can't increase - // their priority other than synchronously flush it. - return; - } - - var eventTime = requestEventTime(); - var lane = requestUpdateLane(fiber); - scheduleUpdateOnFiber(fiber, lane, eventTime); - markRetryLaneIfNotHydrated(fiber, lane); - } - function findHostInstanceWithNoPortals(fiber) { - var hostFiber = findCurrentHostFiberWithNoPortals(fiber); - - if (hostFiber === null) { - return null; - } - - return hostFiber.stateNode; - } - - var shouldErrorImpl = function (fiber) { - return null; - }; - - function shouldError(fiber) { - return shouldErrorImpl(fiber); - } - - var shouldSuspendImpl = function (fiber) { - return false; - }; - - function shouldSuspend(fiber) { - return shouldSuspendImpl(fiber); - } - var overrideHookState = null; - var overrideHookStateDeletePath = null; - var overrideHookStateRenamePath = null; - var overrideProps = null; - var overridePropsDeletePath = null; - var overridePropsRenamePath = null; - var scheduleUpdate = null; - var setErrorHandler = null; - var setSuspenseHandler = null; - - { - var copyWithDeleteImpl = function (obj, path, index) { - var key = path[index]; - var updated = isArray(obj) ? obj.slice() : assign({}, obj); - - if (index + 1 === path.length) { - if (isArray(updated)) { - updated.splice(key, 1); - } else { - delete updated[key]; - } - - return updated; - } // $FlowFixMe number or string is fine here - - - updated[key] = copyWithDeleteImpl(obj[key], path, index + 1); - return updated; - }; - - var copyWithDelete = function (obj, path) { - return copyWithDeleteImpl(obj, path, 0); - }; - - var copyWithRenameImpl = function (obj, oldPath, newPath, index) { - var oldKey = oldPath[index]; - var updated = isArray(obj) ? obj.slice() : assign({}, obj); - - if (index + 1 === oldPath.length) { - var newKey = newPath[index]; // $FlowFixMe number or string is fine here - - updated[newKey] = updated[oldKey]; - - if (isArray(updated)) { - updated.splice(oldKey, 1); - } else { - delete updated[oldKey]; - } - } else { - // $FlowFixMe number or string is fine here - updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here - obj[oldKey], oldPath, newPath, index + 1); - } - - return updated; - }; - - var copyWithRename = function (obj, oldPath, newPath) { - if (oldPath.length !== newPath.length) { - warn('copyWithRename() expects paths of the same length'); - - return; - } else { - for (var i = 0; i < newPath.length - 1; i++) { - if (oldPath[i] !== newPath[i]) { - warn('copyWithRename() expects paths to be the same except for the deepest key'); - - return; - } - } - } - - return copyWithRenameImpl(obj, oldPath, newPath, 0); - }; - - var copyWithSetImpl = function (obj, path, index, value) { - if (index >= path.length) { - return value; - } - - var key = path[index]; - var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here - - updated[key] = copyWithSetImpl(obj[key], path, index + 1, value); - return updated; - }; - - var copyWithSet = function (obj, path, value) { - return copyWithSetImpl(obj, path, 0, value); - }; - - var findHook = function (fiber, id) { - // For now, the "id" of stateful hooks is just the stateful hook index. - // This may change in the future with e.g. nested hooks. - var currentHook = fiber.memoizedState; - - while (currentHook !== null && id > 0) { - currentHook = currentHook.next; - id--; - } - - return currentHook; - }; // Support DevTools editable values for useState and useReducer. - - - overrideHookState = function (fiber, id, path, value) { - var hook = findHook(fiber, id); - - if (hook !== null) { - var newState = copyWithSet(hook.memoizedState, path, value); - hook.memoizedState = newState; - hook.baseState = newState; // We aren't actually adding an update to the queue, - // because there is no update we can add for useReducer hooks that won't trigger an error. - // (There's no appropriate action type for DevTools overrides.) - // As a result though, React will see the scheduled update as a noop and bailout. - // Shallow cloning props works as a workaround for now to bypass the bailout check. - - fiber.memoizedProps = assign({}, fiber.memoizedProps); - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - }; - - overrideHookStateDeletePath = function (fiber, id, path) { - var hook = findHook(fiber, id); - - if (hook !== null) { - var newState = copyWithDelete(hook.memoizedState, path); - hook.memoizedState = newState; - hook.baseState = newState; // We aren't actually adding an update to the queue, - // because there is no update we can add for useReducer hooks that won't trigger an error. - // (There's no appropriate action type for DevTools overrides.) - // As a result though, React will see the scheduled update as a noop and bailout. - // Shallow cloning props works as a workaround for now to bypass the bailout check. - - fiber.memoizedProps = assign({}, fiber.memoizedProps); - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - }; - - overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) { - var hook = findHook(fiber, id); - - if (hook !== null) { - var newState = copyWithRename(hook.memoizedState, oldPath, newPath); - hook.memoizedState = newState; - hook.baseState = newState; // We aren't actually adding an update to the queue, - // because there is no update we can add for useReducer hooks that won't trigger an error. - // (There's no appropriate action type for DevTools overrides.) - // As a result though, React will see the scheduled update as a noop and bailout. - // Shallow cloning props works as a workaround for now to bypass the bailout check. - - fiber.memoizedProps = assign({}, fiber.memoizedProps); - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - } - }; // Support DevTools props for function components, forwardRef, memo, host components, etc. - - - overrideProps = function (fiber, path, value) { - fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); - - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - }; - - overridePropsDeletePath = function (fiber, path) { - fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); - - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - }; - - overridePropsRenamePath = function (fiber, oldPath, newPath) { - fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); - - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - }; - - scheduleUpdate = function (fiber) { - scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); - }; - - setErrorHandler = function (newShouldErrorImpl) { - shouldErrorImpl = newShouldErrorImpl; - }; - - setSuspenseHandler = function (newShouldSuspendImpl) { - shouldSuspendImpl = newShouldSuspendImpl; - }; - } - - function findHostInstanceByFiber(fiber) { - var hostFiber = findCurrentHostFiber(fiber); - - if (hostFiber === null) { - return null; - } - - return hostFiber.stateNode; - } - - function emptyFindFiberByHostInstance(instance) { - return null; - } - - function getCurrentFiberForDevTools() { - return current; - } - - function injectIntoDevTools(devToolsConfig) { - var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - return injectInternals({ - bundleType: devToolsConfig.bundleType, - version: devToolsConfig.version, - rendererPackageName: devToolsConfig.rendererPackageName, - rendererConfig: devToolsConfig.rendererConfig, - overrideHookState: overrideHookState, - overrideHookStateDeletePath: overrideHookStateDeletePath, - overrideHookStateRenamePath: overrideHookStateRenamePath, - overrideProps: overrideProps, - overridePropsDeletePath: overridePropsDeletePath, - overridePropsRenamePath: overridePropsRenamePath, - setErrorHandler: setErrorHandler, - setSuspenseHandler: setSuspenseHandler, - scheduleUpdate: scheduleUpdate, - currentDispatcherRef: ReactCurrentDispatcher, - findHostInstanceByFiber: findHostInstanceByFiber, - findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, - // React Refresh - findHostInstancesForRefresh: findHostInstancesForRefresh , - scheduleRefresh: scheduleRefresh , - scheduleRoot: scheduleRoot , - setRefreshHandler: setRefreshHandler , - // Enables DevTools to append owner stacks to error messages in DEV mode. - getCurrentFiber: getCurrentFiberForDevTools , - // Enables DevTools to detect reconciler version rather than renderer version - // which may not match for third party renderers. - reconcilerVersion: ReactVersion - }); - } - - exports.attemptContinuousHydration = attemptContinuousHydration; - exports.attemptHydrationAtCurrentPriority = attemptHydrationAtCurrentPriority; - exports.attemptSynchronousHydration = attemptSynchronousHydration; - exports.batchedUpdates = batchedUpdates; - exports.createComponentSelector = createComponentSelector; - exports.createContainer = createContainer; - exports.createHasPseudoClassSelector = createHasPseudoClassSelector; - exports.createHydrationContainer = createHydrationContainer; - exports.createPortal = createPortal; - exports.createRoleSelector = createRoleSelector; - exports.createTestNameSelector = createTestNameSelector; - exports.createTextSelector = createTextSelector; - exports.deferredUpdates = deferredUpdates; - exports.discreteUpdates = discreteUpdates; - exports.findAllNodes = findAllNodes; - exports.findBoundingRects = findBoundingRects; - exports.findHostInstance = findHostInstance; - exports.findHostInstanceWithNoPortals = findHostInstanceWithNoPortals; - exports.findHostInstanceWithWarning = findHostInstanceWithWarning; - exports.flushControlled = flushControlled; - exports.flushPassiveEffects = flushPassiveEffects; - exports.flushSync = flushSync; - exports.focusWithin = focusWithin; - exports.getCurrentUpdatePriority = getCurrentUpdatePriority; - exports.getFindAllNodesFailureDescription = getFindAllNodesFailureDescription; - exports.getPublicRootInstance = getPublicRootInstance; - exports.injectIntoDevTools = injectIntoDevTools; - exports.isAlreadyRendering = isAlreadyRendering; - exports.observeVisibleRects = observeVisibleRects; - exports.registerMutableSourceForHydration = registerMutableSourceForHydration; - exports.runWithPriority = runWithPriority; - exports.shouldError = shouldError; - exports.shouldSuspend = shouldSuspend; - exports.updateContainer = updateContainer; - return exports; - }; - } - return reactReconciler_development.exports; -} - -(function (module) { - - if (process.env.NODE_ENV === 'production') { - module.exports = requireReactReconciler_production_min(); - } else { - module.exports = requireReactReconciler_development(); - } -} (reactReconciler)); - -var Reconciler = /*@__PURE__*/getDefaultExportFromCjs(reactReconciler.exports); - -function shallowEqualArrays(arrA, arrB, equal = (a, b) => a === b) { - if (arrA === arrB) return true; - if (!arrA || !arrB) return false; - const len = arrA.length; - if (arrB.length !== len) return false; - - for (let i = 0; i < len; i++) if (!equal(arrA[i], arrB[i])) return false; - - return true; -} - -const globalCache = []; - -function query(fn, keys, preload = false, config = {}) { - for (const entry of globalCache) { - // Find a match - if (shallowEqualArrays(keys, entry.keys, entry.equal)) { - // If we're pre-loading and the element is present, just return - if (preload) return undefined; // If an error occurred, throw - - if (Object.prototype.hasOwnProperty.call(entry, 'error')) throw entry.error; // If a response was successful, return - - if (Object.prototype.hasOwnProperty.call(entry, 'response')) return entry.response; // If the promise is still unresolved, throw - - if (!preload) throw entry.promise; - } - } // The request is new or has changed. - - - const entry = { - keys, - equal: config.equal, - promise: // Execute the promise - fn(...keys) // When it resolves, store its value - .then(response => entry.response = response) // Remove the entry if a lifespan was given - .then(() => { - if (config.lifespan && config.lifespan > 0) { - setTimeout(() => { - const index = globalCache.indexOf(entry); - if (index !== -1) globalCache.splice(index, 1); - }, config.lifespan); - } - }) // Store caught errors, they will be thrown in the render-phase to bubble into an error-bound - .catch(error => entry.error = error) - }; // Register the entry - - globalCache.push(entry); // And throw the promise, this yields control back to React - - if (!preload) throw entry.promise; - return undefined; -} - -const suspend = (fn, keys, config) => query(fn, keys, false, config); - -const isOrthographicCamera = def => def && def.isOrthographicCamera; // React currently throws a warning when using useLayoutEffect on the server. -// To get around it, we can conditionally useEffect on the server (no-op) and -// useLayoutEffect on the client. - -const isSSR$2 = typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); -const useIsomorphicLayoutEffect$1 = isSSR$2 ? React__namespace.useEffect : React__namespace.useLayoutEffect; -function useMutableCallback(fn) { - const ref = React__namespace.useRef(fn); - useIsomorphicLayoutEffect$1(() => void (ref.current = fn), [fn]); - return ref; -} -function Block({ - set -}) { - useIsomorphicLayoutEffect$1(() => { - set(new Promise(() => null)); - return () => set(false); - }, [set]); - return null; -} -class ErrorBoundary extends React__namespace.Component { - constructor(...args) { - super(...args); - this.state = { - error: false - }; - } - - componentDidCatch(error) { - this.props.set(error); - } - - render() { - return this.state.error ? null : this.props.children; - } - -} - -ErrorBoundary.getDerivedStateFromError = () => ({ - error: true -}); - -const DEFAULT = '__default'; -const isDiffSet = def => def && !!def.memoized && !!def.changes; -function calculateDpr(dpr) { - return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], window.devicePixelRatio), dpr[1]) : dpr; -} -/** - * Returns instance root state - */ - -const getRootState = obj => { - var _r3f; - - return (_r3f = obj.__r3f) == null ? void 0 : _r3f.root.getState(); -}; -// A collection of compare functions -const is$1 = { - obj: a => a === Object(a) && !is$1.arr(a) && typeof a !== 'function', - fun: a => typeof a === 'function', - str: a => typeof a === 'string', - num: a => typeof a === 'number', - boo: a => typeof a === 'boolean', - und: a => a === void 0, - arr: a => Array.isArray(a), - - equ(a, b, { - arrays = 'shallow', - objects = 'reference', - strict = true - } = {}) { - // Wrong type or one of the two undefined, doesn't match - if (typeof a !== typeof b || !!a !== !!b) return false; // Atomic, just compare a against b - - if (is$1.str(a) || is$1.num(a)) return a === b; - const isObj = is$1.obj(a); - if (isObj && objects === 'reference') return a === b; - const isArr = is$1.arr(a); - if (isArr && arrays === 'reference') return a === b; // Array or Object, shallow compare first to see if it's a match - - if ((isArr || isObj) && a === b) return true; // Last resort, go through keys - - let i; - - for (i in a) if (!(i in b)) return false; - - for (i in strict ? b : a) if (a[i] !== b[i]) return false; - - if (is$1.und(i)) { - if (isArr && a.length === 0 && b.length === 0) return true; - if (isObj && Object.keys(a).length === 0 && Object.keys(b).length === 0) return true; - if (a !== b) return false; - } - - return true; - } - -}; // Collects nodes and materials from a THREE.Object3D - -function dispose(obj) { - if (obj.dispose && obj.type !== 'Scene') obj.dispose(); - - for (const p in obj) { - p.dispose == null ? void 0 : p.dispose(); - delete obj[p]; - } -} // Each object in the scene carries a small LocalState descriptor - -function prepare(object, state) { - const instance = object; - - if (state != null && state.primitive || !instance.__r3f) { - instance.__r3f = { - type: '', - root: null, - previousAttach: null, - memoizedProps: {}, - eventCount: 0, - handlers: {}, - objects: [], - parent: null, - ...state - }; - } - - return object; -} - -function resolve(instance, key) { - let target = instance; - - if (key.includes('-')) { - const entries = key.split('-'); - const last = entries.pop(); - target = entries.reduce((acc, key) => acc[key], instance); - return { - target, - key: last - }; - } else return { - target, - key - }; -} // Checks if a dash-cased string ends with an integer - - -const INDEX_REGEX = /-\d+$/; -function attach(parent, child, type) { - if (is$1.str(type)) { - // If attaching into an array (foo-0), create one - if (INDEX_REGEX.test(type)) { - const root = type.replace(INDEX_REGEX, ''); - const { - target, - key - } = resolve(parent, root); - if (!Array.isArray(target[key])) target[key] = []; - } - - const { - target, - key - } = resolve(parent, type); - child.__r3f.previousAttach = target[key]; - target[key] = child; - } else child.__r3f.previousAttach = type(parent, child); -} -function detach(parent, child, type) { - var _child$__r3f, _child$__r3f2; - - if (is$1.str(type)) { - const { - target, - key - } = resolve(parent, type); - const previous = child.__r3f.previousAttach; // When the previous value was undefined, it means the value was never set to begin with - - if (previous === undefined) delete target[key]; // Otherwise set the previous value - else target[key] = previous; - } else (_child$__r3f = child.__r3f) == null ? void 0 : _child$__r3f.previousAttach == null ? void 0 : _child$__r3f.previousAttach(parent, child); - - (_child$__r3f2 = child.__r3f) == null ? true : delete _child$__r3f2.previousAttach; -} // This function prepares a set of changes to be applied to the instance - -function diffProps(instance, { - children: cN, - key: kN, - ref: rN, - ...props -}, { - children: cP, - key: kP, - ref: rP, - ...previous -} = {}, remove = false) { - var _instance$__r3f; - - const localState = (_instance$__r3f = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f : {}; - const entries = Object.entries(props); - const changes = []; // Catch removed props, prepend them so they can be reset or removed - - if (remove) { - const previousKeys = Object.keys(previous); - - for (let i = 0; i < previousKeys.length; i++) { - if (!props.hasOwnProperty(previousKeys[i])) entries.unshift([previousKeys[i], DEFAULT + 'remove']); - } - } - - entries.forEach(([key, value]) => { - var _instance$__r3f2; - - // Bail out on primitive object - if ((_instance$__r3f2 = instance.__r3f) != null && _instance$__r3f2.primitive && key === 'object') return; // When props match bail out - - if (is$1.equ(value, previous[key])) return; // Collect handlers and bail out - - if (/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key)) return changes.push([key, value, true, []]); // Split dashed props - - let entries = []; - if (key.includes('-')) entries = key.split('-'); - changes.push([key, value, false, entries]); - }); - const memoized = { ...props - }; - if (localState.memoizedProps && localState.memoizedProps.args) memoized.args = localState.memoizedProps.args; - if (localState.memoizedProps && localState.memoizedProps.attach) memoized.attach = localState.memoizedProps.attach; - return { - memoized, - changes - }; -} // This function applies a set of changes to the instance - -function applyProps$1(instance, data) { - var _instance$__r3f3, _root$getState; - - // Filter equals, events and reserved props - const localState = (_instance$__r3f3 = instance.__r3f) != null ? _instance$__r3f3 : {}; - const root = localState.root; - const rootState = (_root$getState = root == null ? void 0 : root.getState == null ? void 0 : root.getState()) != null ? _root$getState : {}; - const { - memoized, - changes - } = isDiffSet(data) ? data : diffProps(instance, data); - const prevHandlers = localState.eventCount; // Prepare memoized props - - if (instance.__r3f) instance.__r3f.memoizedProps = memoized; - changes.forEach(([key, value, isEvent, keys]) => { - let currentInstance = instance; - let targetProp = currentInstance[key]; // Revolve dashed props - - if (keys.length) { - targetProp = keys.reduce((acc, key) => acc[key], instance); // If the target is atomic, it forces us to switch the root - - if (!(targetProp && targetProp.set)) { - const [name, ...reverseEntries] = keys.reverse(); - currentInstance = reverseEntries.reverse().reduce((acc, key) => acc[key], instance); - key = name; - } - } // https://github.com/mrdoob/three.js/issues/21209 - // HMR/fast-refresh relies on the ability to cancel out props, but threejs - // has no means to do this. Hence we curate a small collection of value-classes - // with their respective constructor/set arguments - // For removed props, try to set default values, if possible - - - if (value === DEFAULT + 'remove') { - if (targetProp && targetProp.constructor) { - var _memoized$args; - - // use the prop constructor to find the default it should be - value = new targetProp.constructor(...((_memoized$args = memoized.args) != null ? _memoized$args : [])); - } else if (currentInstance.constructor) { - var _currentInstance$__r; - - // create a blank slate of the instance and copy the particular parameter. - // @ts-ignore - const defaultClassCall = new currentInstance.constructor(...((_currentInstance$__r = currentInstance.__r3f.memoizedProps.args) != null ? _currentInstance$__r : [])); - value = defaultClassCall[targetProp]; // destory the instance - - if (defaultClassCall.dispose) defaultClassCall.dispose(); // instance does not have constructor, just set it to 0 - } else { - value = 0; - } - } // Deal with pointer events ... - - - if (isEvent) { - if (value) localState.handlers[key] = value;else delete localState.handlers[key]; - localState.eventCount = Object.keys(localState.handlers).length; - } // Special treatment for objects with support for set/copy, and layers - else if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof Layers)) { - // If value is an array - if (Array.isArray(value)) { - if (targetProp.fromArray) targetProp.fromArray(value);else targetProp.set(...value); - } // Test again target.copy(class) next ... - else if (targetProp.copy && value && value.constructor && targetProp.constructor.name === value.constructor.name) { - targetProp.copy(value); - } // If nothing else fits, just set the single value, ignore undefined - // https://github.com/pmndrs/react-three-fiber/issues/274 - else if (value !== undefined) { - const isColor = targetProp instanceof Color; // Allow setting array scalars - - if (!isColor && targetProp.setScalar) targetProp.setScalar(value); // Layers have no copy function, we must therefore copy the mask property - else if (targetProp instanceof Layers && value instanceof Layers) targetProp.mask = value.mask; // Otherwise just set ... - else targetProp.set(value); // For versions of three which don't support THREE.ColorManagement, - // Auto-convert sRGB colors - // https://github.com/pmndrs/react-three-fiber/issues/344 - - const supportsColorManagement = ('ColorManagement' in THREE); - if (!supportsColorManagement && !rootState.linear && isColor) targetProp.convertSRGBToLinear(); - } // Else, just overwrite the value - - } else { - currentInstance[key] = value; // Auto-convert sRGB textures, for now ... - // https://github.com/pmndrs/react-three-fiber/issues/344 - - if (!rootState.linear && currentInstance[key] instanceof Texture) { - currentInstance[key].encoding = sRGBEncoding; - } - } - - invalidateInstance(instance); - }); - - if (localState.parent && rootState.internal && instance.raycast && prevHandlers !== localState.eventCount) { - // Pre-emptively remove the instance from the interaction manager - const index = rootState.internal.interaction.indexOf(instance); - if (index > -1) rootState.internal.interaction.splice(index, 1); // Add the instance to the interaction manager only when it has handlers - - if (localState.eventCount) rootState.internal.interaction.push(instance); - } // Call the update lifecycle when it is being updated, but only when it is part of the scene - - - if (changes.length && instance.parent) updateInstance(instance); - return instance; -} -function invalidateInstance(instance) { - var _instance$__r3f4, _instance$__r3f4$root; - - const state = (_instance$__r3f4 = instance.__r3f) == null ? void 0 : (_instance$__r3f4$root = _instance$__r3f4.root) == null ? void 0 : _instance$__r3f4$root.getState == null ? void 0 : _instance$__r3f4$root.getState(); - if (state && state.internal.frames === 0) state.invalidate(); -} -function updateInstance(instance) { - instance.onUpdate == null ? void 0 : instance.onUpdate(instance); -} -function updateCamera(camera, size) { - // https://github.com/pmndrs/react-three-fiber/issues/92 - // Do not mess with the camera if it belongs to the user - if (!camera.manual) { - if (isOrthographicCamera(camera)) { - camera.left = size.width / -2; - camera.right = size.width / 2; - camera.top = size.height / 2; - camera.bottom = size.height / -2; - } else { - camera.aspect = size.width / size.height; - } - - camera.updateProjectionMatrix(); // https://github.com/pmndrs/react-three-fiber/issues/178 - // Update matrix world since the renderer is a frame late - - camera.updateMatrixWorld(); - } -} -/** - * Safely sets a deeply-nested value on an object. - */ - -function setDeep(obj, value, keys) { - const key = keys.pop(); - const target = keys.reduce((acc, key) => acc[key], obj); - return target[key] = value; -} - -function makeId(event) { - return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId; -} // https://github.com/facebook/react/tree/main/packages/react-reconciler#getcurrenteventpriority -// Gives React a clue as to how import the current interaction is - - -function getEventPriority() { - var _window, _window$event; - - let name = (_window = window) == null ? void 0 : (_window$event = _window.event) == null ? void 0 : _window$event.type; - - switch (name) { - case 'click': - case 'contextmenu': - case 'dblclick': - case 'pointercancel': - case 'pointerdown': - case 'pointerup': - return constants$1.exports.DiscreteEventPriority; - - case 'pointermove': - case 'pointerout': - case 'pointerover': - case 'pointerenter': - case 'pointerleave': - case 'wheel': - return constants$1.exports.ContinuousEventPriority; - - default: - return constants$1.exports.DefaultEventPriority; - } -} -/** - * Release pointer captures. - * This is called by releasePointerCapture in the API, and when an object is removed. - */ - -function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) { - const captureData = captures.get(obj); - - if (captureData) { - captures.delete(obj); // If this was the last capturing object for this pointer - - if (captures.size === 0) { - capturedMap.delete(pointerId); - captureData.target.releasePointerCapture(pointerId); - } - } -} - -function removeInteractivity(store, object) { - const { - internal - } = store.getState(); // Removes every trace of an object from the data store - - internal.interaction = internal.interaction.filter(o => o !== object); - internal.initialHits = internal.initialHits.filter(o => o !== object); - internal.hovered.forEach((value, key) => { - if (value.eventObject === object || value.object === object) { - // Clear out intersects, they are outdated by now - internal.hovered.delete(key); - } - }); - internal.capturedMap.forEach((captures, pointerId) => { - releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId); - }); -} -function createEvents(store) { - const temp = new Vector3(); - /** Calculates delta */ - - function calculateDistance(event) { - const { - internal - } = store.getState(); - const dx = event.offsetX - internal.initialClick[0]; - const dy = event.offsetY - internal.initialClick[1]; - return Math.round(Math.sqrt(dx * dx + dy * dy)); - } - /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */ - - - function filterPointerEvents(objects) { - return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => { - var _r3f; - - return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers['onPointer' + name]; - })); - } - - function intersect(event, filter) { - const state = store.getState(); - const duplicates = new Set(); - const intersections = []; // Allow callers to eliminate event objects - - const eventsObjects = filter ? filter(state.internal.interaction) : state.internal.interaction; // Reset all raycaster cameras to undefined - - eventsObjects.forEach(obj => { - const state = getRootState(obj); - - if (state) { - state.raycaster.camera = undefined; - } - }); - - if (!state.previousRoot) { - // Make sure root-level pointer and ray are set up - state.events.compute == null ? void 0 : state.events.compute(event, state); - } // Collect events - - - let hits = eventsObjects // Intersect objects - .flatMap(obj => { - const state = getRootState(obj); // Skip event handling when noEvents is set, or when the raycasters camera is null - - if (!state || !state.events.enabled || state.raycaster.camera === null) return []; // When the camera is undefined we have to call the event layers update function - - if (state.raycaster.camera === undefined) { - var _state$previousRoot; - - state.events.compute == null ? void 0 : state.events.compute(event, state, (_state$previousRoot = state.previousRoot) == null ? void 0 : _state$previousRoot.getState()); // If the camera is still undefined we have to skip this layer entirely - - if (state.raycaster.camera === undefined) state.raycaster.camera = null; - } // Intersect object by object - - - return state.raycaster.camera ? state.raycaster.intersectObject(obj, true) : []; - }) // Sort by event priority and distance - .sort((a, b) => { - const aState = getRootState(a.object); - const bState = getRootState(b.object); - if (!aState || !bState) return 0; - return bState.events.priority - aState.events.priority || a.distance - b.distance; - }) // Filter out duplicates - .filter(item => { - const id = makeId(item); - if (duplicates.has(id)) return false; - duplicates.add(id); - return true; - }); // https://github.com/mrdoob/three.js/issues/16031 - // Allow custom userland intersect sort order, this likely only makes sense on the root filter - - if (state.events.filter) hits = state.events.filter(hits, state); // Bubble up the events, find the event source (eventObject) - - for (const hit of hits) { - let eventObject = hit.object; // Bubble event up - - while (eventObject) { - var _r3f2; - - if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({ ...hit, - eventObject - }); - eventObject = eventObject.parent; - } - } // If the interaction is captured, make all capturing targets part of the intersect. - - - if ('pointerId' in event && state.internal.capturedMap.has(event.pointerId)) { - for (let captureData of state.internal.capturedMap.get(event.pointerId).values()) { - intersections.push(captureData.intersection); - } - } - - return intersections; - } - /** Handles intersections by forwarding them to handlers */ - - - function handleIntersects(intersections, event, delta, callback) { - const { - raycaster, - pointer, - camera, - internal - } = store.getState(); // If anything has been found, forward it to the event listeners - - if (intersections.length) { - const unprojectedPoint = temp.set(pointer.x, pointer.y, 0).unproject(camera); - const localState = { - stopped: false - }; - - for (const hit of intersections) { - const hasPointerCapture = id => { - var _internal$capturedMap, _internal$capturedMap2; - - return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false; - }; - - const setPointerCapture = id => { - const captureData = { - intersection: hit, - target: event.target - }; - - if (internal.capturedMap.has(id)) { - // if the pointerId was previously captured, we add the hit to the - // event capturedMap. - internal.capturedMap.get(id).set(hit.eventObject, captureData); - } else { - // if the pointerId was not previously captured, we create a map - // containing the hitObject, and the hit. hitObject is used for - // faster access. - internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]])); - } // Call the original event now - event.target.setPointerCapture(id); - }; - - const releasePointerCapture = id => { - const captures = internal.capturedMap.get(id); - - if (captures) { - releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id); - } - }; // Add native event props - - - let extractEventProps = {}; // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones. - - for (let prop in event) { - let property = event[prop]; // Only copy over atomics, leave functions alone as these should be - // called as event.nativeEvent.fn() - - if (typeof property !== 'function') extractEventProps[prop] = property; - } - - let raycastEvent = { ...hit, - ...extractEventProps, - pointer, - intersections, - stopped: localState.stopped, - delta, - unprojectedPoint, - ray: raycaster.ray, - camera: camera, - // Hijack stopPropagation, which just sets a flag - stopPropagation: () => { - // https://github.com/pmndrs/react-three-fiber/issues/596 - // Events are not allowed to stop propagation if the pointer has been captured - const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId); // We only authorize stopPropagation... - - if ( // ...if this pointer hasn't been captured - !capturesForPointer || // ... or if the hit object is capturing the pointer - capturesForPointer.has(hit.eventObject)) { - raycastEvent.stopped = localState.stopped = true; // Propagation is stopped, remove all other hover records - // An event handler is only allowed to flush other handlers if it is hovered itself - - if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) { - // Objects cannot flush out higher up objects that have already caught the event - const higher = intersections.slice(0, intersections.indexOf(hit)); - cancelPointer([...higher, hit]); - } - } - }, - // there should be a distinction between target and currentTarget - target: { - hasPointerCapture, - setPointerCapture, - releasePointerCapture - }, - currentTarget: { - hasPointerCapture, - setPointerCapture, - releasePointerCapture - }, - nativeEvent: event - }; // Call subscribers - - callback(raycastEvent); // Event bubbling may be interrupted by stopPropagation - - if (localState.stopped === true) break; - } - } - - return intersections; - } - - function cancelPointer(intersections) { - const { - internal - } = store.getState(); - Array.from(internal.hovered.values()).forEach(hoveredObj => { - // When no objects were hit or the the hovered object wasn't found underneath the cursor - // we call onPointerOut and delete the object from the hovered-elements map - if (!intersections.length || !intersections.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) { - const eventObject = hoveredObj.eventObject; - const instance = eventObject.__r3f; - const handlers = instance == null ? void 0 : instance.handlers; - internal.hovered.delete(makeId(hoveredObj)); - - if (instance != null && instance.eventCount) { - // Clear out intersects, they are outdated by now - const data = { ...hoveredObj, - intersections - }; - handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data); - handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data); - } - } - }); - } - - const handlePointer = name => { - // Deal with cancelation - switch (name) { - case 'onPointerLeave': - case 'onPointerCancel': - return () => cancelPointer([]); - - case 'onLostPointerCapture': - return event => { - const { - internal - } = store.getState(); - - if ('pointerId' in event && !internal.capturedMap.has(event.pointerId)) { - // If the object event interface had onLostPointerCapture, we'd call it here on every - // object that's getting removed. - internal.capturedMap.delete(event.pointerId); - cancelPointer([]); - } - }; - } // Any other pointer goes here ... - - - return event => { - const { - onPointerMissed, - internal - } = store.getState(); //prepareRay(event) - - internal.lastEvent.current = event; // Get fresh intersects - - const isPointerMove = name === 'onPointerMove'; - const isClickEvent = name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick'; - const filter = isPointerMove ? filterPointerEvents : undefined; //const hits = patchIntersects(intersect(filter), event) - - const hits = intersect(event, filter); - const delta = isClickEvent ? calculateDistance(event) : 0; // Save initial coordinates on pointer-down - - if (name === 'onPointerDown') { - internal.initialClick = [event.offsetX, event.offsetY]; - internal.initialHits = hits.map(hit => hit.eventObject); - } // If a click yields no results, pass it back to the user as a miss - // Missed events have to come first in order to establish user-land side-effect clean up - - - if (isClickEvent && !hits.length) { - if (delta <= 2) { - pointerMissed(event, internal.interaction); - if (onPointerMissed) onPointerMissed(event); - } - } // Take care of unhover - - - if (isPointerMove) cancelPointer(hits); - handleIntersects(hits, event, delta, data => { - const eventObject = data.eventObject; - const instance = eventObject.__r3f; - const handlers = instance == null ? void 0 : instance.handlers; // Check presence of handlers - - if (!(instance != null && instance.eventCount)) return; - - if (isPointerMove) { - // Move event ... - if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) { - // When enter or out is present take care of hover-state - const id = makeId(data); - const hoveredItem = internal.hovered.get(id); - - if (!hoveredItem) { - // If the object wasn't previously hovered, book it and call its handler - internal.hovered.set(id, data); - handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data); - handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data); - } else if (hoveredItem.stopped) { - // If the object was previously hovered and stopped, we shouldn't allow other items to proceed - data.stopPropagation(); - } - } // Call mouse move - - - handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data); - } else { - // All other events ... - const handler = handlers[name]; - - if (handler) { - // Forward all events back to their respective handlers with the exception of click events, - // which must use the initial target - if (!isClickEvent || internal.initialHits.includes(eventObject)) { - // Missed events have to come first - pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); // Now call the handler - - handler(data); - } - } else { - // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit - if (isClickEvent && internal.initialHits.includes(eventObject)) { - pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); - } - } - } - }); - }; - }; - - function pointerMissed(event, objects) { - objects.forEach(object => { - var _r3f3; - - return (_r3f3 = object.__r3f) == null ? void 0 : _r3f3.handlers.onPointerMissed == null ? void 0 : _r3f3.handlers.onPointerMissed(event); - }); - } - - return { - handlePointer - }; -} - -let catalogue = {}; - -let extend = objects => void (catalogue = { ...catalogue, - ...objects -}); - -function createRenderer(roots, getEventPriority) { - function createInstance(type, { - args = [], - attach, - ...props - }, root) { - let name = `${type[0].toUpperCase()}${type.slice(1)}`; - let instance; // Auto-attach geometries and materials - - if (attach === undefined) { - if (name.endsWith('Geometry')) attach = 'geometry';else if (name.endsWith('Material')) attach = 'material'; - } - - if (type === 'primitive') { - if (props.object === undefined) throw `Primitives without 'object' are invalid!`; - const object = props.object; - instance = prepare(object, { - type, - root, - attach, - primitive: true - }); - } else { - const target = catalogue[name]; - - if (!target) { - throw `${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`; - } // Throw if an object or literal was passed for args - - - if (!Array.isArray(args)) throw 'The args prop must be an array!'; // Instanciate new object, link it to the root - // Append memoized props with args so it's not forgotten - - instance = prepare(new target(...args), { - type, - root, - attach, - // Save args in case we need to reconstruct later for HMR - memoizedProps: { - args - } - }); - } // It should NOT call onUpdate on object instanciation, because it hasn't been added to the - // view yet. If the callback relies on references for instance, they won't be ready yet, this is - // why it passes "true" here - // There is no reason to apply props to injects - - - if (name !== 'inject') applyProps$1(instance, props); - return instance; - } - - function appendChild(parentInstance, child) { - let added = false; - - if (child) { - var _child$__r3f, _parentInstance$__r3f; - - // The attach attribute implies that the object attaches itself on the parent - if ((_child$__r3f = child.__r3f) != null && _child$__r3f.attach) { - attach(parentInstance, child, child.__r3f.attach); - } else if (child.isObject3D && parentInstance.isObject3D) { - // add in the usual parent-child way - parentInstance.add(child); - added = true; - } // This is for anything that used attach, and for non-Object3Ds that don't get attached to props; - // that is, anything that's a child in React but not a child in the scenegraph. - - - if (!added) (_parentInstance$__r3f = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f.objects.push(child); - if (!child.__r3f) prepare(child, {}); - child.__r3f.parent = parentInstance; - updateInstance(child); - invalidateInstance(child); - } - } - - function insertBefore(parentInstance, child, beforeChild) { - let added = false; - - if (child) { - var _child$__r3f2, _parentInstance$__r3f2; - - if ((_child$__r3f2 = child.__r3f) != null && _child$__r3f2.attach) { - attach(parentInstance, child, child.__r3f.attach); - } else if (child.isObject3D && parentInstance.isObject3D) { - child.parent = parentInstance; - child.dispatchEvent({ - type: 'added' - }); - const restSiblings = parentInstance.children.filter(sibling => sibling !== child); - const index = restSiblings.indexOf(beforeChild); - parentInstance.children = [...restSiblings.slice(0, index), child, ...restSiblings.slice(index)]; - added = true; - } - - if (!added) (_parentInstance$__r3f2 = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f2.objects.push(child); - if (!child.__r3f) prepare(child, {}); - child.__r3f.parent = parentInstance; - updateInstance(child); - invalidateInstance(child); - } - } - - function removeRecursive(array, parent, dispose = false) { - if (array) [...array].forEach(child => removeChild(parent, child, dispose)); - } - - function removeChild(parentInstance, child, dispose) { - if (child) { - var _parentInstance$__r3f3, _child$__r3f3, _child$__r3f5; - - // Clear the parent reference - if (child.__r3f) child.__r3f.parent = null; // Remove child from the parents objects - - if ((_parentInstance$__r3f3 = parentInstance.__r3f) != null && _parentInstance$__r3f3.objects) parentInstance.__r3f.objects = parentInstance.__r3f.objects.filter(x => x !== child); // Remove attachment - - if ((_child$__r3f3 = child.__r3f) != null && _child$__r3f3.attach) { - detach(parentInstance, child, child.__r3f.attach); - } else if (child.isObject3D && parentInstance.isObject3D) { - var _child$__r3f4; - - parentInstance.remove(child); // Remove interactivity - - if ((_child$__r3f4 = child.__r3f) != null && _child$__r3f4.root) { - removeInteractivity(child.__r3f.root, child); - } - } // Allow objects to bail out of recursive dispose altogether by passing dispose={null} - // Never dispose of primitives because their state may be kept outside of React! - // In order for an object to be able to dispose it has to have - // - a dispose method, - // - it cannot be a - // - it cannot be a THREE.Scene, because three has broken it's own api - // - // Since disposal is recursive, we can check the optional dispose arg, which will be undefined - // when the reconciler calls it, but then carry our own check recursively - - - const isPrimitive = (_child$__r3f5 = child.__r3f) == null ? void 0 : _child$__r3f5.primitive; - const shouldDispose = dispose === undefined ? child.dispose !== null && !isPrimitive : dispose; // Remove nested child objects. Primitives should not have objects and children that are - // attached to them declaratively ... - - if (!isPrimitive) { - var _child$__r3f6; - - removeRecursive((_child$__r3f6 = child.__r3f) == null ? void 0 : _child$__r3f6.objects, child, shouldDispose); - removeRecursive(child.children, child, shouldDispose); - } // Remove references - - - if (child.__r3f) { - delete child.__r3f.root; - delete child.__r3f.objects; - delete child.__r3f.handlers; - delete child.__r3f.memoizedProps; - if (!isPrimitive) delete child.__r3f; - } // Dispose item whenever the reconciler feels like it - - - if (shouldDispose && child.dispose && child.type !== 'Scene') { - scheduler$1.exports.unstable_scheduleCallback(scheduler$1.exports.unstable_IdlePriority, () => { - try { - child.dispose(); - } catch (e) { - /* ... */ - } - }); - } - - invalidateInstance(parentInstance); - } - } - - function switchInstance(instance, type, newProps, fiber) { - var _instance$__r3f; - - const parent = (_instance$__r3f = instance.__r3f) == null ? void 0 : _instance$__r3f.parent; - if (!parent) return; - const newInstance = createInstance(type, newProps, instance.__r3f.root); // https://github.com/pmndrs/react-three-fiber/issues/1348 - // When args change the instance has to be re-constructed, which then - // forces r3f to re-parent the children and non-scene objects - // This can not include primitives, which should not have declarative children - - if (type !== 'primitive' && instance.children) { - instance.children.forEach(child => appendChild(newInstance, child)); - instance.children = []; - } - - instance.__r3f.objects.forEach(child => appendChild(newInstance, child)); - - instance.__r3f.objects = []; - removeChild(parent, instance); - appendChild(parent, newInstance); // Re-bind event handlers - - if (newInstance.raycast && newInstance.__r3f.eventCount) { - const rootState = newInstance.__r3f.root.getState(); - - rootState.internal.interaction.push(newInstance); - } // This evil hack switches the react-internal fiber node - [fiber, fiber.alternate].forEach(fiber => { - if (fiber !== null) { - fiber.stateNode = newInstance; - - if (fiber.ref) { - if (typeof fiber.ref === 'function') fiber.ref(newInstance);else fiber.ref.current = newInstance; - } - } - }); - } - - const reconciler = Reconciler({ - createInstance, - removeChild, - appendChild, - appendInitialChild: appendChild, - insertBefore, - supportsMicrotask: true, - warnsIfNotActing: true, - supportsMutation: true, - isPrimaryRenderer: false, - noTimeout: -1, - appendChildToContainer: (container, child) => { - const scene = container.getState().scene; // Link current root to the default scene - - scene.__r3f.root = container; - appendChild(scene, child); - }, - removeChildFromContainer: (container, child) => removeChild(container.getState().scene, child), - insertInContainerBefore: (container, child, beforeChild) => insertBefore(container.getState().scene, child, beforeChild), - getRootHostContext: () => null, - getChildHostContext: parentHostContext => parentHostContext, - - finalizeInitialChildren(instance) { - var _instance$__r3f2; - - const localState = (_instance$__r3f2 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f2 : {}; // https://github.com/facebook/react/issues/20271 - // Returning true will trigger commitMount - - return !!localState.handlers; - }, - - prepareUpdate(instance, type, oldProps, newProps) { - // Create diff-sets - if (instance.__r3f.primitive && newProps.object && newProps.object !== instance) { - return [true]; - } else { - // This is a data object, let's extract critical information about it - const { - args: argsNew = [], - children: cN, - ...restNew - } = newProps; - const { - args: argsOld = [], - children: cO, - ...restOld - } = oldProps; // Throw if an object or literal was passed for args - - if (!Array.isArray(argsNew)) throw 'The args prop must be an array!'; // If it has new props or arguments, then it needs to be re-instanciated - - if (argsNew.some((value, index) => value !== argsOld[index])) return [true]; // Create a diff-set, flag if there are any changes - - const diff = diffProps(instance, restNew, restOld, true); - if (diff.changes.length) return [false, diff]; // Otherwise do not touch the instance - - return null; - } - }, - - commitUpdate(instance, [reconstruct, diff], type, oldProps, newProps, fiber) { - // Reconstruct when args or instance, - shouldDeprioritizeSubtree: () => false, - prepareForCommit: () => null, - preparePortalMount: container => prepare(container.getState().scene), - resetAfterCommit: () => {}, - shouldSetTextContent: () => false, - clearContainer: () => false, - detachDeletedInstance: () => {}, - - hideInstance(instance) { - var _instance$__r3f4; - - // Deatch while the instance is hidden - const { - attach: type, - parent - } = (_instance$__r3f4 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f4 : {}; - if (type && parent) detach(parent, instance, type); - if (instance.isObject3D) instance.visible = false; - invalidateInstance(instance); - }, - - unhideInstance(instance, props) { - var _instance$__r3f5; - - // Re-attach when the instance is unhidden - const { - attach: type, - parent - } = (_instance$__r3f5 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f5 : {}; - if (type && parent) attach(parent, instance, type); - if (instance.isObject3D && props.visible == null || props.visible) instance.visible = true; - invalidateInstance(instance); - }, - - createTextInstance: () => {}, - hideTextInstance: () => { - throw new Error('Text is not allowed in the R3F tree.'); - }, - unhideTextInstance: () => {}, - getCurrentEventPriority: () => getEventPriority ? getEventPriority() : constants$1.exports.DefaultEventPriority, - // @ts-ignore - now: typeof performance !== 'undefined' && is$1.fun(performance.now) ? performance.now : is$1.fun(Date.now) ? Date.now : undefined, - // @ts-ignore - scheduleTimeout: is$1.fun(setTimeout) ? setTimeout : undefined, - // @ts-ignore - cancelTimeout: is$1.fun(clearTimeout) ? clearTimeout : undefined, - setTimeout: is$1.fun(setTimeout) ? setTimeout : undefined, - clearTimeout: is$1.fun(clearTimeout) ? clearTimeout : undefined - }); - return { - reconciler, - applyProps: applyProps$1 - }; -} -const isRenderer = def => !!(def != null && def.render); -const context = /*#__PURE__*/React__namespace.createContext(null); - -const createStore$2 = (invalidate, advance) => { - const rootState = create$4((set, get) => { - const position = new Vector3(); - const defaultTarget = new Vector3(); - const tempTarget = new Vector3(); - - function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) { - const { - width, - height - } = size; - const aspect = width / height; - if (target instanceof Vector3) tempTarget.copy(target);else tempTarget.set(...target); - const distance = camera.getWorldPosition(position).distanceTo(tempTarget); - - if (isOrthographicCamera(camera)) { - return { - width: width / camera.zoom, - height: height / camera.zoom, - factor: 1, - distance, - aspect - }; - } else { - const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians - - const h = 2 * Math.tan(fov / 2) * distance; // visible height - - const w = h * (width / height); - return { - width: w, - height: h, - factor: width / w, - distance, - aspect - }; - } - } - - let performanceTimeout = undefined; - - const setPerformanceCurrent = current => set(state => ({ - performance: { ...state.performance, - current - } - })); - - const pointer = new Vector2(); - return { - set, - get, - // Mock objects that have to be configured - gl: null, - camera: null, - raycaster: null, - events: { - priority: 1, - enabled: true, - connected: false - }, - xr: null, - invalidate: (frames = 1) => invalidate(get(), frames), - advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()), - legacy: false, - linear: false, - flat: false, - scene: prepare(new Scene$1()), - controls: null, - clock: new Clock(), - pointer, - mouse: pointer, - frameloop: 'always', - onPointerMissed: undefined, - performance: { - current: 1, - min: 0.5, - max: 1, - debounce: 200, - regress: () => { - const state = get(); // Clear timeout - - if (performanceTimeout) clearTimeout(performanceTimeout); // Set lower bound performance - - if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min); // Go back to upper bound performance after a while unless something regresses meanwhile - - performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce); - } - }, - size: { - width: 0, - height: 0, - updateStyle: false - }, - viewport: { - initialDpr: 0, - dpr: 0, - width: 0, - height: 0, - aspect: 0, - distance: 0, - factor: 0, - getCurrentViewport - }, - setEvents: events => set(state => ({ ...state, - events: { ...state.events, - ...events - } - })), - setSize: (width, height, updateStyle) => { - const camera = get().camera; - const size = { - width, - height, - updateStyle - }; - set(state => ({ - size, - viewport: { ...state.viewport, - ...getCurrentViewport(camera, defaultTarget, size) - } - })); - }, - setDpr: dpr => set(state => { - const resolved = calculateDpr(dpr); - return { - viewport: { ...state.viewport, - dpr: resolved, - initialDpr: state.viewport.initialDpr || resolved - } - }; - }), - setFrameloop: (frameloop = 'always') => { - const clock = get().clock; // if frameloop === "never" clock.elapsedTime is updated using advance(timestamp) - - clock.stop(); - clock.elapsedTime = 0; - - if (frameloop !== 'never') { - clock.start(); - clock.elapsedTime = 0; - } - - set(() => ({ - frameloop - })); - }, - previousRoot: undefined, - internal: { - active: false, - priority: 0, - frames: 0, - lastEvent: /*#__PURE__*/React__namespace.createRef(), - interaction: [], - hovered: new Map(), - subscribers: [], - initialClick: [0, 0], - initialHits: [], - capturedMap: new Map(), - subscribe: (ref, priority, store) => { - const internal = get().internal; // If this subscription was given a priority, it takes rendering into its own hands - // For that reason we switch off automatic rendering and increase the manual flag - // As long as this flag is positive there can be no internal rendering at all - // because there could be multiple render subscriptions - - internal.priority = internal.priority + (priority > 0 ? 1 : 0); - internal.subscribers.push({ - ref, - priority, - store - }); // Register subscriber and sort layers from lowest to highest, meaning, - // highest priority renders last (on top of the other frames) - - internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority); - return () => { - const internal = get().internal; - - if (internal != null && internal.subscribers) { - // Decrease manual flag if this subscription had a priority - internal.priority = internal.priority - (priority > 0 ? 1 : 0); // Remove subscriber from list - - internal.subscribers = internal.subscribers.filter(s => s.ref !== ref); - } - }; - } - } - }; - }); - const state = rootState.getState(); - let oldSize = state.size; - let oldDpr = state.viewport.dpr; - let oldCamera = state.camera; - rootState.subscribe(() => { - const { - camera, - size, - viewport, - gl, - set - } = rootState.getState(); // Resize camera and renderer on changes to size and pixelratio - - if (size !== oldSize || viewport.dpr !== oldDpr) { - oldSize = size; - oldDpr = viewport.dpr; // Update camera & renderer - - updateCamera(camera, size); - gl.setPixelRatio(viewport.dpr); - gl.setSize(size.width, size.height, size.updateStyle); - } // Update viewport once the camera changes - - - if (camera !== oldCamera) { - oldCamera = camera; // Update viewport - - set(state => ({ - viewport: { ...state.viewport, - ...state.viewport.getCurrentViewport(camera) - } - })); - } - }); // Invalidate on any change - - rootState.subscribe(state => invalidate(state)); // Return root state - - return rootState; -}; - -function createSubs(callback, subs) { - const index = subs.length; - subs.push(callback); - return () => void subs.splice(index, 1); -} - -let i$4; -let globalEffects = []; -let globalAfterEffects = []; -let globalTailEffects = []; -/** - * Adds a global render callback which is called each frame. - * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect - */ - -const addEffect = callback => createSubs(callback, globalEffects); - -function run(effects, timestamp) { - for (i$4 = 0; i$4 < effects.length; i$4++) effects[i$4](timestamp); -} - -let subscribers; -let subscription; - -function render$1(timestamp, state, frame) { - // Run local effects - let delta = state.clock.getDelta(); // In frameloop='never' mode, clock times are updated using the provided timestamp - - if (state.frameloop === 'never' && typeof timestamp === 'number') { - delta = timestamp - state.clock.elapsedTime; - state.clock.oldTime = state.clock.elapsedTime; - state.clock.elapsedTime = timestamp; - } // Call subscribers (useFrame) - - - subscribers = state.internal.subscribers; - - for (i$4 = 0; i$4 < subscribers.length; i$4++) { - subscription = subscribers[i$4]; - subscription.ref.current(subscription.store.getState(), delta, frame); - } // Render content - - - if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera); // Decrease frame count - - state.internal.frames = Math.max(0, state.internal.frames - 1); - return state.frameloop === 'always' ? 1 : state.internal.frames; -} - -function createLoop(roots) { - let running = false; - let repeat; - let frame; - let state; - - function loop(timestamp) { - frame = requestAnimationFrame(loop); - running = true; - repeat = 0; // Run effects - - if (globalEffects.length) run(globalEffects, timestamp); // Render all roots - - roots.forEach(root => { - var _state$gl$xr; - - state = root.store.getState(); // If the frameloop is invalidated, do not run another frame - - if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) { - repeat += render$1(timestamp, state); - } - }); // Run after-effects - - if (globalAfterEffects.length) run(globalAfterEffects, timestamp); // Stop the loop if nothing invalidates it - - if (repeat === 0) { - // Tail call effects, they are called when rendering stops - if (globalTailEffects.length) run(globalTailEffects, timestamp); // Flag end of operation - - running = false; - return cancelAnimationFrame(frame); - } - } - - function invalidate(state, frames = 1) { - var _state$gl$xr2; - - if (!state) return roots.forEach(root => invalidate(root.store.getState()), frames); - if ((_state$gl$xr2 = state.gl.xr) != null && _state$gl$xr2.isPresenting || !state.internal.active || state.frameloop === 'never') return; // Increase frames, do not go higher than 60 - - state.internal.frames = Math.min(60, state.internal.frames + frames); // If the render-loop isn't active, start it - - if (!running) { - running = true; - requestAnimationFrame(loop); - } - } - - function advance(timestamp, runGlobalEffects = true, state, frame) { - if (runGlobalEffects) run(globalEffects, timestamp); - if (!state) roots.forEach(root => render$1(timestamp, root.store.getState()));else render$1(timestamp, state, frame); - if (runGlobalEffects) run(globalAfterEffects, timestamp); - } - - return { - loop, - - /** - * Invalidates the view, requesting a frame to be rendered. Will globally invalidate unless passed a root's state. - * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate - */ - invalidate, - - /** - * Advances the frameloop and runs render effects, useful for when manually rendering via `frameloop="never"`. - * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance - */ - advance - }; -} - -function useStore$1() { - const store = React__namespace.useContext(context); - if (!store) throw `R3F hooks can only be used within the Canvas component!`; - return store; -} -/** - * Accesses R3F's internal state, containing renderer, canvas, scene, etc. - * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usethree - */ - -function useThree(selector = state => state, equalityFn) { - return useStore$1()(selector, equalityFn); -} -/** - * Executes a callback before render in a shared frame loop. - * Can order effects with render priority or manually render with a positive priority. - * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe - */ - -function useFrame(callback, renderPriority = 0) { - const store = useStore$1(); - const subscribe = store.getState().internal.subscribe; // Memoize ref - - const ref = useMutableCallback(callback); // Subscribe on mount, unsubscribe on unmount - - useIsomorphicLayoutEffect$1(() => subscribe(ref, renderPriority, store), [renderPriority, subscribe, store]); - return null; -} - -const roots = new Map(); -const { - invalidate, - advance: advance$1 -} = createLoop(roots); -const { - reconciler, - applyProps -} = createRenderer(roots, getEventPriority); -const shallowLoose = { - objects: 'shallow', - strict: false -}; - -const createRendererInstance = (gl, canvas) => { - const customRenderer = typeof gl === 'function' ? gl(canvas) : gl; - if (isRenderer(customRenderer)) return customRenderer;else return new WebGLRenderer({ - powerPreference: 'high-performance', - canvas: canvas, - antialias: true, - alpha: true, - ...gl - }); -}; - -function createRoot(canvas) { - // Check against mistaken use of createRoot - let prevRoot = roots.get(canvas); - let prevFiber = prevRoot == null ? void 0 : prevRoot.fiber; - let prevStore = prevRoot == null ? void 0 : prevRoot.store; - if (prevRoot) console.warn('R3F.createRoot should only be called once!'); // Report when an error was detected in a previous render - // https://github.com/pmndrs/react-three-fiber/pull/2261 - - const logRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event, - // emulating an uncaught JavaScript error. - reportError : // In older browsers and test environments, fallback to console.error. - console.error; // Create store - - const store = prevStore || createStore$2(invalidate, advance$1); // Create renderer - - const fiber = prevFiber || reconciler.createContainer(store, constants$1.exports.ConcurrentRoot, null, false, null, '', logRecoverableError, null); // Map it - - if (!prevRoot) roots.set(canvas, { - fiber, - store - }); // Locals - - let onCreated; - let configured = false; - return { - configure(props = {}) { - var _canvas$parentElement, _canvas$parentElement2, _canvas$parentElement3, _canvas$parentElement4; - - let { - gl: glConfig, - size, - events, - onCreated: onCreatedCallback, - shadows = false, - linear = false, - flat = false, - legacy = false, - orthographic = false, - frameloop = 'always', - dpr = [1, 2], - performance, - raycaster: raycastOptions, - camera: cameraOptions, - onPointerMissed - } = props; - let state = store.getState(); // Set up renderer (one time only!) - - let gl = state.gl; - if (!state.gl) state.set({ - gl: gl = createRendererInstance(glConfig, canvas) - }); // Set up raycaster (one time only!) - - let raycaster = state.raycaster; - if (!raycaster) state.set({ - raycaster: raycaster = new Raycaster() - }); // Set raycaster options - - const { - params, - ...options - } = raycastOptions || {}; - if (!is$1.equ(options, raycaster, shallowLoose)) applyProps(raycaster, { ...options - }); - if (!is$1.equ(params, raycaster.params, shallowLoose)) applyProps(raycaster, { - params: { ...raycaster.params, - ...params - } - }); // Create default camera (one time only!) - - if (!state.camera) { - const isCamera = cameraOptions instanceof Camera; - const camera = isCamera ? cameraOptions : orthographic ? new OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new PerspectiveCamera(75, 0, 0.1, 1000); - - if (!isCamera) { - camera.position.z = 5; - if (cameraOptions) applyProps(camera, cameraOptions); // Always look at center by default - - if (!(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0); - } - - state.set({ - camera - }); - } // Set up XR (one time only!) - - - if (!state.xr) { - // Handle frame behavior in WebXR - const handleXRFrame = (timestamp, frame) => { - const state = store.getState(); - if (state.frameloop === 'never') return; - advance$1(timestamp, true, state, frame); - }; // Toggle render switching on session - - - const handleSessionChange = () => { - const state = store.getState(); - state.gl.xr.enabled = state.gl.xr.isPresenting; - state.gl.xr.setAnimationLoop(state.gl.xr.isPresenting ? handleXRFrame : null); - if (!state.gl.xr.isPresenting) invalidate(state); - }; // WebXR session manager - - - const xr = { - connect() { - const gl = store.getState().gl; - gl.xr.addEventListener('sessionstart', handleSessionChange); - gl.xr.addEventListener('sessionend', handleSessionChange); - }, - - disconnect() { - const gl = store.getState().gl; - gl.xr.removeEventListener('sessionstart', handleSessionChange); - gl.xr.removeEventListener('sessionend', handleSessionChange); - } - - }; // Subscribe to WebXR session events - - if (gl.xr) xr.connect(); - state.set({ - xr - }); - } // Set shadowmap - - - if (gl.shadowMap) { - const isBoolean = is$1.boo(shadows); - - if (isBoolean && gl.shadowMap.enabled !== shadows || !is$1.equ(shadows, gl.shadowMap, shallowLoose)) { - const old = gl.shadowMap.enabled; - gl.shadowMap.enabled = !!shadows; - if (!isBoolean) Object.assign(gl.shadowMap, shadows);else gl.shadowMap.type = PCFSoftShadowMap; - if (old !== gl.shadowMap.enabled) gl.shadowMap.needsUpdate = true; - } - } // Safely set color management if available. - // Avoid accessing THREE.ColorManagement to play nice with older versions - - - if ('ColorManagement' in THREE) { - setDeep(THREE, legacy, ['ColorManagement', 'legacyMode']); - } - - const outputEncoding = linear ? LinearEncoding : sRGBEncoding; - const toneMapping = flat ? NoToneMapping : ACESFilmicToneMapping; - if (gl.outputEncoding !== outputEncoding) gl.outputEncoding = outputEncoding; - if (gl.toneMapping !== toneMapping) gl.toneMapping = toneMapping; // Update color management state - - if (state.legacy !== legacy) state.set(() => ({ - legacy - })); - if (state.linear !== linear) state.set(() => ({ - linear - })); - if (state.flat !== flat) state.set(() => ({ - flat - })); // Set gl props - - if (glConfig && !is$1.fun(glConfig) && !isRenderer(glConfig) && !is$1.equ(glConfig, gl, shallowLoose)) applyProps(gl, glConfig); // Store events internally - - if (events && !state.events.handlers) state.set({ - events: events(store) - }); // Check pixelratio - - if (dpr && state.viewport.dpr !== calculateDpr(dpr)) state.setDpr(dpr); // Check size, allow it to take on container bounds initially - - size = size || { - width: (_canvas$parentElement = (_canvas$parentElement2 = canvas.parentElement) == null ? void 0 : _canvas$parentElement2.clientWidth) != null ? _canvas$parentElement : 0, - height: (_canvas$parentElement3 = (_canvas$parentElement4 = canvas.parentElement) == null ? void 0 : _canvas$parentElement4.clientHeight) != null ? _canvas$parentElement3 : 0 - }; - if (!is$1.equ(size, state.size, shallowLoose)) state.setSize(size.width, size.height, size.updateStyle); // Check frameloop - - if (state.frameloop !== frameloop) state.setFrameloop(frameloop); // Check pointer missed - - if (!state.onPointerMissed) state.set({ - onPointerMissed - }); // Check performance - - if (performance && !is$1.equ(performance, state.performance, shallowLoose)) state.set(state => ({ - performance: { ...state.performance, - ...performance - } - })); // Set locals - - onCreated = onCreatedCallback; - configured = true; - return this; - }, - - render(children) { - // The root has to be configured before it can be rendered - if (!configured) this.configure(); - reconciler.updateContainer( /*#__PURE__*/React__namespace.createElement(Provider, { - store: store, - children: children, - onCreated: onCreated, - rootElement: canvas - }), fiber, null, () => undefined); - return store; - }, - - unmount() { - unmountComponentAtNode(canvas); - } - - }; -} - -function Provider({ - store, - children, - onCreated, - rootElement -}) { - useIsomorphicLayoutEffect$1(() => { - const state = store.getState(); // Flag the canvas active, rendering will now begin - - state.set(state => ({ - internal: { ...state.internal, - active: true - } - })); // Notifiy that init is completed, the scene graph exists, but nothing has yet rendered - - if (onCreated) onCreated(state); // Connect events to the targets parent, this is done to ensure events are registered on - // a shared target, and not on the canvas itself - - if (!store.getState().events.connected) state.events.connect == null ? void 0 : state.events.connect(rootElement); // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - return /*#__PURE__*/React__namespace.createElement(context.Provider, { - value: store - }, children); -} - -function unmountComponentAtNode(canvas, callback) { - const root = roots.get(canvas); - const fiber = root == null ? void 0 : root.fiber; - - if (fiber) { - const state = root == null ? void 0 : root.store.getState(); - if (state) state.internal.active = false; - reconciler.updateContainer(null, fiber, null, () => { - if (state) { - setTimeout(() => { - try { - var _state$gl, _state$gl$renderLists, _state$gl2, _state$gl3; - - state.events.disconnect == null ? void 0 : state.events.disconnect(); - (_state$gl = state.gl) == null ? void 0 : (_state$gl$renderLists = _state$gl.renderLists) == null ? void 0 : _state$gl$renderLists.dispose == null ? void 0 : _state$gl$renderLists.dispose(); - (_state$gl2 = state.gl) == null ? void 0 : _state$gl2.forceContextLoss == null ? void 0 : _state$gl2.forceContextLoss(); - if ((_state$gl3 = state.gl) != null && _state$gl3.xr) state.xr.disconnect(); - dispose(state); - roots.delete(canvas); - if (callback) callback(canvas); - } catch (e) { - /* ... */ - } - }, 500); - } - }); - } -} - -reconciler.injectIntoDevTools({ - bundleType: process.env.NODE_ENV === 'production' ? 0 : 1, - rendererPackageName: '@react-three/fiber', - version: React__namespace.version -}); - -function _extends$3() { - _extends$3 = Object.assign ? Object.assign.bind() : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - return _extends$3.apply(this, arguments); -} - -/** - * Returns a function, that, as long as it continues to be invoked, will not - * be triggered. The function will be called after it stops being called for - * N milliseconds. If `immediate` is passed, trigger the function on the - * leading edge, instead of the trailing. The function also has a property 'clear' - * that is a function which will clear the timer to prevent previously scheduled executions. - * - * @source underscore.js - * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ - * @param {Function} function to wrap - * @param {Number} timeout in ms (`100`) - * @param {Boolean} whether to execute at the beginning (`false`) - * @api public - */ - -function debounce(func, wait, immediate){ - var timeout, args, context, timestamp, result; - if (null == wait) wait = 100; - - function later() { - var last = Date.now() - timestamp; - - if (last < wait && last >= 0) { - timeout = setTimeout(later, wait - last); - } else { - timeout = null; - if (!immediate) { - result = func.apply(context, args); - context = args = null; - } - } - } - var debounced = function(){ - context = this; - args = arguments; - timestamp = Date.now(); - var callNow = immediate && !timeout; - if (!timeout) timeout = setTimeout(later, wait); - if (callNow) { - result = func.apply(context, args); - context = args = null; - } - - return result; - }; - - debounced.clear = function() { - if (timeout) { - clearTimeout(timeout); - timeout = null; - } - }; - - debounced.flush = function() { - if (timeout) { - result = func.apply(context, args); - context = args = null; - - clearTimeout(timeout); - timeout = null; - } - }; - - return debounced; -} -// Adds compatibility for ES modules -debounce.debounce = debounce; - -var debounce_1 = debounce; - -function useMeasure(_temp) { - let { - debounce, - scroll, - polyfill, - offsetSize - } = _temp === void 0 ? { - debounce: 0, - scroll: false, - offsetSize: false - } : _temp; - const ResizeObserver = polyfill || (typeof window === 'undefined' ? class ResizeObserver {} : window.ResizeObserver); - - if (!ResizeObserver) { - throw new Error('This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills'); - } - - const [bounds, set] = React.useState({ - left: 0, - top: 0, - width: 0, - height: 0, - bottom: 0, - right: 0, - x: 0, - y: 0 - }); // keep all state in a ref - - const state = React.useRef({ - element: null, - scrollContainers: null, - resizeObserver: null, - lastBounds: bounds - }); // set actual debounce values early, so effects know if they should react accordingly - - const scrollDebounce = debounce ? typeof debounce === 'number' ? debounce : debounce.scroll : null; - const resizeDebounce = debounce ? typeof debounce === 'number' ? debounce : debounce.resize : null; // make sure to update state only as long as the component is truly mounted - - const mounted = React.useRef(false); - React.useEffect(() => { - mounted.current = true; - return () => void (mounted.current = false); - }); // memoize handlers, so event-listeners know when they should update - - const [forceRefresh, resizeChange, scrollChange] = React.useMemo(() => { - const callback = () => { - if (!state.current.element) return; - const { - left, - top, - width, - height, - bottom, - right, - x, - y - } = state.current.element.getBoundingClientRect(); - const size = { - left, - top, - width, - height, - bottom, - right, - x, - y - }; - - if (state.current.element instanceof HTMLElement && offsetSize) { - size.height = state.current.element.offsetHeight; - size.width = state.current.element.offsetWidth; - } - - Object.freeze(size); - if (mounted.current && !areBoundsEqual(state.current.lastBounds, size)) set(state.current.lastBounds = size); - }; - - return [callback, resizeDebounce ? debounce_1(callback, resizeDebounce) : callback, scrollDebounce ? debounce_1(callback, scrollDebounce) : callback]; - }, [set, offsetSize, scrollDebounce, resizeDebounce]); // cleanup current scroll-listeners / observers - - function removeListeners() { - if (state.current.scrollContainers) { - state.current.scrollContainers.forEach(element => element.removeEventListener('scroll', scrollChange, true)); - state.current.scrollContainers = null; - } - - if (state.current.resizeObserver) { - state.current.resizeObserver.disconnect(); - state.current.resizeObserver = null; - } - } // add scroll-listeners / observers - - - function addListeners() { - if (!state.current.element) return; - state.current.resizeObserver = new ResizeObserver(scrollChange); - state.current.resizeObserver.observe(state.current.element); - - if (scroll && state.current.scrollContainers) { - state.current.scrollContainers.forEach(scrollContainer => scrollContainer.addEventListener('scroll', scrollChange, { - capture: true, - passive: true - })); - } - } // the ref we expose to the user - - - const ref = node => { - if (!node || node === state.current.element) return; - removeListeners(); - state.current.element = node; - state.current.scrollContainers = findScrollContainers(node); - addListeners(); - }; // add general event listeners - - - useOnWindowScroll(scrollChange, Boolean(scroll)); - useOnWindowResize(resizeChange); // respond to changes that are relevant for the listeners - - React.useEffect(() => { - removeListeners(); - addListeners(); - }, [scroll, scrollChange, resizeChange]); // remove all listeners when the components unmounts - - React.useEffect(() => removeListeners, []); - return [ref, bounds, forceRefresh]; -} // Adds native resize listener to window - - -function useOnWindowResize(onWindowResize) { - React.useEffect(() => { - const cb = onWindowResize; - window.addEventListener('resize', cb); - return () => void window.removeEventListener('resize', cb); - }, [onWindowResize]); -} - -function useOnWindowScroll(onScroll, enabled) { - React.useEffect(() => { - if (enabled) { - const cb = onScroll; - window.addEventListener('scroll', cb, { - capture: true, - passive: true - }); - return () => void window.removeEventListener('scroll', cb, true); - } - }, [onScroll, enabled]); -} // Returns a list of scroll offsets - - -function findScrollContainers(element) { - const result = []; - if (!element || element === document.body) return result; - const { - overflow, - overflowX, - overflowY - } = window.getComputedStyle(element); - if ([overflow, overflowX, overflowY].some(prop => prop === 'auto' || prop === 'scroll')) result.push(element); - return [...result, ...findScrollContainers(element.parentElement)]; -} // Checks if element boundaries are equal - - -const keys$a = ['x', 'y', 'top', 'bottom', 'left', 'right', 'width', 'height']; - -const areBoundsEqual = (a, b) => keys$a.every(key => a[key] === b[key]); - -const DOM_EVENTS = { - onClick: ['click', false], - onContextMenu: ['contextmenu', false], - onDoubleClick: ['dblclick', false], - onWheel: ['wheel', true], - onPointerDown: ['pointerdown', true], - onPointerUp: ['pointerup', true], - onPointerLeave: ['pointerleave', true], - onPointerMove: ['pointermove', true], - onPointerCancel: ['pointercancel', true], - onLostPointerCapture: ['lostpointercapture', true] -}; -/** Default R3F event manager for web */ - -function createPointerEvents(store) { - const { - handlePointer - } = createEvents(store); - return { - priority: 1, - enabled: true, - - compute(event, state, previous) { - // https://github.com/pmndrs/react-three-fiber/pull/782 - // Events trigger outside of canvas when moved, use offsetX/Y by default and allow overrides - state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1); - state.raycaster.setFromCamera(state.pointer, state.camera); - }, - - connected: undefined, - handlers: Object.keys(DOM_EVENTS).reduce((acc, key) => ({ ...acc, - [key]: handlePointer(key) - }), {}), - connect: target => { - var _events$handlers; - - const { - set, - events - } = store.getState(); - events.disconnect == null ? void 0 : events.disconnect(); - set(state => ({ - events: { ...state.events, - connected: target - } - })); - Object.entries((_events$handlers = events.handlers) != null ? _events$handlers : []).forEach(([name, event]) => { - const [eventName, passive] = DOM_EVENTS[name]; - target.addEventListener(eventName, event, { - passive - }); - }); - }, - disconnect: () => { - const { - set, - events - } = store.getState(); - - if (events.connected) { - var _events$handlers2; - - Object.entries((_events$handlers2 = events.handlers) != null ? _events$handlers2 : []).forEach(([name, event]) => { - if (events && events.connected instanceof HTMLElement) { - const [eventName] = DOM_EVENTS[name]; - events.connected.removeEventListener(eventName, event); - } - }); - set(state => ({ - events: { ...state.events, - connected: undefined - } - })); - } - } - }; -} - -/** - * A DOM canvas which accepts threejs elements as children. - * @see https://docs.pmnd.rs/react-three-fiber/api/canvas - */ -const Canvas = /*#__PURE__*/React__namespace.forwardRef(function Canvas({ - children, - fallback, - resize, - style, - gl, - events = createPointerEvents, - shadows, - linear, - flat, - legacy, - orthographic, - frameloop, - dpr, - performance, - raycaster, - camera, - onPointerMissed, - onCreated, - ...props -}, forwardedRef) { - // Create a known catalogue of Threejs-native elements - // This will include the entire THREE namespace by default, users can extend - // their own elements by using the createRoot API instead - React__namespace.useMemo(() => extend(THREE), []); - const [containerRef, { - width, - height - }] = useMeasure({ - scroll: true, - debounce: { - scroll: 50, - resize: 0 - }, - ...resize - }); - const canvasRef = React__namespace.useRef(null); - const divRef = React__namespace.useRef(null); - const [canvas, setCanvas] = React__namespace.useState(null); - React__namespace.useImperativeHandle(forwardedRef, () => canvasRef.current); - const handlePointerMissed = useMutableCallback(onPointerMissed); - const [block, setBlock] = React__namespace.useState(false); - const [error, setError] = React__namespace.useState(false); // Suspend this component if block is a promise (2nd run) - - if (block) throw block; // Throw exception outwards if anything within canvas throws - - if (error) throw error; - const root = React__namespace.useRef(null); - - if (width > 0 && height > 0 && canvas) { - if (!root.current) root.current = createRoot(canvas); - root.current.configure({ - gl, - events, - shadows, - linear, - flat, - legacy, - orthographic, - frameloop, - dpr, - performance, - raycaster, - camera, - size: { - width, - height - }, - // Pass mutable reference to onPointerMissed so it's free to update - onPointerMissed: (...args) => handlePointerMissed.current == null ? void 0 : handlePointerMissed.current(...args), - onCreated: state => { - state.events.connect == null ? void 0 : state.events.connect(divRef.current); - onCreated == null ? void 0 : onCreated(state); - } - }); - root.current.render( /*#__PURE__*/React__namespace.createElement(ErrorBoundary, { - set: setError - }, /*#__PURE__*/React__namespace.createElement(React__namespace.Suspense, { - fallback: /*#__PURE__*/React__namespace.createElement(Block, { - set: setBlock - }) - }, children))); - } - - useIsomorphicLayoutEffect$1(() => { - setCanvas(canvasRef.current); - }, []); - React__namespace.useEffect(() => { - if (canvas) return () => unmountComponentAtNode(canvas); - }, [canvas]); - return /*#__PURE__*/React__namespace.createElement("div", _extends$3({ - ref: divRef, - style: { - position: 'relative', - width: '100%', - height: '100%', - overflow: 'hidden', - ...style - } - }, props), /*#__PURE__*/React__namespace.createElement("div", { - ref: containerRef, - style: { - width: '100%', - height: '100%' - } - }, /*#__PURE__*/React__namespace.createElement("canvas", { - ref: canvasRef, - style: { - display: 'block' - } - }, fallback))); -}); - -var resizeObservers = []; - -var hasActiveObservations = function () { - return resizeObservers.some(function (ro) { return ro.activeTargets.length > 0; }); -}; - -var hasSkippedObservations = function () { - return resizeObservers.some(function (ro) { return ro.skippedTargets.length > 0; }); -}; - -var msg = 'ResizeObserver loop completed with undelivered notifications.'; -var deliverResizeLoopError = function () { - var event; - if (typeof ErrorEvent === 'function') { - event = new ErrorEvent('error', { - message: msg - }); - } - else { - event = document.createEvent('Event'); - event.initEvent('error', false, false); - event.message = msg; - } - window.dispatchEvent(event); -}; - -var ResizeObserverBoxOptions; -(function (ResizeObserverBoxOptions) { - ResizeObserverBoxOptions["BORDER_BOX"] = "border-box"; - ResizeObserverBoxOptions["CONTENT_BOX"] = "content-box"; - ResizeObserverBoxOptions["DEVICE_PIXEL_CONTENT_BOX"] = "device-pixel-content-box"; -})(ResizeObserverBoxOptions || (ResizeObserverBoxOptions = {})); - -var freeze = function (obj) { return Object.freeze(obj); }; - -var ResizeObserverSize = (function () { - function ResizeObserverSize(inlineSize, blockSize) { - this.inlineSize = inlineSize; - this.blockSize = blockSize; - freeze(this); - } - return ResizeObserverSize; -}()); - -var DOMRectReadOnly = (function () { - function DOMRectReadOnly(x, y, width, height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.top = this.y; - this.left = this.x; - this.bottom = this.top + this.height; - this.right = this.left + this.width; - return freeze(this); - } - DOMRectReadOnly.prototype.toJSON = function () { - var _a = this, x = _a.x, y = _a.y, top = _a.top, right = _a.right, bottom = _a.bottom, left = _a.left, width = _a.width, height = _a.height; - return { x: x, y: y, top: top, right: right, bottom: bottom, left: left, width: width, height: height }; - }; - DOMRectReadOnly.fromRect = function (rectangle) { - return new DOMRectReadOnly(rectangle.x, rectangle.y, rectangle.width, rectangle.height); - }; - return DOMRectReadOnly; -}()); - -var isSVG = function (target) { return target instanceof SVGElement && 'getBBox' in target; }; -var isHidden = function (target) { - if (isSVG(target)) { - var _a = target.getBBox(), width = _a.width, height = _a.height; - return !width && !height; - } - var _b = target, offsetWidth = _b.offsetWidth, offsetHeight = _b.offsetHeight; - return !(offsetWidth || offsetHeight || target.getClientRects().length); -}; -var isElement = function (obj) { - var _a, _b; - if (obj instanceof Element) { - return true; - } - var scope = (_b = (_a = obj) === null || _a === void 0 ? void 0 : _a.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView; - return !!(scope && obj instanceof scope.Element); -}; -var isReplacedElement = function (target) { - switch (target.tagName) { - case 'INPUT': - if (target.type !== 'image') { - break; - } - case 'VIDEO': - case 'AUDIO': - case 'EMBED': - case 'OBJECT': - case 'CANVAS': - case 'IFRAME': - case 'IMG': - return true; - } - return false; -}; - -var global$1 = typeof window !== 'undefined' ? window : {}; - -var cache = new WeakMap(); -var scrollRegexp = /auto|scroll/; -var verticalRegexp = /^tb|vertical/; -var IE = (/msie|trident/i).test(global$1.navigator && global$1.navigator.userAgent); -var parseDimension = function (pixel) { return parseFloat(pixel || '0'); }; -var size$1 = function (inlineSize, blockSize, switchSizes) { - if (inlineSize === void 0) { inlineSize = 0; } - if (blockSize === void 0) { blockSize = 0; } - if (switchSizes === void 0) { switchSizes = false; } - return new ResizeObserverSize((switchSizes ? blockSize : inlineSize) || 0, (switchSizes ? inlineSize : blockSize) || 0); -}; -var zeroBoxes = freeze({ - devicePixelContentBoxSize: size$1(), - borderBoxSize: size$1(), - contentBoxSize: size$1(), - contentRect: new DOMRectReadOnly(0, 0, 0, 0) -}); -var calculateBoxSizes = function (target, forceRecalculation) { - if (forceRecalculation === void 0) { forceRecalculation = false; } - if (cache.has(target) && !forceRecalculation) { - return cache.get(target); - } - if (isHidden(target)) { - cache.set(target, zeroBoxes); - return zeroBoxes; - } - var cs = getComputedStyle(target); - var svg = isSVG(target) && target.ownerSVGElement && target.getBBox(); - var removePadding = !IE && cs.boxSizing === 'border-box'; - var switchSizes = verticalRegexp.test(cs.writingMode || ''); - var canScrollVertically = !svg && scrollRegexp.test(cs.overflowY || ''); - var canScrollHorizontally = !svg && scrollRegexp.test(cs.overflowX || ''); - var paddingTop = svg ? 0 : parseDimension(cs.paddingTop); - var paddingRight = svg ? 0 : parseDimension(cs.paddingRight); - var paddingBottom = svg ? 0 : parseDimension(cs.paddingBottom); - var paddingLeft = svg ? 0 : parseDimension(cs.paddingLeft); - var borderTop = svg ? 0 : parseDimension(cs.borderTopWidth); - var borderRight = svg ? 0 : parseDimension(cs.borderRightWidth); - var borderBottom = svg ? 0 : parseDimension(cs.borderBottomWidth); - var borderLeft = svg ? 0 : parseDimension(cs.borderLeftWidth); - var horizontalPadding = paddingLeft + paddingRight; - var verticalPadding = paddingTop + paddingBottom; - var horizontalBorderArea = borderLeft + borderRight; - var verticalBorderArea = borderTop + borderBottom; - var horizontalScrollbarThickness = !canScrollHorizontally ? 0 : target.offsetHeight - verticalBorderArea - target.clientHeight; - var verticalScrollbarThickness = !canScrollVertically ? 0 : target.offsetWidth - horizontalBorderArea - target.clientWidth; - var widthReduction = removePadding ? horizontalPadding + horizontalBorderArea : 0; - var heightReduction = removePadding ? verticalPadding + verticalBorderArea : 0; - var contentWidth = svg ? svg.width : parseDimension(cs.width) - widthReduction - verticalScrollbarThickness; - var contentHeight = svg ? svg.height : parseDimension(cs.height) - heightReduction - horizontalScrollbarThickness; - var borderBoxWidth = contentWidth + horizontalPadding + verticalScrollbarThickness + horizontalBorderArea; - var borderBoxHeight = contentHeight + verticalPadding + horizontalScrollbarThickness + verticalBorderArea; - var boxes = freeze({ - devicePixelContentBoxSize: size$1(Math.round(contentWidth * devicePixelRatio), Math.round(contentHeight * devicePixelRatio), switchSizes), - borderBoxSize: size$1(borderBoxWidth, borderBoxHeight, switchSizes), - contentBoxSize: size$1(contentWidth, contentHeight, switchSizes), - contentRect: new DOMRectReadOnly(paddingLeft, paddingTop, contentWidth, contentHeight) - }); - cache.set(target, boxes); - return boxes; -}; -var calculateBoxSize = function (target, observedBox, forceRecalculation) { - var _a = calculateBoxSizes(target, forceRecalculation), borderBoxSize = _a.borderBoxSize, contentBoxSize = _a.contentBoxSize, devicePixelContentBoxSize = _a.devicePixelContentBoxSize; - switch (observedBox) { - case ResizeObserverBoxOptions.DEVICE_PIXEL_CONTENT_BOX: - return devicePixelContentBoxSize; - case ResizeObserverBoxOptions.BORDER_BOX: - return borderBoxSize; - default: - return contentBoxSize; - } -}; - -var ResizeObserverEntry = (function () { - function ResizeObserverEntry(target) { - var boxes = calculateBoxSizes(target); - this.target = target; - this.contentRect = boxes.contentRect; - this.borderBoxSize = freeze([boxes.borderBoxSize]); - this.contentBoxSize = freeze([boxes.contentBoxSize]); - this.devicePixelContentBoxSize = freeze([boxes.devicePixelContentBoxSize]); - } - return ResizeObserverEntry; -}()); - -var calculateDepthForNode = function (node) { - if (isHidden(node)) { - return Infinity; - } - var depth = 0; - var parent = node.parentNode; - while (parent) { - depth += 1; - parent = parent.parentNode; - } - return depth; -}; - -var broadcastActiveObservations = function () { - var shallowestDepth = Infinity; - var callbacks = []; - resizeObservers.forEach(function processObserver(ro) { - if (ro.activeTargets.length === 0) { - return; - } - var entries = []; - ro.activeTargets.forEach(function processTarget(ot) { - var entry = new ResizeObserverEntry(ot.target); - var targetDepth = calculateDepthForNode(ot.target); - entries.push(entry); - ot.lastReportedSize = calculateBoxSize(ot.target, ot.observedBox); - if (targetDepth < shallowestDepth) { - shallowestDepth = targetDepth; - } - }); - callbacks.push(function resizeObserverCallback() { - ro.callback.call(ro.observer, entries, ro.observer); - }); - ro.activeTargets.splice(0, ro.activeTargets.length); - }); - for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { - var callback = callbacks_1[_i]; - callback(); - } - return shallowestDepth; -}; - -var gatherActiveObservationsAtDepth = function (depth) { - resizeObservers.forEach(function processObserver(ro) { - ro.activeTargets.splice(0, ro.activeTargets.length); - ro.skippedTargets.splice(0, ro.skippedTargets.length); - ro.observationTargets.forEach(function processTarget(ot) { - if (ot.isActive()) { - if (calculateDepthForNode(ot.target) > depth) { - ro.activeTargets.push(ot); - } - else { - ro.skippedTargets.push(ot); - } - } - }); - }); -}; - -var process$1 = function () { - var depth = 0; - gatherActiveObservationsAtDepth(depth); - while (hasActiveObservations()) { - depth = broadcastActiveObservations(); - gatherActiveObservationsAtDepth(depth); - } - if (hasSkippedObservations()) { - deliverResizeLoopError(); - } - return depth > 0; -}; - -var trigger; -var callbacks = []; -var notify = function () { return callbacks.splice(0).forEach(function (cb) { return cb(); }); }; -var queueMicroTask = function (callback) { - if (!trigger) { - var toggle_1 = 0; - var el_1 = document.createTextNode(''); - var config = { characterData: true }; - new MutationObserver(function () { return notify(); }).observe(el_1, config); - trigger = function () { el_1.textContent = "" + (toggle_1 ? toggle_1-- : toggle_1++); }; - } - callbacks.push(callback); - trigger(); -}; - -var queueResizeObserver = function (cb) { - queueMicroTask(function ResizeObserver() { - requestAnimationFrame(cb); - }); -}; - -var watching = 0; -var isWatching = function () { return !!watching; }; -var CATCH_PERIOD = 250; -var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true }; -var events = [ - 'resize', - 'load', - 'transitionend', - 'animationend', - 'animationstart', - 'animationiteration', - 'keyup', - 'keydown', - 'mouseup', - 'mousedown', - 'mouseover', - 'mouseout', - 'blur', - 'focus' -]; -var time = function (timeout) { - if (timeout === void 0) { timeout = 0; } - return Date.now() + timeout; -}; -var scheduled = false; -var Scheduler = (function () { - function Scheduler() { - var _this = this; - this.stopped = true; - this.listener = function () { return _this.schedule(); }; - } - Scheduler.prototype.run = function (timeout) { - var _this = this; - if (timeout === void 0) { timeout = CATCH_PERIOD; } - if (scheduled) { - return; - } - scheduled = true; - var until = time(timeout); - queueResizeObserver(function () { - var elementsHaveResized = false; - try { - elementsHaveResized = process$1(); - } - finally { - scheduled = false; - timeout = until - time(); - if (!isWatching()) { - return; - } - if (elementsHaveResized) { - _this.run(1000); - } - else if (timeout > 0) { - _this.run(timeout); - } - else { - _this.start(); - } - } - }); - }; - Scheduler.prototype.schedule = function () { - this.stop(); - this.run(); - }; - Scheduler.prototype.observe = function () { - var _this = this; - var cb = function () { return _this.observer && _this.observer.observe(document.body, observerConfig); }; - document.body ? cb() : global$1.addEventListener('DOMContentLoaded', cb); - }; - Scheduler.prototype.start = function () { - var _this = this; - if (this.stopped) { - this.stopped = false; - this.observer = new MutationObserver(this.listener); - this.observe(); - events.forEach(function (name) { return global$1.addEventListener(name, _this.listener, true); }); - } - }; - Scheduler.prototype.stop = function () { - var _this = this; - if (!this.stopped) { - this.observer && this.observer.disconnect(); - events.forEach(function (name) { return global$1.removeEventListener(name, _this.listener, true); }); - this.stopped = true; - } - }; - return Scheduler; -}()); -var scheduler = new Scheduler(); -var updateCount = function (n) { - !watching && n > 0 && scheduler.start(); - watching += n; - !watching && scheduler.stop(); -}; - -var skipNotifyOnElement = function (target) { - return !isSVG(target) - && !isReplacedElement(target) - && getComputedStyle(target).display === 'inline'; -}; -var ResizeObservation = (function () { - function ResizeObservation(target, observedBox) { - this.target = target; - this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX; - this.lastReportedSize = { - inlineSize: 0, - blockSize: 0 - }; - } - ResizeObservation.prototype.isActive = function () { - var size = calculateBoxSize(this.target, this.observedBox, true); - if (skipNotifyOnElement(this.target)) { - this.lastReportedSize = size; - } - if (this.lastReportedSize.inlineSize !== size.inlineSize - || this.lastReportedSize.blockSize !== size.blockSize) { - return true; - } - return false; - }; - return ResizeObservation; -}()); - -var ResizeObserverDetail = (function () { - function ResizeObserverDetail(resizeObserver, callback) { - this.activeTargets = []; - this.skippedTargets = []; - this.observationTargets = []; - this.observer = resizeObserver; - this.callback = callback; - } - return ResizeObserverDetail; -}()); - -var observerMap = new WeakMap(); -var getObservationIndex = function (observationTargets, target) { - for (var i = 0; i < observationTargets.length; i += 1) { - if (observationTargets[i].target === target) { - return i; - } - } - return -1; -}; -var ResizeObserverController = (function () { - function ResizeObserverController() { - } - ResizeObserverController.connect = function (resizeObserver, callback) { - var detail = new ResizeObserverDetail(resizeObserver, callback); - observerMap.set(resizeObserver, detail); - }; - ResizeObserverController.observe = function (resizeObserver, target, options) { - var detail = observerMap.get(resizeObserver); - var firstObservation = detail.observationTargets.length === 0; - if (getObservationIndex(detail.observationTargets, target) < 0) { - firstObservation && resizeObservers.push(detail); - detail.observationTargets.push(new ResizeObservation(target, options && options.box)); - updateCount(1); - scheduler.schedule(); - } - }; - ResizeObserverController.unobserve = function (resizeObserver, target) { - var detail = observerMap.get(resizeObserver); - var index = getObservationIndex(detail.observationTargets, target); - var lastObservation = detail.observationTargets.length === 1; - if (index >= 0) { - lastObservation && resizeObservers.splice(resizeObservers.indexOf(detail), 1); - detail.observationTargets.splice(index, 1); - updateCount(-1); - } - }; - ResizeObserverController.disconnect = function (resizeObserver) { - var _this = this; - var detail = observerMap.get(resizeObserver); - detail.observationTargets.slice().forEach(function (ot) { return _this.unobserve(resizeObserver, ot.target); }); - detail.activeTargets.splice(0, detail.activeTargets.length); - }; - return ResizeObserverController; -}()); - -var ResizeObserver = (function () { - function ResizeObserver(callback) { - if (arguments.length === 0) { - throw new TypeError("Failed to construct 'ResizeObserver': 1 argument required, but only 0 present."); - } - if (typeof callback !== 'function') { - throw new TypeError("Failed to construct 'ResizeObserver': The callback provided as parameter 1 is not a function."); - } - ResizeObserverController.connect(this, callback); - } - ResizeObserver.prototype.observe = function (target, options) { - if (arguments.length === 0) { - throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': 1 argument required, but only 0 present."); - } - if (!isElement(target)) { - throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element"); - } - ResizeObserverController.observe(this, target, options); - }; - ResizeObserver.prototype.unobserve = function (target) { - if (arguments.length === 0) { - throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': 1 argument required, but only 0 present."); - } - if (!isElement(target)) { - throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': parameter 1 is not of type 'Element"); - } - ResizeObserverController.unobserve(this, target); - }; - ResizeObserver.prototype.disconnect = function () { - ResizeObserverController.disconnect(this); - }; - ResizeObserver.toString = function () { - return 'function ResizeObserver () { [polyfill code] }'; - }; - return ResizeObserver; -}()); - -const v1$1 = new Vector3(); -const v2 = new Vector3(); -const v3 = new Vector3(); - -function defaultCalculatePosition(el, camera, size) { - const objectPos = v1$1.setFromMatrixPosition(el.matrixWorld); - objectPos.project(camera); - const widthHalf = size.width / 2; - const heightHalf = size.height / 2; - return [objectPos.x * widthHalf + widthHalf, -(objectPos.y * heightHalf) + heightHalf]; -} - -function isObjectBehindCamera(el, camera) { - const objectPos = v1$1.setFromMatrixPosition(el.matrixWorld); - const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); - const deltaCamObj = objectPos.sub(cameraPos); - const camDir = camera.getWorldDirection(v3); - return deltaCamObj.angleTo(camDir) > Math.PI / 2; -} - -function isObjectVisible(el, camera, raycaster, occlude) { - const elPos = v1$1.setFromMatrixPosition(el.matrixWorld); - const screenPos = elPos.clone(); - screenPos.project(camera); - raycaster.setFromCamera(screenPos, camera); - const intersects = raycaster.intersectObjects(occlude, true); - - if (intersects.length) { - const intersectionDistance = intersects[0].distance; - const pointDistance = elPos.distanceTo(raycaster.ray.origin); - return pointDistance < intersectionDistance; - } - - return true; -} - -function objectScale(el, camera) { - if (camera instanceof OrthographicCamera) { - return camera.zoom; - } else if (camera instanceof PerspectiveCamera) { - const objectPos = v1$1.setFromMatrixPosition(el.matrixWorld); - const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); - const vFOV = camera.fov * Math.PI / 180; - const dist = objectPos.distanceTo(cameraPos); - const scaleFOV = 2 * Math.tan(vFOV / 2) * dist; - return 1 / scaleFOV; - } else { - return 1; - } -} - -function objectZIndex(el, camera, zIndexRange) { - if (camera instanceof PerspectiveCamera || camera instanceof OrthographicCamera) { - const objectPos = v1$1.setFromMatrixPosition(el.matrixWorld); - const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); - const dist = objectPos.distanceTo(cameraPos); - const A = (zIndexRange[1] - zIndexRange[0]) / (camera.far - camera.near); - const B = zIndexRange[1] - A * camera.far; - return Math.round(A * dist + B); - } - - return undefined; -} - -const epsilon = value => Math.abs(value) < 1e-10 ? 0 : value; - -function getCSSMatrix(matrix, multipliers, prepend = '') { - let matrix3d = 'matrix3d('; - - for (let i = 0; i !== 16; i++) { - matrix3d += epsilon(multipliers[i] * matrix.elements[i]) + (i !== 15 ? ',' : ')'); - } - - return prepend + matrix3d; -} - -const getCameraCSSMatrix = (multipliers => { - return matrix => getCSSMatrix(matrix, multipliers); -})([1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1]); - -const getObjectCSSMatrix = (scaleMultipliers => { - return (matrix, factor) => getCSSMatrix(matrix, scaleMultipliers(factor), 'translate(-50%,-50%)'); -})(f => [1 / f, 1 / f, 1 / f, 1, -1 / f, -1 / f, -1 / f, -1, 1 / f, 1 / f, 1 / f, 1, 1, 1, 1, 1]); - -const Html = /*#__PURE__*/React__namespace.forwardRef(({ - children, - eps = 0.001, - style, - className, - prepend, - center, - fullscreen, - portal, - distanceFactor, - sprite = false, - transform = false, - occlude, - onOcclude, - zIndexRange = [16777271, 0], - calculatePosition = defaultCalculatePosition, - as = 'div', - wrapperClass, - pointerEvents = 'auto', - ...props -}, ref) => { - var _portal$current; - - const gl = useThree(({ - gl - }) => gl); - const camera = useThree(({ - camera - }) => camera); - const scene = useThree(({ - scene - }) => scene); - const size = useThree(({ - size - }) => size); - const raycaster = useThree(({ - raycaster - }) => raycaster); - const [el] = React__namespace.useState(() => document.createElement(as)); - const root = React__namespace.useRef(); - const group = React__namespace.useRef(null); - const oldZoom = React__namespace.useRef(0); - const oldPosition = React__namespace.useRef([0, 0]); - const transformOuterRef = React__namespace.useRef(null); - const transformInnerRef = React__namespace.useRef(null); - const target = (_portal$current = portal == null ? void 0 : portal.current) !== null && _portal$current !== void 0 ? _portal$current : gl.domElement.parentNode; - React__namespace.useLayoutEffect(() => { - if (group.current) { - const currentRoot = root.current = ReactDOM__namespace.createRoot(el); - scene.updateMatrixWorld(); - - if (transform) { - el.style.cssText = `position:absolute;top:0;left:0;pointer-events:none;overflow:hidden;`; - } else { - const vec = calculatePosition(group.current, camera, size); - el.style.cssText = `position:absolute;top:0;left:0;transform:translate3d(${vec[0]}px,${vec[1]}px,0);transform-origin:0 0;`; - } - - if (target) { - if (prepend) target.prepend(el);else target.appendChild(el); - } - - return () => { - if (target) target.removeChild(el); - currentRoot.unmount(); - }; - } - }, [target, transform]); - React__namespace.useLayoutEffect(() => { - if (wrapperClass) el.className = wrapperClass; - }, [wrapperClass]); - const styles = React__namespace.useMemo(() => { - if (transform) { - return { - position: 'absolute', - top: 0, - left: 0, - width: size.width, - height: size.height, - transformStyle: 'preserve-3d', - pointerEvents: 'none' - }; - } else { - return { - position: 'absolute', - transform: center ? 'translate3d(-50%,-50%,0)' : 'none', - ...(fullscreen && { - top: -size.height / 2, - left: -size.width / 2, - width: size.width, - height: size.height - }), - ...style - }; - } - }, [style, center, fullscreen, size, transform]); - const transformInnerStyles = React__namespace.useMemo(() => ({ - position: 'absolute', - pointerEvents - }), [pointerEvents]); - React__namespace.useLayoutEffect(() => { - if (transform) { - var _root$current; - - (_root$current = root.current) == null ? void 0 : _root$current.render( /*#__PURE__*/React__namespace.createElement("div", { - ref: transformOuterRef, - style: styles - }, /*#__PURE__*/React__namespace.createElement("div", { - ref: transformInnerRef, - style: transformInnerStyles - }, /*#__PURE__*/React__namespace.createElement("div", { - ref: ref, - className: className, - style: style, - children: children - })))); - } else { - var _root$current2; - - (_root$current2 = root.current) == null ? void 0 : _root$current2.render( /*#__PURE__*/React__namespace.createElement("div", { - ref: ref, - style: styles, - className: className, - children: children - })); - } - }); - const visible = React__namespace.useRef(true); - useFrame(() => { - if (group.current) { - camera.updateMatrixWorld(); - group.current.updateWorldMatrix(true, false); - const vec = transform ? oldPosition.current : calculatePosition(group.current, camera, size); - - if (transform || Math.abs(oldZoom.current - camera.zoom) > eps || Math.abs(oldPosition.current[0] - vec[0]) > eps || Math.abs(oldPosition.current[1] - vec[1]) > eps) { - const isBehindCamera = isObjectBehindCamera(group.current, camera); - let raytraceTarget = false; - - if (typeof occlude === 'boolean') { - if (occlude === true) { - raytraceTarget = [scene]; - } - } else if (Array.isArray(occlude)) { - raytraceTarget = occlude.map(item => item.current); - } - - const previouslyVisible = visible.current; - - if (raytraceTarget) { - const isvisible = isObjectVisible(group.current, camera, raycaster, raytraceTarget); - visible.current = isvisible && !isBehindCamera; - } else { - visible.current = !isBehindCamera; - } - - if (previouslyVisible !== visible.current) { - if (onOcclude) onOcclude(!visible.current);else el.style.display = visible.current ? 'block' : 'none'; - } - - el.style.zIndex = `${objectZIndex(group.current, camera, zIndexRange)}`; - - if (transform) { - const [widthHalf, heightHalf] = [size.width / 2, size.height / 2]; - const fov = camera.projectionMatrix.elements[5] * heightHalf; - const { - isOrthographicCamera, - top, - left, - bottom, - right - } = camera; - const cameraMatrix = getCameraCSSMatrix(camera.matrixWorldInverse); - const cameraTransform = isOrthographicCamera ? `scale(${fov})translate(${epsilon(-(right + left) / 2)}px,${epsilon((top + bottom) / 2)}px)` : `translateZ(${fov}px)`; - let matrix = group.current.matrixWorld; - - if (sprite) { - matrix = camera.matrixWorldInverse.clone().transpose().copyPosition(matrix).scale(group.current.scale); - matrix.elements[3] = matrix.elements[7] = matrix.elements[11] = 0; - matrix.elements[15] = 1; - } - - el.style.width = size.width + 'px'; - el.style.height = size.height + 'px'; - el.style.perspective = isOrthographicCamera ? '' : `${fov}px`; - - if (transformOuterRef.current && transformInnerRef.current) { - transformOuterRef.current.style.transform = `${cameraTransform}${cameraMatrix}translate(${widthHalf}px,${heightHalf}px)`; - transformInnerRef.current.style.transform = getObjectCSSMatrix(matrix, 1 / ((distanceFactor || 10) / 400)); - } - } else { - const scale = distanceFactor === undefined ? 1 : objectScale(group.current, camera) * distanceFactor; - el.style.transform = `translate3d(${vec[0]}px,${vec[1]}px,0) scale(${scale})`; - } - - oldPosition.current = vec; - oldZoom.current = camera.zoom; - } - } - }); - return /*#__PURE__*/React__namespace.createElement("group", _extends$3({}, props, { - ref: group - })); -}); - -function createStore$1(createState) { - let state; - const listeners = /* @__PURE__ */ new Set(); - const setState = (partial, replace) => { - const nextState = typeof partial === "function" ? partial(state) : partial; - if (nextState !== state) { - const previousState = state; - state = replace ? nextState : Object.assign({}, state, nextState); - listeners.forEach((listener) => listener(state, previousState)); - } - }; - const getState = () => state; - const subscribeWithSelector = (listener, selector = getState, equalityFn = Object.is) => { - console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware"); - let currentSlice = selector(state); - function listenerToAdd() { - const nextSlice = selector(state); - if (!equalityFn(currentSlice, nextSlice)) { - const previousSlice = currentSlice; - listener(currentSlice = nextSlice, previousSlice); - } - } - listeners.add(listenerToAdd); - return () => listeners.delete(listenerToAdd); - }; - const subscribe = (listener, selector, equalityFn) => { - if (selector || equalityFn) { - return subscribeWithSelector(listener, selector, equalityFn); - } - listeners.add(listener); - return () => listeners.delete(listener); - }; - const destroy = () => listeners.clear(); - const api = { setState, getState, subscribe, destroy }; - state = createState(setState, getState, api); - return api; -} - -const isSSR$1 = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); -const useIsomorphicLayoutEffect = isSSR$1 ? React.useEffect : React.useLayoutEffect; -function create$3(createState) { - const api = typeof createState === "function" ? createStore$1(createState) : createState; - const useStore = (selector = api.getState, equalityFn = Object.is) => { - const [, forceUpdate] = React.useReducer((c) => c + 1, 0); - const state = api.getState(); - const stateRef = React.useRef(state); - const selectorRef = React.useRef(selector); - const equalityFnRef = React.useRef(equalityFn); - const erroredRef = React.useRef(false); - const currentSliceRef = React.useRef(); - if (currentSliceRef.current === void 0) { - currentSliceRef.current = selector(state); - } - let newStateSlice; - let hasNewStateSlice = false; - if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) { - newStateSlice = selector(state); - hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice); - } - useIsomorphicLayoutEffect(() => { - if (hasNewStateSlice) { - currentSliceRef.current = newStateSlice; - } - stateRef.current = state; - selectorRef.current = selector; - equalityFnRef.current = equalityFn; - erroredRef.current = false; - }); - const stateBeforeSubscriptionRef = React.useRef(state); - useIsomorphicLayoutEffect(() => { - const listener = () => { - try { - const nextState = api.getState(); - const nextStateSlice = selectorRef.current(nextState); - if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) { - stateRef.current = nextState; - currentSliceRef.current = nextStateSlice; - forceUpdate(); - } - } catch (error) { - erroredRef.current = true; - forceUpdate(); - } - }; - const unsubscribe = api.subscribe(listener); - if (api.getState() !== stateBeforeSubscriptionRef.current) { - listener(); - } - return unsubscribe; - }, []); - const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current; - React.useDebugValue(sliceToReturn); - return sliceToReturn; - }; - Object.assign(useStore, api); - useStore[Symbol.iterator] = function() { - console.warn("[useStore, api] = create() is deprecated and will be removed in v4"); - const items = [useStore, api]; - return { - next() { - const done = items.length <= 0; - return { value: items.shift(), done }; - } - }; - }; - return useStore; -} - -let saveLastTotalLoaded = 0; -create$3(set => { - DefaultLoadingManager.onStart = (item, loaded, total) => { - set({ - active: true, - item, - loaded, - total, - progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 - }); - }; - - DefaultLoadingManager.onLoad = () => { - set({ - active: false - }); - }; - - DefaultLoadingManager.onError = item => set(state => ({ - errors: [...state.errors, item] - })); - - DefaultLoadingManager.onProgress = (item, loaded, total) => { - if (loaded === total) { - saveLastTotalLoaded = total; - } - - set({ - active: true, - item, - loaded, - total, - progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 || 100 - }); - }; - - return { - errors: [], - active: false, - progress: 0, - item: '', - loaded: 0, - total: 0 - }; -}); - -function mergeRefs(refs) { - return function (value) { - refs.forEach(function (ref) { - if (typeof ref === "function") { - ref(value); - } else if (ref != null) { - ref.current = value; - } - }); - }; -} - -let updateQueue = makeQueue(); -const raf = fn => schedule(fn, updateQueue); -let writeQueue = makeQueue(); - -raf.write = fn => schedule(fn, writeQueue); - -let onStartQueue = makeQueue(); - -raf.onStart = fn => schedule(fn, onStartQueue); - -let onFrameQueue = makeQueue(); - -raf.onFrame = fn => schedule(fn, onFrameQueue); - -let onFinishQueue = makeQueue(); - -raf.onFinish = fn => schedule(fn, onFinishQueue); - -let timeouts = []; - -raf.setTimeout = (handler, ms) => { - let time = raf.now() + ms; - - let cancel = () => { - let i = timeouts.findIndex(t => t.cancel == cancel); - if (~i) timeouts.splice(i, 1); - pendingCount -= ~i ? 1 : 0; - }; - - let timeout = { - time, - handler, - cancel - }; - timeouts.splice(findTimeout(time), 0, timeout); - pendingCount += 1; - start(); - return timeout; -}; - -let findTimeout = time => ~(~timeouts.findIndex(t => t.time > time) || ~timeouts.length); - -raf.cancel = fn => { - onStartQueue.delete(fn); - onFrameQueue.delete(fn); - updateQueue.delete(fn); - writeQueue.delete(fn); - onFinishQueue.delete(fn); -}; - -raf.sync = fn => { - sync = true; - raf.batchedUpdates(fn); - sync = false; -}; - -raf.throttle = fn => { - let lastArgs; - - function queuedFn() { - try { - fn(...lastArgs); - } finally { - lastArgs = null; - } - } - - function throttled(...args) { - lastArgs = args; - raf.onStart(queuedFn); - } - - throttled.handler = fn; - - throttled.cancel = () => { - onStartQueue.delete(queuedFn); - lastArgs = null; - }; - - return throttled; -}; - -let nativeRaf = typeof window != 'undefined' ? window.requestAnimationFrame : () => {}; - -raf.use = impl => nativeRaf = impl; - -raf.now = typeof performance != 'undefined' ? () => performance.now() : Date.now; - -raf.batchedUpdates = fn => fn(); - -raf.catch = console.error; -raf.frameLoop = 'always'; - -raf.advance = () => { - if (raf.frameLoop !== 'demand') { - console.warn('Cannot call the manual advancement of rafz whilst frameLoop is not set as demand'); - } else { - update(); - } -}; - -let ts = -1; -let pendingCount = 0; -let sync = false; - -function schedule(fn, queue) { - if (sync) { - queue.delete(fn); - fn(0); - } else { - queue.add(fn); - start(); - } -} - -function start() { - if (ts < 0) { - ts = 0; - - if (raf.frameLoop !== 'demand') { - nativeRaf(loop); - } - } -} - -function stop() { - ts = -1; -} - -function loop() { - if (~ts) { - nativeRaf(loop); - raf.batchedUpdates(update); - } -} - -function update() { - let prevTs = ts; - ts = raf.now(); - let count = findTimeout(ts); - - if (count) { - eachSafely(timeouts.splice(0, count), t => t.handler()); - pendingCount -= count; - } - - onStartQueue.flush(); - updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667); - onFrameQueue.flush(); - writeQueue.flush(); - onFinishQueue.flush(); - - if (!pendingCount) { - stop(); - } -} - -function makeQueue() { - let next = new Set(); - let current = next; - return { - add(fn) { - pendingCount += current == next && !next.has(fn) ? 1 : 0; - next.add(fn); - }, - - delete(fn) { - pendingCount -= current == next && next.has(fn) ? 1 : 0; - return next.delete(fn); - }, - - flush(arg) { - if (current.size) { - next = new Set(); - pendingCount -= current.size; - eachSafely(current, fn => fn(arg) && next.add(fn)); - pendingCount += next.size; - current = next; - } - } - - }; -} - -function eachSafely(values, each) { - values.forEach(value => { - try { - each(value); - } catch (e) { - raf.catch(e); - } - }); -} - -function noop$2() {} -const defineHidden = (obj, key, value) => Object.defineProperty(obj, key, { - value, - writable: true, - configurable: true -}); -const is = { - arr: Array.isArray, - obj: a => !!a && a.constructor.name === 'Object', - fun: a => typeof a === 'function', - str: a => typeof a === 'string', - num: a => typeof a === 'number', - und: a => a === undefined -}; -function isEqual(a, b) { - if (is.arr(a)) { - if (!is.arr(b) || a.length !== b.length) return false; - - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return false; - } - - return true; - } - - return a === b; -} -const each = (obj, fn) => obj.forEach(fn); -function eachProp(obj, fn, ctx) { - if (is.arr(obj)) { - for (let i = 0; i < obj.length; i++) { - fn.call(ctx, obj[i], `${i}`); - } - - return; - } - - for (const key in obj) { - if (obj.hasOwnProperty(key)) { - fn.call(ctx, obj[key], key); - } - } -} -const toArray = a => is.und(a) ? [] : is.arr(a) ? a : [a]; -const isSSR = () => typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); - -let createStringInterpolator$1; -let to; -let colors$1 = null; -let skipAnimation = false; -let willAdvance = noop$2; -const assign$4 = globals => { - if (globals.to) to = globals.to; - if (globals.now) raf.now = globals.now; - if (globals.colors !== undefined) colors$1 = globals.colors; - if (globals.skipAnimation != null) skipAnimation = globals.skipAnimation; - if (globals.createStringInterpolator) createStringInterpolator$1 = globals.createStringInterpolator; - if (globals.requestAnimationFrame) raf.use(globals.requestAnimationFrame); - if (globals.batchedUpdates) raf.batchedUpdates = globals.batchedUpdates; - if (globals.willAdvance) willAdvance = globals.willAdvance; - if (globals.frameLoop) raf.frameLoop = globals.frameLoop; -}; - -var globals = /*#__PURE__*/Object.freeze({ - __proto__: null, - get createStringInterpolator () { return createStringInterpolator$1; }, - get to () { return to; }, - get colors () { return colors$1; }, - get skipAnimation () { return skipAnimation; }, - get willAdvance () { return willAdvance; }, - assign: assign$4 -}); - -const startQueue = new Set(); -let currentFrame = []; -let prevFrame = []; -let priority = 0; -const frameLoop = { - get idle() { - return !startQueue.size && !currentFrame.length; - }, - - start(animation) { - if (priority > animation.priority) { - startQueue.add(animation); - raf.onStart(flushStartQueue); - } else { - startSafely(animation); - raf(advance); - } - }, - - advance, - - sort(animation) { - if (priority) { - raf.onFrame(() => frameLoop.sort(animation)); - } else { - const prevIndex = currentFrame.indexOf(animation); - - if (~prevIndex) { - currentFrame.splice(prevIndex, 1); - startUnsafely(animation); - } - } - }, - - clear() { - currentFrame = []; - startQueue.clear(); - } - -}; - -function flushStartQueue() { - startQueue.forEach(startSafely); - startQueue.clear(); - raf(advance); -} - -function startSafely(animation) { - if (!currentFrame.includes(animation)) startUnsafely(animation); -} - -function startUnsafely(animation) { - currentFrame.splice(findIndex$2(currentFrame, other => other.priority > animation.priority), 0, animation); -} - -function advance(dt) { - const nextFrame = prevFrame; - - for (let i = 0; i < currentFrame.length; i++) { - const animation = currentFrame[i]; - priority = animation.priority; - - if (!animation.idle) { - willAdvance(animation); - animation.advance(dt); - - if (!animation.idle) { - nextFrame.push(animation); - } - } - } - - priority = 0; - prevFrame = currentFrame; - prevFrame.length = 0; - currentFrame = nextFrame; - return currentFrame.length > 0; -} - -function findIndex$2(arr, test) { - const index = arr.findIndex(test); - return index < 0 ? arr.length : index; -} - -const colors = { - transparent: 0x00000000, - aliceblue: 0xf0f8ffff, - antiquewhite: 0xfaebd7ff, - aqua: 0x00ffffff, - aquamarine: 0x7fffd4ff, - azure: 0xf0ffffff, - beige: 0xf5f5dcff, - bisque: 0xffe4c4ff, - black: 0x000000ff, - blanchedalmond: 0xffebcdff, - blue: 0x0000ffff, - blueviolet: 0x8a2be2ff, - brown: 0xa52a2aff, - burlywood: 0xdeb887ff, - burntsienna: 0xea7e5dff, - cadetblue: 0x5f9ea0ff, - chartreuse: 0x7fff00ff, - chocolate: 0xd2691eff, - coral: 0xff7f50ff, - cornflowerblue: 0x6495edff, - cornsilk: 0xfff8dcff, - crimson: 0xdc143cff, - cyan: 0x00ffffff, - darkblue: 0x00008bff, - darkcyan: 0x008b8bff, - darkgoldenrod: 0xb8860bff, - darkgray: 0xa9a9a9ff, - darkgreen: 0x006400ff, - darkgrey: 0xa9a9a9ff, - darkkhaki: 0xbdb76bff, - darkmagenta: 0x8b008bff, - darkolivegreen: 0x556b2fff, - darkorange: 0xff8c00ff, - darkorchid: 0x9932ccff, - darkred: 0x8b0000ff, - darksalmon: 0xe9967aff, - darkseagreen: 0x8fbc8fff, - darkslateblue: 0x483d8bff, - darkslategray: 0x2f4f4fff, - darkslategrey: 0x2f4f4fff, - darkturquoise: 0x00ced1ff, - darkviolet: 0x9400d3ff, - deeppink: 0xff1493ff, - deepskyblue: 0x00bfffff, - dimgray: 0x696969ff, - dimgrey: 0x696969ff, - dodgerblue: 0x1e90ffff, - firebrick: 0xb22222ff, - floralwhite: 0xfffaf0ff, - forestgreen: 0x228b22ff, - fuchsia: 0xff00ffff, - gainsboro: 0xdcdcdcff, - ghostwhite: 0xf8f8ffff, - gold: 0xffd700ff, - goldenrod: 0xdaa520ff, - gray: 0x808080ff, - green: 0x008000ff, - greenyellow: 0xadff2fff, - grey: 0x808080ff, - honeydew: 0xf0fff0ff, - hotpink: 0xff69b4ff, - indianred: 0xcd5c5cff, - indigo: 0x4b0082ff, - ivory: 0xfffff0ff, - khaki: 0xf0e68cff, - lavender: 0xe6e6faff, - lavenderblush: 0xfff0f5ff, - lawngreen: 0x7cfc00ff, - lemonchiffon: 0xfffacdff, - lightblue: 0xadd8e6ff, - lightcoral: 0xf08080ff, - lightcyan: 0xe0ffffff, - lightgoldenrodyellow: 0xfafad2ff, - lightgray: 0xd3d3d3ff, - lightgreen: 0x90ee90ff, - lightgrey: 0xd3d3d3ff, - lightpink: 0xffb6c1ff, - lightsalmon: 0xffa07aff, - lightseagreen: 0x20b2aaff, - lightskyblue: 0x87cefaff, - lightslategray: 0x778899ff, - lightslategrey: 0x778899ff, - lightsteelblue: 0xb0c4deff, - lightyellow: 0xffffe0ff, - lime: 0x00ff00ff, - limegreen: 0x32cd32ff, - linen: 0xfaf0e6ff, - magenta: 0xff00ffff, - maroon: 0x800000ff, - mediumaquamarine: 0x66cdaaff, - mediumblue: 0x0000cdff, - mediumorchid: 0xba55d3ff, - mediumpurple: 0x9370dbff, - mediumseagreen: 0x3cb371ff, - mediumslateblue: 0x7b68eeff, - mediumspringgreen: 0x00fa9aff, - mediumturquoise: 0x48d1ccff, - mediumvioletred: 0xc71585ff, - midnightblue: 0x191970ff, - mintcream: 0xf5fffaff, - mistyrose: 0xffe4e1ff, - moccasin: 0xffe4b5ff, - navajowhite: 0xffdeadff, - navy: 0x000080ff, - oldlace: 0xfdf5e6ff, - olive: 0x808000ff, - olivedrab: 0x6b8e23ff, - orange: 0xffa500ff, - orangered: 0xff4500ff, - orchid: 0xda70d6ff, - palegoldenrod: 0xeee8aaff, - palegreen: 0x98fb98ff, - paleturquoise: 0xafeeeeff, - palevioletred: 0xdb7093ff, - papayawhip: 0xffefd5ff, - peachpuff: 0xffdab9ff, - peru: 0xcd853fff, - pink: 0xffc0cbff, - plum: 0xdda0ddff, - powderblue: 0xb0e0e6ff, - purple: 0x800080ff, - rebeccapurple: 0x663399ff, - red: 0xff0000ff, - rosybrown: 0xbc8f8fff, - royalblue: 0x4169e1ff, - saddlebrown: 0x8b4513ff, - salmon: 0xfa8072ff, - sandybrown: 0xf4a460ff, - seagreen: 0x2e8b57ff, - seashell: 0xfff5eeff, - sienna: 0xa0522dff, - silver: 0xc0c0c0ff, - skyblue: 0x87ceebff, - slateblue: 0x6a5acdff, - slategray: 0x708090ff, - slategrey: 0x708090ff, - snow: 0xfffafaff, - springgreen: 0x00ff7fff, - steelblue: 0x4682b4ff, - tan: 0xd2b48cff, - teal: 0x008080ff, - thistle: 0xd8bfd8ff, - tomato: 0xff6347ff, - turquoise: 0x40e0d0ff, - violet: 0xee82eeff, - wheat: 0xf5deb3ff, - white: 0xffffffff, - whitesmoke: 0xf5f5f5ff, - yellow: 0xffff00ff, - yellowgreen: 0x9acd32ff -}; - -const NUMBER = '[-+]?\\d*\\.?\\d+'; -const PERCENTAGE = NUMBER + '%'; - -function call$1(...parts) { - return '\\(\\s*(' + parts.join(')\\s*,\\s*(') + ')\\s*\\)'; -} - -const rgb = new RegExp('rgb' + call$1(NUMBER, NUMBER, NUMBER)); -const rgba = new RegExp('rgba' + call$1(NUMBER, NUMBER, NUMBER, NUMBER)); -const hsl = new RegExp('hsl' + call$1(NUMBER, PERCENTAGE, PERCENTAGE)); -const hsla = new RegExp('hsla' + call$1(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)); -const hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; -const hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; -const hex6 = /^#([0-9a-fA-F]{6})$/; -const hex8 = /^#([0-9a-fA-F]{8})$/; - -function normalizeColor(color) { - let match; - - if (typeof color === 'number') { - return color >>> 0 === color && color >= 0 && color <= 0xffffffff ? color : null; - } - - if (match = hex6.exec(color)) return parseInt(match[1] + 'ff', 16) >>> 0; - - if (colors$1 && colors$1[color] !== undefined) { - return colors$1[color]; - } - - if (match = rgb.exec(color)) { - return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | 0x000000ff) >>> 0; - } - - if (match = rgba.exec(color)) { - return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | parse1(match[4])) >>> 0; - } - - if (match = hex3.exec(color)) { - return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + 'ff', 16) >>> 0; - } - - if (match = hex8.exec(color)) return parseInt(match[1], 16) >>> 0; - - if (match = hex4.exec(color)) { - return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + match[4] + match[4], 16) >>> 0; - } - - if (match = hsl.exec(color)) { - return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | 0x000000ff) >>> 0; - } - - if (match = hsla.exec(color)) { - return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | parse1(match[4])) >>> 0; - } - - return null; -} - -function hue2rgb(p, q, t) { - if (t < 0) t += 1; - if (t > 1) t -= 1; - if (t < 1 / 6) return p + (q - p) * 6 * t; - if (t < 1 / 2) return q; - if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; - return p; -} - -function hslToRgb(h, s, l) { - const q = l < 0.5 ? l * (1 + s) : l + s - l * s; - const p = 2 * l - q; - const r = hue2rgb(p, q, h + 1 / 3); - const g = hue2rgb(p, q, h); - const b = hue2rgb(p, q, h - 1 / 3); - return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8; -} - -function parse255(str) { - const int = parseInt(str, 10); - if (int < 0) return 0; - if (int > 255) return 255; - return int; -} - -function parse360(str) { - const int = parseFloat(str); - return (int % 360 + 360) % 360 / 360; -} - -function parse1(str) { - const num = parseFloat(str); - if (num < 0) return 0; - if (num > 1) return 255; - return Math.round(num * 255); -} - -function parsePercentage(str) { - const int = parseFloat(str); - if (int < 0) return 0; - if (int > 100) return 1; - return int / 100; -} - -function colorToRgba(input) { - let int32Color = normalizeColor(input); - if (int32Color === null) return input; - int32Color = int32Color || 0; - let r = (int32Color & 0xff000000) >>> 24; - let g = (int32Color & 0x00ff0000) >>> 16; - let b = (int32Color & 0x0000ff00) >>> 8; - let a = (int32Color & 0x000000ff) / 255; - return `rgba(${r}, ${g}, ${b}, ${a})`; -} - -const createInterpolator = (range, output, extrapolate) => { - if (is.fun(range)) { - return range; - } - - if (is.arr(range)) { - return createInterpolator({ - range, - output: output, - extrapolate - }); - } - - if (is.str(range.output[0])) { - return createStringInterpolator$1(range); - } - - const config = range; - const outputRange = config.output; - const inputRange = config.range || [0, 1]; - const extrapolateLeft = config.extrapolateLeft || config.extrapolate || 'extend'; - const extrapolateRight = config.extrapolateRight || config.extrapolate || 'extend'; - - const easing = config.easing || (t => t); - - return input => { - const range = findRange(input, inputRange); - return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight, config.map); - }; -}; - -function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) { - let result = map ? map(input) : input; - - if (result < inputMin) { - if (extrapolateLeft === 'identity') return result;else if (extrapolateLeft === 'clamp') result = inputMin; - } - - if (result > inputMax) { - if (extrapolateRight === 'identity') return result;else if (extrapolateRight === 'clamp') result = inputMax; - } - - if (outputMin === outputMax) return outputMin; - if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax; - if (inputMin === -Infinity) result = -result;else if (inputMax === Infinity) result = result - inputMin;else result = (result - inputMin) / (inputMax - inputMin); - result = easing(result); - if (outputMin === -Infinity) result = -result;else if (outputMax === Infinity) result = result + outputMin;else result = result * (outputMax - outputMin) + outputMin; - return result; -} - -function findRange(input, inputRange) { - for (var i = 1; i < inputRange.length - 1; ++i) if (inputRange[i] >= input) break; - - return i - 1; -} - -function _extends$2() { - _extends$2 = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends$2.apply(this, arguments); -} - -const $get = Symbol.for('FluidValue.get'); -const $observers = Symbol.for('FluidValue.observers'); - -const hasFluidValue = arg => Boolean(arg && arg[$get]); - -const getFluidValue = arg => arg && arg[$get] ? arg[$get]() : arg; - -function callFluidObserver(observer, event) { - if (observer.eventObserved) { - observer.eventObserved(event); - } else { - observer(event); - } -} - -function callFluidObservers(target, event) { - let observers = target[$observers]; - - if (observers) { - observers.forEach(observer => { - callFluidObserver(observer, event); - }); - } -} - -class FluidValue { - constructor(get) { - this[$get] = void 0; - this[$observers] = void 0; - - if (!get && !(get = this.get)) { - throw Error('Unknown getter'); - } - - setFluidGetter(this, get); - } - -} - -const setFluidGetter = (target, get) => setHidden(target, $get, get); - -function addFluidObserver(target, observer) { - if (target[$get]) { - let observers = target[$observers]; - - if (!observers) { - setHidden(target, $observers, observers = new Set()); - } - - if (!observers.has(observer)) { - observers.add(observer); - - if (target.observerAdded) { - target.observerAdded(observers.size, observer); - } - } - } - - return observer; -} - -function removeFluidObserver(target, observer) { - let observers = target[$observers]; - - if (observers && observers.has(observer)) { - const count = observers.size - 1; - - if (count) { - observers.delete(observer); - } else { - target[$observers] = null; - } - - if (target.observerRemoved) { - target.observerRemoved(count, observer); - } - } -} - -const setHidden = (target, key, value) => Object.defineProperty(target, key, { - value, - writable: true, - configurable: true -}); - -const numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; -const colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi; -const unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, 'i'); -const rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi; -const cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/; - -const variableToRgba = input => { - const [token, fallback] = parseCSSVariable(input); - - if (!token || isSSR()) { - return input; - } - - const value = window.getComputedStyle(document.documentElement).getPropertyValue(token); - - if (value) { - return value.trim(); - } else if (fallback && fallback.startsWith('--')) { - const _value = window.getComputedStyle(document.documentElement).getPropertyValue(fallback); - - if (_value) { - return _value; - } else { - return input; - } - } else if (fallback && cssVariableRegex.test(fallback)) { - return variableToRgba(fallback); - } else if (fallback) { - return fallback; - } - - return input; -}; - -const parseCSSVariable = current => { - const match = cssVariableRegex.exec(current); - if (!match) return [,]; - const [, token, fallback] = match; - return [token, fallback]; -}; - -let namedColorRegex; - -const rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`; - -const createStringInterpolator = config => { - if (!namedColorRegex) namedColorRegex = colors$1 ? new RegExp(`(${Object.keys(colors$1).join('|')})(?!\\w)`, 'g') : /^\b$/; - const output = config.output.map(value => { - return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba); - }); - const keyframes = output.map(value => value.match(numberRegex).map(Number)); - const outputRanges = keyframes[0].map((_, i) => keyframes.map(values => { - if (!(i in values)) { - throw Error('The arity of each "output" value must be equal'); - } - - return values[i]; - })); - const interpolators = outputRanges.map(output => createInterpolator(_extends$2({}, config, { - output - }))); - return input => { - var _output$find; - - const missingUnit = !unitRegex.test(output[0]) && ((_output$find = output.find(value => unitRegex.test(value))) == null ? void 0 : _output$find.replace(numberRegex, '')); - let i = 0; - return output[0].replace(numberRegex, () => `${interpolators[i++](input)}${missingUnit || ''}`).replace(rgbaRegex, rgbaRound); - }; -}; - -const prefix = 'react-spring: '; - -const once = fn => { - const func = fn; - let called = false; - - if (typeof func != 'function') { - throw new TypeError(`${prefix}once requires a function parameter`); - } - - return (...args) => { - if (!called) { - func(...args); - called = true; - } - }; -}; - -const warnInterpolate = once(console.warn); -function deprecateInterpolate() { - warnInterpolate(`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`); -} -once(console.warn); - -function isAnimatedString(value) { - return is.str(value) && (value[0] == '#' || /\d/.test(value) || !isSSR() && cssVariableRegex.test(value) || value in (colors$1 || {})); -} - -const useLayoutEffect = typeof window !== 'undefined' && window.document && window.document.createElement ? React__namespace.useLayoutEffect : React__namespace.useEffect; - -const useIsMounted = () => { - const isMounted = React.useRef(false); - useLayoutEffect(() => { - isMounted.current = true; - return () => { - isMounted.current = false; - }; - }, []); - return isMounted; -}; - -function useForceUpdate() { - const update = React.useState()[1]; - const isMounted = useIsMounted(); - return () => { - if (isMounted.current) { - update(Math.random()); - } - }; -} - -function useMemoOne(getResult, inputs) { - const [initial] = React.useState(() => ({ - inputs, - result: getResult() - })); - const committed = React.useRef(); - const prevCache = committed.current; - let cache = prevCache; - - if (cache) { - const useCache = Boolean(inputs && cache.inputs && areInputsEqual(inputs, cache.inputs)); - - if (!useCache) { - cache = { - inputs, - result: getResult() - }; - } - } else { - cache = initial; - } - - React.useEffect(() => { - committed.current = cache; - - if (prevCache == initial) { - initial.inputs = initial.result = undefined; - } - }, [cache]); - return cache.result; -} - -function areInputsEqual(next, prev) { - if (next.length !== prev.length) { - return false; - } - - for (let i = 0; i < next.length; i++) { - if (next[i] !== prev[i]) { - return false; - } - } - - return true; -} - -const useOnce = effect => React.useEffect(effect, emptyDeps); -const emptyDeps = []; - -const $node = Symbol.for('Animated:node'); -const isAnimated = value => !!value && value[$node] === value; -const getAnimated = owner => owner && owner[$node]; -const setAnimated = (owner, node) => defineHidden(owner, $node, node); -const getPayload = owner => owner && owner[$node] && owner[$node].getPayload(); -class Animated { - constructor() { - this.payload = void 0; - setAnimated(this, this); - } - - getPayload() { - return this.payload || []; - } - -} - -class AnimatedValue extends Animated { - constructor(_value) { - super(); - this.done = true; - this.elapsedTime = void 0; - this.lastPosition = void 0; - this.lastVelocity = void 0; - this.v0 = void 0; - this.durationProgress = 0; - this._value = _value; - - if (is.num(this._value)) { - this.lastPosition = this._value; - } - } - - static create(value) { - return new AnimatedValue(value); - } - - getPayload() { - return [this]; - } - - getValue() { - return this._value; - } - - setValue(value, step) { - if (is.num(value)) { - this.lastPosition = value; - - if (step) { - value = Math.round(value / step) * step; - - if (this.done) { - this.lastPosition = value; - } - } - } - - if (this._value === value) { - return false; - } - - this._value = value; - return true; - } - - reset() { - const { - done - } = this; - this.done = false; - - if (is.num(this._value)) { - this.elapsedTime = 0; - this.durationProgress = 0; - this.lastPosition = this._value; - if (done) this.lastVelocity = null; - this.v0 = null; - } - } - -} - -class AnimatedString extends AnimatedValue { - constructor(value) { - super(0); - this._string = null; - this._toString = void 0; - this._toString = createInterpolator({ - output: [value, value] - }); - } - - static create(value) { - return new AnimatedString(value); - } - - getValue() { - let value = this._string; - return value == null ? this._string = this._toString(this._value) : value; - } - - setValue(value) { - if (is.str(value)) { - if (value == this._string) { - return false; - } - - this._string = value; - this._value = 1; - } else if (super.setValue(value)) { - this._string = null; - } else { - return false; - } - - return true; - } - - reset(goal) { - if (goal) { - this._toString = createInterpolator({ - output: [this.getValue(), goal] - }); - } - - this._value = 0; - super.reset(); - } - -} - -const TreeContext = { - dependencies: null -}; - -class AnimatedObject extends Animated { - constructor(source) { - super(); - this.source = source; - this.setValue(source); - } - - getValue(animated) { - const values = {}; - eachProp(this.source, (source, key) => { - if (isAnimated(source)) { - values[key] = source.getValue(animated); - } else if (hasFluidValue(source)) { - values[key] = getFluidValue(source); - } else if (!animated) { - values[key] = source; - } - }); - return values; - } - - setValue(source) { - this.source = source; - this.payload = this._makePayload(source); - } - - reset() { - if (this.payload) { - each(this.payload, node => node.reset()); - } - } - - _makePayload(source) { - if (source) { - const payload = new Set(); - eachProp(source, this._addToPayload, payload); - return Array.from(payload); - } - } - - _addToPayload(source) { - if (TreeContext.dependencies && hasFluidValue(source)) { - TreeContext.dependencies.add(source); - } - - const payload = getPayload(source); - - if (payload) { - each(payload, node => this.add(node)); - } - } - -} - -class AnimatedArray extends AnimatedObject { - constructor(source) { - super(source); - } - - static create(source) { - return new AnimatedArray(source); - } - - getValue() { - return this.source.map(node => node.getValue()); - } - - setValue(source) { - const payload = this.getPayload(); - - if (source.length == payload.length) { - return payload.map((node, i) => node.setValue(source[i])).some(Boolean); - } - - super.setValue(source.map(makeAnimated)); - return true; - } - -} - -function makeAnimated(value) { - const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue; - return nodeType.create(value); -} - -function getAnimatedType(value) { - const parentNode = getAnimated(value); - return parentNode ? parentNode.constructor : is.arr(value) ? AnimatedArray : isAnimatedString(value) ? AnimatedString : AnimatedValue; -} - -function _extends$1() { - _extends$1 = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends$1.apply(this, arguments); -} - -const withAnimated = (Component, host) => { - const hasInstance = !is.fun(Component) || Component.prototype && Component.prototype.isReactComponent; - return React.forwardRef((givenProps, givenRef) => { - const instanceRef = React.useRef(null); - const ref = hasInstance && React.useCallback(value => { - instanceRef.current = updateRef(givenRef, value); - }, [givenRef]); - const [props, deps] = getAnimatedState(givenProps, host); - const forceUpdate = useForceUpdate(); - - const callback = () => { - const instance = instanceRef.current; - - if (hasInstance && !instance) { - return; - } - - const didUpdate = instance ? host.applyAnimatedValues(instance, props.getValue(true)) : false; - - if (didUpdate === false) { - forceUpdate(); - } - }; - - const observer = new PropsObserver(callback, deps); - const observerRef = React.useRef(); - useLayoutEffect(() => { - observerRef.current = observer; - each(deps, dep => addFluidObserver(dep, observer)); - return () => { - if (observerRef.current) { - each(observerRef.current.deps, dep => removeFluidObserver(dep, observerRef.current)); - raf.cancel(observerRef.current.update); - } - }; - }); - React.useEffect(callback, []); - useOnce(() => () => { - const observer = observerRef.current; - each(observer.deps, dep => removeFluidObserver(dep, observer)); - }); - const usedProps = host.getComponentProps(props.getValue()); - return React__namespace.createElement(Component, _extends$1({}, usedProps, { - ref: ref - })); - }); -}; - -class PropsObserver { - constructor(update, deps) { - this.update = update; - this.deps = deps; - } - - eventObserved(event) { - if (event.type == 'change') { - raf.write(this.update); - } - } - -} - -function getAnimatedState(props, host) { - const dependencies = new Set(); - TreeContext.dependencies = dependencies; - if (props.style) props = _extends$1({}, props, { - style: host.createAnimatedStyle(props.style) - }); - props = new AnimatedObject(props); - TreeContext.dependencies = null; - return [props, dependencies]; -} - -function updateRef(ref, value) { - if (ref) { - if (is.fun(ref)) ref(value);else ref.current = value; - } - - return value; -} - -const cacheKey = Symbol.for('AnimatedComponent'); -const createHost = (components, { - applyAnimatedValues: _applyAnimatedValues = () => false, - createAnimatedStyle: _createAnimatedStyle = style => new AnimatedObject(style), - getComponentProps: _getComponentProps = props => props -} = {}) => { - const hostConfig = { - applyAnimatedValues: _applyAnimatedValues, - createAnimatedStyle: _createAnimatedStyle, - getComponentProps: _getComponentProps - }; - - const animated = Component => { - const displayName = getDisplayName(Component) || 'Anonymous'; - - if (is.str(Component)) { - Component = animated[Component] || (animated[Component] = withAnimated(Component, hostConfig)); - } else { - Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig)); - } - - Component.displayName = `Animated(${displayName})`; - return Component; - }; - - eachProp(components, (Component, key) => { - if (is.arr(components)) { - key = getDisplayName(Component); - } - - animated[key] = animated(Component); - }); - return { - animated - }; -}; - -const getDisplayName = arg => is.str(arg) ? arg : arg && is.str(arg.displayName) ? arg.displayName : is.fun(arg) && arg.name || null; - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -const config = { - default: { - tension: 170, - friction: 26 - }, - gentle: { - tension: 120, - friction: 14 - }, - wobbly: { - tension: 180, - friction: 12 - }, - stiff: { - tension: 210, - friction: 20 - }, - slow: { - tension: 280, - friction: 60 - }, - molasses: { - tension: 280, - friction: 120 - } -}; -const c1 = 1.70158; -const c2 = c1 * 1.525; -const c3 = c1 + 1; -const c4 = 2 * Math.PI / 3; -const c5 = 2 * Math.PI / 4.5; - -const bounceOut = x => { - const n1 = 7.5625; - const d1 = 2.75; - - if (x < 1 / d1) { - return n1 * x * x; - } else if (x < 2 / d1) { - return n1 * (x -= 1.5 / d1) * x + 0.75; - } else if (x < 2.5 / d1) { - return n1 * (x -= 2.25 / d1) * x + 0.9375; - } else { - return n1 * (x -= 2.625 / d1) * x + 0.984375; - } -}; - -const easings = { - linear: x => x, - easeInQuad: x => x * x, - easeOutQuad: x => 1 - (1 - x) * (1 - x), - easeInOutQuad: x => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2, - easeInCubic: x => x * x * x, - easeOutCubic: x => 1 - Math.pow(1 - x, 3), - easeInOutCubic: x => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2, - easeInQuart: x => x * x * x * x, - easeOutQuart: x => 1 - Math.pow(1 - x, 4), - easeInOutQuart: x => x < 0.5 ? 8 * x * x * x * x : 1 - Math.pow(-2 * x + 2, 4) / 2, - easeInQuint: x => x * x * x * x * x, - easeOutQuint: x => 1 - Math.pow(1 - x, 5), - easeInOutQuint: x => x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2, - easeInSine: x => 1 - Math.cos(x * Math.PI / 2), - easeOutSine: x => Math.sin(x * Math.PI / 2), - easeInOutSine: x => -(Math.cos(Math.PI * x) - 1) / 2, - easeInExpo: x => x === 0 ? 0 : Math.pow(2, 10 * x - 10), - easeOutExpo: x => x === 1 ? 1 : 1 - Math.pow(2, -10 * x), - easeInOutExpo: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2, - easeInCirc: x => 1 - Math.sqrt(1 - Math.pow(x, 2)), - easeOutCirc: x => Math.sqrt(1 - Math.pow(x - 1, 2)), - easeInOutCirc: x => x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2, - easeInBack: x => c3 * x * x * x - c1 * x * x, - easeOutBack: x => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2), - easeInOutBack: x => x < 0.5 ? Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2, - easeInElastic: x => x === 0 ? 0 : x === 1 ? 1 : -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4), - easeOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1, - easeInOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2 : Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5) / 2 + 1, - easeInBounce: x => 1 - bounceOut(1 - x), - easeOutBounce: bounceOut, - easeInOutBounce: x => x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2 -}; - -_extends({}, config.default, { - mass: 1, - damping: 1, - easing: easings.linear, - clamp: false -}); - -const isFrameValue = value => value instanceof FrameValue; -let nextId$1 = 1; -class FrameValue extends FluidValue { - constructor(...args) { - super(...args); - this.id = nextId$1++; - this.key = void 0; - this._priority = 0; - } - - get priority() { - return this._priority; - } - - set priority(priority) { - if (this._priority != priority) { - this._priority = priority; - - this._onPriorityChange(priority); - } - } - - get() { - const node = getAnimated(this); - return node && node.getValue(); - } - - to(...args) { - return globals.to(this, args); - } - - interpolate(...args) { - deprecateInterpolate(); - return globals.to(this, args); - } - - toJSON() { - return this.get(); - } - - observerAdded(count) { - if (count == 1) this._attach(); - } - - observerRemoved(count) { - if (count == 0) this._detach(); - } - - _attach() {} - - _detach() {} - - _onChange(value, idle = false) { - callFluidObservers(this, { - type: 'change', - parent: this, - value, - idle - }); - } - - _onPriorityChange(priority) { - if (!this.idle) { - frameLoop.sort(this); - } - - callFluidObservers(this, { - type: 'priority', - parent: this, - priority - }); - } - -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -const _excluded$3 = ["children"]; -const SpringContext = _ref => { - let { - children - } = _ref, - props = _objectWithoutPropertiesLoose(_ref, _excluded$3); - - const inherited = React.useContext(ctx); - const pause = props.pause || !!inherited.pause, - immediate = props.immediate || !!inherited.immediate; - props = useMemoOne(() => ({ - pause, - immediate - }), [pause, immediate]); - const { - Provider - } = ctx; - return React__namespace.createElement(Provider, { - value: props - }, children); -}; -const ctx = makeContext(SpringContext, {}); -SpringContext.Provider = ctx.Provider; -SpringContext.Consumer = ctx.Consumer; - -function makeContext(target, init) { - Object.assign(target, React__namespace.createContext(init)); - target.Provider._context = target; - target.Consumer._context = target; - return target; -} - -let TransitionPhase; - -(function (TransitionPhase) { - TransitionPhase["MOUNT"] = "mount"; - TransitionPhase["ENTER"] = "enter"; - TransitionPhase["UPDATE"] = "update"; - TransitionPhase["LEAVE"] = "leave"; -})(TransitionPhase || (TransitionPhase = {})); - -class Interpolation extends FrameValue { - constructor(source, args) { - super(); - this.key = void 0; - this.idle = true; - this.calc = void 0; - this._active = new Set(); - this.source = source; - this.calc = createInterpolator(...args); - - const value = this._get(); - - const nodeType = getAnimatedType(value); - setAnimated(this, nodeType.create(value)); - } - - advance(_dt) { - const value = this._get(); - - const oldValue = this.get(); - - if (!isEqual(value, oldValue)) { - getAnimated(this).setValue(value); - - this._onChange(value, this.idle); - } - - if (!this.idle && checkIdle(this._active)) { - becomeIdle(this); - } - } - - _get() { - const inputs = is.arr(this.source) ? this.source.map(getFluidValue) : toArray(getFluidValue(this.source)); - return this.calc(...inputs); - } - - _start() { - if (this.idle && !checkIdle(this._active)) { - this.idle = false; - each(getPayload(this), node => { - node.done = false; - }); - - if (globals.skipAnimation) { - raf.batchedUpdates(() => this.advance()); - becomeIdle(this); - } else { - frameLoop.start(this); - } - } - } - - _attach() { - let priority = 1; - each(toArray(this.source), source => { - if (hasFluidValue(source)) { - addFluidObserver(source, this); - } - - if (isFrameValue(source)) { - if (!source.idle) { - this._active.add(source); - } - - priority = Math.max(priority, source.priority + 1); - } - }); - this.priority = priority; - - this._start(); - } - - _detach() { - each(toArray(this.source), source => { - if (hasFluidValue(source)) { - removeFluidObserver(source, this); - } - }); - - this._active.clear(); - - becomeIdle(this); - } - - eventObserved(event) { - if (event.type == 'change') { - if (event.idle) { - this.advance(); - } else { - this._active.add(event.parent); - - this._start(); - } - } else if (event.type == 'idle') { - this._active.delete(event.parent); - } else if (event.type == 'priority') { - this.priority = toArray(this.source).reduce((highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1), 0); - } - } - -} - -function isIdle(source) { - return source.idle !== false; -} - -function checkIdle(active) { - return !active.size || Array.from(active).every(isIdle); -} - -function becomeIdle(self) { - if (!self.idle) { - self.idle = true; - each(getPayload(self), node => { - node.done = true; - }); - callFluidObservers(self, { - type: 'idle', - parent: self - }); - } -} - -globals.assign({ - createStringInterpolator, - to: (source, args) => new Interpolation(source, args) -}); - -const primitives = ['primitive'].concat(Object.keys(THREE).filter(key => /^[A-Z]/.test(key)).map(key => key[0].toLowerCase() + key.slice(1))); - -globals.assign({ - createStringInterpolator, - colors, - frameLoop: 'demand' -}); -addEffect(() => { - raf.advance(); -}); -createHost(primitives, { - applyAnimatedValues: applyProps -}); - -const V = { - toVector(v, fallback) { - if (v === undefined) v = fallback; - return Array.isArray(v) ? v : [v, v]; - }, - - add(v1, v2) { - return [v1[0] + v2[0], v1[1] + v2[1]]; - }, - - sub(v1, v2) { - return [v1[0] - v2[0], v1[1] - v2[1]]; - }, - - addTo(v1, v2) { - v1[0] += v2[0]; - v1[1] += v2[1]; - }, - - subTo(v1, v2) { - v1[0] -= v2[0]; - v1[1] -= v2[1]; - } - -}; - -function _defineProperty$2(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = null != arguments[i] ? arguments[i] : {}; - i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { - _defineProperty$2(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - - return target; -} - -function call(v, ...args) { - if (typeof v === 'function') { - return v(...args); - } else { - return v; - } -} -function assignDefault(value, fallback) { - return Object.assign({}, fallback, value || {}); -} - -const identity$5 = v => v; -const DEFAULT_RUBBERBAND = 0.15; -const commonConfigResolver = { - enabled(value = true) { - return value; - }, - - eventOptions(value, _k, config) { - return _objectSpread2(_objectSpread2({}, config.shared.eventOptions), value); - }, - - preventDefault(value = false) { - return value; - }, - - triggerAllEvents(value = false) { - return value; - }, - - rubberband(value = 0) { - switch (value) { - case true: - return [DEFAULT_RUBBERBAND, DEFAULT_RUBBERBAND]; - - case false: - return [0, 0]; - - default: - return V.toVector(value); - } - }, - - from(value) { - if (typeof value === 'function') return value; - if (value != null) return V.toVector(value); - }, - - transform(value, _k, config) { - const transform = value || config.shared.transform; - this.hasCustomTransform = !!transform; - - if (process.env.NODE_ENV === 'development') { - const originalTransform = transform || identity$5; - return v => { - const r = originalTransform(v); - - if (!isFinite(r[0]) || !isFinite(r[1])) { - console.warn(`[@use-gesture]: config.transform() must produce a valid result, but it was: [${r[0]},${[1]}]`); - } - - return r; - }; - } - - return transform || identity$5; - }, - - threshold(value) { - return V.toVector(value, 0); - } - -}; - -if (process.env.NODE_ENV === 'development') { - Object.assign(commonConfigResolver, { - domTarget(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`); - } - - return NaN; - }, - - lockDirection(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`lockDirection\` option has been merged with \`axis\`. Use it as in \`{ axis: 'lock' }\``); - } - - return NaN; - }, - - initial(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`initial\` option has been renamed to \`from\`.`); - } - - return NaN; - } - - }); -} - -const DEFAULT_AXIS_THRESHOLD = 0; -const coordinatesConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { - axis(_v, _k, { - axis - }) { - this.lockDirection = axis === 'lock'; - if (!this.lockDirection) return axis; - }, - - axisThreshold(value = DEFAULT_AXIS_THRESHOLD) { - return value; - }, - - bounds(value = {}) { - if (typeof value === 'function') { - return state => coordinatesConfigResolver.bounds(value(state)); - } - - if ('current' in value) { - return () => value.current; - } - - if (typeof HTMLElement === 'function' && value instanceof HTMLElement) { - return value; - } - - const { - left = -Infinity, - right = Infinity, - top = -Infinity, - bottom = Infinity - } = value; - return [[left, right], [top, bottom]]; - } - -}); - -const isBrowser$1 = typeof window !== 'undefined' && window.document && window.document.createElement; - -function supportsTouchEvents() { - return isBrowser$1 && 'ontouchstart' in window; -} - -function isTouchScreen() { - return supportsTouchEvents() || isBrowser$1 && window.navigator.maxTouchPoints > 1; -} - -function supportsPointerEvents() { - return isBrowser$1 && 'onpointerdown' in window; -} - -function supportsPointerLock() { - return isBrowser$1 && 'exitPointerLock' in window.document; -} - -function supportsGestureEvents() { - try { - return 'constructor' in GestureEvent; - } catch (e) { - return false; - } -} - -const SUPPORT = { - isBrowser: isBrowser$1, - gesture: supportsGestureEvents(), - touch: isTouchScreen(), - touchscreen: isTouchScreen(), - pointer: supportsPointerEvents(), - pointerLock: supportsPointerLock() -}; - -const DEFAULT_PREVENT_SCROLL_DELAY = 250; -const DEFAULT_DRAG_DELAY = 180; -const DEFAULT_SWIPE_VELOCITY = 0.5; -const DEFAULT_SWIPE_DISTANCE = 50; -const DEFAULT_SWIPE_DURATION = 250; -const DEFAULT_DRAG_AXIS_THRESHOLD = { - mouse: 0, - touch: 0, - pen: 8 -}; -const dragConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { - device(_v, _k, { - pointer: { - touch = false, - lock = false, - mouse = false - } = {} - }) { - this.pointerLock = lock && SUPPORT.pointerLock; - if (SUPPORT.touch && touch) return 'touch'; - if (this.pointerLock) return 'mouse'; - if (SUPPORT.pointer && !mouse) return 'pointer'; - if (SUPPORT.touch) return 'touch'; - return 'mouse'; - }, - - preventScrollAxis(value, _k, { - preventScroll - }) { - this.preventScrollDelay = typeof preventScroll === 'number' ? preventScroll : preventScroll || preventScroll === undefined && value ? DEFAULT_PREVENT_SCROLL_DELAY : undefined; - if (!SUPPORT.touchscreen || preventScroll === false) return undefined; - return value ? value : preventScroll !== undefined ? 'y' : undefined; - }, - - pointerCapture(_v, _k, { - pointer: { - capture = true, - buttons = 1 - } = {} - }) { - this.pointerButtons = buttons; - return !this.pointerLock && this.device === 'pointer' && capture; - }, - - threshold(value, _k, { - filterTaps = false, - tapsThreshold = 3, - axis = undefined - }) { - const threshold = V.toVector(value, filterTaps ? tapsThreshold : axis ? 1 : 0); - this.filterTaps = filterTaps; - this.tapsThreshold = tapsThreshold; - return threshold; - }, - - swipe({ - velocity = DEFAULT_SWIPE_VELOCITY, - distance = DEFAULT_SWIPE_DISTANCE, - duration = DEFAULT_SWIPE_DURATION - } = {}) { - return { - velocity: this.transform(V.toVector(velocity)), - distance: this.transform(V.toVector(distance)), - duration - }; - }, - - delay(value = 0) { - switch (value) { - case true: - return DEFAULT_DRAG_DELAY; - - case false: - return 0; - - default: - return value; - } - }, - - axisThreshold(value) { - if (!value) return DEFAULT_DRAG_AXIS_THRESHOLD; - return _objectSpread2(_objectSpread2({}, DEFAULT_DRAG_AXIS_THRESHOLD), value); - } - -}); - -if (process.env.NODE_ENV === 'development') { - Object.assign(dragConfigResolver, { - useTouch(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`useTouch\` option has been renamed to \`pointer.touch\`. Use it as in \`{ pointer: { touch: true } }\`.`); - } - - return NaN; - }, - - experimental_preventWindowScrollY(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`experimental_preventWindowScrollY\` option has been renamed to \`preventScroll\`.`); - } - - return NaN; - }, - - swipeVelocity(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`swipeVelocity\` option has been renamed to \`swipe.velocity\`. Use it as in \`{ swipe: { velocity: 0.5 } }\`.`); - } - - return NaN; - }, - - swipeDistance(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`swipeDistance\` option has been renamed to \`swipe.distance\`. Use it as in \`{ swipe: { distance: 50 } }\`.`); - } - - return NaN; - }, - - swipeDuration(value) { - if (value !== undefined) { - throw Error(`[@use-gesture]: \`swipeDuration\` option has been renamed to \`swipe.duration\`. Use it as in \`{ swipe: { duration: 250 } }\`.`); - } - - return NaN; - } - - }); -} - -_objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { - device(_v, _k, { - shared, - pointer: { - touch = false - } = {} - }) { - const sharedConfig = shared; - if (sharedConfig.target && !SUPPORT.touch && SUPPORT.gesture) return 'gesture'; - if (SUPPORT.touch && touch) return 'touch'; - - if (SUPPORT.touchscreen) { - if (SUPPORT.pointer) return 'pointer'; - if (SUPPORT.touch) return 'touch'; - } - }, - - bounds(_v, _k, { - scaleBounds = {}, - angleBounds = {} - }) { - const _scaleBounds = state => { - const D = assignDefault(call(scaleBounds, state), { - min: -Infinity, - max: Infinity - }); - return [D.min, D.max]; - }; - - const _angleBounds = state => { - const A = assignDefault(call(angleBounds, state), { - min: -Infinity, - max: Infinity - }); - return [A.min, A.max]; - }; - - if (typeof scaleBounds !== 'function' && typeof angleBounds !== 'function') return [_scaleBounds(), _angleBounds()]; - return state => [_scaleBounds(state), _angleBounds(state)]; - }, - - threshold(value, _k, config) { - this.lockDirection = config.axis === 'lock'; - const threshold = V.toVector(value, this.lockDirection ? [0.1, 3] : 0); - return threshold; - }, - - modifierKey(value) { - if (value === undefined) return 'ctrlKey'; - return value; - } - -}); - -_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { - mouseOnly: (value = true) => value -}); - -_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { - mouseOnly: (value = true) => value -}); - -var MorphBlendMesh = function (geometry, material) { - Mesh.call(this, geometry, material); - this.animationsMap = {}; - this.animationsList = []; // prepare default animation - // (all frames played together in 1 second) - - var numFrames = Object.keys(this.morphTargetDictionary).length; - var name = '__default'; - var startFrame = 0; - var endFrame = numFrames - 1; - var fps = numFrames / 1; - this.createAnimation(name, startFrame, endFrame, fps); - this.setAnimationWeight(name, 1); -}; - -MorphBlendMesh.prototype = Object.assign(Object.create(Mesh.prototype), { - constructor: MorphBlendMesh, - createAnimation: function (name, start, end, fps) { - var animation = { - start: start, - end: end, - length: end - start + 1, - fps: fps, - duration: (end - start) / fps, - lastFrame: 0, - currentFrame: 0, - active: false, - time: 0, - direction: 1, - weight: 1, - directionBackwards: false, - mirroredLoop: false - }; - this.animationsMap[name] = animation; - this.animationsList.push(animation); - }, - autoCreateAnimations: function (fps) { - var pattern = /([a-z]+)_?(\d+)/i; - var firstAnimation, - frameRanges = {}; - var i = 0; - - for (let key in this.morphTargetDictionary) { - var chunks = key.match(pattern); - - if (chunks && chunks.length > 1) { - var name = chunks[1]; - if (!frameRanges[name]) frameRanges[name] = { - start: Infinity, - end: -Infinity - }; - var range = frameRanges[name]; - if (i < range.start) range.start = i; - if (i > range.end) range.end = i; - if (!firstAnimation) firstAnimation = name; - } - - i++; - } - - for (let name in frameRanges) { - var range = frameRanges[name]; - this.createAnimation(name, range.start, range.end, fps); - } - - this.firstAnimation = firstAnimation; - }, - setAnimationDirectionForward: function (name) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.direction = 1; - animation.directionBackwards = false; - } - }, - setAnimationDirectionBackward: function (name) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.direction = -1; - animation.directionBackwards = true; - } - }, - setAnimationFPS: function (name, fps) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.fps = fps; - animation.duration = (animation.end - animation.start) / animation.fps; - } - }, - setAnimationDuration: function (name, duration) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.duration = duration; - animation.fps = (animation.end - animation.start) / animation.duration; - } - }, - setAnimationWeight: function (name, weight) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.weight = weight; - } - }, - setAnimationTime: function (name, time) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.time = time; - } - }, - getAnimationTime: function (name) { - var time = 0; - var animation = this.animationsMap[name]; - - if (animation) { - time = animation.time; - } - - return time; - }, - getAnimationDuration: function (name) { - var duration = -1; - var animation = this.animationsMap[name]; - - if (animation) { - duration = animation.duration; - } - - return duration; - }, - playAnimation: function (name) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.time = 0; - animation.active = true; - } else { - console.warn('THREE.MorphBlendMesh: animation[' + name + '] undefined in .playAnimation()'); - } - }, - stopAnimation: function (name) { - var animation = this.animationsMap[name]; - - if (animation) { - animation.active = false; - } - }, - update: function (delta) { - for (let i = 0, il = this.animationsList.length; i < il; i++) { - var animation = this.animationsList[i]; - if (!animation.active) continue; - var frameTime = animation.duration / animation.length; - animation.time += animation.direction * delta; - - if (animation.mirroredLoop) { - if (animation.time > animation.duration || animation.time < 0) { - animation.direction *= -1; - - if (animation.time > animation.duration) { - animation.time = animation.duration; - animation.directionBackwards = true; - } - - if (animation.time < 0) { - animation.time = 0; - animation.directionBackwards = false; - } - } - } else { - animation.time = animation.time % animation.duration; - if (animation.time < 0) animation.time += animation.duration; - } - - var keyframe = animation.start + MathUtils.clamp(Math.floor(animation.time / frameTime), 0, animation.length - 1); - var weight = animation.weight; - - if (keyframe !== animation.currentFrame) { - this.morphTargetInfluences[animation.lastFrame] = 0; - this.morphTargetInfluences[animation.currentFrame] = 1 * weight; - this.morphTargetInfluences[keyframe] = 0; - animation.lastFrame = animation.currentFrame; - animation.currentFrame = keyframe; - } - - var mix = animation.time % frameTime / frameTime; - if (animation.directionBackwards) mix = 1 - mix; - - if (animation.currentFrame !== animation.lastFrame) { - this.morphTargetInfluences[animation.currentFrame] = mix * weight; - this.morphTargetInfluences[animation.lastFrame] = (1 - mix) * weight; - } else { - this.morphTargetInfluences[animation.currentFrame] = weight; - } - } - } -}); - -/** - * Ported from: https://github.com/maurizzzio/quickhull3d/ by Mauricio Poppe (https://github.com/maurizzzio) - */ - -var ConvexHull = function () { - var Visible = 0; - var Deleted = 1; - var v1 = new Vector3(); - - function ConvexHull() { - this.tolerance = -1; - this.faces = []; // the generated faces of the convex hull - - this.newFaces = []; // this array holds the faces that are generated within a single iteration - // the vertex lists work as follows: - // - // let 'a' and 'b' be 'Face' instances - // let 'v' be points wrapped as instance of 'Vertex' - // - // [v, v, ..., v, v, v, ...] - // ^ ^ - // | | - // a.outside b.outside - // - - this.assigned = new VertexList(); - this.unassigned = new VertexList(); - this.vertices = []; // vertices of the hull (internal representation of given geometry data) - } - - Object.assign(ConvexHull.prototype, { - setFromPoints: function (points) { - if (Array.isArray(points) !== true) { - console.error('THREE.ConvexHull: Points parameter is not an array.'); - } - - if (points.length < 4) { - console.error('THREE.ConvexHull: The algorithm needs at least four points.'); - } - - this.makeEmpty(); - - for (let i = 0, l = points.length; i < l; i++) { - this.vertices.push(new VertexNode(points[i])); - } - - this.compute(); - return this; - }, - setFromObject: function (object) { - var points = []; - object.updateMatrixWorld(true); - object.traverse(function (node) { - var i, l, point; - var geometry = node.geometry; - - if (geometry !== undefined) { - if (geometry.isGeometry) { - console.error('THREE.ConvexHull no longer supports Geometry. Use THREE.BufferGeometry instead.'); - return; - } else if (geometry.isBufferGeometry) { - var attribute = geometry.attributes.position; - - if (attribute !== undefined) { - for (i = 0, l = attribute.count; i < l; i++) { - point = new Vector3(); - point.fromBufferAttribute(attribute, i).applyMatrix4(node.matrixWorld); - points.push(point); - } - } - } - } - }); - return this.setFromPoints(points); - }, - containsPoint: function (point) { - var faces = this.faces; - - for (let i = 0, l = faces.length; i < l; i++) { - var face = faces[i]; // compute signed distance and check on what half space the point lies - - if (face.distanceToPoint(point) > this.tolerance) return false; - } - - return true; - }, - intersectRay: function (ray, target) { - // based on "Fast Ray-Convex Polyhedron Intersection" by Eric Haines, GRAPHICS GEMS II - var faces = this.faces; - var tNear = -Infinity; - var tFar = Infinity; - - for (let i = 0, l = faces.length; i < l; i++) { - var face = faces[i]; // interpret faces as planes for the further computation - - var vN = face.distanceToPoint(ray.origin); - var vD = face.normal.dot(ray.direction); // if the origin is on the positive side of a plane (so the plane can "see" the origin) and - // the ray is turned away or parallel to the plane, there is no intersection - - if (vN > 0 && vD >= 0) return null; // compute the distance from the ray’s origin to the intersection with the plane - - var t = vD !== 0 ? -vN / vD : 0; // only proceed if the distance is positive. a negative distance means the intersection point - // lies "behind" the origin - - if (t <= 0) continue; // now categorized plane as front-facing or back-facing - - if (vD > 0) { - // plane faces away from the ray, so this plane is a back-face - tFar = Math.min(t, tFar); - } else { - // front-face - tNear = Math.max(t, tNear); - } - - if (tNear > tFar) { - // if tNear ever is greater than tFar, the ray must miss the convex hull - return null; - } - } // evaluate intersection point - // always try tNear first since its the closer intersection point - - - if (tNear !== -Infinity) { - ray.at(tNear, target); - } else { - ray.at(tFar, target); - } - - return target; - }, - intersectsRay: function (ray) { - return this.intersectRay(ray, v1) !== null; - }, - makeEmpty: function () { - this.faces = []; - this.vertices = []; - return this; - }, - // Adds a vertex to the 'assigned' list of vertices and assigns it to the given face - addVertexToFace: function (vertex, face) { - vertex.face = face; - - if (face.outside === null) { - this.assigned.append(vertex); - } else { - this.assigned.insertBefore(face.outside, vertex); - } - - face.outside = vertex; - return this; - }, - // Removes a vertex from the 'assigned' list of vertices and from the given face - removeVertexFromFace: function (vertex, face) { - if (vertex === face.outside) { - // fix face.outside link - if (vertex.next !== null && vertex.next.face === face) { - // face has at least 2 outside vertices, move the 'outside' reference - face.outside = vertex.next; - } else { - // vertex was the only outside vertex that face had - face.outside = null; - } - } - - this.assigned.remove(vertex); - return this; - }, - // Removes all the visible vertices that a given face is able to see which are stored in the 'assigned' vertext list - removeAllVerticesFromFace: function (face) { - if (face.outside !== null) { - // reference to the first and last vertex of this face - var start = face.outside; - var end = face.outside; - - while (end.next !== null && end.next.face === face) { - end = end.next; - } - - this.assigned.removeSubList(start, end); // fix references - - start.prev = end.next = null; - face.outside = null; - return start; - } - }, - // Removes all the visible vertices that 'face' is able to see - deleteFaceVertices: function (face, absorbingFace) { - var faceVertices = this.removeAllVerticesFromFace(face); - - if (faceVertices !== undefined) { - if (absorbingFace === undefined) { - // mark the vertices to be reassigned to some other face - this.unassigned.appendChain(faceVertices); - } else { - // if there's an absorbing face try to assign as many vertices as possible to it - var vertex = faceVertices; - - do { - // we need to buffer the subsequent vertex at this point because the 'vertex.next' reference - // will be changed by upcoming method calls - var nextVertex = vertex.next; - var distance = absorbingFace.distanceToPoint(vertex.point); // check if 'vertex' is able to see 'absorbingFace' - - if (distance > this.tolerance) { - this.addVertexToFace(vertex, absorbingFace); - } else { - this.unassigned.append(vertex); - } // now assign next vertex - - - vertex = nextVertex; - } while (vertex !== null); - } - } - - return this; - }, - // Reassigns as many vertices as possible from the unassigned list to the new faces - resolveUnassignedPoints: function (newFaces) { - if (this.unassigned.isEmpty() === false) { - var vertex = this.unassigned.first(); - - do { - // buffer 'next' reference, see .deleteFaceVertices() - var nextVertex = vertex.next; - var maxDistance = this.tolerance; - var maxFace = null; - - for (let i = 0; i < newFaces.length; i++) { - var face = newFaces[i]; - - if (face.mark === Visible) { - var distance = face.distanceToPoint(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - maxFace = face; - } - - if (maxDistance > 1000 * this.tolerance) break; - } - } // 'maxFace' can be null e.g. if there are identical vertices - - - if (maxFace !== null) { - this.addVertexToFace(vertex, maxFace); - } - - vertex = nextVertex; - } while (vertex !== null); - } - - return this; - }, - // Computes the extremes of a simplex which will be the initial hull - computeExtremes: function () { - var min = new Vector3(); - var max = new Vector3(); - var minVertices = []; - var maxVertices = []; - var i, l, j; // initially assume that the first vertex is the min/max - - for (i = 0; i < 3; i++) { - minVertices[i] = maxVertices[i] = this.vertices[0]; - } - - min.copy(this.vertices[0].point); - max.copy(this.vertices[0].point); // compute the min/max vertex on all six directions - - for (i = 0, l = this.vertices.length; i < l; i++) { - var vertex = this.vertices[i]; - var point = vertex.point; // update the min coordinates - - for (j = 0; j < 3; j++) { - if (point.getComponent(j) < min.getComponent(j)) { - min.setComponent(j, point.getComponent(j)); - minVertices[j] = vertex; - } - } // update the max coordinates - - - for (j = 0; j < 3; j++) { - if (point.getComponent(j) > max.getComponent(j)) { - max.setComponent(j, point.getComponent(j)); - maxVertices[j] = vertex; - } - } - } // use min/max vectors to compute an optimal epsilon - - - this.tolerance = 3 * Number.EPSILON * (Math.max(Math.abs(min.x), Math.abs(max.x)) + Math.max(Math.abs(min.y), Math.abs(max.y)) + Math.max(Math.abs(min.z), Math.abs(max.z))); - return { - min: minVertices, - max: maxVertices - }; - }, - // Computes the initial simplex assigning to its faces all the points - // that are candidates to form part of the hull - computeInitialHull: function () { - var line3, plane, closestPoint; - return function computeInitialHull() { - if (line3 === undefined) { - line3 = new Line3(); - plane = new Plane(); - closestPoint = new Vector3(); - } - - var vertex, - vertices = this.vertices; - var extremes = this.computeExtremes(); - var min = extremes.min; - var max = extremes.max; - var v0, v1, v2, v3; - var i, l, j; // 1. Find the two vertices 'v0' and 'v1' with the greatest 1d separation - // (max.x - min.x) - // (max.y - min.y) - // (max.z - min.z) - - var distance, - maxDistance = 0; - var index = 0; - - for (i = 0; i < 3; i++) { - distance = max[i].point.getComponent(i) - min[i].point.getComponent(i); - - if (distance > maxDistance) { - maxDistance = distance; - index = i; - } - } - - v0 = min[index]; - v1 = max[index]; // 2. The next vertex 'v2' is the one farthest to the line formed by 'v0' and 'v1' - - maxDistance = 0; - line3.set(v0.point, v1.point); - - for (i = 0, l = this.vertices.length; i < l; i++) { - vertex = vertices[i]; - - if (vertex !== v0 && vertex !== v1) { - line3.closestPointToPoint(vertex.point, true, closestPoint); - distance = closestPoint.distanceToSquared(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - v2 = vertex; - } - } - } // 3. The next vertex 'v3' is the one farthest to the plane 'v0', 'v1', 'v2' - - - maxDistance = -1; - plane.setFromCoplanarPoints(v0.point, v1.point, v2.point); - - for (i = 0, l = this.vertices.length; i < l; i++) { - vertex = vertices[i]; - - if (vertex !== v0 && vertex !== v1 && vertex !== v2) { - distance = Math.abs(plane.distanceToPoint(vertex.point)); - - if (distance > maxDistance) { - maxDistance = distance; - v3 = vertex; - } - } - } - - var faces = []; - - if (plane.distanceToPoint(v3.point) < 0) { - // the face is not able to see the point so 'plane.normal' is pointing outside the tetrahedron - faces.push(Face.create(v0, v1, v2), Face.create(v3, v1, v0), Face.create(v3, v2, v1), Face.create(v3, v0, v2)); // set the twin edge - - for (i = 0; i < 3; i++) { - j = (i + 1) % 3; // join face[ i ] i > 0, with the first face - - faces[i + 1].getEdge(2).setTwin(faces[0].getEdge(j)); // join face[ i ] with face[ i + 1 ], 1 <= i <= 3 - - faces[i + 1].getEdge(1).setTwin(faces[j + 1].getEdge(0)); - } - } else { - // the face is able to see the point so 'plane.normal' is pointing inside the tetrahedron - faces.push(Face.create(v0, v2, v1), Face.create(v3, v0, v1), Face.create(v3, v1, v2), Face.create(v3, v2, v0)); // set the twin edge - - for (i = 0; i < 3; i++) { - j = (i + 1) % 3; // join face[ i ] i > 0, with the first face - - faces[i + 1].getEdge(2).setTwin(faces[0].getEdge((3 - i) % 3)); // join face[ i ] with face[ i + 1 ] - - faces[i + 1].getEdge(0).setTwin(faces[j + 1].getEdge(1)); - } - } // the initial hull is the tetrahedron - - - for (i = 0; i < 4; i++) { - this.faces.push(faces[i]); - } // initial assignment of vertices to the faces of the tetrahedron - - - for (i = 0, l = vertices.length; i < l; i++) { - vertex = vertices[i]; - - if (vertex !== v0 && vertex !== v1 && vertex !== v2 && vertex !== v3) { - maxDistance = this.tolerance; - var maxFace = null; - - for (j = 0; j < 4; j++) { - distance = this.faces[j].distanceToPoint(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - maxFace = this.faces[j]; - } - } - - if (maxFace !== null) { - this.addVertexToFace(vertex, maxFace); - } - } - } - - return this; - }; - }(), - // Removes inactive faces - reindexFaces: function () { - var activeFaces = []; - - for (let i = 0; i < this.faces.length; i++) { - var face = this.faces[i]; - - if (face.mark === Visible) { - activeFaces.push(face); - } - } - - this.faces = activeFaces; - return this; - }, - // Finds the next vertex to create faces with the current hull - nextVertexToAdd: function () { - // if the 'assigned' list of vertices is empty, no vertices are left. return with 'undefined' - if (this.assigned.isEmpty() === false) { - var eyeVertex, - maxDistance = 0; // grap the first available face and start with the first visible vertex of that face - - var eyeFace = this.assigned.first().face; - var vertex = eyeFace.outside; // now calculate the farthest vertex that face can see - - do { - var distance = eyeFace.distanceToPoint(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - eyeVertex = vertex; - } - - vertex = vertex.next; - } while (vertex !== null && vertex.face === eyeFace); - - return eyeVertex; - } - }, - // Computes a chain of half edges in CCW order called the 'horizon'. - // For an edge to be part of the horizon it must join a face that can see - // 'eyePoint' and a face that cannot see 'eyePoint'. - computeHorizon: function (eyePoint, crossEdge, face, horizon) { - // moves face's vertices to the 'unassigned' vertex list - this.deleteFaceVertices(face); - face.mark = Deleted; - var edge; - - if (crossEdge === null) { - edge = crossEdge = face.getEdge(0); - } else { - // start from the next edge since 'crossEdge' was already analyzed - // (actually 'crossEdge.twin' was the edge who called this method recursively) - edge = crossEdge.next; - } - - do { - var twinEdge = edge.twin; - var oppositeFace = twinEdge.face; - - if (oppositeFace.mark === Visible) { - if (oppositeFace.distanceToPoint(eyePoint) > this.tolerance) { - // the opposite face can see the vertex, so proceed with next edge - this.computeHorizon(eyePoint, twinEdge, oppositeFace, horizon); - } else { - // the opposite face can't see the vertex, so this edge is part of the horizon - horizon.push(edge); - } - } - - edge = edge.next; - } while (edge !== crossEdge); - - return this; - }, - // Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head' in CCW order - addAdjoiningFace: function (eyeVertex, horizonEdge) { - // all the half edges are created in ccw order thus the face is always pointing outside the hull - var face = Face.create(eyeVertex, horizonEdge.tail(), horizonEdge.head()); - this.faces.push(face); // join face.getEdge( - 1 ) with the horizon's opposite edge face.getEdge( - 1 ) = face.getEdge( 2 ) - - face.getEdge(-1).setTwin(horizonEdge.twin); - return face.getEdge(0); // the half edge whose vertex is the eyeVertex - }, - // Adds 'horizon.length' faces to the hull, each face will be linked with the - // horizon opposite face and the face on the left/right - addNewFaces: function (eyeVertex, horizon) { - this.newFaces = []; - var firstSideEdge = null; - var previousSideEdge = null; - - for (let i = 0; i < horizon.length; i++) { - var horizonEdge = horizon[i]; // returns the right side edge - - var sideEdge = this.addAdjoiningFace(eyeVertex, horizonEdge); - - if (firstSideEdge === null) { - firstSideEdge = sideEdge; - } else { - // joins face.getEdge( 1 ) with previousFace.getEdge( 0 ) - sideEdge.next.setTwin(previousSideEdge); - } - - this.newFaces.push(sideEdge.face); - previousSideEdge = sideEdge; - } // perform final join of new faces - - - firstSideEdge.next.setTwin(previousSideEdge); - return this; - }, - // Adds a vertex to the hull - addVertexToHull: function (eyeVertex) { - var horizon = []; - this.unassigned.clear(); // remove 'eyeVertex' from 'eyeVertex.face' so that it can't be added to the 'unassigned' vertex list - - this.removeVertexFromFace(eyeVertex, eyeVertex.face); - this.computeHorizon(eyeVertex.point, null, eyeVertex.face, horizon); - this.addNewFaces(eyeVertex, horizon); // reassign 'unassigned' vertices to the new faces - - this.resolveUnassignedPoints(this.newFaces); - return this; - }, - cleanup: function () { - this.assigned.clear(); - this.unassigned.clear(); - this.newFaces = []; - return this; - }, - compute: function () { - var vertex; - this.computeInitialHull(); // add all available vertices gradually to the hull - - while ((vertex = this.nextVertexToAdd()) !== undefined) { - this.addVertexToHull(vertex); - } - - this.reindexFaces(); - this.cleanup(); - return this; - } - }); // - - function Face() { - this.normal = new Vector3(); - this.midpoint = new Vector3(); - this.area = 0; - this.constant = 0; // signed distance from face to the origin - - this.outside = null; // reference to a vertex in a vertex list this face can see - - this.mark = Visible; - this.edge = null; - } - - Object.assign(Face, { - create: function (a, b, c) { - var face = new Face(); - var e0 = new HalfEdge(a, face); - var e1 = new HalfEdge(b, face); - var e2 = new HalfEdge(c, face); // join edges - - e0.next = e2.prev = e1; - e1.next = e0.prev = e2; - e2.next = e1.prev = e0; // main half edge reference - - face.edge = e0; - return face.compute(); - } - }); - Object.assign(Face.prototype, { - getEdge: function (i) { - var edge = this.edge; - - while (i > 0) { - edge = edge.next; - i--; - } - - while (i < 0) { - edge = edge.prev; - i++; - } - - return edge; - }, - compute: function () { - var triangle; - return function compute() { - if (triangle === undefined) triangle = new Triangle(); - var a = this.edge.tail(); - var b = this.edge.head(); - var c = this.edge.next.head(); - triangle.set(a.point, b.point, c.point); - triangle.getNormal(this.normal); - triangle.getMidpoint(this.midpoint); - this.area = triangle.getArea(); - this.constant = this.normal.dot(this.midpoint); - return this; - }; - }(), - distanceToPoint: function (point) { - return this.normal.dot(point) - this.constant; - } - }); // Entity for a Doubly-Connected Edge List (DCEL). - - function HalfEdge(vertex, face) { - this.vertex = vertex; - this.prev = null; - this.next = null; - this.twin = null; - this.face = face; - } - - Object.assign(HalfEdge.prototype, { - head: function () { - return this.vertex; - }, - tail: function () { - return this.prev ? this.prev.vertex : null; - }, - length: function () { - var head = this.head(); - var tail = this.tail(); - - if (tail !== null) { - return tail.point.distanceTo(head.point); - } - - return -1; - }, - lengthSquared: function () { - var head = this.head(); - var tail = this.tail(); - - if (tail !== null) { - return tail.point.distanceToSquared(head.point); - } - - return -1; - }, - setTwin: function (edge) { - this.twin = edge; - edge.twin = this; - return this; - } - }); // A vertex as a double linked list node. - - function VertexNode(point) { - this.point = point; - this.prev = null; - this.next = null; - this.face = null; // the face that is able to see this vertex - } // A double linked list that contains vertex nodes. - - - function VertexList() { - this.head = null; - this.tail = null; - } - - Object.assign(VertexList.prototype, { - first: function () { - return this.head; - }, - last: function () { - return this.tail; - }, - clear: function () { - this.head = this.tail = null; - return this; - }, - // Inserts a vertex before the target vertex - insertBefore: function (target, vertex) { - vertex.prev = target.prev; - vertex.next = target; - - if (vertex.prev === null) { - this.head = vertex; - } else { - vertex.prev.next = vertex; - } - - target.prev = vertex; - return this; - }, - // Inserts a vertex after the target vertex - insertAfter: function (target, vertex) { - vertex.prev = target; - vertex.next = target.next; - - if (vertex.next === null) { - this.tail = vertex; - } else { - vertex.next.prev = vertex; - } - - target.next = vertex; - return this; - }, - // Appends a vertex to the end of the linked list - append: function (vertex) { - if (this.head === null) { - this.head = vertex; - } else { - this.tail.next = vertex; - } - - vertex.prev = this.tail; - vertex.next = null; // the tail has no subsequent vertex - - this.tail = vertex; - return this; - }, - // Appends a chain of vertices where 'vertex' is the head. - appendChain: function (vertex) { - if (this.head === null) { - this.head = vertex; - } else { - this.tail.next = vertex; - } - - vertex.prev = this.tail; // ensure that the 'tail' reference points to the last vertex of the chain - - while (vertex.next !== null) { - vertex = vertex.next; - } - - this.tail = vertex; - return this; - }, - // Removes a vertex from the linked list - remove: function (vertex) { - if (vertex.prev === null) { - this.head = vertex.next; - } else { - vertex.prev.next = vertex.next; - } - - if (vertex.next === null) { - this.tail = vertex.prev; - } else { - vertex.next.prev = vertex.prev; - } - - return this; - }, - // Removes a list of vertices whose 'head' is 'a' and whose 'tail' is b - removeSubList: function (a, b) { - if (a.prev === null) { - this.head = b.next; - } else { - a.prev.next = b.next; - } - - if (b.next === null) { - this.tail = a.prev; - } else { - b.next.prev = a.prev; - } - - return this; - }, - isEmpty: function () { - return this.head === null; - } - }); - return ConvexHull; -}(); - -class ConvexGeometry extends BufferGeometry { - constructor(points) { - super(); // buffers - - const vertices = []; - const normals = []; - - if (ConvexHull === undefined) { - console.error('THREE.ConvexBufferGeometry: ConvexBufferGeometry relies on ConvexHull'); - } - - const convexHull = new ConvexHull().setFromPoints(points); // generate vertices and normals - - const faces = convexHull.faces; - - for (let i = 0; i < faces.length; i++) { - const face = faces[i]; - let edge = face.edge; // we move along a doubly-connected edge list to access all face points (see HalfEdge docs) - - do { - const point = edge.head().point; - vertices.push(point.x, point.y, point.z); - normals.push(face.normal.x, face.normal.y, face.normal.z); - edge = edge.next; - } while (edge !== face.edge); - } // build geometry - - - this.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - this.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - } - -} - -/** - * @fileoverview This class can be used to subdivide a convex Geometry object into pieces. - * - * Usage: - * - * Use the function prepareBreakableObject to prepare a Mesh object to be broken. - * - * Then, call the various functions to subdivide the object (subdivideByImpact, cutByPlane) - * - * Sub-objects that are product of subdivision don't need prepareBreakableObject to be called on them. - * - * Requisites for the object: - * - * - Mesh object must have a BufferGeometry (not Geometry) and a Material - * - * - Vertex normals must be planar (not smoothed) - * - * - The geometry must be convex (this is not checked in the library). You can create convex - * geometries with ConvexGeometry. The BoxGeometry, SphereGeometry and other convex primitives - * can also be used. - * - * Note: This lib adds member variables to object's userData member (see prepareBreakableObject function) - * Use with caution and read the code when using with other libs. - * - * @param {double} minSizeForBreak Min size a debris can have to break. - * @param {double} smallDelta Max distance to consider that a point belongs to a plane. - * - */ - -var ConvexObjectBreaker = function (minSizeForBreak, smallDelta) { - this.minSizeForBreak = minSizeForBreak || 1.4; - this.smallDelta = smallDelta || 0.0001; - this.tempLine1 = new Line3(); - this.tempPlane1 = new Plane(); - this.tempPlane2 = new Plane(); - this.tempPlane_Cut = new Plane(); - this.tempCM1 = new Vector3(); - this.tempCM2 = new Vector3(); - this.tempVector3 = new Vector3(); - this.tempVector3_2 = new Vector3(); - this.tempVector3_3 = new Vector3(); - this.tempVector3_P0 = new Vector3(); - this.tempVector3_P1 = new Vector3(); - this.tempVector3_P2 = new Vector3(); - this.tempVector3_N0 = new Vector3(); - this.tempVector3_N1 = new Vector3(); - this.tempVector3_AB = new Vector3(); - this.tempVector3_CB = new Vector3(); - this.tempResultObjects = { - object1: null, - object2: null - }; - this.segments = []; - var n = 30 * 30; - - for (let i = 0; i < n; i++) this.segments[i] = false; -}; - -ConvexObjectBreaker.prototype = { - constructor: ConvexObjectBreaker, - prepareBreakableObject: function (object, mass, velocity, angularVelocity, breakable) { - // object is a Object3d (normally a Mesh), must have a BufferGeometry, and it must be convex. - // Its material property is propagated to its children (sub-pieces) - // mass must be > 0 - if (!object.geometry.isBufferGeometry) { - console.error('THREE.ConvexObjectBreaker.prepareBreakableObject(): Parameter object must have a BufferGeometry.'); - } - - var userData = object.userData; - userData.mass = mass; - userData.velocity = velocity.clone(); - userData.angularVelocity = angularVelocity.clone(); - userData.breakable = breakable; - }, - - /* - * @param {int} maxRadialIterations Iterations for radial cuts. - * @param {int} maxRandomIterations Max random iterations for not-radial cuts - * - * Returns the array of pieces - */ - subdivideByImpact: function (object, pointOfImpact, normal, maxRadialIterations, maxRandomIterations) { - var debris = []; - var tempPlane1 = this.tempPlane1; - var tempPlane2 = this.tempPlane2; - this.tempVector3.addVectors(pointOfImpact, normal); - tempPlane1.setFromCoplanarPoints(pointOfImpact, object.position, this.tempVector3); - var maxTotalIterations = maxRandomIterations + maxRadialIterations; - var scope = this; - - function subdivideRadial(subObject, startAngle, endAngle, numIterations) { - if (Math.random() < numIterations * 0.05 || numIterations > maxTotalIterations) { - debris.push(subObject); - return; - } - - var angle = Math.PI; - - if (numIterations === 0) { - tempPlane2.normal.copy(tempPlane1.normal); - tempPlane2.constant = tempPlane1.constant; - } else { - if (numIterations <= maxRadialIterations) { - angle = (endAngle - startAngle) * (0.2 + 0.6 * Math.random()) + startAngle; // Rotate tempPlane2 at impact point around normal axis and the angle - - scope.tempVector3_2.copy(object.position).sub(pointOfImpact).applyAxisAngle(normal, angle).add(pointOfImpact); - tempPlane2.setFromCoplanarPoints(pointOfImpact, scope.tempVector3, scope.tempVector3_2); - } else { - angle = (0.5 * (numIterations & 1) + 0.2 * (2 - Math.random())) * Math.PI; // Rotate tempPlane2 at object position around normal axis and the angle - - scope.tempVector3_2.copy(pointOfImpact).sub(subObject.position).applyAxisAngle(normal, angle).add(subObject.position); - scope.tempVector3_3.copy(normal).add(subObject.position); - tempPlane2.setFromCoplanarPoints(subObject.position, scope.tempVector3_3, scope.tempVector3_2); - } - } // Perform the cut - - - scope.cutByPlane(subObject, tempPlane2, scope.tempResultObjects); - var obj1 = scope.tempResultObjects.object1; - var obj2 = scope.tempResultObjects.object2; - - if (obj1) { - subdivideRadial(obj1, startAngle, angle, numIterations + 1); - } - - if (obj2) { - subdivideRadial(obj2, angle, endAngle, numIterations + 1); - } - } - - subdivideRadial(object, 0, 2 * Math.PI, 0); - return debris; - }, - cutByPlane: function (object, plane, output) { - // Returns breakable objects in output.object1 and output.object2 members, the resulting 2 pieces of the cut. - // object2 can be null if the plane doesn't cut the object. - // object1 can be null only in case of internal error - // Returned value is number of pieces, 0 for error. - var geometry = object.geometry; - var coords = geometry.attributes.position.array; - var normals = geometry.attributes.normal.array; - var numPoints = coords.length / 3; - var numFaces = numPoints / 3; - var indices = geometry.getIndex(); - - if (indices) { - indices = indices.array; - numFaces = indices.length / 3; - } - - function getVertexIndex(faceIdx, vert) { - // vert = 0, 1 or 2. - var idx = faceIdx * 3 + vert; - return indices ? indices[idx] : idx; - } - - var points1 = []; - var points2 = []; - var delta = this.smallDelta; // Reset segments mark - - var numPointPairs = numPoints * numPoints; - - for (let i = 0; i < numPointPairs; i++) this.segments[i] = false; - - var p0 = this.tempVector3_P0; - var p1 = this.tempVector3_P1; - var n0 = this.tempVector3_N0; - var n1 = this.tempVector3_N1; // Iterate through the faces to mark edges shared by coplanar faces - - for (let i = 0; i < numFaces - 1; i++) { - var a1 = getVertexIndex(i, 0); - var b1 = getVertexIndex(i, 1); - var c1 = getVertexIndex(i, 2); // Assuming all 3 vertices have the same normal - - n0.set(normals[a1], normals[a1] + 1, normals[a1] + 2); - - for (let j = i + 1; j < numFaces; j++) { - var a2 = getVertexIndex(j, 0); - var b2 = getVertexIndex(j, 1); - var c2 = getVertexIndex(j, 2); // Assuming all 3 vertices have the same normal - - n1.set(normals[a2], normals[a2] + 1, normals[a2] + 2); - var coplanar = 1 - n0.dot(n1) < delta; - - if (coplanar) { - if (a1 === a2 || a1 === b2 || a1 === c2) { - if (b1 === a2 || b1 === b2 || b1 === c2) { - this.segments[a1 * numPoints + b1] = true; - this.segments[b1 * numPoints + a1] = true; - } else { - this.segments[c1 * numPoints + a1] = true; - this.segments[a1 * numPoints + c1] = true; - } - } else if (b1 === a2 || b1 === b2 || b1 === c2) { - this.segments[c1 * numPoints + b1] = true; - this.segments[b1 * numPoints + c1] = true; - } - } - } - } // Transform the plane to object local space - - - var localPlane = this.tempPlane_Cut; - object.updateMatrix(); - ConvexObjectBreaker.transformPlaneToLocalSpace(plane, object.matrix, localPlane); // Iterate through the faces adding points to both pieces - - for (let i = 0; i < numFaces; i++) { - var va = getVertexIndex(i, 0); - var vb = getVertexIndex(i, 1); - var vc = getVertexIndex(i, 2); - - for (let segment = 0; segment < 3; segment++) { - var i0 = segment === 0 ? va : segment === 1 ? vb : vc; - var i1 = segment === 0 ? vb : segment === 1 ? vc : va; - var segmentState = this.segments[i0 * numPoints + i1]; - if (segmentState) continue; // The segment already has been processed in another face - // Mark segment as processed (also inverted segment) - - this.segments[i0 * numPoints + i1] = true; - this.segments[i1 * numPoints + i0] = true; - p0.set(coords[3 * i0], coords[3 * i0 + 1], coords[3 * i0 + 2]); - p1.set(coords[3 * i1], coords[3 * i1 + 1], coords[3 * i1 + 2]); // mark: 1 for negative side, 2 for positive side, 3 for coplanar point - - var mark0 = 0; - var d = localPlane.distanceToPoint(p0); - - if (d > delta) { - mark0 = 2; - points2.push(p0.clone()); - } else if (d < -delta) { - mark0 = 1; - points1.push(p0.clone()); - } else { - mark0 = 3; - points1.push(p0.clone()); - points2.push(p0.clone()); - } // mark: 1 for negative side, 2 for positive side, 3 for coplanar point - - - var mark1 = 0; - var d = localPlane.distanceToPoint(p1); - - if (d > delta) { - mark1 = 2; - points2.push(p1.clone()); - } else if (d < -delta) { - mark1 = 1; - points1.push(p1.clone()); - } else { - mark1 = 3; - points1.push(p1.clone()); - points2.push(p1.clone()); - } - - if (mark0 === 1 && mark1 === 2 || mark0 === 2 && mark1 === 1) { - // Intersection of segment with the plane - this.tempLine1.start.copy(p0); - this.tempLine1.end.copy(p1); - var intersection = new Vector3(); - intersection = localPlane.intersectLine(this.tempLine1, intersection); - - if (intersection === undefined) { - // Shouldn't happen - console.error('Internal error: segment does not intersect plane.'); - output.segmentedObject1 = null; - output.segmentedObject2 = null; - return 0; - } - - points1.push(intersection); - points2.push(intersection.clone()); - } - } - } // Calculate debris mass (very fast and imprecise): - - - var newMass = object.userData.mass * 0.5; // Calculate debris Center of Mass (again fast and imprecise) - - this.tempCM1.set(0, 0, 0); - var radius1 = 0; - var numPoints1 = points1.length; - - if (numPoints1 > 0) { - for (let i = 0; i < numPoints1; i++) this.tempCM1.add(points1[i]); - - this.tempCM1.divideScalar(numPoints1); - - for (let i = 0; i < numPoints1; i++) { - var p = points1[i]; - p.sub(this.tempCM1); - radius1 = Math.max(radius1, p.x, p.y, p.z); - } - - this.tempCM1.add(object.position); - } - - this.tempCM2.set(0, 0, 0); - var radius2 = 0; - var numPoints2 = points2.length; - - if (numPoints2 > 0) { - for (let i = 0; i < numPoints2; i++) this.tempCM2.add(points2[i]); - - this.tempCM2.divideScalar(numPoints2); - - for (let i = 0; i < numPoints2; i++) { - var p = points2[i]; - p.sub(this.tempCM2); - radius2 = Math.max(radius2, p.x, p.y, p.z); - } - - this.tempCM2.add(object.position); - } - - var object1 = null; - var object2 = null; - var numObjects = 0; - - if (numPoints1 > 4) { - object1 = new Mesh(new ConvexGeometry(points1), object.material); - object1.position.copy(this.tempCM1); - object1.quaternion.copy(object.quaternion); - this.prepareBreakableObject(object1, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius1 > this.minSizeForBreak); - numObjects++; - } - - if (numPoints2 > 4) { - object2 = new Mesh(new ConvexGeometry(points2), object.material); - object2.position.copy(this.tempCM2); - object2.quaternion.copy(object.quaternion); - this.prepareBreakableObject(object2, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius2 > this.minSizeForBreak); - numObjects++; - } - - output.object1 = object1; - output.object2 = object2; - return numObjects; - } -}; - -ConvexObjectBreaker.transformFreeVector = function (v, m) { - // input: - // vector interpreted as a free vector - // THREE.Matrix4 orthogonal matrix (matrix without scale) - var x = v.x, - y = v.y, - z = v.z; - var e = m.elements; - v.x = e[0] * x + e[4] * y + e[8] * z; - v.y = e[1] * x + e[5] * y + e[9] * z; - v.z = e[2] * x + e[6] * y + e[10] * z; - return v; -}; - -ConvexObjectBreaker.transformFreeVectorInverse = function (v, m) { - // input: - // vector interpreted as a free vector - // THREE.Matrix4 orthogonal matrix (matrix without scale) - var x = v.x, - y = v.y, - z = v.z; - var e = m.elements; - v.x = e[0] * x + e[1] * y + e[2] * z; - v.y = e[4] * x + e[5] * y + e[6] * z; - v.z = e[8] * x + e[9] * y + e[10] * z; - return v; -}; - -ConvexObjectBreaker.transformTiedVectorInverse = function (v, m) { - // input: - // vector interpreted as a tied (ordinary) vector - // THREE.Matrix4 orthogonal matrix (matrix without scale) - var x = v.x, - y = v.y, - z = v.z; - var e = m.elements; - v.x = e[0] * x + e[1] * y + e[2] * z - e[12]; - v.y = e[4] * x + e[5] * y + e[6] * z - e[13]; - v.z = e[8] * x + e[9] * y + e[10] * z - e[14]; - return v; -}; - -ConvexObjectBreaker.transformPlaneToLocalSpace = function () { - var v1 = new Vector3(); - return function transformPlaneToLocalSpace(plane, m, resultPlane) { - resultPlane.normal.copy(plane.normal); - resultPlane.constant = plane.constant; - var referencePoint = ConvexObjectBreaker.transformTiedVectorInverse(plane.coplanarPoint(v1), m); - ConvexObjectBreaker.transformFreeVectorInverse(resultPlane.normal, m); // recalculate constant (like in setFromNormalAndCoplanarPoint) - - resultPlane.constant = -referencePoint.dot(resultPlane.normal); - }; -}(); - -var Gyroscope = function () { - Object3D.call(this); -}; - -Gyroscope.prototype = Object.create(Object3D.prototype); -Gyroscope.prototype.constructor = Gyroscope; - -Gyroscope.prototype.updateMatrixWorld = function () { - var translationObject = new Vector3(); - var quaternionObject = new Quaternion(); - var scaleObject = new Vector3(); - var translationWorld = new Vector3(); - var quaternionWorld = new Quaternion(); - var scaleWorld = new Vector3(); - return function updateMatrixWorld(force) { - this.matrixAutoUpdate && this.updateMatrix(); // update matrixWorld - - if (this.matrixWorldNeedsUpdate || force) { - if (this.parent !== null) { - this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); - this.matrixWorld.decompose(translationWorld, quaternionWorld, scaleWorld); - this.matrix.decompose(translationObject, quaternionObject, scaleObject); - this.matrixWorld.compose(translationWorld, quaternionObject, scaleWorld); - } else { - this.matrixWorld.copy(this.matrix); - } - - this.matrixWorldNeedsUpdate = false; - force = true; - } // update children - - - for (let i = 0, l = this.children.length; i < l; i++) { - this.children[i].updateMatrixWorld(force); - } - }; -}(); - -var MorphAnimMesh = function (geometry, material) { - Mesh.call(this, geometry, material); - this.type = 'MorphAnimMesh'; - this.mixer = new AnimationMixer(this); - this.activeAction = null; -}; - -MorphAnimMesh.prototype = Object.create(Mesh.prototype); -MorphAnimMesh.prototype.constructor = MorphAnimMesh; - -MorphAnimMesh.prototype.setDirectionForward = function () { - this.mixer.timeScale = 1.0; -}; - -MorphAnimMesh.prototype.setDirectionBackward = function () { - this.mixer.timeScale = -1.0; -}; - -MorphAnimMesh.prototype.playAnimation = function (label, fps) { - if (this.activeAction) { - this.activeAction.stop(); - this.activeAction = null; - } - - var clip = AnimationClip.findByName(this, label); - - if (clip) { - var action = this.mixer.clipAction(clip); - action.timeScale = clip.tracks.length * fps / clip.duration; - this.activeAction = action.play(); - } else { - throw new Error('THREE.MorphAnimMesh: animations[' + label + '] undefined in .playAnimation()'); - } -}; - -MorphAnimMesh.prototype.updateAnimation = function (delta) { - this.mixer.update(delta); -}; - -MorphAnimMesh.prototype.copy = function (source) { - Mesh.prototype.copy.call(this, source); - this.mixer = new AnimationMixer(this); - return this; -}; - -Object.create(BufferGeometry.prototype); - -Object.create(BufferGeometry.prototype); - -Object.create(BufferGeometry.prototype); - -Object.create(BufferGeometry.prototype); - -Object.create(BufferGeometry.prototype); - -let webGL2Available; -function isWebGL2Available() { - if (webGL2Available !== undefined) return webGL2Available; - - try { - var _gl$getExtension2; - - let gl; - const canvas = document.createElement('canvas'); - webGL2Available = !!(window.WebGL2RenderingContext && (gl = canvas.getContext('webgl2'))); - if (gl) (_gl$getExtension2 = gl.getExtension('WEBGL_lose_context')) === null || _gl$getExtension2 === void 0 ? void 0 : _gl$getExtension2.loseContext(); - return webGL2Available; - } catch (e) { - return webGL2Available = false; - } -} - -/** - * This class has been made to hold a slice of a volume data - * @class - * @param {Volume} volume The associated volume - * @param {number} [index=0] The index of the slice - * @param {string} [axis='z'] For now only 'x', 'y' or 'z' but later it will change to a normal vector - * @see Volume - */ - -var VolumeSlice = function (volume, index, axis) { - var slice = this; - /** - * @member {Volume} volume The associated volume - */ - - this.volume = volume; - /** - * @member {Number} index The index of the slice, if changed, will automatically call updateGeometry at the next repaint - */ - - index = index || 0; - Object.defineProperty(this, 'index', { - get: function () { - return index; - }, - set: function (value) { - index = value; - slice.geometryNeedsUpdate = true; - return index; - } - }); - /** - * @member {String} axis The normal axis - */ - - this.axis = axis || 'z'; - /** - * @member {HTMLCanvasElement} canvas The final canvas used for the texture - */ - - /** - * @member {CanvasRenderingContext2D} ctx Context of the canvas - */ - - this.canvas = document.createElement('canvas'); - /** - * @member {HTMLCanvasElement} canvasBuffer The intermediary canvas used to paint the data - */ - - /** - * @member {CanvasRenderingContext2D} ctxBuffer Context of the canvas buffer - */ - - this.canvasBuffer = document.createElement('canvas'); - this.updateGeometry(); - var canvasMap = new Texture(this.canvas); - canvasMap.minFilter = LinearFilter; - canvasMap.wrapS = canvasMap.wrapT = ClampToEdgeWrapping; - var material = new MeshBasicMaterial({ - map: canvasMap, - side: DoubleSide, - transparent: true - }); - /** - * @member {Mesh} mesh The mesh ready to get used in the scene - */ - - this.mesh = new Mesh(this.geometry, material); - this.mesh.matrixAutoUpdate = false; - /** - * @member {Boolean} geometryNeedsUpdate If set to true, updateGeometry will be triggered at the next repaint - */ - - this.geometryNeedsUpdate = true; - this.repaint(); - /** - * @member {Number} iLength Width of slice in the original coordinate system, corresponds to the width of the buffer canvas - */ - - /** - * @member {Number} jLength Height of slice in the original coordinate system, corresponds to the height of the buffer canvas - */ - - /** - * @member {Function} sliceAccess Function that allow the slice to access right data - * @see Volume.extractPerpendicularPlane - * @param {Number} i The first coordinate - * @param {Number} j The second coordinate - * @returns {Number} the index corresponding to the voxel in volume.data of the given position in the slice - */ -}; - -VolumeSlice.prototype = { - constructor: VolumeSlice, - - /** - * @member {Function} repaint Refresh the texture and the geometry if geometryNeedsUpdate is set to true - * @memberof VolumeSlice - */ - repaint: function () { - if (this.geometryNeedsUpdate) { - this.updateGeometry(); - } - - var iLength = this.iLength, - jLength = this.jLength, - sliceAccess = this.sliceAccess, - volume = this.volume, - canvas = this.canvasBuffer, - ctx = this.ctxBuffer; // get the imageData and pixel array from the canvas - - var imgData = ctx.getImageData(0, 0, iLength, jLength); - var data = imgData.data; - var volumeData = volume.data; - var upperThreshold = volume.upperThreshold; - var lowerThreshold = volume.lowerThreshold; - var windowLow = volume.windowLow; - var windowHigh = volume.windowHigh; // manipulate some pixel elements - - var pixelCount = 0; - - if (volume.dataType === 'label') { - //this part is currently useless but will be used when colortables will be handled - for (let j = 0; j < jLength; j++) { - for (let i = 0; i < iLength; i++) { - var label = volumeData[sliceAccess(i, j)]; - label = label >= this.colorMap.length ? label % this.colorMap.length + 1 : label; - var color = this.colorMap[label]; - data[4 * pixelCount] = color >> 24 & 0xff; - data[4 * pixelCount + 1] = color >> 16 & 0xff; - data[4 * pixelCount + 2] = color >> 8 & 0xff; - data[4 * pixelCount + 3] = color & 0xff; - pixelCount++; - } - } - } else { - for (let j = 0; j < jLength; j++) { - for (let i = 0; i < iLength; i++) { - var value = volumeData[sliceAccess(i, j)]; - var alpha = 0xff; //apply threshold - - alpha = upperThreshold >= value ? lowerThreshold <= value ? alpha : 0 : 0; //apply window level - - value = Math.floor(255 * (value - windowLow) / (windowHigh - windowLow)); - value = value > 255 ? 255 : value < 0 ? 0 : value | 0; - data[4 * pixelCount] = value; - data[4 * pixelCount + 1] = value; - data[4 * pixelCount + 2] = value; - data[4 * pixelCount + 3] = alpha; - pixelCount++; - } - } - } - - ctx.putImageData(imgData, 0, 0); - this.ctx.drawImage(canvas, 0, 0, iLength, jLength, 0, 0, this.canvas.width, this.canvas.height); - this.mesh.material.map.needsUpdate = true; - }, - - /** - * @member {Function} Refresh the geometry according to axis and index - * @see Volume.extractPerpendicularPlane - * @memberof VolumeSlice - */ - updateGeometry: function () { - var extracted = this.volume.extractPerpendicularPlane(this.axis, this.index); - this.sliceAccess = extracted.sliceAccess; - this.jLength = extracted.jLength; - this.iLength = extracted.iLength; - this.matrix = extracted.matrix; - this.canvas.width = extracted.planeWidth; - this.canvas.height = extracted.planeHeight; - this.canvasBuffer.width = this.iLength; - this.canvasBuffer.height = this.jLength; - this.ctx = this.canvas.getContext('2d'); - this.ctxBuffer = this.canvasBuffer.getContext('2d'); - if (this.geometry) this.geometry.dispose(); // dispose existing geometry - - this.geometry = new PlaneGeometry(extracted.planeWidth, extracted.planeHeight); - - if (this.mesh) { - this.mesh.geometry = this.geometry; //reset mesh matrix - - this.mesh.matrix.identity(); - this.mesh.applyMatrix4(this.matrix); - } - - this.geometryNeedsUpdate = false; - } -}; - -/** - * This class had been written to handle the output of the NRRD loader. - * It contains a volume of data and informations about it. - * For now it only handles 3 dimensional data. - * See the webgl_loader_nrrd.html example and the loaderNRRD.js file to see how to use this class. - * @class - * @param {number} xLength Width of the volume - * @param {number} yLength Length of the volume - * @param {number} zLength Depth of the volume - * @param {string} type The type of data (uint8, uint16, ...) - * @param {ArrayBuffer} arrayBuffer The buffer with volume data - */ - -var Volume = function (xLength, yLength, zLength, type, arrayBuffer) { - if (arguments.length > 0) { - /** - * @member {number} xLength Width of the volume in the IJK coordinate system - */ - this.xLength = Number(xLength) || 1; - /** - * @member {number} yLength Height of the volume in the IJK coordinate system - */ - - this.yLength = Number(yLength) || 1; - /** - * @member {number} zLength Depth of the volume in the IJK coordinate system - */ - - this.zLength = Number(zLength) || 1; - /** - * @member {TypedArray} data Data of the volume - */ - - switch (type) { - case 'Uint8': - case 'uint8': - case 'uchar': - case 'unsigned char': - case 'uint8_t': - this.data = new Uint8Array(arrayBuffer); - break; - - case 'Int8': - case 'int8': - case 'signed char': - case 'int8_t': - this.data = new Int8Array(arrayBuffer); - break; - - case 'Int16': - case 'int16': - case 'short': - case 'short int': - case 'signed short': - case 'signed short int': - case 'int16_t': - this.data = new Int16Array(arrayBuffer); - break; - - case 'Uint16': - case 'uint16': - case 'ushort': - case 'unsigned short': - case 'unsigned short int': - case 'uint16_t': - this.data = new Uint16Array(arrayBuffer); - break; - - case 'Int32': - case 'int32': - case 'int': - case 'signed int': - case 'int32_t': - this.data = new Int32Array(arrayBuffer); - break; - - case 'Uint32': - case 'uint32': - case 'uint': - case 'unsigned int': - case 'uint32_t': - this.data = new Uint32Array(arrayBuffer); - break; - - case 'longlong': - case 'long long': - case 'long long int': - case 'signed long long': - case 'signed long long int': - case 'int64': - case 'int64_t': - case 'ulonglong': - case 'unsigned long long': - case 'unsigned long long int': - case 'uint64': - case 'uint64_t': - throw 'Error in Volume constructor : this type is not supported in JavaScript'; - - case 'Float32': - case 'float32': - case 'float': - this.data = new Float32Array(arrayBuffer); - break; - - case 'Float64': - case 'float64': - case 'double': - this.data = new Float64Array(arrayBuffer); - break; - - default: - this.data = new Uint8Array(arrayBuffer); - } - - if (this.data.length !== this.xLength * this.yLength * this.zLength) { - throw 'Error in Volume constructor, lengths are not matching arrayBuffer size'; - } - } - /** - * @member {Array} spacing Spacing to apply to the volume from IJK to RAS coordinate system - */ - - - this.spacing = [1, 1, 1]; - /** - * @member {Array} offset Offset of the volume in the RAS coordinate system - */ - - this.offset = [0, 0, 0]; - /** - * @member {Martrix3} matrix The IJK to RAS matrix - */ - - this.matrix = new Matrix3(); - this.matrix.identity(); - /** - * @member {Martrix3} inverseMatrix The RAS to IJK matrix - */ - - /** - * @member {number} lowerThreshold The voxels with values under this threshold won't appear in the slices. - * If changed, geometryNeedsUpdate is automatically set to true on all the slices associated to this volume - */ - - var lowerThreshold = -Infinity; - Object.defineProperty(this, 'lowerThreshold', { - get: function () { - return lowerThreshold; - }, - set: function (value) { - lowerThreshold = value; - this.sliceList.forEach(function (slice) { - slice.geometryNeedsUpdate = true; - }); - } - }); - /** - * @member {number} upperThreshold The voxels with values over this threshold won't appear in the slices. - * If changed, geometryNeedsUpdate is automatically set to true on all the slices associated to this volume - */ - - var upperThreshold = Infinity; - Object.defineProperty(this, 'upperThreshold', { - get: function () { - return upperThreshold; - }, - set: function (value) { - upperThreshold = value; - this.sliceList.forEach(function (slice) { - slice.geometryNeedsUpdate = true; - }); - } - }); - /** - * @member {Array} sliceList The list of all the slices associated to this volume - */ - - this.sliceList = []; - /** - * @member {Array} RASDimensions This array holds the dimensions of the volume in the RAS space - */ -}; - -Volume.prototype = { - constructor: Volume, - - /** - * @member {Function} getData Shortcut for data[access(i,j,k)] - * @memberof Volume - * @param {number} i First coordinate - * @param {number} j Second coordinate - * @param {number} k Third coordinate - * @returns {number} value in the data array - */ - getData: function (i, j, k) { - return this.data[k * this.xLength * this.yLength + j * this.xLength + i]; - }, - - /** - * @member {Function} access compute the index in the data array corresponding to the given coordinates in IJK system - * @memberof Volume - * @param {number} i First coordinate - * @param {number} j Second coordinate - * @param {number} k Third coordinate - * @returns {number} index - */ - access: function (i, j, k) { - return k * this.xLength * this.yLength + j * this.xLength + i; - }, - - /** - * @member {Function} reverseAccess Retrieve the IJK coordinates of the voxel corresponding of the given index in the data - * @memberof Volume - * @param {number} index index of the voxel - * @returns {Array} [x,y,z] - */ - reverseAccess: function (index) { - var z = Math.floor(index / (this.yLength * this.xLength)); - var y = Math.floor((index - z * this.yLength * this.xLength) / this.xLength); - var x = index - z * this.yLength * this.xLength - y * this.xLength; - return [x, y, z]; - }, - - /** - * @member {Function} map Apply a function to all the voxels, be careful, the value will be replaced - * @memberof Volume - * @param {Function} functionToMap A function to apply to every voxel, will be called with the following parameters : - * value of the voxel - * index of the voxel - * the data (TypedArray) - * @param {Object} context You can specify a context in which call the function, default if this Volume - * @returns {Volume} this - */ - map: function (functionToMap, context) { - var length = this.data.length; - context = context || this; - - for (let i = 0; i < length; i++) { - this.data[i] = functionToMap.call(context, this.data[i], i, this.data); - } - - return this; - }, - - /** - * @member {Function} extractPerpendicularPlane Compute the orientation of the slice and returns all the information relative to the geometry such as sliceAccess, the plane matrix (orientation and position in RAS coordinate) and the dimensions of the plane in both coordinate system. - * @memberof Volume - * @param {string} axis the normal axis to the slice 'x' 'y' or 'z' - * @param {number} index the index of the slice - * @returns {Object} an object containing all the usefull information on the geometry of the slice - */ - extractPerpendicularPlane: function (axis, RASIndex) { - var iLength, - jLength, - sliceAccess, - planeMatrix = new Matrix4().identity(), - volume = this, - planeWidth, - planeHeight, - firstSpacing, - secondSpacing, - positionOffset, - IJKIndex; - var axisInIJK = new Vector3(), - firstDirection = new Vector3(), - secondDirection = new Vector3(); - var dimensions = new Vector3(this.xLength, this.yLength, this.zLength); - - switch (axis) { - case 'x': - axisInIJK.set(1, 0, 0); - firstDirection.set(0, 0, -1); - secondDirection.set(0, -1, 0); - firstSpacing = this.spacing[2]; - secondSpacing = this.spacing[1]; - IJKIndex = new Vector3(RASIndex, 0, 0); - planeMatrix.multiply(new Matrix4().makeRotationY(Math.PI / 2)); - positionOffset = (volume.RASDimensions[0] - 1) / 2; - planeMatrix.setPosition(new Vector3(RASIndex - positionOffset, 0, 0)); - break; - - case 'y': - axisInIJK.set(0, 1, 0); - firstDirection.set(1, 0, 0); - secondDirection.set(0, 0, 1); - firstSpacing = this.spacing[0]; - secondSpacing = this.spacing[2]; - IJKIndex = new Vector3(0, RASIndex, 0); - planeMatrix.multiply(new Matrix4().makeRotationX(-Math.PI / 2)); - positionOffset = (volume.RASDimensions[1] - 1) / 2; - planeMatrix.setPosition(new Vector3(0, RASIndex - positionOffset, 0)); - break; - - case 'z': - default: - axisInIJK.set(0, 0, 1); - firstDirection.set(1, 0, 0); - secondDirection.set(0, -1, 0); - firstSpacing = this.spacing[0]; - secondSpacing = this.spacing[1]; - IJKIndex = new Vector3(0, 0, RASIndex); - positionOffset = (volume.RASDimensions[2] - 1) / 2; - planeMatrix.setPosition(new Vector3(0, 0, RASIndex - positionOffset)); - break; - } - - firstDirection.applyMatrix4(volume.inverseMatrix).normalize(); - firstDirection.argVar = 'i'; - secondDirection.applyMatrix4(volume.inverseMatrix).normalize(); - secondDirection.argVar = 'j'; - axisInIJK.applyMatrix4(volume.inverseMatrix).normalize(); - iLength = Math.floor(Math.abs(firstDirection.dot(dimensions))); - jLength = Math.floor(Math.abs(secondDirection.dot(dimensions))); - planeWidth = Math.abs(iLength * firstSpacing); - planeHeight = Math.abs(jLength * secondSpacing); - IJKIndex = Math.abs(Math.round(IJKIndex.applyMatrix4(volume.inverseMatrix).dot(axisInIJK))); - var base = [new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1)]; - var iDirection = [firstDirection, secondDirection, axisInIJK].find(function (x) { - return Math.abs(x.dot(base[0])) > 0.9; - }); - var jDirection = [firstDirection, secondDirection, axisInIJK].find(function (x) { - return Math.abs(x.dot(base[1])) > 0.9; - }); - var kDirection = [firstDirection, secondDirection, axisInIJK].find(function (x) { - return Math.abs(x.dot(base[2])) > 0.9; - }); - - sliceAccess = function (i, j) { - var accessI, accessJ, accessK; - var si = iDirection === axisInIJK ? IJKIndex : iDirection.argVar === 'i' ? i : j; - var sj = jDirection === axisInIJK ? IJKIndex : jDirection.argVar === 'i' ? i : j; - var sk = kDirection === axisInIJK ? IJKIndex : kDirection.argVar === 'i' ? i : j; // invert indices if necessary - - var accessI = iDirection.dot(base[0]) > 0 ? si : volume.xLength - 1 - si; - var accessJ = jDirection.dot(base[1]) > 0 ? sj : volume.yLength - 1 - sj; - var accessK = kDirection.dot(base[2]) > 0 ? sk : volume.zLength - 1 - sk; - return volume.access(accessI, accessJ, accessK); - }; - - return { - iLength: iLength, - jLength: jLength, - sliceAccess: sliceAccess, - matrix: planeMatrix, - planeWidth: planeWidth, - planeHeight: planeHeight - }; - }, - - /** - * @member {Function} extractSlice Returns a slice corresponding to the given axis and index - * The coordinate are given in the Right Anterior Superior coordinate format - * @memberof Volume - * @param {string} axis the normal axis to the slice 'x' 'y' or 'z' - * @param {number} index the index of the slice - * @returns {VolumeSlice} the extracted slice - */ - extractSlice: function (axis, index) { - var slice = new VolumeSlice(this, index, axis); - this.sliceList.push(slice); - return slice; - }, - - /** - * @member {Function} repaintAllSlices Call repaint on all the slices extracted from this volume - * @see VolumeSlice.repaint - * @memberof Volume - * @returns {Volume} this - */ - repaintAllSlices: function () { - this.sliceList.forEach(function (slice) { - slice.repaint(); - }); - return this; - }, - - /** - * @member {Function} computeMinMax Compute the minimum and the maximum of the data in the volume - * @memberof Volume - * @returns {Array} [min,max] - */ - computeMinMax: function () { - var min = Infinity; - var max = -Infinity; // buffer the length - - var datasize = this.data.length; - var i = 0; - - for (i = 0; i < datasize; i++) { - if (!isNaN(this.data[i])) { - var value = this.data[i]; - min = Math.min(min, value); - max = Math.max(max, value); - } - } - - this.min = min; - this.max = max; - return [min, max]; - } -}; - -var CSS2DObject = function (element) { - Object3D.call(this); - this.element = element || document.createElement('div'); - this.element.style.position = 'absolute'; - this.addEventListener('removed', function () { - this.traverse(function (object) { - if (object.element instanceof Element && object.element.parentNode !== null) { - object.element.parentNode.removeChild(object.element); - } - }); - }); -}; - -CSS2DObject.prototype = Object.assign(Object.create(Object3D.prototype), { - constructor: CSS2DObject, - copy: function (source, recursive) { - Object3D.prototype.copy.call(this, source, recursive); - this.element = source.element.cloneNode(true); - return this; - } -}); // - -/** - * Based on http://www.emagix.net/academic/mscs-project/item/camera-sync-with-css3-and-webgl-threejs - */ - -var CSS3DObject = function (element) { - Object3D.call(this); - this.element = element || document.createElement('div'); - this.element.style.position = 'absolute'; - this.element.style.pointerEvents = 'auto'; - this.addEventListener('removed', function () { - this.traverse(function (object) { - if (object.element instanceof Element && object.element.parentNode !== null) { - object.element.parentNode.removeChild(object.element); - } - }); - }); -}; - -CSS3DObject.prototype = Object.assign(Object.create(Object3D.prototype), { - constructor: CSS3DObject, - copy: function (source, recursive) { - Object3D.prototype.copy.call(this, source, recursive); - this.element = source.element.cloneNode(true); - return this; - } -}); - -var CSS3DSprite = function (element) { - CSS3DObject.call(this, element); -}; - -CSS3DSprite.prototype = Object.create(CSS3DObject.prototype); -CSS3DSprite.prototype.constructor = CSS3DSprite; // - -var SVGObject = function (node) { - Object3D.call(this); - this.node = node; -}; - -SVGObject.prototype = Object.create(Object3D.prototype); -SVGObject.prototype.constructor = SVGObject; - -function _defineProperty$1(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -new Matrix4(); - -/** - * @param {Array} geometries - * @param {Boolean} useGroups - * @return {BufferGeometry} - */ -const mergeBufferGeometries = (geometries, useGroups) => { - const isIndexed = geometries[0].index !== null; - const attributesUsed = new Set(Object.keys(geometries[0].attributes)); - const morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes)); - const attributes = {}; - const morphAttributes = {}; - const morphTargetsRelative = geometries[0].morphTargetsRelative; - const mergedGeometry = new BufferGeometry(); - let offset = 0; - geometries.forEach((geom, i) => { - let attributesCount = 0; // ensure that all geometries are indexed, or none - - if (isIndexed !== (geom.index !== null)) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.'); - return null; - } // gather attributes, exit early if they're different - - - for (let name in geom.attributes) { - if (!attributesUsed.has(name)) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.'); - return null; - } - - if (attributes[name] === undefined) { - attributes[name] = []; - } - - attributes[name].push(geom.attributes[name]); - attributesCount++; - } // ensure geometries have the same number of attributes - - - if (attributesCount !== attributesUsed.size) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.'); - return null; - } // gather morph attributes, exit early if they're different - - - if (morphTargetsRelative !== geom.morphTargetsRelative) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.'); - return null; - } - - for (let name in geom.morphAttributes) { - if (!morphAttributesUsed.has(name)) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.'); - return null; - } - - if (morphAttributes[name] === undefined) morphAttributes[name] = []; - morphAttributes[name].push(geom.morphAttributes[name]); - } // gather .userData - - - mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || []; - mergedGeometry.userData.mergedUserData.push(geom.userData); - - if (useGroups) { - let count; - - if (geom.index) { - count = geom.index.count; - } else if (geom.attributes.position !== undefined) { - count = geom.attributes.position.count; - } else { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute'); - return null; - } - - mergedGeometry.addGroup(offset, count, i); - offset += count; - } - }); // merge indices - - if (isIndexed) { - let indexOffset = 0; - const mergedIndex = []; - geometries.forEach(geom => { - const index = geom.index; - - for (let j = 0; j < index.count; ++j) { - mergedIndex.push(index.getX(j) + indexOffset); - } - - indexOffset += geom.attributes.position.count; - }); - mergedGeometry.setIndex(mergedIndex); - } // merge attributes - - - for (let name in attributes) { - const mergedAttribute = mergeBufferAttributes(attributes[name]); - - if (!mergedAttribute) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.'); - return null; - } - - mergedGeometry.setAttribute(name, mergedAttribute); - } // merge morph attributes - - - for (let name in morphAttributes) { - const numMorphTargets = morphAttributes[name][0].length; - if (numMorphTargets === 0) break; - mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {}; - mergedGeometry.morphAttributes[name] = []; - - for (let i = 0; i < numMorphTargets; ++i) { - const morphAttributesToMerge = []; - - for (let j = 0; j < morphAttributes[name].length; ++j) { - morphAttributesToMerge.push(morphAttributes[name][j][i]); - } - - const mergedMorphAttribute = mergeBufferAttributes(morphAttributesToMerge); - - if (!mergedMorphAttribute) { - console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.'); - return null; - } - - mergedGeometry.morphAttributes[name].push(mergedMorphAttribute); - } - } - - return mergedGeometry; -}; -/** - * @param {Array} attributes - * @return {BufferAttribute} - */ - -const mergeBufferAttributes = attributes => { - let TypedArray = undefined; - let itemSize = undefined; - let normalized = undefined; - let arrayLength = 0; - attributes.forEach(attr => { - if (TypedArray === undefined) { - TypedArray = attr.array.constructor; - } - - if (TypedArray !== attr.array.constructor) { - console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.'); - return null; - } - - if (itemSize === undefined) itemSize = attr.itemSize; - - if (itemSize !== attr.itemSize) { - console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.'); - return null; - } - - if (normalized === undefined) normalized = attr.normalized; - - if (normalized !== attr.normalized) { - console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.'); - return null; - } - - arrayLength += attr.array.length; - }); - - if (TypedArray && itemSize) { - // @ts-expect-error this works in JS and TS is complaining but it's such a tiny thing I can live with the guilt - const array = new TypedArray(arrayLength); - let offset = 0; - attributes.forEach(attr => { - array.set(attr.array, offset); - offset += attr.array.length; - }); - return new BufferAttribute(array, itemSize, normalized); - } -}; - -new Vector3(); - new Vector3(); - -const NodeShaderStage = { - Vertex: 'vertex', - Fragment: 'fragment' -}; -const NodeUpdateType = { - None: 'none', - Frame: 'frame', - Object: 'object' -}; - -const getNodesKeys = object => { - const props = []; - - for (const name in object) { - const value = object[name]; - - if (value && value.isNode === true) { - props.push(name); - } - } - - return props; -}; -const getValueType = value => { - if (typeof value === 'number') { - return 'float'; - } else if (typeof value === 'boolean') { - return 'bool'; - } else if ((value === null || value === void 0 ? void 0 : value.isVector2) === true) { - return 'vec2'; - } else if ((value === null || value === void 0 ? void 0 : value.isVector3) === true) { - return 'vec3'; - } else if ((value === null || value === void 0 ? void 0 : value.isVector4) === true) { - return 'vec4'; - } else if ((value === null || value === void 0 ? void 0 : value.isMatrix3) === true) { - return 'mat3'; - } else if ((value === null || value === void 0 ? void 0 : value.isMatrix4) === true) { - return 'mat4'; - } else if ((value === null || value === void 0 ? void 0 : value.isColor) === true) { - return 'color'; - } - - return null; -}; -const getValueFromType = (type, ...params) => { - const last4 = type === null || type === void 0 ? void 0 : type.slice(-4); - - if (type === 'color') { - return new Color(...params); - } else if (last4 === 'vec2') { - return new Vector2(...params); - } else if (last4 === 'vec3') { - return new Vector3(...params); - } else if (last4 === 'vec4') { - return new Vector4(...params); - } else if (last4 === 'mat3') { - return new Matrix3(...params); - } else if (last4 === 'mat4') { - return new Matrix4(...params); - } else if (type === 'bool') { - return false; - } else if (type === 'float' || type === 'int' || type === 'uint') { - return 0; - } - - return null; -}; - -let _nodeId = 0; - -class Node { - constructor(nodeType = null) { - this.nodeType = nodeType; - this.updateType = NodeUpdateType.None; - this.uuid = MathUtils.generateUUID(); - Object.defineProperty(this, 'id', { - value: _nodeId++ - }); - } - - get type() { - return this.constructor.name; - } - - getHash() { - return this.uuid; - } - - getUpdateType() { - return this.updateType; - } - - getNodeType() { - return this.nodeType; - } - - update() { - console.warn('Abstract function.'); - } - - generate() { - console.warn('Abstract function.'); - } - - analyze(builder) { - const hash = this.getHash(builder); - const sharedNode = builder.getNodeFromHash(hash); - - if (sharedNode !== undefined && this !== sharedNode) { - return sharedNode.analyze(builder); - } - - const nodeData = builder.getDataFromNode(this); - nodeData.dependenciesCount = nodeData.dependenciesCount === undefined ? 1 : nodeData.dependenciesCount + 1; - const nodeKeys = getNodesKeys(this); - - for (const property of nodeKeys) { - this[property].analyze(builder); - } - } - - build(builder, output = null) { - const hash = this.getHash(builder); - const sharedNode = builder.getNodeFromHash(hash); - - if (sharedNode !== undefined && this !== sharedNode) { - return sharedNode.build(builder, output); - } - - builder.addNode(this); - builder.addStack(this); - const nodeData = builder.getDataFromNode(this); - const isGenerateOnce = this.generate.length === 1; - let snippet = null; - - if (isGenerateOnce) { - const type = this.getNodeType(builder); - snippet = nodeData.snippet; - - if (snippet === undefined) { - snippet = this.generate(builder) || ''; - nodeData.snippet = snippet; - } - - snippet = builder.format(snippet, type, output); - } else { - snippet = this.generate(builder, output) || ''; - } - - builder.removeStack(this); - return snippet; - } - - serialize(json) { - const nodeKeys = getNodesKeys(this); - - if (nodeKeys.length > 0) { - const inputNodes = {}; - - for (const property of nodeKeys) { - inputNodes[property] = this[property].toJSON(json.meta).uuid; - } - - json.inputNodes = inputNodes; - } - } - - deserialize(json) { - if (json.inputNodes !== undefined) { - const nodes = json.meta.nodes; - - for (const property in json.inputNodes) { - const uuid = json.inputNodes[property]; - this[property] = nodes[uuid]; - } - } - } - - toJSON(meta) { - const { - uuid, - type - } = this; - const isRoot = meta === undefined || typeof meta === 'string'; - - if (isRoot) { - meta = { - textures: {}, - images: {}, - nodes: {} - }; - } // serialize - - - let data = meta.nodes[uuid]; - - if (data === undefined) { - data = { - uuid, - type, - meta, - metadata: { - version: 4.5, - type: 'Node', - generator: 'Node.toJSON' - } - }; - meta.nodes[data.uuid] = data; - this.serialize(data); - delete data.meta; - } // TODO: Copied from Object3D.toJSON - - - function extractFromCache(cache) { - const values = []; - - for (const key in cache) { - const data = cache[key]; - delete data.metadata; - values.push(data); - } - - return values; - } - - if (isRoot) { - const textures = extractFromCache(meta.textures); - const images = extractFromCache(meta.images); - const nodes = extractFromCache(meta.nodes); - if (textures.length > 0) data.textures = textures; - if (images.length > 0) data.images = images; - if (nodes.length > 0) data.nodes = nodes; - } - - return data; - } - -} - -Node.prototype.isNode = true; - -class InputNode extends Node { - constructor(value, nodeType = null) { - super(nodeType); - this.value = value; - } - - getNodeType() { - if (this.nodeType === null) { - return getValueType(this.value); - } - - return this.nodeType; - } - - getInputType(builder) { - return this.getNodeType(builder); - } - - serialize(data) { - var _this$value, _this$value$toArray; - - super.serialize(data); - data.value = ((_this$value = this.value) === null || _this$value === void 0 ? void 0 : (_this$value$toArray = _this$value.toArray) === null || _this$value$toArray === void 0 ? void 0 : _this$value$toArray.call(_this$value)) || this.value; - data.valueType = getValueType(this.value); - data.nodeType = this.nodeType; - } - - deserialize(data) { - var _this$value2, _this$value2$fromArra; - - super.deserialize(data); - this.nodeType = data.nodeType; - this.value = getValueFromType(data.valueType); - this.value = ((_this$value2 = this.value) === null || _this$value2 === void 0 ? void 0 : (_this$value2$fromArra = _this$value2.fromArray) === null || _this$value2$fromArra === void 0 ? void 0 : _this$value2$fromArra.call(_this$value2, data.value)) || data.value; - } - - generate() { - console.warn('Abstract function.'); - } - -} - -InputNode.prototype.isInputNode = true; - -class UniformNode extends InputNode { - getUniformHash(builder) { - return this.getHash(builder); - } - - generate(builder, output) { - const type = this.getNodeType(builder); - const hash = this.getUniformHash(builder); - let sharedNode = builder.getNodeFromHash(hash); - - if (sharedNode === undefined) { - builder.setHashNode(this, hash); - sharedNode = this; - } - - const sharedNodeType = sharedNode.getInputType(builder); - const nodeUniform = builder.getUniformFromNode(sharedNode, builder.shaderStage, sharedNodeType); - const propertyName = builder.getPropertyName(nodeUniform); - return builder.format(propertyName, type, output); - } - -} - -UniformNode.prototype.isUniformNode = true; - -class ArrayUniformNode extends UniformNode { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - - getNodeType(builder) { - return this.nodes[0].getNodeType(builder); - } - -} - -ArrayUniformNode.prototype.isArrayUniformNode = true; - -class VaryNode extends Node { - constructor(node, name = null) { - super(); - this.node = node; - this.name = name; - } - - getHash(builder) { - return this.name || super.getHash(builder); - } - - getNodeType(builder) { - // VaryNode is auto type - return this.node.getNodeType(builder); - } - - generate(builder) { - const type = this.getNodeType(builder); - const node = this.node; - const name = this.name; - const nodeVary = builder.getVaryFromNode(this, type); - - if (name !== null) { - nodeVary.name = name; - } - - const propertyName = builder.getPropertyName(nodeVary, NodeShaderStage.Vertex); // force node run in vertex stage - - builder.flowNodeFromShaderStage(NodeShaderStage.Vertex, node, type, propertyName); - return builder.getPropertyName(nodeVary); - } - -} - -class AttributeNode extends Node { - constructor(attributeName, nodeType) { - super(nodeType); - this._attributeName = attributeName; - } - - getHash(builder) { - return this.getAttributeName(builder); - } - - setAttributeName(attributeName) { - this._attributeName = attributeName; - return this; - } - - getAttributeName() { - return this._attributeName; - } - - generate(builder) { - const attribute = builder.getAttribute(this.getAttributeName(builder), this.getNodeType(builder)); - - if (builder.isShaderStage('vertex')) { - return attribute.name; - } else { - const nodeVary = new VaryNode(this); - return nodeVary.build(builder, attribute.type); - } - } - -} - -class BypassNode extends Node { - constructor(returnNode, callNode) { - super(); - this.outputNode = returnNode; - this.callNode = callNode; - } - - getNodeType(builder) { - return this.outputNode.getNodeType(builder); - } - - generate(builder, output) { - const snippet = this.callNode.build(builder, 'void'); - - if (snippet !== '') { - builder.addFlowCode(snippet); - } - - return this.outputNode.build(builder, output); - } - -} - -BypassNode.prototype.isBypassNode = true; - -class CodeNode extends Node { - constructor(code = '', nodeType = 'code') { - super(nodeType); - this.code = code; - this._includes = []; - } - - setIncludes(includes) { - this._includes = includes; - return this; - } - - getIncludes() { - return this._includes; - } - - generate(builder) { - const includes = this.getIncludes(builder); - - for (const include of includes) { - include.build(builder); - } - - const nodeCode = builder.getCodeFromNode(this, this.getNodeType(builder)); - nodeCode.code = this.code; - return nodeCode.code; - } - -} - -CodeNode.prototype.isCodeNode = true; - -class ConstNode extends InputNode { - generateConst(builder) { - return builder.getConst(this.getNodeType(builder), this.value); - } - - generate(builder, output) { - const type = this.getNodeType(builder); - return builder.format(this.generateConst(builder), type, output); - } - -} - -ConstNode.prototype.isConstNode = true; - -class ContextNode extends Node { - constructor(node, context = {}) { - super(); - this.node = node; - this.context = context; - } - - getNodeType(builder) { - return this.node.getNodeType(builder); - } - - generate(builder, output) { - const previousContext = builder.getContext(); - builder.setContext(Object.assign({}, builder.context, this.context)); - const snippet = this.node.build(builder, output); - builder.setContext(previousContext); - return snippet; - } - -} - -ContextNode.prototype.isContextNode = true; - -class TempNode extends Node { - constructor(type) { - super(type); - } - - build(builder, output) { - const type = builder.getVectorType(this.getNodeType(builder, output)); - const nodeData = builder.getDataFromNode(this); - - if (builder.context.temp !== false && type !== 'void ' && output !== 'void' && nodeData.dependenciesCount > 1) { - if (nodeData.snippet === undefined) { - const snippet = super.build(builder, type); - const nodeVar = builder.getVarFromNode(this, type); - const propertyName = builder.getPropertyName(nodeVar); - builder.addFlowCode(`${propertyName} = ${snippet}`); - nodeData.snippet = snippet; - nodeData.propertyName = propertyName; - } - - return builder.format(nodeData.propertyName, type, output); - } - - return super.build(builder, output); - } - -} - -class ExpressionNode extends TempNode { - constructor(snipped = '', nodeType = 'void') { - super(nodeType); - this.snipped = snipped; - } - - generate(builder) { - const type = this.getNodeType(builder); - const snipped = this.snipped; - - if (type === 'void') { - builder.addFlowCode(snipped); - } else { - return `( ${snipped} )`; - } - } - -} - -const vector = ['x', 'y', 'z', 'w']; - -class PropertyNode extends Node { - constructor(name = null, nodeType = 'vec4') { - super(nodeType); - this.name = name; - } - - getHash(builder) { - return this.name || super.getHash(builder); - } - - generate(builder) { - const nodeVary = builder.getVarFromNode(this, this.getNodeType(builder)); - const name = this.name; - - if (name !== null) { - nodeVary.name = name; - } - - return builder.getPropertyName(nodeVary); - } - -} - -class VarNode extends Node { - constructor(node, name = null, nodeType = null) { - super(nodeType); - this.node = node; - this.name = name; - } - - getHash(builder) { - return this.name || super.getHash(builder); - } - - getNodeType(builder) { - return super.getNodeType(builder) || this.node.getNodeType(builder); - } - - generate(builder) { - const type = builder.getVectorType(this.getNodeType(builder)); - const node = this.node; - const name = this.name; - const snippet = node.build(builder, type); - const nodeVar = builder.getVarFromNode(this, type); - - if (name !== null) { - nodeVar.name = name; - } - - const propertyName = builder.getPropertyName(nodeVar); - builder.addFlowCode(`${propertyName} = ${snippet}`); - return propertyName; - } - -} - -VarNode.prototype.isVarNode = true; - -class BufferNode extends UniformNode { - constructor(value, bufferType, bufferCount = 0) { - super(value, bufferType); - this.bufferType = bufferType; - this.bufferCount = bufferCount; - } - - getInputType() { - return 'buffer'; - } - -} - -BufferNode.prototype.isBufferNode = true; - -class Object3DNode extends Node { - constructor(scope = Object3DNode.VIEW_MATRIX, object3d = null) { - super(); - this.scope = scope; - this.object3d = object3d; - this.updateType = NodeUpdateType.Object; - this._uniformNode = new UniformNode(null); - } - - getNodeType() { - const scope = this.scope; - - if (scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX) { - return 'mat4'; - } else if (scope === Object3DNode.NORMAL_MATRIX) { - return 'mat3'; - } else if (scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION) { - return 'vec3'; - } - } - - update(frame) { - const object = this.object3d !== null ? this.object3d : frame.object; - const uniformNode = this._uniformNode; - const camera = frame.camera; - const scope = this.scope; - - if (scope === Object3DNode.VIEW_MATRIX) { - uniformNode.value = object.modelViewMatrix; - } else if (scope === Object3DNode.NORMAL_MATRIX) { - uniformNode.value = object.normalMatrix; - } else if (scope === Object3DNode.WORLD_MATRIX) { - uniformNode.value = object.matrixWorld; - } else if (scope === Object3DNode.POSITION) { - uniformNode.value.setFromMatrixPosition(object.matrixWorld); - } else if (scope === Object3DNode.VIEW_POSITION) { - uniformNode.value.setFromMatrixPosition(object.matrixWorld); - uniformNode.value.applyMatrix4(camera.matrixWorldInverse); - } - } - - generate(builder) { - const scope = this.scope; - - if (scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX) { - this._uniformNode.nodeType = 'mat4'; - } else if (scope === Object3DNode.NORMAL_MATRIX) { - this._uniformNode.nodeType = 'mat3'; - } else if (scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION) { - this._uniformNode.nodeType = 'vec3'; - this._uniformNode.value = new Vector3(); - } - - return this._uniformNode.build(builder); - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - } - -} - -_defineProperty$1(Object3DNode, "VIEW_MATRIX", 'viewMatrix'); - -_defineProperty$1(Object3DNode, "NORMAL_MATRIX", 'normalMatrix'); - -_defineProperty$1(Object3DNode, "WORLD_MATRIX", 'worldMatrix'); - -_defineProperty$1(Object3DNode, "POSITION", 'position'); - -_defineProperty$1(Object3DNode, "VIEW_POSITION", 'viewPosition'); - -class CameraNode extends Object3DNode { - constructor(scope = CameraNode.POSITION) { - super(scope); - } - - getNodeType(builder) { - const scope = this.scope; - - if (scope === CameraNode.PROJECTION_MATRIX) { - return 'mat4'; - } - - return super.getNodeType(builder); - } - - update(frame) { - const camera = frame.camera; - const uniformNode = this._uniformNode; - const scope = this.scope; - - if (scope === CameraNode.PROJECTION_MATRIX) { - uniformNode.value = camera.projectionMatrix; - } else if (scope === CameraNode.VIEW_MATRIX) { - uniformNode.value = camera.matrixWorldInverse; - } else { - this.object3d = camera; - super.update(frame); - } - } - - generate(builder) { - const scope = this.scope; - - if (scope === CameraNode.PROJECTION_MATRIX) { - this._uniformNode.nodeType = 'mat4'; - } - - return super.generate(builder); - } - -} - -_defineProperty$1(CameraNode, "PROJECTION_MATRIX", 'projectionMatrix'); - -class UVNode extends AttributeNode { - constructor(index = 0) { - super(null, 'vec2'); - this.index = index; - } - - getAttributeName() { - const index = this.index; - return 'uv' + (index > 0 ? index + 1 : ''); - } - - serialize(data) { - super.serialize(data); - data.index = this.index; - } - - deserialize(data) { - super.deserialize(data); - this.index = data.index; - } - -} - -UVNode.prototype.isUVNode = true; - -class TextureNode extends UniformNode { - constructor(value, uvNode = new UVNode(), biasNode = null) { - super(value, 'vec4'); - this.uvNode = uvNode; - this.biasNode = biasNode; - } - - getUniformHash() { - return this.value.uuid; - } - - getInputType() { - return 'texture'; - } - - generate(builder, output) { - const texture = this.value; - - if (!texture || texture.isTexture !== true) { - throw new Error('TextureNode: Need a three.js texture.'); - } - - const textureProperty = super.generate(builder, 'texture'); - - if (output === 'sampler') { - return textureProperty + '_sampler'; - } else if (builder.isReference(output)) { - return textureProperty; - } else { - const nodeData = builder.getDataFromNode(this); - let snippet = nodeData.snippet; - - if (snippet === undefined) { - const uvSnippet = this.uvNode.build(builder, 'vec2'); - const biasNode = this.biasNode; - - if (biasNode !== null) { - const biasSnippet = biasNode.build(builder, 'float'); - snippet = builder.getTextureBias(textureProperty, uvSnippet, biasSnippet); - } else { - snippet = builder.getTexture(textureProperty, uvSnippet); - } - - nodeData.snippet = snippet; - } - - return builder.format(snippet, 'vec4', output); - } - } - - serialize(data) { - super.serialize(data); - data.value = this.value.toJSON(data.meta).uuid; - } - - deserialize(data) { - super.deserialize(data); - this.value = data.meta.textures[data.value]; - } - -} - -TextureNode.prototype.isTextureNode = true; - -class ModelNode extends Object3DNode { - constructor(scope = ModelNode.VIEW_MATRIX) { - super(scope); - } - -} - -class JoinNode extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - - getNodeType(builder) { - return builder.getTypeFromLength(this.nodes.reduce((count, cur) => count + builder.getTypeLength(cur.getNodeType(builder)), 0)); - } - - generate(builder) { - const type = this.getNodeType(builder); - const nodes = this.nodes; - const snippetValues = []; - - for (let i = 0; i < nodes.length; i++) { - const input = nodes[i]; - const inputSnippet = input.build(builder); - snippetValues.push(inputSnippet); - } - - return `${builder.getType(type)}( ${snippetValues.join(', ')} )`; - } - -} - -class SplitNode extends Node { - constructor(node, components = 'x') { - super(); - this.node = node; - this.components = components; - } - - getVectorLength() { - let vectorLength = this.components.length; - - for (const c of this.components) { - vectorLength = Math.max(vector.indexOf(c) + 1, vectorLength); - } - - return vectorLength; - } - - getNodeType(builder) { - return builder.getTypeFromLength(this.components.length); - } - - generate(builder) { - const node = this.node; - const nodeTypeLength = builder.getTypeLength(node.getNodeType(builder)); - - if (nodeTypeLength > 1) { - let type = null; - const componentsLength = this.getVectorLength(); - - if (componentsLength >= nodeTypeLength) { - // need expand the input node - type = builder.getTypeFromLength(this.getVectorLength()); - } - - const nodeSnippet = node.build(builder, type); - return `${nodeSnippet}.${this.components}`; - } else { - // ignore components if node is a float - return node.build(builder); - } - } - - serialize(data) { - super.serialize(data); - data.components = this.components; - } - - deserialize(data) { - super.deserialize(data); - this.components = data.components; - } - -} - -class OperatorNode extends TempNode { - constructor(op, aNode, bNode, ...params) { - super(); - this.op = op; - - if (params.length > 0) { - let finalBNode = bNode; - - for (let i = 0; i < params.length; i++) { - finalBNode = new OperatorNode(op, finalBNode, params[i]); - } - - bNode = finalBNode; - } - - this.aNode = aNode; - this.bNode = bNode; - } - - getNodeType(builder, output) { - const op = this.op; - const aNode = this.aNode; - const bNode = this.bNode; - const typeA = aNode.getNodeType(builder); - const typeB = bNode.getNodeType(builder); - - if (typeA === 'void' || typeB === 'void') { - return 'void'; - } else if (op === '=' || op === '%') { - return typeA; - } else if (op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<') { - return 'int'; - } else if (op === '==' || op === '&&' || op === '||' || op === '^^') { - return 'bool'; - } else if (op === '<' || op === '>' || op === '<=' || op === '>=') { - const typeLength = builder.getTypeLength(output); - return typeLength > 1 ? `bvec${typeLength}` : 'bool'; - } else { - if (typeA === 'float' && builder.isMatrix(typeB)) { - return typeB; - } else if (builder.isMatrix(typeA) && builder.isVector(typeB)) { - // matrix x vector - return builder.getVectorFromMatrix(typeA); - } else if (builder.isVector(typeA) && builder.isMatrix(typeB)) { - // vector x matrix - return builder.getVectorFromMatrix(typeB); - } else if (builder.getTypeLength(typeB) > builder.getTypeLength(typeA)) { - // anytype x anytype: use the greater length vector - return typeB; - } - - return typeA; - } - } - - generate(builder, output) { - const op = this.op; - const aNode = this.aNode; - const bNode = this.bNode; - const type = this.getNodeType(builder, output); - let typeA = null; - let typeB = null; - - if (type !== 'void') { - typeA = aNode.getNodeType(builder); - typeB = bNode.getNodeType(builder); - - if (op === '=') { - typeB = typeA; - } else if (op === '<' || op === '>' || op === '<=' || op === '>=') { - if (builder.isVector(typeA)) { - typeB = typeA; - } else { - typeA = typeB = 'float'; - } - } else if (builder.isMatrix(typeA) && builder.isVector(typeB)) { - // matrix x vector - typeB = builder.getVectorFromMatrix(typeA); - } else if (builder.isVector(typeA) && builder.isMatrix(typeB)) { - // vector x matrix - typeA = builder.getVectorFromMatrix(typeB); - } else { - // anytype x anytype - typeA = typeB = type; - } - } else { - typeA = typeB = type; - } - - const a = aNode.build(builder, typeA); - const b = bNode.build(builder, typeB); - const outputLength = builder.getTypeLength(output); - - if (output !== 'void') { - if (op === '=') { - builder.addFlowCode(`${a} ${this.op} ${b}`); - return a; - } else if (op === '>' && outputLength > 1) { - return builder.format(`${builder.getMethod('greaterThan')}( ${a}, ${b} )`, type, output); - } else if (op === '<=' && outputLength > 1) { - return builder.format(`${builder.getMethod('lessThanEqual')}( ${a}, ${b} )`, type, output); - } else { - return builder.format(`( ${a} ${this.op} ${b} )`, type, output); - } - } else if (typeA !== 'void') { - return builder.format(`${a} ${this.op} ${b}`, type, output); - } - } - - serialize(data) { - super.serialize(data); - data.op = this.op; - } - - deserialize(data) { - super.deserialize(data); - this.op = data.op; - } - -} - -class MathNode extends TempNode { - // 1 input - // 2 inputs - // 3 inputs - constructor(method, aNode, bNode = null, cNode = null) { - super(); - this.method = method; - this.aNode = aNode; - this.bNode = bNode; - this.cNode = cNode; - } - - getInputType(builder) { - const aType = this.aNode.getNodeType(builder); - const bType = this.bNode ? this.bNode.getNodeType(builder) : null; - const cType = this.cNode ? this.cNode.getNodeType(builder) : null; - const aLen = builder.getTypeLength(aType); - const bLen = builder.getTypeLength(bType); - const cLen = builder.getTypeLength(cType); - - if (aLen > bLen && aLen > cLen) { - return aType; - } else if (bLen > cLen) { - return bType; - } else if (cLen > aLen) { - return cType; - } - - return aType; - } - - getNodeType(builder) { - const method = this.method; - - if (method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT) { - return 'float'; - } else if (method === MathNode.CROSS) { - return 'vec3'; - } else { - return this.getInputType(builder); - } - } - - generate(builder, output) { - const method = this.method; - const type = this.getNodeType(builder); - const inputType = this.getInputType(builder); - const a = this.aNode; - const b = this.bNode; - const c = this.cNode; - const isWebGL = builder.renderer.isWebGLRenderer === true; - - if (isWebGL && (method === MathNode.DFDX || method === MathNode.DFDY) && output === 'vec3') { - // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988 - return new JoinNode([new MathNode(method, new SplitNode(a, 'x')), new MathNode(method, new SplitNode(a, 'y')), new MathNode(method, new SplitNode(a, 'z'))]).build(builder); - } else if (method === MathNode.TRANSFORM_DIRECTION) { - // dir can be either a direction vector or a normal vector - // upper-left 3x3 of matrix is assumed to be orthogonal - let tA = a; - let tB = b; - - if (builder.isMatrix(tA.getNodeType(builder))) { - tB = new ExpressionNode(`${builder.getType('vec4')}( ${tB.build(builder, 'vec3')}, 0.0 )`, 'vec4'); - } else { - tA = new ExpressionNode(`${builder.getType('vec4')}( ${tA.build(builder, 'vec3')}, 0.0 )`, 'vec4'); - } - - const mulNode = new SplitNode(new OperatorNode('*', tA, tB), 'xyz'); - return new MathNode(MathNode.NORMALIZE, mulNode).build(builder); - } else if (method === MathNode.SATURATE) { - return builder.format(`clamp( ${a.build(builder, inputType)}, 0.0, 1.0 )`, type, output); - } else if (method === MathNode.NEGATE) { - return builder.format('( -' + a.build(builder, inputType) + ' )', type, output); - } else if (method === MathNode.INVERT) { - return builder.format('( 1.0 - ' + a.build(builder, inputType) + ' )', type, output); - } else { - const params = []; - - if (method === MathNode.CROSS) { - params.push(a.build(builder, type), b.build(builder, type)); - } else if (method === MathNode.STEP) { - params.push(a.build(builder, builder.getTypeLength(a.getNodeType(builder)) === 1 ? 'float' : inputType), b.build(builder, inputType)); - } else if (isWebGL && (method === MathNode.MIN || method === MathNode.MAX) || method === MathNode.MOD) { - params.push(a.build(builder, inputType), b.build(builder, builder.getTypeLength(b.getNodeType(builder)) === 1 ? 'float' : inputType)); - } else if (method === MathNode.REFRACT) { - params.push(a.build(builder, inputType), b.build(builder, inputType), c.build(builder, 'float')); - } else if (method === MathNode.MIX) { - params.push(a.build(builder, inputType), b.build(builder, inputType), c.build(builder, builder.getTypeLength(c.getNodeType(builder)) === 1 ? 'float' : inputType)); - } else { - params.push(a.build(builder, inputType)); - - if (c !== null) { - params.push(b.build(builder, inputType), c.build(builder, inputType)); - } else if (b !== null) { - params.push(b.build(builder, inputType)); - } - } - - return builder.format(`${builder.getMethod(method)}( ${params.join(', ')} )`, type, output); - } - } - - serialize(data) { - super.serialize(data); - data.method = this.method; - } - - deserialize(data) { - super.deserialize(data); - this.method = data.method; - } - -} - -_defineProperty$1(MathNode, "RAD", 'radians'); - -_defineProperty$1(MathNode, "DEG", 'degrees'); - -_defineProperty$1(MathNode, "EXP", 'exp'); - -_defineProperty$1(MathNode, "EXP2", 'exp2'); - -_defineProperty$1(MathNode, "LOG", 'log'); - -_defineProperty$1(MathNode, "LOG2", 'log2'); - -_defineProperty$1(MathNode, "SQRT", 'sqrt'); - -_defineProperty$1(MathNode, "INV_SQRT", 'inversesqrt'); - -_defineProperty$1(MathNode, "FLOOR", 'floor'); - -_defineProperty$1(MathNode, "CEIL", 'ceil'); - -_defineProperty$1(MathNode, "NORMALIZE", 'normalize'); - -_defineProperty$1(MathNode, "FRACT", 'fract'); - -_defineProperty$1(MathNode, "SIN", 'sin'); - -_defineProperty$1(MathNode, "COS", 'cos'); - -_defineProperty$1(MathNode, "TAN", 'tan'); - -_defineProperty$1(MathNode, "ASIN", 'asin'); - -_defineProperty$1(MathNode, "ACOS", 'acos'); - -_defineProperty$1(MathNode, "ATAN", 'atan'); - -_defineProperty$1(MathNode, "ABS", 'abs'); - -_defineProperty$1(MathNode, "SIGN", 'sign'); - -_defineProperty$1(MathNode, "LENGTH", 'length'); - -_defineProperty$1(MathNode, "NEGATE", 'negate'); - -_defineProperty$1(MathNode, "INVERT", 'invert'); - -_defineProperty$1(MathNode, "DFDX", 'dFdx'); - -_defineProperty$1(MathNode, "DFDY", 'dFdy'); - -_defineProperty$1(MathNode, "SATURATE", 'saturate'); - -_defineProperty$1(MathNode, "ROUND", 'round'); - -_defineProperty$1(MathNode, "MIN", 'min'); - -_defineProperty$1(MathNode, "MAX", 'max'); - -_defineProperty$1(MathNode, "MOD", 'mod'); - -_defineProperty$1(MathNode, "STEP", 'step'); - -_defineProperty$1(MathNode, "REFLECT", 'reflect'); - -_defineProperty$1(MathNode, "DISTANCE", 'distance'); - -_defineProperty$1(MathNode, "DOT", 'dot'); - -_defineProperty$1(MathNode, "CROSS", 'cross'); - -_defineProperty$1(MathNode, "POW", 'pow'); - -_defineProperty$1(MathNode, "TRANSFORM_DIRECTION", 'transformDirection'); - -_defineProperty$1(MathNode, "MIX", 'mix'); - -_defineProperty$1(MathNode, "CLAMP", 'clamp'); - -_defineProperty$1(MathNode, "REFRACT", 'refract'); - -_defineProperty$1(MathNode, "SMOOTHSTEP", 'smoothstep'); - -_defineProperty$1(MathNode, "FACEFORWARD", 'faceforward'); - -class PositionNode extends Node { - constructor(scope = PositionNode.LOCAL) { - super('vec3'); - this.scope = scope; - } - - getHash() { - return `position-${this.scope}`; - } - - generate(builder) { - const scope = this.scope; - let outputNode = null; - - if (scope === PositionNode.GEOMETRY) { - outputNode = new AttributeNode('position', 'vec3'); - } else if (scope === PositionNode.LOCAL) { - outputNode = new VaryNode(new PositionNode(PositionNode.GEOMETRY)); - } else if (scope === PositionNode.WORLD) { - const vertexPositionNode = new MathNode(MathNode.TRANSFORM_DIRECTION, new ModelNode(ModelNode.WORLD_MATRIX), new PositionNode(PositionNode.LOCAL)); - outputNode = new VaryNode(vertexPositionNode); - } else if (scope === PositionNode.VIEW) { - const vertexPositionNode = new OperatorNode('*', new ModelNode(ModelNode.VIEW_MATRIX), new PositionNode(PositionNode.LOCAL)); - outputNode = new VaryNode(vertexPositionNode); - } else if (scope === PositionNode.VIEW_DIRECTION) { - const vertexPositionNode = new MathNode(MathNode.NEGATE, new PositionNode(PositionNode.VIEW)); - outputNode = new MathNode(MathNode.NORMALIZE, new VaryNode(vertexPositionNode)); - } - - return outputNode.build(builder, this.getNodeType(builder)); - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - } - -} - -_defineProperty$1(PositionNode, "GEOMETRY", 'geometry'); - -_defineProperty$1(PositionNode, "LOCAL", 'local'); - -_defineProperty$1(PositionNode, "WORLD", 'world'); - -_defineProperty$1(PositionNode, "VIEW", 'view'); - -_defineProperty$1(PositionNode, "VIEW_DIRECTION", 'viewDirection'); - -class NormalNode extends Node { - constructor(scope = NormalNode.LOCAL) { - super('vec3'); - this.scope = scope; - } - - getHash() { - return `normal-${this.scope}`; - } - - generate(builder) { - const scope = this.scope; - let outputNode = null; - - if (scope === NormalNode.GEOMETRY) { - outputNode = new AttributeNode('normal', 'vec3'); - } else if (scope === NormalNode.LOCAL) { - outputNode = new VaryNode(new NormalNode(NormalNode.GEOMETRY)); - } else if (scope === NormalNode.VIEW) { - const vertexNormalNode = new OperatorNode('*', new ModelNode(ModelNode.NORMAL_MATRIX), new NormalNode(NormalNode.LOCAL)); - outputNode = new MathNode(MathNode.NORMALIZE, new VaryNode(vertexNormalNode)); - } else if (scope === NormalNode.WORLD) { - // To use INVERSE_TRANSFORM_DIRECTION only inverse the param order like this: MathNode( ..., Vector, Matrix ); - const vertexNormalNode = new MathNode(MathNode.TRANSFORM_DIRECTION, new NormalNode(NormalNode.VIEW), new CameraNode(CameraNode.VIEW_MATRIX)); - outputNode = new MathNode(MathNode.NORMALIZE, new VaryNode(vertexNormalNode)); - } - - return outputNode.build(builder); - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - } - -} - -_defineProperty$1(NormalNode, "GEOMETRY", 'geometry'); - -_defineProperty$1(NormalNode, "LOCAL", 'local'); - -_defineProperty$1(NormalNode, "WORLD", 'world'); - -_defineProperty$1(NormalNode, "VIEW", 'view'); - -class CondNode extends Node { - constructor(node, ifNode, elseNode) { - super(); - this.node = node; - this.ifNode = ifNode; - this.elseNode = elseNode; - } - - getNodeType(builder) { - const ifType = this.ifNode.getNodeType(builder); - const elseType = this.elseNode.getNodeType(builder); - - if (builder.getTypeLength(elseType) > builder.getTypeLength(ifType)) { - return elseType; - } - - return ifType; - } - - generate(builder) { - const type = this.getNodeType(builder); - const context = { - temp: false - }; - const nodeProperty = new PropertyNode(null, type).build(builder); - const nodeSnippet = new ContextNode(this.node - /*, context*/ - ).build(builder, 'bool'), - ifSnippet = new ContextNode(this.ifNode, context).build(builder, type), - elseSnippet = new ContextNode(this.elseNode, context).build(builder, type); - builder.addFlowCode(`if ( ${nodeSnippet} ) { - -\t\t${nodeProperty} = ${ifSnippet}; - -\t} else { - -\t\t${nodeProperty} = ${elseSnippet}; - -\t}`); - return nodeProperty; - } - -} - -class ArrayElementNode extends Node { - constructor(node, indexNode) { - super(); - this.node = node; - this.indexNode = indexNode; - } - - getNodeType(builder) { - return this.node.getNodeType(builder); - } - - generate(builder) { - const nodeSnippet = this.node.build(builder); - const indexSnippet = this.indexNode.build(builder, 'int'); - return `${nodeSnippet}[ ${indexSnippet} ]`; - } - -} - -class ConvertNode extends Node { - constructor(node, convertTo) { - super(); - this.node = node; - this.convertTo = convertTo; - } - - getNodeType() { - return this.convertTo; - } - - generate(builder) { - const convertTo = this.convertTo; - const node = this.node; - - if (builder.isReference(convertTo) === false) { - const convertToSnippet = builder.getType(convertTo); - const nodeSnippet = node.build(builder, convertTo); - return `${builder.getVectorType(convertToSnippet)}( ${nodeSnippet} )`; - } else { - return node.build(builder, convertTo); - } - } - -} - -// core nodes -const NodeHandler = { - construct(NodeClosure, params) { - const inputs = params.shift(); - return NodeClosure(new ShaderNodeObjects(inputs), ...params); - }, - - get: function (node, prop) { - if (typeof prop === 'string' && node[prop] === undefined) { - if (/^[xyzwrgbastpq]{1,4}$/.test(prop) === true) { - // accessing properties ( swizzle ) - prop = prop.replace(/r|s/g, 'x').replace(/g|t/g, 'y').replace(/b|p/g, 'z').replace(/a|q/g, 'w'); - return new ShaderNodeObject(new SplitNode(node, prop)); - } else if (/^\d+$/.test(prop) === true) { - // accessing array - return new ShaderNodeObject(new ArrayElementNode(node, uint(Number(prop)))); - } - } - - return node[prop]; - } -}; -const nodeObjects = new WeakMap(); - -const ShaderNodeObject = function (obj) { - const type = typeof obj; - - if (type === 'number' || type === 'boolean') { - return new ShaderNodeObject(getAutoTypedConstNode(obj)); - } else if (type === 'object') { - if (obj.isNode === true) { - let nodeObject = nodeObjects.get(obj); - - if (nodeObject === undefined) { - nodeObject = new Proxy(obj, NodeHandler); - nodeObjects.set(obj, nodeObject); - nodeObjects.set(nodeObject, nodeObject); - } - - return nodeObject; - } - } - - return obj; -}; - -const ShaderNodeObjects = function (objects) { - for (const name in objects) { - objects[name] = new ShaderNodeObject(objects[name]); - } - - return objects; -}; - -const getShaderNodeArray = array => { - const len = array.length; - - for (let i = 0; i < len; i++) { - array[i] = new ShaderNodeObject(array[i]); - } - - return array; -}; - -const ShaderNodeProxy = function (NodeClass, scope = null, factor = null) { - if (scope === null) { - return (...params) => { - return new ShaderNodeObject(new NodeClass(...getShaderNodeArray(params))); - }; - } else if (factor === null) { - return (...params) => { - return new ShaderNodeObject(new NodeClass(scope, ...getShaderNodeArray(params))); - }; - } else { - factor = new ShaderNodeObject(factor); - return (...params) => { - return new ShaderNodeObject(new NodeClass(scope, ...getShaderNodeArray(params), factor)); - }; - } -}; - -const ShaderNodeScript = function (jsFunc) { - return (inputs, builder) => { - new ShaderNodeObjects(inputs); - return new ShaderNodeObject(jsFunc(inputs, builder)); - }; -}; - -const bools = [false, true]; -const uints = [0, 1, 2, 3]; -const ints = [-1, -2]; -const floats = [0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / (Math.PI * 2), Math.PI / 2]; -const boolsCacheMap = new Map(); - -for (let bool of bools) boolsCacheMap.set(bool, new ConstNode(bool)); - -const uintsCacheMap = new Map(); - -for (let uint of uints) uintsCacheMap.set(uint, new ConstNode(uint, 'uint')); - -const intsCacheMap = new Map([...uintsCacheMap].map(el => new ConstNode(el.value, 'int'))); - -for (let int of ints) intsCacheMap.set(int, new ConstNode(int, 'int')); - -const floatsCacheMap = new Map([...intsCacheMap].map(el => new ConstNode(el.value))); - -for (let float of floats) floatsCacheMap.set(float, new ConstNode(float)); - -for (let float of floats) floatsCacheMap.set(-float, new ConstNode(-float)); - -const constNodesCacheMap = new Map([...boolsCacheMap, ...floatsCacheMap]); - -const getAutoTypedConstNode = value => { - if (constNodesCacheMap.has(value)) { - return constNodesCacheMap.get(value); - } else if (value.isNode === true) { - return value; - } else { - return new ConstNode(value); - } -}; - -const ConvertType = function (type, cacheMap = null) { - return (...params) => { - if (params.length === 0) { - return nodeObject(new ConstNode(getValueFromType(type), type)); - } else { - if (type === 'color' && params[0].isNode !== true) { - params = [getValueFromType(type, ...params)]; - } - - if (params.length === 1 && cacheMap !== null && cacheMap.has(params[0])) { - return cacheMap.get(params[0]); - } - - const nodes = params.map(getAutoTypedConstNode); - return nodeObject(new ConvertNode(nodes.length === 1 ? nodes[0] : new JoinNode(nodes), type)); - } - }; -}; // -// Node Material Shader Syntax -// - - -const ShaderNode = new Proxy(ShaderNodeScript, NodeHandler); -const nodeObject = val => { - return new ShaderNodeObject(val); -}; -const float = new ConvertType('float', floatsCacheMap); -const uint = new ConvertType('uint', uintsCacheMap); -const vec3 = new ConvertType('vec3'); -const join = (...params) => nodeObject(new JoinNode(getShaderNodeArray(params))); -const cond = (...params) => nodeObject(new CondNode(...getShaderNodeArray(params))); -const addTo = (varNode, ...params) => { - varNode.node = add(varNode.node, ...getShaderNodeArray(params)); - return nodeObject(varNode); -}; -const add = new ShaderNodeProxy(OperatorNode, '+'); -const sub = new ShaderNodeProxy(OperatorNode, '-'); -const mul = new ShaderNodeProxy(OperatorNode, '*'); -const div = new ShaderNodeProxy(OperatorNode, '/'); -new ShaderNodeProxy(OperatorNode, '%'); -const equal = new ShaderNodeProxy(OperatorNode, '=='); -const assign$3 = new ShaderNodeProxy(OperatorNode, '='); -new ShaderNodeProxy(OperatorNode, '<'); -const greaterThan = new ShaderNodeProxy(OperatorNode, '>'); -const lessThanEqual = new ShaderNodeProxy(OperatorNode, '<='); -new ShaderNodeProxy(OperatorNode, '>='); -const and = new ShaderNodeProxy(OperatorNode, '&&'); -new ShaderNodeProxy(OperatorNode, '||'); -new ShaderNodeProxy(OperatorNode, '^^'); -new ShaderNodeProxy(OperatorNode, '&'); -new ShaderNodeProxy(OperatorNode, '|'); -new ShaderNodeProxy(OperatorNode, '^'); -new ShaderNodeProxy(OperatorNode, '<<'); -new ShaderNodeProxy(OperatorNode, '>>'); -const element = new ShaderNodeProxy(ArrayElementNode); -new ShaderNodeObject(new NormalNode(NormalNode.GEOMETRY)); -const normalLocal = new ShaderNodeObject(new NormalNode(NormalNode.LOCAL)); -const normalWorld = new ShaderNodeObject(new NormalNode(NormalNode.WORLD)); -new ShaderNodeObject(new NormalNode(NormalNode.VIEW)); -const transformedNormalView = new ShaderNodeObject(new VarNode(new NormalNode(NormalNode.VIEW), 'TransformedNormalView', 'vec3')); -const positionLocal = new ShaderNodeObject(new PositionNode(PositionNode.LOCAL)); -const positionWorld = new ShaderNodeObject(new PositionNode(PositionNode.WORLD)); -const positionView = new ShaderNodeObject(new PositionNode(PositionNode.VIEW)); -const positionViewDirection = new ShaderNodeObject(new PositionNode(PositionNode.VIEW_DIRECTION)); -new ShaderNodeObject(new ModelNode(ModelNode.VIEW_MATRIX)); -const cameraPosition = new ShaderNodeObject(new CameraNode(CameraNode.POSITION)); -const diffuseColor = new ShaderNodeObject(new PropertyNode('DiffuseColor', 'vec4')); -const roughness = new ShaderNodeObject(new PropertyNode('Roughness', 'float')); -new ShaderNodeObject(new PropertyNode('Metalness', 'float')); -new ShaderNodeObject(new PropertyNode('AlphaTest', 'float')); -const specularColor = new ShaderNodeObject(new PropertyNode('SpecularColor', 'color')); -const abs = new ShaderNodeProxy(MathNode, 'abs'); -new ShaderNodeProxy(MathNode, 'acos'); -new ShaderNodeProxy(MathNode, 'asin'); -new ShaderNodeProxy(MathNode, 'atan'); -new ShaderNodeProxy(MathNode, 'ceil'); -new ShaderNodeProxy(MathNode, 'clamp'); -new ShaderNodeProxy(MathNode, 'cos'); -const cross = new ShaderNodeProxy(MathNode, 'cross'); -new ShaderNodeProxy(MathNode, 'degrees'); -const dFdx = new ShaderNodeProxy(MathNode, 'dFdx'); -const dFdy = new ShaderNodeProxy(MathNode, 'dFdy'); -new ShaderNodeProxy(MathNode, 'distance'); -const dot = new ShaderNodeProxy(MathNode, 'dot'); -new ShaderNodeProxy(MathNode, 'exp'); -const exp2 = new ShaderNodeProxy(MathNode, 'exp2'); -new ShaderNodeProxy(MathNode, 'faceforward'); -const floor = new ShaderNodeProxy(MathNode, 'floor'); -const fract = new ShaderNodeProxy(MathNode, 'fract'); -new ShaderNodeProxy(MathNode, 'invert'); -const inversesqrt = new ShaderNodeProxy(MathNode, 'inversesqrt'); -new ShaderNodeProxy(MathNode, 'length'); -new ShaderNodeProxy(MathNode, 'log'); -new ShaderNodeProxy(MathNode, 'log2'); -const max = new ShaderNodeProxy(MathNode, 'max'); -new ShaderNodeProxy(MathNode, 'min'); -const mix = new ShaderNodeProxy(MathNode, 'mix'); -const mod$1 = new ShaderNodeProxy(MathNode, 'mod'); -const negate$2 = new ShaderNodeProxy(MathNode, 'negate'); -const normalize = new ShaderNodeProxy(MathNode, 'normalize'); -const pow = new ShaderNodeProxy(MathNode, 'pow'); -const pow2 = new ShaderNodeProxy(MathNode, 'pow', 2); -new ShaderNodeProxy(MathNode, 'pow', 3); -new ShaderNodeProxy(MathNode, 'pow', 4); -new ShaderNodeProxy(MathNode, 'radians'); -const reflect = new ShaderNodeProxy(MathNode, 'reflect'); -new ShaderNodeProxy(MathNode, 'refract'); -const round = new ShaderNodeProxy(MathNode, 'round'); -const saturate = new ShaderNodeProxy(MathNode, 'saturate'); -const sign = new ShaderNodeProxy(MathNode, 'sign'); -const sin = new ShaderNodeProxy(MathNode, 'sin'); -const smoothstep = new ShaderNodeProxy(MathNode, 'smoothstep'); -const sqrt = new ShaderNodeProxy(MathNode, 'sqrt'); -new ShaderNodeProxy(MathNode, 'step'); -new ShaderNodeProxy(MathNode, 'tan'); -const transformDirection = new ShaderNodeProxy(MathNode, 'transformDirection'); -const EPSILON = float(1e-6); -float(1e6); - -class ReflectNode extends Node { - constructor(scope = ReflectNode.CUBE) { - super('vec3'); - this.scope = scope; - } - - getHash() { - return `reflect-${this.scope}`; - } - - generate(builder) { - const scope = this.scope; - - if (scope === ReflectNode.VECTOR) { - const cameraToFrag = normalize(sub(positionWorld, cameraPosition)); - const reflectVec = reflect(cameraToFrag, normalWorld); - return reflectVec.build(builder); - } else if (scope === ReflectNode.CUBE) { - const reflectVec = nodeObject(new ReflectNode(ReflectNode.VECTOR)); - const cubeUV = join(negate$2(reflectVec.x), reflectVec.yz); - return cubeUV.build(builder); - } - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - } - -} - -_defineProperty$1(ReflectNode, "VECTOR", 'vector'); - -_defineProperty$1(ReflectNode, "CUBE", 'cube'); - -class CubeTextureNode extends TextureNode { - constructor(value, uvNode = new ReflectNode(), biasNode = null) { - super(value, uvNode, biasNode); - } - - getInputType() { - return 'cubeTexture'; - } - - generate(builder, output) { - const texture = this.value; - - if (!texture || texture.isCubeTexture !== true) { - throw new Error('CubeTextureNode: Need a three.js cube texture.'); - } - - const textureProperty = UniformNode.prototype.generate.call(this, builder, 'cubeTexture'); - - if (output === 'sampler') { - return textureProperty + '_sampler'; - } else if (builder.isReference(output)) { - return textureProperty; - } else { - const nodeData = builder.getDataFromNode(this); - let snippet = nodeData.snippet; - - if (snippet === undefined) { - const uvSnippet = this.uvNode.build(builder, 'vec3'); - const biasNode = this.biasNode; - - if (biasNode !== null) { - const biasSnippet = biasNode.build(builder, 'float'); - snippet = builder.getCubeTextureBias(textureProperty, uvSnippet, biasSnippet); - } else { - snippet = builder.getCubeTexture(textureProperty, uvSnippet); - } - - nodeData.snippet = snippet; - } - - return builder.format(snippet, 'vec4', output); - } - } - -} - -CubeTextureNode.prototype.isCubeTextureNode = true; - -class ReferenceNode extends Node { - constructor(property, uniformType, object = null) { - super(); - this.property = property; - this.uniformType = uniformType; - this.object = object; - this.node = null; - this.updateType = NodeUpdateType.Object; - this.setNodeType(uniformType); - } - - setNodeType(uniformType) { - this.node = new UniformNode(null, uniformType); - this.nodeType = uniformType; - - if (uniformType === 'color') { - this.nodeType = 'vec3'; - } else if (uniformType === 'texture') { - this.nodeType = 'vec4'; - } - } - - getNodeType() { - return this.uniformType; - } - - update(frame) { - const object = this.object !== null ? this.object : frame.object; - const value = object[this.property]; - this.node.value = value; - } - - generate(builder) { - return this.node.build(builder, this.getNodeType(builder)); - } - -} - -class MaterialReferenceNode extends ReferenceNode { - constructor(property, inputType, material = null) { - super(property, inputType, material); - this.material = material; - } - - update(frame) { - this.object = this.material !== null ? this.material : frame.material; - super.update(frame); - } - -} - -class MaterialNode extends Node { - constructor(scope = MaterialNode.COLOR) { - super(); - this.scope = scope; - } - - getNodeType(builder) { - const scope = this.scope; - const material = builder.context.material; - - if (scope === MaterialNode.COLOR) { - return material.map !== null ? 'vec4' : 'vec3'; - } else if (scope === MaterialNode.OPACITY) { - return 'float'; - } else if (scope === MaterialNode.SPECULAR) { - return 'vec3'; - } else if (scope === MaterialNode.ROUGHNESS || scope === MaterialNode.METALNESS) { - return 'float'; - } - } - - generate(builder, output) { - const material = builder.context.material; - const scope = this.scope; - let node = null; - - if (scope === MaterialNode.ALPHA_TEST) { - node = new MaterialReferenceNode('alphaTest', 'float'); - } else if (scope === MaterialNode.COLOR) { - const colorNode = new MaterialReferenceNode('color', 'color'); - - if (material.map !== null && material.map !== undefined && material.map.isTexture === true) { - node = new OperatorNode('*', colorNode, new MaterialReferenceNode('map', 'texture')); - } else { - node = colorNode; - } - } else if (scope === MaterialNode.OPACITY) { - const opacityNode = new MaterialReferenceNode('opacity', 'float'); - - if (material.alphaMap !== null && material.alphaMap !== undefined && material.alphaMap.isTexture === true) { - node = new OperatorNode('*', opacityNode, new MaterialReferenceNode('alphaMap', 'texture')); - } else { - node = opacityNode; - } - } else if (scope === MaterialNode.SPECULAR) { - const specularColorNode = new MaterialReferenceNode('specularColor', 'color'); - - if (material.specularColorMap !== null && material.specularColorMap !== undefined && material.specularColorMap.isTexture === true) { - node = new OperatorNode('*', specularColorNode, new MaterialReferenceNode('specularColorMap', 'texture')); - } else { - node = specularColorNode; - } - } else { - const outputType = this.getNodeType(builder); - node = new MaterialReferenceNode(scope, outputType); - } - - return node.build(builder, output); - } - -} - -_defineProperty$1(MaterialNode, "ALPHA_TEST", 'alphaTest'); - -_defineProperty$1(MaterialNode, "COLOR", 'color'); - -_defineProperty$1(MaterialNode, "OPACITY", 'opacity'); - -_defineProperty$1(MaterialNode, "SPECULAR", 'specular'); - -_defineProperty$1(MaterialNode, "ROUGHNESS", 'roughness'); - -_defineProperty$1(MaterialNode, "METALNESS", 'metalness'); - -class PointUVNode extends Node { - constructor() { - super('vec2'); - } - - generate() { - return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )'; - } - -} - -PointUVNode.prototype.isPointUVNode = true; - -new ShaderNode((inputs, builder) => { - const { - index, - weight, - bindMatrix, - bindMatrixInverse, - boneMatrices - } = inputs; - const boneMatX = element(boneMatrices, index.x); - const boneMatY = element(boneMatrices, index.y); - const boneMatZ = element(boneMatrices, index.z); - const boneMatW = element(boneMatrices, index.w); // POSITION - - const skinVertex = mul(bindMatrix, positionLocal); - const skinned = add(mul(mul(boneMatX, skinVertex), weight.x), mul(mul(boneMatY, skinVertex), weight.y), mul(mul(boneMatZ, skinVertex), weight.z), mul(mul(boneMatW, skinVertex), weight.w)); - const skinPosition = mul(bindMatrixInverse, skinned).xyz; // NORMAL - - let skinMatrix = add(mul(weight.x, boneMatX), mul(weight.y, boneMatY), mul(weight.z, boneMatZ), mul(weight.w, boneMatW)); - skinMatrix = mul(mul(bindMatrixInverse, skinMatrix), bindMatrix); - const skinNormal = transformDirection(skinMatrix, normalLocal).xyz; // ASSIGNS - - assign$3(positionLocal, skinPosition).build(builder); - assign$3(normalLocal, skinNormal).build(builder); -}); - -const LinearToLinear = new ShaderNode(inputs => { - return inputs.value; -}); -const LinearTosRGB = new ShaderNode(inputs => { - const { - value - } = inputs; - const rgb = value.rgb; - const a = sub(mul(pow(value.rgb, vec3(0.41666)), 1.055), vec3(0.055)); - const b = mul(rgb, 12.92); - const factor = vec3(lessThanEqual(rgb, vec3(0.0031308))); - const rgbResult = mix(a, b, factor); - return join(rgbResult.r, rgbResult.g, rgbResult.b, value.a); -}); -const EncodingLib = { - LinearToLinear, - LinearTosRGB -}; - -class ColorSpaceNode extends Node { - constructor(method, node) { - super('vec4'); - this.method = method; - this.node = node; - } - - fromEncoding(encoding) { - let method = null; - - if (encoding === LinearEncoding) { - method = 'Linear'; - } else if (encoding === sRGBEncoding) { - method = 'sRGB'; - } - - this.method = 'LinearTo' + method; - return this; - } - - generate(builder) { - const type = this.getNodeType(builder); - const method = this.method; - const node = this.node; - - if (method !== ColorSpaceNode.LINEAR_TO_LINEAR) { - const encodingFunctionNode = EncodingLib[method]; - return encodingFunctionNode({ - value: node - }).build(builder, type); - } else { - return node.build(builder, type); - } - } - -} - -_defineProperty$1(ColorSpaceNode, "LINEAR_TO_LINEAR", 'LinearToLinear'); - -_defineProperty$1(ColorSpaceNode, "LINEAR_TO_SRGB", 'LinearTosRGB'); - -// http://www.thetenthplanet.de/archives/1180 - -new ShaderNode(inputs => { - const { - eye_pos, - surf_norm, - mapN, - faceDirection, - uv - } = inputs; - const q0 = dFdx(eye_pos.xyz); - const q1 = dFdy(eye_pos.xyz); - const st0 = dFdx(uv.st); - const st1 = dFdy(uv.st); - const N = surf_norm; // normalized - - const q1perp = cross(q1, N); - const q0perp = cross(N, q0); - const T = add(mul(q1perp, st0.x), mul(q0perp, st1.x)); - const B = add(mul(q1perp, st0.y), mul(q0perp, st1.y)); - const det = max(dot(T, T), dot(B, B)); - const scale = cond(equal(det, 0), 0, mul(faceDirection, inversesqrt(det))); - return normalize(add(mul(T, mul(mapN.x, scale)), mul(B, mul(mapN.y, scale)), mul(N, mapN.z))); -}); - -const F_Schlick = new ShaderNode(inputs => { - const { - f0, - f90, - dotVH - } = inputs; // Original approximation by Christophe Schlick '94 - // float fresnel = pow( 1.0 - dotVH, 5.0 ); - // Optimized variant (presented by Epic at SIGGRAPH '13) - // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf - - const fresnel = exp2(mul(sub(mul(-5.55473, dotVH), 6.98316), dotVH)); - return add(mul(f0, sub(1.0, fresnel)), mul(f90, fresnel)); -}); // validated - -const BRDF_Lambert = new ShaderNode(inputs => { - return mul(1 / Math.PI, inputs.diffuseColor); // punctual light -}); // validated - -new ShaderNode(inputs => { - const { - lightDistance, - cutoffDistance, - decayExponent - } = inputs; - return cond(and(greaterThan(cutoffDistance, 0), greaterThan(decayExponent, 0)), pow(saturate(add(div(negate$2(lightDistance), cutoffDistance), 1.0)), decayExponent), 1.0); -}); // validated -// -// STANDARD -// -// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2 -// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - -const V_GGX_SmithCorrelated = new ShaderNode(inputs => { - const { - alpha, - dotNL, - dotNV - } = inputs; - const a2 = pow2(alpha); - const gv = mul(dotNL, sqrt(add(a2, mul(sub(1.0, a2), pow2(dotNV))))); - const gl = mul(dotNV, sqrt(add(a2, mul(sub(1.0, a2), pow2(dotNL))))); - return div(0.5, max(add(gv, gl), EPSILON)); -}); // validated -// Microfacet Models for Refraction through Rough Surfaces - equation (33) -// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html -// alpha is "roughness squared" in Disney’s reparameterization - -const D_GGX = new ShaderNode(inputs => { - const { - alpha, - dotNH - } = inputs; - const a2 = pow2(alpha); - const denom = add(mul(pow2(dotNH), sub(a2, 1.0)), 1.0); // avoid alpha = 0 with dotNH = 1 - - return mul(1 / Math.PI, div(a2, pow2(denom))); -}); // validated -// GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility - -const BRDF_GGX = new ShaderNode(inputs => { - const { - lightDirection, - f0, - f90, - roughness - } = inputs; - const alpha = pow2(roughness); // UE4's roughness - - const halfDir = normalize(add(lightDirection, positionViewDirection)); - const dotNL = saturate(dot(transformedNormalView, lightDirection)); - const dotNV = saturate(dot(transformedNormalView, positionViewDirection)); - const dotNH = saturate(dot(transformedNormalView, halfDir)); - const dotVH = saturate(dot(positionViewDirection, halfDir)); - const F = F_Schlick({ - f0, - f90, - dotVH - }); - const V = V_GGX_SmithCorrelated({ - alpha, - dotNL, - dotNV - }); - const D = D_GGX({ - alpha, - dotNH - }); - return mul(F, mul(V, D)); -}); // validated - -const RE_Direct_Physical = new ShaderNode(inputs => { - const { - lightDirection, - lightColor, - directDiffuse, - directSpecular - } = inputs; - const dotNL = saturate(dot(transformedNormalView, lightDirection)); - let irradiance = mul(dotNL, lightColor); - irradiance = mul(irradiance, Math.PI); // punctual light - - addTo(directDiffuse, mul(irradiance, BRDF_Lambert({ - diffuseColor: diffuseColor.rgb - }))); - addTo(directSpecular, mul(irradiance, BRDF_GGX({ - lightDirection, - f0: specularColor, - f90: 1, - roughness - }))); -}); -new ShaderNode((inputs -/*, builder*/ -) => { - // PHYSICALLY_CORRECT_LIGHTS <-> builder.renderer.physicallyCorrectLights === true - RE_Direct_Physical(inputs); -}); - -class TimerNode extends UniformNode { - constructor(scope = TimerNode.LOCAL) { - super(0); - this.scope = scope; - this.scale = 1; - this.updateType = NodeUpdateType.Frame; - } - - update(frame) { - const scope = this.scope; - const scale = this.scale; - - if (scope === TimerNode.LOCAL) { - this.value += frame.deltaTime * scale; - } else if (scope === TimerNode.DELTA) { - this.value = frame.deltaTime * scale; - } else { - // global - this.value = frame.time * scale; - } - } - - serialize(data) { - super.serialize(data); - data.scope = this.scope; - data.scale = this.scale; - } - - deserialize(data) { - super.deserialize(data); - this.scope = data.scope; - this.scale = data.scale; - } - -} - -_defineProperty$1(TimerNode, "LOCAL", 'local'); - -_defineProperty$1(TimerNode, "GLOBAL", 'global'); - -_defineProperty$1(TimerNode, "DELTA", 'delta'); - -class OscNode extends Node { - constructor(method = OscNode.SINE, timeNode = new TimerNode()) { - super(); - this.method = method; - this.timeNode = timeNode; - } - - getNodeType(builder) { - return this.timeNode.getNodeType(builder); - } - - generate(builder) { - const method = this.method; - const timeNode = this.timeNode; - let outputNode = null; - - if (method === OscNode.SINE) { - outputNode = add(mul(sin(mul(add(timeNode, 0.75), Math.PI * 2)), 0.5), 0.5); - } else if (method === OscNode.SQUARE) { - outputNode = round(fract(timeNode)); - } else if (method === OscNode.TRIANGLE) { - outputNode = abs(sub(1, mul(fract(add(timeNode, 0.5)), 2))); - } else if (method === OscNode.SAWTOOTH) { - outputNode = fract(timeNode); - } - - return outputNode.build(builder); - } - - serialize(data) { - super.serialize(data); - data.method = this.method; - } - - deserialize(data) { - super.deserialize(data); - this.method = data.method; - } - -} - -_defineProperty$1(OscNode, "SINE", 'sine'); - -_defineProperty$1(OscNode, "SQUARE", 'square'); - -_defineProperty$1(OscNode, "TRIANGLE", 'triangle'); - -_defineProperty$1(OscNode, "SAWTOOTH", 'sawtooth'); - -new ShaderNode(inputs => { - const uv = mul(inputs.uv, 2.0); - const cx = floor(uv.x); - const cy = floor(uv.y); - const result = mod$1(add(cx, cy), 2.0); - return sign(result); -}); - -class FogNode extends Node { - constructor(colorNode, factorNode) { - super('float'); - this.colorNode = colorNode; - this.factorNode = factorNode; - } - - generate(builder) { - return this.factorNode.build(builder, 'float'); - } - -} - -FogNode.prototype.isFogNode = true; - -class FogRangeNode extends FogNode { - constructor(colorNode, nearNode, farNode) { - super(colorNode); - this.nearNode = nearNode; - this.farNode = farNode; - } - - generate(builder) { - this.factorNode = smoothstep(this.nearNode, this.farNode, negate$2(positionView.z)); - return super.generate(builder); - } - -} - -FogRangeNode.prototype.isFogRangeNode = true; - -class GLTFExporter { - constructor() { - _defineProperty$1(this, "pluginCallbacks", void 0); - - this.pluginCallbacks = []; - this.register(function (writer) { - return new GLTFLightExtension(writer); - }); - this.register(function (writer) { - return new GLTFMaterialsUnlitExtension(writer); - }); - this.register(function (writer) { - return new GLTFMaterialsPBRSpecularGlossiness(writer); - }); - this.register(function (writer) { - return new GLTFMaterialsTransmissionExtension(writer); - }); - this.register(function (writer) { - return new GLTFMaterialsVolumeExtension(writer); - }); - } - - register(callback) { - if (this.pluginCallbacks.indexOf(callback) === -1) { - this.pluginCallbacks.push(callback); - } - - return this; - } - - unregister(callback) { - if (this.pluginCallbacks.indexOf(callback) !== -1) { - this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); - } - - return this; - } - - parse(input, onDone, options) { - const writer = new GLTFWriter(); - const plugins = []; - - for (let i = 0, il = this.pluginCallbacks.length; i < il; i++) { - plugins.push(this.pluginCallbacks[i](writer)); - } - - writer.setPlugins(plugins); - writer.write(input, onDone, options); - } - /** - * Static utility functions - */ - - -} //------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - - -_defineProperty$1(GLTFExporter, "Utils", { - insertKeyframe: function (track, time) { - const tolerance = 0.001; // 1ms - - const valueSize = track.getValueSize(); // @ts-expect-error - - const times = new track.TimeBufferType(track.times.length + 1); // @ts-expect-error - - const values = new track.ValueBufferType(track.values.length + valueSize); - /** - * NOTE: createInterpolant does not exist in the type, but it does exist as a property of the class - * https://github.com/mrdoob/three.js/blob/77480d339d737b7505b335101ffd3cf29a30738d/src/animation/KeyframeTrack.js#L117 - */ - // @ts-expect-error - - const interpolant = track.createInterpolant(new track.ValueBufferType(valueSize)); - let index; - - if (track.times.length === 0) { - times[0] = time; - - for (let i = 0; i < valueSize; i++) { - values[i] = 0; - } - - index = 0; - } else if (time < track.times[0]) { - if (Math.abs(track.times[0] - time) < tolerance) return 0; - times[0] = time; - times.set(track.times, 1); - values.set(interpolant.evaluate(time), 0); - values.set(track.values, valueSize); - index = 0; - } else if (time > track.times[track.times.length - 1]) { - if (Math.abs(track.times[track.times.length - 1] - time) < tolerance) { - return track.times.length - 1; - } - - times[times.length - 1] = time; - times.set(track.times, 0); - values.set(track.values, 0); - values.set(interpolant.evaluate(time), track.values.length); - index = times.length - 1; - } else { - for (let i = 0; i < track.times.length; i++) { - if (Math.abs(track.times[i] - time) < tolerance) return i; - - if (track.times[i] < time && track.times[i + 1] > time) { - times.set(track.times.slice(0, i + 1), 0); - times[i + 1] = time; - times.set(track.times.slice(i + 1), i + 2); - values.set(track.values.slice(0, (i + 1) * valueSize), 0); - values.set(interpolant.evaluate(time), (i + 1) * valueSize); - values.set(track.values.slice((i + 1) * valueSize), (i + 2) * valueSize); - index = i + 1; - break; - } - } - } - - track.times = times; - track.values = values; - return index; - }, - mergeMorphTargetTracks: function (clip, root) { - const tracks = []; - const mergedTracks = {}; - const sourceTracks = clip.tracks; - - for (let i = 0; i < sourceTracks.length; ++i) { - let sourceTrack = sourceTracks[i]; - const sourceTrackBinding = PropertyBinding.parseTrackName(sourceTrack.name); - const sourceTrackNode = PropertyBinding.findNode(root, sourceTrackBinding.nodeName); - - if (sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined) { - // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is. - tracks.push(sourceTrack); - continue; - } - - if ( // @ts-expect-error - sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && // @ts-expect-error - sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear) { - // @ts-expect-error - if (sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { - // This should never happen, because glTF morph target animations - // affect all targets already. - throw new Error('THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.'); - } - - console.warn('THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.'); - sourceTrack = sourceTrack.clone(); - sourceTrack.setInterpolation(InterpolateLinear); - } - - const targetCount = sourceTrackNode.morphTargetInfluences.length; - const targetIndex = sourceTrackNode.morphTargetDictionary[sourceTrackBinding.propertyIndex]; - - if (targetIndex === undefined) { - throw new Error('THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex); - } - - let mergedTrack; // If this is the first time we've seen this object, create a new - // track to store merged keyframe data for each morph target. - - if (mergedTracks[sourceTrackNode.uuid] === undefined) { - mergedTrack = sourceTrack.clone(); // @ts-expect-error - - const values = new mergedTrack.ValueBufferType(targetCount * mergedTrack.times.length); - - for (let j = 0; j < mergedTrack.times.length; j++) { - values[j * targetCount + targetIndex] = mergedTrack.values[j]; - } // We need to take into consideration the intended target node - // of our original un-merged morphTarget animation. - - - mergedTrack.name = (sourceTrackBinding.nodeName || '') + '.morphTargetInfluences'; - mergedTrack.values = values; - mergedTracks[sourceTrackNode.uuid] = mergedTrack; - tracks.push(mergedTrack); - continue; - } // @ts-expect-error - - - const sourceInterpolant = sourceTrack.createInterpolant(new sourceTrack.ValueBufferType(1)); - mergedTrack = mergedTracks[sourceTrackNode.uuid]; // For every existing keyframe of the merged track, write a (possibly - // interpolated) value from the source track. - - for (let j = 0; j < mergedTrack.times.length; j++) { - mergedTrack.values[j * targetCount + targetIndex] = sourceInterpolant.evaluate(mergedTrack.times[j]); - } // For every existing keyframe of the source track, write a (possibly - // new) keyframe to the merged track. Values from the previous loop may - // be written again, but keyframes are de-duplicated. - - - for (let j = 0; j < sourceTrack.times.length; j++) { - const keyframeIndex = this.insertKeyframe(mergedTrack, sourceTrack.times[j]); - mergedTrack.values[keyframeIndex * targetCount + targetIndex] = sourceTrack.values[j]; - } - } - - clip.tracks = tracks; - return clip; - } -}); - -const WEBGL_CONSTANTS = { - POINTS: 0x0000, - LINES: 0x0001, - LINE_LOOP: 0x0002, - LINE_STRIP: 0x0003, - TRIANGLES: 0x0004, - TRIANGLE_STRIP: 0x0005, - TRIANGLE_FAN: 0x0006, - UNSIGNED_BYTE: 0x1401, - UNSIGNED_SHORT: 0x1403, - FLOAT: 0x1406, - UNSIGNED_INT: 0x1405, - ARRAY_BUFFER: 0x8892, - ELEMENT_ARRAY_BUFFER: 0x8893, - NEAREST: 0x2600, - LINEAR: 0x2601, - NEAREST_MIPMAP_NEAREST: 0x2700, - LINEAR_MIPMAP_NEAREST: 0x2701, - NEAREST_MIPMAP_LINEAR: 0x2702, - LINEAR_MIPMAP_LINEAR: 0x2703, - CLAMP_TO_EDGE: 33071, - MIRRORED_REPEAT: 33648, - REPEAT: 10497 -}; -const THREE_TO_WEBGL = {}; -THREE_TO_WEBGL[NearestFilter] = WEBGL_CONSTANTS.NEAREST; -THREE_TO_WEBGL[NearestMipmapNearestFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST; -THREE_TO_WEBGL[NearestMipmapLinearFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR; -THREE_TO_WEBGL[LinearFilter] = WEBGL_CONSTANTS.LINEAR; -THREE_TO_WEBGL[LinearMipmapNearestFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST; -THREE_TO_WEBGL[LinearMipmapLinearFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR; -THREE_TO_WEBGL[ClampToEdgeWrapping] = WEBGL_CONSTANTS.CLAMP_TO_EDGE; -THREE_TO_WEBGL[RepeatWrapping] = WEBGL_CONSTANTS.REPEAT; -THREE_TO_WEBGL[MirroredRepeatWrapping] = WEBGL_CONSTANTS.MIRRORED_REPEAT; -const PATH_PROPERTIES = { - scale: 'scale', - position: 'translation', - quaternion: 'rotation', - morphTargetInfluences: 'weights' -}; // GLB constants -// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification - -const GLB_HEADER_BYTES = 12; -const GLB_HEADER_MAGIC = 0x46546c67; -const GLB_VERSION = 2; -const GLB_CHUNK_PREFIX_BYTES = 8; -const GLB_CHUNK_TYPE_JSON = 0x4e4f534a; -const GLB_CHUNK_TYPE_BIN = 0x004e4942; -/** - * Writer - */ - -class GLTFWriter { - constructor() { - _defineProperty$1(this, "plugins", void 0); - - _defineProperty$1(this, "options", void 0); - - _defineProperty$1(this, "pending", void 0); - - _defineProperty$1(this, "buffers", void 0); - - _defineProperty$1(this, "byteOffset", void 0); - - _defineProperty$1(this, "nodeMap", void 0); - - _defineProperty$1(this, "skins", void 0); - - _defineProperty$1(this, "extensionsUsed", void 0); - - _defineProperty$1(this, "uids", void 0); - - _defineProperty$1(this, "uid", void 0); - - _defineProperty$1(this, "json", void 0); - - _defineProperty$1(this, "cache", void 0); - - _defineProperty$1(this, "cachedCanvas", void 0); - - this.plugins = []; - this.options = {}; - this.pending = []; - this.buffers = []; - this.byteOffset = 0; - this.nodeMap = new Map(); - this.skins = []; - this.extensionsUsed = {}; - this.uids = new Map(); - this.uid = 0; - this.json = { - asset: { - version: '2.0', - generator: 'THREE.GLTFExporter' - } - }; - this.cache = { - meshes: new Map(), - attributes: new Map(), - attributesNormalized: new Map(), - materials: new Map(), - textures: new Map(), - images: new Map() - }; - this.cachedCanvas = null; - } - - setPlugins(plugins) { - this.plugins = plugins; - } - /** - * Parse scenes and generate GLTF output - * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes - * @param {Function} onDone Callback on completed - * @param {Object} options options - */ - - - write(input, onDone, options) { - this.options = Object.assign({}, { - // default options - binary: false, - trs: false, - onlyVisible: true, - truncateDrawRange: true, - embedImages: true, - maxTextureSize: Infinity, - animations: [], - includeCustomExtensions: false - }, options); - - if (this.options.animations !== undefined && this.options.animations.length > 0) { - // Only TRS properties, and not matrices, may be targeted by animation. - this.options.trs = true; - } - - this.processInput(input); - const writer = this; - Promise.all(this.pending).then(() => { - const buffers = writer.buffers; - const json = writer.json; - const options = writer.options; - const extensionsUsed = writer.extensionsUsed; // Merge buffers. - - const blob = new Blob(buffers, { - type: 'application/octet-stream' - }); // Declare extensions. - - const extensionsUsedList = Object.keys(extensionsUsed); - if (extensionsUsedList.length > 0) json.extensionsUsed = extensionsUsedList; // Update bytelength of the single buffer. - - if (json.buffers && json.buffers.length > 0) json.buffers[0].byteLength = blob.size; - - if (options.binary) { - // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification - const reader = new window.FileReader(); - reader.readAsArrayBuffer(blob); - - reader.onloadend = () => { - if (reader.result !== null && typeof reader.result !== 'string') { - // Binary chunk. - const binaryChunk = this.getPaddedArrayBuffer(reader.result); - const binaryChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); - binaryChunkPrefix.setUint32(0, binaryChunk.byteLength, true); - binaryChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_BIN, true); // JSON chunk. - - const jsonChunk = this.getPaddedArrayBuffer(this.stringToArrayBuffer(JSON.stringify(json)), 0x20); - const jsonChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); - jsonChunkPrefix.setUint32(0, jsonChunk.byteLength, true); - jsonChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_JSON, true); // GLB header. - - const header = new ArrayBuffer(GLB_HEADER_BYTES); - const headerView = new DataView(header); - headerView.setUint32(0, GLB_HEADER_MAGIC, true); - headerView.setUint32(4, GLB_VERSION, true); - const totalByteLength = GLB_HEADER_BYTES + jsonChunkPrefix.byteLength + jsonChunk.byteLength + binaryChunkPrefix.byteLength + binaryChunk.byteLength; - headerView.setUint32(8, totalByteLength, true); - const glbBlob = new Blob([header, jsonChunkPrefix, jsonChunk, binaryChunkPrefix, binaryChunk], { - type: 'application/octet-stream' - }); - const glbReader = new window.FileReader(); - glbReader.readAsArrayBuffer(glbBlob); - - glbReader.onloadend = function () { - if (glbReader.result !== null && typeof glbReader.result !== 'string') { - onDone(glbReader.result); - } - }; - } - }; - } else { - if (json.buffers && json.buffers.length > 0) { - const reader = new window.FileReader(); - reader.readAsDataURL(blob); - - reader.onloadend = function () { - const base64data = reader.result; - - if (json.buffers !== undefined && base64data !== null) { - json.buffers[0].uri = base64data; - onDone(json); - } - }; - } else { - onDone(json); - } - } - }); - } - /** - * Serializes a userData. - * - * @param {THREE.Object3D|THREE.Material} object - * @param {Object} objectDef - */ - - - serializeUserData(object, objectDef) { - if (Object.keys(object.userData).length === 0) return; - const options = this.options; - const extensionsUsed = this.extensionsUsed; - - try { - const json = JSON.parse(JSON.stringify(object.userData)); - - if (options.includeCustomExtensions && json.gltfExtensions) { - if (objectDef.extensions === undefined) objectDef.extensions = {}; - - for (const extensionName in json.gltfExtensions) { - objectDef.extensions[extensionName] = json.gltfExtensions[extensionName]; - extensionsUsed[extensionName] = true; - } - - delete json.gltfExtensions; - } - - if (Object.keys(json).length > 0) objectDef.extras = json; - } catch (error) { - if (error instanceof Error) { - console.warn("THREE.GLTFExporter: userData of '" + object.name + "' " + "won't be serialized because of JSON.stringify error - " + error.message); - } - } - } - /** - * Assign and return a temporal unique id for an object - * especially which doesn't have .uuid - * @param {Object} object - * @return {Integer} - */ - - - getUID(object) { - if (!this.uids.has(object)) this.uids.set(object, this.uid++); - return this.uids.get(object); - } - /** - * Checks if normal attribute values are normalized. - * - * @param {BufferAttribute} normal - * @returns {Boolean} - */ - - - isNormalizedNormalAttribute(normal) { - const cache = this.cache; - if (cache.attributesNormalized.has(normal)) return false; - const v = new Vector3(); - - for (let i = 0, il = normal.count; i < il; i++) { - // 0.0005 is from glTF-validator - if (Math.abs(v.fromBufferAttribute(normal, i).length() - 1.0) > 0.0005) return false; - } - - return true; - } - /** - * Creates normalized normal buffer attribute. - * - * @param {BufferAttribute} normal - * @returns {BufferAttribute} - * - */ - - - createNormalizedNormalAttribute(normal) { - const cache = this.cache; - if (cache.attributesNormalized.has(normal)) return cache.attributesNormalized.get(normal); - const attribute = normal.clone(); - const v = new Vector3(); - - for (let i = 0, il = attribute.count; i < il; i++) { - v.fromBufferAttribute(attribute, i); - - if (v.x === 0 && v.y === 0 && v.z === 0) { - // if values can't be normalized set (1, 0, 0) - v.setX(1.0); - } else { - v.normalize(); - } - - attribute.setXYZ(i, v.x, v.y, v.z); - } - - cache.attributesNormalized.set(normal, attribute); - return attribute; - } - /** - * Applies a texture transform, if present, to the map definition. Requires - * the KHR_texture_transform extension. - * - * @param {Object} mapDef - * @param {THREE.Texture} texture - */ - - - applyTextureTransform(mapDef, texture) { - let didTransform = false; - const transformDef = {}; - - if (texture.offset.x !== 0 || texture.offset.y !== 0) { - transformDef.offset = texture.offset.toArray(); - didTransform = true; - } - - if (texture.rotation !== 0) { - transformDef.rotation = texture.rotation; - didTransform = true; - } - - if (texture.repeat.x !== 1 || texture.repeat.y !== 1) { - transformDef.scale = texture.repeat.toArray(); - didTransform = true; - } - - if (didTransform) { - mapDef.extensions = mapDef.extensions || {}; - mapDef.extensions['KHR_texture_transform'] = transformDef; - this.extensionsUsed['KHR_texture_transform'] = true; - } - } - /** - * Process a buffer to append to the default one. - * @param {ArrayBuffer} buffer - * @return {Integer} - */ - - - processBuffer(buffer) { - const json = this.json; - const buffers = this.buffers; - if (!json.buffers) json.buffers = [{ - byteLength: 0 - }]; // All buffers are merged before export. - - buffers.push(buffer); - return 0; - } - /** - * Process and generate a BufferView - * @param {BufferAttribute} attribute - * @param {number} componentType - * @param {number} start - * @param {number} count - * @param {number} target (Optional) Target usage of the BufferView - * @return {Object} - */ - - - processBufferView(attribute, componentType, start, count, target) { - const json = this.json; - if (!json.bufferViews) json.bufferViews = []; // Create a new dataview and dump the attribute's array into it - - let componentSize; - - if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) { - componentSize = 1; - } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) { - componentSize = 2; - } else { - componentSize = 4; - } - - const byteLength = this.getPaddedBufferSize(count * attribute.itemSize * componentSize); - const dataView = new DataView(new ArrayBuffer(byteLength)); - let offset = 0; - - for (let i = start; i < start + count; i++) { - for (let a = 0; a < attribute.itemSize; a++) { - let value; - - if (attribute.itemSize > 4) { - // no support for interleaved data for itemSize > 4 - value = attribute.array[i * attribute.itemSize + a]; - } else { - if (a === 0) value = attribute.getX(i);else if (a === 1) value = attribute.getY(i);else if (a === 2) value = attribute.getZ(i);else if (a === 3) value = attribute.getW(i); - } - - if (value !== undefined) { - if (componentType === WEBGL_CONSTANTS.FLOAT) { - dataView.setFloat32(offset, value, true); - } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_INT) { - dataView.setUint32(offset, value, true); - } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) { - dataView.setUint16(offset, value, true); - } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) { - dataView.setUint8(offset, value); - } - } - - offset += componentSize; - } - } - - const bufferViewDef = { - buffer: this.processBuffer(dataView.buffer), - byteOffset: this.byteOffset, - byteLength: byteLength - }; - if (target !== undefined) bufferViewDef.target = target; - - if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) { - // Only define byteStride for vertex attributes. - bufferViewDef.byteStride = attribute.itemSize * componentSize; - } - - this.byteOffset += byteLength; - json.bufferViews.push(bufferViewDef); // @TODO Merge bufferViews where possible. - - const output = { - id: json.bufferViews.length - 1, - byteLength: 0 - }; - return output; - } - /** - * Process and generate a BufferView from an image Blob. - * @param {Blob} blob - * @return {Promise} - */ - - - processBufferViewImage(blob) { - const writer = this; - const json = writer.json; - if (!json.bufferViews) json.bufferViews = []; - return new Promise(resolve => { - const reader = new window.FileReader(); - reader.readAsArrayBuffer(blob); - - reader.onloadend = () => { - if (reader.result !== null && typeof reader.result !== 'string' && json.bufferViews !== undefined) { - const buffer = this.getPaddedArrayBuffer(reader.result); - const bufferViewDef = { - buffer: writer.processBuffer(buffer), - byteOffset: writer.byteOffset, - byteLength: buffer.byteLength - }; - writer.byteOffset += buffer.byteLength; - resolve(json.bufferViews.push(bufferViewDef) - 1); - } - }; - }); - } - /** - * Process attribute to generate an accessor - * @param {BufferAttribute} attribute Attribute to process - * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range - * @param {Integer} start (Optional) - * @param {Integer} count (Optional) - * @return {Integer|null} Index of the processed accessor on the "accessors" array - */ - - - processAccessor(attribute, geometry, start, count) { - const options = this.options; - const json = this.json; - const types = { - 1: 'SCALAR', - 2: 'VEC2', - 3: 'VEC3', - 4: 'VEC4', - 16: 'MAT4' - }; - let componentType; // Detect the component type of the attribute array (float, uint or ushort) - - if (attribute.array.constructor === Float32Array) { - componentType = WEBGL_CONSTANTS.FLOAT; - } else if (attribute.array.constructor === Uint32Array) { - componentType = WEBGL_CONSTANTS.UNSIGNED_INT; - } else if (attribute.array.constructor === Uint16Array) { - componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT; - } else if (attribute.array.constructor === Uint8Array) { - componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE; - } else { - throw new Error('THREE.GLTFExporter: Unsupported bufferAttribute component type.'); - } - - if (start === undefined) start = 0; - if (count === undefined) count = attribute.count; // @TODO Indexed buffer geometry with drawRange not supported yet - - if (options.truncateDrawRange && geometry !== undefined && geometry.index === null) { - const end = start + count; - const end2 = geometry.drawRange.count === Infinity ? attribute.count : geometry.drawRange.start + geometry.drawRange.count; - start = Math.max(start, geometry.drawRange.start); - count = Math.min(end, end2) - start; - if (count < 0) count = 0; - } // Skip creating an accessor if the attribute doesn't have data to export - - - if (count === 0) return null; - const minMax = this.getMinMax(attribute, start, count); - let bufferViewTarget; // If geometry isn't provided, don't infer the target usage of the bufferView. For - // animation samplers, target must not be set. - - if (geometry !== undefined) { - bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER; - } - - if (bufferViewTarget !== undefined) { - const bufferView = this.processBufferView(attribute, componentType, start, count, bufferViewTarget); - const accessorDef = { - bufferView: bufferView.id, - byteOffset: bufferView.byteOffset, - componentType: componentType, - count: count, - max: minMax.max, - min: minMax.min, - type: types[attribute.itemSize] - }; - if (attribute.normalized) accessorDef.normalized = true; - if (!json.accessors) json.accessors = []; - return json.accessors.push(accessorDef) - 1; - } - } - /** - * Process image - * @param {Image} image to process - * @param {Integer} format of the image (RGBAFormat) - * @param {Boolean} flipY before writing out the image - * @return {Integer} Index of the processed texture in the "images" array - */ - - - processImage(image, format, flipY) { - const writer = this; - const cache = writer.cache; - const json = writer.json; - const options = writer.options; - const pending = writer.pending; - if (!cache.images.has(image)) cache.images.set(image, {}); - const cachedImages = cache.images.get(image); - const mimeType = format === RGBAFormat ? 'image/png' : 'image/jpeg'; - const key = mimeType + ':flipY/' + flipY.toString(); - if (cachedImages !== undefined && cachedImages[key] !== undefined) return cachedImages[key]; - if (!json.images) json.images = []; - const imageDef = { - mimeType: mimeType - }; - - if (options.embedImages && options.maxTextureSize !== undefined) { - const canvas = this.cachedCanvas = this.cachedCanvas || document.createElement('canvas'); - canvas.width = Math.min(image.width, options.maxTextureSize); - canvas.height = Math.min(image.height, options.maxTextureSize); - const ctx = canvas.getContext('2d'); - - if (flipY) { - ctx === null || ctx === void 0 ? void 0 : ctx.translate(0, canvas.height); - ctx === null || ctx === void 0 ? void 0 : ctx.scale(1, -1); - } - - if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) { - ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(image, 0, 0, canvas.width, canvas.height); - } else { - if (format !== RGBAFormat) { - console.error('GLTFExporter: Only RGBA format is supported.'); - } - - if (image.width > options.maxTextureSize || image.height > options.maxTextureSize) { - console.warn('GLTFExporter: Image size is bigger than maxTextureSize', image); - } - - const data = new Uint8ClampedArray(image.height * image.width * 4); - - if (image instanceof ImageData) { - for (let i = 0; i < data.length; i += 4) { - data[i + 0] = image.data[i + 0]; - data[i + 1] = image.data[i + 1]; - data[i + 2] = image.data[i + 2]; - data[i + 3] = image.data[i + 3]; - } - } - - ctx === null || ctx === void 0 ? void 0 : ctx.putImageData(new ImageData(data, image.width, image.height), 0, 0); - } - - if (options.binary) { - pending.push(new Promise(function (resolve) { - canvas.toBlob(function (blob) { - if (blob !== null) { - writer.processBufferViewImage(blob).then(function (bufferViewIndex) { - imageDef.bufferView = bufferViewIndex; // @ts-expect-error - - resolve(); - }); - } - }, mimeType); - })); - } else { - imageDef.uri = canvas.toDataURL(mimeType); - } - } else if (image instanceof Image) { - imageDef.uri = image.src; - } - - const index = json.images.push(imageDef) - 1; - if (cachedImages !== undefined) cachedImages[key] = index; - return index; - } - /** - * Process sampler - * @param {Texture} map Texture to process - * @return {Integer} Index of the processed texture in the "samplers" array - */ - - - processSampler(map) { - const json = this.json; - if (!json.samplers) json.samplers = []; - const samplerDef = { - magFilter: THREE_TO_WEBGL[map.magFilter], - minFilter: THREE_TO_WEBGL[map.minFilter], - wrapS: THREE_TO_WEBGL[map.wrapS], - wrapT: THREE_TO_WEBGL[map.wrapT] - }; - return json.samplers.push(samplerDef) - 1; - } - /** - * Process texture - * @param {Texture} map Map to process - * @return {Integer} Index of the processed texture in the "textures" array - */ - - - processTexture(map) { - const cache = this.cache; - const json = this.json; - if (cache.textures.has(map)) return cache.textures.get(map); - if (!json.textures) json.textures = []; - const textureDef = { - sampler: this.processSampler(map), - source: this.processImage(map.image, map.format, map.flipY) - }; - if (map.name) textureDef.name = map.name; - - this._invokeAll(function (ext) { - ext.writeTexture && ext.writeTexture(map, textureDef); - }); - - const index = json.textures.push(textureDef) - 1; - cache.textures.set(map, index); - return index; - } - /** - * Process material - * @param {THREE.Material} material Material to process - * @return {Integer|null} Index of the processed material in the "materials" array - */ - - - processMaterial(material) { - const cache = this.cache; - const json = this.json; - if (cache.materials.has(material)) return cache.materials.get(material); - - if (material instanceof ShaderMaterial && material.isShaderMaterial) { - console.warn('GLTFExporter: THREE.ShaderMaterial not supported.'); - return null; - } - - if (!json.materials) json.materials = []; // @QUESTION Should we avoid including any attribute that has the default value? - - const materialDef = { - pbrMetallicRoughness: {} - }; - - if (!(material instanceof MeshStandardMaterial && material.isMeshStandardMaterial && material instanceof MeshBasicMaterial && // @ts-expect-error - material.isMeshBasicMaterial)) { - console.warn('GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.'); - } - - if (material instanceof MeshStandardMaterial || material instanceof MeshPhysicalMaterial) { - // pbrMetallicRoughness.baseColorFactor - const color = material.color.toArray().concat([material.opacity]); - - if (!this.equalArray(color, [1, 1, 1, 1])) { - materialDef.pbrMetallicRoughness.baseColorFactor = color; - } - } - - if (material instanceof MeshStandardMaterial && material.isMeshStandardMaterial) { - materialDef.pbrMetallicRoughness.metallicFactor = material.metalness; - materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness; - } else { - materialDef.pbrMetallicRoughness.metallicFactor = 0.5; - materialDef.pbrMetallicRoughness.roughnessFactor = 0.5; - } // pbrMetallicRoughness.metallicRoughnessTexture - - - if (material instanceof MeshStandardMaterial && material.metalnessMap || material instanceof MeshStandardMaterial && material.roughnessMap) { - if (material.metalnessMap === material.roughnessMap && material.metalnessMap !== null) { - const metalRoughMapDef = { - index: this.processTexture(material.metalnessMap) - }; - this.applyTextureTransform(metalRoughMapDef, material.metalnessMap); - materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; - } else { - console.warn('THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.'); - } - } // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture - - - if ((material instanceof MeshStandardMaterial || material instanceof MeshPhysicalMaterial) && material.map) { - const baseColorMapDef = { - index: this.processTexture(material.map) - }; - this.applyTextureTransform(baseColorMapDef, material.map); - materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef; - } - - if ((material instanceof MeshStandardMaterial || material instanceof MeshPhysicalMaterial) && material.emissive) { - // note: emissive components are limited to stay within the 0 - 1 range to accommodate glTF spec. see #21849 and #22000. - const emissive = material.emissive.clone().multiplyScalar(material.emissiveIntensity); - const maxEmissiveComponent = Math.max(emissive.r, emissive.g, emissive.b); - - if (maxEmissiveComponent > 1) { - emissive.multiplyScalar(1 / maxEmissiveComponent); - console.warn('THREE.GLTFExporter: Some emissive components exceed 1; emissive has been limited'); - } - - if (maxEmissiveComponent > 0) { - materialDef.emissiveFactor = emissive.toArray(); - } // emissiveTexture - - - if (material.emissiveMap) { - const emissiveMapDef = { - index: this.processTexture(material.emissiveMap) - }; - this.applyTextureTransform(emissiveMapDef, material.emissiveMap); - materialDef.emissiveTexture = emissiveMapDef; - } - } // normalTexture - - - if ((material instanceof MeshMatcapMaterial || material instanceof MeshNormalMaterial || material instanceof MeshPhongMaterial || material instanceof MeshStandardMaterial || material instanceof MeshToonMaterial) && material.normalMap) { - const normalMapDef = { - index: this.processTexture(material.normalMap) - }; - - if (material.normalScale && material.normalScale.x !== 1) { - // glTF normal scale is univariate. Ignore `y`, which may be flipped. - // Context: https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 - normalMapDef.scale = material.normalScale.x; - } - - this.applyTextureTransform(normalMapDef, material.normalMap); - materialDef.normalTexture = normalMapDef; - } // occlusionTexture - - - if ((material instanceof MeshBasicMaterial || material instanceof MeshLambertMaterial || material instanceof MeshPhongMaterial || material instanceof MeshStandardMaterial || material instanceof MeshToonMaterial) && material.aoMap) { - const occlusionMapDef = { - index: this.processTexture(material.aoMap), - texCoord: 1 - }; - - if (material.aoMapIntensity !== 1.0) { - occlusionMapDef.strength = material.aoMapIntensity; - } - - this.applyTextureTransform(occlusionMapDef, material.aoMap); - materialDef.occlusionTexture = occlusionMapDef; - } // alphaMode - - - if (material.transparent) { - materialDef.alphaMode = 'BLEND'; - } else { - if (material.alphaTest > 0.0) { - materialDef.alphaMode = 'MASK'; - materialDef.alphaCutoff = material.alphaTest; - } - } // doubleSided - - - if (material.side === DoubleSide) materialDef.doubleSided = true; - if (material.name !== '') materialDef.name = material.name; - this.serializeUserData(material, materialDef); - - this._invokeAll(function (ext) { - ext.writeMaterial && ext.writeMaterial(material, materialDef); - }); - - const index = json.materials.push(materialDef) - 1; - cache.materials.set(material, index); - return index; - } - /** - * Process mesh - * @param {THREE.Mesh} mesh Mesh to process - * @return {Integer|null} Index of the processed mesh in the "meshes" array - */ - - - processMesh(mesh) { - const cache = this.cache; - const json = this.json; - const meshCacheKeyParts = [mesh.geometry.uuid]; - - if (Array.isArray(mesh.material)) { - for (let i = 0, l = mesh.material.length; i < l; i++) { - meshCacheKeyParts.push(mesh.material[i].uuid); - } - } else { - meshCacheKeyParts.push(mesh.material.uuid); - } - - const meshCacheKey = meshCacheKeyParts.join(':'); - if (cache.meshes.has(meshCacheKey)) return cache.meshes.get(meshCacheKey); - const geometry = mesh.geometry; - let mode; // Use the correct mode - - if (mesh instanceof LineSegments && mesh.isLineSegments) { - mode = WEBGL_CONSTANTS.LINES; - } else if (mesh instanceof LineLoop && mesh.isLineLoop) { - mode = WEBGL_CONSTANTS.LINE_LOOP; - } else if (mesh instanceof Line$2 && mesh.isLine) { - mode = WEBGL_CONSTANTS.LINE_STRIP; - } else if (mesh instanceof Points && mesh.isPoints) { - mode = WEBGL_CONSTANTS.POINTS; - } else { - mode = (mesh.material instanceof MeshBasicMaterial || mesh.material instanceof MeshDepthMaterial || mesh.material instanceof MeshLambertMaterial || mesh.material instanceof MeshNormalMaterial || mesh.material instanceof MeshPhongMaterial || mesh.material instanceof MeshStandardMaterial || mesh.material instanceof MeshToonMaterial || mesh.material instanceof ShaderMaterial) && mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES; - } - - if (!geometry.isBufferGeometry) { - throw new Error('THREE.GLTFExporter: Geometry is not of type THREE.BufferGeometry.'); - } - - const meshDef = {}; - const attributes = {}; - const primitives = []; - const targets = []; // Conversion between attributes names in threejs and gltf spec - - const nameConversion = { - uv: 'TEXCOORD_0', - uv2: 'TEXCOORD_1', - color: 'COLOR_0', - skinWeight: 'WEIGHTS_0', - skinIndex: 'JOINTS_0' - }; - const originalNormal = geometry.getAttribute('normal'); - - if (originalNormal !== undefined && !(originalNormal instanceof InterleavedBufferAttribute) && !this.isNormalizedNormalAttribute(originalNormal)) { - console.warn('THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.'); - geometry.setAttribute('normal', this.createNormalizedNormalAttribute(originalNormal)); - } // @QUESTION Detect if .vertexColors = true? - // For every attribute create an accessor - - - let modifiedAttribute = null; - - for (let attributeName in geometry.attributes) { - // Ignore morph target attributes, which are exported later. - if (attributeName.substr(0, 5) === 'morph') continue; - const attribute = geometry.attributes[attributeName]; - attributeName = nameConversion[attributeName] || attributeName.toUpperCase(); // Prefix all geometry attributes except the ones specifically - // listed in the spec; non-spec attributes are considered custom. - - const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/; - if (!validVertexAttributes.test(attributeName)) attributeName = '_' + attributeName; - - if (cache.attributes.has(this.getUID(attribute))) { - attributes[attributeName] = cache.attributes.get(this.getUID(attribute)); - continue; - } // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT. - - - modifiedAttribute = null; - const array = attribute.array; - - if (attributeName === 'JOINTS_0' && !(array instanceof Uint16Array) && !(array instanceof Uint8Array)) { - console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'); - modifiedAttribute = new BufferAttribute(new Uint16Array(array), attribute.itemSize, attribute.normalized); - } - - const accessor = modifiedAttribute !== null && this.processAccessor(modifiedAttribute || attribute, geometry); - - if (accessor) { - attributes[attributeName] = accessor; - cache.attributes.set(this.getUID(attribute), accessor); - } - } - - if (originalNormal !== undefined) geometry.setAttribute('normal', originalNormal); // Skip if no exportable attributes found - - if (Object.keys(attributes).length === 0) return null; // Morph targets - - if (mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0) { - const weights = []; - const targetNames = []; - const reverseDictionary = {}; - - if (mesh.morphTargetDictionary !== undefined) { - for (const key in mesh.morphTargetDictionary) { - reverseDictionary[mesh.morphTargetDictionary[key]] = key; - } - } - - for (let i = 0; i < mesh.morphTargetInfluences.length; ++i) { - const target = {}; - let warned = false; - - for (const attributeName in geometry.morphAttributes) { - // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT. - // Three.js doesn't support TANGENT yet. - if (attributeName !== 'position' && attributeName !== 'normal') { - if (!warned) { - console.warn('GLTFExporter: Only POSITION and NORMAL morph are supported.'); - warned = true; - } - - continue; - } - - const attribute = geometry.morphAttributes[attributeName][i]; - const gltfAttributeName = attributeName.toUpperCase(); // Three.js morph attribute has absolute values while the one of glTF has relative values. - // - // glTF 2.0 Specification: - // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets - - const baseAttribute = geometry.attributes[attributeName]; - - if (cache.attributes.has(this.getUID(attribute))) { - target[gltfAttributeName] = cache.attributes.get(this.getUID(attribute)); - continue; - } // Clones attribute not to override - - - const relativeAttribute = attribute.clone(); - - if (!geometry.morphTargetsRelative) { - for (let j = 0, jl = attribute.count; j < jl; j++) { - relativeAttribute.setXYZ(j, attribute.getX(j) - baseAttribute.getX(j), attribute.getY(j) - baseAttribute.getY(j), attribute.getZ(j) - baseAttribute.getZ(j)); - } - } - - const accessor = this.processAccessor(relativeAttribute, geometry); - - if (accessor != undefined) { - target[gltfAttributeName] = accessor; - } - - cache.attributes.set(this.getUID(baseAttribute), target[gltfAttributeName]); - } - - targets.push(target); - weights.push(mesh.morphTargetInfluences[i]); - if (mesh.morphTargetDictionary !== undefined) targetNames.push(reverseDictionary[i]); - } - - meshDef.weights = weights; - - if (targetNames.length > 0) { - meshDef.extras = {}; - meshDef.extras.targetNames = targetNames; - } - } - - const isMultiMaterial = Array.isArray(mesh.material); - if (isMultiMaterial && geometry.groups.length === 0) return null; - const materials = isMultiMaterial ? mesh.material : [mesh.material]; - const groups = isMultiMaterial ? geometry.groups : [{ - materialIndex: 0, - start: undefined, - count: undefined - }]; - - for (let i = 0, il = groups.length; i < il; i++) { - const primitive = { - mode: mode, - attributes: attributes - }; - - if (geometry instanceof Object3D || geometry instanceof Material) { - this.serializeUserData(geometry, primitive); - } - - if (targets.length > 0) primitive.targets = targets; - - if (geometry.index !== null) { - let cacheKey = this.getUID(geometry.index); - - if (groups[i].start !== undefined || groups[i].count !== undefined) { - // @ts-expect-error - cacheKey += `:${groups[i].start}:${groups[i].count}`; - } - - if (cache.attributes.has(cacheKey)) { - primitive.indices = cache.attributes.get(cacheKey); - } else { - primitive.indices = this.processAccessor(geometry.index, geometry, groups[i].start, groups[i].count); - cache.attributes.set(cacheKey, primitive.indices); - } - - if (primitive.indices === null) delete primitive.indices; - } - - const materialIndex = groups[i].materialIndex; - - if (materialIndex !== undefined && Array.isArray(materials)) { - const targetMaterials = materials[materialIndex]; - - if (!Array.isArray(targetMaterials)) { - const material = this.processMaterial(targetMaterials); - if (material !== null) primitive.material = material; - primitives.push(primitive); - } - } - } - - meshDef.primitives = primitives; - if (!json.meshes) json.meshes = []; - - this._invokeAll(function (ext) { - ext.writeMesh && ext.writeMesh(mesh, meshDef); - }); - - const index = json.meshes.push(meshDef) - 1; - cache.meshes.set(meshCacheKey, index); - return index; - } - /** - * Process camera - * @param {THREE.Camera} camera Camera to process - * @return {Integer} Index of the processed mesh in the "camera" array - */ - - - processCamera(camera) { - const json = this.json; - if (!json.cameras) json.cameras = []; - const isOrtho = camera instanceof OrthographicCamera && camera.isOrthographicCamera; - const cameraDef = { - type: isOrtho ? 'orthographic' : 'perspective' - }; - - if (camera instanceof OrthographicCamera && isOrtho) { - cameraDef.orthographic = { - xmag: camera.right * 2, - ymag: camera.top * 2, - zfar: camera.far <= 0 ? 0.001 : camera.far, - znear: camera.near < 0 ? 0 : camera.near - }; - } else if (camera instanceof PerspectiveCamera) { - cameraDef.perspective = { - aspectRatio: camera.aspect, - yfov: MathUtils.degToRad(camera.fov), - zfar: camera.far <= 0 ? 0.001 : camera.far, - znear: camera.near < 0 ? 0 : camera.near - }; - } // Question: Is saving "type" as name intentional? - - - if (camera.name !== '') cameraDef.name = camera.type; - return json.cameras.push(cameraDef) - 1; - } - /** - * Creates glTF animation entry from AnimationClip object. - * - * Status: - * - Only properties listed in PATH_PROPERTIES may be animated. - * - * @param {THREE.AnimationClip} clip - * @param {THREE.Object3D} root - * @return {number|null} - */ - - - processAnimation(clip, root) { - const json = this.json; - const nodeMap = this.nodeMap; - if (!json.animations) json.animations = []; - clip = GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(), root); - const tracks = clip.tracks; - const channels = []; - const samplers = []; - - for (let i = 0; i < tracks.length; ++i) { - const track = tracks[i]; - const trackBinding = PropertyBinding.parseTrackName(track.name); - let trackNode = PropertyBinding.findNode(root, trackBinding.nodeName); - const trackProperty = PATH_PROPERTIES[trackBinding.propertyName]; - - if (trackBinding.objectName === 'bones') { - if (trackNode.isSkinnedMesh) { - trackNode = trackNode.skeleton.getBoneByName(trackBinding.objectIndex); - } else { - trackNode = undefined; - } - } - - if (!trackNode || !trackProperty) { - console.warn('THREE.GLTFExporter: Could not export animation track "%s".', track.name); - return null; - } - - const inputItemSize = 1; - let outputItemSize = track.values.length / track.times.length; - - if (trackProperty === PATH_PROPERTIES.morphTargetInfluences) { - outputItemSize /= trackNode.morphTargetInfluences.length; - } - - let interpolation; // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE - // Detecting glTF cubic spline interpolant by checking factory method's special property - // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return - // valid value from .getInterpolation(). - // @ts-expect-error - - if (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { - interpolation = 'CUBICSPLINE'; // itemSize of CUBICSPLINE keyframe is 9 - // (VEC3 * 3: inTangent, splineVertex, and outTangent) - // but needs to be stored as VEC3 so dividing by 3 here. - - outputItemSize /= 3; - } else if (track.getInterpolation() === InterpolateDiscrete) { - interpolation = 'STEP'; - } else { - interpolation = 'LINEAR'; - } - - samplers.push({ - input: this.processAccessor(new BufferAttribute(track.times, inputItemSize)), - output: this.processAccessor(new BufferAttribute(track.values, outputItemSize)), - interpolation: interpolation - }); - channels.push({ - sampler: samplers.length - 1, - target: { - node: nodeMap.get(trackNode), - path: trackProperty - } - }); - } - - json.animations.push({ - name: clip.name || 'clip_' + json.animations.length, - samplers: samplers, - channels: channels - }); - return json.animations.length - 1; - } - /** - * @param {THREE.Object3D} object - * @return {number|null} - */ - - - processSkin(object) { - const json = this.json; - const nodeMap = this.nodeMap; - - if (json.nodes !== undefined && object instanceof SkinnedMesh) { - const node = json.nodes[nodeMap.get(object)]; - const skeleton = object.skeleton; - if (skeleton === undefined) return null; - const rootJoint = object.skeleton.bones[0]; - if (rootJoint === undefined) return null; - const joints = []; - const inverseBindMatrices = new Float32Array(skeleton.bones.length * 16); - const temporaryBoneInverse = new Matrix4(); - - for (let i = 0; i < skeleton.bones.length; ++i) { - joints.push(nodeMap.get(skeleton.bones[i])); - temporaryBoneInverse.copy(skeleton.boneInverses[i]); - temporaryBoneInverse.multiply(object.bindMatrix).toArray(inverseBindMatrices, i * 16); - } - - if (json.skins === undefined) json.skins = []; - json.skins.push({ - inverseBindMatrices: this.processAccessor(new BufferAttribute(inverseBindMatrices, 16)), - joints: joints, - skeleton: nodeMap.get(rootJoint) - }); - const skinIndex = node.skin = json.skins.length - 1; - return skinIndex; - } else { - return null; - } - } - /** - * Process Object3D node - * @param {THREE.Object3D} node Object3D to processNode - * @return {Integer} Index of the node in the nodes list - */ - - - processNode(object) { - const json = this.json; - const options = this.options; - const nodeMap = this.nodeMap; - if (!json.nodes) json.nodes = []; - const nodeDef = {}; - - if (options.trs) { - const rotation = object.quaternion.toArray(); - const position = object.position.toArray(); - const scale = object.scale.toArray(); - - if (!this.equalArray(rotation, [0, 0, 0, 1])) { - nodeDef.rotation = rotation; - } - - if (!this.equalArray(position, [0, 0, 0])) { - nodeDef.translation = position; - } - - if (!this.equalArray(scale, [1, 1, 1])) { - nodeDef.scale = scale; - } - } else { - if (object.matrixAutoUpdate) { - object.updateMatrix(); - } - - if (!this.isIdentityMatrix(object.matrix)) { - nodeDef.matrix = object.matrix.elements; - } - } // We don't export empty strings name because it represents no-name in Three.js. - - - if (object.name !== '') nodeDef.name = String(object.name); - this.serializeUserData(object, nodeDef); - - if ((object instanceof Mesh && object.isMesh || object instanceof Line$2 && object.isLine || object instanceof Points && object.isPoints) && object instanceof Mesh) { - const meshIndex = this.processMesh(object); - if (meshIndex !== null) nodeDef.mesh = meshIndex; - } else if (object instanceof Camera && object.isCamera) { - nodeDef.camera = this.processCamera(object); - } - - if (object instanceof SkinnedMesh && object.isSkinnedMesh) this.skins.push(object); - - if (object.children.length > 0) { - const children = []; - - for (let i = 0, l = object.children.length; i < l; i++) { - const child = object.children[i]; - - if (child.visible || !options.onlyVisible) { - const nodeIndex = this.processNode(child); - if (nodeIndex !== null) children.push(nodeIndex); - } - } - - if (children.length > 0) nodeDef.children = children; - } - - this._invokeAll(function (ext) { - ext.writeNode && ext.writeNode(object, nodeDef); - }); - - const nodeIndex = json.nodes.push(nodeDef) - 1; - nodeMap.set(object, nodeIndex); - return nodeIndex; - } - /** - * Process Scene - * @param {Scene} node Scene to process - */ - - - processScene(scene) { - const json = this.json; - const options = this.options; - - if (!json.scenes) { - json.scenes = []; - json.scene = 0; - } - - const sceneDef = {}; - if (scene.name !== '') sceneDef.name = scene.name; - json.scenes.push(sceneDef); - const nodes = []; - - for (let i = 0, l = scene.children.length; i < l; i++) { - const child = scene.children[i]; - - if (child.visible || !options.onlyVisible) { - const nodeIndex = this.processNode(child); - if (nodeIndex !== null) nodes.push(nodeIndex); - } - } - - if (nodes.length > 0) sceneDef.nodes = nodes; - this.serializeUserData(scene, sceneDef); - } - - processObjects(objects) { - const scene = new Scene$1(); - scene.name = 'AuxScene'; - - for (let i = 0; i < objects.length; i++) { - // We push directly to children instead of calling `add` to prevent - // modify the .parent and break its original scene and hierarchy - scene.children.push(objects[i]); - } - - this.processScene(scene); - } - /** - * @param {THREE.Object3D|Array} input - */ - - - processInput(input) { - const options = this.options; - input = input instanceof Array ? input : [input]; - - this._invokeAll(function (ext) { - ext.beforeParse && ext.beforeParse(input); - }); - - const objectsWithoutScene = []; - - for (let i = 0; i < input.length; i++) { - const inputScene = input[i]; - - if (inputScene instanceof Scene$1) { - this.processScene(inputScene); - } else { - objectsWithoutScene.push(input[i]); - } - } - - if (objectsWithoutScene.length > 0) this.processObjects(objectsWithoutScene); - - for (let i = 0; i < this.skins.length; ++i) { - this.processSkin(this.skins[i]); - } - - for (let i = 0; options.animations !== undefined && i < options.animations.length; ++i) { - this.processAnimation(options.animations[i], input[0]); - } - - this._invokeAll(function (ext) { - ext.afterParse && ext.afterParse(input); - }); - } - - _invokeAll(func) { - for (let i = 0, il = this.plugins.length; i < il; i++) { - func(this.plugins[i]); - } - } //------------------------------------------------------------------------------ - // Utility functions - //------------------------------------------------------------------------------ - - /** - * Compare two arrays - * @param {Array} array1 Array 1 to compare - * @param {Array} array2 Array 2 to compare - * @return {Boolean} Returns true if both arrays are equal - */ - - - equalArray(array1, array2) { - return array1.length === array2.length && array1.every(function (element, index) { - return element === array2[index]; - }); - } - /** - * Converts a string to an ArrayBuffer. - * @param {string} text - * @return {ArrayBuffer} - */ - - - stringToArrayBuffer(text) { - if (window.TextEncoder !== undefined) { - return new TextEncoder().encode(text).buffer; - } - - const array = new Uint8Array(new ArrayBuffer(text.length)); - - for (let i = 0, il = text.length; i < il; i++) { - const value = text.charCodeAt(i); // Replacing multi-byte character with space(0x20). - - array[i] = value > 0xff ? 0x20 : value; - } - - return array.buffer; - } - - isIdentityMatrix(matrix) { - return this.equalArray(matrix.elements, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); - } - - getMinMax(attribute, start, count) { - const output = { - min: new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY), - max: new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY) - }; - - for (let i = start; i < start + count; i++) { - for (let a = 0; a < attribute.itemSize; a++) { - let value; - - if (attribute.itemSize > 4) { - // no support for interleaved data for itemSize > 4 - value = attribute.array[i * attribute.itemSize + a]; - } else { - if (a === 0) value = attribute.getX(i);else if (a === 1) value = attribute.getY(i);else if (a === 2) value = attribute.getZ(i);else if (a === 3) value = attribute.getW(i); - } - - if (value !== undefined) { - output.min[a] = Math.min(output.min[a], value); - output.max[a] = Math.max(output.max[a], value); - } - } - } - - return output; - } - /** - * Get the required size + padding for a buffer, rounded to the next 4-byte boundary. - * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment - */ - - - getPaddedBufferSize(bufferSize) { - return Math.ceil(bufferSize / 4) * 4; - } - /** - * Returns a buffer aligned to 4-byte boundary. - * - * @param {ArrayBuffer} arrayBuffer Buffer to pad - * @param {Integer} paddingByte (Optional) - * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer - */ - - - getPaddedArrayBuffer(arrayBuffer, paddingByte = 0) { - const paddedLength = this.getPaddedBufferSize(arrayBuffer.byteLength); - - if (paddedLength !== arrayBuffer.byteLength) { - const array = new Uint8Array(paddedLength); - array.set(new Uint8Array(arrayBuffer)); - - if (paddingByte !== 0) { - for (let i = arrayBuffer.byteLength; i < paddedLength; i++) { - array[i] = paddingByte; - } - } - - return array.buffer; - } - - return arrayBuffer; - } - -} -/** - * Punctual Lights Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual - */ - - -class GLTFLightExtension { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_lights_punctual'; - } - - writeNode(light, nodeDef) { - if (!light.isLight) return; - - if (!(light instanceof DirectionalLight$1 && light.isDirectionalLight) && // @ts-expect-error - !(light instanceof PointLight && light.isPointLight) && !(light instanceof SpotLight && light.isSpotLight)) { - console.warn('THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light); - return; - } - - const writer = this.writer; - const json = writer.json; - const extensionsUsed = writer.extensionsUsed; - const lightDef = {}; - if (light.name) lightDef.name = light.name; - lightDef.color = light.color.toArray(); - lightDef.intensity = light.intensity; - - if (light instanceof DirectionalLight$1 && light.isDirectionalLight) { - lightDef.type = 'directional'; - } else if (light instanceof PointLight && // @ts-expect-error - light.isPointLight) { - lightDef.type = 'point'; - if (light.distance > 0) lightDef.range = light.distance; - } else if (light instanceof SpotLight && light.isSpotLight) { - lightDef.type = 'spot'; - if (light.distance > 0) lightDef.range = light.distance; - lightDef.spot = {}; - lightDef.spot.innerConeAngle = (light.penumbra - 1.0) * light.angle * -1.0; - lightDef.spot.outerConeAngle = light.angle; - } - - if (!(light instanceof DirectionalLight$1) && light.decay !== undefined && light.decay !== 2) { - console.warn('THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, ' + 'and expects light.decay=2.'); - } - - if (!(light instanceof PointLight) && light.target && (light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== -1)) { - console.warn('THREE.GLTFExporter: Light direction may be lost. For best results, ' + 'make light.target a child of the light with position 0,0,-1.'); - } - - if (!extensionsUsed[this.name]) { - json.extensions = json.extensions || {}; - json.extensions[this.name] = { - lights: [] - }; - extensionsUsed[this.name] = true; - } - - if (json.extensions !== undefined) { - const lights = json.extensions[this.name].lights; - lights.push(lightDef); - nodeDef.extensions = nodeDef.extensions || {}; - nodeDef.extensions[this.name] = { - light: lights.length - 1 - }; - } - } - -} -/** - * Unlit Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit - */ - - -class GLTFMaterialsUnlitExtension { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_materials_unlit'; - } - - writeMaterial(material, materialDef) { - if (!(material instanceof MeshBasicMaterial && // @ts-expect-error - material.isMeshBasicMaterial)) { - return; - } - - const writer = this.writer; - const extensionsUsed = writer.extensionsUsed; - materialDef.extensions = materialDef.extensions || {}; - materialDef.extensions[this.name] = {}; - extensionsUsed[this.name] = true; - materialDef.pbrMetallicRoughness.metallicFactor = 0.0; - materialDef.pbrMetallicRoughness.roughnessFactor = 0.9; - } - -} -/** - * Specular-Glossiness Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness - */ - - -class GLTFMaterialsPBRSpecularGlossiness { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_materials_pbrSpecularGlossiness'; - } - - writeMaterial(material, materialDef) { - // @ts-expect-error - if (!material.isGLTFSpecularGlossinessMaterial) return; - const writer = this.writer; - const extensionsUsed = writer.extensionsUsed; - const extensionDef = {}; - - if (materialDef.pbrMetallicRoughness.baseColorFactor) { - extensionDef.diffuseFactor = materialDef.pbrMetallicRoughness.baseColorFactor; - } - - if (material instanceof MeshPhongMaterial) { - const specularFactor = [1, 1, 1]; - material.specular.toArray(specularFactor, 0); - extensionDef.specularFactor = specularFactor; - extensionDef.glossinessFactor = // @ts-expect-error - material.glossiness; - } - - if (materialDef.pbrMetallicRoughness.baseColorTexture) { - extensionDef.diffuseTexture = materialDef.pbrMetallicRoughness.baseColorTexture; - } - - if ((material instanceof MeshBasicMaterial || material instanceof MeshLambertMaterial || material instanceof MeshPhongMaterial) && material.specularMap) { - const specularMapDef = { - index: writer.processTexture(material.specularMap) - }; - writer.applyTextureTransform(specularMapDef, material.specularMap); - extensionDef.specularGlossinessTexture = specularMapDef; - } - - materialDef.extensions = materialDef.extensions || {}; - materialDef.extensions[this.name] = extensionDef; - extensionsUsed[this.name] = true; - } - -} -/** - * Transmission Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission - */ - - -class GLTFMaterialsTransmissionExtension { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_materials_transmission'; - } - - writeMaterial(material, materialDef) { - if (!(material instanceof MeshPhysicalMaterial && // @ts-expect-error - material.isMeshPhysicalMaterial) || material.transmission === 0) { - return; - } - - const writer = this.writer; - const extensionsUsed = writer.extensionsUsed; - const extensionDef = {}; - extensionDef.transmissionFactor = material.transmission; - - if (material.transmissionMap) { - const transmissionMapDef = { - index: writer.processTexture(material.transmissionMap) - }; - writer.applyTextureTransform(transmissionMapDef, material.transmissionMap); - extensionDef.transmissionTexture = transmissionMapDef; - } - - materialDef.extensions = materialDef.extensions || {}; - materialDef.extensions[this.name] = extensionDef; - extensionsUsed[this.name] = true; - } - -} -/** - * Materials Volume Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume - */ - - -class GLTFMaterialsVolumeExtension { - constructor(writer) { - _defineProperty$1(this, "writer", void 0); - - _defineProperty$1(this, "name", void 0); - - this.writer = writer; - this.name = 'KHR_materials_volume'; - } - - writeMaterial(material, materialDef) { - if (!(material instanceof MeshPhysicalMaterial && // @ts-expect-error - material.isMeshPhysicalMaterial) || material.thickness === 0) { - return; - } - - const writer = this.writer; - const extensionsUsed = writer.extensionsUsed; - const extensionDef = {}; - extensionDef.thickness = material.thickness; - - if (material.thicknessMap) { - const thicknessMapDef = { - index: writer.processTexture(material.thicknessMap) - }; - writer.applyTextureTransform(thicknessMapDef, material.thicknessMap); - extensionDef.thicknessTexture = thicknessMapDef; - } - - extensionDef.attenuationDistance = material.attenuationDistance; - extensionDef.attenuationColor = //@ts-expect-error - material.attenuationTint.toArray(); - materialDef.extensions = materialDef.extensions || {}; - materialDef.extensions[this.name] = extensionDef; - extensionsUsed[this.name] = true; - } - -} - -// DEFLATE is a complex format; to read this code, you should probably check the RFC first: - -// aliases for shorter compressed code (most minifers don't do this) -var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array; -// fixed length extra bits -var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); -// fixed distance extra bits -// see fleb note -var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); -// get base, reverse index map from extra bits -var freb = function (eb, start) { - var b = new u16(31); - for (var i = 0; i < 31; ++i) { - b[i] = start += 1 << eb[i - 1]; - } - // numbers here are at max 18 bits - var r = new u32(b[30]); - for (var i = 1; i < 30; ++i) { - for (var j = b[i]; j < b[i + 1]; ++j) { - r[j] = ((j - b[i]) << 5) | i; - } - } - return [b, r]; -}; -var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1]; -// we can ignore the fact that the other numbers are wrong; they never happen anyway -fl[28] = 258, revfl[258] = 28; -freb(fdeb, 0); -// map of value to reverse (assuming 16 bits) -var rev = new u16(32768); -for (var i$3 = 0; i$3 < 32768; ++i$3) { - // reverse table algorithm from SO - var x$1 = ((i$3 & 0xAAAA) >>> 1) | ((i$3 & 0x5555) << 1); - x$1 = ((x$1 & 0xCCCC) >>> 2) | ((x$1 & 0x3333) << 2); - x$1 = ((x$1 & 0xF0F0) >>> 4) | ((x$1 & 0x0F0F) << 4); - rev[i$3] = (((x$1 & 0xFF00) >>> 8) | ((x$1 & 0x00FF) << 8)) >>> 1; -} -// fixed length tree -var flt = new u8(288); -for (var i$3 = 0; i$3 < 144; ++i$3) - flt[i$3] = 8; -for (var i$3 = 144; i$3 < 256; ++i$3) - flt[i$3] = 9; -for (var i$3 = 256; i$3 < 280; ++i$3) - flt[i$3] = 7; -for (var i$3 = 280; i$3 < 288; ++i$3) - flt[i$3] = 8; -// fixed distance tree -var fdt = new u8(32); -for (var i$3 = 0; i$3 < 32; ++i$3) - fdt[i$3] = 5; -// empty -var et = /*#__PURE__*/ new u8(0); -// text decoder -var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); -// text decoder stream -var tds = 0; -try { - td.decode(et, { stream: true }); - tds = 1; -} -catch (e) { } - -/** - * Export draco compressed files from threejs geometry objects. - * - * Draco files are compressed and usually are smaller than conventional 3D file formats. - * - * The exporter receives a options object containing - * - decodeSpeed, indicates how to tune the encoder regarding decode speed (0 gives better speed but worst quality) - * - encodeSpeed, indicates how to tune the encoder parameters (0 gives better speed but worst quality) - * - encoderMethod - * - quantization, indicates the presision of each type of data stored in the draco file in the order (POSITION, NORMAL, COLOR, TEX_COORD, GENERIC) - * - exportUvs - * - exportNormals - */ - -class DRACOExporter { - // Encoder methods - // Geometry type - // Attribute type - parse(object, options = { - decodeSpeed: 5, - encodeSpeed: 5, - encoderMethod: DRACOExporter.MESH_EDGEBREAKER_ENCODING, - quantization: [16, 8, 8, 8, 8], - exportUvs: true, - exportNormals: true, - exportColor: false - }) { - if (object instanceof BufferGeometry && object.isBufferGeometry) { - throw new Error('DRACOExporter: The first parameter of parse() is now an instance of Mesh or Points.'); - } - - if (DracoEncoderModule === undefined) { - throw new Error('THREE.DRACOExporter: required the draco_encoder to work.'); - } - - const geometry = object.geometry; - const dracoEncoder = DracoEncoderModule(); - const encoder = new dracoEncoder.Encoder(); - let builder; - let dracoObject; - - if (!geometry.isBufferGeometry) { - throw new Error('THREE.DRACOExporter.parse(geometry, options): geometry is not a THREE.BufferGeometry instance.'); - } - - if (object instanceof Mesh && object.isMesh) { - builder = new dracoEncoder.MeshBuilder(); - dracoObject = new dracoEncoder.Mesh(); - const vertices = geometry.getAttribute('position'); // @ts-expect-error - - builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); - const faces = geometry.getIndex(); - - if (faces !== null) { - // @ts-expect-error - builder.AddFacesToMesh(dracoObject, faces.count / 3, faces.array); - } else { - const faces = new (vertices.count > 65535 ? Uint32Array : Uint16Array)(vertices.count); - - for (let i = 0; i < faces.length; i++) { - faces[i] = i; - } - - builder.AddFacesToMesh(dracoObject, vertices.count, faces); - } - - if (options.exportNormals) { - const normals = geometry.getAttribute('normal'); - - if (normals !== undefined) { - // @ts-expect-error - builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array); - } - } - - if (options.exportUvs) { - const uvs = geometry.getAttribute('uv'); - - if (uvs !== undefined) { - // @ts-expect-error - builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array); - } - } - - if (options.exportColor) { - const colors = geometry.getAttribute('color'); - - if (colors !== undefined) { - // @ts-expect-error - builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array); - } - } - } else if (object instanceof Points && object.isPoints) { - // @ts-expect-error - builder = new dracoEncoder.PointCloudBuilder(); // @ts-expect-error - - dracoObject = new dracoEncoder.PointCloud(); - const vertices = geometry.getAttribute('position'); - builder.AddFloatAttribute(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); - - if (options.exportColor) { - const colors = geometry.getAttribute('color'); - - if (colors !== undefined) { - builder.AddFloatAttribute(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array); - } - } - } else { - throw new Error('DRACOExporter: Unsupported object type.'); - } //Compress using draco encoder - - - const encodedData = new dracoEncoder.DracoInt8Array(); //Sets the desired encoding and decoding speed for the given options from 0 (slowest speed, but the best compression) to 10 (fastest, but the worst compression). - - const encodeSpeed = options.encodeSpeed !== undefined ? options.encodeSpeed : 5; - const decodeSpeed = options.decodeSpeed !== undefined ? options.decodeSpeed : 5; - encoder.SetSpeedOptions(encodeSpeed, decodeSpeed); // Sets the desired encoding method for a given geometry. - - if (options.encoderMethod !== undefined) { - encoder.SetEncodingMethod(options.encoderMethod); - } // Sets the quantization (number of bits used to represent) compression options for a named attribute. - // The attribute values will be quantized in a box defined by the maximum extent of the attribute values. - - - if (options.quantization !== undefined) { - for (let i = 0; i < 5; i++) { - if (options.quantization[i] !== undefined) { - encoder.SetAttributeQuantization(i, options.quantization[i]); - } - } - } - - let length; - - if (object instanceof Mesh && object.isMesh) { - length = encoder.EncodeMeshToDracoBuffer(dracoObject, encodedData); - } else { - // @ts-expect-error - length = encoder.EncodePointCloudToDracoBuffer(dracoObject, true, encodedData); - } - - dracoEncoder.destroy(dracoObject); - - if (length === 0) { - throw new Error('THREE.DRACOExporter: Draco encoding failed.'); - } //Copy encoded data to buffer. - - - const outputData = new Int8Array(new ArrayBuffer(length)); - - for (let i = 0; i < length; i++) { - outputData[i] = encodedData.GetValue(i); - } - - dracoEncoder.destroy(encodedData); - dracoEncoder.destroy(encoder); - dracoEncoder.destroy(builder); - return outputData; - } - -} - -_defineProperty$1(DRACOExporter, "MESH_EDGEBREAKER_ENCODING", 1); - -_defineProperty$1(DRACOExporter, "MESH_SEQUENTIAL_ENCODING", 0); - -_defineProperty$1(DRACOExporter, "POINT_CLOUD", 0); - -_defineProperty$1(DRACOExporter, "TRIANGULAR_MESH", 1); - -_defineProperty$1(DRACOExporter, "INVALID", -1); - -_defineProperty$1(DRACOExporter, "POSITION", 0); - -_defineProperty$1(DRACOExporter, "NORMAL", 1); - -_defineProperty$1(DRACOExporter, "COLOR", 2); - -_defineProperty$1(DRACOExporter, "TEX_COORD", 3); - -_defineProperty$1(DRACOExporter, "GENERIC", 4); - -var mmdparser = {exports: {}}; - -(function (module, exports) { - (function (global, factory) { - factory(exports) ; - }(commonjsGlobal, (function (exports) { - /** - * @author Takahiro / https://github.com/takahirox - * - * Simple CharsetEncoder. - */ - - function CharsetEncoder() { - } - - /* - * Converts from Shift_JIS Uint8Array data to Unicode strings. - */ - CharsetEncoder.prototype.s2u = function(uint8Array) { - var t = this.s2uTable; - var str = ''; - var p = 0; - - while(p < uint8Array.length) { - var key = uint8Array[p++]; - - if(! ((key >= 0x00 && key <= 0x7e) || - (key >= 0xa1 && key <= 0xdf)) && - p < uint8Array.length) { - key = (key << 8) | uint8Array[p++]; - } - - if(t[key] === undefined) { - console.error('unknown char code ' + key + '.'); - return str; - } - - str += String.fromCharCode(t[key]); - } - - return str; - }; - - CharsetEncoder.prototype.s2uTable = { - 0:0, - 1:1, - 2:2, - 3:3, - 4:4, - 5:5, - 6:6, - 7:7, - 8:8, - 9:9, - 10:10, - 11:11, - 12:12, - 13:13, - 14:14, - 15:15, - 16:16, - 17:17, - 18:18, - 19:19, - 20:20, - 21:21, - 22:22, - 23:23, - 24:24, - 25:25, - 26:26, - 27:27, - 28:28, - 29:29, - 30:30, - 31:31, - 32:32, - 33:33, - 34:34, - 35:35, - 36:36, - 37:37, - 38:38, - 39:39, - 40:40, - 41:41, - 42:42, - 43:43, - 44:44, - 45:45, - 46:46, - 47:47, - 48:48, - 49:49, - 50:50, - 51:51, - 52:52, - 53:53, - 54:54, - 55:55, - 56:56, - 57:57, - 58:58, - 59:59, - 60:60, - 61:61, - 62:62, - 63:63, - 64:64, - 65:65, - 66:66, - 67:67, - 68:68, - 69:69, - 70:70, - 71:71, - 72:72, - 73:73, - 74:74, - 75:75, - 76:76, - 77:77, - 78:78, - 79:79, - 80:80, - 81:81, - 82:82, - 83:83, - 84:84, - 85:85, - 86:86, - 87:87, - 88:88, - 89:89, - 90:90, - 91:91, - 92:92, - 93:93, - 94:94, - 95:95, - 96:96, - 97:97, - 98:98, - 99:99, - 100:100, - 101:101, - 102:102, - 103:103, - 104:104, - 105:105, - 106:106, - 107:107, - 108:108, - 109:109, - 110:110, - 111:111, - 112:112, - 113:113, - 114:114, - 115:115, - 116:116, - 117:117, - 118:118, - 119:119, - 120:120, - 121:121, - 122:122, - 123:123, - 124:124, - 125:125, - 126:126, - 161:65377, - 162:65378, - 163:65379, - 164:65380, - 165:65381, - 166:65382, - 167:65383, - 168:65384, - 169:65385, - 170:65386, - 171:65387, - 172:65388, - 173:65389, - 174:65390, - 175:65391, - 176:65392, - 177:65393, - 178:65394, - 179:65395, - 180:65396, - 181:65397, - 182:65398, - 183:65399, - 184:65400, - 185:65401, - 186:65402, - 187:65403, - 188:65404, - 189:65405, - 190:65406, - 191:65407, - 192:65408, - 193:65409, - 194:65410, - 195:65411, - 196:65412, - 197:65413, - 198:65414, - 199:65415, - 200:65416, - 201:65417, - 202:65418, - 203:65419, - 204:65420, - 205:65421, - 206:65422, - 207:65423, - 208:65424, - 209:65425, - 210:65426, - 211:65427, - 212:65428, - 213:65429, - 214:65430, - 215:65431, - 216:65432, - 217:65433, - 218:65434, - 219:65435, - 220:65436, - 221:65437, - 222:65438, - 223:65439, - 33088:12288, - 33089:12289, - 33090:12290, - 33091:65292, - 33092:65294, - 33093:12539, - 33094:65306, - 33095:65307, - 33096:65311, - 33097:65281, - 33098:12443, - 33099:12444, - 33100:180, - 33101:65344, - 33102:168, - 33103:65342, - 33104:65507, - 33105:65343, - 33106:12541, - 33107:12542, - 33108:12445, - 33109:12446, - 33110:12291, - 33111:20189, - 33112:12293, - 33113:12294, - 33114:12295, - 33115:12540, - 33116:8213, - 33117:8208, - 33118:65295, - 33119:65340, - 33120:65374, - 33121:8741, - 33122:65372, - 33123:8230, - 33124:8229, - 33125:8216, - 33126:8217, - 33127:8220, - 33128:8221, - 33129:65288, - 33130:65289, - 33131:12308, - 33132:12309, - 33133:65339, - 33134:65341, - 33135:65371, - 33136:65373, - 33137:12296, - 33138:12297, - 33139:12298, - 33140:12299, - 33141:12300, - 33142:12301, - 33143:12302, - 33144:12303, - 33145:12304, - 33146:12305, - 33147:65291, - 33148:65293, - 33149:177, - 33150:215, - 33152:247, - 33153:65309, - 33154:8800, - 33155:65308, - 33156:65310, - 33157:8806, - 33158:8807, - 33159:8734, - 33160:8756, - 33161:9794, - 33162:9792, - 33163:176, - 33164:8242, - 33165:8243, - 33166:8451, - 33167:65509, - 33168:65284, - 33169:65504, - 33170:65505, - 33171:65285, - 33172:65283, - 33173:65286, - 33174:65290, - 33175:65312, - 33176:167, - 33177:9734, - 33178:9733, - 33179:9675, - 33180:9679, - 33181:9678, - 33182:9671, - 33183:9670, - 33184:9633, - 33185:9632, - 33186:9651, - 33187:9650, - 33188:9661, - 33189:9660, - 33190:8251, - 33191:12306, - 33192:8594, - 33193:8592, - 33194:8593, - 33195:8595, - 33196:12307, - 33208:8712, - 33209:8715, - 33210:8838, - 33211:8839, - 33212:8834, - 33213:8835, - 33214:8746, - 33215:8745, - 33224:8743, - 33225:8744, - 33226:65506, - 33227:8658, - 33228:8660, - 33229:8704, - 33230:8707, - 33242:8736, - 33243:8869, - 33244:8978, - 33245:8706, - 33246:8711, - 33247:8801, - 33248:8786, - 33249:8810, - 33250:8811, - 33251:8730, - 33252:8765, - 33253:8733, - 33254:8757, - 33255:8747, - 33256:8748, - 33264:8491, - 33265:8240, - 33266:9839, - 33267:9837, - 33268:9834, - 33269:8224, - 33270:8225, - 33271:182, - 33276:9711, - 33359:65296, - 33360:65297, - 33361:65298, - 33362:65299, - 33363:65300, - 33364:65301, - 33365:65302, - 33366:65303, - 33367:65304, - 33368:65305, - 33376:65313, - 33377:65314, - 33378:65315, - 33379:65316, - 33380:65317, - 33381:65318, - 33382:65319, - 33383:65320, - 33384:65321, - 33385:65322, - 33386:65323, - 33387:65324, - 33388:65325, - 33389:65326, - 33390:65327, - 33391:65328, - 33392:65329, - 33393:65330, - 33394:65331, - 33395:65332, - 33396:65333, - 33397:65334, - 33398:65335, - 33399:65336, - 33400:65337, - 33401:65338, - 33409:65345, - 33410:65346, - 33411:65347, - 33412:65348, - 33413:65349, - 33414:65350, - 33415:65351, - 33416:65352, - 33417:65353, - 33418:65354, - 33419:65355, - 33420:65356, - 33421:65357, - 33422:65358, - 33423:65359, - 33424:65360, - 33425:65361, - 33426:65362, - 33427:65363, - 33428:65364, - 33429:65365, - 33430:65366, - 33431:65367, - 33432:65368, - 33433:65369, - 33434:65370, - 33439:12353, - 33440:12354, - 33441:12355, - 33442:12356, - 33443:12357, - 33444:12358, - 33445:12359, - 33446:12360, - 33447:12361, - 33448:12362, - 33449:12363, - 33450:12364, - 33451:12365, - 33452:12366, - 33453:12367, - 33454:12368, - 33455:12369, - 33456:12370, - 33457:12371, - 33458:12372, - 33459:12373, - 33460:12374, - 33461:12375, - 33462:12376, - 33463:12377, - 33464:12378, - 33465:12379, - 33466:12380, - 33467:12381, - 33468:12382, - 33469:12383, - 33470:12384, - 33471:12385, - 33472:12386, - 33473:12387, - 33474:12388, - 33475:12389, - 33476:12390, - 33477:12391, - 33478:12392, - 33479:12393, - 33480:12394, - 33481:12395, - 33482:12396, - 33483:12397, - 33484:12398, - 33485:12399, - 33486:12400, - 33487:12401, - 33488:12402, - 33489:12403, - 33490:12404, - 33491:12405, - 33492:12406, - 33493:12407, - 33494:12408, - 33495:12409, - 33496:12410, - 33497:12411, - 33498:12412, - 33499:12413, - 33500:12414, - 33501:12415, - 33502:12416, - 33503:12417, - 33504:12418, - 33505:12419, - 33506:12420, - 33507:12421, - 33508:12422, - 33509:12423, - 33510:12424, - 33511:12425, - 33512:12426, - 33513:12427, - 33514:12428, - 33515:12429, - 33516:12430, - 33517:12431, - 33518:12432, - 33519:12433, - 33520:12434, - 33521:12435, - 33600:12449, - 33601:12450, - 33602:12451, - 33603:12452, - 33604:12453, - 33605:12454, - 33606:12455, - 33607:12456, - 33608:12457, - 33609:12458, - 33610:12459, - 33611:12460, - 33612:12461, - 33613:12462, - 33614:12463, - 33615:12464, - 33616:12465, - 33617:12466, - 33618:12467, - 33619:12468, - 33620:12469, - 33621:12470, - 33622:12471, - 33623:12472, - 33624:12473, - 33625:12474, - 33626:12475, - 33627:12476, - 33628:12477, - 33629:12478, - 33630:12479, - 33631:12480, - 33632:12481, - 33633:12482, - 33634:12483, - 33635:12484, - 33636:12485, - 33637:12486, - 33638:12487, - 33639:12488, - 33640:12489, - 33641:12490, - 33642:12491, - 33643:12492, - 33644:12493, - 33645:12494, - 33646:12495, - 33647:12496, - 33648:12497, - 33649:12498, - 33650:12499, - 33651:12500, - 33652:12501, - 33653:12502, - 33654:12503, - 33655:12504, - 33656:12505, - 33657:12506, - 33658:12507, - 33659:12508, - 33660:12509, - 33661:12510, - 33662:12511, - 33664:12512, - 33665:12513, - 33666:12514, - 33667:12515, - 33668:12516, - 33669:12517, - 33670:12518, - 33671:12519, - 33672:12520, - 33673:12521, - 33674:12522, - 33675:12523, - 33676:12524, - 33677:12525, - 33678:12526, - 33679:12527, - 33680:12528, - 33681:12529, - 33682:12530, - 33683:12531, - 33684:12532, - 33685:12533, - 33686:12534, - 33695:913, - 33696:914, - 33697:915, - 33698:916, - 33699:917, - 33700:918, - 33701:919, - 33702:920, - 33703:921, - 33704:922, - 33705:923, - 33706:924, - 33707:925, - 33708:926, - 33709:927, - 33710:928, - 33711:929, - 33712:931, - 33713:932, - 33714:933, - 33715:934, - 33716:935, - 33717:936, - 33718:937, - 33727:945, - 33728:946, - 33729:947, - 33730:948, - 33731:949, - 33732:950, - 33733:951, - 33734:952, - 33735:953, - 33736:954, - 33737:955, - 33738:956, - 33739:957, - 33740:958, - 33741:959, - 33742:960, - 33743:961, - 33744:963, - 33745:964, - 33746:965, - 33747:966, - 33748:967, - 33749:968, - 33750:969, - 33856:1040, - 33857:1041, - 33858:1042, - 33859:1043, - 33860:1044, - 33861:1045, - 33862:1025, - 33863:1046, - 33864:1047, - 33865:1048, - 33866:1049, - 33867:1050, - 33868:1051, - 33869:1052, - 33870:1053, - 33871:1054, - 33872:1055, - 33873:1056, - 33874:1057, - 33875:1058, - 33876:1059, - 33877:1060, - 33878:1061, - 33879:1062, - 33880:1063, - 33881:1064, - 33882:1065, - 33883:1066, - 33884:1067, - 33885:1068, - 33886:1069, - 33887:1070, - 33888:1071, - 33904:1072, - 33905:1073, - 33906:1074, - 33907:1075, - 33908:1076, - 33909:1077, - 33910:1105, - 33911:1078, - 33912:1079, - 33913:1080, - 33914:1081, - 33915:1082, - 33916:1083, - 33917:1084, - 33918:1085, - 33920:1086, - 33921:1087, - 33922:1088, - 33923:1089, - 33924:1090, - 33925:1091, - 33926:1092, - 33927:1093, - 33928:1094, - 33929:1095, - 33930:1096, - 33931:1097, - 33932:1098, - 33933:1099, - 33934:1100, - 33935:1101, - 33936:1102, - 33937:1103, - 33951:9472, - 33952:9474, - 33953:9484, - 33954:9488, - 33955:9496, - 33956:9492, - 33957:9500, - 33958:9516, - 33959:9508, - 33960:9524, - 33961:9532, - 33962:9473, - 33963:9475, - 33964:9487, - 33965:9491, - 33966:9499, - 33967:9495, - 33968:9507, - 33969:9523, - 33970:9515, - 33971:9531, - 33972:9547, - 33973:9504, - 33974:9519, - 33975:9512, - 33976:9527, - 33977:9535, - 33978:9501, - 33979:9520, - 33980:9509, - 33981:9528, - 33982:9538, - 34624:9312, - 34625:9313, - 34626:9314, - 34627:9315, - 34628:9316, - 34629:9317, - 34630:9318, - 34631:9319, - 34632:9320, - 34633:9321, - 34634:9322, - 34635:9323, - 34636:9324, - 34637:9325, - 34638:9326, - 34639:9327, - 34640:9328, - 34641:9329, - 34642:9330, - 34643:9331, - 34644:8544, - 34645:8545, - 34646:8546, - 34647:8547, - 34648:8548, - 34649:8549, - 34650:8550, - 34651:8551, - 34652:8552, - 34653:8553, - 34655:13129, - 34656:13076, - 34657:13090, - 34658:13133, - 34659:13080, - 34660:13095, - 34661:13059, - 34662:13110, - 34663:13137, - 34664:13143, - 34665:13069, - 34666:13094, - 34667:13091, - 34668:13099, - 34669:13130, - 34670:13115, - 34671:13212, - 34672:13213, - 34673:13214, - 34674:13198, - 34675:13199, - 34676:13252, - 34677:13217, - 34686:13179, - 34688:12317, - 34689:12319, - 34690:8470, - 34691:13261, - 34692:8481, - 34693:12964, - 34694:12965, - 34695:12966, - 34696:12967, - 34697:12968, - 34698:12849, - 34699:12850, - 34700:12857, - 34701:13182, - 34702:13181, - 34703:13180, - 34704:8786, - 34705:8801, - 34706:8747, - 34707:8750, - 34708:8721, - 34709:8730, - 34710:8869, - 34711:8736, - 34712:8735, - 34713:8895, - 34714:8757, - 34715:8745, - 34716:8746, - 34975:20124, - 34976:21782, - 34977:23043, - 34978:38463, - 34979:21696, - 34980:24859, - 34981:25384, - 34982:23030, - 34983:36898, - 34984:33909, - 34985:33564, - 34986:31312, - 34987:24746, - 34988:25569, - 34989:28197, - 34990:26093, - 34991:33894, - 34992:33446, - 34993:39925, - 34994:26771, - 34995:22311, - 34996:26017, - 34997:25201, - 34998:23451, - 34999:22992, - 35000:34427, - 35001:39156, - 35002:32098, - 35003:32190, - 35004:39822, - 35005:25110, - 35006:31903, - 35007:34999, - 35008:23433, - 35009:24245, - 35010:25353, - 35011:26263, - 35012:26696, - 35013:38343, - 35014:38797, - 35015:26447, - 35016:20197, - 35017:20234, - 35018:20301, - 35019:20381, - 35020:20553, - 35021:22258, - 35022:22839, - 35023:22996, - 35024:23041, - 35025:23561, - 35026:24799, - 35027:24847, - 35028:24944, - 35029:26131, - 35030:26885, - 35031:28858, - 35032:30031, - 35033:30064, - 35034:31227, - 35035:32173, - 35036:32239, - 35037:32963, - 35038:33806, - 35039:34915, - 35040:35586, - 35041:36949, - 35042:36986, - 35043:21307, - 35044:20117, - 35045:20133, - 35046:22495, - 35047:32946, - 35048:37057, - 35049:30959, - 35050:19968, - 35051:22769, - 35052:28322, - 35053:36920, - 35054:31282, - 35055:33576, - 35056:33419, - 35057:39983, - 35058:20801, - 35059:21360, - 35060:21693, - 35061:21729, - 35062:22240, - 35063:23035, - 35064:24341, - 35065:39154, - 35066:28139, - 35067:32996, - 35068:34093, - 35136:38498, - 35137:38512, - 35138:38560, - 35139:38907, - 35140:21515, - 35141:21491, - 35142:23431, - 35143:28879, - 35144:32701, - 35145:36802, - 35146:38632, - 35147:21359, - 35148:40284, - 35149:31418, - 35150:19985, - 35151:30867, - 35152:33276, - 35153:28198, - 35154:22040, - 35155:21764, - 35156:27421, - 35157:34074, - 35158:39995, - 35159:23013, - 35160:21417, - 35161:28006, - 35162:29916, - 35163:38287, - 35164:22082, - 35165:20113, - 35166:36939, - 35167:38642, - 35168:33615, - 35169:39180, - 35170:21473, - 35171:21942, - 35172:23344, - 35173:24433, - 35174:26144, - 35175:26355, - 35176:26628, - 35177:27704, - 35178:27891, - 35179:27945, - 35180:29787, - 35181:30408, - 35182:31310, - 35183:38964, - 35184:33521, - 35185:34907, - 35186:35424, - 35187:37613, - 35188:28082, - 35189:30123, - 35190:30410, - 35191:39365, - 35192:24742, - 35193:35585, - 35194:36234, - 35195:38322, - 35196:27022, - 35197:21421, - 35198:20870, - 35200:22290, - 35201:22576, - 35202:22852, - 35203:23476, - 35204:24310, - 35205:24616, - 35206:25513, - 35207:25588, - 35208:27839, - 35209:28436, - 35210:28814, - 35211:28948, - 35212:29017, - 35213:29141, - 35214:29503, - 35215:32257, - 35216:33398, - 35217:33489, - 35218:34199, - 35219:36960, - 35220:37467, - 35221:40219, - 35222:22633, - 35223:26044, - 35224:27738, - 35225:29989, - 35226:20985, - 35227:22830, - 35228:22885, - 35229:24448, - 35230:24540, - 35231:25276, - 35232:26106, - 35233:27178, - 35234:27431, - 35235:27572, - 35236:29579, - 35237:32705, - 35238:35158, - 35239:40236, - 35240:40206, - 35241:40644, - 35242:23713, - 35243:27798, - 35244:33659, - 35245:20740, - 35246:23627, - 35247:25014, - 35248:33222, - 35249:26742, - 35250:29281, - 35251:20057, - 35252:20474, - 35253:21368, - 35254:24681, - 35255:28201, - 35256:31311, - 35257:38899, - 35258:19979, - 35259:21270, - 35260:20206, - 35261:20309, - 35262:20285, - 35263:20385, - 35264:20339, - 35265:21152, - 35266:21487, - 35267:22025, - 35268:22799, - 35269:23233, - 35270:23478, - 35271:23521, - 35272:31185, - 35273:26247, - 35274:26524, - 35275:26550, - 35276:27468, - 35277:27827, - 35278:28779, - 35279:29634, - 35280:31117, - 35281:31166, - 35282:31292, - 35283:31623, - 35284:33457, - 35285:33499, - 35286:33540, - 35287:33655, - 35288:33775, - 35289:33747, - 35290:34662, - 35291:35506, - 35292:22057, - 35293:36008, - 35294:36838, - 35295:36942, - 35296:38686, - 35297:34442, - 35298:20420, - 35299:23784, - 35300:25105, - 35301:29273, - 35302:30011, - 35303:33253, - 35304:33469, - 35305:34558, - 35306:36032, - 35307:38597, - 35308:39187, - 35309:39381, - 35310:20171, - 35311:20250, - 35312:35299, - 35313:22238, - 35314:22602, - 35315:22730, - 35316:24315, - 35317:24555, - 35318:24618, - 35319:24724, - 35320:24674, - 35321:25040, - 35322:25106, - 35323:25296, - 35324:25913, - 35392:39745, - 35393:26214, - 35394:26800, - 35395:28023, - 35396:28784, - 35397:30028, - 35398:30342, - 35399:32117, - 35400:33445, - 35401:34809, - 35402:38283, - 35403:38542, - 35404:35997, - 35405:20977, - 35406:21182, - 35407:22806, - 35408:21683, - 35409:23475, - 35410:23830, - 35411:24936, - 35412:27010, - 35413:28079, - 35414:30861, - 35415:33995, - 35416:34903, - 35417:35442, - 35418:37799, - 35419:39608, - 35420:28012, - 35421:39336, - 35422:34521, - 35423:22435, - 35424:26623, - 35425:34510, - 35426:37390, - 35427:21123, - 35428:22151, - 35429:21508, - 35430:24275, - 35431:25313, - 35432:25785, - 35433:26684, - 35434:26680, - 35435:27579, - 35436:29554, - 35437:30906, - 35438:31339, - 35439:35226, - 35440:35282, - 35441:36203, - 35442:36611, - 35443:37101, - 35444:38307, - 35445:38548, - 35446:38761, - 35447:23398, - 35448:23731, - 35449:27005, - 35450:38989, - 35451:38990, - 35452:25499, - 35453:31520, - 35454:27179, - 35456:27263, - 35457:26806, - 35458:39949, - 35459:28511, - 35460:21106, - 35461:21917, - 35462:24688, - 35463:25324, - 35464:27963, - 35465:28167, - 35466:28369, - 35467:33883, - 35468:35088, - 35469:36676, - 35470:19988, - 35471:39993, - 35472:21494, - 35473:26907, - 35474:27194, - 35475:38788, - 35476:26666, - 35477:20828, - 35478:31427, - 35479:33970, - 35480:37340, - 35481:37772, - 35482:22107, - 35483:40232, - 35484:26658, - 35485:33541, - 35486:33841, - 35487:31909, - 35488:21000, - 35489:33477, - 35490:29926, - 35491:20094, - 35492:20355, - 35493:20896, - 35494:23506, - 35495:21002, - 35496:21208, - 35497:21223, - 35498:24059, - 35499:21914, - 35500:22570, - 35501:23014, - 35502:23436, - 35503:23448, - 35504:23515, - 35505:24178, - 35506:24185, - 35507:24739, - 35508:24863, - 35509:24931, - 35510:25022, - 35511:25563, - 35512:25954, - 35513:26577, - 35514:26707, - 35515:26874, - 35516:27454, - 35517:27475, - 35518:27735, - 35519:28450, - 35520:28567, - 35521:28485, - 35522:29872, - 35523:29976, - 35524:30435, - 35525:30475, - 35526:31487, - 35527:31649, - 35528:31777, - 35529:32233, - 35530:32566, - 35531:32752, - 35532:32925, - 35533:33382, - 35534:33694, - 35535:35251, - 35536:35532, - 35537:36011, - 35538:36996, - 35539:37969, - 35540:38291, - 35541:38289, - 35542:38306, - 35543:38501, - 35544:38867, - 35545:39208, - 35546:33304, - 35547:20024, - 35548:21547, - 35549:23736, - 35550:24012, - 35551:29609, - 35552:30284, - 35553:30524, - 35554:23721, - 35555:32747, - 35556:36107, - 35557:38593, - 35558:38929, - 35559:38996, - 35560:39000, - 35561:20225, - 35562:20238, - 35563:21361, - 35564:21916, - 35565:22120, - 35566:22522, - 35567:22855, - 35568:23305, - 35569:23492, - 35570:23696, - 35571:24076, - 35572:24190, - 35573:24524, - 35574:25582, - 35575:26426, - 35576:26071, - 35577:26082, - 35578:26399, - 35579:26827, - 35580:26820, - 35648:27231, - 35649:24112, - 35650:27589, - 35651:27671, - 35652:27773, - 35653:30079, - 35654:31048, - 35655:23395, - 35656:31232, - 35657:32000, - 35658:24509, - 35659:35215, - 35660:35352, - 35661:36020, - 35662:36215, - 35663:36556, - 35664:36637, - 35665:39138, - 35666:39438, - 35667:39740, - 35668:20096, - 35669:20605, - 35670:20736, - 35671:22931, - 35672:23452, - 35673:25135, - 35674:25216, - 35675:25836, - 35676:27450, - 35677:29344, - 35678:30097, - 35679:31047, - 35680:32681, - 35681:34811, - 35682:35516, - 35683:35696, - 35684:25516, - 35685:33738, - 35686:38816, - 35687:21513, - 35688:21507, - 35689:21931, - 35690:26708, - 35691:27224, - 35692:35440, - 35693:30759, - 35694:26485, - 35695:40653, - 35696:21364, - 35697:23458, - 35698:33050, - 35699:34384, - 35700:36870, - 35701:19992, - 35702:20037, - 35703:20167, - 35704:20241, - 35705:21450, - 35706:21560, - 35707:23470, - 35708:24339, - 35709:24613, - 35710:25937, - 35712:26429, - 35713:27714, - 35714:27762, - 35715:27875, - 35716:28792, - 35717:29699, - 35718:31350, - 35719:31406, - 35720:31496, - 35721:32026, - 35722:31998, - 35723:32102, - 35724:26087, - 35725:29275, - 35726:21435, - 35727:23621, - 35728:24040, - 35729:25298, - 35730:25312, - 35731:25369, - 35732:28192, - 35733:34394, - 35734:35377, - 35735:36317, - 35736:37624, - 35737:28417, - 35738:31142, - 35739:39770, - 35740:20136, - 35741:20139, - 35742:20140, - 35743:20379, - 35744:20384, - 35745:20689, - 35746:20807, - 35747:31478, - 35748:20849, - 35749:20982, - 35750:21332, - 35751:21281, - 35752:21375, - 35753:21483, - 35754:21932, - 35755:22659, - 35756:23777, - 35757:24375, - 35758:24394, - 35759:24623, - 35760:24656, - 35761:24685, - 35762:25375, - 35763:25945, - 35764:27211, - 35765:27841, - 35766:29378, - 35767:29421, - 35768:30703, - 35769:33016, - 35770:33029, - 35771:33288, - 35772:34126, - 35773:37111, - 35774:37857, - 35775:38911, - 35776:39255, - 35777:39514, - 35778:20208, - 35779:20957, - 35780:23597, - 35781:26241, - 35782:26989, - 35783:23616, - 35784:26354, - 35785:26997, - 35786:29577, - 35787:26704, - 35788:31873, - 35789:20677, - 35790:21220, - 35791:22343, - 35792:24062, - 35793:37670, - 35794:26020, - 35795:27427, - 35796:27453, - 35797:29748, - 35798:31105, - 35799:31165, - 35800:31563, - 35801:32202, - 35802:33465, - 35803:33740, - 35804:34943, - 35805:35167, - 35806:35641, - 35807:36817, - 35808:37329, - 35809:21535, - 35810:37504, - 35811:20061, - 35812:20534, - 35813:21477, - 35814:21306, - 35815:29399, - 35816:29590, - 35817:30697, - 35818:33510, - 35819:36527, - 35820:39366, - 35821:39368, - 35822:39378, - 35823:20855, - 35824:24858, - 35825:34398, - 35826:21936, - 35827:31354, - 35828:20598, - 35829:23507, - 35830:36935, - 35831:38533, - 35832:20018, - 35833:27355, - 35834:37351, - 35835:23633, - 35836:23624, - 35904:25496, - 35905:31391, - 35906:27795, - 35907:38772, - 35908:36705, - 35909:31402, - 35910:29066, - 35911:38536, - 35912:31874, - 35913:26647, - 35914:32368, - 35915:26705, - 35916:37740, - 35917:21234, - 35918:21531, - 35919:34219, - 35920:35347, - 35921:32676, - 35922:36557, - 35923:37089, - 35924:21350, - 35925:34952, - 35926:31041, - 35927:20418, - 35928:20670, - 35929:21009, - 35930:20804, - 35931:21843, - 35932:22317, - 35933:29674, - 35934:22411, - 35935:22865, - 35936:24418, - 35937:24452, - 35938:24693, - 35939:24950, - 35940:24935, - 35941:25001, - 35942:25522, - 35943:25658, - 35944:25964, - 35945:26223, - 35946:26690, - 35947:28179, - 35948:30054, - 35949:31293, - 35950:31995, - 35951:32076, - 35952:32153, - 35953:32331, - 35954:32619, - 35955:33550, - 35956:33610, - 35957:34509, - 35958:35336, - 35959:35427, - 35960:35686, - 35961:36605, - 35962:38938, - 35963:40335, - 35964:33464, - 35965:36814, - 35966:39912, - 35968:21127, - 35969:25119, - 35970:25731, - 35971:28608, - 35972:38553, - 35973:26689, - 35974:20625, - 35975:27424, - 35976:27770, - 35977:28500, - 35978:31348, - 35979:32080, - 35980:34880, - 35981:35363, - 35982:26376, - 35983:20214, - 35984:20537, - 35985:20518, - 35986:20581, - 35987:20860, - 35988:21048, - 35989:21091, - 35990:21927, - 35991:22287, - 35992:22533, - 35993:23244, - 35994:24314, - 35995:25010, - 35996:25080, - 35997:25331, - 35998:25458, - 35999:26908, - 36000:27177, - 36001:29309, - 36002:29356, - 36003:29486, - 36004:30740, - 36005:30831, - 36006:32121, - 36007:30476, - 36008:32937, - 36009:35211, - 36010:35609, - 36011:36066, - 36012:36562, - 36013:36963, - 36014:37749, - 36015:38522, - 36016:38997, - 36017:39443, - 36018:40568, - 36019:20803, - 36020:21407, - 36021:21427, - 36022:24187, - 36023:24358, - 36024:28187, - 36025:28304, - 36026:29572, - 36027:29694, - 36028:32067, - 36029:33335, - 36030:35328, - 36031:35578, - 36032:38480, - 36033:20046, - 36034:20491, - 36035:21476, - 36036:21628, - 36037:22266, - 36038:22993, - 36039:23396, - 36040:24049, - 36041:24235, - 36042:24359, - 36043:25144, - 36044:25925, - 36045:26543, - 36046:28246, - 36047:29392, - 36048:31946, - 36049:34996, - 36050:32929, - 36051:32993, - 36052:33776, - 36053:34382, - 36054:35463, - 36055:36328, - 36056:37431, - 36057:38599, - 36058:39015, - 36059:40723, - 36060:20116, - 36061:20114, - 36062:20237, - 36063:21320, - 36064:21577, - 36065:21566, - 36066:23087, - 36067:24460, - 36068:24481, - 36069:24735, - 36070:26791, - 36071:27278, - 36072:29786, - 36073:30849, - 36074:35486, - 36075:35492, - 36076:35703, - 36077:37264, - 36078:20062, - 36079:39881, - 36080:20132, - 36081:20348, - 36082:20399, - 36083:20505, - 36084:20502, - 36085:20809, - 36086:20844, - 36087:21151, - 36088:21177, - 36089:21246, - 36090:21402, - 36091:21475, - 36092:21521, - 36160:21518, - 36161:21897, - 36162:22353, - 36163:22434, - 36164:22909, - 36165:23380, - 36166:23389, - 36167:23439, - 36168:24037, - 36169:24039, - 36170:24055, - 36171:24184, - 36172:24195, - 36173:24218, - 36174:24247, - 36175:24344, - 36176:24658, - 36177:24908, - 36178:25239, - 36179:25304, - 36180:25511, - 36181:25915, - 36182:26114, - 36183:26179, - 36184:26356, - 36185:26477, - 36186:26657, - 36187:26775, - 36188:27083, - 36189:27743, - 36190:27946, - 36191:28009, - 36192:28207, - 36193:28317, - 36194:30002, - 36195:30343, - 36196:30828, - 36197:31295, - 36198:31968, - 36199:32005, - 36200:32024, - 36201:32094, - 36202:32177, - 36203:32789, - 36204:32771, - 36205:32943, - 36206:32945, - 36207:33108, - 36208:33167, - 36209:33322, - 36210:33618, - 36211:34892, - 36212:34913, - 36213:35611, - 36214:36002, - 36215:36092, - 36216:37066, - 36217:37237, - 36218:37489, - 36219:30783, - 36220:37628, - 36221:38308, - 36222:38477, - 36224:38917, - 36225:39321, - 36226:39640, - 36227:40251, - 36228:21083, - 36229:21163, - 36230:21495, - 36231:21512, - 36232:22741, - 36233:25335, - 36234:28640, - 36235:35946, - 36236:36703, - 36237:40633, - 36238:20811, - 36239:21051, - 36240:21578, - 36241:22269, - 36242:31296, - 36243:37239, - 36244:40288, - 36245:40658, - 36246:29508, - 36247:28425, - 36248:33136, - 36249:29969, - 36250:24573, - 36251:24794, - 36252:39592, - 36253:29403, - 36254:36796, - 36255:27492, - 36256:38915, - 36257:20170, - 36258:22256, - 36259:22372, - 36260:22718, - 36261:23130, - 36262:24680, - 36263:25031, - 36264:26127, - 36265:26118, - 36266:26681, - 36267:26801, - 36268:28151, - 36269:30165, - 36270:32058, - 36271:33390, - 36272:39746, - 36273:20123, - 36274:20304, - 36275:21449, - 36276:21766, - 36277:23919, - 36278:24038, - 36279:24046, - 36280:26619, - 36281:27801, - 36282:29811, - 36283:30722, - 36284:35408, - 36285:37782, - 36286:35039, - 36287:22352, - 36288:24231, - 36289:25387, - 36290:20661, - 36291:20652, - 36292:20877, - 36293:26368, - 36294:21705, - 36295:22622, - 36296:22971, - 36297:23472, - 36298:24425, - 36299:25165, - 36300:25505, - 36301:26685, - 36302:27507, - 36303:28168, - 36304:28797, - 36305:37319, - 36306:29312, - 36307:30741, - 36308:30758, - 36309:31085, - 36310:25998, - 36311:32048, - 36312:33756, - 36313:35009, - 36314:36617, - 36315:38555, - 36316:21092, - 36317:22312, - 36318:26448, - 36319:32618, - 36320:36001, - 36321:20916, - 36322:22338, - 36323:38442, - 36324:22586, - 36325:27018, - 36326:32948, - 36327:21682, - 36328:23822, - 36329:22524, - 36330:30869, - 36331:40442, - 36332:20316, - 36333:21066, - 36334:21643, - 36335:25662, - 36336:26152, - 36337:26388, - 36338:26613, - 36339:31364, - 36340:31574, - 36341:32034, - 36342:37679, - 36343:26716, - 36344:39853, - 36345:31545, - 36346:21273, - 36347:20874, - 36348:21047, - 36416:23519, - 36417:25334, - 36418:25774, - 36419:25830, - 36420:26413, - 36421:27578, - 36422:34217, - 36423:38609, - 36424:30352, - 36425:39894, - 36426:25420, - 36427:37638, - 36428:39851, - 36429:30399, - 36430:26194, - 36431:19977, - 36432:20632, - 36433:21442, - 36434:23665, - 36435:24808, - 36436:25746, - 36437:25955, - 36438:26719, - 36439:29158, - 36440:29642, - 36441:29987, - 36442:31639, - 36443:32386, - 36444:34453, - 36445:35715, - 36446:36059, - 36447:37240, - 36448:39184, - 36449:26028, - 36450:26283, - 36451:27531, - 36452:20181, - 36453:20180, - 36454:20282, - 36455:20351, - 36456:21050, - 36457:21496, - 36458:21490, - 36459:21987, - 36460:22235, - 36461:22763, - 36462:22987, - 36463:22985, - 36464:23039, - 36465:23376, - 36466:23629, - 36467:24066, - 36468:24107, - 36469:24535, - 36470:24605, - 36471:25351, - 36472:25903, - 36473:23388, - 36474:26031, - 36475:26045, - 36476:26088, - 36477:26525, - 36478:27490, - 36480:27515, - 36481:27663, - 36482:29509, - 36483:31049, - 36484:31169, - 36485:31992, - 36486:32025, - 36487:32043, - 36488:32930, - 36489:33026, - 36490:33267, - 36491:35222, - 36492:35422, - 36493:35433, - 36494:35430, - 36495:35468, - 36496:35566, - 36497:36039, - 36498:36060, - 36499:38604, - 36500:39164, - 36501:27503, - 36502:20107, - 36503:20284, - 36504:20365, - 36505:20816, - 36506:23383, - 36507:23546, - 36508:24904, - 36509:25345, - 36510:26178, - 36511:27425, - 36512:28363, - 36513:27835, - 36514:29246, - 36515:29885, - 36516:30164, - 36517:30913, - 36518:31034, - 36519:32780, - 36520:32819, - 36521:33258, - 36522:33940, - 36523:36766, - 36524:27728, - 36525:40575, - 36526:24335, - 36527:35672, - 36528:40235, - 36529:31482, - 36530:36600, - 36531:23437, - 36532:38635, - 36533:19971, - 36534:21489, - 36535:22519, - 36536:22833, - 36537:23241, - 36538:23460, - 36539:24713, - 36540:28287, - 36541:28422, - 36542:30142, - 36543:36074, - 36544:23455, - 36545:34048, - 36546:31712, - 36547:20594, - 36548:26612, - 36549:33437, - 36550:23649, - 36551:34122, - 36552:32286, - 36553:33294, - 36554:20889, - 36555:23556, - 36556:25448, - 36557:36198, - 36558:26012, - 36559:29038, - 36560:31038, - 36561:32023, - 36562:32773, - 36563:35613, - 36564:36554, - 36565:36974, - 36566:34503, - 36567:37034, - 36568:20511, - 36569:21242, - 36570:23610, - 36571:26451, - 36572:28796, - 36573:29237, - 36574:37196, - 36575:37320, - 36576:37675, - 36577:33509, - 36578:23490, - 36579:24369, - 36580:24825, - 36581:20027, - 36582:21462, - 36583:23432, - 36584:25163, - 36585:26417, - 36586:27530, - 36587:29417, - 36588:29664, - 36589:31278, - 36590:33131, - 36591:36259, - 36592:37202, - 36593:39318, - 36594:20754, - 36595:21463, - 36596:21610, - 36597:23551, - 36598:25480, - 36599:27193, - 36600:32172, - 36601:38656, - 36602:22234, - 36603:21454, - 36604:21608, - 36672:23447, - 36673:23601, - 36674:24030, - 36675:20462, - 36676:24833, - 36677:25342, - 36678:27954, - 36679:31168, - 36680:31179, - 36681:32066, - 36682:32333, - 36683:32722, - 36684:33261, - 36685:33311, - 36686:33936, - 36687:34886, - 36688:35186, - 36689:35728, - 36690:36468, - 36691:36655, - 36692:36913, - 36693:37195, - 36694:37228, - 36695:38598, - 36696:37276, - 36697:20160, - 36698:20303, - 36699:20805, - 36700:21313, - 36701:24467, - 36702:25102, - 36703:26580, - 36704:27713, - 36705:28171, - 36706:29539, - 36707:32294, - 36708:37325, - 36709:37507, - 36710:21460, - 36711:22809, - 36712:23487, - 36713:28113, - 36714:31069, - 36715:32302, - 36716:31899, - 36717:22654, - 36718:29087, - 36719:20986, - 36720:34899, - 36721:36848, - 36722:20426, - 36723:23803, - 36724:26149, - 36725:30636, - 36726:31459, - 36727:33308, - 36728:39423, - 36729:20934, - 36730:24490, - 36731:26092, - 36732:26991, - 36733:27529, - 36734:28147, - 36736:28310, - 36737:28516, - 36738:30462, - 36739:32020, - 36740:24033, - 36741:36981, - 36742:37255, - 36743:38918, - 36744:20966, - 36745:21021, - 36746:25152, - 36747:26257, - 36748:26329, - 36749:28186, - 36750:24246, - 36751:32210, - 36752:32626, - 36753:26360, - 36754:34223, - 36755:34295, - 36756:35576, - 36757:21161, - 36758:21465, - 36759:22899, - 36760:24207, - 36761:24464, - 36762:24661, - 36763:37604, - 36764:38500, - 36765:20663, - 36766:20767, - 36767:21213, - 36768:21280, - 36769:21319, - 36770:21484, - 36771:21736, - 36772:21830, - 36773:21809, - 36774:22039, - 36775:22888, - 36776:22974, - 36777:23100, - 36778:23477, - 36779:23558, - 36780:23567, - 36781:23569, - 36782:23578, - 36783:24196, - 36784:24202, - 36785:24288, - 36786:24432, - 36787:25215, - 36788:25220, - 36789:25307, - 36790:25484, - 36791:25463, - 36792:26119, - 36793:26124, - 36794:26157, - 36795:26230, - 36796:26494, - 36797:26786, - 36798:27167, - 36799:27189, - 36800:27836, - 36801:28040, - 36802:28169, - 36803:28248, - 36804:28988, - 36805:28966, - 36806:29031, - 36807:30151, - 36808:30465, - 36809:30813, - 36810:30977, - 36811:31077, - 36812:31216, - 36813:31456, - 36814:31505, - 36815:31911, - 36816:32057, - 36817:32918, - 36818:33750, - 36819:33931, - 36820:34121, - 36821:34909, - 36822:35059, - 36823:35359, - 36824:35388, - 36825:35412, - 36826:35443, - 36827:35937, - 36828:36062, - 36829:37284, - 36830:37478, - 36831:37758, - 36832:37912, - 36833:38556, - 36834:38808, - 36835:19978, - 36836:19976, - 36837:19998, - 36838:20055, - 36839:20887, - 36840:21104, - 36841:22478, - 36842:22580, - 36843:22732, - 36844:23330, - 36845:24120, - 36846:24773, - 36847:25854, - 36848:26465, - 36849:26454, - 36850:27972, - 36851:29366, - 36852:30067, - 36853:31331, - 36854:33976, - 36855:35698, - 36856:37304, - 36857:37664, - 36858:22065, - 36859:22516, - 36860:39166, - 36928:25325, - 36929:26893, - 36930:27542, - 36931:29165, - 36932:32340, - 36933:32887, - 36934:33394, - 36935:35302, - 36936:39135, - 36937:34645, - 36938:36785, - 36939:23611, - 36940:20280, - 36941:20449, - 36942:20405, - 36943:21767, - 36944:23072, - 36945:23517, - 36946:23529, - 36947:24515, - 36948:24910, - 36949:25391, - 36950:26032, - 36951:26187, - 36952:26862, - 36953:27035, - 36954:28024, - 36955:28145, - 36956:30003, - 36957:30137, - 36958:30495, - 36959:31070, - 36960:31206, - 36961:32051, - 36962:33251, - 36963:33455, - 36964:34218, - 36965:35242, - 36966:35386, - 36967:36523, - 36968:36763, - 36969:36914, - 36970:37341, - 36971:38663, - 36972:20154, - 36973:20161, - 36974:20995, - 36975:22645, - 36976:22764, - 36977:23563, - 36978:29978, - 36979:23613, - 36980:33102, - 36981:35338, - 36982:36805, - 36983:38499, - 36984:38765, - 36985:31525, - 36986:35535, - 36987:38920, - 36988:37218, - 36989:22259, - 36990:21416, - 36992:36887, - 36993:21561, - 36994:22402, - 36995:24101, - 36996:25512, - 36997:27700, - 36998:28810, - 36999:30561, - 37000:31883, - 37001:32736, - 37002:34928, - 37003:36930, - 37004:37204, - 37005:37648, - 37006:37656, - 37007:38543, - 37008:29790, - 37009:39620, - 37010:23815, - 37011:23913, - 37012:25968, - 37013:26530, - 37014:36264, - 37015:38619, - 37016:25454, - 37017:26441, - 37018:26905, - 37019:33733, - 37020:38935, - 37021:38592, - 37022:35070, - 37023:28548, - 37024:25722, - 37025:23544, - 37026:19990, - 37027:28716, - 37028:30045, - 37029:26159, - 37030:20932, - 37031:21046, - 37032:21218, - 37033:22995, - 37034:24449, - 37035:24615, - 37036:25104, - 37037:25919, - 37038:25972, - 37039:26143, - 37040:26228, - 37041:26866, - 37042:26646, - 37043:27491, - 37044:28165, - 37045:29298, - 37046:29983, - 37047:30427, - 37048:31934, - 37049:32854, - 37050:22768, - 37051:35069, - 37052:35199, - 37053:35488, - 37054:35475, - 37055:35531, - 37056:36893, - 37057:37266, - 37058:38738, - 37059:38745, - 37060:25993, - 37061:31246, - 37062:33030, - 37063:38587, - 37064:24109, - 37065:24796, - 37066:25114, - 37067:26021, - 37068:26132, - 37069:26512, - 37070:30707, - 37071:31309, - 37072:31821, - 37073:32318, - 37074:33034, - 37075:36012, - 37076:36196, - 37077:36321, - 37078:36447, - 37079:30889, - 37080:20999, - 37081:25305, - 37082:25509, - 37083:25666, - 37084:25240, - 37085:35373, - 37086:31363, - 37087:31680, - 37088:35500, - 37089:38634, - 37090:32118, - 37091:33292, - 37092:34633, - 37093:20185, - 37094:20808, - 37095:21315, - 37096:21344, - 37097:23459, - 37098:23554, - 37099:23574, - 37100:24029, - 37101:25126, - 37102:25159, - 37103:25776, - 37104:26643, - 37105:26676, - 37106:27849, - 37107:27973, - 37108:27927, - 37109:26579, - 37110:28508, - 37111:29006, - 37112:29053, - 37113:26059, - 37114:31359, - 37115:31661, - 37116:32218, - 37184:32330, - 37185:32680, - 37186:33146, - 37187:33307, - 37188:33337, - 37189:34214, - 37190:35438, - 37191:36046, - 37192:36341, - 37193:36984, - 37194:36983, - 37195:37549, - 37196:37521, - 37197:38275, - 37198:39854, - 37199:21069, - 37200:21892, - 37201:28472, - 37202:28982, - 37203:20840, - 37204:31109, - 37205:32341, - 37206:33203, - 37207:31950, - 37208:22092, - 37209:22609, - 37210:23720, - 37211:25514, - 37212:26366, - 37213:26365, - 37214:26970, - 37215:29401, - 37216:30095, - 37217:30094, - 37218:30990, - 37219:31062, - 37220:31199, - 37221:31895, - 37222:32032, - 37223:32068, - 37224:34311, - 37225:35380, - 37226:38459, - 37227:36961, - 37228:40736, - 37229:20711, - 37230:21109, - 37231:21452, - 37232:21474, - 37233:20489, - 37234:21930, - 37235:22766, - 37236:22863, - 37237:29245, - 37238:23435, - 37239:23652, - 37240:21277, - 37241:24803, - 37242:24819, - 37243:25436, - 37244:25475, - 37245:25407, - 37246:25531, - 37248:25805, - 37249:26089, - 37250:26361, - 37251:24035, - 37252:27085, - 37253:27133, - 37254:28437, - 37255:29157, - 37256:20105, - 37257:30185, - 37258:30456, - 37259:31379, - 37260:31967, - 37261:32207, - 37262:32156, - 37263:32865, - 37264:33609, - 37265:33624, - 37266:33900, - 37267:33980, - 37268:34299, - 37269:35013, - 37270:36208, - 37271:36865, - 37272:36973, - 37273:37783, - 37274:38684, - 37275:39442, - 37276:20687, - 37277:22679, - 37278:24974, - 37279:33235, - 37280:34101, - 37281:36104, - 37282:36896, - 37283:20419, - 37284:20596, - 37285:21063, - 37286:21363, - 37287:24687, - 37288:25417, - 37289:26463, - 37290:28204, - 37291:36275, - 37292:36895, - 37293:20439, - 37294:23646, - 37295:36042, - 37296:26063, - 37297:32154, - 37298:21330, - 37299:34966, - 37300:20854, - 37301:25539, - 37302:23384, - 37303:23403, - 37304:23562, - 37305:25613, - 37306:26449, - 37307:36956, - 37308:20182, - 37309:22810, - 37310:22826, - 37311:27760, - 37312:35409, - 37313:21822, - 37314:22549, - 37315:22949, - 37316:24816, - 37317:25171, - 37318:26561, - 37319:33333, - 37320:26965, - 37321:38464, - 37322:39364, - 37323:39464, - 37324:20307, - 37325:22534, - 37326:23550, - 37327:32784, - 37328:23729, - 37329:24111, - 37330:24453, - 37331:24608, - 37332:24907, - 37333:25140, - 37334:26367, - 37335:27888, - 37336:28382, - 37337:32974, - 37338:33151, - 37339:33492, - 37340:34955, - 37341:36024, - 37342:36864, - 37343:36910, - 37344:38538, - 37345:40667, - 37346:39899, - 37347:20195, - 37348:21488, - 37349:22823, - 37350:31532, - 37351:37261, - 37352:38988, - 37353:40441, - 37354:28381, - 37355:28711, - 37356:21331, - 37357:21828, - 37358:23429, - 37359:25176, - 37360:25246, - 37361:25299, - 37362:27810, - 37363:28655, - 37364:29730, - 37365:35351, - 37366:37944, - 37367:28609, - 37368:35582, - 37369:33592, - 37370:20967, - 37371:34552, - 37372:21482, - 37440:21481, - 37441:20294, - 37442:36948, - 37443:36784, - 37444:22890, - 37445:33073, - 37446:24061, - 37447:31466, - 37448:36799, - 37449:26842, - 37450:35895, - 37451:29432, - 37452:40008, - 37453:27197, - 37454:35504, - 37455:20025, - 37456:21336, - 37457:22022, - 37458:22374, - 37459:25285, - 37460:25506, - 37461:26086, - 37462:27470, - 37463:28129, - 37464:28251, - 37465:28845, - 37466:30701, - 37467:31471, - 37468:31658, - 37469:32187, - 37470:32829, - 37471:32966, - 37472:34507, - 37473:35477, - 37474:37723, - 37475:22243, - 37476:22727, - 37477:24382, - 37478:26029, - 37479:26262, - 37480:27264, - 37481:27573, - 37482:30007, - 37483:35527, - 37484:20516, - 37485:30693, - 37486:22320, - 37487:24347, - 37488:24677, - 37489:26234, - 37490:27744, - 37491:30196, - 37492:31258, - 37493:32622, - 37494:33268, - 37495:34584, - 37496:36933, - 37497:39347, - 37498:31689, - 37499:30044, - 37500:31481, - 37501:31569, - 37502:33988, - 37504:36880, - 37505:31209, - 37506:31378, - 37507:33590, - 37508:23265, - 37509:30528, - 37510:20013, - 37511:20210, - 37512:23449, - 37513:24544, - 37514:25277, - 37515:26172, - 37516:26609, - 37517:27880, - 37518:34411, - 37519:34935, - 37520:35387, - 37521:37198, - 37522:37619, - 37523:39376, - 37524:27159, - 37525:28710, - 37526:29482, - 37527:33511, - 37528:33879, - 37529:36015, - 37530:19969, - 37531:20806, - 37532:20939, - 37533:21899, - 37534:23541, - 37535:24086, - 37536:24115, - 37537:24193, - 37538:24340, - 37539:24373, - 37540:24427, - 37541:24500, - 37542:25074, - 37543:25361, - 37544:26274, - 37545:26397, - 37546:28526, - 37547:29266, - 37548:30010, - 37549:30522, - 37550:32884, - 37551:33081, - 37552:33144, - 37553:34678, - 37554:35519, - 37555:35548, - 37556:36229, - 37557:36339, - 37558:37530, - 37559:38263, - 37560:38914, - 37561:40165, - 37562:21189, - 37563:25431, - 37564:30452, - 37565:26389, - 37566:27784, - 37567:29645, - 37568:36035, - 37569:37806, - 37570:38515, - 37571:27941, - 37572:22684, - 37573:26894, - 37574:27084, - 37575:36861, - 37576:37786, - 37577:30171, - 37578:36890, - 37579:22618, - 37580:26626, - 37581:25524, - 37582:27131, - 37583:20291, - 37584:28460, - 37585:26584, - 37586:36795, - 37587:34086, - 37588:32180, - 37589:37716, - 37590:26943, - 37591:28528, - 37592:22378, - 37593:22775, - 37594:23340, - 37595:32044, - 37596:29226, - 37597:21514, - 37598:37347, - 37599:40372, - 37600:20141, - 37601:20302, - 37602:20572, - 37603:20597, - 37604:21059, - 37605:35998, - 37606:21576, - 37607:22564, - 37608:23450, - 37609:24093, - 37610:24213, - 37611:24237, - 37612:24311, - 37613:24351, - 37614:24716, - 37615:25269, - 37616:25402, - 37617:25552, - 37618:26799, - 37619:27712, - 37620:30855, - 37621:31118, - 37622:31243, - 37623:32224, - 37624:33351, - 37625:35330, - 37626:35558, - 37627:36420, - 37628:36883, - 37696:37048, - 37697:37165, - 37698:37336, - 37699:40718, - 37700:27877, - 37701:25688, - 37702:25826, - 37703:25973, - 37704:28404, - 37705:30340, - 37706:31515, - 37707:36969, - 37708:37841, - 37709:28346, - 37710:21746, - 37711:24505, - 37712:25764, - 37713:36685, - 37714:36845, - 37715:37444, - 37716:20856, - 37717:22635, - 37718:22825, - 37719:23637, - 37720:24215, - 37721:28155, - 37722:32399, - 37723:29980, - 37724:36028, - 37725:36578, - 37726:39003, - 37727:28857, - 37728:20253, - 37729:27583, - 37730:28593, - 37731:30000, - 37732:38651, - 37733:20814, - 37734:21520, - 37735:22581, - 37736:22615, - 37737:22956, - 37738:23648, - 37739:24466, - 37740:26007, - 37741:26460, - 37742:28193, - 37743:30331, - 37744:33759, - 37745:36077, - 37746:36884, - 37747:37117, - 37748:37709, - 37749:30757, - 37750:30778, - 37751:21162, - 37752:24230, - 37753:22303, - 37754:22900, - 37755:24594, - 37756:20498, - 37757:20826, - 37758:20908, - 37760:20941, - 37761:20992, - 37762:21776, - 37763:22612, - 37764:22616, - 37765:22871, - 37766:23445, - 37767:23798, - 37768:23947, - 37769:24764, - 37770:25237, - 37771:25645, - 37772:26481, - 37773:26691, - 37774:26812, - 37775:26847, - 37776:30423, - 37777:28120, - 37778:28271, - 37779:28059, - 37780:28783, - 37781:29128, - 37782:24403, - 37783:30168, - 37784:31095, - 37785:31561, - 37786:31572, - 37787:31570, - 37788:31958, - 37789:32113, - 37790:21040, - 37791:33891, - 37792:34153, - 37793:34276, - 37794:35342, - 37795:35588, - 37796:35910, - 37797:36367, - 37798:36867, - 37799:36879, - 37800:37913, - 37801:38518, - 37802:38957, - 37803:39472, - 37804:38360, - 37805:20685, - 37806:21205, - 37807:21516, - 37808:22530, - 37809:23566, - 37810:24999, - 37811:25758, - 37812:27934, - 37813:30643, - 37814:31461, - 37815:33012, - 37816:33796, - 37817:36947, - 37818:37509, - 37819:23776, - 37820:40199, - 37821:21311, - 37822:24471, - 37823:24499, - 37824:28060, - 37825:29305, - 37826:30563, - 37827:31167, - 37828:31716, - 37829:27602, - 37830:29420, - 37831:35501, - 37832:26627, - 37833:27233, - 37834:20984, - 37835:31361, - 37836:26932, - 37837:23626, - 37838:40182, - 37839:33515, - 37840:23493, - 37841:37193, - 37842:28702, - 37843:22136, - 37844:23663, - 37845:24775, - 37846:25958, - 37847:27788, - 37848:35930, - 37849:36929, - 37850:38931, - 37851:21585, - 37852:26311, - 37853:37389, - 37854:22856, - 37855:37027, - 37856:20869, - 37857:20045, - 37858:20970, - 37859:34201, - 37860:35598, - 37861:28760, - 37862:25466, - 37863:37707, - 37864:26978, - 37865:39348, - 37866:32260, - 37867:30071, - 37868:21335, - 37869:26976, - 37870:36575, - 37871:38627, - 37872:27741, - 37873:20108, - 37874:23612, - 37875:24336, - 37876:36841, - 37877:21250, - 37878:36049, - 37879:32905, - 37880:34425, - 37881:24319, - 37882:26085, - 37883:20083, - 37884:20837, - 37952:22914, - 37953:23615, - 37954:38894, - 37955:20219, - 37956:22922, - 37957:24525, - 37958:35469, - 37959:28641, - 37960:31152, - 37961:31074, - 37962:23527, - 37963:33905, - 37964:29483, - 37965:29105, - 37966:24180, - 37967:24565, - 37968:25467, - 37969:25754, - 37970:29123, - 37971:31896, - 37972:20035, - 37973:24316, - 37974:20043, - 37975:22492, - 37976:22178, - 37977:24745, - 37978:28611, - 37979:32013, - 37980:33021, - 37981:33075, - 37982:33215, - 37983:36786, - 37984:35223, - 37985:34468, - 37986:24052, - 37987:25226, - 37988:25773, - 37989:35207, - 37990:26487, - 37991:27874, - 37992:27966, - 37993:29750, - 37994:30772, - 37995:23110, - 37996:32629, - 37997:33453, - 37998:39340, - 37999:20467, - 38000:24259, - 38001:25309, - 38002:25490, - 38003:25943, - 38004:26479, - 38005:30403, - 38006:29260, - 38007:32972, - 38008:32954, - 38009:36649, - 38010:37197, - 38011:20493, - 38012:22521, - 38013:23186, - 38014:26757, - 38016:26995, - 38017:29028, - 38018:29437, - 38019:36023, - 38020:22770, - 38021:36064, - 38022:38506, - 38023:36889, - 38024:34687, - 38025:31204, - 38026:30695, - 38027:33833, - 38028:20271, - 38029:21093, - 38030:21338, - 38031:25293, - 38032:26575, - 38033:27850, - 38034:30333, - 38035:31636, - 38036:31893, - 38037:33334, - 38038:34180, - 38039:36843, - 38040:26333, - 38041:28448, - 38042:29190, - 38043:32283, - 38044:33707, - 38045:39361, - 38046:40614, - 38047:20989, - 38048:31665, - 38049:30834, - 38050:31672, - 38051:32903, - 38052:31560, - 38053:27368, - 38054:24161, - 38055:32908, - 38056:30033, - 38057:30048, - 38058:20843, - 38059:37474, - 38060:28300, - 38061:30330, - 38062:37271, - 38063:39658, - 38064:20240, - 38065:32624, - 38066:25244, - 38067:31567, - 38068:38309, - 38069:40169, - 38070:22138, - 38071:22617, - 38072:34532, - 38073:38588, - 38074:20276, - 38075:21028, - 38076:21322, - 38077:21453, - 38078:21467, - 38079:24070, - 38080:25644, - 38081:26001, - 38082:26495, - 38083:27710, - 38084:27726, - 38085:29256, - 38086:29359, - 38087:29677, - 38088:30036, - 38089:32321, - 38090:33324, - 38091:34281, - 38092:36009, - 38093:31684, - 38094:37318, - 38095:29033, - 38096:38930, - 38097:39151, - 38098:25405, - 38099:26217, - 38100:30058, - 38101:30436, - 38102:30928, - 38103:34115, - 38104:34542, - 38105:21290, - 38106:21329, - 38107:21542, - 38108:22915, - 38109:24199, - 38110:24444, - 38111:24754, - 38112:25161, - 38113:25209, - 38114:25259, - 38115:26000, - 38116:27604, - 38117:27852, - 38118:30130, - 38119:30382, - 38120:30865, - 38121:31192, - 38122:32203, - 38123:32631, - 38124:32933, - 38125:34987, - 38126:35513, - 38127:36027, - 38128:36991, - 38129:38750, - 38130:39131, - 38131:27147, - 38132:31800, - 38133:20633, - 38134:23614, - 38135:24494, - 38136:26503, - 38137:27608, - 38138:29749, - 38139:30473, - 38140:32654, - 38208:40763, - 38209:26570, - 38210:31255, - 38211:21305, - 38212:30091, - 38213:39661, - 38214:24422, - 38215:33181, - 38216:33777, - 38217:32920, - 38218:24380, - 38219:24517, - 38220:30050, - 38221:31558, - 38222:36924, - 38223:26727, - 38224:23019, - 38225:23195, - 38226:32016, - 38227:30334, - 38228:35628, - 38229:20469, - 38230:24426, - 38231:27161, - 38232:27703, - 38233:28418, - 38234:29922, - 38235:31080, - 38236:34920, - 38237:35413, - 38238:35961, - 38239:24287, - 38240:25551, - 38241:30149, - 38242:31186, - 38243:33495, - 38244:37672, - 38245:37618, - 38246:33948, - 38247:34541, - 38248:39981, - 38249:21697, - 38250:24428, - 38251:25996, - 38252:27996, - 38253:28693, - 38254:36007, - 38255:36051, - 38256:38971, - 38257:25935, - 38258:29942, - 38259:19981, - 38260:20184, - 38261:22496, - 38262:22827, - 38263:23142, - 38264:23500, - 38265:20904, - 38266:24067, - 38267:24220, - 38268:24598, - 38269:25206, - 38270:25975, - 38272:26023, - 38273:26222, - 38274:28014, - 38275:29238, - 38276:31526, - 38277:33104, - 38278:33178, - 38279:33433, - 38280:35676, - 38281:36000, - 38282:36070, - 38283:36212, - 38284:38428, - 38285:38468, - 38286:20398, - 38287:25771, - 38288:27494, - 38289:33310, - 38290:33889, - 38291:34154, - 38292:37096, - 38293:23553, - 38294:26963, - 38295:39080, - 38296:33914, - 38297:34135, - 38298:20239, - 38299:21103, - 38300:24489, - 38301:24133, - 38302:26381, - 38303:31119, - 38304:33145, - 38305:35079, - 38306:35206, - 38307:28149, - 38308:24343, - 38309:25173, - 38310:27832, - 38311:20175, - 38312:29289, - 38313:39826, - 38314:20998, - 38315:21563, - 38316:22132, - 38317:22707, - 38318:24996, - 38319:25198, - 38320:28954, - 38321:22894, - 38322:31881, - 38323:31966, - 38324:32027, - 38325:38640, - 38326:25991, - 38327:32862, - 38328:19993, - 38329:20341, - 38330:20853, - 38331:22592, - 38332:24163, - 38333:24179, - 38334:24330, - 38335:26564, - 38336:20006, - 38337:34109, - 38338:38281, - 38339:38491, - 38340:31859, - 38341:38913, - 38342:20731, - 38343:22721, - 38344:30294, - 38345:30887, - 38346:21029, - 38347:30629, - 38348:34065, - 38349:31622, - 38350:20559, - 38351:22793, - 38352:29255, - 38353:31687, - 38354:32232, - 38355:36794, - 38356:36820, - 38357:36941, - 38358:20415, - 38359:21193, - 38360:23081, - 38361:24321, - 38362:38829, - 38363:20445, - 38364:33303, - 38365:37610, - 38366:22275, - 38367:25429, - 38368:27497, - 38369:29995, - 38370:35036, - 38371:36628, - 38372:31298, - 38373:21215, - 38374:22675, - 38375:24917, - 38376:25098, - 38377:26286, - 38378:27597, - 38379:31807, - 38380:33769, - 38381:20515, - 38382:20472, - 38383:21253, - 38384:21574, - 38385:22577, - 38386:22857, - 38387:23453, - 38388:23792, - 38389:23791, - 38390:23849, - 38391:24214, - 38392:25265, - 38393:25447, - 38394:25918, - 38395:26041, - 38396:26379, - 38464:27861, - 38465:27873, - 38466:28921, - 38467:30770, - 38468:32299, - 38469:32990, - 38470:33459, - 38471:33804, - 38472:34028, - 38473:34562, - 38474:35090, - 38475:35370, - 38476:35914, - 38477:37030, - 38478:37586, - 38479:39165, - 38480:40179, - 38481:40300, - 38482:20047, - 38483:20129, - 38484:20621, - 38485:21078, - 38486:22346, - 38487:22952, - 38488:24125, - 38489:24536, - 38490:24537, - 38491:25151, - 38492:26292, - 38493:26395, - 38494:26576, - 38495:26834, - 38496:20882, - 38497:32033, - 38498:32938, - 38499:33192, - 38500:35584, - 38501:35980, - 38502:36031, - 38503:37502, - 38504:38450, - 38505:21536, - 38506:38956, - 38507:21271, - 38508:20693, - 38509:21340, - 38510:22696, - 38511:25778, - 38512:26420, - 38513:29287, - 38514:30566, - 38515:31302, - 38516:37350, - 38517:21187, - 38518:27809, - 38519:27526, - 38520:22528, - 38521:24140, - 38522:22868, - 38523:26412, - 38524:32763, - 38525:20961, - 38526:30406, - 38528:25705, - 38529:30952, - 38530:39764, - 38531:40635, - 38532:22475, - 38533:22969, - 38534:26151, - 38535:26522, - 38536:27598, - 38537:21737, - 38538:27097, - 38539:24149, - 38540:33180, - 38541:26517, - 38542:39850, - 38543:26622, - 38544:40018, - 38545:26717, - 38546:20134, - 38547:20451, - 38548:21448, - 38549:25273, - 38550:26411, - 38551:27819, - 38552:36804, - 38553:20397, - 38554:32365, - 38555:40639, - 38556:19975, - 38557:24930, - 38558:28288, - 38559:28459, - 38560:34067, - 38561:21619, - 38562:26410, - 38563:39749, - 38564:24051, - 38565:31637, - 38566:23724, - 38567:23494, - 38568:34588, - 38569:28234, - 38570:34001, - 38571:31252, - 38572:33032, - 38573:22937, - 38574:31885, - 38575:27665, - 38576:30496, - 38577:21209, - 38578:22818, - 38579:28961, - 38580:29279, - 38581:30683, - 38582:38695, - 38583:40289, - 38584:26891, - 38585:23167, - 38586:23064, - 38587:20901, - 38588:21517, - 38589:21629, - 38590:26126, - 38591:30431, - 38592:36855, - 38593:37528, - 38594:40180, - 38595:23018, - 38596:29277, - 38597:28357, - 38598:20813, - 38599:26825, - 38600:32191, - 38601:32236, - 38602:38754, - 38603:40634, - 38604:25720, - 38605:27169, - 38606:33538, - 38607:22916, - 38608:23391, - 38609:27611, - 38610:29467, - 38611:30450, - 38612:32178, - 38613:32791, - 38614:33945, - 38615:20786, - 38616:26408, - 38617:40665, - 38618:30446, - 38619:26466, - 38620:21247, - 38621:39173, - 38622:23588, - 38623:25147, - 38624:31870, - 38625:36016, - 38626:21839, - 38627:24758, - 38628:32011, - 38629:38272, - 38630:21249, - 38631:20063, - 38632:20918, - 38633:22812, - 38634:29242, - 38635:32822, - 38636:37326, - 38637:24357, - 38638:30690, - 38639:21380, - 38640:24441, - 38641:32004, - 38642:34220, - 38643:35379, - 38644:36493, - 38645:38742, - 38646:26611, - 38647:34222, - 38648:37971, - 38649:24841, - 38650:24840, - 38651:27833, - 38652:30290, - 38720:35565, - 38721:36664, - 38722:21807, - 38723:20305, - 38724:20778, - 38725:21191, - 38726:21451, - 38727:23461, - 38728:24189, - 38729:24736, - 38730:24962, - 38731:25558, - 38732:26377, - 38733:26586, - 38734:28263, - 38735:28044, - 38736:29494, - 38737:29495, - 38738:30001, - 38739:31056, - 38740:35029, - 38741:35480, - 38742:36938, - 38743:37009, - 38744:37109, - 38745:38596, - 38746:34701, - 38747:22805, - 38748:20104, - 38749:20313, - 38750:19982, - 38751:35465, - 38752:36671, - 38753:38928, - 38754:20653, - 38755:24188, - 38756:22934, - 38757:23481, - 38758:24248, - 38759:25562, - 38760:25594, - 38761:25793, - 38762:26332, - 38763:26954, - 38764:27096, - 38765:27915, - 38766:28342, - 38767:29076, - 38768:29992, - 38769:31407, - 38770:32650, - 38771:32768, - 38772:33865, - 38773:33993, - 38774:35201, - 38775:35617, - 38776:36362, - 38777:36965, - 38778:38525, - 38779:39178, - 38780:24958, - 38781:25233, - 38782:27442, - 38784:27779, - 38785:28020, - 38786:32716, - 38787:32764, - 38788:28096, - 38789:32645, - 38790:34746, - 38791:35064, - 38792:26469, - 38793:33713, - 38794:38972, - 38795:38647, - 38796:27931, - 38797:32097, - 38798:33853, - 38799:37226, - 38800:20081, - 38801:21365, - 38802:23888, - 38803:27396, - 38804:28651, - 38805:34253, - 38806:34349, - 38807:35239, - 38808:21033, - 38809:21519, - 38810:23653, - 38811:26446, - 38812:26792, - 38813:29702, - 38814:29827, - 38815:30178, - 38816:35023, - 38817:35041, - 38818:37324, - 38819:38626, - 38820:38520, - 38821:24459, - 38822:29575, - 38823:31435, - 38824:33870, - 38825:25504, - 38826:30053, - 38827:21129, - 38828:27969, - 38829:28316, - 38830:29705, - 38831:30041, - 38832:30827, - 38833:31890, - 38834:38534, - 38835:31452, - 38836:40845, - 38837:20406, - 38838:24942, - 38839:26053, - 38840:34396, - 38841:20102, - 38842:20142, - 38843:20698, - 38844:20001, - 38845:20940, - 38846:23534, - 38847:26009, - 38848:26753, - 38849:28092, - 38850:29471, - 38851:30274, - 38852:30637, - 38853:31260, - 38854:31975, - 38855:33391, - 38856:35538, - 38857:36988, - 38858:37327, - 38859:38517, - 38860:38936, - 38861:21147, - 38862:32209, - 38863:20523, - 38864:21400, - 38865:26519, - 38866:28107, - 38867:29136, - 38868:29747, - 38869:33256, - 38870:36650, - 38871:38563, - 38872:40023, - 38873:40607, - 38874:29792, - 38875:22593, - 38876:28057, - 38877:32047, - 38878:39006, - 38879:20196, - 38880:20278, - 38881:20363, - 38882:20919, - 38883:21169, - 38884:23994, - 38885:24604, - 38886:29618, - 38887:31036, - 38888:33491, - 38889:37428, - 38890:38583, - 38891:38646, - 38892:38666, - 38893:40599, - 38894:40802, - 38895:26278, - 38896:27508, - 38897:21015, - 38898:21155, - 38899:28872, - 38900:35010, - 38901:24265, - 38902:24651, - 38903:24976, - 38904:28451, - 38905:29001, - 38906:31806, - 38907:32244, - 38908:32879, - 38976:34030, - 38977:36899, - 38978:37676, - 38979:21570, - 38980:39791, - 38981:27347, - 38982:28809, - 38983:36034, - 38984:36335, - 38985:38706, - 38986:21172, - 38987:23105, - 38988:24266, - 38989:24324, - 38990:26391, - 38991:27004, - 38992:27028, - 38993:28010, - 38994:28431, - 38995:29282, - 38996:29436, - 38997:31725, - 38998:32769, - 38999:32894, - 39000:34635, - 39001:37070, - 39002:20845, - 39003:40595, - 39004:31108, - 39005:32907, - 39006:37682, - 39007:35542, - 39008:20525, - 39009:21644, - 39010:35441, - 39011:27498, - 39012:36036, - 39013:33031, - 39014:24785, - 39015:26528, - 39016:40434, - 39017:20121, - 39018:20120, - 39019:39952, - 39020:35435, - 39021:34241, - 39022:34152, - 39023:26880, - 39024:28286, - 39025:30871, - 39026:33109, - 39071:24332, - 39072:19984, - 39073:19989, - 39074:20010, - 39075:20017, - 39076:20022, - 39077:20028, - 39078:20031, - 39079:20034, - 39080:20054, - 39081:20056, - 39082:20098, - 39083:20101, - 39084:35947, - 39085:20106, - 39086:33298, - 39087:24333, - 39088:20110, - 39089:20126, - 39090:20127, - 39091:20128, - 39092:20130, - 39093:20144, - 39094:20147, - 39095:20150, - 39096:20174, - 39097:20173, - 39098:20164, - 39099:20166, - 39100:20162, - 39101:20183, - 39102:20190, - 39103:20205, - 39104:20191, - 39105:20215, - 39106:20233, - 39107:20314, - 39108:20272, - 39109:20315, - 39110:20317, - 39111:20311, - 39112:20295, - 39113:20342, - 39114:20360, - 39115:20367, - 39116:20376, - 39117:20347, - 39118:20329, - 39119:20336, - 39120:20369, - 39121:20335, - 39122:20358, - 39123:20374, - 39124:20760, - 39125:20436, - 39126:20447, - 39127:20430, - 39128:20440, - 39129:20443, - 39130:20433, - 39131:20442, - 39132:20432, - 39133:20452, - 39134:20453, - 39135:20506, - 39136:20520, - 39137:20500, - 39138:20522, - 39139:20517, - 39140:20485, - 39141:20252, - 39142:20470, - 39143:20513, - 39144:20521, - 39145:20524, - 39146:20478, - 39147:20463, - 39148:20497, - 39149:20486, - 39150:20547, - 39151:20551, - 39152:26371, - 39153:20565, - 39154:20560, - 39155:20552, - 39156:20570, - 39157:20566, - 39158:20588, - 39159:20600, - 39160:20608, - 39161:20634, - 39162:20613, - 39163:20660, - 39164:20658, - 39232:20681, - 39233:20682, - 39234:20659, - 39235:20674, - 39236:20694, - 39237:20702, - 39238:20709, - 39239:20717, - 39240:20707, - 39241:20718, - 39242:20729, - 39243:20725, - 39244:20745, - 39245:20737, - 39246:20738, - 39247:20758, - 39248:20757, - 39249:20756, - 39250:20762, - 39251:20769, - 39252:20794, - 39253:20791, - 39254:20796, - 39255:20795, - 39256:20799, - 39257:20800, - 39258:20818, - 39259:20812, - 39260:20820, - 39261:20834, - 39262:31480, - 39263:20841, - 39264:20842, - 39265:20846, - 39266:20864, - 39267:20866, - 39268:22232, - 39269:20876, - 39270:20873, - 39271:20879, - 39272:20881, - 39273:20883, - 39274:20885, - 39275:20886, - 39276:20900, - 39277:20902, - 39278:20898, - 39279:20905, - 39280:20906, - 39281:20907, - 39282:20915, - 39283:20913, - 39284:20914, - 39285:20912, - 39286:20917, - 39287:20925, - 39288:20933, - 39289:20937, - 39290:20955, - 39291:20960, - 39292:34389, - 39293:20969, - 39294:20973, - 39296:20976, - 39297:20981, - 39298:20990, - 39299:20996, - 39300:21003, - 39301:21012, - 39302:21006, - 39303:21031, - 39304:21034, - 39305:21038, - 39306:21043, - 39307:21049, - 39308:21071, - 39309:21060, - 39310:21067, - 39311:21068, - 39312:21086, - 39313:21076, - 39314:21098, - 39315:21108, - 39316:21097, - 39317:21107, - 39318:21119, - 39319:21117, - 39320:21133, - 39321:21140, - 39322:21138, - 39323:21105, - 39324:21128, - 39325:21137, - 39326:36776, - 39327:36775, - 39328:21164, - 39329:21165, - 39330:21180, - 39331:21173, - 39332:21185, - 39333:21197, - 39334:21207, - 39335:21214, - 39336:21219, - 39337:21222, - 39338:39149, - 39339:21216, - 39340:21235, - 39341:21237, - 39342:21240, - 39343:21241, - 39344:21254, - 39345:21256, - 39346:30008, - 39347:21261, - 39348:21264, - 39349:21263, - 39350:21269, - 39351:21274, - 39352:21283, - 39353:21295, - 39354:21297, - 39355:21299, - 39356:21304, - 39357:21312, - 39358:21318, - 39359:21317, - 39360:19991, - 39361:21321, - 39362:21325, - 39363:20950, - 39364:21342, - 39365:21353, - 39366:21358, - 39367:22808, - 39368:21371, - 39369:21367, - 39370:21378, - 39371:21398, - 39372:21408, - 39373:21414, - 39374:21413, - 39375:21422, - 39376:21424, - 39377:21430, - 39378:21443, - 39379:31762, - 39380:38617, - 39381:21471, - 39382:26364, - 39383:29166, - 39384:21486, - 39385:21480, - 39386:21485, - 39387:21498, - 39388:21505, - 39389:21565, - 39390:21568, - 39391:21548, - 39392:21549, - 39393:21564, - 39394:21550, - 39395:21558, - 39396:21545, - 39397:21533, - 39398:21582, - 39399:21647, - 39400:21621, - 39401:21646, - 39402:21599, - 39403:21617, - 39404:21623, - 39405:21616, - 39406:21650, - 39407:21627, - 39408:21632, - 39409:21622, - 39410:21636, - 39411:21648, - 39412:21638, - 39413:21703, - 39414:21666, - 39415:21688, - 39416:21669, - 39417:21676, - 39418:21700, - 39419:21704, - 39420:21672, - 39488:21675, - 39489:21698, - 39490:21668, - 39491:21694, - 39492:21692, - 39493:21720, - 39494:21733, - 39495:21734, - 39496:21775, - 39497:21780, - 39498:21757, - 39499:21742, - 39500:21741, - 39501:21754, - 39502:21730, - 39503:21817, - 39504:21824, - 39505:21859, - 39506:21836, - 39507:21806, - 39508:21852, - 39509:21829, - 39510:21846, - 39511:21847, - 39512:21816, - 39513:21811, - 39514:21853, - 39515:21913, - 39516:21888, - 39517:21679, - 39518:21898, - 39519:21919, - 39520:21883, - 39521:21886, - 39522:21912, - 39523:21918, - 39524:21934, - 39525:21884, - 39526:21891, - 39527:21929, - 39528:21895, - 39529:21928, - 39530:21978, - 39531:21957, - 39532:21983, - 39533:21956, - 39534:21980, - 39535:21988, - 39536:21972, - 39537:22036, - 39538:22007, - 39539:22038, - 39540:22014, - 39541:22013, - 39542:22043, - 39543:22009, - 39544:22094, - 39545:22096, - 39546:29151, - 39547:22068, - 39548:22070, - 39549:22066, - 39550:22072, - 39552:22123, - 39553:22116, - 39554:22063, - 39555:22124, - 39556:22122, - 39557:22150, - 39558:22144, - 39559:22154, - 39560:22176, - 39561:22164, - 39562:22159, - 39563:22181, - 39564:22190, - 39565:22198, - 39566:22196, - 39567:22210, - 39568:22204, - 39569:22209, - 39570:22211, - 39571:22208, - 39572:22216, - 39573:22222, - 39574:22225, - 39575:22227, - 39576:22231, - 39577:22254, - 39578:22265, - 39579:22272, - 39580:22271, - 39581:22276, - 39582:22281, - 39583:22280, - 39584:22283, - 39585:22285, - 39586:22291, - 39587:22296, - 39588:22294, - 39589:21959, - 39590:22300, - 39591:22310, - 39592:22327, - 39593:22328, - 39594:22350, - 39595:22331, - 39596:22336, - 39597:22351, - 39598:22377, - 39599:22464, - 39600:22408, - 39601:22369, - 39602:22399, - 39603:22409, - 39604:22419, - 39605:22432, - 39606:22451, - 39607:22436, - 39608:22442, - 39609:22448, - 39610:22467, - 39611:22470, - 39612:22484, - 39613:22482, - 39614:22483, - 39615:22538, - 39616:22486, - 39617:22499, - 39618:22539, - 39619:22553, - 39620:22557, - 39621:22642, - 39622:22561, - 39623:22626, - 39624:22603, - 39625:22640, - 39626:27584, - 39627:22610, - 39628:22589, - 39629:22649, - 39630:22661, - 39631:22713, - 39632:22687, - 39633:22699, - 39634:22714, - 39635:22750, - 39636:22715, - 39637:22712, - 39638:22702, - 39639:22725, - 39640:22739, - 39641:22737, - 39642:22743, - 39643:22745, - 39644:22744, - 39645:22757, - 39646:22748, - 39647:22756, - 39648:22751, - 39649:22767, - 39650:22778, - 39651:22777, - 39652:22779, - 39653:22780, - 39654:22781, - 39655:22786, - 39656:22794, - 39657:22800, - 39658:22811, - 39659:26790, - 39660:22821, - 39661:22828, - 39662:22829, - 39663:22834, - 39664:22840, - 39665:22846, - 39666:31442, - 39667:22869, - 39668:22864, - 39669:22862, - 39670:22874, - 39671:22872, - 39672:22882, - 39673:22880, - 39674:22887, - 39675:22892, - 39676:22889, - 39744:22904, - 39745:22913, - 39746:22941, - 39747:20318, - 39748:20395, - 39749:22947, - 39750:22962, - 39751:22982, - 39752:23016, - 39753:23004, - 39754:22925, - 39755:23001, - 39756:23002, - 39757:23077, - 39758:23071, - 39759:23057, - 39760:23068, - 39761:23049, - 39762:23066, - 39763:23104, - 39764:23148, - 39765:23113, - 39766:23093, - 39767:23094, - 39768:23138, - 39769:23146, - 39770:23194, - 39771:23228, - 39772:23230, - 39773:23243, - 39774:23234, - 39775:23229, - 39776:23267, - 39777:23255, - 39778:23270, - 39779:23273, - 39780:23254, - 39781:23290, - 39782:23291, - 39783:23308, - 39784:23307, - 39785:23318, - 39786:23346, - 39787:23248, - 39788:23338, - 39789:23350, - 39790:23358, - 39791:23363, - 39792:23365, - 39793:23360, - 39794:23377, - 39795:23381, - 39796:23386, - 39797:23387, - 39798:23397, - 39799:23401, - 39800:23408, - 39801:23411, - 39802:23413, - 39803:23416, - 39804:25992, - 39805:23418, - 39806:23424, - 39808:23427, - 39809:23462, - 39810:23480, - 39811:23491, - 39812:23495, - 39813:23497, - 39814:23508, - 39815:23504, - 39816:23524, - 39817:23526, - 39818:23522, - 39819:23518, - 39820:23525, - 39821:23531, - 39822:23536, - 39823:23542, - 39824:23539, - 39825:23557, - 39826:23559, - 39827:23560, - 39828:23565, - 39829:23571, - 39830:23584, - 39831:23586, - 39832:23592, - 39833:23608, - 39834:23609, - 39835:23617, - 39836:23622, - 39837:23630, - 39838:23635, - 39839:23632, - 39840:23631, - 39841:23409, - 39842:23660, - 39843:23662, - 39844:20066, - 39845:23670, - 39846:23673, - 39847:23692, - 39848:23697, - 39849:23700, - 39850:22939, - 39851:23723, - 39852:23739, - 39853:23734, - 39854:23740, - 39855:23735, - 39856:23749, - 39857:23742, - 39858:23751, - 39859:23769, - 39860:23785, - 39861:23805, - 39862:23802, - 39863:23789, - 39864:23948, - 39865:23786, - 39866:23819, - 39867:23829, - 39868:23831, - 39869:23900, - 39870:23839, - 39871:23835, - 39872:23825, - 39873:23828, - 39874:23842, - 39875:23834, - 39876:23833, - 39877:23832, - 39878:23884, - 39879:23890, - 39880:23886, - 39881:23883, - 39882:23916, - 39883:23923, - 39884:23926, - 39885:23943, - 39886:23940, - 39887:23938, - 39888:23970, - 39889:23965, - 39890:23980, - 39891:23982, - 39892:23997, - 39893:23952, - 39894:23991, - 39895:23996, - 39896:24009, - 39897:24013, - 39898:24019, - 39899:24018, - 39900:24022, - 39901:24027, - 39902:24043, - 39903:24050, - 39904:24053, - 39905:24075, - 39906:24090, - 39907:24089, - 39908:24081, - 39909:24091, - 39910:24118, - 39911:24119, - 39912:24132, - 39913:24131, - 39914:24128, - 39915:24142, - 39916:24151, - 39917:24148, - 39918:24159, - 39919:24162, - 39920:24164, - 39921:24135, - 39922:24181, - 39923:24182, - 39924:24186, - 39925:40636, - 39926:24191, - 39927:24224, - 39928:24257, - 39929:24258, - 39930:24264, - 39931:24272, - 39932:24271, - 40000:24278, - 40001:24291, - 40002:24285, - 40003:24282, - 40004:24283, - 40005:24290, - 40006:24289, - 40007:24296, - 40008:24297, - 40009:24300, - 40010:24305, - 40011:24307, - 40012:24304, - 40013:24308, - 40014:24312, - 40015:24318, - 40016:24323, - 40017:24329, - 40018:24413, - 40019:24412, - 40020:24331, - 40021:24337, - 40022:24342, - 40023:24361, - 40024:24365, - 40025:24376, - 40026:24385, - 40027:24392, - 40028:24396, - 40029:24398, - 40030:24367, - 40031:24401, - 40032:24406, - 40033:24407, - 40034:24409, - 40035:24417, - 40036:24429, - 40037:24435, - 40038:24439, - 40039:24451, - 40040:24450, - 40041:24447, - 40042:24458, - 40043:24456, - 40044:24465, - 40045:24455, - 40046:24478, - 40047:24473, - 40048:24472, - 40049:24480, - 40050:24488, - 40051:24493, - 40052:24508, - 40053:24534, - 40054:24571, - 40055:24548, - 40056:24568, - 40057:24561, - 40058:24541, - 40059:24755, - 40060:24575, - 40061:24609, - 40062:24672, - 40064:24601, - 40065:24592, - 40066:24617, - 40067:24590, - 40068:24625, - 40069:24603, - 40070:24597, - 40071:24619, - 40072:24614, - 40073:24591, - 40074:24634, - 40075:24666, - 40076:24641, - 40077:24682, - 40078:24695, - 40079:24671, - 40080:24650, - 40081:24646, - 40082:24653, - 40083:24675, - 40084:24643, - 40085:24676, - 40086:24642, - 40087:24684, - 40088:24683, - 40089:24665, - 40090:24705, - 40091:24717, - 40092:24807, - 40093:24707, - 40094:24730, - 40095:24708, - 40096:24731, - 40097:24726, - 40098:24727, - 40099:24722, - 40100:24743, - 40101:24715, - 40102:24801, - 40103:24760, - 40104:24800, - 40105:24787, - 40106:24756, - 40107:24560, - 40108:24765, - 40109:24774, - 40110:24757, - 40111:24792, - 40112:24909, - 40113:24853, - 40114:24838, - 40115:24822, - 40116:24823, - 40117:24832, - 40118:24820, - 40119:24826, - 40120:24835, - 40121:24865, - 40122:24827, - 40123:24817, - 40124:24845, - 40125:24846, - 40126:24903, - 40127:24894, - 40128:24872, - 40129:24871, - 40130:24906, - 40131:24895, - 40132:24892, - 40133:24876, - 40134:24884, - 40135:24893, - 40136:24898, - 40137:24900, - 40138:24947, - 40139:24951, - 40140:24920, - 40141:24921, - 40142:24922, - 40143:24939, - 40144:24948, - 40145:24943, - 40146:24933, - 40147:24945, - 40148:24927, - 40149:24925, - 40150:24915, - 40151:24949, - 40152:24985, - 40153:24982, - 40154:24967, - 40155:25004, - 40156:24980, - 40157:24986, - 40158:24970, - 40159:24977, - 40160:25003, - 40161:25006, - 40162:25036, - 40163:25034, - 40164:25033, - 40165:25079, - 40166:25032, - 40167:25027, - 40168:25030, - 40169:25018, - 40170:25035, - 40171:32633, - 40172:25037, - 40173:25062, - 40174:25059, - 40175:25078, - 40176:25082, - 40177:25076, - 40178:25087, - 40179:25085, - 40180:25084, - 40181:25086, - 40182:25088, - 40183:25096, - 40184:25097, - 40185:25101, - 40186:25100, - 40187:25108, - 40188:25115, - 40256:25118, - 40257:25121, - 40258:25130, - 40259:25134, - 40260:25136, - 40261:25138, - 40262:25139, - 40263:25153, - 40264:25166, - 40265:25182, - 40266:25187, - 40267:25179, - 40268:25184, - 40269:25192, - 40270:25212, - 40271:25218, - 40272:25225, - 40273:25214, - 40274:25234, - 40275:25235, - 40276:25238, - 40277:25300, - 40278:25219, - 40279:25236, - 40280:25303, - 40281:25297, - 40282:25275, - 40283:25295, - 40284:25343, - 40285:25286, - 40286:25812, - 40287:25288, - 40288:25308, - 40289:25292, - 40290:25290, - 40291:25282, - 40292:25287, - 40293:25243, - 40294:25289, - 40295:25356, - 40296:25326, - 40297:25329, - 40298:25383, - 40299:25346, - 40300:25352, - 40301:25327, - 40302:25333, - 40303:25424, - 40304:25406, - 40305:25421, - 40306:25628, - 40307:25423, - 40308:25494, - 40309:25486, - 40310:25472, - 40311:25515, - 40312:25462, - 40313:25507, - 40314:25487, - 40315:25481, - 40316:25503, - 40317:25525, - 40318:25451, - 40320:25449, - 40321:25534, - 40322:25577, - 40323:25536, - 40324:25542, - 40325:25571, - 40326:25545, - 40327:25554, - 40328:25590, - 40329:25540, - 40330:25622, - 40331:25652, - 40332:25606, - 40333:25619, - 40334:25638, - 40335:25654, - 40336:25885, - 40337:25623, - 40338:25640, - 40339:25615, - 40340:25703, - 40341:25711, - 40342:25718, - 40343:25678, - 40344:25898, - 40345:25749, - 40346:25747, - 40347:25765, - 40348:25769, - 40349:25736, - 40350:25788, - 40351:25818, - 40352:25810, - 40353:25797, - 40354:25799, - 40355:25787, - 40356:25816, - 40357:25794, - 40358:25841, - 40359:25831, - 40360:33289, - 40361:25824, - 40362:25825, - 40363:25260, - 40364:25827, - 40365:25839, - 40366:25900, - 40367:25846, - 40368:25844, - 40369:25842, - 40370:25850, - 40371:25856, - 40372:25853, - 40373:25880, - 40374:25884, - 40375:25861, - 40376:25892, - 40377:25891, - 40378:25899, - 40379:25908, - 40380:25909, - 40381:25911, - 40382:25910, - 40383:25912, - 40384:30027, - 40385:25928, - 40386:25942, - 40387:25941, - 40388:25933, - 40389:25944, - 40390:25950, - 40391:25949, - 40392:25970, - 40393:25976, - 40394:25986, - 40395:25987, - 40396:35722, - 40397:26011, - 40398:26015, - 40399:26027, - 40400:26039, - 40401:26051, - 40402:26054, - 40403:26049, - 40404:26052, - 40405:26060, - 40406:26066, - 40407:26075, - 40408:26073, - 40409:26080, - 40410:26081, - 40411:26097, - 40412:26482, - 40413:26122, - 40414:26115, - 40415:26107, - 40416:26483, - 40417:26165, - 40418:26166, - 40419:26164, - 40420:26140, - 40421:26191, - 40422:26180, - 40423:26185, - 40424:26177, - 40425:26206, - 40426:26205, - 40427:26212, - 40428:26215, - 40429:26216, - 40430:26207, - 40431:26210, - 40432:26224, - 40433:26243, - 40434:26248, - 40435:26254, - 40436:26249, - 40437:26244, - 40438:26264, - 40439:26269, - 40440:26305, - 40441:26297, - 40442:26313, - 40443:26302, - 40444:26300, - 40512:26308, - 40513:26296, - 40514:26326, - 40515:26330, - 40516:26336, - 40517:26175, - 40518:26342, - 40519:26345, - 40520:26352, - 40521:26357, - 40522:26359, - 40523:26383, - 40524:26390, - 40525:26398, - 40526:26406, - 40527:26407, - 40528:38712, - 40529:26414, - 40530:26431, - 40531:26422, - 40532:26433, - 40533:26424, - 40534:26423, - 40535:26438, - 40536:26462, - 40537:26464, - 40538:26457, - 40539:26467, - 40540:26468, - 40541:26505, - 40542:26480, - 40543:26537, - 40544:26492, - 40545:26474, - 40546:26508, - 40547:26507, - 40548:26534, - 40549:26529, - 40550:26501, - 40551:26551, - 40552:26607, - 40553:26548, - 40554:26604, - 40555:26547, - 40556:26601, - 40557:26552, - 40558:26596, - 40559:26590, - 40560:26589, - 40561:26594, - 40562:26606, - 40563:26553, - 40564:26574, - 40565:26566, - 40566:26599, - 40567:27292, - 40568:26654, - 40569:26694, - 40570:26665, - 40571:26688, - 40572:26701, - 40573:26674, - 40574:26702, - 40576:26803, - 40577:26667, - 40578:26713, - 40579:26723, - 40580:26743, - 40581:26751, - 40582:26783, - 40583:26767, - 40584:26797, - 40585:26772, - 40586:26781, - 40587:26779, - 40588:26755, - 40589:27310, - 40590:26809, - 40591:26740, - 40592:26805, - 40593:26784, - 40594:26810, - 40595:26895, - 40596:26765, - 40597:26750, - 40598:26881, - 40599:26826, - 40600:26888, - 40601:26840, - 40602:26914, - 40603:26918, - 40604:26849, - 40605:26892, - 40606:26829, - 40607:26836, - 40608:26855, - 40609:26837, - 40610:26934, - 40611:26898, - 40612:26884, - 40613:26839, - 40614:26851, - 40615:26917, - 40616:26873, - 40617:26848, - 40618:26863, - 40619:26920, - 40620:26922, - 40621:26906, - 40622:26915, - 40623:26913, - 40624:26822, - 40625:27001, - 40626:26999, - 40627:26972, - 40628:27000, - 40629:26987, - 40630:26964, - 40631:27006, - 40632:26990, - 40633:26937, - 40634:26996, - 40635:26941, - 40636:26969, - 40637:26928, - 40638:26977, - 40639:26974, - 40640:26973, - 40641:27009, - 40642:26986, - 40643:27058, - 40644:27054, - 40645:27088, - 40646:27071, - 40647:27073, - 40648:27091, - 40649:27070, - 40650:27086, - 40651:23528, - 40652:27082, - 40653:27101, - 40654:27067, - 40655:27075, - 40656:27047, - 40657:27182, - 40658:27025, - 40659:27040, - 40660:27036, - 40661:27029, - 40662:27060, - 40663:27102, - 40664:27112, - 40665:27138, - 40666:27163, - 40667:27135, - 40668:27402, - 40669:27129, - 40670:27122, - 40671:27111, - 40672:27141, - 40673:27057, - 40674:27166, - 40675:27117, - 40676:27156, - 40677:27115, - 40678:27146, - 40679:27154, - 40680:27329, - 40681:27171, - 40682:27155, - 40683:27204, - 40684:27148, - 40685:27250, - 40686:27190, - 40687:27256, - 40688:27207, - 40689:27234, - 40690:27225, - 40691:27238, - 40692:27208, - 40693:27192, - 40694:27170, - 40695:27280, - 40696:27277, - 40697:27296, - 40698:27268, - 40699:27298, - 40700:27299, - 40768:27287, - 40769:34327, - 40770:27323, - 40771:27331, - 40772:27330, - 40773:27320, - 40774:27315, - 40775:27308, - 40776:27358, - 40777:27345, - 40778:27359, - 40779:27306, - 40780:27354, - 40781:27370, - 40782:27387, - 40783:27397, - 40784:34326, - 40785:27386, - 40786:27410, - 40787:27414, - 40788:39729, - 40789:27423, - 40790:27448, - 40791:27447, - 40792:30428, - 40793:27449, - 40794:39150, - 40795:27463, - 40796:27459, - 40797:27465, - 40798:27472, - 40799:27481, - 40800:27476, - 40801:27483, - 40802:27487, - 40803:27489, - 40804:27512, - 40805:27513, - 40806:27519, - 40807:27520, - 40808:27524, - 40809:27523, - 40810:27533, - 40811:27544, - 40812:27541, - 40813:27550, - 40814:27556, - 40815:27562, - 40816:27563, - 40817:27567, - 40818:27570, - 40819:27569, - 40820:27571, - 40821:27575, - 40822:27580, - 40823:27590, - 40824:27595, - 40825:27603, - 40826:27615, - 40827:27628, - 40828:27627, - 40829:27635, - 40830:27631, - 40832:40638, - 40833:27656, - 40834:27667, - 40835:27668, - 40836:27675, - 40837:27684, - 40838:27683, - 40839:27742, - 40840:27733, - 40841:27746, - 40842:27754, - 40843:27778, - 40844:27789, - 40845:27802, - 40846:27777, - 40847:27803, - 40848:27774, - 40849:27752, - 40850:27763, - 40851:27794, - 40852:27792, - 40853:27844, - 40854:27889, - 40855:27859, - 40856:27837, - 40857:27863, - 40858:27845, - 40859:27869, - 40860:27822, - 40861:27825, - 40862:27838, - 40863:27834, - 40864:27867, - 40865:27887, - 40866:27865, - 40867:27882, - 40868:27935, - 40869:34893, - 40870:27958, - 40871:27947, - 40872:27965, - 40873:27960, - 40874:27929, - 40875:27957, - 40876:27955, - 40877:27922, - 40878:27916, - 40879:28003, - 40880:28051, - 40881:28004, - 40882:27994, - 40883:28025, - 40884:27993, - 40885:28046, - 40886:28053, - 40887:28644, - 40888:28037, - 40889:28153, - 40890:28181, - 40891:28170, - 40892:28085, - 40893:28103, - 40894:28134, - 40895:28088, - 40896:28102, - 40897:28140, - 40898:28126, - 40899:28108, - 40900:28136, - 40901:28114, - 40902:28101, - 40903:28154, - 40904:28121, - 40905:28132, - 40906:28117, - 40907:28138, - 40908:28142, - 40909:28205, - 40910:28270, - 40911:28206, - 40912:28185, - 40913:28274, - 40914:28255, - 40915:28222, - 40916:28195, - 40917:28267, - 40918:28203, - 40919:28278, - 40920:28237, - 40921:28191, - 40922:28227, - 40923:28218, - 40924:28238, - 40925:28196, - 40926:28415, - 40927:28189, - 40928:28216, - 40929:28290, - 40930:28330, - 40931:28312, - 40932:28361, - 40933:28343, - 40934:28371, - 40935:28349, - 40936:28335, - 40937:28356, - 40938:28338, - 40939:28372, - 40940:28373, - 40941:28303, - 40942:28325, - 40943:28354, - 40944:28319, - 40945:28481, - 40946:28433, - 40947:28748, - 40948:28396, - 40949:28408, - 40950:28414, - 40951:28479, - 40952:28402, - 40953:28465, - 40954:28399, - 40955:28466, - 40956:28364, - 57408:28478, - 57409:28435, - 57410:28407, - 57411:28550, - 57412:28538, - 57413:28536, - 57414:28545, - 57415:28544, - 57416:28527, - 57417:28507, - 57418:28659, - 57419:28525, - 57420:28546, - 57421:28540, - 57422:28504, - 57423:28558, - 57424:28561, - 57425:28610, - 57426:28518, - 57427:28595, - 57428:28579, - 57429:28577, - 57430:28580, - 57431:28601, - 57432:28614, - 57433:28586, - 57434:28639, - 57435:28629, - 57436:28652, - 57437:28628, - 57438:28632, - 57439:28657, - 57440:28654, - 57441:28635, - 57442:28681, - 57443:28683, - 57444:28666, - 57445:28689, - 57446:28673, - 57447:28687, - 57448:28670, - 57449:28699, - 57450:28698, - 57451:28532, - 57452:28701, - 57453:28696, - 57454:28703, - 57455:28720, - 57456:28734, - 57457:28722, - 57458:28753, - 57459:28771, - 57460:28825, - 57461:28818, - 57462:28847, - 57463:28913, - 57464:28844, - 57465:28856, - 57466:28851, - 57467:28846, - 57468:28895, - 57469:28875, - 57470:28893, - 57472:28889, - 57473:28937, - 57474:28925, - 57475:28956, - 57476:28953, - 57477:29029, - 57478:29013, - 57479:29064, - 57480:29030, - 57481:29026, - 57482:29004, - 57483:29014, - 57484:29036, - 57485:29071, - 57486:29179, - 57487:29060, - 57488:29077, - 57489:29096, - 57490:29100, - 57491:29143, - 57492:29113, - 57493:29118, - 57494:29138, - 57495:29129, - 57496:29140, - 57497:29134, - 57498:29152, - 57499:29164, - 57500:29159, - 57501:29173, - 57502:29180, - 57503:29177, - 57504:29183, - 57505:29197, - 57506:29200, - 57507:29211, - 57508:29224, - 57509:29229, - 57510:29228, - 57511:29232, - 57512:29234, - 57513:29243, - 57514:29244, - 57515:29247, - 57516:29248, - 57517:29254, - 57518:29259, - 57519:29272, - 57520:29300, - 57521:29310, - 57522:29314, - 57523:29313, - 57524:29319, - 57525:29330, - 57526:29334, - 57527:29346, - 57528:29351, - 57529:29369, - 57530:29362, - 57531:29379, - 57532:29382, - 57533:29380, - 57534:29390, - 57535:29394, - 57536:29410, - 57537:29408, - 57538:29409, - 57539:29433, - 57540:29431, - 57541:20495, - 57542:29463, - 57543:29450, - 57544:29468, - 57545:29462, - 57546:29469, - 57547:29492, - 57548:29487, - 57549:29481, - 57550:29477, - 57551:29502, - 57552:29518, - 57553:29519, - 57554:40664, - 57555:29527, - 57556:29546, - 57557:29544, - 57558:29552, - 57559:29560, - 57560:29557, - 57561:29563, - 57562:29562, - 57563:29640, - 57564:29619, - 57565:29646, - 57566:29627, - 57567:29632, - 57568:29669, - 57569:29678, - 57570:29662, - 57571:29858, - 57572:29701, - 57573:29807, - 57574:29733, - 57575:29688, - 57576:29746, - 57577:29754, - 57578:29781, - 57579:29759, - 57580:29791, - 57581:29785, - 57582:29761, - 57583:29788, - 57584:29801, - 57585:29808, - 57586:29795, - 57587:29802, - 57588:29814, - 57589:29822, - 57590:29835, - 57591:29854, - 57592:29863, - 57593:29898, - 57594:29903, - 57595:29908, - 57596:29681, - 57664:29920, - 57665:29923, - 57666:29927, - 57667:29929, - 57668:29934, - 57669:29938, - 57670:29936, - 57671:29937, - 57672:29944, - 57673:29943, - 57674:29956, - 57675:29955, - 57676:29957, - 57677:29964, - 57678:29966, - 57679:29965, - 57680:29973, - 57681:29971, - 57682:29982, - 57683:29990, - 57684:29996, - 57685:30012, - 57686:30020, - 57687:30029, - 57688:30026, - 57689:30025, - 57690:30043, - 57691:30022, - 57692:30042, - 57693:30057, - 57694:30052, - 57695:30055, - 57696:30059, - 57697:30061, - 57698:30072, - 57699:30070, - 57700:30086, - 57701:30087, - 57702:30068, - 57703:30090, - 57704:30089, - 57705:30082, - 57706:30100, - 57707:30106, - 57708:30109, - 57709:30117, - 57710:30115, - 57711:30146, - 57712:30131, - 57713:30147, - 57714:30133, - 57715:30141, - 57716:30136, - 57717:30140, - 57718:30129, - 57719:30157, - 57720:30154, - 57721:30162, - 57722:30169, - 57723:30179, - 57724:30174, - 57725:30206, - 57726:30207, - 57728:30204, - 57729:30209, - 57730:30192, - 57731:30202, - 57732:30194, - 57733:30195, - 57734:30219, - 57735:30221, - 57736:30217, - 57737:30239, - 57738:30247, - 57739:30240, - 57740:30241, - 57741:30242, - 57742:30244, - 57743:30260, - 57744:30256, - 57745:30267, - 57746:30279, - 57747:30280, - 57748:30278, - 57749:30300, - 57750:30296, - 57751:30305, - 57752:30306, - 57753:30312, - 57754:30313, - 57755:30314, - 57756:30311, - 57757:30316, - 57758:30320, - 57759:30322, - 57760:30326, - 57761:30328, - 57762:30332, - 57763:30336, - 57764:30339, - 57765:30344, - 57766:30347, - 57767:30350, - 57768:30358, - 57769:30355, - 57770:30361, - 57771:30362, - 57772:30384, - 57773:30388, - 57774:30392, - 57775:30393, - 57776:30394, - 57777:30402, - 57778:30413, - 57779:30422, - 57780:30418, - 57781:30430, - 57782:30433, - 57783:30437, - 57784:30439, - 57785:30442, - 57786:34351, - 57787:30459, - 57788:30472, - 57789:30471, - 57790:30468, - 57791:30505, - 57792:30500, - 57793:30494, - 57794:30501, - 57795:30502, - 57796:30491, - 57797:30519, - 57798:30520, - 57799:30535, - 57800:30554, - 57801:30568, - 57802:30571, - 57803:30555, - 57804:30565, - 57805:30591, - 57806:30590, - 57807:30585, - 57808:30606, - 57809:30603, - 57810:30609, - 57811:30624, - 57812:30622, - 57813:30640, - 57814:30646, - 57815:30649, - 57816:30655, - 57817:30652, - 57818:30653, - 57819:30651, - 57820:30663, - 57821:30669, - 57822:30679, - 57823:30682, - 57824:30684, - 57825:30691, - 57826:30702, - 57827:30716, - 57828:30732, - 57829:30738, - 57830:31014, - 57831:30752, - 57832:31018, - 57833:30789, - 57834:30862, - 57835:30836, - 57836:30854, - 57837:30844, - 57838:30874, - 57839:30860, - 57840:30883, - 57841:30901, - 57842:30890, - 57843:30895, - 57844:30929, - 57845:30918, - 57846:30923, - 57847:30932, - 57848:30910, - 57849:30908, - 57850:30917, - 57851:30922, - 57852:30956, - 57920:30951, - 57921:30938, - 57922:30973, - 57923:30964, - 57924:30983, - 57925:30994, - 57926:30993, - 57927:31001, - 57928:31020, - 57929:31019, - 57930:31040, - 57931:31072, - 57932:31063, - 57933:31071, - 57934:31066, - 57935:31061, - 57936:31059, - 57937:31098, - 57938:31103, - 57939:31114, - 57940:31133, - 57941:31143, - 57942:40779, - 57943:31146, - 57944:31150, - 57945:31155, - 57946:31161, - 57947:31162, - 57948:31177, - 57949:31189, - 57950:31207, - 57951:31212, - 57952:31201, - 57953:31203, - 57954:31240, - 57955:31245, - 57956:31256, - 57957:31257, - 57958:31264, - 57959:31263, - 57960:31104, - 57961:31281, - 57962:31291, - 57963:31294, - 57964:31287, - 57965:31299, - 57966:31319, - 57967:31305, - 57968:31329, - 57969:31330, - 57970:31337, - 57971:40861, - 57972:31344, - 57973:31353, - 57974:31357, - 57975:31368, - 57976:31383, - 57977:31381, - 57978:31384, - 57979:31382, - 57980:31401, - 57981:31432, - 57982:31408, - 57984:31414, - 57985:31429, - 57986:31428, - 57987:31423, - 57988:36995, - 57989:31431, - 57990:31434, - 57991:31437, - 57992:31439, - 57993:31445, - 57994:31443, - 57995:31449, - 57996:31450, - 57997:31453, - 57998:31457, - 57999:31458, - 58000:31462, - 58001:31469, - 58002:31472, - 58003:31490, - 58004:31503, - 58005:31498, - 58006:31494, - 58007:31539, - 58008:31512, - 58009:31513, - 58010:31518, - 58011:31541, - 58012:31528, - 58013:31542, - 58014:31568, - 58015:31610, - 58016:31492, - 58017:31565, - 58018:31499, - 58019:31564, - 58020:31557, - 58021:31605, - 58022:31589, - 58023:31604, - 58024:31591, - 58025:31600, - 58026:31601, - 58027:31596, - 58028:31598, - 58029:31645, - 58030:31640, - 58031:31647, - 58032:31629, - 58033:31644, - 58034:31642, - 58035:31627, - 58036:31634, - 58037:31631, - 58038:31581, - 58039:31641, - 58040:31691, - 58041:31681, - 58042:31692, - 58043:31695, - 58044:31668, - 58045:31686, - 58046:31709, - 58047:31721, - 58048:31761, - 58049:31764, - 58050:31718, - 58051:31717, - 58052:31840, - 58053:31744, - 58054:31751, - 58055:31763, - 58056:31731, - 58057:31735, - 58058:31767, - 58059:31757, - 58060:31734, - 58061:31779, - 58062:31783, - 58063:31786, - 58064:31775, - 58065:31799, - 58066:31787, - 58067:31805, - 58068:31820, - 58069:31811, - 58070:31828, - 58071:31823, - 58072:31808, - 58073:31824, - 58074:31832, - 58075:31839, - 58076:31844, - 58077:31830, - 58078:31845, - 58079:31852, - 58080:31861, - 58081:31875, - 58082:31888, - 58083:31908, - 58084:31917, - 58085:31906, - 58086:31915, - 58087:31905, - 58088:31912, - 58089:31923, - 58090:31922, - 58091:31921, - 58092:31918, - 58093:31929, - 58094:31933, - 58095:31936, - 58096:31941, - 58097:31938, - 58098:31960, - 58099:31954, - 58100:31964, - 58101:31970, - 58102:39739, - 58103:31983, - 58104:31986, - 58105:31988, - 58106:31990, - 58107:31994, - 58108:32006, - 58176:32002, - 58177:32028, - 58178:32021, - 58179:32010, - 58180:32069, - 58181:32075, - 58182:32046, - 58183:32050, - 58184:32063, - 58185:32053, - 58186:32070, - 58187:32115, - 58188:32086, - 58189:32078, - 58190:32114, - 58191:32104, - 58192:32110, - 58193:32079, - 58194:32099, - 58195:32147, - 58196:32137, - 58197:32091, - 58198:32143, - 58199:32125, - 58200:32155, - 58201:32186, - 58202:32174, - 58203:32163, - 58204:32181, - 58205:32199, - 58206:32189, - 58207:32171, - 58208:32317, - 58209:32162, - 58210:32175, - 58211:32220, - 58212:32184, - 58213:32159, - 58214:32176, - 58215:32216, - 58216:32221, - 58217:32228, - 58218:32222, - 58219:32251, - 58220:32242, - 58221:32225, - 58222:32261, - 58223:32266, - 58224:32291, - 58225:32289, - 58226:32274, - 58227:32305, - 58228:32287, - 58229:32265, - 58230:32267, - 58231:32290, - 58232:32326, - 58233:32358, - 58234:32315, - 58235:32309, - 58236:32313, - 58237:32323, - 58238:32311, - 58240:32306, - 58241:32314, - 58242:32359, - 58243:32349, - 58244:32342, - 58245:32350, - 58246:32345, - 58247:32346, - 58248:32377, - 58249:32362, - 58250:32361, - 58251:32380, - 58252:32379, - 58253:32387, - 58254:32213, - 58255:32381, - 58256:36782, - 58257:32383, - 58258:32392, - 58259:32393, - 58260:32396, - 58261:32402, - 58262:32400, - 58263:32403, - 58264:32404, - 58265:32406, - 58266:32398, - 58267:32411, - 58268:32412, - 58269:32568, - 58270:32570, - 58271:32581, - 58272:32588, - 58273:32589, - 58274:32590, - 58275:32592, - 58276:32593, - 58277:32597, - 58278:32596, - 58279:32600, - 58280:32607, - 58281:32608, - 58282:32616, - 58283:32617, - 58284:32615, - 58285:32632, - 58286:32642, - 58287:32646, - 58288:32643, - 58289:32648, - 58290:32647, - 58291:32652, - 58292:32660, - 58293:32670, - 58294:32669, - 58295:32666, - 58296:32675, - 58297:32687, - 58298:32690, - 58299:32697, - 58300:32686, - 58301:32694, - 58302:32696, - 58303:35697, - 58304:32709, - 58305:32710, - 58306:32714, - 58307:32725, - 58308:32724, - 58309:32737, - 58310:32742, - 58311:32745, - 58312:32755, - 58313:32761, - 58314:39132, - 58315:32774, - 58316:32772, - 58317:32779, - 58318:32786, - 58319:32792, - 58320:32793, - 58321:32796, - 58322:32801, - 58323:32808, - 58324:32831, - 58325:32827, - 58326:32842, - 58327:32838, - 58328:32850, - 58329:32856, - 58330:32858, - 58331:32863, - 58332:32866, - 58333:32872, - 58334:32883, - 58335:32882, - 58336:32880, - 58337:32886, - 58338:32889, - 58339:32893, - 58340:32895, - 58341:32900, - 58342:32902, - 58343:32901, - 58344:32923, - 58345:32915, - 58346:32922, - 58347:32941, - 58348:20880, - 58349:32940, - 58350:32987, - 58351:32997, - 58352:32985, - 58353:32989, - 58354:32964, - 58355:32986, - 58356:32982, - 58357:33033, - 58358:33007, - 58359:33009, - 58360:33051, - 58361:33065, - 58362:33059, - 58363:33071, - 58364:33099, - 58432:38539, - 58433:33094, - 58434:33086, - 58435:33107, - 58436:33105, - 58437:33020, - 58438:33137, - 58439:33134, - 58440:33125, - 58441:33126, - 58442:33140, - 58443:33155, - 58444:33160, - 58445:33162, - 58446:33152, - 58447:33154, - 58448:33184, - 58449:33173, - 58450:33188, - 58451:33187, - 58452:33119, - 58453:33171, - 58454:33193, - 58455:33200, - 58456:33205, - 58457:33214, - 58458:33208, - 58459:33213, - 58460:33216, - 58461:33218, - 58462:33210, - 58463:33225, - 58464:33229, - 58465:33233, - 58466:33241, - 58467:33240, - 58468:33224, - 58469:33242, - 58470:33247, - 58471:33248, - 58472:33255, - 58473:33274, - 58474:33275, - 58475:33278, - 58476:33281, - 58477:33282, - 58478:33285, - 58479:33287, - 58480:33290, - 58481:33293, - 58482:33296, - 58483:33302, - 58484:33321, - 58485:33323, - 58486:33336, - 58487:33331, - 58488:33344, - 58489:33369, - 58490:33368, - 58491:33373, - 58492:33370, - 58493:33375, - 58494:33380, - 58496:33378, - 58497:33384, - 58498:33386, - 58499:33387, - 58500:33326, - 58501:33393, - 58502:33399, - 58503:33400, - 58504:33406, - 58505:33421, - 58506:33426, - 58507:33451, - 58508:33439, - 58509:33467, - 58510:33452, - 58511:33505, - 58512:33507, - 58513:33503, - 58514:33490, - 58515:33524, - 58516:33523, - 58517:33530, - 58518:33683, - 58519:33539, - 58520:33531, - 58521:33529, - 58522:33502, - 58523:33542, - 58524:33500, - 58525:33545, - 58526:33497, - 58527:33589, - 58528:33588, - 58529:33558, - 58530:33586, - 58531:33585, - 58532:33600, - 58533:33593, - 58534:33616, - 58535:33605, - 58536:33583, - 58537:33579, - 58538:33559, - 58539:33560, - 58540:33669, - 58541:33690, - 58542:33706, - 58543:33695, - 58544:33698, - 58545:33686, - 58546:33571, - 58547:33678, - 58548:33671, - 58549:33674, - 58550:33660, - 58551:33717, - 58552:33651, - 58553:33653, - 58554:33696, - 58555:33673, - 58556:33704, - 58557:33780, - 58558:33811, - 58559:33771, - 58560:33742, - 58561:33789, - 58562:33795, - 58563:33752, - 58564:33803, - 58565:33729, - 58566:33783, - 58567:33799, - 58568:33760, - 58569:33778, - 58570:33805, - 58571:33826, - 58572:33824, - 58573:33725, - 58574:33848, - 58575:34054, - 58576:33787, - 58577:33901, - 58578:33834, - 58579:33852, - 58580:34138, - 58581:33924, - 58582:33911, - 58583:33899, - 58584:33965, - 58585:33902, - 58586:33922, - 58587:33897, - 58588:33862, - 58589:33836, - 58590:33903, - 58591:33913, - 58592:33845, - 58593:33994, - 58594:33890, - 58595:33977, - 58596:33983, - 58597:33951, - 58598:34009, - 58599:33997, - 58600:33979, - 58601:34010, - 58602:34000, - 58603:33985, - 58604:33990, - 58605:34006, - 58606:33953, - 58607:34081, - 58608:34047, - 58609:34036, - 58610:34071, - 58611:34072, - 58612:34092, - 58613:34079, - 58614:34069, - 58615:34068, - 58616:34044, - 58617:34112, - 58618:34147, - 58619:34136, - 58620:34120, - 58688:34113, - 58689:34306, - 58690:34123, - 58691:34133, - 58692:34176, - 58693:34212, - 58694:34184, - 58695:34193, - 58696:34186, - 58697:34216, - 58698:34157, - 58699:34196, - 58700:34203, - 58701:34282, - 58702:34183, - 58703:34204, - 58704:34167, - 58705:34174, - 58706:34192, - 58707:34249, - 58708:34234, - 58709:34255, - 58710:34233, - 58711:34256, - 58712:34261, - 58713:34269, - 58714:34277, - 58715:34268, - 58716:34297, - 58717:34314, - 58718:34323, - 58719:34315, - 58720:34302, - 58721:34298, - 58722:34310, - 58723:34338, - 58724:34330, - 58725:34352, - 58726:34367, - 58727:34381, - 58728:20053, - 58729:34388, - 58730:34399, - 58731:34407, - 58732:34417, - 58733:34451, - 58734:34467, - 58735:34473, - 58736:34474, - 58737:34443, - 58738:34444, - 58739:34486, - 58740:34479, - 58741:34500, - 58742:34502, - 58743:34480, - 58744:34505, - 58745:34851, - 58746:34475, - 58747:34516, - 58748:34526, - 58749:34537, - 58750:34540, - 58752:34527, - 58753:34523, - 58754:34543, - 58755:34578, - 58756:34566, - 58757:34568, - 58758:34560, - 58759:34563, - 58760:34555, - 58761:34577, - 58762:34569, - 58763:34573, - 58764:34553, - 58765:34570, - 58766:34612, - 58767:34623, - 58768:34615, - 58769:34619, - 58770:34597, - 58771:34601, - 58772:34586, - 58773:34656, - 58774:34655, - 58775:34680, - 58776:34636, - 58777:34638, - 58778:34676, - 58779:34647, - 58780:34664, - 58781:34670, - 58782:34649, - 58783:34643, - 58784:34659, - 58785:34666, - 58786:34821, - 58787:34722, - 58788:34719, - 58789:34690, - 58790:34735, - 58791:34763, - 58792:34749, - 58793:34752, - 58794:34768, - 58795:38614, - 58796:34731, - 58797:34756, - 58798:34739, - 58799:34759, - 58800:34758, - 58801:34747, - 58802:34799, - 58803:34802, - 58804:34784, - 58805:34831, - 58806:34829, - 58807:34814, - 58808:34806, - 58809:34807, - 58810:34830, - 58811:34770, - 58812:34833, - 58813:34838, - 58814:34837, - 58815:34850, - 58816:34849, - 58817:34865, - 58818:34870, - 58819:34873, - 58820:34855, - 58821:34875, - 58822:34884, - 58823:34882, - 58824:34898, - 58825:34905, - 58826:34910, - 58827:34914, - 58828:34923, - 58829:34945, - 58830:34942, - 58831:34974, - 58832:34933, - 58833:34941, - 58834:34997, - 58835:34930, - 58836:34946, - 58837:34967, - 58838:34962, - 58839:34990, - 58840:34969, - 58841:34978, - 58842:34957, - 58843:34980, - 58844:34992, - 58845:35007, - 58846:34993, - 58847:35011, - 58848:35012, - 58849:35028, - 58850:35032, - 58851:35033, - 58852:35037, - 58853:35065, - 58854:35074, - 58855:35068, - 58856:35060, - 58857:35048, - 58858:35058, - 58859:35076, - 58860:35084, - 58861:35082, - 58862:35091, - 58863:35139, - 58864:35102, - 58865:35109, - 58866:35114, - 58867:35115, - 58868:35137, - 58869:35140, - 58870:35131, - 58871:35126, - 58872:35128, - 58873:35148, - 58874:35101, - 58875:35168, - 58876:35166, - 58944:35174, - 58945:35172, - 58946:35181, - 58947:35178, - 58948:35183, - 58949:35188, - 58950:35191, - 58951:35198, - 58952:35203, - 58953:35208, - 58954:35210, - 58955:35219, - 58956:35224, - 58957:35233, - 58958:35241, - 58959:35238, - 58960:35244, - 58961:35247, - 58962:35250, - 58963:35258, - 58964:35261, - 58965:35263, - 58966:35264, - 58967:35290, - 58968:35292, - 58969:35293, - 58970:35303, - 58971:35316, - 58972:35320, - 58973:35331, - 58974:35350, - 58975:35344, - 58976:35340, - 58977:35355, - 58978:35357, - 58979:35365, - 58980:35382, - 58981:35393, - 58982:35419, - 58983:35410, - 58984:35398, - 58985:35400, - 58986:35452, - 58987:35437, - 58988:35436, - 58989:35426, - 58990:35461, - 58991:35458, - 58992:35460, - 58993:35496, - 58994:35489, - 58995:35473, - 58996:35493, - 58997:35494, - 58998:35482, - 58999:35491, - 59000:35524, - 59001:35533, - 59002:35522, - 59003:35546, - 59004:35563, - 59005:35571, - 59006:35559, - 59008:35556, - 59009:35569, - 59010:35604, - 59011:35552, - 59012:35554, - 59013:35575, - 59014:35550, - 59015:35547, - 59016:35596, - 59017:35591, - 59018:35610, - 59019:35553, - 59020:35606, - 59021:35600, - 59022:35607, - 59023:35616, - 59024:35635, - 59025:38827, - 59026:35622, - 59027:35627, - 59028:35646, - 59029:35624, - 59030:35649, - 59031:35660, - 59032:35663, - 59033:35662, - 59034:35657, - 59035:35670, - 59036:35675, - 59037:35674, - 59038:35691, - 59039:35679, - 59040:35692, - 59041:35695, - 59042:35700, - 59043:35709, - 59044:35712, - 59045:35724, - 59046:35726, - 59047:35730, - 59048:35731, - 59049:35734, - 59050:35737, - 59051:35738, - 59052:35898, - 59053:35905, - 59054:35903, - 59055:35912, - 59056:35916, - 59057:35918, - 59058:35920, - 59059:35925, - 59060:35938, - 59061:35948, - 59062:35960, - 59063:35962, - 59064:35970, - 59065:35977, - 59066:35973, - 59067:35978, - 59068:35981, - 59069:35982, - 59070:35988, - 59071:35964, - 59072:35992, - 59073:25117, - 59074:36013, - 59075:36010, - 59076:36029, - 59077:36018, - 59078:36019, - 59079:36014, - 59080:36022, - 59081:36040, - 59082:36033, - 59083:36068, - 59084:36067, - 59085:36058, - 59086:36093, - 59087:36090, - 59088:36091, - 59089:36100, - 59090:36101, - 59091:36106, - 59092:36103, - 59093:36111, - 59094:36109, - 59095:36112, - 59096:40782, - 59097:36115, - 59098:36045, - 59099:36116, - 59100:36118, - 59101:36199, - 59102:36205, - 59103:36209, - 59104:36211, - 59105:36225, - 59106:36249, - 59107:36290, - 59108:36286, - 59109:36282, - 59110:36303, - 59111:36314, - 59112:36310, - 59113:36300, - 59114:36315, - 59115:36299, - 59116:36330, - 59117:36331, - 59118:36319, - 59119:36323, - 59120:36348, - 59121:36360, - 59122:36361, - 59123:36351, - 59124:36381, - 59125:36382, - 59126:36368, - 59127:36383, - 59128:36418, - 59129:36405, - 59130:36400, - 59131:36404, - 59132:36426, - 59200:36423, - 59201:36425, - 59202:36428, - 59203:36432, - 59204:36424, - 59205:36441, - 59206:36452, - 59207:36448, - 59208:36394, - 59209:36451, - 59210:36437, - 59211:36470, - 59212:36466, - 59213:36476, - 59214:36481, - 59215:36487, - 59216:36485, - 59217:36484, - 59218:36491, - 59219:36490, - 59220:36499, - 59221:36497, - 59222:36500, - 59223:36505, - 59224:36522, - 59225:36513, - 59226:36524, - 59227:36528, - 59228:36550, - 59229:36529, - 59230:36542, - 59231:36549, - 59232:36552, - 59233:36555, - 59234:36571, - 59235:36579, - 59236:36604, - 59237:36603, - 59238:36587, - 59239:36606, - 59240:36618, - 59241:36613, - 59242:36629, - 59243:36626, - 59244:36633, - 59245:36627, - 59246:36636, - 59247:36639, - 59248:36635, - 59249:36620, - 59250:36646, - 59251:36659, - 59252:36667, - 59253:36665, - 59254:36677, - 59255:36674, - 59256:36670, - 59257:36684, - 59258:36681, - 59259:36678, - 59260:36686, - 59261:36695, - 59262:36700, - 59264:36706, - 59265:36707, - 59266:36708, - 59267:36764, - 59268:36767, - 59269:36771, - 59270:36781, - 59271:36783, - 59272:36791, - 59273:36826, - 59274:36837, - 59275:36834, - 59276:36842, - 59277:36847, - 59278:36999, - 59279:36852, - 59280:36869, - 59281:36857, - 59282:36858, - 59283:36881, - 59284:36885, - 59285:36897, - 59286:36877, - 59287:36894, - 59288:36886, - 59289:36875, - 59290:36903, - 59291:36918, - 59292:36917, - 59293:36921, - 59294:36856, - 59295:36943, - 59296:36944, - 59297:36945, - 59298:36946, - 59299:36878, - 59300:36937, - 59301:36926, - 59302:36950, - 59303:36952, - 59304:36958, - 59305:36968, - 59306:36975, - 59307:36982, - 59308:38568, - 59309:36978, - 59310:36994, - 59311:36989, - 59312:36993, - 59313:36992, - 59314:37002, - 59315:37001, - 59316:37007, - 59317:37032, - 59318:37039, - 59319:37041, - 59320:37045, - 59321:37090, - 59322:37092, - 59323:25160, - 59324:37083, - 59325:37122, - 59326:37138, - 59327:37145, - 59328:37170, - 59329:37168, - 59330:37194, - 59331:37206, - 59332:37208, - 59333:37219, - 59334:37221, - 59335:37225, - 59336:37235, - 59337:37234, - 59338:37259, - 59339:37257, - 59340:37250, - 59341:37282, - 59342:37291, - 59343:37295, - 59344:37290, - 59345:37301, - 59346:37300, - 59347:37306, - 59348:37312, - 59349:37313, - 59350:37321, - 59351:37323, - 59352:37328, - 59353:37334, - 59354:37343, - 59355:37345, - 59356:37339, - 59357:37372, - 59358:37365, - 59359:37366, - 59360:37406, - 59361:37375, - 59362:37396, - 59363:37420, - 59364:37397, - 59365:37393, - 59366:37470, - 59367:37463, - 59368:37445, - 59369:37449, - 59370:37476, - 59371:37448, - 59372:37525, - 59373:37439, - 59374:37451, - 59375:37456, - 59376:37532, - 59377:37526, - 59378:37523, - 59379:37531, - 59380:37466, - 59381:37583, - 59382:37561, - 59383:37559, - 59384:37609, - 59385:37647, - 59386:37626, - 59387:37700, - 59388:37678, - 59456:37657, - 59457:37666, - 59458:37658, - 59459:37667, - 59460:37690, - 59461:37685, - 59462:37691, - 59463:37724, - 59464:37728, - 59465:37756, - 59466:37742, - 59467:37718, - 59468:37808, - 59469:37804, - 59470:37805, - 59471:37780, - 59472:37817, - 59473:37846, - 59474:37847, - 59475:37864, - 59476:37861, - 59477:37848, - 59478:37827, - 59479:37853, - 59480:37840, - 59481:37832, - 59482:37860, - 59483:37914, - 59484:37908, - 59485:37907, - 59486:37891, - 59487:37895, - 59488:37904, - 59489:37942, - 59490:37931, - 59491:37941, - 59492:37921, - 59493:37946, - 59494:37953, - 59495:37970, - 59496:37956, - 59497:37979, - 59498:37984, - 59499:37986, - 59500:37982, - 59501:37994, - 59502:37417, - 59503:38000, - 59504:38005, - 59505:38007, - 59506:38013, - 59507:37978, - 59508:38012, - 59509:38014, - 59510:38017, - 59511:38015, - 59512:38274, - 59513:38279, - 59514:38282, - 59515:38292, - 59516:38294, - 59517:38296, - 59518:38297, - 59520:38304, - 59521:38312, - 59522:38311, - 59523:38317, - 59524:38332, - 59525:38331, - 59526:38329, - 59527:38334, - 59528:38346, - 59529:28662, - 59530:38339, - 59531:38349, - 59532:38348, - 59533:38357, - 59534:38356, - 59535:38358, - 59536:38364, - 59537:38369, - 59538:38373, - 59539:38370, - 59540:38433, - 59541:38440, - 59542:38446, - 59543:38447, - 59544:38466, - 59545:38476, - 59546:38479, - 59547:38475, - 59548:38519, - 59549:38492, - 59550:38494, - 59551:38493, - 59552:38495, - 59553:38502, - 59554:38514, - 59555:38508, - 59556:38541, - 59557:38552, - 59558:38549, - 59559:38551, - 59560:38570, - 59561:38567, - 59562:38577, - 59563:38578, - 59564:38576, - 59565:38580, - 59566:38582, - 59567:38584, - 59568:38585, - 59569:38606, - 59570:38603, - 59571:38601, - 59572:38605, - 59573:35149, - 59574:38620, - 59575:38669, - 59576:38613, - 59577:38649, - 59578:38660, - 59579:38662, - 59580:38664, - 59581:38675, - 59582:38670, - 59583:38673, - 59584:38671, - 59585:38678, - 59586:38681, - 59587:38692, - 59588:38698, - 59589:38704, - 59590:38713, - 59591:38717, - 59592:38718, - 59593:38724, - 59594:38726, - 59595:38728, - 59596:38722, - 59597:38729, - 59598:38748, - 59599:38752, - 59600:38756, - 59601:38758, - 59602:38760, - 59603:21202, - 59604:38763, - 59605:38769, - 59606:38777, - 59607:38789, - 59608:38780, - 59609:38785, - 59610:38778, - 59611:38790, - 59612:38795, - 59613:38799, - 59614:38800, - 59615:38812, - 59616:38824, - 59617:38822, - 59618:38819, - 59619:38835, - 59620:38836, - 59621:38851, - 59622:38854, - 59623:38856, - 59624:38859, - 59625:38876, - 59626:38893, - 59627:40783, - 59628:38898, - 59629:31455, - 59630:38902, - 59631:38901, - 59632:38927, - 59633:38924, - 59634:38968, - 59635:38948, - 59636:38945, - 59637:38967, - 59638:38973, - 59639:38982, - 59640:38991, - 59641:38987, - 59642:39019, - 59643:39023, - 59644:39024, - 59712:39025, - 59713:39028, - 59714:39027, - 59715:39082, - 59716:39087, - 59717:39089, - 59718:39094, - 59719:39108, - 59720:39107, - 59721:39110, - 59722:39145, - 59723:39147, - 59724:39171, - 59725:39177, - 59726:39186, - 59727:39188, - 59728:39192, - 59729:39201, - 59730:39197, - 59731:39198, - 59732:39204, - 59733:39200, - 59734:39212, - 59735:39214, - 59736:39229, - 59737:39230, - 59738:39234, - 59739:39241, - 59740:39237, - 59741:39248, - 59742:39243, - 59743:39249, - 59744:39250, - 59745:39244, - 59746:39253, - 59747:39319, - 59748:39320, - 59749:39333, - 59750:39341, - 59751:39342, - 59752:39356, - 59753:39391, - 59754:39387, - 59755:39389, - 59756:39384, - 59757:39377, - 59758:39405, - 59759:39406, - 59760:39409, - 59761:39410, - 59762:39419, - 59763:39416, - 59764:39425, - 59765:39439, - 59766:39429, - 59767:39394, - 59768:39449, - 59769:39467, - 59770:39479, - 59771:39493, - 59772:39490, - 59773:39488, - 59774:39491, - 59776:39486, - 59777:39509, - 59778:39501, - 59779:39515, - 59780:39511, - 59781:39519, - 59782:39522, - 59783:39525, - 59784:39524, - 59785:39529, - 59786:39531, - 59787:39530, - 59788:39597, - 59789:39600, - 59790:39612, - 59791:39616, - 59792:39631, - 59793:39633, - 59794:39635, - 59795:39636, - 59796:39646, - 59797:39647, - 59798:39650, - 59799:39651, - 59800:39654, - 59801:39663, - 59802:39659, - 59803:39662, - 59804:39668, - 59805:39665, - 59806:39671, - 59807:39675, - 59808:39686, - 59809:39704, - 59810:39706, - 59811:39711, - 59812:39714, - 59813:39715, - 59814:39717, - 59815:39719, - 59816:39720, - 59817:39721, - 59818:39722, - 59819:39726, - 59820:39727, - 59821:39730, - 59822:39748, - 59823:39747, - 59824:39759, - 59825:39757, - 59826:39758, - 59827:39761, - 59828:39768, - 59829:39796, - 59830:39827, - 59831:39811, - 59832:39825, - 59833:39830, - 59834:39831, - 59835:39839, - 59836:39840, - 59837:39848, - 59838:39860, - 59839:39872, - 59840:39882, - 59841:39865, - 59842:39878, - 59843:39887, - 59844:39889, - 59845:39890, - 59846:39907, - 59847:39906, - 59848:39908, - 59849:39892, - 59850:39905, - 59851:39994, - 59852:39922, - 59853:39921, - 59854:39920, - 59855:39957, - 59856:39956, - 59857:39945, - 59858:39955, - 59859:39948, - 59860:39942, - 59861:39944, - 59862:39954, - 59863:39946, - 59864:39940, - 59865:39982, - 59866:39963, - 59867:39973, - 59868:39972, - 59869:39969, - 59870:39984, - 59871:40007, - 59872:39986, - 59873:40006, - 59874:39998, - 59875:40026, - 59876:40032, - 59877:40039, - 59878:40054, - 59879:40056, - 59880:40167, - 59881:40172, - 59882:40176, - 59883:40201, - 59884:40200, - 59885:40171, - 59886:40195, - 59887:40198, - 59888:40234, - 59889:40230, - 59890:40367, - 59891:40227, - 59892:40223, - 59893:40260, - 59894:40213, - 59895:40210, - 59896:40257, - 59897:40255, - 59898:40254, - 59899:40262, - 59900:40264, - 59968:40285, - 59969:40286, - 59970:40292, - 59971:40273, - 59972:40272, - 59973:40281, - 59974:40306, - 59975:40329, - 59976:40327, - 59977:40363, - 59978:40303, - 59979:40314, - 59980:40346, - 59981:40356, - 59982:40361, - 59983:40370, - 59984:40388, - 59985:40385, - 59986:40379, - 59987:40376, - 59988:40378, - 59989:40390, - 59990:40399, - 59991:40386, - 59992:40409, - 59993:40403, - 59994:40440, - 59995:40422, - 59996:40429, - 59997:40431, - 59998:40445, - 59999:40474, - 60000:40475, - 60001:40478, - 60002:40565, - 60003:40569, - 60004:40573, - 60005:40577, - 60006:40584, - 60007:40587, - 60008:40588, - 60009:40594, - 60010:40597, - 60011:40593, - 60012:40605, - 60013:40613, - 60014:40617, - 60015:40632, - 60016:40618, - 60017:40621, - 60018:38753, - 60019:40652, - 60020:40654, - 60021:40655, - 60022:40656, - 60023:40660, - 60024:40668, - 60025:40670, - 60026:40669, - 60027:40672, - 60028:40677, - 60029:40680, - 60030:40687, - 60032:40692, - 60033:40694, - 60034:40695, - 60035:40697, - 60036:40699, - 60037:40700, - 60038:40701, - 60039:40711, - 60040:40712, - 60041:30391, - 60042:40725, - 60043:40737, - 60044:40748, - 60045:40766, - 60046:40778, - 60047:40786, - 60048:40788, - 60049:40803, - 60050:40799, - 60051:40800, - 60052:40801, - 60053:40806, - 60054:40807, - 60055:40812, - 60056:40810, - 60057:40823, - 60058:40818, - 60059:40822, - 60060:40853, - 60061:40860, - 60062:40864, - 60063:22575, - 60064:27079, - 60065:36953, - 60066:29796, - 60067:20956, - 60068:29081, - 60736:32394, - 60737:35100, - 60738:37704, - 60739:37512, - 60740:34012, - 60741:20425, - 60742:28859, - 60743:26161, - 60744:26824, - 60745:37625, - 60746:26363, - 60747:24389, - 60748:20008, - 60749:20193, - 60750:20220, - 60751:20224, - 60752:20227, - 60753:20281, - 60754:20310, - 60755:20370, - 60756:20362, - 60757:20378, - 60758:20372, - 60759:20429, - 60760:20544, - 60761:20514, - 60762:20479, - 60763:20510, - 60764:20550, - 60765:20592, - 60766:20546, - 60767:20628, - 60768:20724, - 60769:20696, - 60770:20810, - 60771:20836, - 60772:20893, - 60773:20926, - 60774:20972, - 60775:21013, - 60776:21148, - 60777:21158, - 60778:21184, - 60779:21211, - 60780:21248, - 60781:21255, - 60782:21284, - 60783:21362, - 60784:21395, - 60785:21426, - 60786:21469, - 60787:64014, - 60788:21660, - 60789:21642, - 60790:21673, - 60791:21759, - 60792:21894, - 60793:22361, - 60794:22373, - 60795:22444, - 60796:22472, - 60797:22471, - 60798:64015, - 60800:64016, - 60801:22686, - 60802:22706, - 60803:22795, - 60804:22867, - 60805:22875, - 60806:22877, - 60807:22883, - 60808:22948, - 60809:22970, - 60810:23382, - 60811:23488, - 60812:29999, - 60813:23512, - 60814:23532, - 60815:23582, - 60816:23718, - 60817:23738, - 60818:23797, - 60819:23847, - 60820:23891, - 60821:64017, - 60822:23874, - 60823:23917, - 60824:23992, - 60825:23993, - 60826:24016, - 60827:24353, - 60828:24372, - 60829:24423, - 60830:24503, - 60831:24542, - 60832:24669, - 60833:24709, - 60834:24714, - 60835:24798, - 60836:24789, - 60837:24864, - 60838:24818, - 60839:24849, - 60840:24887, - 60841:24880, - 60842:24984, - 60843:25107, - 60844:25254, - 60845:25589, - 60846:25696, - 60847:25757, - 60848:25806, - 60849:25934, - 60850:26112, - 60851:26133, - 60852:26171, - 60853:26121, - 60854:26158, - 60855:26142, - 60856:26148, - 60857:26213, - 60858:26199, - 60859:26201, - 60860:64018, - 60861:26227, - 60862:26265, - 60863:26272, - 60864:26290, - 60865:26303, - 60866:26362, - 60867:26382, - 60868:63785, - 60869:26470, - 60870:26555, - 60871:26706, - 60872:26560, - 60873:26625, - 60874:26692, - 60875:26831, - 60876:64019, - 60877:26984, - 60878:64020, - 60879:27032, - 60880:27106, - 60881:27184, - 60882:27243, - 60883:27206, - 60884:27251, - 60885:27262, - 60886:27362, - 60887:27364, - 60888:27606, - 60889:27711, - 60890:27740, - 60891:27782, - 60892:27759, - 60893:27866, - 60894:27908, - 60895:28039, - 60896:28015, - 60897:28054, - 60898:28076, - 60899:28111, - 60900:28152, - 60901:28146, - 60902:28156, - 60903:28217, - 60904:28252, - 60905:28199, - 60906:28220, - 60907:28351, - 60908:28552, - 60909:28597, - 60910:28661, - 60911:28677, - 60912:28679, - 60913:28712, - 60914:28805, - 60915:28843, - 60916:28943, - 60917:28932, - 60918:29020, - 60919:28998, - 60920:28999, - 60921:64021, - 60922:29121, - 60923:29182, - 60924:29361, - 60992:29374, - 60993:29476, - 60994:64022, - 60995:29559, - 60996:29629, - 60997:29641, - 60998:29654, - 60999:29667, - 61000:29650, - 61001:29703, - 61002:29685, - 61003:29734, - 61004:29738, - 61005:29737, - 61006:29742, - 61007:29794, - 61008:29833, - 61009:29855, - 61010:29953, - 61011:30063, - 61012:30338, - 61013:30364, - 61014:30366, - 61015:30363, - 61016:30374, - 61017:64023, - 61018:30534, - 61019:21167, - 61020:30753, - 61021:30798, - 61022:30820, - 61023:30842, - 61024:31024, - 61025:64024, - 61026:64025, - 61027:64026, - 61028:31124, - 61029:64027, - 61030:31131, - 61031:31441, - 61032:31463, - 61033:64028, - 61034:31467, - 61035:31646, - 61036:64029, - 61037:32072, - 61038:32092, - 61039:32183, - 61040:32160, - 61041:32214, - 61042:32338, - 61043:32583, - 61044:32673, - 61045:64030, - 61046:33537, - 61047:33634, - 61048:33663, - 61049:33735, - 61050:33782, - 61051:33864, - 61052:33972, - 61053:34131, - 61054:34137, - 61056:34155, - 61057:64031, - 61058:34224, - 61059:64032, - 61060:64033, - 61061:34823, - 61062:35061, - 61063:35346, - 61064:35383, - 61065:35449, - 61066:35495, - 61067:35518, - 61068:35551, - 61069:64034, - 61070:35574, - 61071:35667, - 61072:35711, - 61073:36080, - 61074:36084, - 61075:36114, - 61076:36214, - 61077:64035, - 61078:36559, - 61079:64036, - 61080:64037, - 61081:36967, - 61082:37086, - 61083:64038, - 61084:37141, - 61085:37159, - 61086:37338, - 61087:37335, - 61088:37342, - 61089:37357, - 61090:37358, - 61091:37348, - 61092:37349, - 61093:37382, - 61094:37392, - 61095:37386, - 61096:37434, - 61097:37440, - 61098:37436, - 61099:37454, - 61100:37465, - 61101:37457, - 61102:37433, - 61103:37479, - 61104:37543, - 61105:37495, - 61106:37496, - 61107:37607, - 61108:37591, - 61109:37593, - 61110:37584, - 61111:64039, - 61112:37589, - 61113:37600, - 61114:37587, - 61115:37669, - 61116:37665, - 61117:37627, - 61118:64040, - 61119:37662, - 61120:37631, - 61121:37661, - 61122:37634, - 61123:37744, - 61124:37719, - 61125:37796, - 61126:37830, - 61127:37854, - 61128:37880, - 61129:37937, - 61130:37957, - 61131:37960, - 61132:38290, - 61133:63964, - 61134:64041, - 61135:38557, - 61136:38575, - 61137:38707, - 61138:38715, - 61139:38723, - 61140:38733, - 61141:38735, - 61142:38737, - 61143:38741, - 61144:38999, - 61145:39013, - 61146:64042, - 61147:64043, - 61148:39207, - 61149:64044, - 61150:39326, - 61151:39502, - 61152:39641, - 61153:39644, - 61154:39797, - 61155:39794, - 61156:39823, - 61157:39857, - 61158:39867, - 61159:39936, - 61160:40304, - 61161:40299, - 61162:64045, - 61163:40473, - 61164:40657, - 61167:8560, - 61168:8561, - 61169:8562, - 61170:8563, - 61171:8564, - 61172:8565, - 61173:8566, - 61174:8567, - 61175:8568, - 61176:8569, - 61177:65506, - 61178:65508, - 61179:65287, - 61180:65282, - 61504:57344, - 61505:57345, - 61506:57346, - 61507:57347, - 61508:57348, - 61509:57349, - 61510:57350, - 61511:57351, - 61512:57352, - 61513:57353, - 61514:57354, - 61515:57355, - 61516:57356, - 61517:57357, - 61518:57358, - 61519:57359, - 61520:57360, - 61521:57361, - 61522:57362, - 61523:57363, - 61524:57364, - 61525:57365, - 61526:57366, - 61527:57367, - 61528:57368, - 61529:57369, - 61530:57370, - 61531:57371, - 61532:57372, - 61533:57373, - 61534:57374, - 61535:57375, - 61536:57376, - 61537:57377, - 61538:57378, - 61539:57379, - 61540:57380, - 61541:57381, - 61542:57382, - 61543:57383, - 61544:57384, - 61545:57385, - 61546:57386, - 61547:57387, - 61548:57388, - 61549:57389, - 61550:57390, - 61551:57391, - 61552:57392, - 61553:57393, - 61554:57394, - 61555:57395, - 61556:57396, - 61557:57397, - 61558:57398, - 61559:57399, - 61560:57400, - 61561:57401, - 61562:57402, - 61563:57403, - 61564:57404, - 61565:57405, - 61566:57406, - 61568:57407, - 61569:57408, - 61570:57409, - 61571:57410, - 61572:57411, - 61573:57412, - 61574:57413, - 61575:57414, - 61576:57415, - 61577:57416, - 61578:57417, - 61579:57418, - 61580:57419, - 61581:57420, - 61582:57421, - 61583:57422, - 61584:57423, - 61585:57424, - 61586:57425, - 61587:57426, - 61588:57427, - 61589:57428, - 61590:57429, - 61591:57430, - 61592:57431, - 61593:57432, - 61594:57433, - 61595:57434, - 61596:57435, - 61597:57436, - 61598:57437, - 61599:57438, - 61600:57439, - 61601:57440, - 61602:57441, - 61603:57442, - 61604:57443, - 61605:57444, - 61606:57445, - 61607:57446, - 61608:57447, - 61609:57448, - 61610:57449, - 61611:57450, - 61612:57451, - 61613:57452, - 61614:57453, - 61615:57454, - 61616:57455, - 61617:57456, - 61618:57457, - 61619:57458, - 61620:57459, - 61621:57460, - 61622:57461, - 61623:57462, - 61624:57463, - 61625:57464, - 61626:57465, - 61627:57466, - 61628:57467, - 61629:57468, - 61630:57469, - 61631:57470, - 61632:57471, - 61633:57472, - 61634:57473, - 61635:57474, - 61636:57475, - 61637:57476, - 61638:57477, - 61639:57478, - 61640:57479, - 61641:57480, - 61642:57481, - 61643:57482, - 61644:57483, - 61645:57484, - 61646:57485, - 61647:57486, - 61648:57487, - 61649:57488, - 61650:57489, - 61651:57490, - 61652:57491, - 61653:57492, - 61654:57493, - 61655:57494, - 61656:57495, - 61657:57496, - 61658:57497, - 61659:57498, - 61660:57499, - 61661:57500, - 61662:57501, - 61663:57502, - 61664:57503, - 61665:57504, - 61666:57505, - 61667:57506, - 61668:57507, - 61669:57508, - 61670:57509, - 61671:57510, - 61672:57511, - 61673:57512, - 61674:57513, - 61675:57514, - 61676:57515, - 61677:57516, - 61678:57517, - 61679:57518, - 61680:57519, - 61681:57520, - 61682:57521, - 61683:57522, - 61684:57523, - 61685:57524, - 61686:57525, - 61687:57526, - 61688:57527, - 61689:57528, - 61690:57529, - 61691:57530, - 61692:57531, - 61760:57532, - 61761:57533, - 61762:57534, - 61763:57535, - 61764:57536, - 61765:57537, - 61766:57538, - 61767:57539, - 61768:57540, - 61769:57541, - 61770:57542, - 61771:57543, - 61772:57544, - 61773:57545, - 61774:57546, - 61775:57547, - 61776:57548, - 61777:57549, - 61778:57550, - 61779:57551, - 61780:57552, - 61781:57553, - 61782:57554, - 61783:57555, - 61784:57556, - 61785:57557, - 61786:57558, - 61787:57559, - 61788:57560, - 61789:57561, - 61790:57562, - 61791:57563, - 61792:57564, - 61793:57565, - 61794:57566, - 61795:57567, - 61796:57568, - 61797:57569, - 61798:57570, - 61799:57571, - 61800:57572, - 61801:57573, - 61802:57574, - 61803:57575, - 61804:57576, - 61805:57577, - 61806:57578, - 61807:57579, - 61808:57580, - 61809:57581, - 61810:57582, - 61811:57583, - 61812:57584, - 61813:57585, - 61814:57586, - 61815:57587, - 61816:57588, - 61817:57589, - 61818:57590, - 61819:57591, - 61820:57592, - 61821:57593, - 61822:57594, - 61824:57595, - 61825:57596, - 61826:57597, - 61827:57598, - 61828:57599, - 61829:57600, - 61830:57601, - 61831:57602, - 61832:57603, - 61833:57604, - 61834:57605, - 61835:57606, - 61836:57607, - 61837:57608, - 61838:57609, - 61839:57610, - 61840:57611, - 61841:57612, - 61842:57613, - 61843:57614, - 61844:57615, - 61845:57616, - 61846:57617, - 61847:57618, - 61848:57619, - 61849:57620, - 61850:57621, - 61851:57622, - 61852:57623, - 61853:57624, - 61854:57625, - 61855:57626, - 61856:57627, - 61857:57628, - 61858:57629, - 61859:57630, - 61860:57631, - 61861:57632, - 61862:57633, - 61863:57634, - 61864:57635, - 61865:57636, - 61866:57637, - 61867:57638, - 61868:57639, - 61869:57640, - 61870:57641, - 61871:57642, - 61872:57643, - 61873:57644, - 61874:57645, - 61875:57646, - 61876:57647, - 61877:57648, - 61878:57649, - 61879:57650, - 61880:57651, - 61881:57652, - 61882:57653, - 61883:57654, - 61884:57655, - 61885:57656, - 61886:57657, - 61887:57658, - 61888:57659, - 61889:57660, - 61890:57661, - 61891:57662, - 61892:57663, - 61893:57664, - 61894:57665, - 61895:57666, - 61896:57667, - 61897:57668, - 61898:57669, - 61899:57670, - 61900:57671, - 61901:57672, - 61902:57673, - 61903:57674, - 61904:57675, - 61905:57676, - 61906:57677, - 61907:57678, - 61908:57679, - 61909:57680, - 61910:57681, - 61911:57682, - 61912:57683, - 61913:57684, - 61914:57685, - 61915:57686, - 61916:57687, - 61917:57688, - 61918:57689, - 61919:57690, - 61920:57691, - 61921:57692, - 61922:57693, - 61923:57694, - 61924:57695, - 61925:57696, - 61926:57697, - 61927:57698, - 61928:57699, - 61929:57700, - 61930:57701, - 61931:57702, - 61932:57703, - 61933:57704, - 61934:57705, - 61935:57706, - 61936:57707, - 61937:57708, - 61938:57709, - 61939:57710, - 61940:57711, - 61941:57712, - 61942:57713, - 61943:57714, - 61944:57715, - 61945:57716, - 61946:57717, - 61947:57718, - 61948:57719, - 62016:57720, - 62017:57721, - 62018:57722, - 62019:57723, - 62020:57724, - 62021:57725, - 62022:57726, - 62023:57727, - 62024:57728, - 62025:57729, - 62026:57730, - 62027:57731, - 62028:57732, - 62029:57733, - 62030:57734, - 62031:57735, - 62032:57736, - 62033:57737, - 62034:57738, - 62035:57739, - 62036:57740, - 62037:57741, - 62038:57742, - 62039:57743, - 62040:57744, - 62041:57745, - 62042:57746, - 62043:57747, - 62044:57748, - 62045:57749, - 62046:57750, - 62047:57751, - 62048:57752, - 62049:57753, - 62050:57754, - 62051:57755, - 62052:57756, - 62053:57757, - 62054:57758, - 62055:57759, - 62056:57760, - 62057:57761, - 62058:57762, - 62059:57763, - 62060:57764, - 62061:57765, - 62062:57766, - 62063:57767, - 62064:57768, - 62065:57769, - 62066:57770, - 62067:57771, - 62068:57772, - 62069:57773, - 62070:57774, - 62071:57775, - 62072:57776, - 62073:57777, - 62074:57778, - 62075:57779, - 62076:57780, - 62077:57781, - 62078:57782, - 62080:57783, - 62081:57784, - 62082:57785, - 62083:57786, - 62084:57787, - 62085:57788, - 62086:57789, - 62087:57790, - 62088:57791, - 62089:57792, - 62090:57793, - 62091:57794, - 62092:57795, - 62093:57796, - 62094:57797, - 62095:57798, - 62096:57799, - 62097:57800, - 62098:57801, - 62099:57802, - 62100:57803, - 62101:57804, - 62102:57805, - 62103:57806, - 62104:57807, - 62105:57808, - 62106:57809, - 62107:57810, - 62108:57811, - 62109:57812, - 62110:57813, - 62111:57814, - 62112:57815, - 62113:57816, - 62114:57817, - 62115:57818, - 62116:57819, - 62117:57820, - 62118:57821, - 62119:57822, - 62120:57823, - 62121:57824, - 62122:57825, - 62123:57826, - 62124:57827, - 62125:57828, - 62126:57829, - 62127:57830, - 62128:57831, - 62129:57832, - 62130:57833, - 62131:57834, - 62132:57835, - 62133:57836, - 62134:57837, - 62135:57838, - 62136:57839, - 62137:57840, - 62138:57841, - 62139:57842, - 62140:57843, - 62141:57844, - 62142:57845, - 62143:57846, - 62144:57847, - 62145:57848, - 62146:57849, - 62147:57850, - 62148:57851, - 62149:57852, - 62150:57853, - 62151:57854, - 62152:57855, - 62153:57856, - 62154:57857, - 62155:57858, - 62156:57859, - 62157:57860, - 62158:57861, - 62159:57862, - 62160:57863, - 62161:57864, - 62162:57865, - 62163:57866, - 62164:57867, - 62165:57868, - 62166:57869, - 62167:57870, - 62168:57871, - 62169:57872, - 62170:57873, - 62171:57874, - 62172:57875, - 62173:57876, - 62174:57877, - 62175:57878, - 62176:57879, - 62177:57880, - 62178:57881, - 62179:57882, - 62180:57883, - 62181:57884, - 62182:57885, - 62183:57886, - 62184:57887, - 62185:57888, - 62186:57889, - 62187:57890, - 62188:57891, - 62189:57892, - 62190:57893, - 62191:57894, - 62192:57895, - 62193:57896, - 62194:57897, - 62195:57898, - 62196:57899, - 62197:57900, - 62198:57901, - 62199:57902, - 62200:57903, - 62201:57904, - 62202:57905, - 62203:57906, - 62204:57907, - 62272:57908, - 62273:57909, - 62274:57910, - 62275:57911, - 62276:57912, - 62277:57913, - 62278:57914, - 62279:57915, - 62280:57916, - 62281:57917, - 62282:57918, - 62283:57919, - 62284:57920, - 62285:57921, - 62286:57922, - 62287:57923, - 62288:57924, - 62289:57925, - 62290:57926, - 62291:57927, - 62292:57928, - 62293:57929, - 62294:57930, - 62295:57931, - 62296:57932, - 62297:57933, - 62298:57934, - 62299:57935, - 62300:57936, - 62301:57937, - 62302:57938, - 62303:57939, - 62304:57940, - 62305:57941, - 62306:57942, - 62307:57943, - 62308:57944, - 62309:57945, - 62310:57946, - 62311:57947, - 62312:57948, - 62313:57949, - 62314:57950, - 62315:57951, - 62316:57952, - 62317:57953, - 62318:57954, - 62319:57955, - 62320:57956, - 62321:57957, - 62322:57958, - 62323:57959, - 62324:57960, - 62325:57961, - 62326:57962, - 62327:57963, - 62328:57964, - 62329:57965, - 62330:57966, - 62331:57967, - 62332:57968, - 62333:57969, - 62334:57970, - 62336:57971, - 62337:57972, - 62338:57973, - 62339:57974, - 62340:57975, - 62341:57976, - 62342:57977, - 62343:57978, - 62344:57979, - 62345:57980, - 62346:57981, - 62347:57982, - 62348:57983, - 62349:57984, - 62350:57985, - 62351:57986, - 62352:57987, - 62353:57988, - 62354:57989, - 62355:57990, - 62356:57991, - 62357:57992, - 62358:57993, - 62359:57994, - 62360:57995, - 62361:57996, - 62362:57997, - 62363:57998, - 62364:57999, - 62365:58000, - 62366:58001, - 62367:58002, - 62368:58003, - 62369:58004, - 62370:58005, - 62371:58006, - 62372:58007, - 62373:58008, - 62374:58009, - 62375:58010, - 62376:58011, - 62377:58012, - 62378:58013, - 62379:58014, - 62380:58015, - 62381:58016, - 62382:58017, - 62383:58018, - 62384:58019, - 62385:58020, - 62386:58021, - 62387:58022, - 62388:58023, - 62389:58024, - 62390:58025, - 62391:58026, - 62392:58027, - 62393:58028, - 62394:58029, - 62395:58030, - 62396:58031, - 62397:58032, - 62398:58033, - 62399:58034, - 62400:58035, - 62401:58036, - 62402:58037, - 62403:58038, - 62404:58039, - 62405:58040, - 62406:58041, - 62407:58042, - 62408:58043, - 62409:58044, - 62410:58045, - 62411:58046, - 62412:58047, - 62413:58048, - 62414:58049, - 62415:58050, - 62416:58051, - 62417:58052, - 62418:58053, - 62419:58054, - 62420:58055, - 62421:58056, - 62422:58057, - 62423:58058, - 62424:58059, - 62425:58060, - 62426:58061, - 62427:58062, - 62428:58063, - 62429:58064, - 62430:58065, - 62431:58066, - 62432:58067, - 62433:58068, - 62434:58069, - 62435:58070, - 62436:58071, - 62437:58072, - 62438:58073, - 62439:58074, - 62440:58075, - 62441:58076, - 62442:58077, - 62443:58078, - 62444:58079, - 62445:58080, - 62446:58081, - 62447:58082, - 62448:58083, - 62449:58084, - 62450:58085, - 62451:58086, - 62452:58087, - 62453:58088, - 62454:58089, - 62455:58090, - 62456:58091, - 62457:58092, - 62458:58093, - 62459:58094, - 62460:58095, - 62528:58096, - 62529:58097, - 62530:58098, - 62531:58099, - 62532:58100, - 62533:58101, - 62534:58102, - 62535:58103, - 62536:58104, - 62537:58105, - 62538:58106, - 62539:58107, - 62540:58108, - 62541:58109, - 62542:58110, - 62543:58111, - 62544:58112, - 62545:58113, - 62546:58114, - 62547:58115, - 62548:58116, - 62549:58117, - 62550:58118, - 62551:58119, - 62552:58120, - 62553:58121, - 62554:58122, - 62555:58123, - 62556:58124, - 62557:58125, - 62558:58126, - 62559:58127, - 62560:58128, - 62561:58129, - 62562:58130, - 62563:58131, - 62564:58132, - 62565:58133, - 62566:58134, - 62567:58135, - 62568:58136, - 62569:58137, - 62570:58138, - 62571:58139, - 62572:58140, - 62573:58141, - 62574:58142, - 62575:58143, - 62576:58144, - 62577:58145, - 62578:58146, - 62579:58147, - 62580:58148, - 62581:58149, - 62582:58150, - 62583:58151, - 62584:58152, - 62585:58153, - 62586:58154, - 62587:58155, - 62588:58156, - 62589:58157, - 62590:58158, - 62592:58159, - 62593:58160, - 62594:58161, - 62595:58162, - 62596:58163, - 62597:58164, - 62598:58165, - 62599:58166, - 62600:58167, - 62601:58168, - 62602:58169, - 62603:58170, - 62604:58171, - 62605:58172, - 62606:58173, - 62607:58174, - 62608:58175, - 62609:58176, - 62610:58177, - 62611:58178, - 62612:58179, - 62613:58180, - 62614:58181, - 62615:58182, - 62616:58183, - 62617:58184, - 62618:58185, - 62619:58186, - 62620:58187, - 62621:58188, - 62622:58189, - 62623:58190, - 62624:58191, - 62625:58192, - 62626:58193, - 62627:58194, - 62628:58195, - 62629:58196, - 62630:58197, - 62631:58198, - 62632:58199, - 62633:58200, - 62634:58201, - 62635:58202, - 62636:58203, - 62637:58204, - 62638:58205, - 62639:58206, - 62640:58207, - 62641:58208, - 62642:58209, - 62643:58210, - 62644:58211, - 62645:58212, - 62646:58213, - 62647:58214, - 62648:58215, - 62649:58216, - 62650:58217, - 62651:58218, - 62652:58219, - 62653:58220, - 62654:58221, - 62655:58222, - 62656:58223, - 62657:58224, - 62658:58225, - 62659:58226, - 62660:58227, - 62661:58228, - 62662:58229, - 62663:58230, - 62664:58231, - 62665:58232, - 62666:58233, - 62667:58234, - 62668:58235, - 62669:58236, - 62670:58237, - 62671:58238, - 62672:58239, - 62673:58240, - 62674:58241, - 62675:58242, - 62676:58243, - 62677:58244, - 62678:58245, - 62679:58246, - 62680:58247, - 62681:58248, - 62682:58249, - 62683:58250, - 62684:58251, - 62685:58252, - 62686:58253, - 62687:58254, - 62688:58255, - 62689:58256, - 62690:58257, - 62691:58258, - 62692:58259, - 62693:58260, - 62694:58261, - 62695:58262, - 62696:58263, - 62697:58264, - 62698:58265, - 62699:58266, - 62700:58267, - 62701:58268, - 62702:58269, - 62703:58270, - 62704:58271, - 62705:58272, - 62706:58273, - 62707:58274, - 62708:58275, - 62709:58276, - 62710:58277, - 62711:58278, - 62712:58279, - 62713:58280, - 62714:58281, - 62715:58282, - 62716:58283, - 62784:58284, - 62785:58285, - 62786:58286, - 62787:58287, - 62788:58288, - 62789:58289, - 62790:58290, - 62791:58291, - 62792:58292, - 62793:58293, - 62794:58294, - 62795:58295, - 62796:58296, - 62797:58297, - 62798:58298, - 62799:58299, - 62800:58300, - 62801:58301, - 62802:58302, - 62803:58303, - 62804:58304, - 62805:58305, - 62806:58306, - 62807:58307, - 62808:58308, - 62809:58309, - 62810:58310, - 62811:58311, - 62812:58312, - 62813:58313, - 62814:58314, - 62815:58315, - 62816:58316, - 62817:58317, - 62818:58318, - 62819:58319, - 62820:58320, - 62821:58321, - 62822:58322, - 62823:58323, - 62824:58324, - 62825:58325, - 62826:58326, - 62827:58327, - 62828:58328, - 62829:58329, - 62830:58330, - 62831:58331, - 62832:58332, - 62833:58333, - 62834:58334, - 62835:58335, - 62836:58336, - 62837:58337, - 62838:58338, - 62839:58339, - 62840:58340, - 62841:58341, - 62842:58342, - 62843:58343, - 62844:58344, - 62845:58345, - 62846:58346, - 62848:58347, - 62849:58348, - 62850:58349, - 62851:58350, - 62852:58351, - 62853:58352, - 62854:58353, - 62855:58354, - 62856:58355, - 62857:58356, - 62858:58357, - 62859:58358, - 62860:58359, - 62861:58360, - 62862:58361, - 62863:58362, - 62864:58363, - 62865:58364, - 62866:58365, - 62867:58366, - 62868:58367, - 62869:58368, - 62870:58369, - 62871:58370, - 62872:58371, - 62873:58372, - 62874:58373, - 62875:58374, - 62876:58375, - 62877:58376, - 62878:58377, - 62879:58378, - 62880:58379, - 62881:58380, - 62882:58381, - 62883:58382, - 62884:58383, - 62885:58384, - 62886:58385, - 62887:58386, - 62888:58387, - 62889:58388, - 62890:58389, - 62891:58390, - 62892:58391, - 62893:58392, - 62894:58393, - 62895:58394, - 62896:58395, - 62897:58396, - 62898:58397, - 62899:58398, - 62900:58399, - 62901:58400, - 62902:58401, - 62903:58402, - 62904:58403, - 62905:58404, - 62906:58405, - 62907:58406, - 62908:58407, - 62909:58408, - 62910:58409, - 62911:58410, - 62912:58411, - 62913:58412, - 62914:58413, - 62915:58414, - 62916:58415, - 62917:58416, - 62918:58417, - 62919:58418, - 62920:58419, - 62921:58420, - 62922:58421, - 62923:58422, - 62924:58423, - 62925:58424, - 62926:58425, - 62927:58426, - 62928:58427, - 62929:58428, - 62930:58429, - 62931:58430, - 62932:58431, - 62933:58432, - 62934:58433, - 62935:58434, - 62936:58435, - 62937:58436, - 62938:58437, - 62939:58438, - 62940:58439, - 62941:58440, - 62942:58441, - 62943:58442, - 62944:58443, - 62945:58444, - 62946:58445, - 62947:58446, - 62948:58447, - 62949:58448, - 62950:58449, - 62951:58450, - 62952:58451, - 62953:58452, - 62954:58453, - 62955:58454, - 62956:58455, - 62957:58456, - 62958:58457, - 62959:58458, - 62960:58459, - 62961:58460, - 62962:58461, - 62963:58462, - 62964:58463, - 62965:58464, - 62966:58465, - 62967:58466, - 62968:58467, - 62969:58468, - 62970:58469, - 62971:58470, - 62972:58471, - 63040:58472, - 63041:58473, - 63042:58474, - 63043:58475, - 63044:58476, - 63045:58477, - 63046:58478, - 63047:58479, - 63048:58480, - 63049:58481, - 63050:58482, - 63051:58483, - 63052:58484, - 63053:58485, - 63054:58486, - 63055:58487, - 63056:58488, - 63057:58489, - 63058:58490, - 63059:58491, - 63060:58492, - 63061:58493, - 63062:58494, - 63063:58495, - 63064:58496, - 63065:58497, - 63066:58498, - 63067:58499, - 63068:58500, - 63069:58501, - 63070:58502, - 63071:58503, - 63072:58504, - 63073:58505, - 63074:58506, - 63075:58507, - 63076:58508, - 63077:58509, - 63078:58510, - 63079:58511, - 63080:58512, - 63081:58513, - 63082:58514, - 63083:58515, - 63084:58516, - 63085:58517, - 63086:58518, - 63087:58519, - 63088:58520, - 63089:58521, - 63090:58522, - 63091:58523, - 63092:58524, - 63093:58525, - 63094:58526, - 63095:58527, - 63096:58528, - 63097:58529, - 63098:58530, - 63099:58531, - 63100:58532, - 63101:58533, - 63102:58534, - 63104:58535, - 63105:58536, - 63106:58537, - 63107:58538, - 63108:58539, - 63109:58540, - 63110:58541, - 63111:58542, - 63112:58543, - 63113:58544, - 63114:58545, - 63115:58546, - 63116:58547, - 63117:58548, - 63118:58549, - 63119:58550, - 63120:58551, - 63121:58552, - 63122:58553, - 63123:58554, - 63124:58555, - 63125:58556, - 63126:58557, - 63127:58558, - 63128:58559, - 63129:58560, - 63130:58561, - 63131:58562, - 63132:58563, - 63133:58564, - 63134:58565, - 63135:58566, - 63136:58567, - 63137:58568, - 63138:58569, - 63139:58570, - 63140:58571, - 63141:58572, - 63142:58573, - 63143:58574, - 63144:58575, - 63145:58576, - 63146:58577, - 63147:58578, - 63148:58579, - 63149:58580, - 63150:58581, - 63151:58582, - 63152:58583, - 63153:58584, - 63154:58585, - 63155:58586, - 63156:58587, - 63157:58588, - 63158:58589, - 63159:58590, - 63160:58591, - 63161:58592, - 63162:58593, - 63163:58594, - 63164:58595, - 63165:58596, - 63166:58597, - 63167:58598, - 63168:58599, - 63169:58600, - 63170:58601, - 63171:58602, - 63172:58603, - 63173:58604, - 63174:58605, - 63175:58606, - 63176:58607, - 63177:58608, - 63178:58609, - 63179:58610, - 63180:58611, - 63181:58612, - 63182:58613, - 63183:58614, - 63184:58615, - 63185:58616, - 63186:58617, - 63187:58618, - 63188:58619, - 63189:58620, - 63190:58621, - 63191:58622, - 63192:58623, - 63193:58624, - 63194:58625, - 63195:58626, - 63196:58627, - 63197:58628, - 63198:58629, - 63199:58630, - 63200:58631, - 63201:58632, - 63202:58633, - 63203:58634, - 63204:58635, - 63205:58636, - 63206:58637, - 63207:58638, - 63208:58639, - 63209:58640, - 63210:58641, - 63211:58642, - 63212:58643, - 63213:58644, - 63214:58645, - 63215:58646, - 63216:58647, - 63217:58648, - 63218:58649, - 63219:58650, - 63220:58651, - 63221:58652, - 63222:58653, - 63223:58654, - 63224:58655, - 63225:58656, - 63226:58657, - 63227:58658, - 63228:58659, - 63296:58660, - 63297:58661, - 63298:58662, - 63299:58663, - 63300:58664, - 63301:58665, - 63302:58666, - 63303:58667, - 63304:58668, - 63305:58669, - 63306:58670, - 63307:58671, - 63308:58672, - 63309:58673, - 63310:58674, - 63311:58675, - 63312:58676, - 63313:58677, - 63314:58678, - 63315:58679, - 63316:58680, - 63317:58681, - 63318:58682, - 63319:58683, - 63320:58684, - 63321:58685, - 63322:58686, - 63323:58687, - 63324:58688, - 63325:58689, - 63326:58690, - 63327:58691, - 63328:58692, - 63329:58693, - 63330:58694, - 63331:58695, - 63332:58696, - 63333:58697, - 63334:58698, - 63335:58699, - 63336:58700, - 63337:58701, - 63338:58702, - 63339:58703, - 63340:58704, - 63341:58705, - 63342:58706, - 63343:58707, - 63344:58708, - 63345:58709, - 63346:58710, - 63347:58711, - 63348:58712, - 63349:58713, - 63350:58714, - 63351:58715, - 63352:58716, - 63353:58717, - 63354:58718, - 63355:58719, - 63356:58720, - 63357:58721, - 63358:58722, - 63360:58723, - 63361:58724, - 63362:58725, - 63363:58726, - 63364:58727, - 63365:58728, - 63366:58729, - 63367:58730, - 63368:58731, - 63369:58732, - 63370:58733, - 63371:58734, - 63372:58735, - 63373:58736, - 63374:58737, - 63375:58738, - 63376:58739, - 63377:58740, - 63378:58741, - 63379:58742, - 63380:58743, - 63381:58744, - 63382:58745, - 63383:58746, - 63384:58747, - 63385:58748, - 63386:58749, - 63387:58750, - 63388:58751, - 63389:58752, - 63390:58753, - 63391:58754, - 63392:58755, - 63393:58756, - 63394:58757, - 63395:58758, - 63396:58759, - 63397:58760, - 63398:58761, - 63399:58762, - 63400:58763, - 63401:58764, - 63402:58765, - 63403:58766, - 63404:58767, - 63405:58768, - 63406:58769, - 63407:58770, - 63408:58771, - 63409:58772, - 63410:58773, - 63411:58774, - 63412:58775, - 63413:58776, - 63414:58777, - 63415:58778, - 63416:58779, - 63417:58780, - 63418:58781, - 63419:58782, - 63420:58783, - 63421:58784, - 63422:58785, - 63423:58786, - 63424:58787, - 63425:58788, - 63426:58789, - 63427:58790, - 63428:58791, - 63429:58792, - 63430:58793, - 63431:58794, - 63432:58795, - 63433:58796, - 63434:58797, - 63435:58798, - 63436:58799, - 63437:58800, - 63438:58801, - 63439:58802, - 63440:58803, - 63441:58804, - 63442:58805, - 63443:58806, - 63444:58807, - 63445:58808, - 63446:58809, - 63447:58810, - 63448:58811, - 63449:58812, - 63450:58813, - 63451:58814, - 63452:58815, - 63453:58816, - 63454:58817, - 63455:58818, - 63456:58819, - 63457:58820, - 63458:58821, - 63459:58822, - 63460:58823, - 63461:58824, - 63462:58825, - 63463:58826, - 63464:58827, - 63465:58828, - 63466:58829, - 63467:58830, - 63468:58831, - 63469:58832, - 63470:58833, - 63471:58834, - 63472:58835, - 63473:58836, - 63474:58837, - 63475:58838, - 63476:58839, - 63477:58840, - 63478:58841, - 63479:58842, - 63480:58843, - 63481:58844, - 63482:58845, - 63483:58846, - 63484:58847, - 63552:58848, - 63553:58849, - 63554:58850, - 63555:58851, - 63556:58852, - 63557:58853, - 63558:58854, - 63559:58855, - 63560:58856, - 63561:58857, - 63562:58858, - 63563:58859, - 63564:58860, - 63565:58861, - 63566:58862, - 63567:58863, - 63568:58864, - 63569:58865, - 63570:58866, - 63571:58867, - 63572:58868, - 63573:58869, - 63574:58870, - 63575:58871, - 63576:58872, - 63577:58873, - 63578:58874, - 63579:58875, - 63580:58876, - 63581:58877, - 63582:58878, - 63583:58879, - 63584:58880, - 63585:58881, - 63586:58882, - 63587:58883, - 63588:58884, - 63589:58885, - 63590:58886, - 63591:58887, - 63592:58888, - 63593:58889, - 63594:58890, - 63595:58891, - 63596:58892, - 63597:58893, - 63598:58894, - 63599:58895, - 63600:58896, - 63601:58897, - 63602:58898, - 63603:58899, - 63604:58900, - 63605:58901, - 63606:58902, - 63607:58903, - 63608:58904, - 63609:58905, - 63610:58906, - 63611:58907, - 63612:58908, - 63613:58909, - 63614:58910, - 63616:58911, - 63617:58912, - 63618:58913, - 63619:58914, - 63620:58915, - 63621:58916, - 63622:58917, - 63623:58918, - 63624:58919, - 63625:58920, - 63626:58921, - 63627:58922, - 63628:58923, - 63629:58924, - 63630:58925, - 63631:58926, - 63632:58927, - 63633:58928, - 63634:58929, - 63635:58930, - 63636:58931, - 63637:58932, - 63638:58933, - 63639:58934, - 63640:58935, - 63641:58936, - 63642:58937, - 63643:58938, - 63644:58939, - 63645:58940, - 63646:58941, - 63647:58942, - 63648:58943, - 63649:58944, - 63650:58945, - 63651:58946, - 63652:58947, - 63653:58948, - 63654:58949, - 63655:58950, - 63656:58951, - 63657:58952, - 63658:58953, - 63659:58954, - 63660:58955, - 63661:58956, - 63662:58957, - 63663:58958, - 63664:58959, - 63665:58960, - 63666:58961, - 63667:58962, - 63668:58963, - 63669:58964, - 63670:58965, - 63671:58966, - 63672:58967, - 63673:58968, - 63674:58969, - 63675:58970, - 63676:58971, - 63677:58972, - 63678:58973, - 63679:58974, - 63680:58975, - 63681:58976, - 63682:58977, - 63683:58978, - 63684:58979, - 63685:58980, - 63686:58981, - 63687:58982, - 63688:58983, - 63689:58984, - 63690:58985, - 63691:58986, - 63692:58987, - 63693:58988, - 63694:58989, - 63695:58990, - 63696:58991, - 63697:58992, - 63698:58993, - 63699:58994, - 63700:58995, - 63701:58996, - 63702:58997, - 63703:58998, - 63704:58999, - 63705:59000, - 63706:59001, - 63707:59002, - 63708:59003, - 63709:59004, - 63710:59005, - 63711:59006, - 63712:59007, - 63713:59008, - 63714:59009, - 63715:59010, - 63716:59011, - 63717:59012, - 63718:59013, - 63719:59014, - 63720:59015, - 63721:59016, - 63722:59017, - 63723:59018, - 63724:59019, - 63725:59020, - 63726:59021, - 63727:59022, - 63728:59023, - 63729:59024, - 63730:59025, - 63731:59026, - 63732:59027, - 63733:59028, - 63734:59029, - 63735:59030, - 63736:59031, - 63737:59032, - 63738:59033, - 63739:59034, - 63740:59035, - 64064:8560, - 64065:8561, - 64066:8562, - 64067:8563, - 64068:8564, - 64069:8565, - 64070:8566, - 64071:8567, - 64072:8568, - 64073:8569, - 64074:8544, - 64075:8545, - 64076:8546, - 64077:8547, - 64078:8548, - 64079:8549, - 64080:8550, - 64081:8551, - 64082:8552, - 64083:8553, - 64084:65506, - 64085:65508, - 64086:65287, - 64087:65282, - 64088:12849, - 64089:8470, - 64090:8481, - 64091:8757, - 64092:32394, - 64093:35100, - 64094:37704, - 64095:37512, - 64096:34012, - 64097:20425, - 64098:28859, - 64099:26161, - 64100:26824, - 64101:37625, - 64102:26363, - 64103:24389, - 64104:20008, - 64105:20193, - 64106:20220, - 64107:20224, - 64108:20227, - 64109:20281, - 64110:20310, - 64111:20370, - 64112:20362, - 64113:20378, - 64114:20372, - 64115:20429, - 64116:20544, - 64117:20514, - 64118:20479, - 64119:20510, - 64120:20550, - 64121:20592, - 64122:20546, - 64123:20628, - 64124:20724, - 64125:20696, - 64126:20810, - 64128:20836, - 64129:20893, - 64130:20926, - 64131:20972, - 64132:21013, - 64133:21148, - 64134:21158, - 64135:21184, - 64136:21211, - 64137:21248, - 64138:21255, - 64139:21284, - 64140:21362, - 64141:21395, - 64142:21426, - 64143:21469, - 64144:64014, - 64145:21660, - 64146:21642, - 64147:21673, - 64148:21759, - 64149:21894, - 64150:22361, - 64151:22373, - 64152:22444, - 64153:22472, - 64154:22471, - 64155:64015, - 64156:64016, - 64157:22686, - 64158:22706, - 64159:22795, - 64160:22867, - 64161:22875, - 64162:22877, - 64163:22883, - 64164:22948, - 64165:22970, - 64166:23382, - 64167:23488, - 64168:29999, - 64169:23512, - 64170:23532, - 64171:23582, - 64172:23718, - 64173:23738, - 64174:23797, - 64175:23847, - 64176:23891, - 64177:64017, - 64178:23874, - 64179:23917, - 64180:23992, - 64181:23993, - 64182:24016, - 64183:24353, - 64184:24372, - 64185:24423, - 64186:24503, - 64187:24542, - 64188:24669, - 64189:24709, - 64190:24714, - 64191:24798, - 64192:24789, - 64193:24864, - 64194:24818, - 64195:24849, - 64196:24887, - 64197:24880, - 64198:24984, - 64199:25107, - 64200:25254, - 64201:25589, - 64202:25696, - 64203:25757, - 64204:25806, - 64205:25934, - 64206:26112, - 64207:26133, - 64208:26171, - 64209:26121, - 64210:26158, - 64211:26142, - 64212:26148, - 64213:26213, - 64214:26199, - 64215:26201, - 64216:64018, - 64217:26227, - 64218:26265, - 64219:26272, - 64220:26290, - 64221:26303, - 64222:26362, - 64223:26382, - 64224:63785, - 64225:26470, - 64226:26555, - 64227:26706, - 64228:26560, - 64229:26625, - 64230:26692, - 64231:26831, - 64232:64019, - 64233:26984, - 64234:64020, - 64235:27032, - 64236:27106, - 64237:27184, - 64238:27243, - 64239:27206, - 64240:27251, - 64241:27262, - 64242:27362, - 64243:27364, - 64244:27606, - 64245:27711, - 64246:27740, - 64247:27782, - 64248:27759, - 64249:27866, - 64250:27908, - 64251:28039, - 64252:28015, - 64320:28054, - 64321:28076, - 64322:28111, - 64323:28152, - 64324:28146, - 64325:28156, - 64326:28217, - 64327:28252, - 64328:28199, - 64329:28220, - 64330:28351, - 64331:28552, - 64332:28597, - 64333:28661, - 64334:28677, - 64335:28679, - 64336:28712, - 64337:28805, - 64338:28843, - 64339:28943, - 64340:28932, - 64341:29020, - 64342:28998, - 64343:28999, - 64344:64021, - 64345:29121, - 64346:29182, - 64347:29361, - 64348:29374, - 64349:29476, - 64350:64022, - 64351:29559, - 64352:29629, - 64353:29641, - 64354:29654, - 64355:29667, - 64356:29650, - 64357:29703, - 64358:29685, - 64359:29734, - 64360:29738, - 64361:29737, - 64362:29742, - 64363:29794, - 64364:29833, - 64365:29855, - 64366:29953, - 64367:30063, - 64368:30338, - 64369:30364, - 64370:30366, - 64371:30363, - 64372:30374, - 64373:64023, - 64374:30534, - 64375:21167, - 64376:30753, - 64377:30798, - 64378:30820, - 64379:30842, - 64380:31024, - 64381:64024, - 64382:64025, - 64384:64026, - 64385:31124, - 64386:64027, - 64387:31131, - 64388:31441, - 64389:31463, - 64390:64028, - 64391:31467, - 64392:31646, - 64393:64029, - 64394:32072, - 64395:32092, - 64396:32183, - 64397:32160, - 64398:32214, - 64399:32338, - 64400:32583, - 64401:32673, - 64402:64030, - 64403:33537, - 64404:33634, - 64405:33663, - 64406:33735, - 64407:33782, - 64408:33864, - 64409:33972, - 64410:34131, - 64411:34137, - 64412:34155, - 64413:64031, - 64414:34224, - 64415:64032, - 64416:64033, - 64417:34823, - 64418:35061, - 64419:35346, - 64420:35383, - 64421:35449, - 64422:35495, - 64423:35518, - 64424:35551, - 64425:64034, - 64426:35574, - 64427:35667, - 64428:35711, - 64429:36080, - 64430:36084, - 64431:36114, - 64432:36214, - 64433:64035, - 64434:36559, - 64435:64036, - 64436:64037, - 64437:36967, - 64438:37086, - 64439:64038, - 64440:37141, - 64441:37159, - 64442:37338, - 64443:37335, - 64444:37342, - 64445:37357, - 64446:37358, - 64447:37348, - 64448:37349, - 64449:37382, - 64450:37392, - 64451:37386, - 64452:37434, - 64453:37440, - 64454:37436, - 64455:37454, - 64456:37465, - 64457:37457, - 64458:37433, - 64459:37479, - 64460:37543, - 64461:37495, - 64462:37496, - 64463:37607, - 64464:37591, - 64465:37593, - 64466:37584, - 64467:64039, - 64468:37589, - 64469:37600, - 64470:37587, - 64471:37669, - 64472:37665, - 64473:37627, - 64474:64040, - 64475:37662, - 64476:37631, - 64477:37661, - 64478:37634, - 64479:37744, - 64480:37719, - 64481:37796, - 64482:37830, - 64483:37854, - 64484:37880, - 64485:37937, - 64486:37957, - 64487:37960, - 64488:38290, - 64489:63964, - 64490:64041, - 64491:38557, - 64492:38575, - 64493:38707, - 64494:38715, - 64495:38723, - 64496:38733, - 64497:38735, - 64498:38737, - 64499:38741, - 64500:38999, - 64501:39013, - 64502:64042, - 64503:64043, - 64504:39207, - 64505:64044, - 64506:39326, - 64507:39502, - 64508:39641, - 64576:39644, - 64577:39797, - 64578:39794, - 64579:39823, - 64580:39857, - 64581:39867, - 64582:39936, - 64583:40304, - 64584:40299, - 64585:64045, - 64586:40473, - 64587:40657 - }; - - /** - * @author takahiro / https://github.com/takahirox - */ - - function DataViewEx ( buffer, littleEndian ) { - - this.dv = new DataView( buffer ); - this.offset = 0; - this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true; - this.encoder = new CharsetEncoder(); - - } - - DataViewEx.prototype = { - - constructor: DataViewEx, - - getInt8: function () { - - var value = this.dv.getInt8( this.offset ); - this.offset += 1; - return value; - - }, - - getInt8Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getInt8() ); - - } - - return a; - - }, - - getUint8: function () { - - var value = this.dv.getUint8( this.offset ); - this.offset += 1; - return value; - - }, - - getUint8Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getUint8() ); - - } - - return a; - - }, - - - getInt16: function () { - - var value = this.dv.getInt16( this.offset, this.littleEndian ); - this.offset += 2; - return value; - - }, - - getInt16Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getInt16() ); - - } - - return a; - - }, - - getUint16: function () { - - var value = this.dv.getUint16( this.offset, this.littleEndian ); - this.offset += 2; - return value; - - }, - - getUint16Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getUint16() ); - - } - - return a; - - }, - - getInt32: function () { - - var value = this.dv.getInt32( this.offset, this.littleEndian ); - this.offset += 4; - return value; - - }, - - getInt32Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getInt32() ); - - } - - return a; - - }, - - getUint32: function () { - - var value = this.dv.getUint32( this.offset, this.littleEndian ); - this.offset += 4; - return value; - - }, - - getUint32Array: function ( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getUint32() ); - - } - - return a; - - }, - - getFloat32: function () { - - var value = this.dv.getFloat32( this.offset, this.littleEndian ); - this.offset += 4; - return value; - - }, - - getFloat32Array: function( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getFloat32() ); - - } - - return a; - - }, - - getFloat64: function () { - - var value = this.dv.getFloat64( this.offset, this.littleEndian ); - this.offset += 8; - return value; - - }, - - getFloat64Array: function( size ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getFloat64() ); - - } - - return a; - - }, - - getIndex: function ( type, isUnsigned ) { - - switch ( type ) { - - case 1: - return ( isUnsigned === true ) ? this.getUint8() : this.getInt8(); - - case 2: - return ( isUnsigned === true ) ? this.getUint16() : this.getInt16(); - - case 4: - return this.getInt32(); // No Uint32 - - default: - throw 'unknown number type ' + type + ' exception.'; - - } - - }, - - getIndexArray: function ( type, size, isUnsigned ) { - - var a = []; - - for ( var i = 0; i < size; i++ ) { - - a.push( this.getIndex( type, isUnsigned ) ); - - } - - return a; - - }, - - getChars: function ( size ) { - - var str = ''; - - while ( size > 0 ) { - - var value = this.getUint8(); - size--; - - if ( value === 0 ) { - - break; - - } - - str += String.fromCharCode( value ); - - } - - while ( size > 0 ) { - - this.getUint8(); - size--; - - } - - return str; - - }, - - getSjisStringsAsUnicode: function ( size ) { - - var a = []; - - while ( size > 0 ) { - - var value = this.getUint8(); - size--; - - if ( value === 0 ) { - - break; - - } - - a.push( value ); - - } - - while ( size > 0 ) { - - this.getUint8(); - size--; - - } - - return this.encoder.s2u( new Uint8Array( a ) ); - - }, - - getUnicodeStrings: function ( size ) { - - var str = ''; - - while ( size > 0 ) { - - var value = this.getUint16(); - size -= 2; - - if ( value === 0 ) { - - break; - - } - - str += String.fromCharCode( value ); - - } - - while ( size > 0 ) { - - this.getUint8(); - size--; - - } - - return str; - - }, - - getTextBuffer: function () { - - var size = this.getUint32(); - return this.getUnicodeStrings( size ); - - } - - }; - - /** - * @author takahiro / https://github.com/takahirox - */ - - function DataCreationHelper () { - } - - DataCreationHelper.prototype = { - - constructor: DataCreationHelper, - - leftToRightVector3: function ( v ) { - - v[ 2 ] = -v[ 2 ]; - - }, - - leftToRightQuaternion: function ( q ) { - - q[ 0 ] = -q[ 0 ]; - q[ 1 ] = -q[ 1 ]; - - }, - - leftToRightEuler: function ( r ) { - - r[ 0 ] = -r[ 0 ]; - r[ 1 ] = -r[ 1 ]; - - }, - - leftToRightIndexOrder: function ( p ) { - - var tmp = p[ 2 ]; - p[ 2 ] = p[ 0 ]; - p[ 0 ] = tmp; - - }, - - leftToRightVector3Range: function ( v1, v2 ) { - - var tmp = -v2[ 2 ]; - v2[ 2 ] = -v1[ 2 ]; - v1[ 2 ] = tmp; - - }, - - leftToRightEulerRange: function ( r1, r2 ) { - - var tmp1 = -r2[ 0 ]; - var tmp2 = -r2[ 1 ]; - r2[ 0 ] = -r1[ 0 ]; - r2[ 1 ] = -r1[ 1 ]; - r1[ 0 ] = tmp1; - r1[ 1 ] = tmp2; - - } - - }; - - /** - * @author takahiro / https://github.com/takahirox - */ - - function Parser() { - } - - Parser.prototype.parsePmd = function ( buffer, leftToRight ) { - - var pmd = {}; - var dv = new DataViewEx( buffer ); - - pmd.metadata = {}; - pmd.metadata.format = 'pmd'; - pmd.metadata.coordinateSystem = 'left'; - - var parseHeader = function () { - - var metadata = pmd.metadata; - metadata.magic = dv.getChars( 3 ); - - if ( metadata.magic !== 'Pmd' ) { - - throw 'PMD file magic is not Pmd, but ' + metadata.magic; - - } - - metadata.version = dv.getFloat32(); - metadata.modelName = dv.getSjisStringsAsUnicode( 20 ); - metadata.comment = dv.getSjisStringsAsUnicode( 256 ); - - }; - - var parseVertices = function () { - - var parseVertex = function () { - - var p = {}; - p.position = dv.getFloat32Array( 3 ); - p.normal = dv.getFloat32Array( 3 ); - p.uv = dv.getFloat32Array( 2 ); - p.skinIndices = dv.getUint16Array( 2 ); - p.skinWeights = [ dv.getUint8() / 100 ]; - p.skinWeights.push( 1.0 - p.skinWeights[ 0 ] ); - p.edgeFlag = dv.getUint8(); - return p; - - }; - - var metadata = pmd.metadata; - metadata.vertexCount = dv.getUint32(); - - pmd.vertices = []; - - for ( var i = 0; i < metadata.vertexCount; i++ ) { - - pmd.vertices.push( parseVertex() ); - - } - - }; - - var parseFaces = function () { - - var parseFace = function () { - - var p = {}; - p.indices = dv.getUint16Array( 3 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.faceCount = dv.getUint32() / 3; - - pmd.faces = []; - - for ( var i = 0; i < metadata.faceCount; i++ ) { - - pmd.faces.push( parseFace() ); - - } - - }; - - var parseMaterials = function () { - - var parseMaterial = function () { - - var p = {}; - p.diffuse = dv.getFloat32Array( 4 ); - p.shininess = dv.getFloat32(); - p.specular = dv.getFloat32Array( 3 ); - p.ambient = dv.getFloat32Array( 3 ); - p.toonIndex = dv.getInt8(); - p.edgeFlag = dv.getUint8(); - p.faceCount = dv.getUint32() / 3; - p.fileName = dv.getSjisStringsAsUnicode( 20 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.materialCount = dv.getUint32(); - - pmd.materials = []; - - for ( var i = 0; i < metadata.materialCount; i++ ) { - - pmd.materials.push( parseMaterial() ); - - } - - }; - - var parseBones = function () { - - var parseBone = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - p.parentIndex = dv.getInt16(); - p.tailIndex = dv.getInt16(); - p.type = dv.getUint8(); - p.ikIndex = dv.getInt16(); - p.position = dv.getFloat32Array( 3 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.boneCount = dv.getUint16(); - - pmd.bones = []; - - for ( var i = 0; i < metadata.boneCount; i++ ) { - - pmd.bones.push( parseBone() ); - - } - - }; - - var parseIks = function () { - - var parseIk = function () { - - var p = {}; - p.target = dv.getUint16(); - p.effector = dv.getUint16(); - p.linkCount = dv.getUint8(); - p.iteration = dv.getUint16(); - p.maxAngle = dv.getFloat32(); - - p.links = []; - for ( var i = 0; i < p.linkCount; i++ ) { - - var link = {}; - link.index = dv.getUint16(); - p.links.push( link ); - - } - - return p; - - }; - - var metadata = pmd.metadata; - metadata.ikCount = dv.getUint16(); - - pmd.iks = []; - - for ( var i = 0; i < metadata.ikCount; i++ ) { - - pmd.iks.push( parseIk() ); - - } - - }; - - var parseMorphs = function () { - - var parseMorph = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - p.elementCount = dv.getUint32(); - p.type = dv.getUint8(); - - p.elements = []; - for ( var i = 0; i < p.elementCount; i++ ) { - - p.elements.push( { - index: dv.getUint32(), - position: dv.getFloat32Array( 3 ) - } ) ; - - } - - return p; - - }; - - var metadata = pmd.metadata; - metadata.morphCount = dv.getUint16(); - - pmd.morphs = []; - - for ( var i = 0; i < metadata.morphCount; i++ ) { - - pmd.morphs.push( parseMorph() ); - - } - - - }; - - var parseMorphFrames = function () { - - var parseMorphFrame = function () { - - var p = {}; - p.index = dv.getUint16(); - return p; - - }; - - var metadata = pmd.metadata; - metadata.morphFrameCount = dv.getUint8(); - - pmd.morphFrames = []; - - for ( var i = 0; i < metadata.morphFrameCount; i++ ) { - - pmd.morphFrames.push( parseMorphFrame() ); - - } - - }; - - var parseBoneFrameNames = function () { - - var parseBoneFrameName = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 50 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.boneFrameNameCount = dv.getUint8(); - - pmd.boneFrameNames = []; - - for ( var i = 0; i < metadata.boneFrameNameCount; i++ ) { - - pmd.boneFrameNames.push( parseBoneFrameName() ); - - } - - }; - - var parseBoneFrames = function () { - - var parseBoneFrame = function () { - - var p = {}; - p.boneIndex = dv.getInt16(); - p.frameIndex = dv.getUint8(); - return p; - - }; - - var metadata = pmd.metadata; - metadata.boneFrameCount = dv.getUint32(); - - pmd.boneFrames = []; - - for ( var i = 0; i < metadata.boneFrameCount; i++ ) { - - pmd.boneFrames.push( parseBoneFrame() ); - - } - - }; - - var parseEnglishHeader = function () { - - var metadata = pmd.metadata; - metadata.englishCompatibility = dv.getUint8(); - - if ( metadata.englishCompatibility > 0 ) { - - metadata.englishModelName = dv.getSjisStringsAsUnicode( 20 ); - metadata.englishComment = dv.getSjisStringsAsUnicode( 256 ); - - } - - }; - - var parseEnglishBoneNames = function () { - - var parseEnglishBoneName = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - return p; - - }; - - var metadata = pmd.metadata; - - if ( metadata.englishCompatibility === 0 ) { - - return; - - } - - pmd.englishBoneNames = []; - - for ( var i = 0; i < metadata.boneCount; i++ ) { - - pmd.englishBoneNames.push( parseEnglishBoneName() ); - - } - - }; - - var parseEnglishMorphNames = function () { - - var parseEnglishMorphName = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - return p; - - }; - - var metadata = pmd.metadata; - - if ( metadata.englishCompatibility === 0 ) { - - return; - - } - - pmd.englishMorphNames = []; - - for ( var i = 0; i < metadata.morphCount - 1; i++ ) { - - pmd.englishMorphNames.push( parseEnglishMorphName() ); - - } - - }; - - var parseEnglishBoneFrameNames = function () { - - var parseEnglishBoneFrameName = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 50 ); - return p; - - }; - - var metadata = pmd.metadata; - - if ( metadata.englishCompatibility === 0 ) { - - return; - - } - - pmd.englishBoneFrameNames = []; - - for ( var i = 0; i < metadata.boneFrameNameCount; i++ ) { - - pmd.englishBoneFrameNames.push( parseEnglishBoneFrameName() ); - - } - - }; - - var parseToonTextures = function () { - - var parseToonTexture = function () { - - var p = {}; - p.fileName = dv.getSjisStringsAsUnicode( 100 ); - return p; - - }; - - pmd.toonTextures = []; - - for ( var i = 0; i < 10; i++ ) { - - pmd.toonTextures.push( parseToonTexture() ); - - } - - }; - - var parseRigidBodies = function () { - - var parseRigidBody = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - p.boneIndex = dv.getInt16(); - p.groupIndex = dv.getUint8(); - p.groupTarget = dv.getUint16(); - p.shapeType = dv.getUint8(); - p.width = dv.getFloat32(); - p.height = dv.getFloat32(); - p.depth = dv.getFloat32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.weight = dv.getFloat32(); - p.positionDamping = dv.getFloat32(); - p.rotationDamping = dv.getFloat32(); - p.restitution = dv.getFloat32(); - p.friction = dv.getFloat32(); - p.type = dv.getUint8(); - return p; - - }; - - var metadata = pmd.metadata; - metadata.rigidBodyCount = dv.getUint32(); - - pmd.rigidBodies = []; - - for ( var i = 0; i < metadata.rigidBodyCount; i++ ) { - - pmd.rigidBodies.push( parseRigidBody() ); - - } - - }; - - var parseConstraints = function () { - - var parseConstraint = function () { - - var p = {}; - p.name = dv.getSjisStringsAsUnicode( 20 ); - p.rigidBodyIndex1 = dv.getUint32(); - p.rigidBodyIndex2 = dv.getUint32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.translationLimitation1 = dv.getFloat32Array( 3 ); - p.translationLimitation2 = dv.getFloat32Array( 3 ); - p.rotationLimitation1 = dv.getFloat32Array( 3 ); - p.rotationLimitation2 = dv.getFloat32Array( 3 ); - p.springPosition = dv.getFloat32Array( 3 ); - p.springRotation = dv.getFloat32Array( 3 ); - return p; - - }; - - var metadata = pmd.metadata; - metadata.constraintCount = dv.getUint32(); - - pmd.constraints = []; - - for ( var i = 0; i < metadata.constraintCount; i++ ) { - - pmd.constraints.push( parseConstraint() ); - - } - - }; - - parseHeader(); - parseVertices(); - parseFaces(); - parseMaterials(); - parseBones(); - parseIks(); - parseMorphs(); - parseMorphFrames(); - parseBoneFrameNames(); - parseBoneFrames(); - parseEnglishHeader(); - parseEnglishBoneNames(); - parseEnglishMorphNames(); - parseEnglishBoneFrameNames(); - parseToonTextures(); - parseRigidBodies(); - parseConstraints(); - - if ( leftToRight === true ) this.leftToRightModel( pmd ); - - // console.log( pmd ); // for console debug - - return pmd; - - }; - - Parser.prototype.parsePmx = function ( buffer, leftToRight ) { - - var pmx = {}; - var dv = new DataViewEx( buffer ); - - pmx.metadata = {}; - pmx.metadata.format = 'pmx'; - pmx.metadata.coordinateSystem = 'left'; - - var parseHeader = function () { - - var metadata = pmx.metadata; - metadata.magic = dv.getChars( 4 ); - - // Note: don't remove the last blank space. - if ( metadata.magic !== 'PMX ' ) { - - throw 'PMX file magic is not PMX , but ' + metadata.magic; - - } - - metadata.version = dv.getFloat32(); - - if ( metadata.version !== 2.0 && metadata.version !== 2.1 ) { - - throw 'PMX version ' + metadata.version + ' is not supported.'; - - } - - metadata.headerSize = dv.getUint8(); - metadata.encoding = dv.getUint8(); - metadata.additionalUvNum = dv.getUint8(); - metadata.vertexIndexSize = dv.getUint8(); - metadata.textureIndexSize = dv.getUint8(); - metadata.materialIndexSize = dv.getUint8(); - metadata.boneIndexSize = dv.getUint8(); - metadata.morphIndexSize = dv.getUint8(); - metadata.rigidBodyIndexSize = dv.getUint8(); - metadata.modelName = dv.getTextBuffer(); - metadata.englishModelName = dv.getTextBuffer(); - metadata.comment = dv.getTextBuffer(); - metadata.englishComment = dv.getTextBuffer(); - - }; - - var parseVertices = function () { - - var parseVertex = function () { - - var p = {}; - p.position = dv.getFloat32Array( 3 ); - p.normal = dv.getFloat32Array( 3 ); - p.uv = dv.getFloat32Array( 2 ); - - p.auvs = []; - - for ( var i = 0; i < pmx.metadata.additionalUvNum; i++ ) { - - p.auvs.push( dv.getFloat32Array( 4 ) ); - - } - - p.type = dv.getUint8(); - - var indexSize = metadata.boneIndexSize; - - if ( p.type === 0 ) { // BDEF1 - - p.skinIndices = dv.getIndexArray( indexSize, 1 ); - p.skinWeights = [ 1.0 ]; - - } else if ( p.type === 1 ) { // BDEF2 - - p.skinIndices = dv.getIndexArray( indexSize, 2 ); - p.skinWeights = dv.getFloat32Array( 1 ); - p.skinWeights.push( 1.0 - p.skinWeights[ 0 ] ); - - } else if ( p.type === 2 ) { // BDEF4 - - p.skinIndices = dv.getIndexArray( indexSize, 4 ); - p.skinWeights = dv.getFloat32Array( 4 ); - - } else if ( p.type === 3 ) { // SDEF - - p.skinIndices = dv.getIndexArray( indexSize, 2 ); - p.skinWeights = dv.getFloat32Array( 1 ); - p.skinWeights.push( 1.0 - p.skinWeights[ 0 ] ); - - p.skinC = dv.getFloat32Array( 3 ); - p.skinR0 = dv.getFloat32Array( 3 ); - p.skinR1 = dv.getFloat32Array( 3 ); - - // SDEF is not supported yet and is handled as BDEF2 so far. - // TODO: SDEF support - p.type = 1; - - } else { - - throw 'unsupport bone type ' + p.type + ' exception.'; - - } - - p.edgeRatio = dv.getFloat32(); - return p; - - }; - - var metadata = pmx.metadata; - metadata.vertexCount = dv.getUint32(); - - pmx.vertices = []; - - for ( var i = 0; i < metadata.vertexCount; i++ ) { - - pmx.vertices.push( parseVertex() ); - - } - - }; - - var parseFaces = function () { - - var parseFace = function () { - - var p = {}; - p.indices = dv.getIndexArray( metadata.vertexIndexSize, 3, true ); - return p; - - }; - - var metadata = pmx.metadata; - metadata.faceCount = dv.getUint32() / 3; - - pmx.faces = []; - - for ( var i = 0; i < metadata.faceCount; i++ ) { - - pmx.faces.push( parseFace() ); - - } - - }; - - var parseTextures = function () { - - var parseTexture = function () { - - return dv.getTextBuffer(); - - }; - - var metadata = pmx.metadata; - metadata.textureCount = dv.getUint32(); - - pmx.textures = []; - - for ( var i = 0; i < metadata.textureCount; i++ ) { - - pmx.textures.push( parseTexture() ); - - } - - }; - - var parseMaterials = function () { - - var parseMaterial = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.diffuse = dv.getFloat32Array( 4 ); - p.specular = dv.getFloat32Array( 3 ); - p.shininess = dv.getFloat32(); - p.ambient = dv.getFloat32Array( 3 ); - p.flag = dv.getUint8(); - p.edgeColor = dv.getFloat32Array( 4 ); - p.edgeSize = dv.getFloat32(); - p.textureIndex = dv.getIndex( pmx.metadata.textureIndexSize ); - p.envTextureIndex = dv.getIndex( pmx.metadata.textureIndexSize ); - p.envFlag = dv.getUint8(); - p.toonFlag = dv.getUint8(); - - if ( p.toonFlag === 0 ) { - - p.toonIndex = dv.getIndex( pmx.metadata.textureIndexSize ); - - } else if ( p.toonFlag === 1 ) { - - p.toonIndex = dv.getInt8(); - - } else { - - throw 'unknown toon flag ' + p.toonFlag + ' exception.'; - - } - - p.comment = dv.getTextBuffer(); - p.faceCount = dv.getUint32() / 3; - return p; - - }; - - var metadata = pmx.metadata; - metadata.materialCount = dv.getUint32(); - - pmx.materials = []; - - for ( var i = 0; i < metadata.materialCount; i++ ) { - - pmx.materials.push( parseMaterial() ); - - } - - }; - - var parseBones = function () { - - var parseBone = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.position = dv.getFloat32Array( 3 ); - p.parentIndex = dv.getIndex( pmx.metadata.boneIndexSize ); - p.transformationClass = dv.getUint32(); - p.flag = dv.getUint16(); - - if ( p.flag & 0x1 ) { - - p.connectIndex = dv.getIndex( pmx.metadata.boneIndexSize ); - - } else { - - p.offsetPosition = dv.getFloat32Array( 3 ); - - } - - if ( p.flag & 0x100 || p.flag & 0x200 ) { - - // Note: I don't think Grant is an appropriate name - // but I found that some English translated MMD tools use this term - // so I've named it Grant so far. - // I'd rename to more appropriate name from Grant later. - var grant = {}; - - grant.isLocal = ( p.flag & 0x80 ) !== 0 ? true : false; - grant.affectRotation = ( p.flag & 0x100 ) !== 0 ? true : false; - grant.affectPosition = ( p.flag & 0x200 ) !== 0 ? true : false; - grant.parentIndex = dv.getIndex( pmx.metadata.boneIndexSize ); - grant.ratio = dv.getFloat32(); - - p.grant = grant; - - } - - if ( p.flag & 0x400 ) { - - p.fixAxis = dv.getFloat32Array( 3 ); - - } - - if ( p.flag & 0x800 ) { - - p.localXVector = dv.getFloat32Array( 3 ); - p.localZVector = dv.getFloat32Array( 3 ); - - } - - if ( p.flag & 0x2000 ) { - - p.key = dv.getUint32(); - - } - - if ( p.flag & 0x20 ) { - - var ik = {}; - - ik.effector = dv.getIndex( pmx.metadata.boneIndexSize ); - ik.target = null; - ik.iteration = dv.getUint32(); - ik.maxAngle = dv.getFloat32(); - ik.linkCount = dv.getUint32(); - ik.links = []; - - for ( var i = 0; i < ik.linkCount; i++ ) { - - var link = {}; - link.index = dv.getIndex( pmx.metadata.boneIndexSize ); - link.angleLimitation = dv.getUint8(); - - if ( link.angleLimitation === 1 ) { - - link.lowerLimitationAngle = dv.getFloat32Array( 3 ); - link.upperLimitationAngle = dv.getFloat32Array( 3 ); - - } - - ik.links.push( link ); - - } - - p.ik = ik; - } - - return p; - - }; - - var metadata = pmx.metadata; - metadata.boneCount = dv.getUint32(); - - pmx.bones = []; - - for ( var i = 0; i < metadata.boneCount; i++ ) { - - pmx.bones.push( parseBone() ); - - } - - }; - - var parseMorphs = function () { - - var parseMorph = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.panel = dv.getUint8(); - p.type = dv.getUint8(); - p.elementCount = dv.getUint32(); - p.elements = []; - - for ( var i = 0; i < p.elementCount; i++ ) { - - if ( p.type === 0 ) { // group morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.morphIndexSize ); - m.ratio = dv.getFloat32(); - p.elements.push( m ); - - } else if ( p.type === 1 ) { // vertex morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.vertexIndexSize, true ); - m.position = dv.getFloat32Array( 3 ); - p.elements.push( m ); - - } else if ( p.type === 2 ) { // bone morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.boneIndexSize ); - m.position = dv.getFloat32Array( 3 ); - m.rotation = dv.getFloat32Array( 4 ); - p.elements.push( m ); - - } else if ( p.type === 3 ) { // uv morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.vertexIndexSize, true ); - m.uv = dv.getFloat32Array( 4 ); - p.elements.push( m ); - - } else if ( p.type === 4 ) ; else if ( p.type === 5 ) ; else if ( p.type === 6 ) ; else if ( p.type === 7 ) ; else if ( p.type === 8 ) { // material morph - - var m = {}; - m.index = dv.getIndex( pmx.metadata.materialIndexSize ); - m.type = dv.getUint8(); - m.diffuse = dv.getFloat32Array( 4 ); - m.specular = dv.getFloat32Array( 3 ); - m.shininess = dv.getFloat32(); - m.ambient = dv.getFloat32Array( 3 ); - m.edgeColor = dv.getFloat32Array( 4 ); - m.edgeSize = dv.getFloat32(); - m.textureColor = dv.getFloat32Array( 4 ); - m.sphereTextureColor = dv.getFloat32Array( 4 ); - m.toonColor = dv.getFloat32Array( 4 ); - p.elements.push( m ); - - } - - } - - return p; - - }; - - var metadata = pmx.metadata; - metadata.morphCount = dv.getUint32(); - - pmx.morphs = []; - - for ( var i = 0; i < metadata.morphCount; i++ ) { - - pmx.morphs.push( parseMorph() ); - - } - - }; - - var parseFrames = function () { - - var parseFrame = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.type = dv.getUint8(); - p.elementCount = dv.getUint32(); - p.elements = []; - - for ( var i = 0; i < p.elementCount; i++ ) { - - var e = {}; - e.target = dv.getUint8(); - e.index = ( e.target === 0 ) ? dv.getIndex( pmx.metadata.boneIndexSize ) : dv.getIndex( pmx.metadata.morphIndexSize ); - p.elements.push( e ); - - } - - return p; - - }; - - var metadata = pmx.metadata; - metadata.frameCount = dv.getUint32(); - - pmx.frames = []; - - for ( var i = 0; i < metadata.frameCount; i++ ) { - - pmx.frames.push( parseFrame() ); - - } - - }; - - var parseRigidBodies = function () { - - var parseRigidBody = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.boneIndex = dv.getIndex( pmx.metadata.boneIndexSize ); - p.groupIndex = dv.getUint8(); - p.groupTarget = dv.getUint16(); - p.shapeType = dv.getUint8(); - p.width = dv.getFloat32(); - p.height = dv.getFloat32(); - p.depth = dv.getFloat32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.weight = dv.getFloat32(); - p.positionDamping = dv.getFloat32(); - p.rotationDamping = dv.getFloat32(); - p.restitution = dv.getFloat32(); - p.friction = dv.getFloat32(); - p.type = dv.getUint8(); - return p; - - }; - - var metadata = pmx.metadata; - metadata.rigidBodyCount = dv.getUint32(); - - pmx.rigidBodies = []; - - for ( var i = 0; i < metadata.rigidBodyCount; i++ ) { - - pmx.rigidBodies.push( parseRigidBody() ); - - } - - }; - - var parseConstraints = function () { - - var parseConstraint = function () { - - var p = {}; - p.name = dv.getTextBuffer(); - p.englishName = dv.getTextBuffer(); - p.type = dv.getUint8(); - p.rigidBodyIndex1 = dv.getIndex( pmx.metadata.rigidBodyIndexSize ); - p.rigidBodyIndex2 = dv.getIndex( pmx.metadata.rigidBodyIndexSize ); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.translationLimitation1 = dv.getFloat32Array( 3 ); - p.translationLimitation2 = dv.getFloat32Array( 3 ); - p.rotationLimitation1 = dv.getFloat32Array( 3 ); - p.rotationLimitation2 = dv.getFloat32Array( 3 ); - p.springPosition = dv.getFloat32Array( 3 ); - p.springRotation = dv.getFloat32Array( 3 ); - return p; - - }; - - var metadata = pmx.metadata; - metadata.constraintCount = dv.getUint32(); - - pmx.constraints = []; - - for ( var i = 0; i < metadata.constraintCount; i++ ) { - - pmx.constraints.push( parseConstraint() ); - - } - - }; - - parseHeader(); - parseVertices(); - parseFaces(); - parseTextures(); - parseMaterials(); - parseBones(); - parseMorphs(); - parseFrames(); - parseRigidBodies(); - parseConstraints(); - - if ( leftToRight === true ) this.leftToRightModel( pmx ); - - // console.log( pmx ); // for console debug - - return pmx; - - }; - - Parser.prototype.parseVmd = function ( buffer, leftToRight ) { - - var vmd = {}; - var dv = new DataViewEx( buffer ); - - vmd.metadata = {}; - vmd.metadata.coordinateSystem = 'left'; - - var parseHeader = function () { - - var metadata = vmd.metadata; - metadata.magic = dv.getChars( 30 ); - - if ( metadata.magic !== 'Vocaloid Motion Data 0002' ) { - - throw 'VMD file magic is not Vocaloid Motion Data 0002, but ' + metadata.magic; - - } - - metadata.name = dv.getSjisStringsAsUnicode( 20 ); - - }; - - var parseMotions = function () { - - var parseMotion = function () { - - var p = {}; - p.boneName = dv.getSjisStringsAsUnicode( 15 ); - p.frameNum = dv.getUint32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 4 ); - p.interpolation = dv.getUint8Array( 64 ); - return p; - - }; - - var metadata = vmd.metadata; - metadata.motionCount = dv.getUint32(); - - vmd.motions = []; - for ( var i = 0; i < metadata.motionCount; i++ ) { - - vmd.motions.push( parseMotion() ); - - } - - }; - - var parseMorphs = function () { - - var parseMorph = function () { - - var p = {}; - p.morphName = dv.getSjisStringsAsUnicode( 15 ); - p.frameNum = dv.getUint32(); - p.weight = dv.getFloat32(); - return p; - - }; - - var metadata = vmd.metadata; - metadata.morphCount = dv.getUint32(); - - vmd.morphs = []; - for ( var i = 0; i < metadata.morphCount; i++ ) { - - vmd.morphs.push( parseMorph() ); - - } - - }; - - var parseCameras = function () { - - var parseCamera = function () { - - var p = {}; - p.frameNum = dv.getUint32(); - p.distance = dv.getFloat32(); - p.position = dv.getFloat32Array( 3 ); - p.rotation = dv.getFloat32Array( 3 ); - p.interpolation = dv.getUint8Array( 24 ); - p.fov = dv.getUint32(); - p.perspective = dv.getUint8(); - return p; - - }; - - var metadata = vmd.metadata; - metadata.cameraCount = dv.getUint32(); - - vmd.cameras = []; - for ( var i = 0; i < metadata.cameraCount; i++ ) { - - vmd.cameras.push( parseCamera() ); - - } - - }; - - parseHeader(); - parseMotions(); - parseMorphs(); - parseCameras(); - - if ( leftToRight === true ) this.leftToRightVmd( vmd ); - - // console.log( vmd ); // for console debug - - return vmd; - - }; - - Parser.prototype.parseVpd = function ( text, leftToRight ) { - - var vpd = {}; - - vpd.metadata = {}; - vpd.metadata.coordinateSystem = 'left'; - - vpd.bones = []; - - var commentPatternG = /\/\/\w*(\r|\n|\r\n)/g; - var newlinePattern = /\r|\n|\r\n/; - - var lines = text.replace( commentPatternG, '' ).split( newlinePattern ); - - function throwError () { - - throw 'the file seems not vpd file.'; - - } - - function checkMagic () { - - if ( lines[ 0 ] !== 'Vocaloid Pose Data file' ) { - - throwError(); - - } - - } - - function parseHeader () { - - if ( lines.length < 4 ) { - - throwError(); - - } - - vpd.metadata.parentFile = lines[ 2 ]; - vpd.metadata.boneCount = parseInt( lines[ 3 ] ); - - } - - function parseBones () { - - var boneHeaderPattern = /^\s*(Bone[0-9]+)\s*\{\s*(.*)$/; - var boneVectorPattern = /^\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*;/; - var boneQuaternionPattern = /^\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*;/; - var boneFooterPattern = /^\s*}/; - - var bones = vpd.bones; - var n = null; - var v = null; - var q = null; - - for ( var i = 4; i < lines.length; i++ ) { - - var line = lines[ i ]; - - var result; - - result = line.match( boneHeaderPattern ); - - if ( result !== null ) { - - if ( n !== null ) { - - throwError(); - - } - - n = result[ 2 ]; - - } - - result = line.match( boneVectorPattern ); - - if ( result !== null ) { - - if ( v !== null ) { - - throwError(); - - } - - v = [ - - parseFloat( result[ 1 ] ), - parseFloat( result[ 2 ] ), - parseFloat( result[ 3 ] ) - - ]; - - } - - result = line.match( boneQuaternionPattern ); - - if ( result !== null ) { - - if ( q !== null ) { - - throwError(); - - } - - q = [ - - parseFloat( result[ 1 ] ), - parseFloat( result[ 2 ] ), - parseFloat( result[ 3 ] ), - parseFloat( result[ 4 ] ) - - ]; - - - } - - result = line.match( boneFooterPattern ); - - if ( result !== null ) { - - if ( n === null || v === null || q === null ) { - - throwError(); - - } - - bones.push( { - - name: n, - translation: v, - quaternion: q - - } ); - - n = null; - v = null; - q = null; - - } - - } - - if ( n !== null || v !== null || q !== null ) { - - throwError(); - - } - - } - - checkMagic(); - parseHeader(); - parseBones(); - - if ( leftToRight === true ) this.leftToRightVpd( vpd ); - - // console.log( vpd ); // for console debug - - return vpd; - - }; - - Parser.prototype.mergeVmds = function ( vmds ) { - - var v = {}; - v.metadata = {}; - v.metadata.name = vmds[ 0 ].metadata.name; - v.metadata.coordinateSystem = vmds[ 0 ].metadata.coordinateSystem; - v.metadata.motionCount = 0; - v.metadata.morphCount = 0; - v.metadata.cameraCount = 0; - v.motions = []; - v.morphs = []; - v.cameras = []; - - for ( var i = 0; i < vmds.length; i++ ) { - - var v2 = vmds[ i ]; - - v.metadata.motionCount += v2.metadata.motionCount; - v.metadata.morphCount += v2.metadata.morphCount; - v.metadata.cameraCount += v2.metadata.cameraCount; - - for ( var j = 0; j < v2.metadata.motionCount; j++ ) { - - v.motions.push( v2.motions[ j ] ); - - } - - for ( var j = 0; j < v2.metadata.morphCount; j++ ) { - - v.morphs.push( v2.morphs[ j ] ); - - } - - for ( var j = 0; j < v2.metadata.cameraCount; j++ ) { - - v.cameras.push( v2.cameras[ j ] ); - - } - - } - - return v; - - }; - - Parser.prototype.leftToRightModel = function ( model ) { - - if ( model.metadata.coordinateSystem === 'right' ) { - - return; - - } - - model.metadata.coordinateSystem = 'right'; - - var helper = new DataCreationHelper(); - - for ( var i = 0; i < model.metadata.vertexCount; i++ ) { - - helper.leftToRightVector3( model.vertices[ i ].position ); - helper.leftToRightVector3( model.vertices[ i ].normal ); - - } - - for ( var i = 0; i < model.metadata.faceCount; i++ ) { - - helper.leftToRightIndexOrder( model.faces[ i ].indices ); - - } - - for ( var i = 0; i < model.metadata.boneCount; i++ ) { - - helper.leftToRightVector3( model.bones[ i ].position ); - - } - - // TODO: support other morph for PMX - for ( var i = 0; i < model.metadata.morphCount; i++ ) { - - var m = model.morphs[ i ]; - - if ( model.metadata.format === 'pmx' && m.type !== 1 ) { - - // TODO: implement - continue; - - } - - for ( var j = 0; j < m.elements.length; j++ ) { - - helper.leftToRightVector3( m.elements[ j ].position ); - - } - - } - - for ( var i = 0; i < model.metadata.rigidBodyCount; i++ ) { - - helper.leftToRightVector3( model.rigidBodies[ i ].position ); - helper.leftToRightEuler( model.rigidBodies[ i ].rotation ); - - } - - for ( var i = 0; i < model.metadata.constraintCount; i++ ) { - - helper.leftToRightVector3( model.constraints[ i ].position ); - helper.leftToRightEuler( model.constraints[ i ].rotation ); - helper.leftToRightVector3Range( model.constraints[ i ].translationLimitation1, model.constraints[ i ].translationLimitation2 ); - helper.leftToRightEulerRange( model.constraints[ i ].rotationLimitation1, model.constraints[ i ].rotationLimitation2 ); - - } - - }; - - Parser.prototype.leftToRightVmd = function ( vmd ) { - - if ( vmd.metadata.coordinateSystem === 'right' ) { - - return; - - } - - vmd.metadata.coordinateSystem = 'right'; - - var helper = new DataCreationHelper(); - - for ( var i = 0; i < vmd.metadata.motionCount; i++ ) { - - helper.leftToRightVector3( vmd.motions[ i ].position ); - helper.leftToRightQuaternion( vmd.motions[ i ].rotation ); - - } - - for ( var i = 0; i < vmd.metadata.cameraCount; i++ ) { - - helper.leftToRightVector3( vmd.cameras[ i ].position ); - helper.leftToRightEuler( vmd.cameras[ i ].rotation ); - - } - - }; - - Parser.prototype.leftToRightVpd = function ( vpd ) { - - if ( vpd.metadata.coordinateSystem === 'right' ) { - - return; - - } - - vpd.metadata.coordinateSystem = 'right'; - - var helper = new DataCreationHelper(); - - for ( var i = 0; i < vpd.bones.length; i++ ) { - - helper.leftToRightVector3( vpd.bones[ i ].translation ); - helper.leftToRightQuaternion( vpd.bones[ i ].quaternion ); - - } - - }; - - var MMDParser = { - CharsetEncoder: CharsetEncoder, - Parser: Parser - }; - - exports.MMDParser = MMDParser; - exports.CharsetEncoder = CharsetEncoder; - exports.Parser = Parser; - - Object.defineProperty(exports, '__esModule', { value: true }); - - }))); -} (mmdparser, mmdparser.exports)); - -/** - * CCD Algorithm - * - https://sites.google.com/site/auraliusproject/ccd-algorithm - * - * // ik parameter example - * // - * // target, effector, index in links are bone index in skeleton.bones. - * // the bones relation should be - * // <-- parent child --> - * // links[ n ], links[ n - 1 ], ..., links[ 0 ], effector - * iks = [ { - * target: 1, - * effector: 2, - * links: [ { index: 5, limitation: new Vector3( 1, 0, 0 ) }, { index: 4, enabled: false }, { index : 3 } ], - * iteration: 10, - * minAngle: 0.0, - * maxAngle: 1.0, - * } ]; - */ - -const CCDIKSolver = (() => { - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Array} iks - */ - function CCDIKSolver(mesh, iks) { - this.mesh = mesh; - this.iks = iks || []; - - this._valid(); - } - - CCDIKSolver.prototype = { - constructor: CCDIKSolver, - - /** - * Update IK bones. - * - * @return {CCDIKSolver} - */ - update: (() => { - const q = new Quaternion(); - const targetPos = new Vector3(); - const targetVec = new Vector3(); - const effectorPos = new Vector3(); - const effectorVec = new Vector3(); - const linkPos = new Vector3(); - const invLinkQ = new Quaternion(); - const linkScale = new Vector3(); - const axis = new Vector3(); - const vector = new Vector3(); - return function update() { - const bones = this.mesh.skeleton.bones; - const iks = this.iks; // for reference overhead reduction in loop - - const math = Math; - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - const effector = bones[ik.effector]; - const target = bones[ik.target]; // don't use getWorldPosition() here for the performance - // because it calls updateMatrixWorld( true ) inside. - - targetPos.setFromMatrixPosition(target.matrixWorld); - const links = ik.links; - const iteration = ik.iteration !== undefined ? ik.iteration : 1; - - for (let j = 0; j < iteration; j++) { - let rotated = false; - - for (let k = 0, kl = links.length; k < kl; k++) { - const link = bones[links[k].index]; // skip this link and following links. - // this skip is used for MMD performance optimization. - - if (links[k].enabled === false) break; - const limitation = links[k].limitation; - const rotationMin = links[k].rotationMin; - const rotationMax = links[k].rotationMax; // don't use getWorldPosition/Quaternion() here for the performance - // because they call updateMatrixWorld( true ) inside. - - link.matrixWorld.decompose(linkPos, invLinkQ, linkScale); - invLinkQ.invert(); - effectorPos.setFromMatrixPosition(effector.matrixWorld); // work in link world - - effectorVec.subVectors(effectorPos, linkPos); - effectorVec.applyQuaternion(invLinkQ); - effectorVec.normalize(); - targetVec.subVectors(targetPos, linkPos); - targetVec.applyQuaternion(invLinkQ); - targetVec.normalize(); - let angle = targetVec.dot(effectorVec); - - if (angle > 1.0) { - angle = 1.0; - } else if (angle < -1.0) { - angle = -1.0; - } - - angle = math.acos(angle); // skip if changing angle is too small to prevent vibration of bone - // Refer to http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js - - if (angle < 1e-5) continue; - - if (ik.minAngle !== undefined && angle < ik.minAngle) { - angle = ik.minAngle; - } - - if (ik.maxAngle !== undefined && angle > ik.maxAngle) { - angle = ik.maxAngle; - } - - axis.crossVectors(effectorVec, targetVec); - axis.normalize(); - q.setFromAxisAngle(axis, angle); - link.quaternion.multiply(q); // TODO: re-consider the limitation specification - - if (limitation !== undefined) { - let c = link.quaternion.w; - if (c > 1.0) c = 1.0; - const c2 = math.sqrt(1 - c * c); - link.quaternion.set(limitation.x * c2, limitation.y * c2, limitation.z * c2, c); - } - - if (rotationMin !== undefined) { - link.rotation.setFromVector3(link.rotation.toVector3(vector).max(rotationMin)); - } - - if (rotationMax !== undefined) { - link.rotation.setFromVector3(link.rotation.toVector3(vector).min(rotationMax)); - } - - link.updateMatrixWorld(true); - rotated = true; - } - - if (!rotated) break; - } - } - - return this; - }; - })(), - - /** - * Creates Helper - * - * @return {CCDIKHelper} - */ - createHelper: function () { - return new CCDIKHelper(this.mesh, this.mesh.geometry.userData.MMD.iks); - }, - // private methods - _valid: function () { - const iks = this.iks; - const bones = this.mesh.skeleton.bones; - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - const effector = bones[ik.effector]; - const links = ik.links; - let link0, link1; - link0 = effector; - - for (let j = 0, jl = links.length; j < jl; j++) { - link1 = bones[links[j].index]; - - if (link0.parent !== link1) { - console.warn(`THREE.CCDIKSolver: bone ${link0.name} is not the child of bone ${link1.name}`); - } - - link0 = link1; - } - } - } - }; - /** - * Visualize IK bones - * - * @param {SkinnedMesh} mesh - * @param {Array} iks - */ - - function CCDIKHelper(mesh, iks) { - Object3D.call(this); - this.root = mesh; - this.iks = iks || []; - this.matrix.copy(mesh.matrixWorld); - this.matrixAutoUpdate = false; - this.sphereGeometry = new SphereGeometry(0.25, 16, 8); - this.targetSphereMaterial = new MeshBasicMaterial({ - color: new Color(0xff8888), - depthTest: false, - depthWrite: false, - transparent: true - }); - this.effectorSphereMaterial = new MeshBasicMaterial({ - color: new Color(0x88ff88), - depthTest: false, - depthWrite: false, - transparent: true - }); - this.linkSphereMaterial = new MeshBasicMaterial({ - color: new Color(0x8888ff), - depthTest: false, - depthWrite: false, - transparent: true - }); - this.lineMaterial = new LineBasicMaterial({ - color: new Color(0xff0000), - depthTest: false, - depthWrite: false, - transparent: true - }); - - this._init(); - } - - CCDIKHelper.prototype = Object.assign(Object.create(Object3D.prototype), { - constructor: CCDIKHelper, - - /** - * Updates IK bones visualization. - */ - updateMatrixWorld: (() => { - const matrix = new Matrix4(); - const vector = new Vector3(); - - function getPosition(bone, matrixWorldInv) { - return vector.setFromMatrixPosition(bone.matrixWorld).applyMatrix4(matrixWorldInv); - } - - function setPositionOfBoneToAttributeArray(array, index, bone, matrixWorldInv) { - const v = getPosition(bone, matrixWorldInv); - array[index * 3 + 0] = v.x; - array[index * 3 + 1] = v.y; - array[index * 3 + 2] = v.z; - } - - return function updateMatrixWorld(force) { - const mesh = this.root; - - if (this.visible) { - let offset = 0; - const iks = this.iks; - const bones = mesh.skeleton.bones; - matrix.copy(mesh.matrixWorld).invert(); - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - const targetBone = bones[ik.target]; - const effectorBone = bones[ik.effector]; - const targetMesh = this.children[offset++]; - const effectorMesh = this.children[offset++]; - targetMesh.position.copy(getPosition(targetBone, matrix)); - effectorMesh.position.copy(getPosition(effectorBone, matrix)); - - for (let j = 0, jl = ik.links.length; j < jl; j++) { - var link = ik.links[j]; - var linkBone = bones[link.index]; - const linkMesh = this.children[offset++]; - linkMesh.position.copy(getPosition(linkBone, matrix)); - } - - const line = this.children[offset++]; - const array = line.geometry.attributes.position.array; - setPositionOfBoneToAttributeArray(array, 0, targetBone, matrix); - setPositionOfBoneToAttributeArray(array, 1, effectorBone, matrix); - - for (let j = 0, jl = ik.links.length; j < jl; j++) { - var link = ik.links[j]; - var linkBone = bones[link.index]; - setPositionOfBoneToAttributeArray(array, j + 2, linkBone, matrix); - } - - line.geometry.attributes.position.needsUpdate = true; - } - } - - this.matrix.copy(mesh.matrixWorld); - Object3D.prototype.updateMatrixWorld.call(this, force); - }; - })(), - // private method - _init: function () { - const scope = this; - const iks = this.iks; - - function createLineGeometry(ik) { - const geometry = new BufferGeometry(); - const vertices = new Float32Array((2 + ik.links.length) * 3); - geometry.setAttribute('position', new BufferAttribute(vertices, 3)); - return geometry; - } - - function createTargetMesh() { - return new Mesh(scope.sphereGeometry, scope.targetSphereMaterial); - } - - function createEffectorMesh() { - return new Mesh(scope.sphereGeometry, scope.effectorSphereMaterial); - } - - function createLinkMesh() { - return new Mesh(scope.sphereGeometry, scope.linkSphereMaterial); - } - - function createLine(ik) { - return new Line$2(createLineGeometry(ik), scope.lineMaterial); - } - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - this.add(createTargetMesh()); - this.add(createEffectorMesh()); - - for (let j = 0, jl = ik.links.length; j < jl; j++) { - this.add(createLinkMesh()); - } - - this.add(createLine(ik)); - } - } - }); - return CCDIKSolver; -})(); - -/** - * Dependencies - * - Ammo.js https://github.com/kripken/ammo.js - * - * MMDPhysics calculates physics with Ammo(Bullet based JavaScript Physics engine) - * for MMD model loaded by MMDLoader. - * - * TODO - * - Physics in Worker - */ - -/* global Ammo */ - -const MMDPhysics = (() => { - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Array} rigidBodyParams - * @param {Array} (optional) constraintParams - * @param {Object} params - (optional) - * @param {Number} params.unitStep - Default is 1 / 65. - * @param {Integer} params.maxStepNum - Default is 3. - * @param {Vector3} params.gravity - Default is ( 0, - 9.8 * 10, 0 ) - */ - function MMDPhysics(mesh, rigidBodyParams, constraintParams, params) { - if (typeof Ammo === 'undefined') { - throw new Error('THREE.MMDPhysics: Import ammo.js https://github.com/kripken/ammo.js'); - } - - constraintParams = constraintParams || []; - params = params || {}; - this.manager = new ResourceManager(); - this.mesh = mesh; - /* - * I don't know why but 1/60 unitStep easily breaks models - * so I set it 1/65 so far. - * Don't set too small unitStep because - * the smaller unitStep can make the performance worse. - */ - - this.unitStep = params.unitStep !== undefined ? params.unitStep : 1 / 65; - this.maxStepNum = params.maxStepNum !== undefined ? params.maxStepNum : 3; - this.gravity = new Vector3(0, -9.8 * 10, 0); - if (params.gravity !== undefined) this.gravity.copy(params.gravity); - this.world = params.world !== undefined ? params.world : null; // experimental - - this.bodies = []; - this.constraints = []; - - this._init(mesh, rigidBodyParams, constraintParams); - } - - MMDPhysics.prototype = { - constructor: MMDPhysics, - - /** - * Advances Physics calculation and updates bones. - * - * @param {Number} delta - time in second - * @return {MMDPhysics} - */ - update: function (delta) { - const manager = this.manager; - const mesh = this.mesh; // rigid bodies and constrains are for - // mesh's world scale (1, 1, 1). - // Convert to (1, 1, 1) if it isn't. - - let isNonDefaultScale = false; - const position = manager.allocThreeVector3(); - const quaternion = manager.allocThreeQuaternion(); - const scale = manager.allocThreeVector3(); - mesh.matrixWorld.decompose(position, quaternion, scale); - - if (scale.x !== 1 || scale.y !== 1 || scale.z !== 1) { - isNonDefaultScale = true; - } - - let parent; - - if (isNonDefaultScale) { - parent = mesh.parent; - if (parent !== null) mesh.parent = null; - scale.copy(this.mesh.scale); - mesh.scale.set(1, 1, 1); - mesh.updateMatrixWorld(true); - } // calculate physics and update bones - - - this._updateRigidBodies(); - - this._stepSimulation(delta); - - this._updateBones(); // restore mesh if converted above - - - if (isNonDefaultScale) { - if (parent !== null) mesh.parent = parent; - mesh.scale.copy(scale); - } - - manager.freeThreeVector3(scale); - manager.freeThreeQuaternion(quaternion); - manager.freeThreeVector3(position); - return this; - }, - - /** - * Resets rigid bodies transorm to current bone's. - * - * @return {MMDPhysics} - */ - reset: function () { - for (let i = 0, il = this.bodies.length; i < il; i++) { - this.bodies[i].reset(); - } - - return this; - }, - - /** - * Warm ups Rigid bodies. Calculates cycles steps. - * - * @param {Integer} cycles - * @return {MMDPhysics} - */ - warmup: function (cycles) { - for (let i = 0; i < cycles; i++) { - this.update(1 / 60); - } - - return this; - }, - - /** - * Sets gravity. - * - * @param {Vector3} gravity - * @return {MMDPhysicsHelper} - */ - setGravity: function (gravity) { - this.world.setGravity(new Ammo.btVector3(gravity.x, gravity.y, gravity.z)); - this.gravity.copy(gravity); - return this; - }, - - /** - * Creates MMDPhysicsHelper - * - * @return {MMDPhysicsHelper} - */ - createHelper: function () { - return new MMDPhysicsHelper(this.mesh, this); - }, - // private methods - _init: function (mesh, rigidBodyParams, constraintParams) { - const manager = this.manager; // rigid body/constraint parameters are for - // mesh's default world transform as position(0, 0, 0), - // quaternion(0, 0, 0, 1) and scale(0, 0, 0) - - let parent = mesh.parent; - if (parent !== null) parent = null; - const currentPosition = manager.allocThreeVector3(); - const currentQuaternion = manager.allocThreeQuaternion(); - const currentScale = manager.allocThreeVector3(); - currentPosition.copy(mesh.position); - currentQuaternion.copy(mesh.quaternion); - currentScale.copy(mesh.scale); - mesh.position.set(0, 0, 0); - mesh.quaternion.set(0, 0, 0, 1); - mesh.scale.set(1, 1, 1); - mesh.updateMatrixWorld(true); - - if (this.world === null) { - this.world = this._createWorld(); - this.setGravity(this.gravity); - } - - this._initRigidBodies(rigidBodyParams); - - this._initConstraints(constraintParams); - - if (parent !== null) mesh.parent = parent; - mesh.position.copy(currentPosition); - mesh.quaternion.copy(currentQuaternion); - mesh.scale.copy(currentScale); - mesh.updateMatrixWorld(true); - this.reset(); - manager.freeThreeVector3(currentPosition); - manager.freeThreeQuaternion(currentQuaternion); - manager.freeThreeVector3(currentScale); - }, - _createWorld: function () { - const config = new Ammo.btDefaultCollisionConfiguration(); - const dispatcher = new Ammo.btCollisionDispatcher(config); - const cache = new Ammo.btDbvtBroadphase(); - const solver = new Ammo.btSequentialImpulseConstraintSolver(); - const world = new Ammo.btDiscreteDynamicsWorld(dispatcher, cache, solver, config); - return world; - }, - _initRigidBodies: function (rigidBodies) { - for (let i = 0, il = rigidBodies.length; i < il; i++) { - this.bodies.push(new RigidBody(this.mesh, this.world, rigidBodies[i], this.manager)); - } - }, - _initConstraints: function (constraints) { - for (let i = 0, il = constraints.length; i < il; i++) { - const params = constraints[i]; - const bodyA = this.bodies[params.rigidBodyIndex1]; - const bodyB = this.bodies[params.rigidBodyIndex2]; - this.constraints.push(new Constraint(this.mesh, this.world, bodyA, bodyB, params, this.manager)); - } - }, - _stepSimulation: function (delta) { - const unitStep = this.unitStep; - let stepTime = delta; - let maxStepNum = (delta / unitStep | 0) + 1; - - if (stepTime < unitStep) { - stepTime = unitStep; - maxStepNum = 1; - } - - if (maxStepNum > this.maxStepNum) { - maxStepNum = this.maxStepNum; - } - - this.world.stepSimulation(stepTime, maxStepNum, unitStep); - }, - _updateRigidBodies: function () { - for (let i = 0, il = this.bodies.length; i < il; i++) { - this.bodies[i].updateFromBone(); - } - }, - _updateBones: function () { - for (let i = 0, il = this.bodies.length; i < il; i++) { - this.bodies[i].updateBone(); - } - } - }; - /** - * This manager's responsibilies are - * - * 1. manage Ammo.js and Three.js object resources and - * improve the performance and the memory consumption by - * reusing objects. - * - * 2. provide simple Ammo object operations. - */ - - function ResourceManager() { - // for Three.js - this.threeVector3s = []; - this.threeMatrix4s = []; - this.threeQuaternions = []; - this.threeEulers = []; // for Ammo.js - - this.transforms = []; - this.quaternions = []; - this.vector3s = []; - } - - ResourceManager.prototype = { - constructor: ResourceManager, - allocThreeVector3: function () { - return this.threeVector3s.length > 0 ? this.threeVector3s.pop() : new Vector3(); - }, - freeThreeVector3: function (v) { - this.threeVector3s.push(v); - }, - allocThreeMatrix4: function () { - return this.threeMatrix4s.length > 0 ? this.threeMatrix4s.pop() : new Matrix4(); - }, - freeThreeMatrix4: function (m) { - this.threeMatrix4s.push(m); - }, - allocThreeQuaternion: function () { - return this.threeQuaternions.length > 0 ? this.threeQuaternions.pop() : new Quaternion(); - }, - freeThreeQuaternion: function (q) { - this.threeQuaternions.push(q); - }, - allocThreeEuler: function () { - return this.threeEulers.length > 0 ? this.threeEulers.pop() : new Euler(); - }, - freeThreeEuler: function (e) { - this.threeEulers.push(e); - }, - allocTransform: function () { - return this.transforms.length > 0 ? this.transforms.pop() : new Ammo.btTransform(); - }, - freeTransform: function (t) { - this.transforms.push(t); - }, - allocQuaternion: function () { - return this.quaternions.length > 0 ? this.quaternions.pop() : new Ammo.btQuaternion(); - }, - freeQuaternion: function (q) { - this.quaternions.push(q); - }, - allocVector3: function () { - return this.vector3s.length > 0 ? this.vector3s.pop() : new Ammo.btVector3(); - }, - freeVector3: function (v) { - this.vector3s.push(v); - }, - setIdentity: function (t) { - t.setIdentity(); - }, - getBasis: function (t) { - const q = this.allocQuaternion(); - t.getBasis().getRotation(q); - return q; - }, - getBasisAsMatrix3: function (t) { - const q = this.getBasis(t); - const m = this.quaternionToMatrix3(q); - this.freeQuaternion(q); - return m; - }, - getOrigin: function (t) { - return t.getOrigin(); - }, - setOrigin: function (t, v) { - t.getOrigin().setValue(v.x(), v.y(), v.z()); - }, - copyOrigin: function (t1, t2) { - const o = t2.getOrigin(); - this.setOrigin(t1, o); - }, - setBasis: function (t, q) { - t.setRotation(q); - }, - setBasisFromMatrix3: function (t, m) { - const q = this.matrix3ToQuaternion(m); - this.setBasis(t, q); - this.freeQuaternion(q); - }, - setOriginFromArray3: function (t, a) { - t.getOrigin().setValue(a[0], a[1], a[2]); - }, - setOriginFromThreeVector3: function (t, v) { - t.getOrigin().setValue(v.x, v.y, v.z); - }, - setBasisFromArray3: function (t, a) { - const thQ = this.allocThreeQuaternion(); - const thE = this.allocThreeEuler(); - thE.set(a[0], a[1], a[2]); - this.setBasisFromThreeQuaternion(t, thQ.setFromEuler(thE)); - this.freeThreeEuler(thE); - this.freeThreeQuaternion(thQ); - }, - setBasisFromThreeQuaternion: function (t, a) { - const q = this.allocQuaternion(); - q.setX(a.x); - q.setY(a.y); - q.setZ(a.z); - q.setW(a.w); - this.setBasis(t, q); - this.freeQuaternion(q); - }, - multiplyTransforms: function (t1, t2) { - const t = this.allocTransform(); - this.setIdentity(t); - const m1 = this.getBasisAsMatrix3(t1); - const m2 = this.getBasisAsMatrix3(t2); - const o1 = this.getOrigin(t1); - const o2 = this.getOrigin(t2); - const v1 = this.multiplyMatrix3ByVector3(m1, o2); - const v2 = this.addVector3(v1, o1); - this.setOrigin(t, v2); - const m3 = this.multiplyMatrices3(m1, m2); - this.setBasisFromMatrix3(t, m3); - this.freeVector3(v1); - this.freeVector3(v2); - return t; - }, - inverseTransform: function (t) { - const t2 = this.allocTransform(); - const m1 = this.getBasisAsMatrix3(t); - const o = this.getOrigin(t); - const m2 = this.transposeMatrix3(m1); - const v1 = this.negativeVector3(o); - const v2 = this.multiplyMatrix3ByVector3(m2, v1); - this.setOrigin(t2, v2); - this.setBasisFromMatrix3(t2, m2); - this.freeVector3(v1); - this.freeVector3(v2); - return t2; - }, - multiplyMatrices3: function (m1, m2) { - const m3 = []; - const v10 = this.rowOfMatrix3(m1, 0); - const v11 = this.rowOfMatrix3(m1, 1); - const v12 = this.rowOfMatrix3(m1, 2); - const v20 = this.columnOfMatrix3(m2, 0); - const v21 = this.columnOfMatrix3(m2, 1); - const v22 = this.columnOfMatrix3(m2, 2); - m3[0] = this.dotVectors3(v10, v20); - m3[1] = this.dotVectors3(v10, v21); - m3[2] = this.dotVectors3(v10, v22); - m3[3] = this.dotVectors3(v11, v20); - m3[4] = this.dotVectors3(v11, v21); - m3[5] = this.dotVectors3(v11, v22); - m3[6] = this.dotVectors3(v12, v20); - m3[7] = this.dotVectors3(v12, v21); - m3[8] = this.dotVectors3(v12, v22); - this.freeVector3(v10); - this.freeVector3(v11); - this.freeVector3(v12); - this.freeVector3(v20); - this.freeVector3(v21); - this.freeVector3(v22); - return m3; - }, - addVector3: function (v1, v2) { - const v = this.allocVector3(); - v.setValue(v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z()); - return v; - }, - dotVectors3: function (v1, v2) { - return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z(); - }, - rowOfMatrix3: function (m, i) { - const v = this.allocVector3(); - v.setValue(m[i * 3 + 0], m[i * 3 + 1], m[i * 3 + 2]); - return v; - }, - columnOfMatrix3: function (m, i) { - const v = this.allocVector3(); - v.setValue(m[i + 0], m[i + 3], m[i + 6]); - return v; - }, - negativeVector3: function (v) { - const v2 = this.allocVector3(); - v2.setValue(-v.x(), -v.y(), -v.z()); - return v2; - }, - multiplyMatrix3ByVector3: function (m, v) { - const v4 = this.allocVector3(); - const v0 = this.rowOfMatrix3(m, 0); - const v1 = this.rowOfMatrix3(m, 1); - const v2 = this.rowOfMatrix3(m, 2); - const x = this.dotVectors3(v0, v); - const y = this.dotVectors3(v1, v); - const z = this.dotVectors3(v2, v); - v4.setValue(x, y, z); - this.freeVector3(v0); - this.freeVector3(v1); - this.freeVector3(v2); - return v4; - }, - transposeMatrix3: function (m) { - const m2 = []; - m2[0] = m[0]; - m2[1] = m[3]; - m2[2] = m[6]; - m2[3] = m[1]; - m2[4] = m[4]; - m2[5] = m[7]; - m2[6] = m[2]; - m2[7] = m[5]; - m2[8] = m[8]; - return m2; - }, - quaternionToMatrix3: function (q) { - const m = []; - const x = q.x(); - const y = q.y(); - const z = q.z(); - const w = q.w(); - const xx = x * x; - const yy = y * y; - const zz = z * z; - const xy = x * y; - const yz = y * z; - const zx = z * x; - const xw = x * w; - const yw = y * w; - const zw = z * w; - m[0] = 1 - 2 * (yy + zz); - m[1] = 2 * (xy - zw); - m[2] = 2 * (zx + yw); - m[3] = 2 * (xy + zw); - m[4] = 1 - 2 * (zz + xx); - m[5] = 2 * (yz - xw); - m[6] = 2 * (zx - yw); - m[7] = 2 * (yz + xw); - m[8] = 1 - 2 * (xx + yy); - return m; - }, - matrix3ToQuaternion: function (m) { - const t = m[0] + m[4] + m[8]; - let s, x, y, z, w; - - if (t > 0) { - s = Math.sqrt(t + 1.0) * 2; - w = 0.25 * s; - x = (m[7] - m[5]) / s; - y = (m[2] - m[6]) / s; - z = (m[3] - m[1]) / s; - } else if (m[0] > m[4] && m[0] > m[8]) { - s = Math.sqrt(1.0 + m[0] - m[4] - m[8]) * 2; - w = (m[7] - m[5]) / s; - x = 0.25 * s; - y = (m[1] + m[3]) / s; - z = (m[2] + m[6]) / s; - } else if (m[4] > m[8]) { - s = Math.sqrt(1.0 + m[4] - m[0] - m[8]) * 2; - w = (m[2] - m[6]) / s; - x = (m[1] + m[3]) / s; - y = 0.25 * s; - z = (m[5] + m[7]) / s; - } else { - s = Math.sqrt(1.0 + m[8] - m[0] - m[4]) * 2; - w = (m[3] - m[1]) / s; - x = (m[2] + m[6]) / s; - y = (m[5] + m[7]) / s; - z = 0.25 * s; - } - - const q = this.allocQuaternion(); - q.setX(x); - q.setY(y); - q.setZ(z); - q.setW(w); - return q; - } - }; - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Ammo.btDiscreteDynamicsWorld} world - * @param {Object} params - * @param {ResourceManager} manager - */ - - function RigidBody(mesh, world, params, manager) { - this.mesh = mesh; - this.world = world; - this.params = params; - this.manager = manager; - this.body = null; - this.bone = null; - this.boneOffsetForm = null; - this.boneOffsetFormInverse = null; - - this._init(); - } - - RigidBody.prototype = { - constructor: MMDPhysics.RigidBody, - - /** - * Resets rigid body transform to the current bone's. - * - * @return {RigidBody} - */ - reset: function () { - this._setTransformFromBone(); - - return this; - }, - - /** - * Updates rigid body's transform from the current bone. - * - * @return {RidigBody} - */ - updateFromBone: function () { - if (this.params.boneIndex !== -1 && this.params.type === 0) { - this._setTransformFromBone(); - } - - return this; - }, - - /** - * Updates bone from the current ridid body's transform. - * - * @return {RidigBody} - */ - updateBone: function () { - if (this.params.type === 0 || this.params.boneIndex === -1) { - return this; - } - - this._updateBoneRotation(); - - if (this.params.type === 1) { - this._updateBonePosition(); - } - - this.bone.updateMatrixWorld(true); - - if (this.params.type === 2) { - this._setPositionFromBone(); - } - - return this; - }, - // private methods - _init: function () { - function generateShape(p) { - switch (p.shapeType) { - case 0: - return new Ammo.btSphereShape(p.width); - - case 1: - return new Ammo.btBoxShape(new Ammo.btVector3(p.width, p.height, p.depth)); - - case 2: - return new Ammo.btCapsuleShape(p.width, p.height); - - default: - throw `unknown shape type ${p.shapeType}`; - } - } - - const manager = this.manager; - const params = this.params; - const bones = this.mesh.skeleton.bones; - const bone = params.boneIndex === -1 ? new Bone() : bones[params.boneIndex]; - const shape = generateShape(params); - const weight = params.type === 0 ? 0 : params.weight; - const localInertia = manager.allocVector3(); - localInertia.setValue(0, 0, 0); - - if (weight !== 0) { - shape.calculateLocalInertia(weight, localInertia); - } - - const boneOffsetForm = manager.allocTransform(); - manager.setIdentity(boneOffsetForm); - manager.setOriginFromArray3(boneOffsetForm, params.position); - manager.setBasisFromArray3(boneOffsetForm, params.rotation); - const vector = manager.allocThreeVector3(); - const boneForm = manager.allocTransform(); - manager.setIdentity(boneForm); - manager.setOriginFromThreeVector3(boneForm, bone.getWorldPosition(vector)); - const form = manager.multiplyTransforms(boneForm, boneOffsetForm); - const state = new Ammo.btDefaultMotionState(form); - const info = new Ammo.btRigidBodyConstructionInfo(weight, state, shape, localInertia); - info.set_m_friction(params.friction); - info.set_m_restitution(params.restitution); - const body = new Ammo.btRigidBody(info); - - if (params.type === 0) { - body.setCollisionFlags(body.getCollisionFlags() | 2); - /* - * It'd be better to comment out this line though in general I should call this method - * because I'm not sure why but physics will be more like MMD's - * if I comment out. - */ - - body.setActivationState(4); - } - - body.setDamping(params.positionDamping, params.rotationDamping); - body.setSleepingThresholds(0, 0); - this.world.addRigidBody(body, 1 << params.groupIndex, params.groupTarget); - this.body = body; - this.bone = bone; - this.boneOffsetForm = boneOffsetForm; - this.boneOffsetFormInverse = manager.inverseTransform(boneOffsetForm); - manager.freeVector3(localInertia); - manager.freeTransform(form); - manager.freeTransform(boneForm); - manager.freeThreeVector3(vector); - }, - _getBoneTransform: function () { - const manager = this.manager; - const p = manager.allocThreeVector3(); - const q = manager.allocThreeQuaternion(); - const s = manager.allocThreeVector3(); - this.bone.matrixWorld.decompose(p, q, s); - const tr = manager.allocTransform(); - manager.setOriginFromThreeVector3(tr, p); - manager.setBasisFromThreeQuaternion(tr, q); - const form = manager.multiplyTransforms(tr, this.boneOffsetForm); - manager.freeTransform(tr); - manager.freeThreeVector3(s); - manager.freeThreeQuaternion(q); - manager.freeThreeVector3(p); - return form; - }, - _getWorldTransformForBone: function () { - const manager = this.manager; - const tr = this.body.getCenterOfMassTransform(); - return manager.multiplyTransforms(tr, this.boneOffsetFormInverse); - }, - _setTransformFromBone: function () { - const manager = this.manager; - - const form = this._getBoneTransform(); // TODO: check the most appropriate way to set - //this.body.setWorldTransform( form ); - - - this.body.setCenterOfMassTransform(form); - this.body.getMotionState().setWorldTransform(form); - manager.freeTransform(form); - }, - _setPositionFromBone: function () { - const manager = this.manager; - - const form = this._getBoneTransform(); - - const tr = manager.allocTransform(); - this.body.getMotionState().getWorldTransform(tr); - manager.copyOrigin(tr, form); // TODO: check the most appropriate way to set - //this.body.setWorldTransform( tr ); - - this.body.setCenterOfMassTransform(tr); - this.body.getMotionState().setWorldTransform(tr); - manager.freeTransform(tr); - manager.freeTransform(form); - }, - _updateBoneRotation: function () { - const manager = this.manager; - - const tr = this._getWorldTransformForBone(); - - const q = manager.getBasis(tr); - const thQ = manager.allocThreeQuaternion(); - const thQ2 = manager.allocThreeQuaternion(); - const thQ3 = manager.allocThreeQuaternion(); - thQ.set(q.x(), q.y(), q.z(), q.w()); - thQ2.setFromRotationMatrix(this.bone.matrixWorld); - thQ2.conjugate(); - thQ2.multiply(thQ); //this.bone.quaternion.multiply( thQ2 ); - - thQ3.setFromRotationMatrix(this.bone.matrix); // Renormalizing quaternion here because repeatedly transforming - // quaternion continuously accumulates floating point error and - // can end up being overflow. See #15335 - - this.bone.quaternion.copy(thQ2.multiply(thQ3).normalize()); - manager.freeThreeQuaternion(thQ); - manager.freeThreeQuaternion(thQ2); - manager.freeThreeQuaternion(thQ3); - manager.freeQuaternion(q); - manager.freeTransform(tr); - }, - _updateBonePosition: function () { - const manager = this.manager; - - const tr = this._getWorldTransformForBone(); - - const thV = manager.allocThreeVector3(); - const o = manager.getOrigin(tr); - thV.set(o.x(), o.y(), o.z()); - - if (this.bone.parent) { - this.bone.parent.worldToLocal(thV); - } - - this.bone.position.copy(thV); - manager.freeThreeVector3(thV); - manager.freeTransform(tr); - } - }; - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Ammo.btDiscreteDynamicsWorld} world - * @param {RigidBody} bodyA - * @param {RigidBody} bodyB - * @param {Object} params - * @param {ResourceManager} manager - */ - - function Constraint(mesh, world, bodyA, bodyB, params, manager) { - this.mesh = mesh; - this.world = world; - this.bodyA = bodyA; - this.bodyB = bodyB; - this.params = params; - this.manager = manager; - this.constraint = null; - - this._init(); - } - - Constraint.prototype = { - constructor: Constraint, - // private method - _init: function () { - const manager = this.manager; - const params = this.params; - const bodyA = this.bodyA; - const bodyB = this.bodyB; - const form = manager.allocTransform(); - manager.setIdentity(form); - manager.setOriginFromArray3(form, params.position); - manager.setBasisFromArray3(form, params.rotation); - const formA = manager.allocTransform(); - const formB = manager.allocTransform(); - bodyA.body.getMotionState().getWorldTransform(formA); - bodyB.body.getMotionState().getWorldTransform(formB); - const formInverseA = manager.inverseTransform(formA); - const formInverseB = manager.inverseTransform(formB); - const formA2 = manager.multiplyTransforms(formInverseA, form); - const formB2 = manager.multiplyTransforms(formInverseB, form); - const constraint = new Ammo.btGeneric6DofSpringConstraint(bodyA.body, bodyB.body, formA2, formB2, true); - const lll = manager.allocVector3(); - const lul = manager.allocVector3(); - const all = manager.allocVector3(); - const aul = manager.allocVector3(); - lll.setValue(params.translationLimitation1[0], params.translationLimitation1[1], params.translationLimitation1[2]); - lul.setValue(params.translationLimitation2[0], params.translationLimitation2[1], params.translationLimitation2[2]); - all.setValue(params.rotationLimitation1[0], params.rotationLimitation1[1], params.rotationLimitation1[2]); - aul.setValue(params.rotationLimitation2[0], params.rotationLimitation2[1], params.rotationLimitation2[2]); - constraint.setLinearLowerLimit(lll); - constraint.setLinearUpperLimit(lul); - constraint.setAngularLowerLimit(all); - constraint.setAngularUpperLimit(aul); - - for (let i = 0; i < 3; i++) { - if (params.springPosition[i] !== 0) { - constraint.enableSpring(i, true); - constraint.setStiffness(i, params.springPosition[i]); - } - } - - for (let i = 0; i < 3; i++) { - if (params.springRotation[i] !== 0) { - constraint.enableSpring(i + 3, true); - constraint.setStiffness(i + 3, params.springRotation[i]); - } - } - /* - * Currently(10/31/2016) official ammo.js doesn't support - * btGeneric6DofSpringConstraint.setParam method. - * You need custom ammo.js (add the method into idl) if you wanna use. - * By setting this parameter, physics will be more like MMD's - */ - - - if (constraint.setParam !== undefined) { - for (let i = 0; i < 6; i++) { - // this parameter is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js - constraint.setParam(2, 0.475, i); - } - } - - this.world.addConstraint(constraint, true); - this.constraint = constraint; - manager.freeTransform(form); - manager.freeTransform(formA); - manager.freeTransform(formB); - manager.freeTransform(formInverseA); - manager.freeTransform(formInverseB); - manager.freeTransform(formA2); - manager.freeTransform(formB2); - manager.freeVector3(lll); - manager.freeVector3(lul); - manager.freeVector3(all); - manager.freeVector3(aul); - } - }; - /** - * Visualize Rigid bodies - * - * @param {THREE.SkinnedMesh} mesh - * @param {Physics} physics - */ - - function MMDPhysicsHelper(mesh, physics) { - Object3D.call(this); - this.root = mesh; - this.physics = physics; - this.matrix.copy(mesh.matrixWorld); - this.matrixAutoUpdate = false; - this.materials = []; - this.materials.push(new MeshBasicMaterial({ - color: new Color(0xff8888), - wireframe: true, - depthTest: false, - depthWrite: false, - opacity: 0.25, - transparent: true - })); - this.materials.push(new MeshBasicMaterial({ - color: new Color(0x88ff88), - wireframe: true, - depthTest: false, - depthWrite: false, - opacity: 0.25, - transparent: true - })); - this.materials.push(new MeshBasicMaterial({ - color: new Color(0x8888ff), - wireframe: true, - depthTest: false, - depthWrite: false, - opacity: 0.25, - transparent: true - })); - - this._init(); - } - - MMDPhysicsHelper.prototype = Object.assign(Object.create(Object3D.prototype), { - constructor: MMDPhysicsHelper, - - /** - * Updates Rigid Bodies visualization. - */ - updateMatrixWorld: (() => { - const position = new Vector3(); - const quaternion = new Quaternion(); - const scale = new Vector3(); - const matrixWorldInv = new Matrix4(); - return function updateMatrixWorld(force) { - const mesh = this.root; - - if (this.visible) { - const bodies = this.physics.bodies; - matrixWorldInv.copy(mesh.matrixWorld).decompose(position, quaternion, scale).compose(position, quaternion, scale.set(1, 1, 1)).invert(); - - for (let i = 0, il = bodies.length; i < il; i++) { - const body = bodies[i].body; - const child = this.children[i]; - const tr = body.getCenterOfMassTransform(); - const origin = tr.getOrigin(); - const rotation = tr.getRotation(); - child.position.set(origin.x(), origin.y(), origin.z()).applyMatrix4(matrixWorldInv); - child.quaternion.setFromRotationMatrix(matrixWorldInv).multiply(quaternion.set(rotation.x(), rotation.y(), rotation.z(), rotation.w())); - } - } - - this.matrix.copy(mesh.matrixWorld).decompose(position, quaternion, scale).compose(position, quaternion, scale.set(1, 1, 1)); - Object3D.prototype.updateMatrixWorld.call(this, force); - }; - })(), - // private method - _init: function () { - const bodies = this.physics.bodies; - - function createGeometry(param) { - switch (param.shapeType) { - case 0: - return new SphereGeometry(param.width, 16, 8); - - case 1: - return new BoxGeometry(param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8); - - case 2: - return new createCapsuleGeometry(param.width, param.height, 16, 8); - - default: - return null; - } - } // copy from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mytest37.js?ver=20160815 - - - function createCapsuleGeometry(radius, cylinderHeight, segmentsRadius, segmentsHeight) { - const geometry = new CylinderGeometry(radius, radius, cylinderHeight, segmentsRadius, segmentsHeight, true); - const upperSphere = new Mesh(new SphereGeometry(radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, 0, Math.PI / 2)); - const lowerSphere = new Mesh(new SphereGeometry(radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2)); - upperSphere.position.set(0, cylinderHeight / 2, 0); - lowerSphere.position.set(0, -cylinderHeight / 2, 0); - upperSphere.updateMatrix(); - lowerSphere.updateMatrix(); - geometry.merge(upperSphere.geometry, upperSphere.matrix); - geometry.merge(lowerSphere.geometry, lowerSphere.matrix); - return geometry; - } - - for (let i = 0, il = bodies.length; i < il; i++) { - const param = bodies[i].params; - this.add(new Mesh(createGeometry(param), this.materials[param.type])); - } - } - }); - return MMDPhysics; -})(); - -/** - * MMDAnimationHelper handles animation of MMD assets loaded by MMDLoader - * with MMD special features as IK, Grant, and Physics. - * - * Dependencies - * - ammo.js https://github.com/kripken/ammo.js - * - MMDPhysics - * - CCDIKSolver - * - * TODO - * - more precise grant skinning support. - */ - -(() => { - /** - * @param {Object} params - (optional) - * @param {boolean} params.sync - Whether animation durations of added objects are synched. Default is true. - * @param {Number} params.afterglow - Default is 0.0. - * @param {boolean} params.resetPhysicsOnLoop - Default is true. - */ - function MMDAnimationHelper(params) { - params = params || {}; - this.meshes = []; - this.camera = null; - this.cameraTarget = new Object3D(); - this.cameraTarget.name = 'target'; - this.audio = null; - this.audioManager = null; - this.objects = new WeakMap(); - this.configuration = { - sync: params.sync !== undefined ? params.sync : true, - afterglow: params.afterglow !== undefined ? params.afterglow : 0.0, - resetPhysicsOnLoop: params.resetPhysicsOnLoop !== undefined ? params.resetPhysicsOnLoop : true - }; - this.enabled = { - animation: true, - ik: true, - grant: true, - physics: true, - cameraAnimation: true - }; - - this.onBeforePhysics = () => - /* mesh */ - {}; // experimental - - - this.sharedPhysics = false; - this.masterPhysics = null; - } - - MMDAnimationHelper.prototype = { - constructor: MMDAnimationHelper, - - /** - * Adds an Three.js Object to helper and setups animation. - * The anmation durations of added objects are synched - * if this.configuration.sync is true. - * - * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object - * @param {Object} params - (optional) - * @param {THREE.AnimationClip|Array} params.animation - Only for THREE.SkinnedMesh and THREE.Camera. Default is undefined. - * @param {boolean} params.physics - Only for THREE.SkinnedMesh. Default is true. - * @param {Integer} params.warmup - Only for THREE.SkinnedMesh and physics is true. Default is 60. - * @param {Number} params.unitStep - Only for THREE.SkinnedMesh and physics is true. Default is 1 / 65. - * @param {Integer} params.maxStepNum - Only for THREE.SkinnedMesh and physics is true. Default is 3. - * @param {Vector3} params.gravity - Only for THREE.SkinnedMesh and physics is true. Default ( 0, - 9.8 * 10, 0 ). - * @param {Number} params.delayTime - Only for THREE.Audio. Default is 0.0. - * @return {MMDAnimationHelper} - */ - add: function (object, params) { - params = params || {}; - - if (object.isSkinnedMesh) { - this._addMesh(object, params); - } else if (object.isCamera) { - this._setupCamera(object, params); - } else if (object.type === 'Audio') { - this._setupAudio(object, params); - } else { - throw new Error('THREE.MMDAnimationHelper.add: ' + 'accepts only ' + 'THREE.SkinnedMesh or ' + 'THREE.Camera or ' + 'THREE.Audio instance.'); - } - - if (this.configuration.sync) this._syncDuration(); - return this; - }, - - /** - * Removes an Three.js Object from helper. - * - * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object - * @return {MMDAnimationHelper} - */ - remove: function (object) { - if (object.isSkinnedMesh) { - this._removeMesh(object); - } else if (object.isCamera) { - this._clearCamera(object); - } else if (object.type === 'Audio') { - this._clearAudio(object); - } else { - throw new Error('THREE.MMDAnimationHelper.remove: ' + 'accepts only ' + 'THREE.SkinnedMesh or ' + 'THREE.Camera or ' + 'THREE.Audio instance.'); - } - - if (this.configuration.sync) this._syncDuration(); - return this; - }, - - /** - * Updates the animation. - * - * @param {Number} delta - * @return {MMDAnimationHelper} - */ - update: function (delta) { - if (this.audioManager !== null) this.audioManager.control(delta); - - for (let i = 0; i < this.meshes.length; i++) { - this._animateMesh(this.meshes[i], delta); - } - - if (this.sharedPhysics) this._updateSharedPhysics(delta); - if (this.camera !== null) this._animateCamera(this.camera, delta); - return this; - }, - - /** - * Changes the pose of SkinnedMesh as VPD specifies. - * - * @param {THREE.SkinnedMesh} mesh - * @param {Object} vpd - VPD content parsed MMDParser - * @param {Object} params - (optional) - * @param {boolean} params.resetPose - Default is true. - * @param {boolean} params.ik - Default is true. - * @param {boolean} params.grant - Default is true. - * @return {MMDAnimationHelper} - */ - pose: function (mesh, vpd, params) { - params = params || {}; - if (params.resetPose !== false) mesh.pose(); - const bones = mesh.skeleton.bones; - const boneParams = vpd.bones; - const boneNameDictionary = {}; - - for (let i = 0, il = bones.length; i < il; i++) { - boneNameDictionary[bones[i].name] = i; - } - - const vector = new Vector3(); - const quaternion = new Quaternion(); - - for (let i = 0, il = boneParams.length; i < il; i++) { - const boneParam = boneParams[i]; - const boneIndex = boneNameDictionary[boneParam.name]; - if (boneIndex === undefined) continue; - const bone = bones[boneIndex]; - bone.position.add(vector.fromArray(boneParam.translation)); - bone.quaternion.multiply(quaternion.fromArray(boneParam.quaternion)); - } - - mesh.updateMatrixWorld(true); - - if (params.ik !== false) { - this._createCCDIKSolver(mesh).update(params.saveOriginalBonesBeforeIK); // this param is experimental - - } - - if (params.grant !== false) { - this.createGrantSolver(mesh).update(); - } - - return this; - }, - - /** - * Enabes/Disables an animation feature. - * - * @param {string} key - * @param {boolean} enabled - * @return {MMDAnimationHelper} - */ - enable: function (key, enabled) { - if (this.enabled[key] === undefined) { - throw new Error(`THREE.MMDAnimationHelper.enable: unknown key ${key}`); - } - - this.enabled[key] = enabled; - - if (key === 'physics') { - for (let i = 0, il = this.meshes.length; i < il; i++) { - this._optimizeIK(this.meshes[i], enabled); - } - } - - return this; - }, - - /** - * Creates an GrantSolver instance. - * - * @param {THREE.SkinnedMesh} mesh - * @return {GrantSolver} - */ - createGrantSolver: function (mesh) { - return new GrantSolver(mesh, mesh.geometry.userData.MMD.grants); - }, - // private methods - _addMesh: function (mesh, params) { - if (this.meshes.indexOf(mesh) >= 0) { - throw new Error(`THREE.MMDAnimationHelper._addMesh: SkinnedMesh '${mesh.name}' has already been added.`); - } - - this.meshes.push(mesh); - this.objects.set(mesh, { - looped: false - }); - - this._setupMeshAnimation(mesh, params.animation); - - if (params.physics !== false) { - this._setupMeshPhysics(mesh, params); - } - - return this; - }, - _setupCamera: function (camera, params) { - if (this.camera === camera) { - throw new Error(`THREE.MMDAnimationHelper._setupCamera: Camera '${camera.name}' has already been set.`); - } - - if (this.camera) this.clearCamera(this.camera); - this.camera = camera; - camera.add(this.cameraTarget); - this.objects.set(camera, {}); - - if (params.animation !== undefined) { - this._setupCameraAnimation(camera, params.animation); - } - - return this; - }, - _setupAudio: function (audio, params) { - if (this.audio === audio) { - throw new Error(`THREE.MMDAnimationHelper._setupAudio: Audio '${audio.name}' has already been set.`); - } - - if (this.audio) this.clearAudio(this.audio); - this.audio = audio; - this.audioManager = new AudioManager(audio, params); - this.objects.set(this.audioManager, { - duration: this.audioManager.duration - }); - return this; - }, - _removeMesh: function (mesh) { - let found = false; - let writeIndex = 0; - - for (let i = 0, il = this.meshes.length; i < il; i++) { - if (this.meshes[i] === mesh) { - this.objects.delete(mesh); - found = true; - continue; - } - - this.meshes[writeIndex++] = this.meshes[i]; - } - - if (!found) { - throw new Error(`THREE.MMDAnimationHelper._removeMesh: SkinnedMesh '${mesh.name}' has not been added yet.`); - } - - this.meshes.length = writeIndex; - return this; - }, - _clearCamera: function (camera) { - if (camera !== this.camera) { - throw new Error(`THREE.MMDAnimationHelper._clearCamera: Camera '${camera.name}' has not been set yet.`); - } - - this.camera.remove(this.cameraTarget); - this.objects.delete(this.camera); - this.camera = null; - return this; - }, - _clearAudio: function (audio) { - if (audio !== this.audio) { - throw new Error(`THREE.MMDAnimationHelper._clearAudio: Audio '${audio.name}' has not been set yet.`); - } - - this.objects.delete(this.audioManager); - this.audio = null; - this.audioManager = null; - return this; - }, - _setupMeshAnimation: function (mesh, animation) { - const objects = this.objects.get(mesh); - - if (animation !== undefined) { - const animations = Array.isArray(animation) ? animation : [animation]; - objects.mixer = new AnimationMixer(mesh); - - for (let i = 0, il = animations.length; i < il; i++) { - objects.mixer.clipAction(animations[i]).play(); - } // TODO: find a workaround not to access ._clip looking like a private property - - - objects.mixer.addEventListener('loop', event => { - const tracks = event.action._clip.tracks; - if (tracks.length > 0 && tracks[0].name.slice(0, 6) !== '.bones') return; - objects.looped = true; - }); - } - - objects.ikSolver = this._createCCDIKSolver(mesh); - objects.grantSolver = this.createGrantSolver(mesh); - return this; - }, - _setupCameraAnimation: function (camera, animation) { - const animations = Array.isArray(animation) ? animation : [animation]; - const objects = this.objects.get(camera); - objects.mixer = new AnimationMixer(camera); - - for (let i = 0, il = animations.length; i < il; i++) { - objects.mixer.clipAction(animations[i]).play(); - } - }, - _setupMeshPhysics: function (mesh, params) { - const objects = this.objects.get(mesh); // shared physics is experimental - - if (params.world === undefined && this.sharedPhysics) { - const masterPhysics = this._getMasterPhysics(); - - if (masterPhysics !== null) world = masterPhysics.world; // eslint-disable-line no-undef - } - - objects.physics = this._createMMDPhysics(mesh, params); - - if (objects.mixer && params.animationWarmup !== false) { - this._animateMesh(mesh, 0); - - objects.physics.reset(); - } - - objects.physics.warmup(params.warmup !== undefined ? params.warmup : 60); - - this._optimizeIK(mesh, true); - }, - _animateMesh: function (mesh, delta) { - const objects = this.objects.get(mesh); - const mixer = objects.mixer; - const ikSolver = objects.ikSolver; - const grantSolver = objects.grantSolver; - const physics = objects.physics; - const looped = objects.looped; // alternate solution to save/restore bones but less performant? - //mesh.pose(); - //this._updatePropertyMixersBuffer( mesh ); - - if (mixer && this.enabled.animation) { - this._restoreBones(mesh); - - mixer.update(delta); - - this._saveBones(mesh); - - if (ikSolver && this.enabled.ik) { - mesh.updateMatrixWorld(true); - ikSolver.update(); - } - - if (grantSolver && this.enabled.grant) { - grantSolver.update(); - } - } - - if (looped === true && this.enabled.physics) { - if (physics && this.configuration.resetPhysicsOnLoop) physics.reset(); - objects.looped = false; - } - - if (physics && this.enabled.physics && !this.sharedPhysics) { - this.onBeforePhysics(mesh); - physics.update(delta); - } - }, - _animateCamera: function (camera, delta) { - const mixer = this.objects.get(camera).mixer; - - if (mixer && this.enabled.cameraAnimation) { - mixer.update(delta); - camera.updateProjectionMatrix(); - camera.up.set(0, 1, 0); - camera.up.applyQuaternion(camera.quaternion); - camera.lookAt(this.cameraTarget.position); - } - }, - _optimizeIK: function (mesh, physicsEnabled) { - const iks = mesh.geometry.userData.MMD.iks; - const bones = mesh.geometry.userData.MMD.bones; - - for (let i = 0, il = iks.length; i < il; i++) { - const ik = iks[i]; - const links = ik.links; - - for (let j = 0, jl = links.length; j < jl; j++) { - const link = links[j]; - - if (physicsEnabled === true) { - // disable IK of the bone the corresponding rigidBody type of which is 1 or 2 - // because its rotation will be overriden by physics - link.enabled = bones[link.index].rigidBodyType > 0 ? false : true; - } else { - link.enabled = true; - } - } - } - }, - _createCCDIKSolver: function (mesh) { - if (CCDIKSolver === undefined) { - throw new Error('THREE.MMDAnimationHelper: Import CCDIKSolver.'); - } - - return new CCDIKSolver(mesh, mesh.geometry.userData.MMD.iks); - }, - _createMMDPhysics: function (mesh, params) { - if (MMDPhysics === undefined) { - throw new Error('THREE.MMDPhysics: Import MMDPhysics.'); - } - - return new MMDPhysics(mesh, mesh.geometry.userData.MMD.rigidBodies, mesh.geometry.userData.MMD.constraints, params); - }, - - /* - * Detects the longest duration and then sets it to them to sync. - * TODO: Not to access private properties ( ._actions and ._clip ) - */ - _syncDuration: function () { - let max = 0.0; - const objects = this.objects; - const meshes = this.meshes; - const camera = this.camera; - const audioManager = this.audioManager; // get the longest duration - - for (let i = 0, il = meshes.length; i < il; i++) { - var mixer = this.objects.get(meshes[i]).mixer; - if (mixer === undefined) continue; - - for (let j = 0; j < mixer._actions.length; j++) { - var clip = mixer._actions[j]._clip; - - if (!objects.has(clip)) { - objects.set(clip, { - duration: clip.duration - }); - } - - max = Math.max(max, objects.get(clip).duration); - } - } - - if (camera !== null) { - var mixer = this.objects.get(camera).mixer; - - if (mixer !== undefined) { - for (let i = 0, il = mixer._actions.length; i < il; i++) { - var clip = mixer._actions[i]._clip; - - if (!objects.has(clip)) { - objects.set(clip, { - duration: clip.duration - }); - } - - max = Math.max(max, objects.get(clip).duration); - } - } - } - - if (audioManager !== null) { - max = Math.max(max, objects.get(audioManager).duration); - } - - max += this.configuration.afterglow; // update the duration - - for (let i = 0, il = this.meshes.length; i < il; i++) { - var mixer = this.objects.get(this.meshes[i]).mixer; - if (mixer === undefined) continue; - - for (let j = 0, jl = mixer._actions.length; j < jl; j++) { - mixer._actions[j]._clip.duration = max; - } - } - - if (camera !== null) { - var mixer = this.objects.get(camera).mixer; - - if (mixer !== undefined) { - for (let i = 0, il = mixer._actions.length; i < il; i++) { - mixer._actions[i]._clip.duration = max; - } - } - } - - if (audioManager !== null) { - audioManager.duration = max; - } - }, - // workaround - _updatePropertyMixersBuffer: function (mesh) { - const mixer = this.objects.get(mesh).mixer; - const propertyMixers = mixer._bindings; - const accuIndex = mixer._accuIndex; - - for (let i = 0, il = propertyMixers.length; i < il; i++) { - const propertyMixer = propertyMixers[i]; - const buffer = propertyMixer.buffer; - const stride = propertyMixer.valueSize; - const offset = (accuIndex + 1) * stride; - propertyMixer.binding.getValue(buffer, offset); - } - }, - - /* - * Avoiding these two issues by restore/save bones before/after mixer animation. - * - * 1. PropertyMixer used by AnimationMixer holds cache value in .buffer. - * Calculating IK, Grant, and Physics after mixer animation can break - * the cache coherency. - * - * 2. Applying Grant two or more times without reset the posing breaks model. - */ - _saveBones: function (mesh) { - const objects = this.objects.get(mesh); - const bones = mesh.skeleton.bones; - let backupBones = objects.backupBones; - - if (backupBones === undefined) { - backupBones = new Float32Array(bones.length * 7); - objects.backupBones = backupBones; - } - - for (let i = 0, il = bones.length; i < il; i++) { - const bone = bones[i]; - bone.position.toArray(backupBones, i * 7); - bone.quaternion.toArray(backupBones, i * 7 + 3); - } - }, - _restoreBones: function (mesh) { - const objects = this.objects.get(mesh); - const backupBones = objects.backupBones; - if (backupBones === undefined) return; - const bones = mesh.skeleton.bones; - - for (let i = 0, il = bones.length; i < il; i++) { - const bone = bones[i]; - bone.position.fromArray(backupBones, i * 7); - bone.quaternion.fromArray(backupBones, i * 7 + 3); - } - }, - // experimental - _getMasterPhysics: function () { - if (this.masterPhysics !== null) return this.masterPhysics; - - for (let i = 0, il = this.meshes.length; i < il; i++) { - const physics = this.meshes[i].physics; - - if (physics !== undefined && physics !== null) { - this.masterPhysics = physics; - return this.masterPhysics; - } - } - - return null; - }, - _updateSharedPhysics: function (delta) { - if (this.meshes.length === 0 || !this.enabled.physics || !this.sharedPhysics) return; - - const physics = this._getMasterPhysics(); - - if (physics === null) return; - - for (let i = 0, il = this.meshes.length; i < il; i++) { - var p = this.meshes[i].physics; - - if (p !== null && p !== undefined) { - p.updateRigidBodies(); - } - } - - physics.stepSimulation(delta); - - for (let i = 0, il = this.meshes.length; i < il; i++) { - var p = this.meshes[i].physics; - - if (p !== null && p !== undefined) { - p.updateBones(); - } - } - } - }; // - - /** - * @param {THREE.Audio} audio - * @param {Object} params - (optional) - * @param {Nuumber} params.delayTime - */ - - function AudioManager(audio, params) { - params = params || {}; - this.audio = audio; - this.elapsedTime = 0.0; - this.currentTime = 0.0; - this.delayTime = params.delayTime !== undefined ? params.delayTime : 0.0; - this.audioDuration = this.audio.buffer.duration; - this.duration = this.audioDuration + this.delayTime; - } - - AudioManager.prototype = { - constructor: AudioManager, - - /** - * @param {Number} delta - * @return {AudioManager} - */ - control: function (delta) { - this.elapsed += delta; - this.currentTime += delta; - if (this._shouldStopAudio()) this.audio.stop(); - if (this._shouldStartAudio()) this.audio.play(); - return this; - }, - // private methods - _shouldStartAudio: function () { - if (this.audio.isPlaying) return false; - - while (this.currentTime >= this.duration) { - this.currentTime -= this.duration; - } - - if (this.currentTime < this.delayTime) return false; // 'duration' can be bigger than 'audioDuration + delayTime' because of sync configuration - - if (this.currentTime - this.delayTime > this.audioDuration) return false; - return true; - }, - _shouldStopAudio: function () { - return this.audio.isPlaying && this.currentTime >= this.duration; - } - }; - /** - * @param {THREE.SkinnedMesh} mesh - * @param {Array} grants - */ - - function GrantSolver(mesh, grants) { - this.mesh = mesh; - this.grants = grants || []; - } - - GrantSolver.prototype = { - constructor: GrantSolver, - - /** - * @return {GrantSolver} - */ - update: (() => { - const quaternion = new Quaternion(); - return function () { - const bones = this.mesh.skeleton.bones; - const grants = this.grants; - - for (let i = 0, il = grants.length; i < il; i++) { - const grant = grants[i]; - const bone = bones[grant.index]; - const parentBone = bones[grant.parentIndex]; - - if (grant.isLocal) { - // TODO: implement - if (grant.affectPosition) ; // TODO: implement - - - if (grant.affectRotation) ; - } else { - // TODO: implement - if (grant.affectPosition) ; - - if (grant.affectRotation) { - quaternion.set(0, 0, 0, 1); - quaternion.slerp(parentBone.quaternion, grant.ratio); - bone.quaternion.multiply(quaternion); - } - } - } - - return this; - }; - })() - }; - return MMDAnimationHelper; -})(); - -class Reflector extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - this.type = 'Reflector'; - const scope = this; - const color = options.color !== undefined ? new Color(options.color) : new Color(0x7f7f7f); - const textureWidth = options.textureWidth || 512; - const textureHeight = options.textureHeight || 512; - const clipBias = options.clipBias || 0; - const shader = options.shader || Reflector.ReflectorShader; // - - const reflectorPlane = new Plane(); - const normal = new Vector3(); - const reflectorWorldPosition = new Vector3(); - const cameraWorldPosition = new Vector3(); - const rotationMatrix = new Matrix4(); - const lookAtPosition = new Vector3(0, 0, -1); - const clipPlane = new Vector4(); - const view = new Vector3(); - const target = new Vector3(); - const q = new Vector4(); - const textureMatrix = new Matrix4(); - const virtualCamera = new PerspectiveCamera(); - const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight); - const material = new ShaderMaterial({ - uniforms: UniformsUtils.clone(shader.uniforms), - fragmentShader: shader.fragmentShader, - vertexShader: shader.vertexShader - }); - material.uniforms['tDiffuse'].value = renderTarget.texture; - material.uniforms['color'].value = color; - material.uniforms['textureMatrix'].value = textureMatrix; - this.material = material; - - this.onBeforeRender = function (renderer, scene, camera) { - reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); - cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); - rotationMatrix.extractRotation(scope.matrixWorld); - normal.set(0, 0, 1); - normal.applyMatrix4(rotationMatrix); - view.subVectors(reflectorWorldPosition, cameraWorldPosition); // Avoid rendering when reflector is facing away - - if (view.dot(normal) > 0) return; - view.reflect(normal).negate(); - view.add(reflectorWorldPosition); - rotationMatrix.extractRotation(camera.matrixWorld); - lookAtPosition.set(0, 0, -1); - lookAtPosition.applyMatrix4(rotationMatrix); - lookAtPosition.add(cameraWorldPosition); - target.subVectors(reflectorWorldPosition, lookAtPosition); - target.reflect(normal).negate(); - target.add(reflectorWorldPosition); - virtualCamera.position.copy(view); - virtualCamera.up.set(0, 1, 0); - virtualCamera.up.applyMatrix4(rotationMatrix); - virtualCamera.up.reflect(normal); - virtualCamera.lookAt(target); - virtualCamera.far = camera.far; // Used in WebGLBackground - - virtualCamera.updateMatrixWorld(); - virtualCamera.projectionMatrix.copy(camera.projectionMatrix); // Update the texture matrix - - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); - textureMatrix.multiply(virtualCamera.projectionMatrix); - textureMatrix.multiply(virtualCamera.matrixWorldInverse); - textureMatrix.multiply(scope.matrixWorld); // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html - // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf - - reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition); - reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse); - clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant); - const projectionMatrix = virtualCamera.projectionMatrix; - q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; - q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; - q.z = -1.0; - q.w = (1.0 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; // Calculate the scaled plane vector - - clipPlane.multiplyScalar(2.0 / clipPlane.dot(q)); // Replacing the third row of the projection matrix - - projectionMatrix.elements[2] = clipPlane.x; - projectionMatrix.elements[6] = clipPlane.y; - projectionMatrix.elements[10] = clipPlane.z + 1.0 - clipBias; - projectionMatrix.elements[14] = clipPlane.w; // Render - - renderTarget.texture.encoding = renderer.outputEncoding; - scope.visible = false; - const currentRenderTarget = renderer.getRenderTarget(); - const currentXrEnabled = renderer.xr.enabled; - const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; - renderer.xr.enabled = false; // Avoid camera modification - - renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows - - renderer.setRenderTarget(renderTarget); - renderer.state.buffers.depth.setMask(true); // make sure the depth buffer is writable so it can be properly cleared, see #18897 - - if (renderer.autoClear === false) renderer.clear(); - renderer.render(scene, virtualCamera); - renderer.xr.enabled = currentXrEnabled; - renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; - renderer.setRenderTarget(currentRenderTarget); // Restore viewport - - const viewport = camera.viewport; - - if (viewport !== undefined) { - renderer.state.viewport(viewport); - } - - scope.visible = true; - }; - - this.getRenderTarget = function () { - return renderTarget; - }; - - this.dispose = function () { - renderTarget.dispose(); - scope.material.dispose(); - }; - } - -} - -Reflector.prototype.isReflector = true; -Reflector.ReflectorShader = { - uniforms: { - color: { - value: null - }, - tDiffuse: { - value: null - }, - textureMatrix: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - uniform mat4 textureMatrix; - varying vec4 vUv; - - #include - #include - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - #include - - }`, - fragmentShader: - /* glsl */ - ` - uniform vec3 color; - uniform sampler2D tDiffuse; - varying vec4 vUv; - - #include - - float blendOverlay( float base, float blend ) { - - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - - } - - vec3 blendOverlay( vec3 base, vec3 blend ) { - - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - - } - - void main() { - - #include - - vec4 base = texture2DProj( tDiffuse, vUv ); - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - - }` -}; - -class Refractor extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - this.type = 'Refractor'; - const scope = this; - const color = options.color !== undefined ? new Color(options.color) : new Color(0x7f7f7f); - const textureWidth = options.textureWidth || 512; - const textureHeight = options.textureHeight || 512; - const clipBias = options.clipBias || 0; - const shader = options.shader || Refractor.RefractorShader; // - - const virtualCamera = new PerspectiveCamera(); - virtualCamera.matrixAutoUpdate = false; - virtualCamera.userData.refractor = true; // - - const refractorPlane = new Plane(); - const textureMatrix = new Matrix4(); // render target - - const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight); // material - - this.material = new ShaderMaterial({ - uniforms: UniformsUtils.clone(shader.uniforms), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - transparent: true // ensures, refractors are drawn from farthest to closest - - }); - this.material.uniforms['color'].value = color; - this.material.uniforms['tDiffuse'].value = renderTarget.texture; - this.material.uniforms['textureMatrix'].value = textureMatrix; // functions - - const visible = function () { - const refractorWorldPosition = new Vector3(); - const cameraWorldPosition = new Vector3(); - const rotationMatrix = new Matrix4(); - const view = new Vector3(); - const normal = new Vector3(); - return function visible(camera) { - refractorWorldPosition.setFromMatrixPosition(scope.matrixWorld); - cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); - view.subVectors(refractorWorldPosition, cameraWorldPosition); - rotationMatrix.extractRotation(scope.matrixWorld); - normal.set(0, 0, 1); - normal.applyMatrix4(rotationMatrix); - return view.dot(normal) < 0; - }; - }(); - - const updateRefractorPlane = function () { - const normal = new Vector3(); - const position = new Vector3(); - const quaternion = new Quaternion(); - const scale = new Vector3(); - return function updateRefractorPlane() { - scope.matrixWorld.decompose(position, quaternion, scale); - normal.set(0, 0, 1).applyQuaternion(quaternion).normalize(); // flip the normal because we want to cull everything above the plane - - normal.negate(); - refractorPlane.setFromNormalAndCoplanarPoint(normal, position); - }; - }(); - - const updateVirtualCamera = function () { - const clipPlane = new Plane(); - const clipVector = new Vector4(); - const q = new Vector4(); - return function updateVirtualCamera(camera) { - virtualCamera.matrixWorld.copy(camera.matrixWorld); - virtualCamera.matrixWorldInverse.copy(virtualCamera.matrixWorld).invert(); - virtualCamera.projectionMatrix.copy(camera.projectionMatrix); - virtualCamera.far = camera.far; // used in WebGLBackground - // The following code creates an oblique view frustum for clipping. - // see: Lengyel, Eric. “Oblique View Frustum Depth Projection and Clipping”. - // Journal of Game Development, Vol. 1, No. 2 (2005), Charles River Media, pp. 5–16 - - clipPlane.copy(refractorPlane); - clipPlane.applyMatrix4(virtualCamera.matrixWorldInverse); - clipVector.set(clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant); // calculate the clip-space corner point opposite the clipping plane and - // transform it into camera space by multiplying it by the inverse of the projection matrix - - const projectionMatrix = virtualCamera.projectionMatrix; - q.x = (Math.sign(clipVector.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; - q.y = (Math.sign(clipVector.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; - q.z = -1.0; - q.w = (1.0 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; // calculate the scaled plane vector - - clipVector.multiplyScalar(2.0 / clipVector.dot(q)); // replacing the third row of the projection matrix - - projectionMatrix.elements[2] = clipVector.x; - projectionMatrix.elements[6] = clipVector.y; - projectionMatrix.elements[10] = clipVector.z + 1.0 - clipBias; - projectionMatrix.elements[14] = clipVector.w; - }; - }(); // This will update the texture matrix that is used for projective texture mapping in the shader. - // see: http://developer.download.nvidia.com/assets/gamedev/docs/projective_texture_mapping.pdf - - - function updateTextureMatrix(camera) { - // this matrix does range mapping to [ 0, 1 ] - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); // we use "Object Linear Texgen", so we need to multiply the texture matrix T - // (matrix above) with the projection and view matrix of the virtual camera - // and the model matrix of the refractor - - textureMatrix.multiply(camera.projectionMatrix); - textureMatrix.multiply(camera.matrixWorldInverse); - textureMatrix.multiply(scope.matrixWorld); - } // - - - function render(renderer, scene, camera) { - scope.visible = false; - const currentRenderTarget = renderer.getRenderTarget(); - const currentXrEnabled = renderer.xr.enabled; - const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; - renderer.xr.enabled = false; // avoid camera modification - - renderer.shadowMap.autoUpdate = false; // avoid re-computing shadows - - renderer.setRenderTarget(renderTarget); - if (renderer.autoClear === false) renderer.clear(); - renderer.render(scene, virtualCamera); - renderer.xr.enabled = currentXrEnabled; - renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; - renderer.setRenderTarget(currentRenderTarget); // restore viewport - - const viewport = camera.viewport; - - if (viewport !== undefined) { - renderer.state.viewport(viewport); - } - - scope.visible = true; - } // - - - this.onBeforeRender = function (renderer, scene, camera) { - // Render - renderTarget.texture.encoding = renderer.outputEncoding; // ensure refractors are rendered only once per frame - - if (camera.userData.refractor === true) return; // avoid rendering when the refractor is viewed from behind - - if (!visible(camera) === true) return; // update - - updateRefractorPlane(); - updateTextureMatrix(camera); - updateVirtualCamera(camera); - render(renderer, scene, camera); - }; - - this.getRenderTarget = function () { - return renderTarget; - }; - - this.dispose = function () { - renderTarget.dispose(); - scope.material.dispose(); - }; - } - -} - -Refractor.prototype.isRefractor = true; -Refractor.RefractorShader = { - uniforms: { - color: { - value: null - }, - tDiffuse: { - value: null - }, - textureMatrix: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - - uniform mat4 textureMatrix; - - varying vec4 vUv; - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - - uniform vec3 color; - uniform sampler2D tDiffuse; - - varying vec4 vUv; - - float blendOverlay( float base, float blend ) { - - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - - } - - vec3 blendOverlay( vec3 base, vec3 blend ) { - - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - - } - - void main() { - - vec4 base = texture2DProj( tDiffuse, vUv ); - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - - }` -}; - -/** - * A shadow Mesh that follows a shadow-casting Mesh in the scene, but is confined to a single plane. - */ - -const _shadowMatrix = new Matrix4(); - -class ShadowMesh extends Mesh { - constructor(mesh) { - const shadowMaterial = new MeshBasicMaterial({ - color: 0x000000, - transparent: true, - opacity: 0.6, - depthWrite: false - }); - super(mesh.geometry, shadowMaterial); - this.meshMatrix = mesh.matrixWorld; - this.frustumCulled = false; - this.matrixAutoUpdate = false; - } - - update(plane, lightPosition4D) { - // based on https://www.opengl.org/archives/resources/features/StencilTalk/tsld021.htm - const dot = plane.normal.x * lightPosition4D.x + plane.normal.y * lightPosition4D.y + plane.normal.z * lightPosition4D.z + -plane.constant * lightPosition4D.w; - const sme = _shadowMatrix.elements; - sme[0] = dot - lightPosition4D.x * plane.normal.x; - sme[4] = -lightPosition4D.x * plane.normal.y; - sme[8] = -lightPosition4D.x * plane.normal.z; - sme[12] = -lightPosition4D.x * -plane.constant; - sme[1] = -lightPosition4D.y * plane.normal.x; - sme[5] = dot - lightPosition4D.y * plane.normal.y; - sme[9] = -lightPosition4D.y * plane.normal.z; - sme[13] = -lightPosition4D.y * -plane.constant; - sme[2] = -lightPosition4D.z * plane.normal.x; - sme[6] = -lightPosition4D.z * plane.normal.y; - sme[10] = dot - lightPosition4D.z * plane.normal.z; - sme[14] = -lightPosition4D.z * -plane.constant; - sme[3] = -lightPosition4D.w * plane.normal.x; - sme[7] = -lightPosition4D.w * plane.normal.y; - sme[11] = -lightPosition4D.w * plane.normal.z; - sme[15] = dot - lightPosition4D.w * -plane.constant; - this.matrix.multiplyMatrices(_shadowMatrix, this.meshMatrix); - } - -} - -ShadowMesh.prototype.isShadowMesh = true; - -class Lensflare extends Mesh { - constructor() { - super(Lensflare.Geometry, new MeshBasicMaterial({ - opacity: 0, - transparent: true - })); - this.type = 'Lensflare'; - this.frustumCulled = false; - this.renderOrder = Infinity; // - - const positionScreen = new Vector3(); - const positionView = new Vector3(); // textures - - const tempMap = new DataTexture(new Uint8Array(16 * 16 * 3), 16, 16, RGBAFormat); - tempMap.minFilter = NearestFilter; - tempMap.magFilter = NearestFilter; - tempMap.wrapS = ClampToEdgeWrapping; - tempMap.wrapT = ClampToEdgeWrapping; - const occlusionMap = new DataTexture(new Uint8Array(16 * 16 * 3), 16, 16, RGBAFormat); - occlusionMap.minFilter = NearestFilter; - occlusionMap.magFilter = NearestFilter; - occlusionMap.wrapS = ClampToEdgeWrapping; - occlusionMap.wrapT = ClampToEdgeWrapping; // material - - const geometry = Lensflare.Geometry; - const material1a = new RawShaderMaterial({ - uniforms: { - scale: { - value: null - }, - screenPosition: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - attribute vec3 position; - - void main() { - - gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - - precision highp float; - - void main() { - - gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 ); - - }`, - depthTest: true, - depthWrite: false, - transparent: false - }); - const material1b = new RawShaderMaterial({ - uniforms: { - map: { - value: tempMap - }, - scale: { - value: null - }, - screenPosition: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - attribute vec3 position; - attribute vec2 uv; - - varying vec2 vUV; - - void main() { - - vUV = uv; - - gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - - precision highp float; - - uniform sampler2D map; - - varying vec2 vUV; - - void main() { - - gl_FragColor = texture2D( map, vUV ); - - }`, - depthTest: false, - depthWrite: false, - transparent: false - }); // the following object is used for occlusionMap generation - - const mesh1 = new Mesh(geometry, material1a); // - - const elements = []; - const shader = LensflareElement.Shader; - const material2 = new RawShaderMaterial({ - uniforms: { - map: { - value: null - }, - occlusionMap: { - value: occlusionMap - }, - color: { - value: new Color(0xffffff) - }, - scale: { - value: new Vector2() - }, - screenPosition: { - value: new Vector3() - } - }, - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - blending: AdditiveBlending, - transparent: true, - depthWrite: false - }); - const mesh2 = new Mesh(geometry, material2); - - this.addElement = function (element) { - elements.push(element); - }; // - - - const scale = new Vector2(); - const screenPositionPixels = new Vector2(); - const validArea = new Box2(); - const viewport = new Vector4(); - - this.onBeforeRender = function (renderer, scene, camera) { - renderer.getCurrentViewport(viewport); - const invAspect = viewport.w / viewport.z; - const halfViewportWidth = viewport.z / 2.0; - const halfViewportHeight = viewport.w / 2.0; - let size = 16 / viewport.w; - scale.set(size * invAspect, size); - validArea.min.set(viewport.x, viewport.y); - validArea.max.set(viewport.x + (viewport.z - 16), viewport.y + (viewport.w - 16)); // calculate position in screen space - - positionView.setFromMatrixPosition(this.matrixWorld); - positionView.applyMatrix4(camera.matrixWorldInverse); - if (positionView.z > 0) return; // lensflare is behind the camera - - positionScreen.copy(positionView).applyMatrix4(camera.projectionMatrix); // horizontal and vertical coordinate of the lower left corner of the pixels to copy - - screenPositionPixels.x = viewport.x + positionScreen.x * halfViewportWidth + halfViewportWidth - 8; - screenPositionPixels.y = viewport.y + positionScreen.y * halfViewportHeight + halfViewportHeight - 8; // screen cull - - if (validArea.containsPoint(screenPositionPixels)) { - // save current RGB to temp texture - renderer.copyFramebufferToTexture(screenPositionPixels, tempMap); // render pink quad - - let uniforms = material1a.uniforms; - uniforms['scale'].value = scale; - uniforms['screenPosition'].value = positionScreen; - renderer.renderBufferDirect(camera, null, geometry, material1a, mesh1, null); // copy result to occlusionMap - - renderer.copyFramebufferToTexture(screenPositionPixels, occlusionMap); // restore graphics - - uniforms = material1b.uniforms; - uniforms['scale'].value = scale; - uniforms['screenPosition'].value = positionScreen; - renderer.renderBufferDirect(camera, null, geometry, material1b, mesh1, null); // render elements - - const vecX = -positionScreen.x * 2; - const vecY = -positionScreen.y * 2; - - for (let i = 0, l = elements.length; i < l; i++) { - const element = elements[i]; - const uniforms = material2.uniforms; - uniforms['color'].value.copy(element.color); - uniforms['map'].value = element.texture; - uniforms['screenPosition'].value.x = positionScreen.x + vecX * element.distance; - uniforms['screenPosition'].value.y = positionScreen.y + vecY * element.distance; - size = element.size / viewport.w; - const invAspect = viewport.w / viewport.z; - uniforms['scale'].value.set(size * invAspect, size); - material2.uniformsNeedUpdate = true; - renderer.renderBufferDirect(camera, null, geometry, material2, mesh2, null); - } - } - }; - - this.dispose = function () { - material1a.dispose(); - material1b.dispose(); - material2.dispose(); - tempMap.dispose(); - occlusionMap.dispose(); - - for (let i = 0, l = elements.length; i < l; i++) { - elements[i].texture.dispose(); - } - }; - } - -} - -Lensflare.prototype.isLensflare = true; // - -class LensflareElement { - constructor(texture, size = 1, distance = 0, color = new Color(0xffffff)) { - this.texture = texture; - this.size = size; - this.distance = distance; - this.color = color; - } - -} - -LensflareElement.Shader = { - uniforms: { - map: { - value: null - }, - occlusionMap: { - value: null - }, - color: { - value: null - }, - scale: { - value: null - }, - screenPosition: { - value: null - } - }, - vertexShader: - /* glsl */ - ` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - uniform sampler2D occlusionMap; - - attribute vec3 position; - attribute vec2 uv; - - varying vec2 vUV; - varying float vVisibility; - - void main() { - - vUV = uv; - - vec2 pos = position.xy; - - vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ); - visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) ); - visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) ); - visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ); - visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) ); - visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ); - visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) ); - visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ); - visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) ); - - vVisibility = visibility.r / 9.0; - vVisibility *= 1.0 - visibility.g / 9.0; - vVisibility *= visibility.b / 9.0; - - gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - - precision highp float; - - uniform sampler2D map; - uniform vec3 color; - - varying vec2 vUV; - varying float vVisibility; - - void main() { - - vec4 texture = texture2D( map, vUV ); - texture.a *= vVisibility; - gl_FragColor = texture; - gl_FragColor.rgb *= color; - - }` -}; - -Lensflare.Geometry = function () { - const geometry = new BufferGeometry(); - const float32Array = new Float32Array([-1, -1, 0, 0, 0, 1, -1, 0, 1, 0, 1, 1, 0, 1, 1, -1, 1, 0, 0, 1]); - const interleavedBuffer = new InterleavedBuffer(float32Array, 5); - geometry.setIndex([0, 1, 2, 0, 2, 3]); - geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); - geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); - return geometry; -}(); - -/** - * Work based on : - * https://github.com/Slayvin: Flat mirror for three.js - * https://home.adelphi.edu/~stemkoski/ : An implementation of water shader based on the flat mirror - * http://29a.ch/ && http://29a.ch/slides/2012/webglwater/ : Water shader explanations in WebGL - */ - -class Water$1 extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - const scope = this; - const textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512; - const textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512; - const clipBias = options.clipBias !== undefined ? options.clipBias : 0.0; - const alpha = options.alpha !== undefined ? options.alpha : 1.0; - const time = options.time !== undefined ? options.time : 0.0; - const normalSampler = options.waterNormals !== undefined ? options.waterNormals : null; - const sunDirection = options.sunDirection !== undefined ? options.sunDirection : new Vector3(0.70707, 0.70707, 0.0); - const sunColor = new Color(options.sunColor !== undefined ? options.sunColor : 0xffffff); - const waterColor = new Color(options.waterColor !== undefined ? options.waterColor : 0x7f7f7f); - const eye = options.eye !== undefined ? options.eye : new Vector3(0, 0, 0); - const distortionScale = options.distortionScale !== undefined ? options.distortionScale : 20.0; - const side = options.side !== undefined ? options.side : FrontSide; - const fog = options.fog !== undefined ? options.fog : false; // - - const mirrorPlane = new Plane(); - const normal = new Vector3(); - const mirrorWorldPosition = new Vector3(); - const cameraWorldPosition = new Vector3(); - const rotationMatrix = new Matrix4(); - const lookAtPosition = new Vector3(0, 0, -1); - const clipPlane = new Vector4(); - const view = new Vector3(); - const target = new Vector3(); - const q = new Vector4(); - const textureMatrix = new Matrix4(); - const mirrorCamera = new PerspectiveCamera(); - const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight); - const mirrorShader = { - uniforms: UniformsUtils.merge([UniformsLib['fog'], UniformsLib['lights'], { - normalSampler: { - value: null - }, - mirrorSampler: { - value: null - }, - alpha: { - value: 1.0 - }, - time: { - value: 0.0 - }, - size: { - value: 1.0 - }, - distortionScale: { - value: 20.0 - }, - textureMatrix: { - value: new Matrix4() - }, - sunColor: { - value: new Color(0x7f7f7f) - }, - sunDirection: { - value: new Vector3(0.70707, 0.70707, 0) - }, - eye: { - value: new Vector3() - }, - waterColor: { - value: new Color(0x555555) - } - }]), - vertexShader: - /* glsl */ - ` - uniform mat4 textureMatrix; - uniform float time; - - varying vec4 mirrorCoord; - varying vec4 worldPosition; - - #include - #include - #include - #include - - void main() { - mirrorCoord = modelMatrix * vec4( position, 1.0 ); - worldPosition = mirrorCoord.xyzw; - mirrorCoord = textureMatrix * mirrorCoord; - vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); - gl_Position = projectionMatrix * mvPosition; - - #include - #include - #include - #include - #include - }`, - fragmentShader: - /* glsl */ - ` - uniform sampler2D mirrorSampler; - uniform float alpha; - uniform float time; - uniform float size; - uniform float distortionScale; - uniform sampler2D normalSampler; - uniform vec3 sunColor; - uniform vec3 sunDirection; - uniform vec3 eye; - uniform vec3 waterColor; - - varying vec4 mirrorCoord; - varying vec4 worldPosition; - - vec4 getNoise( vec2 uv ) { - vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0); - vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 ); - vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 ); - vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 ); - vec4 noise = texture2D( normalSampler, uv0 ) + - texture2D( normalSampler, uv1 ) + - texture2D( normalSampler, uv2 ) + - texture2D( normalSampler, uv3 ); - return noise * 0.5 - 1.0; - } - - void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) { - vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) ); - float direction = max( 0.0, dot( eyeDirection, reflection ) ); - specularColor += pow( direction, shiny ) * sunColor * spec; - diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse; - } - - #include - #include - #include - #include - #include - #include - #include - #include - - void main() { - - #include - vec4 noise = getNoise( worldPosition.xz * size ); - vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) ); - - vec3 diffuseLight = vec3(0.0); - vec3 specularLight = vec3(0.0); - - vec3 worldToEye = eye-worldPosition.xyz; - vec3 eyeDirection = normalize( worldToEye ); - sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight ); - - float distance = length(worldToEye); - - vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale; - vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) ); - - float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 ); - float rf0 = 0.3; - float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 ); - vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor; - vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance); - vec3 outgoingLight = albedo; - gl_FragColor = vec4( outgoingLight, alpha ); - - #include - #include - }` - }; - const material = new ShaderMaterial({ - fragmentShader: mirrorShader.fragmentShader, - vertexShader: mirrorShader.vertexShader, - uniforms: UniformsUtils.clone(mirrorShader.uniforms), - lights: true, - side: side, - fog: fog - }); - material.uniforms['mirrorSampler'].value = renderTarget.texture; - material.uniforms['textureMatrix'].value = textureMatrix; - material.uniforms['alpha'].value = alpha; - material.uniforms['time'].value = time; - material.uniforms['normalSampler'].value = normalSampler; - material.uniforms['sunColor'].value = sunColor; - material.uniforms['waterColor'].value = waterColor; - material.uniforms['sunDirection'].value = sunDirection; - material.uniforms['distortionScale'].value = distortionScale; - material.uniforms['eye'].value = eye; - scope.material = material; - - scope.onBeforeRender = function (renderer, scene, camera) { - mirrorWorldPosition.setFromMatrixPosition(scope.matrixWorld); - cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); - rotationMatrix.extractRotation(scope.matrixWorld); - normal.set(0, 0, 1); - normal.applyMatrix4(rotationMatrix); - view.subVectors(mirrorWorldPosition, cameraWorldPosition); // Avoid rendering when mirror is facing away - - if (view.dot(normal) > 0) return; - view.reflect(normal).negate(); - view.add(mirrorWorldPosition); - rotationMatrix.extractRotation(camera.matrixWorld); - lookAtPosition.set(0, 0, -1); - lookAtPosition.applyMatrix4(rotationMatrix); - lookAtPosition.add(cameraWorldPosition); - target.subVectors(mirrorWorldPosition, lookAtPosition); - target.reflect(normal).negate(); - target.add(mirrorWorldPosition); - mirrorCamera.position.copy(view); - mirrorCamera.up.set(0, 1, 0); - mirrorCamera.up.applyMatrix4(rotationMatrix); - mirrorCamera.up.reflect(normal); - mirrorCamera.lookAt(target); - mirrorCamera.far = camera.far; // Used in WebGLBackground - - mirrorCamera.updateMatrixWorld(); - mirrorCamera.projectionMatrix.copy(camera.projectionMatrix); // Update the texture matrix - - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); - textureMatrix.multiply(mirrorCamera.projectionMatrix); - textureMatrix.multiply(mirrorCamera.matrixWorldInverse); // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html - // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf - - mirrorPlane.setFromNormalAndCoplanarPoint(normal, mirrorWorldPosition); - mirrorPlane.applyMatrix4(mirrorCamera.matrixWorldInverse); - clipPlane.set(mirrorPlane.normal.x, mirrorPlane.normal.y, mirrorPlane.normal.z, mirrorPlane.constant); - const projectionMatrix = mirrorCamera.projectionMatrix; - q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; - q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; - q.z = -1.0; - q.w = (1.0 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; // Calculate the scaled plane vector - - clipPlane.multiplyScalar(2.0 / clipPlane.dot(q)); // Replacing the third row of the projection matrix - - projectionMatrix.elements[2] = clipPlane.x; - projectionMatrix.elements[6] = clipPlane.y; - projectionMatrix.elements[10] = clipPlane.z + 1.0 - clipBias; - projectionMatrix.elements[14] = clipPlane.w; - eye.setFromMatrixPosition(camera.matrixWorld); // Render - - const currentRenderTarget = renderer.getRenderTarget(); - const currentXrEnabled = renderer.xr.enabled; - const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; - scope.visible = false; - renderer.xr.enabled = false; // Avoid camera modification and recursion - - renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows - - renderer.setRenderTarget(renderTarget); - renderer.state.buffers.depth.setMask(true); // make sure the depth buffer is writable so it can be properly cleared, see #18897 - - if (renderer.autoClear === false) renderer.clear(); - renderer.render(scene, mirrorCamera); - scope.visible = true; - renderer.xr.enabled = currentXrEnabled; - renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; - renderer.setRenderTarget(currentRenderTarget); // Restore viewport - - const viewport = camera.viewport; - - if (viewport !== undefined) { - renderer.state.viewport(viewport); - } - }; - } - -} - -Water$1.prototype.isWater = true; - -/** - * Port of http://webglsamples.org/blob/blob.html - */ - -class MarchingCubes extends Mesh { - constructor(resolution, material, enableUvs = false, enableColors = false, maxPolyCount = 10000) { - const geometry = new BufferGeometry(); - super(geometry, material); - const scope = this; // temp buffers used in polygonize - - const vlist = new Float32Array(12 * 3); - const nlist = new Float32Array(12 * 3); - const clist = new Float32Array(12 * 3); - this.enableUvs = enableUvs; - this.enableColors = enableColors; // functions have to be object properties - // prototype functions kill performance - // (tested and it was 4x slower !!!) - - this.init = function (resolution) { - this.resolution = resolution; // parameters - - this.isolation = 80.0; // size of field, 32 is pushing it in Javascript :) - - this.size = resolution; - this.size2 = this.size * this.size; - this.size3 = this.size2 * this.size; - this.halfsize = this.size / 2.0; // deltas - - this.delta = 2.0 / this.size; - this.yd = this.size; - this.zd = this.size2; - this.field = new Float32Array(this.size3); - this.normal_cache = new Float32Array(this.size3 * 3); - this.palette = new Float32Array(this.size3 * 3); // - - this.count = 0; - const maxVertexCount = maxPolyCount * 3; - this.positionArray = new Float32Array(maxVertexCount * 3); - const positionAttribute = new BufferAttribute(this.positionArray, 3); - positionAttribute.setUsage(DynamicDrawUsage); - geometry.setAttribute('position', positionAttribute); - this.normalArray = new Float32Array(maxVertexCount * 3); - const normalAttribute = new BufferAttribute(this.normalArray, 3); - normalAttribute.setUsage(DynamicDrawUsage); - geometry.setAttribute('normal', normalAttribute); - - if (this.enableUvs) { - this.uvArray = new Float32Array(maxVertexCount * 2); - const uvAttribute = new BufferAttribute(this.uvArray, 2); - uvAttribute.setUsage(DynamicDrawUsage); - geometry.setAttribute('uv', uvAttribute); - } - - if (this.enableColors) { - this.colorArray = new Float32Array(maxVertexCount * 3); - const colorAttribute = new BufferAttribute(this.colorArray, 3); - colorAttribute.setUsage(DynamicDrawUsage); - geometry.setAttribute('color', colorAttribute); - } - }; /////////////////////// - // Polygonization - /////////////////////// - - - function lerp(a, b, t) { - return a + (b - a) * t; - } - - function VIntX(q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2) { - const mu = (isol - valp1) / (valp2 - valp1), - nc = scope.normal_cache; - vlist[offset + 0] = x + mu * scope.delta; - vlist[offset + 1] = y; - vlist[offset + 2] = z; - nlist[offset + 0] = lerp(nc[q + 0], nc[q + 3], mu); - nlist[offset + 1] = lerp(nc[q + 1], nc[q + 4], mu); - nlist[offset + 2] = lerp(nc[q + 2], nc[q + 5], mu); - clist[offset + 0] = lerp(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); - clist[offset + 1] = lerp(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); - clist[offset + 2] = lerp(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu); - } - - function VIntY(q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2) { - const mu = (isol - valp1) / (valp2 - valp1), - nc = scope.normal_cache; - vlist[offset + 0] = x; - vlist[offset + 1] = y + mu * scope.delta; - vlist[offset + 2] = z; - const q2 = q + scope.yd * 3; - nlist[offset + 0] = lerp(nc[q + 0], nc[q2 + 0], mu); - nlist[offset + 1] = lerp(nc[q + 1], nc[q2 + 1], mu); - nlist[offset + 2] = lerp(nc[q + 2], nc[q2 + 2], mu); - clist[offset + 0] = lerp(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); - clist[offset + 1] = lerp(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); - clist[offset + 2] = lerp(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu); - } - - function VIntZ(q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2) { - const mu = (isol - valp1) / (valp2 - valp1), - nc = scope.normal_cache; - vlist[offset + 0] = x; - vlist[offset + 1] = y; - vlist[offset + 2] = z + mu * scope.delta; - const q2 = q + scope.zd * 3; - nlist[offset + 0] = lerp(nc[q + 0], nc[q2 + 0], mu); - nlist[offset + 1] = lerp(nc[q + 1], nc[q2 + 1], mu); - nlist[offset + 2] = lerp(nc[q + 2], nc[q2 + 2], mu); - clist[offset + 0] = lerp(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); - clist[offset + 1] = lerp(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); - clist[offset + 2] = lerp(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu); - } - - function compNorm(q) { - const q3 = q * 3; - - if (scope.normal_cache[q3] === 0.0) { - scope.normal_cache[q3 + 0] = scope.field[q - 1] - scope.field[q + 1]; - scope.normal_cache[q3 + 1] = scope.field[q - scope.yd] - scope.field[q + scope.yd]; - scope.normal_cache[q3 + 2] = scope.field[q - scope.zd] - scope.field[q + scope.zd]; - } - } // Returns total number of triangles. Fills triangles. - // (this is where most of time is spent - it's inner work of O(n3) loop ) - - - function polygonize(fx, fy, fz, q, isol) { - // cache indices - const q1 = q + 1, - qy = q + scope.yd, - qz = q + scope.zd, - q1y = q1 + scope.yd, - q1z = q1 + scope.zd, - qyz = q + scope.yd + scope.zd, - q1yz = q1 + scope.yd + scope.zd; - let cubeindex = 0; - const field0 = scope.field[q], - field1 = scope.field[q1], - field2 = scope.field[qy], - field3 = scope.field[q1y], - field4 = scope.field[qz], - field5 = scope.field[q1z], - field6 = scope.field[qyz], - field7 = scope.field[q1yz]; - if (field0 < isol) cubeindex |= 1; - if (field1 < isol) cubeindex |= 2; - if (field2 < isol) cubeindex |= 8; - if (field3 < isol) cubeindex |= 4; - if (field4 < isol) cubeindex |= 16; - if (field5 < isol) cubeindex |= 32; - if (field6 < isol) cubeindex |= 128; - if (field7 < isol) cubeindex |= 64; // if cube is entirely in/out of the surface - bail, nothing to draw - - const bits = edgeTable[cubeindex]; - if (bits === 0) return 0; - const d = scope.delta, - fx2 = fx + d, - fy2 = fy + d, - fz2 = fz + d; // top of the cube - - if (bits & 1) { - compNorm(q); - compNorm(q1); - VIntX(q * 3, 0, isol, fx, fy, fz, field0, field1, q, q1); - } - - if (bits & 2) { - compNorm(q1); - compNorm(q1y); - VIntY(q1 * 3, 3, isol, fx2, fy, fz, field1, field3, q1, q1y); - } - - if (bits & 4) { - compNorm(qy); - compNorm(q1y); - VIntX(qy * 3, 6, isol, fx, fy2, fz, field2, field3, qy, q1y); - } - - if (bits & 8) { - compNorm(q); - compNorm(qy); - VIntY(q * 3, 9, isol, fx, fy, fz, field0, field2, q, qy); - } // bottom of the cube - - - if (bits & 16) { - compNorm(qz); - compNorm(q1z); - VIntX(qz * 3, 12, isol, fx, fy, fz2, field4, field5, qz, q1z); - } - - if (bits & 32) { - compNorm(q1z); - compNorm(q1yz); - VIntY(q1z * 3, 15, isol, fx2, fy, fz2, field5, field7, q1z, q1yz); - } - - if (bits & 64) { - compNorm(qyz); - compNorm(q1yz); - VIntX(qyz * 3, 18, isol, fx, fy2, fz2, field6, field7, qyz, q1yz); - } - - if (bits & 128) { - compNorm(qz); - compNorm(qyz); - VIntY(qz * 3, 21, isol, fx, fy, fz2, field4, field6, qz, qyz); - } // vertical lines of the cube - - - if (bits & 256) { - compNorm(q); - compNorm(qz); - VIntZ(q * 3, 24, isol, fx, fy, fz, field0, field4, q, qz); - } - - if (bits & 512) { - compNorm(q1); - compNorm(q1z); - VIntZ(q1 * 3, 27, isol, fx2, fy, fz, field1, field5, q1, q1z); - } - - if (bits & 1024) { - compNorm(q1y); - compNorm(q1yz); - VIntZ(q1y * 3, 30, isol, fx2, fy2, fz, field3, field7, q1y, q1yz); - } - - if (bits & 2048) { - compNorm(qy); - compNorm(qyz); - VIntZ(qy * 3, 33, isol, fx, fy2, fz, field2, field6, qy, qyz); - } - - cubeindex <<= 4; // re-purpose cubeindex into an offset into triTable - - let o1, - o2, - o3, - numtris = 0, - i = 0; // here is where triangles are created - - while (triTable[cubeindex + i] != -1) { - o1 = cubeindex + i; - o2 = o1 + 1; - o3 = o1 + 2; - posnormtriv(vlist, nlist, clist, 3 * triTable[o1], 3 * triTable[o2], 3 * triTable[o3]); - i += 3; - numtris++; - } - - return numtris; - } - - function posnormtriv(pos, norm, colors, o1, o2, o3) { - const c = scope.count * 3; // positions - - scope.positionArray[c + 0] = pos[o1]; - scope.positionArray[c + 1] = pos[o1 + 1]; - scope.positionArray[c + 2] = pos[o1 + 2]; - scope.positionArray[c + 3] = pos[o2]; - scope.positionArray[c + 4] = pos[o2 + 1]; - scope.positionArray[c + 5] = pos[o2 + 2]; - scope.positionArray[c + 6] = pos[o3]; - scope.positionArray[c + 7] = pos[o3 + 1]; - scope.positionArray[c + 8] = pos[o3 + 2]; // normals - - if (scope.material.flatShading === true) { - const nx = (norm[o1 + 0] + norm[o2 + 0] + norm[o3 + 0]) / 3; - const ny = (norm[o1 + 1] + norm[o2 + 1] + norm[o3 + 1]) / 3; - const nz = (norm[o1 + 2] + norm[o2 + 2] + norm[o3 + 2]) / 3; - scope.normalArray[c + 0] = nx; - scope.normalArray[c + 1] = ny; - scope.normalArray[c + 2] = nz; - scope.normalArray[c + 3] = nx; - scope.normalArray[c + 4] = ny; - scope.normalArray[c + 5] = nz; - scope.normalArray[c + 6] = nx; - scope.normalArray[c + 7] = ny; - scope.normalArray[c + 8] = nz; - } else { - scope.normalArray[c + 0] = norm[o1 + 0]; - scope.normalArray[c + 1] = norm[o1 + 1]; - scope.normalArray[c + 2] = norm[o1 + 2]; - scope.normalArray[c + 3] = norm[o2 + 0]; - scope.normalArray[c + 4] = norm[o2 + 1]; - scope.normalArray[c + 5] = norm[o2 + 2]; - scope.normalArray[c + 6] = norm[o3 + 0]; - scope.normalArray[c + 7] = norm[o3 + 1]; - scope.normalArray[c + 8] = norm[o3 + 2]; - } // uvs - - - if (scope.enableUvs) { - const d = scope.count * 2; - scope.uvArray[d + 0] = pos[o1 + 0]; - scope.uvArray[d + 1] = pos[o1 + 2]; - scope.uvArray[d + 2] = pos[o2 + 0]; - scope.uvArray[d + 3] = pos[o2 + 2]; - scope.uvArray[d + 4] = pos[o3 + 0]; - scope.uvArray[d + 5] = pos[o3 + 2]; - } // colors - - - if (scope.enableColors) { - scope.colorArray[c + 0] = colors[o1 + 0]; - scope.colorArray[c + 1] = colors[o1 + 1]; - scope.colorArray[c + 2] = colors[o1 + 2]; - scope.colorArray[c + 3] = colors[o2 + 0]; - scope.colorArray[c + 4] = colors[o2 + 1]; - scope.colorArray[c + 5] = colors[o2 + 2]; - scope.colorArray[c + 6] = colors[o3 + 0]; - scope.colorArray[c + 7] = colors[o3 + 1]; - scope.colorArray[c + 8] = colors[o3 + 2]; - } - - scope.count += 3; - } ///////////////////////////////////// - // Metaballs - ///////////////////////////////////// - // Adds a reciprocal ball (nice and blobby) that, to be fast, fades to zero after - // a fixed distance, determined by strength and subtract. - - - this.addBall = function (ballx, bally, ballz, strength, subtract, colors) { - const sign = Math.sign(strength); - strength = Math.abs(strength); - const userDefineColor = !(colors === undefined || colors === null); - let ballColor = new Color(ballx, bally, ballz); - - if (userDefineColor) { - try { - ballColor = colors instanceof Color ? colors : Array.isArray(colors) ? new Color(Math.min(Math.abs(colors[0]), 1), Math.min(Math.abs(colors[1]), 1), Math.min(Math.abs(colors[2]), 1)) : new Color(colors); - } catch (err) { - ballColor = new Color(ballx, bally, ballz); - } - } // Let's solve the equation to find the radius: - // 1.0 / (0.000001 + radius^2) * strength - subtract = 0 - // strength / (radius^2) = subtract - // strength = subtract * radius^2 - // radius^2 = strength / subtract - // radius = sqrt(strength / subtract) - - - const radius = this.size * Math.sqrt(strength / subtract), - zs = ballz * this.size, - ys = bally * this.size, - xs = ballx * this.size; - let min_z = Math.floor(zs - radius); - if (min_z < 1) min_z = 1; - let max_z = Math.floor(zs + radius); - if (max_z > this.size - 1) max_z = this.size - 1; - let min_y = Math.floor(ys - radius); - if (min_y < 1) min_y = 1; - let max_y = Math.floor(ys + radius); - if (max_y > this.size - 1) max_y = this.size - 1; - let min_x = Math.floor(xs - radius); - if (min_x < 1) min_x = 1; - let max_x = Math.floor(xs + radius); - if (max_x > this.size - 1) max_x = this.size - 1; // Don't polygonize in the outer layer because normals aren't - // well-defined there. - - let x, y, z, y_offset, z_offset, fx, fy, fz, fz2, fy2, val; - - for (z = min_z; z < max_z; z++) { - z_offset = this.size2 * z; - fz = z / this.size - ballz; - fz2 = fz * fz; - - for (y = min_y; y < max_y; y++) { - y_offset = z_offset + this.size * y; - fy = y / this.size - bally; - fy2 = fy * fy; - - for (x = min_x; x < max_x; x++) { - fx = x / this.size - ballx; - val = strength / (0.000001 + fx * fx + fy2 + fz2) - subtract; - - if (val > 0.0) { - this.field[y_offset + x] += val * sign; // optimization - // http://www.geisswerks.com/ryan/BLOBS/blobs.html - - const ratio = Math.sqrt((x - xs) * (x - xs) + (y - ys) * (y - ys) + (z - zs) * (z - zs)) / radius; - const contrib = 1 - ratio * ratio * ratio * (ratio * (ratio * 6 - 15) + 10); - this.palette[(y_offset + x) * 3 + 0] += ballColor.r * contrib; - this.palette[(y_offset + x) * 3 + 1] += ballColor.g * contrib; - this.palette[(y_offset + x) * 3 + 2] += ballColor.b * contrib; - } - } - } - } - }; - - this.addPlaneX = function (strength, subtract) { - // cache attribute lookups - const size = this.size, - yd = this.yd, - zd = this.zd, - field = this.field; - let x, - y, - z, - xx, - val, - xdiv, - cxy, - dist = size * Math.sqrt(strength / subtract); - if (dist > size) dist = size; - - for (x = 0; x < dist; x++) { - xdiv = x / size; - xx = xdiv * xdiv; - val = strength / (0.0001 + xx) - subtract; - - if (val > 0.0) { - for (y = 0; y < size; y++) { - cxy = x + y * yd; - - for (z = 0; z < size; z++) { - field[zd * z + cxy] += val; - } - } - } - } - }; - - this.addPlaneY = function (strength, subtract) { - // cache attribute lookups - const size = this.size, - yd = this.yd, - zd = this.zd, - field = this.field; - let x, - y, - z, - yy, - val, - ydiv, - cy, - cxy, - dist = size * Math.sqrt(strength / subtract); - if (dist > size) dist = size; - - for (y = 0; y < dist; y++) { - ydiv = y / size; - yy = ydiv * ydiv; - val = strength / (0.0001 + yy) - subtract; - - if (val > 0.0) { - cy = y * yd; - - for (x = 0; x < size; x++) { - cxy = cy + x; - - for (z = 0; z < size; z++) field[zd * z + cxy] += val; - } - } - } - }; - - this.addPlaneZ = function (strength, subtract) { - // cache attribute lookups - const size = this.size, - yd = this.yd, - zd = this.zd, - field = this.field; - let x, - y, - z, - zz, - val, - zdiv, - cz, - cyz, - dist = size * Math.sqrt(strength / subtract); - if (dist > size) dist = size; - - for (z = 0; z < dist; z++) { - zdiv = z / size; - zz = zdiv * zdiv; - val = strength / (0.0001 + zz) - subtract; - - if (val > 0.0) { - cz = zd * z; - - for (y = 0; y < size; y++) { - cyz = cz + y * yd; - - for (x = 0; x < size; x++) field[cyz + x] += val; - } - } - } - }; ///////////////////////////////////// - // Updates - ///////////////////////////////////// - - - this.setCell = function (x, y, z, value) { - const index = this.size2 * z + this.size * y + x; - this.field[index] = value; - }; - - this.getCell = function (x, y, z) { - const index = this.size2 * z + this.size * y + x; - return this.field[index]; - }; - - this.blur = function (intensity = 1) { - const field = this.field; - const fieldCopy = field.slice(); - const size = this.size; - const size2 = this.size2; - - for (let x = 0; x < size; x++) { - for (let y = 0; y < size; y++) { - for (let z = 0; z < size; z++) { - const index = size2 * z + size * y + x; - let val = fieldCopy[index]; - let count = 1; - - for (let x2 = -1; x2 <= 1; x2 += 2) { - const x3 = x2 + x; - if (x3 < 0 || x3 >= size) continue; - - for (let y2 = -1; y2 <= 1; y2 += 2) { - const y3 = y2 + y; - if (y3 < 0 || y3 >= size) continue; - - for (let z2 = -1; z2 <= 1; z2 += 2) { - const z3 = z2 + z; - if (z3 < 0 || z3 >= size) continue; - const index2 = size2 * z3 + size * y3 + x3; - const val2 = fieldCopy[index2]; - count++; - val += intensity * (val2 - val) / count; - } - } - } - - field[index] = val; - } - } - } - }; - - this.reset = function () { - // wipe the normal cache - for (let i = 0; i < this.size3; i++) { - this.normal_cache[i * 3] = 0.0; - this.field[i] = 0.0; - this.palette[i * 3] = this.palette[i * 3 + 1] = this.palette[i * 3 + 2] = 0.0; - } - }; - - this.onBeforeRender = function () { - this.count = 0; // Triangulate. Yeah, this is slow. - - const smin2 = this.size - 2; - - for (let z = 1; z < smin2; z++) { - const z_offset = this.size2 * z; - const fz = (z - this.halfsize) / this.halfsize; //+ 1 - - for (let y = 1; y < smin2; y++) { - const y_offset = z_offset + this.size * y; - const fy = (y - this.halfsize) / this.halfsize; //+ 1 - - for (let x = 1; x < smin2; x++) { - const fx = (x - this.halfsize) / this.halfsize; //+ 1 - - const q = y_offset + x; - polygonize(fx, fy, fz, q, this.isolation); - } - } - } // reset unneeded data - - - for (let i = this.count * 3; i < this.positionArray.length; i++) { - this.positionArray[i] = 0.0; - } // update geometry data - - - geometry.getAttribute('position').needsUpdate = true; - geometry.getAttribute('normal').needsUpdate = true; - if (this.enableUvs) geometry.getAttribute('uv').needsUpdate = true; - if (this.enableColors) geometry.getAttribute('color').needsUpdate = true; // safety check - - if (this.count / 3 > maxPolyCount) { - console.warn('MarchingCubes: Geometry buffers too small for rendering. Please create an instance with a higher poly count.'); - } - }; - - this.init(resolution); - } - -} - -MarchingCubes.prototype.isMarchingCubes = true; ///////////////////////////////////// -// Marching cubes lookup tables -///////////////////////////////////// -// These tables are straight from Paul Bourke's page: -// http://paulbourke.net/geometry/polygonise/ -// who in turn got them from Cory Gene Bloyd. -// prettier-ignore - -const edgeTable = new Int32Array([0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66, 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa, 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33, 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99, 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0]); // prettier-ignore - -const triTable = new Int32Array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1, 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1, 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1, 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1, 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1, 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1, 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1, 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1, 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1, 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1, 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1, 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1, 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1, 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1, 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1, 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1, 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1, 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1, 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1, 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1, 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1, 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1, 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1, 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1, 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1, 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1, 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1, 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1, 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1, 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1, 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1, 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1, 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1, 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1, 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1, 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1, 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1, 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1, 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1, 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1, 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1, 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1, 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1, 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1, 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1, 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1, 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1, 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1, 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1, 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1, 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1, 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1, 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1, 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1, 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1, 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1, 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1, 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1, 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1, 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1, 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1, 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1, 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1, 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1, 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1, 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1, 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1, 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1, 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1, 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1, 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1, 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1, 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1, 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1, 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1, 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1, 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1, 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1, 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1, 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1, 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1, 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1, 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1, 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1, 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1, 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1, 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1, 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1, 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1, 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1, 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1, 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1, 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1, 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1, 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1, 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1, 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1, 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1, 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1, 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1, 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1, 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1, 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1, 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1, 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1, 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1, 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1, 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1, 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1, 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1, 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1, 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1, 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1, 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1, 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1, 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1, 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1, 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1, 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1, 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1, 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1, 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1, 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1, 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1, 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1, 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1, 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1, 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1, 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1, 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1, 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1, 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1, 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1, 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1, 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1, 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1, 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1, 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1, 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1, 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1, 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1, 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1, 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1, 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1, 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1, 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1, 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1, 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]); - -// Ported from Stefan Gustavson's java implementation -// http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf -// Read Stefan's excellent paper for details on how this code works. -// -// Sean McCullough banksean@gmail.com -// -// Added 4D noise -class SimplexNoise { - // To remove the need for index wrapping, double the permutation table length - // A lookup table to traverse the simplex around a given point in 4D. - // Details can be found where this table is used, in the 4D noise method. - - /** - * You can pass in a random number generator object if you like. - * It is assumed to have a random() method. - */ - constructor(r = Math) { - _defineProperty$1(this, "grad3", [[1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1], [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1]]); - - _defineProperty$1(this, "grad4", [[0, 1, 1, 1], [0, 1, 1, -1], [0, 1, -1, 1], [0, 1, -1, -1], [0, -1, 1, 1], [0, -1, 1, -1], [0, -1, -1, 1], [0, -1, -1, -1], [1, 0, 1, 1], [1, 0, 1, -1], [1, 0, -1, 1], [1, 0, -1, -1], [-1, 0, 1, 1], [-1, 0, 1, -1], [-1, 0, -1, 1], [-1, 0, -1, -1], [1, 1, 0, 1], [1, 1, 0, -1], [1, -1, 0, 1], [1, -1, 0, -1], [-1, 1, 0, 1], [-1, 1, 0, -1], [-1, -1, 0, 1], [-1, -1, 0, -1], [1, 1, 1, 0], [1, 1, -1, 0], [1, -1, 1, 0], [1, -1, -1, 0], [-1, 1, 1, 0], [-1, 1, -1, 0], [-1, -1, 1, 0], [-1, -1, -1, 0]]); - - _defineProperty$1(this, "p", []); - - _defineProperty$1(this, "perm", []); - - _defineProperty$1(this, "simplex", [[0, 1, 2, 3], [0, 1, 3, 2], [0, 0, 0, 0], [0, 2, 3, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 3, 0], [0, 2, 1, 3], [0, 0, 0, 0], [0, 3, 1, 2], [0, 3, 2, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 3, 2, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 0, 3], [0, 0, 0, 0], [1, 3, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 3, 0, 1], [2, 3, 1, 0], [1, 0, 2, 3], [1, 0, 3, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 3, 1], [0, 0, 0, 0], [2, 1, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 1, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 1, 2], [3, 0, 2, 1], [0, 0, 0, 0], [3, 1, 2, 0], [2, 1, 0, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 1, 0, 2], [0, 0, 0, 0], [3, 2, 0, 1], [3, 2, 1, 0]]); - - _defineProperty$1(this, "dot", (g, x, y) => { - return g[0] * x + g[1] * y; - }); - - _defineProperty$1(this, "dot3", (g, x, y, z) => { - return g[0] * x + g[1] * y + g[2] * z; - }); - - _defineProperty$1(this, "dot4", (g, x, y, z, w) => { - return g[0] * x + g[1] * y + g[2] * z + g[3] * w; - }); - - _defineProperty$1(this, "noise", (xin, yin) => { - let n0; - let n1; - let n2; // Noise contributions from the three corners - // Skew the input space to determine which simplex cell we're in - - const F2 = 0.5 * (Math.sqrt(3.0) - 1.0); - const s = (xin + yin) * F2; // Hairy factor for 2D - - const i = Math.floor(xin + s); - const j = Math.floor(yin + s); - const G2 = (3.0 - Math.sqrt(3.0)) / 6.0; - const t = (i + j) * G2; - const X0 = i - t; // Unskew the cell origin back to (x,y) space - - const Y0 = j - t; - const x0 = xin - X0; // The x,y distances from the cell origin - - const y0 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. - // Determine which simplex we are in. - // upper triangle, YX order: (0,0)->(0,1)->(1,1) - - let i1 = 0; // Offsets for second (middle) corner of simplex in (i,j) coords - - let j1 = 1; - - if (x0 > y0) { - i1 = 1; - j1 = 0; - } // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and - // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where - // c = (3-sqrt(3))/6 - - - const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords - - const y1 = y0 - j1 + G2; - const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords - - const y2 = y0 - 1.0 + 2.0 * G2; // Work out the hashed gradient indices of the three simplex corners - - const ii = i & 255; - const jj = j & 255; - const gi0 = this.perm[ii + this.perm[jj]] % 12; - const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12; - const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12; // Calculate the contribution from the three corners - - let t0 = 0.5 - x0 * x0 - y0 * y0; - - if (t0 < 0) { - n0 = 0.0; - } else { - t0 *= t0; - n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient - } - - let t1 = 0.5 - x1 * x1 - y1 * y1; - - if (t1 < 0) { - n1 = 0.0; - } else { - t1 *= t1; - n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1); - } - - let t2 = 0.5 - x2 * x2 - y2 * y2; - - if (t2 < 0) { - n2 = 0.0; - } else { - t2 *= t2; - n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2); - } // Add contributions from each corner to get the final noise value. - // The result is scaled to return values in the interval [-1,1]. - - - return 70.0 * (n0 + n1 + n2); - }); - - _defineProperty$1(this, "noise3d", (xin, yin, zin) => { - // Noise contributions from the four corners - let n0; - let n1; - let n2; - let n3; // Skew the input space to determine which simplex cell we're in - - const F3 = 1.0 / 3.0; - const s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D - - const i = Math.floor(xin + s); - const j = Math.floor(yin + s); - const k = Math.floor(zin + s); - const G3 = 1.0 / 6.0; // Very nice and simple unskew factor, too - - const t = (i + j + k) * G3; - const X0 = i - t; // Unskew the cell origin back to (x,y,z) space - - const Y0 = j - t; - const Z0 = k - t; - const x0 = xin - X0; // The x,y,z distances from the cell origin - - const y0 = yin - Y0; - const z0 = zin - Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. - // Determine which simplex we are in. - - let i1; - let j1; - let k1; // Offsets for second corner of simplex in (i,j,k) coords - - let i2; - let j2; - let k2; // Offsets for third corner of simplex in (i,j,k) coords - - if (x0 >= y0) { - if (y0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; // X Y Z order - } else if (x0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 0; - k2 = 1; // X Z Y order - } else { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 1; - j2 = 0; - k2 = 1; - } // Z X Y order - - } else { - // x0 { - // For faster and easier lookups - const grad4 = this.grad4; - const simplex = this.simplex; - const perm = this.perm; // The skewing and unskewing factors are hairy again for the 4D case - - const F4 = (Math.sqrt(5.0) - 1.0) / 4.0; - const G4 = (5.0 - Math.sqrt(5.0)) / 20.0; - let n0; - let n1; - let n2; - let n3; - let n4; // Noise contributions from the five corners - // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in - - const s = (x + y + z + w) * F4; // Factor for 4D skewing - - const i = Math.floor(x + s); - const j = Math.floor(y + s); - const k = Math.floor(z + s); - const l = Math.floor(w + s); - const t = (i + j + k + l) * G4; // Factor for 4D unskewing - - const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space - - const Y0 = j - t; - const Z0 = k - t; - const W0 = l - t; - const x0 = x - X0; // The x,y,z,w distances from the cell origin - - const y0 = y - Y0; - const z0 = z - Z0; - const w0 = w - W0; // For the 4D case, the simplex is a 4D shape I won't even try to describe. - // To find out which of the 24 possible simplices we're in, we need to - // determine the magnitude ordering of x0, y0, z0 and w0. - // The method below is a good way of finding the ordering of x,y,z,w and - // then find the correct traversal order for the simplex we’re in. - // First, six pair-wise comparisons are performed between each possible pair - // of the four coordinates, and the results are used to add up binary bits - // for an integer index. - - const c1 = x0 > y0 ? 32 : 0; - const c2 = x0 > z0 ? 16 : 0; - const c3 = y0 > z0 ? 8 : 0; - const c4 = x0 > w0 ? 4 : 0; - const c5 = y0 > w0 ? 2 : 0; - const c6 = z0 > w0 ? 1 : 0; - const c = c1 + c2 + c3 + c4 + c5 + c6; // The integer offsets for the second simplex corner - - let i1; - let j1; - let k1; - let l1; // The integer offsets for the third simplex corner - - let i2; - let j2; - let k2; - let l2; // The integer offsets for the fourth simplex corner - - let i3; - let j3; - let k3; - let l3; // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. - // Many values of c will never occur, since e.g. x>y>z>w makes x= 3 ? 1 : 0; - j1 = simplex[c][1] >= 3 ? 1 : 0; - k1 = simplex[c][2] >= 3 ? 1 : 0; - l1 = simplex[c][3] >= 3 ? 1 : 0; // The number 2 in the "simplex" array is at the second largest coordinate. - - i2 = simplex[c][0] >= 2 ? 1 : 0; - j2 = simplex[c][1] >= 2 ? 1 : 0; - k2 = simplex[c][2] >= 2 ? 1 : 0; - l2 = simplex[c][3] >= 2 ? 1 : 0; // The number 1 in the "simplex" array is at the second smallest coordinate. - - i3 = simplex[c][0] >= 1 ? 1 : 0; - j3 = simplex[c][1] >= 1 ? 1 : 0; - k3 = simplex[c][2] >= 1 ? 1 : 0; - l3 = simplex[c][3] >= 1 ? 1 : 0; // The fifth corner has all coordinate offsets = 1, so no need to look that up. - - const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords - - const y1 = y0 - j1 + G4; - const z1 = z0 - k1 + G4; - const w1 = w0 - l1 + G4; - const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords - - const y2 = y0 - j2 + 2.0 * G4; - const z2 = z0 - k2 + 2.0 * G4; - const w2 = w0 - l2 + 2.0 * G4; - const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords - - const y3 = y0 - j3 + 3.0 * G4; - const z3 = z0 - k3 + 3.0 * G4; - const w3 = w0 - l3 + 3.0 * G4; - const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords - - const y4 = y0 - 1.0 + 4.0 * G4; - const z4 = z0 - 1.0 + 4.0 * G4; - const w4 = w0 - 1.0 + 4.0 * G4; // Work out the hashed gradient indices of the five simplex corners - - const ii = i & 255; - const jj = j & 255; - const kk = k & 255; - const ll = l & 255; - const gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; - const gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; - const gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; - const gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; - const gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; // Calculate the contribution from the five corners - - let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; - - if (t0 < 0) { - n0 = 0.0; - } else { - t0 *= t0; - n0 = t0 * t0 * this.dot4(grad4[gi0], x0, y0, z0, w0); - } - - let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; - - if (t1 < 0) { - n1 = 0.0; - } else { - t1 *= t1; - n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1); - } - - let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; - - if (t2 < 0) { - n2 = 0.0; - } else { - t2 *= t2; - n2 = t2 * t2 * this.dot4(grad4[gi2], x2, y2, z2, w2); - } - - let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; - - if (t3 < 0) { - n3 = 0.0; - } else { - t3 *= t3; - n3 = t3 * t3 * this.dot4(grad4[gi3], x3, y3, z3, w3); - } - - let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; - - if (t4 < 0) { - n4 = 0.0; - } else { - t4 *= t4; - n4 = t4 * t4 * this.dot4(grad4[gi4], x4, y4, z4, w4); - } // Sum up and scale the result to cover the range [-1,1] - - - return 27.0 * (n0 + n1 + n2 + n3 + n4); - }); - - for (let i = 0; i < 256; i++) { - this.p[i] = Math.floor(r.random() * 256); - } - - for (let i = 0; i < 512; i++) { - this.perm[i] = this.p[i & 255]; - } - } - -} - -/** - * @fileoverview LightningStrike object for creating lightning strikes and voltaic arcs. - * - * - * Usage - * - * var myRay = new LightningStrike( paramsObject ); - * var myRayMesh = new THREE.Mesh( myRay, myMaterial ); - * scene.add( myRayMesh ); - * ... - * myRay.update( currentTime ); - * - * The "currentTime" can vary its rate, go forwards, backwards or even jump, but it cannot be negative. - * - * You should normally leave the ray position to (0, 0, 0). You should control it by changing the sourceOffset and destOffset parameters. - * - * - * LightningStrike parameters - * - * The paramsObject can contain any of the following parameters. - * - * Legend: - * 'LightningStrike' (also called 'ray'): An independent voltaic arc with its ramifications and defined with a set of parameters. - * 'Subray': A ramification of the ray. It is not a LightningStrike object. - * 'Segment': A linear segment piece of a subray. - * 'Leaf segment': A ray segment which cannot be smaller. - * - * - * The following parameters can be changed any time and if they vary smoothly, the ray form will also change smoothly: - * - * @param {Vector3} sourceOffset The point where the ray starts. - * - * @param {Vector3} destOffset The point where the ray ends. - * - * @param {double} timeScale The rate at wich the ray form changes in time. Default: 1 - * - * @param {double} roughness From 0 to 1. The higher the value, the more wrinkled is the ray. Default: 0.9 - * - * @param {double} straightness From 0 to 1. The higher the value, the more straight will be a subray path. Default: 0.7 - * - * @param {Vector3} up0 Ray 'up' direction at the ray starting point. Must be normalized. It should be perpendicular to the ray forward direction but it doesn't matter much. - * - * @param {Vector3} up1 Like the up0 parameter but at the end of the ray. Must be normalized. - * - * @param {double} radius0 Radius of the main ray trunk at the start point. Default: 1 - * - * @param {double} radius1 Radius of the main ray trunk at the end point. Default: 1 - * - * @param {double} radius0Factor The radius0 of a subray is this factor times the radius0 of its parent subray. Default: 0.5 - * - * @param {double} radius1Factor The radius1 of a subray is this factor times the radius1 of its parent subray. Default: 0.2 - * - * @param {minRadius} Minimum value a subray radius0 or radius1 can get. Default: 0.1 - * - * - * The following parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly: - * - * @param {boolean} isEternal If true the ray never extinguishes. Otherwise its life is controlled by the 'birthTime' and 'deathTime' parameters. Default: true if any of those two parameters is undefined. - * - * @param {double} birthTime The time at which the ray starts its life and begins propagating. Only if isEternal is false. Default: None. - * - * @param {double} deathTime The time at which the ray ends vanishing and its life. Only if isEternal is false. Default: None. - * - * @param {double} propagationTimeFactor From 0 to 1. Lifetime factor at which the ray ends propagating and enters the steady phase. For example, 0.1 means it is propagating 1/10 of its lifetime. Default: 0.1 - * - * @param {double} vanishingTimeFactor From 0 to 1. Lifetime factor at which the ray ends the steady phase and begins vanishing. For example, 0.9 means it is vanishing 1/10 of its lifetime. Default: 0.9 - * - * @param {double} subrayPeriod Subrays cycle periodically. This is their time period. Default: 4 - * - * @param {double} subrayDutyCycle From 0 to 1. This is the fraction of time a subray is active. Default: 0.6 - * - * - * These parameters cannot change after lightning creation: - * - * @param {integer} maxIterations: Greater than 0. The number of ray's leaf segments is 2**maxIterations. Default: 9 - * - * @param {boolean} isStatic Set to true only for rays which won't change over time and are not attached to moving objects (Rare case). It is used to set the vertex buffers non-dynamic. You can omit calling update() for these rays. - * - * @param {integer} ramification Greater than 0. Maximum number of child subrays a subray can have. Default: 5 - * - * @param {integer} maxSubrayRecursion Greater than 0. Maximum level of recursion (subray descendant generations). Default: 3 - * - * @param {double} recursionProbability From 0 to 1. The lower the value, the less chance each new generation of subrays has to generate new subrays. Default: 0.6 - * - * @param {boolean} generateUVs If true, the ray geometry will have uv coordinates generated. u runs along the ray, and v across its perimeter. Default: false. - * - * @param {Object} randomGenerator Set here your random number generator which will seed the SimplexNoise and other decisions during ray tree creation. - * It can be used to generate repeatable rays. For that, set also the noiseSeed parameter, and each ray created with that generator and seed pair will be identical in time. - * The randomGenerator parameter should be an object with a random() function similar to Math.random, but seedable. - * It must have also a getSeed() method, which returns the current seed, and a setSeed( seed ) method, which accepts as seed a fractional number from 0 to 1, as well as any other number. - * The default value is an internal generator for some uses and Math.random for others (It is non-repeatable even if noiseSeed is supplied) - * - * @param {double} noiseSeed Seed used to make repeatable rays (see the randomGenerator) - * - * @param {function} onDecideSubrayCreation Set this to change the callback which decides subray creation. You can look at the default callback in the code (createDefaultSubrayCreationCallbacks)for more info. - * - * @param {function} onSubrayCreation This is another callback, more simple than the previous one. It can be used to adapt the form of subrays or other parameters once a subray has been created and initialized. It is used in the examples to adapt subrays to a sphere or to a plane. - * - * - */ - -class LightningStrike extends BufferGeometry { - constructor(rayParameters) { - super(); - this.type = 'LightningStrike'; // Set parameters, and set undefined parameters to default values - - rayParameters = rayParameters || {}; - this.init(LightningStrike.copyParameters(rayParameters, rayParameters)); // Creates and populates the mesh - - this.createMesh(); - } - - update(time) { - if (this.isStatic) return; - - if (this.rayParameters.isEternal || this.rayParameters.birthTime <= time && time <= this.rayParameters.deathTime) { - this.updateMesh(time); - - if (time < this.subrays[0].endPropagationTime) { - this.state = LightningStrike.RAY_PROPAGATING; - } else if (time > this.subrays[0].beginVanishingTime) { - this.state = LightningStrike.RAY_VANISHING; - } else { - this.state = LightningStrike.RAY_STEADY; - } - - this.visible = true; - } else { - this.visible = false; - - if (time < this.rayParameters.birthTime) { - this.state = LightningStrike.RAY_UNBORN; - } else { - this.state = LightningStrike.RAY_EXTINGUISHED; - } - } - } - - init(rayParameters) { - // Init all the state from the parameters - this.rayParameters = rayParameters; // These parameters cannot change after lightning creation: - - this.maxIterations = rayParameters.maxIterations !== undefined ? Math.floor(rayParameters.maxIterations) : 9; - rayParameters.maxIterations = this.maxIterations; - this.isStatic = rayParameters.isStatic !== undefined ? rayParameters.isStatic : false; - rayParameters.isStatic = this.isStatic; - this.ramification = rayParameters.ramification !== undefined ? Math.floor(rayParameters.ramification) : 5; - rayParameters.ramification = this.ramification; - this.maxSubrayRecursion = rayParameters.maxSubrayRecursion !== undefined ? Math.floor(rayParameters.maxSubrayRecursion) : 3; - rayParameters.maxSubrayRecursion = this.maxSubrayRecursion; - this.recursionProbability = rayParameters.recursionProbability !== undefined ? rayParameters.recursionProbability : 0.6; - rayParameters.recursionProbability = this.recursionProbability; - this.generateUVs = rayParameters.generateUVs !== undefined ? rayParameters.generateUVs : false; - rayParameters.generateUVs = this.generateUVs; // Random generator - - if (rayParameters.randomGenerator !== undefined) { - this.randomGenerator = rayParameters.randomGenerator; - this.seedGenerator = rayParameters.randomGenerator; - - if (rayParameters.noiseSeed !== undefined) { - this.seedGenerator.setSeed(rayParameters.noiseSeed); - } - } else { - this.randomGenerator = LightningStrike.createRandomGenerator(); - this.seedGenerator = Math; - } // Ray creation callbacks - - - if (rayParameters.onDecideSubrayCreation !== undefined) { - this.onDecideSubrayCreation = rayParameters.onDecideSubrayCreation; - } else { - this.createDefaultSubrayCreationCallbacks(); - - if (rayParameters.onSubrayCreation !== undefined) { - this.onSubrayCreation = rayParameters.onSubrayCreation; - } - } // Internal state - - - this.state = LightningStrike.RAY_INITIALIZED; - this.maxSubrays = Math.ceil(1 + Math.pow(this.ramification, Math.max(0, this.maxSubrayRecursion - 1))); - rayParameters.maxSubrays = this.maxSubrays; - this.maxRaySegments = 2 * (1 << this.maxIterations); - this.subrays = []; - - for (let i = 0; i < this.maxSubrays; i++) { - this.subrays.push(this.createSubray()); - } - - this.raySegments = []; - - for (let i = 0; i < this.maxRaySegments; i++) { - this.raySegments.push(this.createSegment()); - } - - this.time = 0; - this.timeFraction = 0; - this.currentSegmentCallback = null; - this.currentCreateTriangleVertices = this.generateUVs ? this.createTriangleVerticesWithUVs : this.createTriangleVerticesWithoutUVs; - this.numSubrays = 0; - this.currentSubray = null; - this.currentSegmentIndex = 0; - this.isInitialSegment = false; - this.subrayProbability = 0; - this.currentVertex = 0; - this.currentIndex = 0; - this.currentCoordinate = 0; - this.currentUVCoordinate = 0; - this.vertices = null; - this.uvs = null; - this.indices = null; - this.positionAttribute = null; - this.uvsAttribute = null; - this.simplexX = new SimplexNoise(this.seedGenerator); - this.simplexY = new SimplexNoise(this.seedGenerator); - this.simplexZ = new SimplexNoise(this.seedGenerator); // Temp vectors - - this.forwards = new Vector3(); - this.forwardsFill = new Vector3(); - this.side = new Vector3(); - this.down = new Vector3(); - this.middlePos = new Vector3(); - this.middleLinPos = new Vector3(); - this.newPos = new Vector3(); - this.vPos = new Vector3(); - this.cross1 = new Vector3(); - } - - createMesh() { - const maxDrawableSegmentsPerSubRay = 1 << this.maxIterations; - const maxVerts = 3 * (maxDrawableSegmentsPerSubRay + 1) * this.maxSubrays; - const maxIndices = 18 * maxDrawableSegmentsPerSubRay * this.maxSubrays; - this.vertices = new Float32Array(maxVerts * 3); - this.indices = new Uint32Array(maxIndices); - - if (this.generateUVs) { - this.uvs = new Float32Array(maxVerts * 2); - } // Populate the mesh - - - this.fillMesh(0); - this.setIndex(new Uint32BufferAttribute(this.indices, 1)); - this.positionAttribute = new Float32BufferAttribute(this.vertices, 3); - this.setAttribute('position', this.positionAttribute); - - if (this.generateUVs) { - this.uvsAttribute = new Float32BufferAttribute(new Float32Array(this.uvs), 2); - this.setAttribute('uv', this.uvsAttribute); - } - - if (!this.isStatic) { - this.index.usage = DynamicDrawUsage; - this.positionAttribute.usage = DynamicDrawUsage; - - if (this.generateUVs) { - this.uvsAttribute.usage = DynamicDrawUsage; - } - } // Store buffers for later modification - - - this.vertices = this.positionAttribute.array; - this.indices = this.index.array; - - if (this.generateUVs) { - this.uvs = this.uvsAttribute.array; - } - } - - updateMesh(time) { - this.fillMesh(time); - this.drawRange.count = this.currentIndex; - this.index.needsUpdate = true; - this.positionAttribute.needsUpdate = true; - - if (this.generateUVs) { - this.uvsAttribute.needsUpdate = true; - } - } - - fillMesh(time) { - const scope = this; - this.currentVertex = 0; - this.currentIndex = 0; - this.currentCoordinate = 0; - this.currentUVCoordinate = 0; - this.fractalRay(time, function fillVertices(segment) { - const subray = scope.currentSubray; - - if (time < subray.birthTime) { - //&& ( ! this.rayParameters.isEternal || scope.currentSubray.recursion > 0 ) ) { - return; - } else if (this.rayParameters.isEternal && scope.currentSubray.recursion == 0) { - // Eternal rays don't propagate nor vanish, but its subrays do - scope.createPrism(segment); - scope.onDecideSubrayCreation(segment, scope); - } else if (time < subray.endPropagationTime) { - if (scope.timeFraction >= segment.fraction0 * subray.propagationTimeFactor) { - // Ray propagation has arrived to this segment - scope.createPrism(segment); - scope.onDecideSubrayCreation(segment, scope); - } - } else if (time < subray.beginVanishingTime) { - // Ray is steady (nor propagating nor vanishing) - scope.createPrism(segment); - scope.onDecideSubrayCreation(segment, scope); - } else { - if (scope.timeFraction <= subray.vanishingTimeFactor + segment.fraction1 * (1 - subray.vanishingTimeFactor)) { - // Segment has not yet vanished - scope.createPrism(segment); - } - - scope.onDecideSubrayCreation(segment, scope); - } - }); - } - - addNewSubray() - /*rayParameters*/ - { - return this.subrays[this.numSubrays++]; - } - - initSubray(subray, rayParameters) { - subray.pos0.copy(rayParameters.sourceOffset); - subray.pos1.copy(rayParameters.destOffset); - subray.up0.copy(rayParameters.up0); - subray.up1.copy(rayParameters.up1); - subray.radius0 = rayParameters.radius0; - subray.radius1 = rayParameters.radius1; - subray.birthTime = rayParameters.birthTime; - subray.deathTime = rayParameters.deathTime; - subray.timeScale = rayParameters.timeScale; - subray.roughness = rayParameters.roughness; - subray.straightness = rayParameters.straightness; - subray.propagationTimeFactor = rayParameters.propagationTimeFactor; - subray.vanishingTimeFactor = rayParameters.vanishingTimeFactor; - subray.maxIterations = this.maxIterations; - subray.seed = rayParameters.noiseSeed !== undefined ? rayParameters.noiseSeed : 0; - subray.recursion = 0; - } - - fractalRay(time, segmentCallback) { - this.time = time; - this.currentSegmentCallback = segmentCallback; - this.numSubrays = 0; // Add the top level subray - - this.initSubray(this.addNewSubray(), this.rayParameters); // Process all subrays that are being generated until consuming all of them - - for (let subrayIndex = 0; subrayIndex < this.numSubrays; subrayIndex++) { - const subray = this.subrays[subrayIndex]; - this.currentSubray = subray; - this.randomGenerator.setSeed(subray.seed); - subray.endPropagationTime = MathUtils.lerp(subray.birthTime, subray.deathTime, subray.propagationTimeFactor); - subray.beginVanishingTime = MathUtils.lerp(subray.deathTime, subray.birthTime, 1 - subray.vanishingTimeFactor); - const random1 = this.randomGenerator.random; - subray.linPos0.set(random1(), random1(), random1()).multiplyScalar(1000); - subray.linPos1.set(random1(), random1(), random1()).multiplyScalar(1000); - this.timeFraction = (time - subray.birthTime) / (subray.deathTime - subray.birthTime); - this.currentSegmentIndex = 0; - this.isInitialSegment = true; - const segment = this.getNewSegment(); - segment.iteration = 0; - segment.pos0.copy(subray.pos0); - segment.pos1.copy(subray.pos1); - segment.linPos0.copy(subray.linPos0); - segment.linPos1.copy(subray.linPos1); - segment.up0.copy(subray.up0); - segment.up1.copy(subray.up1); - segment.radius0 = subray.radius0; - segment.radius1 = subray.radius1; - segment.fraction0 = 0; - segment.fraction1 = 1; - segment.positionVariationFactor = 1 - subray.straightness; - this.subrayProbability = this.ramification * Math.pow(this.recursionProbability, subray.recursion) / (1 << subray.maxIterations); - this.fractalRayRecursive(segment); - } - - this.currentSegmentCallback = null; - this.currentSubray = null; - } - - fractalRayRecursive(segment) { - // Leave recursion condition - if (segment.iteration >= this.currentSubray.maxIterations) { - this.currentSegmentCallback(segment); - return; - } // Interpolation - - - this.forwards.subVectors(segment.pos1, segment.pos0); - let lForwards = this.forwards.length(); - - if (lForwards < 0.000001) { - this.forwards.set(0, 0, 0.01); - lForwards = this.forwards.length(); - } - - const middleRadius = (segment.radius0 + segment.radius1) * 0.5; - const middleFraction = (segment.fraction0 + segment.fraction1) * 0.5; - const timeDimension = this.time * this.currentSubray.timeScale * Math.pow(2, segment.iteration); - this.middlePos.lerpVectors(segment.pos0, segment.pos1, 0.5); - this.middleLinPos.lerpVectors(segment.linPos0, segment.linPos1, 0.5); - const p = this.middleLinPos; // Noise - - this.newPos.set(this.simplexX.noise4d(p.x, p.y, p.z, timeDimension), this.simplexY.noise4d(p.x, p.y, p.z, timeDimension), this.simplexZ.noise4d(p.x, p.y, p.z, timeDimension)); - this.newPos.multiplyScalar(segment.positionVariationFactor * lForwards); - this.newPos.add(this.middlePos); // Recursion - - const newSegment1 = this.getNewSegment(); - newSegment1.pos0.copy(segment.pos0); - newSegment1.pos1.copy(this.newPos); - newSegment1.linPos0.copy(segment.linPos0); - newSegment1.linPos1.copy(this.middleLinPos); - newSegment1.up0.copy(segment.up0); - newSegment1.up1.copy(segment.up1); - newSegment1.radius0 = segment.radius0; - newSegment1.radius1 = middleRadius; - newSegment1.fraction0 = segment.fraction0; - newSegment1.fraction1 = middleFraction; - newSegment1.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; - newSegment1.iteration = segment.iteration + 1; - const newSegment2 = this.getNewSegment(); - newSegment2.pos0.copy(this.newPos); - newSegment2.pos1.copy(segment.pos1); - newSegment2.linPos0.copy(this.middleLinPos); - newSegment2.linPos1.copy(segment.linPos1); - this.cross1.crossVectors(segment.up0, this.forwards.normalize()); - newSegment2.up0.crossVectors(this.forwards, this.cross1).normalize(); - newSegment2.up1.copy(segment.up1); - newSegment2.radius0 = middleRadius; - newSegment2.radius1 = segment.radius1; - newSegment2.fraction0 = middleFraction; - newSegment2.fraction1 = segment.fraction1; - newSegment2.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; - newSegment2.iteration = segment.iteration + 1; - this.fractalRayRecursive(newSegment1); - this.fractalRayRecursive(newSegment2); - } - - createPrism(segment) { - // Creates one triangular prism and its vertices at the segment - this.forwardsFill.subVectors(segment.pos1, segment.pos0).normalize(); - - if (this.isInitialSegment) { - this.currentCreateTriangleVertices(segment.pos0, segment.up0, this.forwardsFill, segment.radius0, 0); - this.isInitialSegment = false; - } - - this.currentCreateTriangleVertices(segment.pos1, segment.up0, this.forwardsFill, segment.radius1, segment.fraction1); - this.createPrismFaces(); - } - - createTriangleVerticesWithoutUVs(pos, up, forwards, radius) { - // Create an equilateral triangle (only vertices) - this.side.crossVectors(up, forwards).multiplyScalar(radius * LightningStrike.COS30DEG); - this.down.copy(up).multiplyScalar(-radius * LightningStrike.SIN30DEG); - const p = this.vPos; - const v = this.vertices; - p.copy(pos).sub(this.side).add(this.down); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - p.copy(pos).add(this.side).add(this.down); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - p.copy(up).multiplyScalar(radius).add(pos); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - this.currentVertex += 3; - } - - createTriangleVerticesWithUVs(pos, up, forwards, radius, u) { - // Create an equilateral triangle (only vertices) - this.side.crossVectors(up, forwards).multiplyScalar(radius * LightningStrike.COS30DEG); - this.down.copy(up).multiplyScalar(-radius * LightningStrike.SIN30DEG); - const p = this.vPos; - const v = this.vertices; - const uv = this.uvs; - p.copy(pos).sub(this.side).add(this.down); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - uv[this.currentUVCoordinate++] = u; - uv[this.currentUVCoordinate++] = 0; - p.copy(pos).add(this.side).add(this.down); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - uv[this.currentUVCoordinate++] = u; - uv[this.currentUVCoordinate++] = 0.5; - p.copy(up).multiplyScalar(radius).add(pos); - v[this.currentCoordinate++] = p.x; - v[this.currentCoordinate++] = p.y; - v[this.currentCoordinate++] = p.z; - uv[this.currentUVCoordinate++] = u; - uv[this.currentUVCoordinate++] = 1; - this.currentVertex += 3; - } - - createPrismFaces(vertex - /*, index*/ - ) { - const indices = this.indices; - var vertex = this.currentVertex - 6; - indices[this.currentIndex++] = vertex + 1; - indices[this.currentIndex++] = vertex + 2; - indices[this.currentIndex++] = vertex + 5; - indices[this.currentIndex++] = vertex + 1; - indices[this.currentIndex++] = vertex + 5; - indices[this.currentIndex++] = vertex + 4; - indices[this.currentIndex++] = vertex + 0; - indices[this.currentIndex++] = vertex + 1; - indices[this.currentIndex++] = vertex + 4; - indices[this.currentIndex++] = vertex + 0; - indices[this.currentIndex++] = vertex + 4; - indices[this.currentIndex++] = vertex + 3; - indices[this.currentIndex++] = vertex + 2; - indices[this.currentIndex++] = vertex + 0; - indices[this.currentIndex++] = vertex + 3; - indices[this.currentIndex++] = vertex + 2; - indices[this.currentIndex++] = vertex + 3; - indices[this.currentIndex++] = vertex + 5; - } - - createDefaultSubrayCreationCallbacks() { - const random1 = this.randomGenerator.random; - - this.onDecideSubrayCreation = (segment, lightningStrike) => { - // Decide subrays creation at parent (sub)ray segment - const subray = lightningStrike.currentSubray; - const period = lightningStrike.rayParameters.subrayPeriod; - const dutyCycle = lightningStrike.rayParameters.subrayDutyCycle; - const phase0 = lightningStrike.rayParameters.isEternal && subray.recursion == 0 ? -random1() * period : MathUtils.lerp(subray.birthTime, subray.endPropagationTime, segment.fraction0) - random1() * period; - const phase = lightningStrike.time - phase0; - const currentCycle = Math.floor(phase / period); - const childSubraySeed = random1() * (currentCycle + 1); - const isActive = phase % period <= dutyCycle * period; - let probability = 0; - - if (isActive) { - probability = lightningStrike.subrayProbability; // Distribution test: probability *= segment.fraction0 > 0.5 && segment.fraction0 < 0.9 ? 1 / 0.4 : 0; - } - - if (subray.recursion < lightningStrike.maxSubrayRecursion && lightningStrike.numSubrays < lightningStrike.maxSubrays && random1() < probability) { - const childSubray = lightningStrike.addNewSubray(); - const parentSeed = lightningStrike.randomGenerator.getSeed(); - childSubray.seed = childSubraySeed; - lightningStrike.randomGenerator.setSeed(childSubraySeed); - childSubray.recursion = subray.recursion + 1; - childSubray.maxIterations = Math.max(1, subray.maxIterations - 1); - childSubray.linPos0.set(random1(), random1(), random1()).multiplyScalar(1000); - childSubray.linPos1.set(random1(), random1(), random1()).multiplyScalar(1000); - childSubray.up0.copy(subray.up0); - childSubray.up1.copy(subray.up1); - childSubray.radius0 = segment.radius0 * lightningStrike.rayParameters.radius0Factor; - childSubray.radius1 = Math.min(lightningStrike.rayParameters.minRadius, segment.radius1 * lightningStrike.rayParameters.radius1Factor); - childSubray.birthTime = phase0 + currentCycle * period; - childSubray.deathTime = childSubray.birthTime + period * dutyCycle; - - if (!lightningStrike.rayParameters.isEternal && subray.recursion == 0) { - childSubray.birthTime = Math.max(childSubray.birthTime, subray.birthTime); - childSubray.deathTime = Math.min(childSubray.deathTime, subray.deathTime); - } - - childSubray.timeScale = subray.timeScale * 2; - childSubray.roughness = subray.roughness; - childSubray.straightness = subray.straightness; - childSubray.propagationTimeFactor = subray.propagationTimeFactor; - childSubray.vanishingTimeFactor = subray.vanishingTimeFactor; - lightningStrike.onSubrayCreation(segment, subray, childSubray, lightningStrike); - lightningStrike.randomGenerator.setSeed(parentSeed); - } - }; - - const vec1Pos = new Vector3(); - const vec2Forward = new Vector3(); - const vec3Side = new Vector3(); - const vec4Up = new Vector3(); - - this.onSubrayCreation = (segment, parentSubray, childSubray, lightningStrike) => { - // Decide childSubray origin and destination positions (pos0 and pos1) and possibly other properties of childSubray - // Just use the default cone position generator - lightningStrike.subrayCylinderPosition(segment, parentSubray, childSubray, 0.5, 0.6, 0.2); - }; - - this.subrayConePosition = (segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor) => { - // Sets childSubray pos0 and pos1 in a cone - childSubray.pos0.copy(segment.pos0); - vec1Pos.subVectors(parentSubray.pos1, parentSubray.pos0); - vec2Forward.copy(vec1Pos).normalize(); - vec1Pos.multiplyScalar(segment.fraction0 + (1 - segment.fraction0) * (random1() * heightFactor)); - const length = vec1Pos.length(); - vec3Side.crossVectors(parentSubray.up0, vec2Forward); - const angle = 2 * Math.PI * random1(); - vec3Side.multiplyScalar(Math.cos(angle)); - vec4Up.copy(parentSubray.up0).multiplyScalar(Math.sin(angle)); - childSubray.pos1.copy(vec3Side).add(vec4Up).multiplyScalar(length * sideWidthFactor * (minSideWidthFactor + random1() * (1 - minSideWidthFactor))).add(vec1Pos).add(parentSubray.pos0); - }; - - this.subrayCylinderPosition = (segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor) => { - // Sets childSubray pos0 and pos1 in a cylinder - childSubray.pos0.copy(segment.pos0); - vec1Pos.subVectors(parentSubray.pos1, parentSubray.pos0); - vec2Forward.copy(vec1Pos).normalize(); - vec1Pos.multiplyScalar(segment.fraction0 + (1 - segment.fraction0) * ((2 * random1() - 1) * heightFactor)); - const length = vec1Pos.length(); - vec3Side.crossVectors(parentSubray.up0, vec2Forward); - const angle = 2 * Math.PI * random1(); - vec3Side.multiplyScalar(Math.cos(angle)); - vec4Up.copy(parentSubray.up0).multiplyScalar(Math.sin(angle)); - childSubray.pos1.copy(vec3Side).add(vec4Up).multiplyScalar(length * sideWidthFactor * (minSideWidthFactor + random1() * (1 - minSideWidthFactor))).add(vec1Pos).add(parentSubray.pos0); - }; - } - - createSubray() { - return { - seed: 0, - maxIterations: 0, - recursion: 0, - pos0: new Vector3(), - pos1: new Vector3(), - linPos0: new Vector3(), - linPos1: new Vector3(), - up0: new Vector3(), - up1: new Vector3(), - radius0: 0, - radius1: 0, - birthTime: 0, - deathTime: 0, - timeScale: 0, - roughness: 0, - straightness: 0, - propagationTimeFactor: 0, - vanishingTimeFactor: 0, - endPropagationTime: 0, - beginVanishingTime: 0 - }; - } - - createSegment() { - return { - iteration: 0, - pos0: new Vector3(), - pos1: new Vector3(), - linPos0: new Vector3(), - linPos1: new Vector3(), - up0: new Vector3(), - up1: new Vector3(), - radius0: 0, - radius1: 0, - fraction0: 0, - fraction1: 0, - positionVariationFactor: 0 - }; - } - - getNewSegment() { - return this.raySegments[this.currentSegmentIndex++]; - } - - copy(source) { - super.copy(source); - this.init(LightningStrike.copyParameters({}, source.rayParameters)); - return this; - } +var THREE = /*#__PURE__*/Object.freeze({ + __proto__: null, + ACESFilmicToneMapping: ACESFilmicToneMapping, + AddEquation: AddEquation, + AddOperation: AddOperation, + AdditiveAnimationBlendMode: AdditiveAnimationBlendMode, + AdditiveBlending: AdditiveBlending, + AlphaFormat: AlphaFormat, + AlwaysDepth: AlwaysDepth, + AlwaysStencilFunc: AlwaysStencilFunc, + AmbientLight: AmbientLight$1, + AmbientLightProbe: AmbientLightProbe, + AnimationClip: AnimationClip, + AnimationLoader: AnimationLoader, + AnimationMixer: AnimationMixer, + AnimationObjectGroup: AnimationObjectGroup, + AnimationUtils: AnimationUtils, + ArcCurve: ArcCurve, + ArrayCamera: ArrayCamera, + ArrowHelper: ArrowHelper, + Audio: Audio, + AudioAnalyser: AudioAnalyser, + AudioContext: AudioContext, + AudioListener: AudioListener, + AudioLoader: AudioLoader, + AxesHelper: AxesHelper, + BackSide: BackSide, + BasicDepthPacking: BasicDepthPacking, + BasicShadowMap: BasicShadowMap, + Bone: Bone, + BooleanKeyframeTrack: BooleanKeyframeTrack, + Box2: Box2, + Box3: Box3, + Box3Helper: Box3Helper, + BoxBufferGeometry: BoxGeometry, + BoxGeometry: BoxGeometry, + BoxHelper: BoxHelper, + BufferAttribute: BufferAttribute, + BufferGeometry: BufferGeometry, + BufferGeometryLoader: BufferGeometryLoader, + ByteType: ByteType, + Cache: Cache, + Camera: Camera, + CameraHelper: CameraHelper, + CanvasTexture: CanvasTexture, + CapsuleBufferGeometry: CapsuleGeometry, + CapsuleGeometry: CapsuleGeometry, + CatmullRomCurve3: CatmullRomCurve3, + CineonToneMapping: CineonToneMapping, + CircleBufferGeometry: CircleGeometry, + CircleGeometry: CircleGeometry, + ClampToEdgeWrapping: ClampToEdgeWrapping, + Clock: Clock, + Color: Color, + ColorKeyframeTrack: ColorKeyframeTrack, + ColorManagement: ColorManagement, + CompressedTexture: CompressedTexture, + CompressedTextureLoader: CompressedTextureLoader, + ConeBufferGeometry: ConeGeometry, + ConeGeometry: ConeGeometry, + CubeCamera: CubeCamera, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + CubeTexture: CubeTexture, + CubeTextureLoader: CubeTextureLoader, + CubeUVReflectionMapping: CubeUVReflectionMapping, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + CubicInterpolant: CubicInterpolant, + CullFaceBack: CullFaceBack, + CullFaceFront: CullFaceFront, + CullFaceFrontBack: CullFaceFrontBack, + CullFaceNone: CullFaceNone, + Curve: Curve, + CurvePath: CurvePath, + CustomBlending: CustomBlending, + CustomToneMapping: CustomToneMapping, + CylinderBufferGeometry: CylinderGeometry, + CylinderGeometry: CylinderGeometry, + Cylindrical: Cylindrical, + Data3DTexture: Data3DTexture, + DataArrayTexture: DataArrayTexture, + DataTexture: DataTexture, + DataTexture2DArray: DataTexture2DArray, + DataTexture3D: DataTexture3D, + DataTextureLoader: DataTextureLoader, + DataUtils: DataUtils, + DecrementStencilOp: DecrementStencilOp, + DecrementWrapStencilOp: DecrementWrapStencilOp, + DefaultLoadingManager: DefaultLoadingManager, + DepthFormat: DepthFormat, + DepthStencilFormat: DepthStencilFormat, + DepthTexture: DepthTexture, + DirectionalLight: DirectionalLight$1, + DirectionalLightHelper: DirectionalLightHelper, + DiscreteInterpolant: DiscreteInterpolant, + DodecahedronBufferGeometry: DodecahedronGeometry, + DodecahedronGeometry: DodecahedronGeometry, + DoubleSide: DoubleSide, + DstAlphaFactor: DstAlphaFactor, + DstColorFactor: DstColorFactor, + DynamicCopyUsage: DynamicCopyUsage, + DynamicDrawUsage: DynamicDrawUsage, + DynamicReadUsage: DynamicReadUsage, + EdgesGeometry: EdgesGeometry, + EllipseCurve: EllipseCurve, + EqualDepth: EqualDepth, + EqualStencilFunc: EqualStencilFunc, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + Euler: Euler, + EventDispatcher: EventDispatcher, + ExtrudeBufferGeometry: ExtrudeGeometry, + ExtrudeGeometry: ExtrudeGeometry, + FileLoader: FileLoader, + FlatShading: FlatShading, + Float16BufferAttribute: Float16BufferAttribute, + Float32BufferAttribute: Float32BufferAttribute, + Float64BufferAttribute: Float64BufferAttribute, + FloatType: FloatType, + Fog: Fog, + FogExp2: FogExp2, + Font: Font, + FontLoader: FontLoader, + FramebufferTexture: FramebufferTexture, + FrontSide: FrontSide, + Frustum: Frustum, + GLBufferAttribute: GLBufferAttribute, + GLSL1: GLSL1, + GLSL3: GLSL3, + GreaterDepth: GreaterDepth, + GreaterEqualDepth: GreaterEqualDepth, + GreaterEqualStencilFunc: GreaterEqualStencilFunc, + GreaterStencilFunc: GreaterStencilFunc, + GridHelper: GridHelper, + Group: Group, + HalfFloatType: HalfFloatType, + HemisphereLight: HemisphereLight, + HemisphereLightHelper: HemisphereLightHelper, + HemisphereLightProbe: HemisphereLightProbe, + IcosahedronBufferGeometry: IcosahedronGeometry, + IcosahedronGeometry: IcosahedronGeometry, + ImageBitmapLoader: ImageBitmapLoader, + ImageLoader: ImageLoader, + ImageUtils: ImageUtils, + ImmediateRenderObject: ImmediateRenderObject, + IncrementStencilOp: IncrementStencilOp, + IncrementWrapStencilOp: IncrementWrapStencilOp, + InstancedBufferAttribute: InstancedBufferAttribute, + InstancedBufferGeometry: InstancedBufferGeometry, + InstancedInterleavedBuffer: InstancedInterleavedBuffer, + InstancedMesh: InstancedMesh, + Int16BufferAttribute: Int16BufferAttribute, + Int32BufferAttribute: Int32BufferAttribute, + Int8BufferAttribute: Int8BufferAttribute, + IntType: IntType, + InterleavedBuffer: InterleavedBuffer, + InterleavedBufferAttribute: InterleavedBufferAttribute, + Interpolant: Interpolant, + InterpolateDiscrete: InterpolateDiscrete, + InterpolateLinear: InterpolateLinear, + InterpolateSmooth: InterpolateSmooth, + InvertStencilOp: InvertStencilOp, + KeepStencilOp: KeepStencilOp, + KeyframeTrack: KeyframeTrack, + LOD: LOD, + LatheBufferGeometry: LatheGeometry, + LatheGeometry: LatheGeometry, + Layers: Layers, + LessDepth: LessDepth, + LessEqualDepth: LessEqualDepth, + LessEqualStencilFunc: LessEqualStencilFunc, + LessStencilFunc: LessStencilFunc, + Light: Light, + LightProbe: LightProbe, + Line: Line$2, + Line3: Line3, + LineBasicMaterial: LineBasicMaterial, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + LineDashedMaterial: LineDashedMaterial, + LineLoop: LineLoop, + LineSegments: LineSegments, + LinearEncoding: LinearEncoding, + LinearFilter: LinearFilter, + LinearInterpolant: LinearInterpolant, + LinearMipMapLinearFilter: LinearMipMapLinearFilter, + LinearMipMapNearestFilter: LinearMipMapNearestFilter, + LinearMipmapLinearFilter: LinearMipmapLinearFilter, + LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearSRGBColorSpace: LinearSRGBColorSpace, + LinearToneMapping: LinearToneMapping, + Loader: Loader, + LoaderUtils: LoaderUtils, + LoadingManager: LoadingManager, + LoopOnce: LoopOnce, + LoopPingPong: LoopPingPong, + LoopRepeat: LoopRepeat, + LuminanceAlphaFormat: LuminanceAlphaFormat, + LuminanceFormat: LuminanceFormat, + MOUSE: MOUSE, + Material: Material, + MaterialLoader: MaterialLoader, + MathUtils: MathUtils, + Matrix3: Matrix3, + Matrix4: Matrix4, + MaxEquation: MaxEquation, + Mesh: Mesh, + MeshBasicMaterial: MeshBasicMaterial, + MeshDepthMaterial: MeshDepthMaterial, + MeshDistanceMaterial: MeshDistanceMaterial, + MeshLambertMaterial: MeshLambertMaterial, + MeshMatcapMaterial: MeshMatcapMaterial, + MeshNormalMaterial: MeshNormalMaterial, + MeshPhongMaterial: MeshPhongMaterial, + MeshPhysicalMaterial: MeshPhysicalMaterial, + MeshStandardMaterial: MeshStandardMaterial, + MeshToonMaterial: MeshToonMaterial, + MinEquation: MinEquation, + MirroredRepeatWrapping: MirroredRepeatWrapping, + MixOperation: MixOperation, + MultiplyBlending: MultiplyBlending, + MultiplyOperation: MultiplyOperation, + NearestFilter: NearestFilter, + NearestMipMapLinearFilter: NearestMipMapLinearFilter, + NearestMipMapNearestFilter: NearestMipMapNearestFilter, + NearestMipmapLinearFilter: NearestMipmapLinearFilter, + NearestMipmapNearestFilter: NearestMipmapNearestFilter, + NeverDepth: NeverDepth, + NeverStencilFunc: NeverStencilFunc, + NoBlending: NoBlending, + NoColorSpace: NoColorSpace, + NoToneMapping: NoToneMapping, + NormalAnimationBlendMode: NormalAnimationBlendMode, + NormalBlending: NormalBlending, + NotEqualDepth: NotEqualDepth, + NotEqualStencilFunc: NotEqualStencilFunc, + NumberKeyframeTrack: NumberKeyframeTrack, + Object3D: Object3D, + ObjectLoader: ObjectLoader, + ObjectSpaceNormalMap: ObjectSpaceNormalMap, + OctahedronBufferGeometry: OctahedronGeometry, + OctahedronGeometry: OctahedronGeometry, + OneFactor: OneFactor, + OneMinusDstAlphaFactor: OneMinusDstAlphaFactor, + OneMinusDstColorFactor: OneMinusDstColorFactor, + OneMinusSrcAlphaFactor: OneMinusSrcAlphaFactor, + OneMinusSrcColorFactor: OneMinusSrcColorFactor, + OrthographicCamera: OrthographicCamera, + PCFShadowMap: PCFShadowMap, + PCFSoftShadowMap: PCFSoftShadowMap, + PMREMGenerator: PMREMGenerator, + ParametricGeometry: ParametricGeometry, + Path: Path, + PerspectiveCamera: PerspectiveCamera, + Plane: Plane, + PlaneBufferGeometry: PlaneGeometry, + PlaneGeometry: PlaneGeometry, + PlaneHelper: PlaneHelper, + PointLight: PointLight, + PointLightHelper: PointLightHelper, + Points: Points, + PointsMaterial: PointsMaterial, + PolarGridHelper: PolarGridHelper, + PolyhedronBufferGeometry: PolyhedronGeometry, + PolyhedronGeometry: PolyhedronGeometry, + PositionalAudio: PositionalAudio, + PropertyBinding: PropertyBinding, + PropertyMixer: PropertyMixer, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + Quaternion: Quaternion, + QuaternionKeyframeTrack: QuaternionKeyframeTrack, + QuaternionLinearInterpolant: QuaternionLinearInterpolant, + REVISION: REVISION, + RGBADepthPacking: RGBADepthPacking, + RGBAFormat: RGBAFormat, + RGBAIntegerFormat: RGBAIntegerFormat, + RGBA_ASTC_10x10_Format: RGBA_ASTC_10x10_Format, + RGBA_ASTC_10x5_Format: RGBA_ASTC_10x5_Format, + RGBA_ASTC_10x6_Format: RGBA_ASTC_10x6_Format, + RGBA_ASTC_10x8_Format: RGBA_ASTC_10x8_Format, + RGBA_ASTC_12x10_Format: RGBA_ASTC_12x10_Format, + RGBA_ASTC_12x12_Format: RGBA_ASTC_12x12_Format, + RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format, + RGBA_ASTC_5x4_Format: RGBA_ASTC_5x4_Format, + RGBA_ASTC_5x5_Format: RGBA_ASTC_5x5_Format, + RGBA_ASTC_6x5_Format: RGBA_ASTC_6x5_Format, + RGBA_ASTC_6x6_Format: RGBA_ASTC_6x6_Format, + RGBA_ASTC_8x5_Format: RGBA_ASTC_8x5_Format, + RGBA_ASTC_8x6_Format: RGBA_ASTC_8x6_Format, + RGBA_ASTC_8x8_Format: RGBA_ASTC_8x8_Format, + RGBA_BPTC_Format: RGBA_BPTC_Format, + RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format, + RGBA_PVRTC_2BPPV1_Format: RGBA_PVRTC_2BPPV1_Format, + RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format, + RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format, + RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format, + RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format, + RGBFormat: RGBFormat, + RGB_ETC1_Format: RGB_ETC1_Format, + RGB_ETC2_Format: RGB_ETC2_Format, + RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format, + RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format, + RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format, + RGFormat: RGFormat, + RGIntegerFormat: RGIntegerFormat, + RawShaderMaterial: RawShaderMaterial, + Ray: Ray, + Raycaster: Raycaster, + RectAreaLight: RectAreaLight, + RedFormat: RedFormat, + RedIntegerFormat: RedIntegerFormat, + ReinhardToneMapping: ReinhardToneMapping, + RepeatWrapping: RepeatWrapping, + ReplaceStencilOp: ReplaceStencilOp, + ReverseSubtractEquation: ReverseSubtractEquation, + RingBufferGeometry: RingGeometry, + RingGeometry: RingGeometry, + SRGBColorSpace: SRGBColorSpace, + Scene: Scene$1, + ShaderChunk: ShaderChunk, + ShaderLib: ShaderLib, + ShaderMaterial: ShaderMaterial, + ShadowMaterial: ShadowMaterial, + Shape: Shape, + ShapeBufferGeometry: ShapeGeometry, + ShapeGeometry: ShapeGeometry, + ShapePath: ShapePath, + ShapeUtils: ShapeUtils, + ShortType: ShortType, + Skeleton: Skeleton, + SkeletonHelper: SkeletonHelper, + SkinnedMesh: SkinnedMesh, + SmoothShading: SmoothShading, + Source: Source, + Sphere: Sphere, + SphereBufferGeometry: SphereGeometry, + SphereGeometry: SphereGeometry, + Spherical: Spherical, + SphericalHarmonics3: SphericalHarmonics3, + SplineCurve: SplineCurve, + SpotLight: SpotLight, + SpotLightHelper: SpotLightHelper, + Sprite: Sprite, + SpriteMaterial: SpriteMaterial, + SrcAlphaFactor: SrcAlphaFactor, + SrcAlphaSaturateFactor: SrcAlphaSaturateFactor, + SrcColorFactor: SrcColorFactor, + StaticCopyUsage: StaticCopyUsage, + StaticDrawUsage: StaticDrawUsage, + StaticReadUsage: StaticReadUsage, + StereoCamera: StereoCamera, + StreamCopyUsage: StreamCopyUsage, + StreamDrawUsage: StreamDrawUsage, + StreamReadUsage: StreamReadUsage, + StringKeyframeTrack: StringKeyframeTrack, + SubtractEquation: SubtractEquation, + SubtractiveBlending: SubtractiveBlending, + TOUCH: TOUCH, + TangentSpaceNormalMap: TangentSpaceNormalMap, + TetrahedronBufferGeometry: TetrahedronGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TextGeometry: TextGeometry, + Texture: Texture, + TextureLoader: TextureLoader, + TorusBufferGeometry: TorusGeometry, + TorusGeometry: TorusGeometry, + TorusKnotBufferGeometry: TorusKnotGeometry, + TorusKnotGeometry: TorusKnotGeometry, + Triangle: Triangle, + TriangleFanDrawMode: TriangleFanDrawMode, + TriangleStripDrawMode: TriangleStripDrawMode, + TrianglesDrawMode: TrianglesDrawMode, + TubeBufferGeometry: TubeGeometry, + TubeGeometry: TubeGeometry, + UVMapping: UVMapping, + Uint16BufferAttribute: Uint16BufferAttribute, + Uint32BufferAttribute: Uint32BufferAttribute, + Uint8BufferAttribute: Uint8BufferAttribute, + Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute, + Uniform: Uniform, + UniformsLib: UniformsLib, + UniformsUtils: UniformsUtils, + UnsignedByteType: UnsignedByteType, + UnsignedInt248Type: UnsignedInt248Type, + UnsignedIntType: UnsignedIntType, + UnsignedShort4444Type: UnsignedShort4444Type, + UnsignedShort5551Type: UnsignedShort5551Type, + UnsignedShortType: UnsignedShortType, + VSMShadowMap: VSMShadowMap, + Vector2: Vector2, + Vector3: Vector3, + Vector4: Vector4, + VectorKeyframeTrack: VectorKeyframeTrack, + VideoTexture: VideoTexture, + WebGL1Renderer: WebGL1Renderer, + WebGL3DRenderTarget: WebGL3DRenderTarget, + WebGLArrayRenderTarget: WebGLArrayRenderTarget, + WebGLCubeRenderTarget: WebGLCubeRenderTarget, + WebGLMultipleRenderTargets: WebGLMultipleRenderTargets, + WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget, + WebGLRenderTarget: WebGLRenderTarget, + WebGLRenderer: WebGLRenderer, + WebGLUtils: WebGLUtils, + WireframeGeometry: WireframeGeometry, + WrapAroundEnding: WrapAroundEnding, + ZeroCurvatureEnding: ZeroCurvatureEnding, + ZeroFactor: ZeroFactor, + ZeroSlopeEnding: ZeroSlopeEnding, + ZeroStencilOp: ZeroStencilOp, + _SRGBAFormat: _SRGBAFormat, + sRGBEncoding: sRGBEncoding +}); - clone() { - return new this.constructor(LightningStrike.copyParameters({}, this.rayParameters)); - } +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } -LightningStrike.prototype.isLightningStrike = true; // Ray states - -LightningStrike.RAY_INITIALIZED = 0; -LightningStrike.RAY_UNBORN = 1; -LightningStrike.RAY_PROPAGATING = 2; -LightningStrike.RAY_STEADY = 3; -LightningStrike.RAY_VANISHING = 4; -LightningStrike.RAY_EXTINGUISHED = 5; -LightningStrike.COS30DEG = Math.cos(30 * Math.PI / 180); -LightningStrike.SIN30DEG = Math.sin(30 * Math.PI / 180); - -LightningStrike.createRandomGenerator = () => { - const numSeeds = 2053; - const seeds = []; - - for (let i = 0; i < numSeeds; i++) { - seeds.push(Math.random()); - } - - const generator = { - currentSeed: 0, - random: function () { - const value = seeds[generator.currentSeed]; - generator.currentSeed = (generator.currentSeed + 1) % numSeeds; - return value; - }, - getSeed: function () { - return generator.currentSeed / numSeeds; - }, - setSeed: function (seed) { - generator.currentSeed = Math.floor(seed * numSeeds) % numSeeds; - } - }; - return generator; -}; - -LightningStrike.copyParameters = (dest, source) => { - source = source || {}; - dest = dest || {}; - - const vecCopy = v => { - if (source === dest) { - return v; - } else { - return v.clone(); - } - }; +var constants = {exports: {}}; - dest.sourceOffset = source.sourceOffset !== undefined ? vecCopy(source.sourceOffset) : new Vector3(0, 100, 0), dest.destOffset = source.destOffset !== undefined ? vecCopy(source.destOffset) : new Vector3(0, 0, 0), dest.timeScale = source.timeScale !== undefined ? source.timeScale : 1, dest.roughness = source.roughness !== undefined ? source.roughness : 0.9, dest.straightness = source.straightness !== undefined ? source.straightness : 0.7, dest.up0 = source.up0 !== undefined ? vecCopy(source.up0) : new Vector3(0, 0, 1); - dest.up1 = source.up1 !== undefined ? vecCopy(source.up1) : new Vector3(0, 0, 1), dest.radius0 = source.radius0 !== undefined ? source.radius0 : 1, dest.radius1 = source.radius1 !== undefined ? source.radius1 : 1, dest.radius0Factor = source.radius0Factor !== undefined ? source.radius0Factor : 0.5, dest.radius1Factor = source.radius1Factor !== undefined ? source.radius1Factor : 0.2, dest.minRadius = source.minRadius !== undefined ? source.minRadius : 0.2, // These parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly: - dest.isEternal = source.isEternal !== undefined ? source.isEternal : source.birthTime === undefined || source.deathTime === undefined, dest.birthTime = source.birthTime, dest.deathTime = source.deathTime, dest.propagationTimeFactor = source.propagationTimeFactor !== undefined ? source.propagationTimeFactor : 0.1, dest.vanishingTimeFactor = source.vanishingTimeFactor !== undefined ? source.vanishingTimeFactor : 0.9, dest.subrayPeriod = source.subrayPeriod !== undefined ? source.subrayPeriod : 4, dest.subrayDutyCycle = source.subrayDutyCycle !== undefined ? source.subrayDutyCycle : 0.6; // These parameters cannot change after lightning creation: - - dest.maxIterations = source.maxIterations !== undefined ? source.maxIterations : 9; - dest.isStatic = source.isStatic !== undefined ? source.isStatic : false; - dest.ramification = source.ramification !== undefined ? source.ramification : 5; - dest.maxSubrayRecursion = source.maxSubrayRecursion !== undefined ? source.maxSubrayRecursion : 3; - dest.recursionProbability = source.recursionProbability !== undefined ? source.recursionProbability : 0.6; - dest.generateUVs = source.generateUVs !== undefined ? source.generateUVs : false; - dest.randomGenerator = source.randomGenerator, dest.noiseSeed = source.noiseSeed, dest.onDecideSubrayCreation = source.onDecideSubrayCreation, dest.onSubrayCreation = source.onSubrayCreation; - return dest; -}; +var reactReconcilerConstants_production_min = {}; /** - * @fileoverview Lightning strike object generator - * - * - * Usage - * - * const myStorm = new LightningStorm( paramsObject ); - * myStorm.position.set( ... ); - * scene.add( myStorm ); - * ... - * myStorm.update( currentTime ); - * - * The "currentTime" can only go forwards or be stopped. - * - * - * LightningStorm parameters: - * - * @param {double} size Size of the storm. If no 'onRayPosition' parameter is defined, it means the side of the rectangle the storm covers. - * - * @param {double} minHeight Minimum height a ray can start at. If no 'onRayPosition' parameter is defined, it means the height above plane y = 0. - * - * @param {double} maxHeight Maximum height a ray can start at. If no 'onRayPosition' parameter is defined, it means the height above plane y = 0. - * - * @param {double} maxSlope The maximum inclination slope of a ray. If no 'onRayPosition' parameter is defined, it means the slope relative to plane y = 0. - * - * @param {integer} maxLightnings Greater than 0. The maximum number of simultaneous rays. - * - * @param {double} lightningMinPeriod minimum time between two consecutive rays. - * - * @param {double} lightningMaxPeriod maximum time between two consecutive rays. - * - * @param {double} lightningMinDuration The minimum time a ray can last. - * - * @param {double} lightningMaxDuration The maximum time a ray can last. - * - * @param {Object} lightningParameters The parameters for created rays. See LightningStrike (geometry) - * - * @param {Material} lightningMaterial The THREE.Material used for the created rays. - * - * @param {function} onRayPosition Optional callback with two Vector3 parameters (source, dest). You can set here the start and end points for each created ray, using the standard size, minHeight, etc parameters and other values in your algorithm. - * - * @param {function} onLightningDown This optional callback is called with one parameter (lightningStrike) when a ray ends propagating, so it has hit the ground. + * @license React + * react-reconciler-constants.production.min.js * + * Copyright (c) Facebook, Inc. and its affiliates. * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -class LightningStorm extends Object3D { - constructor(stormParams = {}) { - super(); // Parameters - - this.stormParams = stormParams; - stormParams.size = stormParams.size !== undefined ? stormParams.size : 1000.0; - stormParams.minHeight = stormParams.minHeight !== undefined ? stormParams.minHeight : 80.0; - stormParams.maxHeight = stormParams.maxHeight !== undefined ? stormParams.maxHeight : 100.0; - stormParams.maxSlope = stormParams.maxSlope !== undefined ? stormParams.maxSlope : 1.1; - stormParams.maxLightnings = stormParams.maxLightnings !== undefined ? stormParams.maxLightnings : 3; - stormParams.lightningMinPeriod = stormParams.lightningMinPeriod !== undefined ? stormParams.lightningMinPeriod : 3.0; - stormParams.lightningMaxPeriod = stormParams.lightningMaxPeriod !== undefined ? stormParams.lightningMaxPeriod : 7.0; - stormParams.lightningMinDuration = stormParams.lightningMinDuration !== undefined ? stormParams.lightningMinDuration : 1.0; - stormParams.lightningMaxDuration = stormParams.lightningMaxDuration !== undefined ? stormParams.lightningMaxDuration : 2.5; - this.lightningParameters = LightningStrike.copyParameters(stormParams.lightningParameters, stormParams.lightningParameters); - this.lightningParameters.isEternal = false; - this.lightningMaterial = stormParams.lightningMaterial !== undefined ? stormParams.lightningMaterial : new MeshBasicMaterial({ - color: 0xb0ffff - }); - - if (stormParams.onRayPosition !== undefined) { - this.onRayPosition = stormParams.onRayPosition; - } else { - this.onRayPosition = function (source, dest) { - dest.set((Math.random() - 0.5) * stormParams.size, 0, (Math.random() - 0.5) * stormParams.size); - const height = MathUtils.lerp(stormParams.minHeight, stormParams.maxHeight, Math.random()); - source.set(stormParams.maxSlope * (2 * Math.random() - 1), 1, stormParams.maxSlope * (2 * Math.random() - 1)).multiplyScalar(height).add(dest); - }; - } - - this.onLightningDown = stormParams.onLightningDown; // Internal state - - this.inited = false; - this.nextLightningTime = 0; - this.lightningsMeshes = []; - this.deadLightningsMeshes = []; - - for (let i = 0; i < this.stormParams.maxLightnings; i++) { - const lightning = new LightningStrike(LightningStrike.copyParameters({}, this.lightningParameters)); - const mesh = new Mesh(lightning, this.lightningMaterial); - this.deadLightningsMeshes.push(mesh); - } - } - - update(time) { - if (!this.inited) { - this.nextLightningTime = this.getNextLightningTime(time) * Math.random(); - this.inited = true; - } - - if (time >= this.nextLightningTime) { - // Lightning creation - const lightningMesh = this.deadLightningsMeshes.pop(); - - if (lightningMesh) { - const lightningParams1 = LightningStrike.copyParameters(lightningMesh.geometry.rayParameters, this.lightningParameters); - lightningParams1.birthTime = time; - lightningParams1.deathTime = time + MathUtils.lerp(this.stormParams.lightningMinDuration, this.stormParams.lightningMaxDuration, Math.random()); - this.onRayPosition(lightningParams1.sourceOffset, lightningParams1.destOffset); - lightningParams1.noiseSeed = Math.random(); - this.add(lightningMesh); - this.lightningsMeshes.push(lightningMesh); - } // Schedule next lightning - - - this.nextLightningTime = this.getNextLightningTime(time); - } - - let i = 0, - il = this.lightningsMeshes.length; - - while (i < il) { - const mesh = this.lightningsMeshes[i]; - const lightning = mesh.geometry; - const prevState = lightning.state; - lightning.update(time); - - if (prevState === LightningStrike.RAY_PROPAGATING && lightning.state > prevState) { - if (this.onLightningDown) { - this.onLightningDown(lightning); - } - } - - if (lightning.state === LightningStrike.RAY_EXTINGUISHED) { - // Lightning is to be destroyed - this.lightningsMeshes.splice(this.lightningsMeshes.indexOf(mesh), 1); - this.deadLightningsMeshes.push(mesh); - this.remove(mesh); - il--; - } else { - i++; - } - } - } - - getNextLightningTime(currentTime) { - return currentTime + MathUtils.lerp(this.stormParams.lightningMinPeriod, this.stormParams.lightningMaxPeriod, Math.random()) / (this.stormParams.maxLightnings + 1); - } - - copy(source) { - super.copy(source); - this.stormParams.size = source.stormParams.size; - this.stormParams.minHeight = source.stormParams.minHeight; - this.stormParams.maxHeight = source.stormParams.maxHeight; - this.stormParams.maxSlope = source.stormParams.maxSlope; - this.stormParams.maxLightnings = source.stormParams.maxLightnings; - this.stormParams.lightningMinPeriod = source.stormParams.lightningMinPeriod; - this.stormParams.lightningMaxPeriod = source.stormParams.lightningMaxPeriod; - this.stormParams.lightningMinDuration = source.stormParams.lightningMinDuration; - this.stormParams.lightningMaxDuration = source.stormParams.lightningMaxDuration; - this.lightningParameters = LightningStrike.copyParameters({}, source.lightningParameters); - this.lightningMaterial = source.stormParams.lightningMaterial; - this.onLightningDown = source.onLightningDown; - return this; - } - - clone() { - return new this.constructor(this.stormParams).copy(this); - } - -} - -LightningStorm.prototype.isLightningStorm = true; - -class ReflectorForSSRPass extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - this.type = 'ReflectorForSSRPass'; - const scope = this; - const color = options.color !== undefined ? new Color(options.color) : new Color(0x7f7f7f); - const textureWidth = options.textureWidth || 512; - const textureHeight = options.textureHeight || 512; - const clipBias = options.clipBias || 0; - const shader = options.shader || ReflectorForSSRPass.ReflectorShader; - const useDepthTexture = options.useDepthTexture === true; - const yAxis = new Vector3(0, 1, 0); - const vecTemp0 = new Vector3(); - const vecTemp1 = new Vector3(); // - - scope.needsUpdate = false; - scope.maxDistance = ReflectorForSSRPass.ReflectorShader.uniforms.maxDistance.value; - scope.opacity = ReflectorForSSRPass.ReflectorShader.uniforms.opacity.value; - scope.color = color; - scope.resolution = options.resolution || new Vector2(window.innerWidth, window.innerHeight); - scope._distanceAttenuation = ReflectorForSSRPass.ReflectorShader.defines.DISTANCE_ATTENUATION; - Object.defineProperty(scope, 'distanceAttenuation', { - get() { - return scope._distanceAttenuation; - }, - - set(val) { - if (scope._distanceAttenuation === val) return; - scope._distanceAttenuation = val; - scope.material.defines.DISTANCE_ATTENUATION = val; - scope.material.needsUpdate = true; - } - - }); - scope._fresnel = ReflectorForSSRPass.ReflectorShader.defines.FRESNEL; - Object.defineProperty(scope, 'fresnel', { - get() { - return scope._fresnel; - }, - - set(val) { - if (scope._fresnel === val) return; - scope._fresnel = val; - scope.material.defines.FRESNEL = val; - scope.material.needsUpdate = true; - } - - }); - const normal = new Vector3(); - const reflectorWorldPosition = new Vector3(); - const cameraWorldPosition = new Vector3(); - const rotationMatrix = new Matrix4(); - const lookAtPosition = new Vector3(0, 0, -1); - const view = new Vector3(); - const target = new Vector3(); - const textureMatrix = new Matrix4(); - const virtualCamera = new PerspectiveCamera(); - let depthTexture; - - if (useDepthTexture) { - depthTexture = new DepthTexture(); - depthTexture.type = UnsignedShortType; - depthTexture.minFilter = NearestFilter; - depthTexture.magFilter = NearestFilter; - } - - const parameters = { - depthTexture: useDepthTexture ? depthTexture : null - }; - const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, parameters); - const material = new ShaderMaterial({ - transparent: useDepthTexture, - defines: Object.assign({}, ReflectorForSSRPass.ReflectorShader.defines, { - useDepthTexture - }), - uniforms: UniformsUtils.clone(shader.uniforms), - fragmentShader: shader.fragmentShader, - vertexShader: shader.vertexShader - }); - material.uniforms['tDiffuse'].value = renderTarget.texture; - material.uniforms['color'].value = scope.color; - material.uniforms['textureMatrix'].value = textureMatrix; - - if (useDepthTexture) { - material.uniforms['tDepth'].value = renderTarget.depthTexture; - } - - this.material = material; - const globalPlane = new Plane(new Vector3(0, 1, 0), clipBias); - const globalPlanes = [globalPlane]; - - this.doRender = function (renderer, scene, camera) { - material.uniforms['maxDistance'].value = scope.maxDistance; - material.uniforms['color'].value = scope.color; - material.uniforms['opacity'].value = scope.opacity; - vecTemp0.copy(camera.position).normalize(); - vecTemp1.copy(vecTemp0).reflect(yAxis); - material.uniforms['fresnelCoe'].value = (vecTemp0.dot(vecTemp1) + 1) / 2; // TODO: Also need to use glsl viewPosition and viewNormal per pixel. - - reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); - cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); - rotationMatrix.extractRotation(scope.matrixWorld); - normal.set(0, 0, 1); - normal.applyMatrix4(rotationMatrix); - view.subVectors(reflectorWorldPosition, cameraWorldPosition); // Avoid rendering when reflector is facing away - - if (view.dot(normal) > 0) return; - view.reflect(normal).negate(); - view.add(reflectorWorldPosition); - rotationMatrix.extractRotation(camera.matrixWorld); - lookAtPosition.set(0, 0, -1); - lookAtPosition.applyMatrix4(rotationMatrix); - lookAtPosition.add(cameraWorldPosition); - target.subVectors(reflectorWorldPosition, lookAtPosition); - target.reflect(normal).negate(); - target.add(reflectorWorldPosition); - virtualCamera.position.copy(view); - virtualCamera.up.set(0, 1, 0); - virtualCamera.up.applyMatrix4(rotationMatrix); - virtualCamera.up.reflect(normal); - virtualCamera.lookAt(target); - virtualCamera.far = camera.far; // Used in WebGLBackground - - virtualCamera.updateMatrixWorld(); - virtualCamera.projectionMatrix.copy(camera.projectionMatrix); - material.uniforms['virtualCameraNear'].value = camera.near; - material.uniforms['virtualCameraFar'].value = camera.far; - material.uniforms['virtualCameraMatrixWorld'].value = virtualCamera.matrixWorld; - material.uniforms['virtualCameraProjectionMatrix'].value = camera.projectionMatrix; - material.uniforms['virtualCameraProjectionMatrixInverse'].value = camera.projectionMatrixInverse; - material.uniforms['resolution'].value = scope.resolution; // Update the texture matrix - - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); - textureMatrix.multiply(virtualCamera.projectionMatrix); - textureMatrix.multiply(virtualCamera.matrixWorldInverse); - textureMatrix.multiply(scope.matrixWorld); // Render - - renderTarget.texture.encoding = renderer.outputEncoding; // scope.visible = false; - - const currentRenderTarget = renderer.getRenderTarget(); - const currentXrEnabled = renderer.xr.enabled; - const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; - const currentClippingPlanes = renderer.clippingPlanes; - renderer.xr.enabled = false; // Avoid camera modification - - renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows - - renderer.clippingPlanes = globalPlanes; - renderer.setRenderTarget(renderTarget); - renderer.state.buffers.depth.setMask(true); // make sure the depth buffer is writable so it can be properly cleared, see #18897 - - if (renderer.autoClear === false) renderer.clear(); - renderer.render(scene, virtualCamera); - renderer.xr.enabled = currentXrEnabled; - renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; - renderer.clippingPlanes = currentClippingPlanes; - renderer.setRenderTarget(currentRenderTarget); // Restore viewport - - const viewport = camera.viewport; - - if (viewport !== undefined) { - renderer.state.viewport(viewport); - } // scope.visible = true; - - }; - - this.getRenderTarget = function () { - return renderTarget; - }; - } +var hasRequiredReactReconcilerConstants_production_min; +function requireReactReconcilerConstants_production_min () { + if (hasRequiredReactReconcilerConstants_production_min) return reactReconcilerConstants_production_min; + hasRequiredReactReconcilerConstants_production_min = 1; +reactReconcilerConstants_production_min.ConcurrentRoot=1;reactReconcilerConstants_production_min.ContinuousEventPriority=4;reactReconcilerConstants_production_min.DefaultEventPriority=16;reactReconcilerConstants_production_min.DiscreteEventPriority=1;reactReconcilerConstants_production_min.IdleEventPriority=536870912;reactReconcilerConstants_production_min.LegacyRoot=0; + return reactReconcilerConstants_production_min; } -ReflectorForSSRPass.prototype.isReflectorForSSRPass = true; -ReflectorForSSRPass.ReflectorShader = { - defines: { - DISTANCE_ATTENUATION: true, - FRESNEL: true - }, - uniforms: { - color: { - value: null - }, - tDiffuse: { - value: null - }, - tDepth: { - value: null - }, - textureMatrix: { - value: new Matrix4() - }, - maxDistance: { - value: 180 - }, - opacity: { - value: 0.5 - }, - fresnelCoe: { - value: null - }, - virtualCameraNear: { - value: null - }, - virtualCameraFar: { - value: null - }, - virtualCameraProjectionMatrix: { - value: new Matrix4() - }, - virtualCameraMatrixWorld: { - value: new Matrix4() - }, - virtualCameraProjectionMatrixInverse: { - value: new Matrix4() - }, - resolution: { - value: new Vector2() - } - }, - vertexShader: - /* glsl */ - ` - uniform mat4 textureMatrix; - varying vec4 vUv; - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`, - fragmentShader: - /* glsl */ - ` - uniform vec3 color; - uniform sampler2D tDiffuse; - uniform sampler2D tDepth; - uniform float maxDistance; - uniform float opacity; - uniform float fresnelCoe; - uniform float virtualCameraNear; - uniform float virtualCameraFar; - uniform mat4 virtualCameraProjectionMatrix; - uniform mat4 virtualCameraProjectionMatrixInverse; - uniform mat4 virtualCameraMatrixWorld; - uniform vec2 resolution; - varying vec4 vUv; - #include - float blendOverlay( float base, float blend ) { - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - } - vec3 blendOverlay( vec3 base, vec3 blend ) { - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - } - float getDepth( const in vec2 uv ) { - return texture2D( tDepth, uv ).x; - } - float getViewZ( const in float depth ) { - return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar ); - } - vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { - vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc - clipPosition *= clipW; //clip - return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view - } - void main() { - vec4 base = texture2DProj( tDiffuse, vUv ); - #ifdef useDepthTexture - vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy; - uv.x=1.-uv.x; - float depth = texture2DProj( tDepth, vUv ).r; - float viewZ = getViewZ( depth ); - float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3]; - vec3 viewPosition=getViewPosition( uv, depth, clipW ); - vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz; - if(worldPosition.y>maxDistance) discard; - float op=opacity; - #ifdef DISTANCE_ATTENUATION - float ratio=1.-(worldPosition.y/maxDistance); - float attenuation=ratio*ratio; - op=opacity*attenuation; - #endif - #ifdef FRESNEL - op*=fresnelCoe; - #endif - gl_FragColor = vec4( blendOverlay( base.rgb, color ), op ); - #else - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - #endif - } - ` -}; +var reactReconcilerConstants_development = {}; /** - * Based on "A Practical Analytic Model for Daylight" - * aka The Preetham Model, the de facto standard analytic skydome model - * https://www.researchgate.net/publication/220720443_A_Practical_Analytic_Model_for_Daylight - * - * First implemented by Simon Wallner - * http://www.simonwallner.at/projects/atmospheric-scattering - * - * Improved by Martin Upitis - * http://blenderartists.org/forum/showthread.php?245954-preethams-sky-impementation-HDR + * @license React + * react-reconciler-constants.development.js * - * Three.js integration by zz85 http://twitter.com/blurspline - */ - -class Sky extends Mesh { - constructor() { - super(new BoxGeometry(1, 1, 1), Sky.material); - } - -} - -_defineProperty$1(Sky, "SkyShader", { - uniforms: { - turbidity: { - value: 2 - }, - rayleigh: { - value: 1 - }, - mieCoefficient: { - value: 0.005 - }, - mieDirectionalG: { - value: 0.8 - }, - sunPosition: { - value: new Vector3() - }, - up: { - value: new Vector3(0, 1, 0) - } - }, - vertexShader: ['uniform vec3 sunPosition;', 'uniform float rayleigh;', 'uniform float turbidity;', 'uniform float mieCoefficient;', 'uniform vec3 up;', 'varying vec3 vWorldPosition;', 'varying vec3 vSunDirection;', 'varying float vSunfade;', 'varying vec3 vBetaR;', 'varying vec3 vBetaM;', 'varying float vSunE;', // constants for atmospheric scattering - 'const float e = 2.71828182845904523536028747135266249775724709369995957;', 'const float pi = 3.141592653589793238462643383279502884197169;', // wavelength of used primaries, according to preetham - 'const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );', // this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function: - // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) - 'const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );', // mie stuff - // K coefficient for the primaries - 'const float v = 4.0;', 'const vec3 K = vec3( 0.686, 0.678, 0.666 );', // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K - 'const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );', // earth shadow hack - // cutoffAngle = pi / 1.95; - 'const float cutoffAngle = 1.6110731556870734;', 'const float steepness = 1.5;', 'const float EE = 1000.0;', 'float sunIntensity( float zenithAngleCos ) {', ' zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );', ' return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );', '}', 'vec3 totalMie( float T ) {', ' float c = ( 0.2 * T ) * 10E-18;', ' return 0.434 * c * MieConst;', '}', 'void main() {', ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );', ' vWorldPosition = worldPosition.xyz;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', ' gl_Position.z = gl_Position.w;', // set z to camera.far - ' vSunDirection = normalize( sunPosition );', ' vSunE = sunIntensity( dot( vSunDirection, up ) );', ' vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );', ' float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );', // extinction (absorbtion + out scattering) - // rayleigh coefficients - ' vBetaR = totalRayleigh * rayleighCoefficient;', // mie coefficients - ' vBetaM = totalMie( turbidity ) * mieCoefficient;', '}'].join('\n'), - fragmentShader: ['varying vec3 vWorldPosition;', 'varying vec3 vSunDirection;', 'varying float vSunfade;', 'varying vec3 vBetaR;', 'varying vec3 vBetaM;', 'varying float vSunE;', 'uniform float mieDirectionalG;', 'uniform vec3 up;', 'const vec3 cameraPos = vec3( 0.0, 0.0, 0.0 );', // constants for atmospheric scattering - 'const float pi = 3.141592653589793238462643383279502884197169;', 'const float n = 1.0003;', // refractive index of air - 'const float N = 2.545E25;', // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius) - // optical length at zenith for molecules - 'const float rayleighZenithLength = 8.4E3;', 'const float mieZenithLength = 1.25E3;', // 66 arc seconds -> degrees, and the cosine of that - 'const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;', // 3.0 / ( 16.0 * pi ) - 'const float THREE_OVER_SIXTEENPI = 0.05968310365946075;', // 1.0 / ( 4.0 * pi ) - 'const float ONE_OVER_FOURPI = 0.07957747154594767;', 'float rayleighPhase( float cosTheta ) {', ' return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );', '}', 'float hgPhase( float cosTheta, float g ) {', ' float g2 = pow( g, 2.0 );', ' float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );', ' return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );', '}', 'void main() {', ' vec3 direction = normalize( vWorldPosition - cameraPos );', // optical length - // cutoff angle at 90 to avoid singularity in next formula. - ' float zenithAngle = acos( max( 0.0, dot( up, direction ) ) );', ' float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );', ' float sR = rayleighZenithLength * inverse;', ' float sM = mieZenithLength * inverse;', // combined extinction factor - ' vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );', // in scattering - ' float cosTheta = dot( direction, vSunDirection );', ' float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );', ' vec3 betaRTheta = vBetaR * rPhase;', ' float mPhase = hgPhase( cosTheta, mieDirectionalG );', ' vec3 betaMTheta = vBetaM * mPhase;', ' vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );', ' Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) );', // nightsky - ' float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]', ' float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]', ' vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );', ' vec3 L0 = vec3( 0.1 ) * Fex;', // composition + solar disc - ' float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta );', ' L0 += ( vSunE * 19000.0 * Fex ) * sundisk;', ' vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );', ' vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );', ' gl_FragColor = vec4( retColor, 1.0 );', '#include ', '#include ', '}'].join('\n') -}); - -_defineProperty$1(Sky, "material", new ShaderMaterial({ - name: 'SkyShader', - fragmentShader: Sky.SkyShader.fragmentShader, - vertexShader: Sky.SkyShader.vertexShader, - uniforms: UniformsUtils.clone(Sky.SkyShader.uniforms), - side: BackSide, - depthWrite: false -})); - -/** - * References: - * http://www.valvesoftware.com/publications/2010/siggraph2010_vlachos_waterflow.pdf - * http://graphicsrunner.blogspot.de/2010/08/water-using-flow-maps.html + * Copyright (c) Facebook, Inc. and its affiliates. * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -class Water2 extends Mesh { - constructor(geometry, options = {}) { - super(geometry); - this.type = 'Water'; - const scope = this; - const color = options.color !== undefined ? new Color(options.color) : new Color(0xffffff); - const textureWidth = options.textureWidth || 512; - const textureHeight = options.textureHeight || 512; - const clipBias = options.clipBias || 0; - const flowDirection = options.flowDirection || new Vector2(1, 0); - const flowSpeed = options.flowSpeed || 0.03; - const reflectivity = options.reflectivity || 0.02; - const scale = options.scale || 1; - const shader = options.shader || Water.WaterShader; - const encoding = options.encoding !== undefined ? options.encoding : LinearEncoding; - const textureLoader = new TextureLoader(); - const flowMap = options.flowMap || undefined; - const normalMap0 = options.normalMap0 || textureLoader.load('textures/water/Water_1_M_Normal.jpg'); - const normalMap1 = options.normalMap1 || textureLoader.load('textures/water/Water_2_M_Normal.jpg'); - const cycle = 0.15; // a cycle of a flow map phase - - const halfCycle = cycle * 0.5; - const textureMatrix = new Matrix4(); - const clock = new Clock(); // internal components - - if (Reflector === undefined) { - console.error('THREE.Water: Required component Reflector not found.'); - return; - } - - if (Refractor === undefined) { - console.error('THREE.Water: Required component Refractor not found.'); - return; - } - - const reflector = new Reflector(geometry, { - textureWidth: textureWidth, - textureHeight: textureHeight, - clipBias: clipBias, - encoding: encoding - }); - const refractor = new Refractor(geometry, { - textureWidth: textureWidth, - textureHeight: textureHeight, - clipBias: clipBias, - encoding: encoding - }); - reflector.matrixAutoUpdate = false; - refractor.matrixAutoUpdate = false; // material - - this.material = new ShaderMaterial({ - uniforms: UniformsUtils.merge([UniformsLib['fog'], shader.uniforms]), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - transparent: true, - fog: true - }); - - if (flowMap !== undefined) { - this.material.defines.USE_FLOWMAP = ''; - this.material.uniforms['tFlowMap'] = { - type: 't', - value: flowMap - }; - } else { - this.material.uniforms['flowDirection'] = { - type: 'v2', - value: flowDirection - }; - } // maps - - - normalMap0.wrapS = normalMap0.wrapT = RepeatWrapping; - normalMap1.wrapS = normalMap1.wrapT = RepeatWrapping; - this.material.uniforms['tReflectionMap'].value = reflector.getRenderTarget().texture; - this.material.uniforms['tRefractionMap'].value = refractor.getRenderTarget().texture; - this.material.uniforms['tNormalMap0'].value = normalMap0; - this.material.uniforms['tNormalMap1'].value = normalMap1; // water - - this.material.uniforms['color'].value = color; - this.material.uniforms['reflectivity'].value = reflectivity; - this.material.uniforms['textureMatrix'].value = textureMatrix; // inital values - - this.material.uniforms['config'].value.x = 0; // flowMapOffset0 - - this.material.uniforms['config'].value.y = halfCycle; // flowMapOffset1 - - this.material.uniforms['config'].value.z = halfCycle; // halfCycle - - this.material.uniforms['config'].value.w = scale; // scale - // functions - - function updateTextureMatrix(camera) { - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); - textureMatrix.multiply(camera.projectionMatrix); - textureMatrix.multiply(camera.matrixWorldInverse); - textureMatrix.multiply(scope.matrixWorld); - } - - function updateFlow() { - const delta = clock.getDelta(); - const config = scope.material.uniforms['config']; - config.value.x += flowSpeed * delta; // flowMapOffset0 - - config.value.y = config.value.x + halfCycle; // flowMapOffset1 - // Important: The distance between offsets should be always the value of "halfCycle". - // Moreover, both offsets should be in the range of [ 0, cycle ]. - // This approach ensures a smooth water flow and avoids "reset" effects. - - if (config.value.x >= cycle) { - config.value.x = 0; - config.value.y = halfCycle; - } else if (config.value.y >= cycle) { - config.value.y = config.value.y - cycle; - } - } // - - - this.onBeforeRender = function (renderer, scene, camera) { - updateTextureMatrix(camera); - updateFlow(); - scope.visible = false; - reflector.matrixWorld.copy(scope.matrixWorld); - refractor.matrixWorld.copy(scope.matrixWorld); - reflector.onBeforeRender(renderer, scene, camera); - refractor.onBeforeRender(renderer, scene, camera); - scope.visible = true; - }; - } - -} - -Water2.prototype.isWater = true; -Water2.WaterShader = { - uniforms: { - color: { - type: 'c', - value: null - }, - reflectivity: { - type: 'f', - value: 0 - }, - tReflectionMap: { - type: 't', - value: null - }, - tRefractionMap: { - type: 't', - value: null - }, - tNormalMap0: { - type: 't', - value: null - }, - tNormalMap1: { - type: 't', - value: null - }, - textureMatrix: { - type: 'm4', - value: null - }, - config: { - type: 'v4', - value: new Vector4() - } - }, - vertexShader: - /* glsl */ - ` - - #include - #include - #include - - uniform mat4 textureMatrix; - - varying vec4 vCoord; - varying vec2 vUv; - varying vec3 vToEye; - - void main() { - - vUv = uv; - vCoord = textureMatrix * vec4( position, 1.0 ); - - vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); - vToEye = cameraPosition - worldPosition.xyz; - - vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex - gl_Position = projectionMatrix * mvPosition; - - #include - #include - - }`, - fragmentShader: - /* glsl */ - ` - - #include - #include - #include - - uniform sampler2D tReflectionMap; - uniform sampler2D tRefractionMap; - uniform sampler2D tNormalMap0; - uniform sampler2D tNormalMap1; - - #ifdef USE_FLOWMAP - uniform sampler2D tFlowMap; - #else - uniform vec2 flowDirection; - #endif - - uniform vec3 color; - uniform float reflectivity; - uniform vec4 config; - - varying vec4 vCoord; - varying vec2 vUv; - varying vec3 vToEye; - - void main() { +var hasRequiredReactReconcilerConstants_development; - #include +function requireReactReconcilerConstants_development () { + if (hasRequiredReactReconcilerConstants_development) return reactReconcilerConstants_development; + hasRequiredReactReconcilerConstants_development = 1; - float flowMapOffset0 = config.x; - float flowMapOffset1 = config.y; - float halfCycle = config.z; - float scale = config.w; + if (process.env.NODE_ENV !== "production") { + (function() { - vec3 toEye = normalize( vToEye ); + var SyncLane = + /* */ + 1; + var InputContinuousLane = + /* */ + 4; + var DefaultLane = + /* */ + 16; + var IdleLane = + /* */ + 536870912; - // determine flow direction - vec2 flow; - #ifdef USE_FLOWMAP - flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0; - #else - flow = flowDirection; - #endif - flow.x *= - 1.0; + var DiscreteEventPriority = SyncLane; + var ContinuousEventPriority = InputContinuousLane; + var DefaultEventPriority = DefaultLane; + var IdleEventPriority = IdleLane; - // sample normal maps (distort uvs with flowdata) - vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 ); - vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 ); + var LegacyRoot = 0; + var ConcurrentRoot = 1; - // linear interpolate to get the final normal color - float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle; - vec4 normalColor = mix( normalColor0, normalColor1, flowLerp ); + reactReconcilerConstants_development.ConcurrentRoot = ConcurrentRoot; + reactReconcilerConstants_development.ContinuousEventPriority = ContinuousEventPriority; + reactReconcilerConstants_development.DefaultEventPriority = DefaultEventPriority; + reactReconcilerConstants_development.DiscreteEventPriority = DiscreteEventPriority; + reactReconcilerConstants_development.IdleEventPriority = IdleEventPriority; + reactReconcilerConstants_development.LegacyRoot = LegacyRoot; + })(); + } + return reactReconcilerConstants_development; +} - // calculate normal vector - vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) ); +(function (module) { - // calculate the fresnel term to blend reflection and refraction maps - float theta = max( dot( toEye, normal ), 0.0 ); - float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 ); + if (process.env.NODE_ENV === 'production') { + module.exports = requireReactReconcilerConstants_production_min(); + } else { + module.exports = requireReactReconcilerConstants_development(); + } +} (constants)); - // calculate final uv coords - vec3 coord = vCoord.xyz / vCoord.w; - vec2 uv = coord.xy + coord.z * normal.xz * 0.05; +function createStore$3(createState) { + let state; + const listeners = /* @__PURE__ */ new Set(); + const setState = (partial, replace) => { + const nextState = typeof partial === "function" ? partial(state) : partial; + if (nextState !== state) { + const previousState = state; + state = replace ? nextState : Object.assign({}, state, nextState); + listeners.forEach((listener) => listener(state, previousState)); + } + }; + const getState = () => state; + const subscribeWithSelector = (listener, selector = getState, equalityFn = Object.is) => { + console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware"); + let currentSlice = selector(state); + function listenerToAdd() { + const nextSlice = selector(state); + if (!equalityFn(currentSlice, nextSlice)) { + const previousSlice = currentSlice; + listener(currentSlice = nextSlice, previousSlice); + } + } + listeners.add(listenerToAdd); + return () => listeners.delete(listenerToAdd); + }; + const subscribe = (listener, selector, equalityFn) => { + if (selector || equalityFn) { + return subscribeWithSelector(listener, selector, equalityFn); + } + listeners.add(listener); + return () => listeners.delete(listener); + }; + const destroy = () => listeners.clear(); + const api = { setState, getState, subscribe, destroy }; + state = createState(setState, getState, api); + return api; +} - vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) ); - vec4 refractColor = texture2D( tRefractionMap, uv ); +const isSSR$3 = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); +const useIsomorphicLayoutEffect$2 = isSSR$3 ? React.useEffect : React.useLayoutEffect; +function create$4(createState) { + const api = typeof createState === "function" ? createStore$3(createState) : createState; + const useStore = (selector = api.getState, equalityFn = Object.is) => { + const [, forceUpdate] = React.useReducer((c) => c + 1, 0); + const state = api.getState(); + const stateRef = React.useRef(state); + const selectorRef = React.useRef(selector); + const equalityFnRef = React.useRef(equalityFn); + const erroredRef = React.useRef(false); + const currentSliceRef = React.useRef(); + if (currentSliceRef.current === void 0) { + currentSliceRef.current = selector(state); + } + let newStateSlice; + let hasNewStateSlice = false; + if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) { + newStateSlice = selector(state); + hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice); + } + useIsomorphicLayoutEffect$2(() => { + if (hasNewStateSlice) { + currentSliceRef.current = newStateSlice; + } + stateRef.current = state; + selectorRef.current = selector; + equalityFnRef.current = equalityFn; + erroredRef.current = false; + }); + const stateBeforeSubscriptionRef = React.useRef(state); + useIsomorphicLayoutEffect$2(() => { + const listener = () => { + try { + const nextState = api.getState(); + const nextStateSlice = selectorRef.current(nextState); + if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) { + stateRef.current = nextState; + currentSliceRef.current = nextStateSlice; + forceUpdate(); + } + } catch (error) { + erroredRef.current = true; + forceUpdate(); + } + }; + const unsubscribe = api.subscribe(listener); + if (api.getState() !== stateBeforeSubscriptionRef.current) { + listener(); + } + return unsubscribe; + }, []); + const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current; + React.useDebugValue(sliceToReturn); + return sliceToReturn; + }; + Object.assign(useStore, api); + useStore[Symbol.iterator] = function() { + console.warn("[useStore, api] = create() is deprecated and will be removed in v4"); + const items = [useStore, api]; + return { + next() { + const done = items.length <= 0; + return { value: items.shift(), done }; + } + }; + }; + return useStore; +} - // multiply water color with the mix of both textures - gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance ); +var reactReconciler = {exports: {}}; - #include - #include - #include +var scheduler$1 = {exports: {}}; - }` -}; +var scheduler_production_min = {}; /** - * This class generates custom mipmaps for a roughness map by encoding the lost variation in the - * normal map mip levels as increased roughness in the corresponding roughness mip levels. This - * helps with rendering accuracy for MeshStandardMaterial, and also helps with anti-aliasing when - * using PMREM. If the normal map is larger than the roughness map, the roughness map will be - * enlarged to match the dimensions of the normal map. + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -var _mipmapMaterial = _getMipmapMaterial(); - -var _mesh = new Mesh(new PlaneGeometry(2, 2), _mipmapMaterial); - -var _flatCamera = new OrthographicCamera(0, 1, 0, 1, 0, 1); - -var _tempTarget = null; -var _renderer = null; - -function RoughnessMipmapper(renderer) { - _renderer = renderer; +var hasRequiredScheduler_production_min; - _renderer.compile(_mesh, _flatCamera); +function requireScheduler_production_min () { + if (hasRequiredScheduler_production_min) return scheduler_production_min; + hasRequiredScheduler_production_min = 1; + (function (exports) { +function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} + function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; + "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} + function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; + function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; + exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; +} (scheduler_production_min)); + return scheduler_production_min; } -RoughnessMipmapper.prototype = { - constructor: RoughnessMipmapper, - generateMipmaps: function (material) { - if ('roughnessMap' in material === false) return; - var { - roughnessMap, - normalMap - } = material; - - if (roughnessMap === null || normalMap === null || !roughnessMap.generateMipmaps || material.userData.roughnessUpdated) { - return; - } - - material.userData.roughnessUpdated = true; - var width = Math.max(roughnessMap.image.width, normalMap.image.width); - var height = Math.max(roughnessMap.image.height, normalMap.image.height); - if (!MathUtils.isPowerOfTwo(width) || !MathUtils.isPowerOfTwo(height)) return; - - var oldTarget = _renderer.getRenderTarget(); - - var autoClear = _renderer.autoClear; - _renderer.autoClear = false; - - if (_tempTarget === null || _tempTarget.width !== width || _tempTarget.height !== height) { - if (_tempTarget !== null) _tempTarget.dispose(); - _tempTarget = new WebGLRenderTarget(width, height, { - depthBuffer: false - }); - _tempTarget.scissorTest = true; - } +var scheduler_development = {}; - if (width !== roughnessMap.image.width || height !== roughnessMap.image.height) { - var params = { - wrapS: roughnessMap.wrapS, - wrapT: roughnessMap.wrapT, - magFilter: roughnessMap.magFilter, - minFilter: roughnessMap.minFilter, - depthBuffer: false - }; - var newRoughnessTarget = new WebGLRenderTarget(width, height, params); - newRoughnessTarget.texture.generateMipmaps = true; // Setting the render target causes the memory to be allocated. +/** + * @license React + * scheduler.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ - _renderer.setRenderTarget(newRoughnessTarget); +var hasRequiredScheduler_development; - material.roughnessMap = newRoughnessTarget.texture; - if (material.metalnessMap == roughnessMap) material.metalnessMap = material.roughnessMap; - if (material.aoMap == roughnessMap) material.aoMap = material.roughnessMap; - } +function requireScheduler_development () { + if (hasRequiredScheduler_development) return scheduler_development; + hasRequiredScheduler_development = 1; + (function (exports) { - _mipmapMaterial.uniforms.roughnessMap.value = roughnessMap; - _mipmapMaterial.uniforms.normalMap.value = normalMap; - var position = new Vector2(0, 0); - var texelSize = _mipmapMaterial.uniforms.texelSize.value; + if (process.env.NODE_ENV !== "production") { + (function() { - for (let mip = 0; width >= 1 && height >= 1; ++mip, width /= 2, height /= 2) { - // Rendering to a mip level is not allowed in webGL1. Instead we must set - // up a secondary texture to write the result to, then copy it back to the - // proper mipmap level. - texelSize.set(1.0 / width, 1.0 / height); - if (mip == 0) texelSize.set(0.0, 0.0); + /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ + if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === + 'function' + ) { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); + } + var enableSchedulerDebugging = false; + var enableProfiling = false; + var frameYieldMs = 5; - _tempTarget.viewport.set(position.x, position.y, width, height); + function push(heap, node) { + var index = heap.length; + heap.push(node); + siftUp(heap, node, index); + } + function peek(heap) { + return heap.length === 0 ? null : heap[0]; + } + function pop(heap) { + if (heap.length === 0) { + return null; + } - _tempTarget.scissor.set(position.x, position.y, width, height); + var first = heap[0]; + var last = heap.pop(); - _renderer.setRenderTarget(_tempTarget); + if (last !== first) { + heap[0] = last; + siftDown(heap, last, 0); + } - _renderer.render(_mesh, _flatCamera); + return first; + } - _renderer.copyFramebufferToTexture(position, material.roughnessMap, mip); + function siftUp(heap, node, i) { + var index = i; - _mipmapMaterial.uniforms.roughnessMap.value = material.roughnessMap; - } + while (index > 0) { + var parentIndex = index - 1 >>> 1; + var parent = heap[parentIndex]; - if (roughnessMap !== material.roughnessMap) roughnessMap.dispose(); + if (compare(parent, node) > 0) { + // The parent is larger. Swap positions. + heap[parentIndex] = node; + heap[index] = parent; + index = parentIndex; + } else { + // The parent is smaller. Exit. + return; + } + } + } - _renderer.setRenderTarget(oldTarget); + function siftDown(heap, node, i) { + var index = i; + var length = heap.length; + var halfLength = length >>> 1; - _renderer.autoClear = autoClear; - }, - dispose: function () { - _mipmapMaterial.dispose(); + while (index < halfLength) { + var leftIndex = (index + 1) * 2 - 1; + var left = heap[leftIndex]; + var rightIndex = leftIndex + 1; + var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. - _mesh.geometry.dispose(); + if (compare(left, node) < 0) { + if (rightIndex < length && compare(right, left) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + heap[index] = left; + heap[leftIndex] = node; + index = leftIndex; + } + } else if (rightIndex < length && compare(right, node) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + // Neither child is smaller. Exit. + return; + } + } + } - if (_tempTarget != null) _tempTarget.dispose(); - } -}; + function compare(a, b) { + // Compare sort index first, then task id. + var diff = a.sortIndex - b.sortIndex; + return diff !== 0 ? diff : a.id - b.id; + } -function _getMipmapMaterial() { - var shaderMaterial = new RawShaderMaterial({ - uniforms: { - roughnessMap: { - value: null - }, - normalMap: { - value: null - }, - texelSize: { - value: new Vector2(1, 1) - } - }, - vertexShader: - /* glsl */ - ` - precision mediump float; - precision mediump int; + // TODO: Use symbols? + var ImmediatePriority = 1; + var UserBlockingPriority = 2; + var NormalPriority = 3; + var LowPriority = 4; + var IdlePriority = 5; - attribute vec3 position; - attribute vec2 uv; + function markTaskErrored(task, ms) { + } - varying vec2 vUv; + /* eslint-disable no-var */ - void main() { + var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; - vUv = uv; + if (hasPerformanceNow) { + var localPerformance = performance; - gl_Position = vec4( position, 1.0 ); + exports.unstable_now = function () { + return localPerformance.now(); + }; + } else { + var localDate = Date; + var initialTime = localDate.now(); - } - `, - fragmentShader: - /* glsl */ - ` - precision mediump float; - precision mediump int; + exports.unstable_now = function () { + return localDate.now() - initialTime; + }; + } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. + // Math.pow(2, 30) - 1 + // 0b111111111111111111111111111111 - varying vec2 vUv; - uniform sampler2D roughnessMap; - uniform sampler2D normalMap; - uniform vec2 texelSize; + var maxSigned31BitInt = 1073741823; // Times out immediately - #define ENVMAP_TYPE_CUBE_UV + var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out - vec4 envMapTexelToLinear( vec4 a ) { return a; } + var USER_BLOCKING_PRIORITY_TIMEOUT = 250; + var NORMAL_PRIORITY_TIMEOUT = 5000; + var LOW_PRIORITY_TIMEOUT = 10000; // Never times out - #include + var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap - float roughnessToVariance( float roughness ) { + var taskQueue = []; + var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. - float variance = 0.0; + var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. + var currentTask = null; + var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. - if ( roughness >= r1 ) { + var isPerformingWork = false; + var isHostCallbackScheduled = false; + var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. - variance = ( r0 - roughness ) * ( v1 - v0 ) / ( r0 - r1 ) + v0; + var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; + var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; + var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom - } else if ( roughness >= r4 ) { + typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; - variance = ( r1 - roughness ) * ( v4 - v1 ) / ( r1 - r4 ) + v1; + function advanceTimers(currentTime) { + // Check for tasks that are no longer delayed and add them to the queue. + var timer = peek(timerQueue); - } else if ( roughness >= r5 ) { + while (timer !== null) { + if (timer.callback === null) { + // Timer was cancelled. + pop(timerQueue); + } else if (timer.startTime <= currentTime) { + // Timer fired. Transfer to the task queue. + pop(timerQueue); + timer.sortIndex = timer.expirationTime; + push(taskQueue, timer); + } else { + // Remaining timers are pending. + return; + } - variance = ( r4 - roughness ) * ( v5 - v4 ) / ( r4 - r5 ) + v4; + timer = peek(timerQueue); + } + } - } else { + function handleTimeout(currentTime) { + isHostTimeoutScheduled = false; + advanceTimers(currentTime); - float roughness2 = roughness * roughness; + if (!isHostCallbackScheduled) { + if (peek(taskQueue) !== null) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } else { + var firstTimer = peek(timerQueue); - variance = 1.79 * roughness2 * roughness2; + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + } + } + } - } + function flushWork(hasTimeRemaining, initialTime) { - return variance; - } + isHostCallbackScheduled = false; - float varianceToRoughness( float variance ) { + if (isHostTimeoutScheduled) { + // We scheduled a timeout but it's no longer needed. Cancel it. + isHostTimeoutScheduled = false; + cancelHostTimeout(); + } - float roughness = 0.0; + isPerformingWork = true; + var previousPriorityLevel = currentPriorityLevel; - if ( variance >= v1 ) { + try { + var currentTime; if (enableProfiling) ; else { + // No catch in prod code path. + return workLoop(hasTimeRemaining, initialTime); + } + } finally { + currentTask = null; + currentPriorityLevel = previousPriorityLevel; + isPerformingWork = false; + } + } - roughness = ( v0 - variance ) * ( r1 - r0 ) / ( v0 - v1 ) + r0; + function workLoop(hasTimeRemaining, initialTime) { + var currentTime = initialTime; + advanceTimers(currentTime); + currentTask = peek(taskQueue); - } else if ( variance >= v4 ) { + while (currentTask !== null && !(enableSchedulerDebugging )) { + if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { + // This currentTask hasn't expired, and we've reached the deadline. + break; + } - roughness = ( v1 - variance ) * ( r4 - r1 ) / ( v1 - v4 ) + r1; + var callback = currentTask.callback; - } else if ( variance >= v5 ) { + if (typeof callback === 'function') { + currentTask.callback = null; + currentPriorityLevel = currentTask.priorityLevel; + var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; - roughness = ( v4 - variance ) * ( r5 - r4 ) / ( v4 - v5 ) + r4; + var continuationCallback = callback(didUserCallbackTimeout); + currentTime = exports.unstable_now(); - } else { + if (typeof continuationCallback === 'function') { + currentTask.callback = continuationCallback; + } else { - roughness = pow( 0.559 * variance, 0.25 ); // 0.559 = 1.0 / 1.79 + if (currentTask === peek(taskQueue)) { + pop(taskQueue); + } + } - } + advanceTimers(currentTime); + } else { + pop(taskQueue); + } - return roughness; + currentTask = peek(taskQueue); + } // Return whether there's additional work - } - void main() { + if (currentTask !== null) { + return true; + } else { + var firstTimer = peek(timerQueue); - gl_FragColor = texture2D( roughnessMap, vUv, - 1.0 ); + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } - if ( texelSize.x == 0.0 ) return; + return false; + } + } - float roughness = gl_FragColor.g; + function unstable_runWithPriority(priorityLevel, eventHandler) { + switch (priorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + case LowPriority: + case IdlePriority: + break; - float variance = roughnessToVariance( roughness ); + default: + priorityLevel = NormalPriority; + } - vec3 avgNormal; + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; - for ( float x = - 1.0; x < 2.0; x += 2.0 ) { + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } - for ( float y = - 1.0; y < 2.0; y += 2.0 ) { + function unstable_next(eventHandler) { + var priorityLevel; - vec2 uv = vUv + vec2( x, y ) * 0.25 * texelSize; + switch (currentPriorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + // Shift down to normal priority + priorityLevel = NormalPriority; + break; - avgNormal += normalize( texture2D( normalMap, uv, - 1.0 ).xyz - 0.5 ); + default: + // Anything lower than normal priority should remain at the current level. + priorityLevel = currentPriorityLevel; + break; + } - } + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; - } + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } - variance += 1.0 - 0.25 * length( avgNormal ); + function unstable_wrapCallback(callback) { + var parentPriorityLevel = currentPriorityLevel; + return function () { + // This is a fork of runWithPriority, inlined for performance. + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = parentPriorityLevel; - gl_FragColor.g = varianceToRoughness( variance ); + try { + return callback.apply(this, arguments); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + }; + } - } - `, - blending: NoBlending, - depthTest: false, - depthWrite: false - }); - shaderMaterial.type = 'RoughnessMipmapper'; - return shaderMaterial; -} + function unstable_scheduleCallback(priorityLevel, callback, options) { + var currentTime = exports.unstable_now(); + var startTime; -({ - retarget: function () { - var pos = new Vector3(), - quat = new Quaternion(), - scale = new Vector3(), - bindBoneMatrix = new Matrix4(), - relativeMatrix = new Matrix4(), - globalMatrix = new Matrix4(); - return function (target, source, options) { - options = options || {}; - options.preserveMatrix = options.preserveMatrix !== undefined ? options.preserveMatrix : true; - options.preservePosition = options.preservePosition !== undefined ? options.preservePosition : true; - options.preserveHipPosition = options.preserveHipPosition !== undefined ? options.preserveHipPosition : false; - options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false; - options.hip = options.hip !== undefined ? options.hip : 'hip'; - options.names = options.names || {}; - var sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones(source), - bones = target.isObject3D ? target.skeleton.bones : this.getBones(target), - bindBones, - bone, - name, - boneTo, - bonesPosition, - i; // reset bones - - if (target.isObject3D) { - target.skeleton.pose(); - } else { - options.useTargetMatrix = true; - options.preserveMatrix = false; - } + if (typeof options === 'object' && options !== null) { + var delay = options.delay; - if (options.preservePosition) { - bonesPosition = []; + if (typeof delay === 'number' && delay > 0) { + startTime = currentTime + delay; + } else { + startTime = currentTime; + } + } else { + startTime = currentTime; + } - for (i = 0; i < bones.length; i++) { - bonesPosition.push(bones[i].position.clone()); - } - } + var timeout; - if (options.preserveMatrix) { - // reset matrix - target.updateMatrixWorld(); - target.matrixWorld.identity(); // reset children matrix + switch (priorityLevel) { + case ImmediatePriority: + timeout = IMMEDIATE_PRIORITY_TIMEOUT; + break; - for (i = 0; i < target.children.length; ++i) { - target.children[i].updateMatrixWorld(true); - } - } + case UserBlockingPriority: + timeout = USER_BLOCKING_PRIORITY_TIMEOUT; + break; - if (options.offsets) { - bindBones = []; + case IdlePriority: + timeout = IDLE_PRIORITY_TIMEOUT; + break; - for (i = 0; i < bones.length; ++i) { - bone = bones[i]; - name = options.names[bone.name] || bone.name; + case LowPriority: + timeout = LOW_PRIORITY_TIMEOUT; + break; - if (options.offsets && options.offsets[name]) { - bone.matrix.multiply(options.offsets[name]); - bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); - bone.updateMatrixWorld(); - } + case NormalPriority: + default: + timeout = NORMAL_PRIORITY_TIMEOUT; + break; + } - bindBones.push(bone.matrixWorld.clone()); - } - } + var expirationTime = startTime + timeout; + var newTask = { + id: taskIdCounter++, + callback: callback, + priorityLevel: priorityLevel, + startTime: startTime, + expirationTime: expirationTime, + sortIndex: -1 + }; - for (i = 0; i < bones.length; ++i) { - bone = bones[i]; - name = options.names[bone.name] || bone.name; - boneTo = this.getBoneByName(name, sourceBones); - globalMatrix.copy(bone.matrixWorld); + if (startTime > currentTime) { + // This is a delayed task. + newTask.sortIndex = startTime; + push(timerQueue, newTask); - if (boneTo) { - boneTo.updateMatrixWorld(); + if (peek(taskQueue) === null && newTask === peek(timerQueue)) { + // All tasks are delayed, and this is the task with the earliest delay. + if (isHostTimeoutScheduled) { + // Cancel an existing timeout. + cancelHostTimeout(); + } else { + isHostTimeoutScheduled = true; + } // Schedule a timeout. - if (options.useTargetMatrix) { - relativeMatrix.copy(boneTo.matrixWorld); - } else { - relativeMatrix.copy(target.matrixWorld).invert(); - relativeMatrix.multiply(boneTo.matrixWorld); - } // ignore scale to extract rotation + requestHostTimeout(handleTimeout, startTime - currentTime); + } + } else { + newTask.sortIndex = expirationTime; + push(taskQueue, newTask); + // wait until the next time we yield. - scale.setFromMatrixScale(relativeMatrix); - relativeMatrix.scale(scale.set(1 / scale.x, 1 / scale.y, 1 / scale.z)); // apply to global matrix - globalMatrix.makeRotationFromQuaternion(quat.setFromRotationMatrix(relativeMatrix)); + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } - if (target.isObject3D) { - var boneIndex = bones.indexOf(bone), - wBindMatrix = bindBones ? bindBones[boneIndex] : bindBoneMatrix.copy(target.skeleton.boneInverses[boneIndex]).invert(); - globalMatrix.multiply(wBindMatrix); - } + return newTask; + } - globalMatrix.copyPosition(relativeMatrix); - } + function unstable_pauseExecution() { + } - if (bone.parent && bone.parent.isBone) { - bone.matrix.copy(bone.parent.matrixWorld).invert(); - bone.matrix.multiply(globalMatrix); - } else { - bone.matrix.copy(globalMatrix); - } + function unstable_continueExecution() { - if (options.preserveHipPosition && name === options.hip) { - bone.matrix.setPosition(pos.set(0, bone.position.y, 0)); - } + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } - bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); - bone.updateMatrixWorld(); - } + function unstable_getFirstCallbackNode() { + return peek(taskQueue); + } - if (options.preservePosition) { - for (i = 0; i < bones.length; ++i) { - bone = bones[i]; - name = options.names[bone.name] || bone.name; + function unstable_cancelCallback(task) { + // remove from the queue because you can't remove arbitrary nodes from an + // array based heap, only the first one.) - if (name !== options.hip) { - bone.position.copy(bonesPosition[i]); - } - } - } - if (options.preserveMatrix) { - // restore matrix - target.updateMatrixWorld(true); - } - }; - }(), - retargetClip: function (target, source, clip, options) { - options = options || {}; - options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false; - options.fps = options.fps !== undefined ? options.fps : 30; - options.names = options.names || []; - - if (!source.isObject3D) { - source = this.getHelperFromSkeleton(source); - } + task.callback = null; + } - var numFrames = Math.round(clip.duration * (options.fps / 1000) * 1000), - delta = 1 / options.fps, - convertedTracks = [], - mixer = new AnimationMixer(source), - bones = this.getBones(target.skeleton), - boneDatas = [], - positionOffset, - bone, - boneTo, - boneData, - name, - i, - j; - mixer.clipAction(clip).play(); - mixer.update(0); - source.updateMatrixWorld(); - - for (i = 0; i < numFrames; ++i) { - var time = i * delta; - this.retarget(target, source, options); - - for (j = 0; j < bones.length; ++j) { - name = options.names[bones[j].name] || bones[j].name; - boneTo = this.getBoneByName(name, source.skeleton); - - if (boneTo) { - bone = bones[j]; - boneData = boneDatas[j] = boneDatas[j] || { - bone: bone - }; + function unstable_getCurrentPriorityLevel() { + return currentPriorityLevel; + } - if (options.hip === name) { - if (!boneData.pos) { - boneData.pos = { - times: new Float32Array(numFrames), - values: new Float32Array(numFrames * 3) - }; - } + var isMessageLoopRunning = false; + var scheduledHostCallback = null; + var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main + // thread, like user events. By default, it yields multiple times per frame. + // It does not attempt to align with frame boundaries, since most tasks don't + // need to be frame aligned; for those that do, use requestAnimationFrame. - if (options.useFirstFramePosition) { - if (i === 0) { - positionOffset = bone.position.clone(); - } + var frameInterval = frameYieldMs; + var startTime = -1; - bone.position.sub(positionOffset); - } + function shouldYieldToHost() { + var timeElapsed = exports.unstable_now() - startTime; - boneData.pos.times[i] = time; - bone.position.toArray(boneData.pos.values, i * 3); - } + if (timeElapsed < frameInterval) { + // The main thread has only been blocked for a really short amount of time; + // smaller than a single frame. Don't yield yet. + return false; + } // The main thread has been blocked for a non-negligible amount of time. We - if (!boneData.quat) { - boneData.quat = { - times: new Float32Array(numFrames), - values: new Float32Array(numFrames * 4) - }; - } - boneData.quat.times[i] = time; - bone.quaternion.toArray(boneData.quat.values, i * 4); - } - } + return true; + } - mixer.update(delta); - source.updateMatrixWorld(); - } + function requestPaint() { - for (i = 0; i < boneDatas.length; ++i) { - boneData = boneDatas[i]; + } - if (boneData) { - if (boneData.pos) { - convertedTracks.push(new VectorKeyframeTrack('.bones[' + boneData.bone.name + '].position', boneData.pos.times, boneData.pos.values)); - } + function forceFrameRate(fps) { + if (fps < 0 || fps > 125) { + // Using console['error'] to evade Babel and ESLint + console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); + return; + } - convertedTracks.push(new QuaternionKeyframeTrack('.bones[' + boneData.bone.name + '].quaternion', boneData.quat.times, boneData.quat.values)); - } - } + if (fps > 0) { + frameInterval = Math.floor(1000 / fps); + } else { + // reset the framerate + frameInterval = frameYieldMs; + } + } - mixer.uncacheAction(clip); - return new AnimationClip(clip.name, -1, convertedTracks); - }, - getHelperFromSkeleton: function (skeleton) { - var source = new SkeletonHelper(skeleton.bones[0]); - source.skeleton = skeleton; - return source; - }, - getSkeletonOffsets: function () { - var targetParentPos = new Vector3(), - targetPos = new Vector3(), - sourceParentPos = new Vector3(), - sourcePos = new Vector3(), - targetDir = new Vector2(), - sourceDir = new Vector2(); - return function (target, source, options) { - options = options || {}; - options.hip = options.hip !== undefined ? options.hip : 'hip'; - options.names = options.names || {}; - - if (!source.isObject3D) { - source = this.getHelperFromSkeleton(source); - } + var performWorkUntilDeadline = function () { + if (scheduledHostCallback !== null) { + var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread + // has been blocked. - var nameKeys = Object.keys(options.names), - nameValues = Object.values(options.names), - sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones(source), - bones = target.isObject3D ? target.skeleton.bones : this.getBones(target), - offsets = [], - bone, - boneTo, - name, - i; - target.skeleton.pose(); - - for (i = 0; i < bones.length; ++i) { - bone = bones[i]; - name = options.names[bone.name] || bone.name; - boneTo = this.getBoneByName(name, sourceBones); - - if (boneTo && name !== options.hip) { - var boneParent = this.getNearestBone(bone.parent, nameKeys), - boneToParent = this.getNearestBone(boneTo.parent, nameValues); - boneParent.updateMatrixWorld(); - boneToParent.updateMatrixWorld(); - targetParentPos.setFromMatrixPosition(boneParent.matrixWorld); - targetPos.setFromMatrixPosition(bone.matrixWorld); - sourceParentPos.setFromMatrixPosition(boneToParent.matrixWorld); - sourcePos.setFromMatrixPosition(boneTo.matrixWorld); - targetDir.subVectors(new Vector2(targetPos.x, targetPos.y), new Vector2(targetParentPos.x, targetParentPos.y)).normalize(); - sourceDir.subVectors(new Vector2(sourcePos.x, sourcePos.y), new Vector2(sourceParentPos.x, sourceParentPos.y)).normalize(); - var laterialAngle = targetDir.angle() - sourceDir.angle(); - var offset = new Matrix4().makeRotationFromEuler(new Euler(0, 0, laterialAngle)); - bone.matrix.multiply(offset); - bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); - bone.updateMatrixWorld(); - offsets[name] = offset; - } - } + startTime = currentTime; + var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the + // error can be observed. + // + // Intentionally not using a try-catch, since that makes some debugging + // techniques harder. Instead, if `scheduledHostCallback` errors, then + // `hasMoreWork` will remain true, and we'll continue the work loop. - return offsets; - }; - }(), - renameBones: function (skeleton, names) { - var bones = this.getBones(skeleton); + var hasMoreWork = true; - for (let i = 0; i < bones.length; ++i) { - var bone = bones[i]; + try { + hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); + } finally { + if (hasMoreWork) { + // If there's more work, schedule the next message event at the end + // of the preceding one. + schedulePerformWorkUntilDeadline(); + } else { + isMessageLoopRunning = false; + scheduledHostCallback = null; + } + } + } else { + isMessageLoopRunning = false; + } // Yielding to the browser will give it a chance to paint, so we can + }; - if (names[bone.name]) { - bone.name = names[bone.name]; - } - } + var schedulePerformWorkUntilDeadline; - return this; - }, - getBones: function (skeleton) { - return Array.isArray(skeleton) ? skeleton : skeleton.bones; - }, - getBoneByName: function (name, skeleton) { - for (let i = 0, bones = this.getBones(skeleton); i < bones.length; i++) { - if (name === bones[i].name) return bones[i]; - } - }, - getNearestBone: function (bone, names) { - while (bone.isBone) { - if (names.indexOf(bone.name) !== -1) { - return bone; - } + if (typeof localSetImmediate === 'function') { + // Node.js and old IE. + // There's a few reasons for why we prefer setImmediate. + // + // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. + // (Even though this is a DOM fork of the Scheduler, you could get here + // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) + // https://github.com/facebook/react/issues/20756 + // + // But also, it runs earlier which is the semantic we want. + // If other browsers ever implement it, it's better to use it. + // Although both of these would be inferior to native scheduling. + schedulePerformWorkUntilDeadline = function () { + localSetImmediate(performWorkUntilDeadline); + }; + } else if (typeof MessageChannel !== 'undefined') { + // DOM and Worker environments. + // We prefer MessageChannel because of the 4ms setTimeout clamping. + var channel = new MessageChannel(); + var port = channel.port2; + channel.port1.onmessage = performWorkUntilDeadline; - bone = bone.parent; - } - }, - findBoneTrackData: function (name, tracks) { - var regexp = /\[(.*)\]\.(.*)/, - result = { - name: name - }; + schedulePerformWorkUntilDeadline = function () { + port.postMessage(null); + }; + } else { + // We should only fallback here in non-browser environments. + schedulePerformWorkUntilDeadline = function () { + localSetTimeout(performWorkUntilDeadline, 0); + }; + } - for (let i = 0; i < tracks.length; ++i) { - // 1 is track name - // 2 is track type - var trackData = regexp.exec(tracks[i].name); + function requestHostCallback(callback) { + scheduledHostCallback = callback; - if (trackData && name === trackData[1]) { - result[trackData[2]] = i; - } - } + if (!isMessageLoopRunning) { + isMessageLoopRunning = true; + schedulePerformWorkUntilDeadline(); + } + } - return result; - }, - getEqualsBonesNames: function (skeleton, targetSkeleton) { - var sourceBones = this.getBones(skeleton), - targetBones = this.getBones(targetSkeleton), - bones = []; - - search: for (let i = 0; i < sourceBones.length; i++) { - var boneName = sourceBones[i].name; - - for (let j = 0; j < targetBones.length; j++) { - if (boneName === targetBones[j].name) { - bones.push(boneName); - continue search; - } - } - } + function requestHostTimeout(callback, ms) { + taskTimeoutID = localSetTimeout(function () { + callback(exports.unstable_now()); + }, ms); + } - return bones; - }, - clone: function (source) { - var sourceLookup = new Map(); - var cloneLookup = new Map(); - var clone = source.clone(); - parallelTraverse(source, clone, function (sourceNode, clonedNode) { - sourceLookup.set(clonedNode, sourceNode); - cloneLookup.set(sourceNode, clonedNode); - }); - clone.traverse(function (node) { - if (!node.isSkinnedMesh) return; - var clonedMesh = node; - var sourceMesh = sourceLookup.get(node); - var sourceBones = sourceMesh.skeleton.bones; - clonedMesh.skeleton = sourceMesh.skeleton.clone(); - clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix); - clonedMesh.skeleton.bones = sourceBones.map(function (bone) { - return cloneLookup.get(bone); - }); - clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix); - }); - return clone; - } -}); + function cancelHostTimeout() { + localClearTimeout(taskTimeoutID); + taskTimeoutID = -1; + } -function parallelTraverse(a, b, callback) { - callback(a, b); + var unstable_requestPaint = requestPaint; + var unstable_Profiling = null; - for (let i = 0; i < a.children.length; i++) { - parallelTraverse(a.children[i], b.children[i], callback); - } + exports.unstable_IdlePriority = IdlePriority; + exports.unstable_ImmediatePriority = ImmediatePriority; + exports.unstable_LowPriority = LowPriority; + exports.unstable_NormalPriority = NormalPriority; + exports.unstable_Profiling = unstable_Profiling; + exports.unstable_UserBlockingPriority = UserBlockingPriority; + exports.unstable_cancelCallback = unstable_cancelCallback; + exports.unstable_continueExecution = unstable_continueExecution; + exports.unstable_forceFrameRate = forceFrameRate; + exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; + exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; + exports.unstable_next = unstable_next; + exports.unstable_pauseExecution = unstable_pauseExecution; + exports.unstable_requestPaint = unstable_requestPaint; + exports.unstable_runWithPriority = unstable_runWithPriority; + exports.unstable_scheduleCallback = unstable_scheduleCallback; + exports.unstable_shouldYield = shouldYieldToHost; + exports.unstable_wrapCallback = unstable_wrapCallback; + /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ + if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === + 'function' + ) { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); + } + + })(); + } +} (scheduler_development)); + return scheduler_development; } -/** - * Unpack RGBA depth shader - * - show RGBA encoded depth as monochrome color - */ -const UnpackDepthRGBAShader = { - uniforms: { - tDiffuse: { - value: null - }, - opacity: { - value: 1.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform float opacity;', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', '#include ', 'void main() {', ' float depth = 1.0 - unpackRGBAToDepth( texture2D( tDiffuse, vUv ) );', ' gl_FragColor = vec4( vec3( depth ), opacity );', '}'].join('\n') -}; +(function (module) { + + if (process.env.NODE_ENV === 'production') { + module.exports = requireScheduler_production_min(); + } else { + module.exports = requireScheduler_development(); + } +} (scheduler$1)); /** - * This is a helper for visualising a given light's shadow map. - * It works for shadow casting lights: DirectionalLight and SpotLight. - * It renders out the shadow map and displays it on a HUD. - * - * Example usage: - * 1) Import ShadowMapViewer into your app. - * - * 2) Create a shadow casting light and name it optionally: - * var light = new DirectionalLight( 0xffffff, 1 ); - * light.castShadow = true; - * light.name = 'Sun'; - * - * 3) Create a shadow map viewer for that light and set its size and position optionally: - * var shadowMapViewer = new ShadowMapViewer( light ); - * shadowMapViewer.size.set( 128, 128 ); //width, height default: 256, 256 - * shadowMapViewer.position.set( 10, 10 ); //x, y in pixel default: 0, 0 (top left corner) - * - * 4) Render the shadow map viewer in your render loop: - * shadowMapViewer.render( renderer ); + * @license React + * react-reconciler.production.min.js * - * 5) Optionally: Update the shadow map viewer on window resize: - * shadowMapViewer.updateForWindowResize(); + * Copyright (c) Facebook, Inc. and its affiliates. * - * 6) If you set the position or size members directly, you need to call shadowMapViewer.update(); + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -var ShadowMapViewer = function (light) { - //- Internals - var scope = this; - var doRenderLabel = light.name !== undefined && light.name !== ''; - var userAutoClearSetting; //Holds the initial position and dimension of the HUD - - var frame = { - x: 10, - y: 10, - width: 256, - height: 256 - }; - var camera = new OrthographicCamera(window.innerWidth / -2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / -2, 1, 10); - camera.position.set(0, 0, 2); - var scene = new Scene$1(); //HUD for shadow map - - var shader = UnpackDepthRGBAShader; - var uniforms = UniformsUtils.clone(shader.uniforms); - var material = new ShaderMaterial({ - uniforms: uniforms, - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - }); - var plane = new PlaneGeometry(frame.width, frame.height); - var mesh = new Mesh(plane, material); - scene.add(mesh); //Label for light's name - - var labelCanvas, labelMesh; - - if (doRenderLabel) { - labelCanvas = document.createElement('canvas'); - var context = labelCanvas.getContext('2d'); - context.font = 'Bold 20px Arial'; - var labelWidth = context.measureText(light.name).width; - labelCanvas.width = labelWidth; - labelCanvas.height = 25; //25 to account for g, p, etc. - - context.font = 'Bold 20px Arial'; - context.fillStyle = 'rgba( 255, 0, 0, 1 )'; - context.fillText(light.name, 0, 20); - var labelTexture = new Texture(labelCanvas); - labelTexture.magFilter = LinearFilter; - labelTexture.minFilter = LinearFilter; - labelTexture.needsUpdate = true; - var labelMaterial = new MeshBasicMaterial({ - map: labelTexture, - side: DoubleSide - }); - labelMaterial.transparent = true; - var labelPlane = new PlaneGeometry(labelCanvas.width, labelCanvas.height); - labelMesh = new Mesh(labelPlane, labelMaterial); - scene.add(labelMesh); - } - - function resetPosition() { - scope.position.set(scope.position.x, scope.position.y); - } //- API - // Set to false to disable displaying this shadow map - - - this.enabled = true; // Set the size of the displayed shadow map on the HUD - - this.size = { - width: frame.width, - height: frame.height, - set: function (width, height) { - this.width = width; - this.height = height; - mesh.scale.set(this.width / frame.width, this.height / frame.height, 1); //Reset the position as it is off when we scale stuff - - resetPosition(); - } - }; // Set the position of the displayed shadow map on the HUD - - this.position = { - x: frame.x, - y: frame.y, - set: function (x, y) { - this.x = x; - this.y = y; - var width = scope.size.width; - var height = scope.size.height; - mesh.position.set(-window.innerWidth / 2 + width / 2 + this.x, window.innerHeight / 2 - height / 2 - this.y, 0); - - if (doRenderLabel) { - labelMesh.position.set(mesh.position.x, mesh.position.y - scope.size.height / 2 + labelCanvas.height / 2, 0); - } - } - }; - - this.render = function (renderer) { - if (this.enabled) { - //Because a light's .shadowMap is only initialised after the first render pass - //we have to make sure the correct map is sent into the shader, otherwise we - //always end up with the scene's first added shadow casting light's shadowMap - //in the shader - //See: https://github.com/mrdoob/three.js/issues/5932 - uniforms.tDiffuse.value = light.shadow.map.texture; - userAutoClearSetting = renderer.autoClear; - renderer.autoClear = false; // To allow render overlay - - renderer.clearDepth(); - renderer.render(scene, camera); - renderer.autoClear = userAutoClearSetting; //Restore user's setting - } - }; - - this.updateForWindowResize = function () { - if (this.enabled) { - camera.left = window.innerWidth / -2; - camera.right = window.innerWidth / 2; - camera.top = window.innerHeight / 2; - camera.bottom = window.innerHeight / -2; - camera.updateProjectionMatrix(); - this.update(); - } - }; - - this.update = function () { - this.position.set(this.position.x, this.position.y); - this.size.set(this.size.width, this.size.height); - }; //Force an update to set position/size - - - this.update(); -}; +var reactReconciler_production_min; +var hasRequiredReactReconciler_production_min; -ShadowMapViewer.prototype.constructor = ShadowMapViewer; +function requireReactReconciler_production_min () { + if (hasRequiredReactReconciler_production_min) return reactReconciler_production_min; + hasRequiredReactReconciler_production_min = 1; + reactReconciler_production_min = function $$$reconciler($$$hostConfig) { + var exports = {}; +var aa=React__default["default"],ba=scheduler$1.exports,ca=Object.assign;function n(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;ch||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{bc=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?ac(a):""}var dc=Object.prototype.hasOwnProperty,ec=[],fc=-1;function gc(a){return {current:a}} + function x(a){0>fc||(a.current=ec[fc],ec[fc]=null,fc--);}function y(a,b){fc++;ec[fc]=a.current;a.current=b;}var hc={},A=gc(hc),B=gc(!1),ic=hc;function jc(a,b){var c=a.type.contextTypes;if(!c)return hc;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} + function C(a){a=a.childContextTypes;return null!==a&&void 0!==a}function kc(){x(B);x(A);}function lc(a,b,c){if(A.current!==hc)throw Error(n(168));y(A,b);y(B,c);}function mc(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(n(108,xa(a)||"Unknown",e));return ca({},c,d)} + function nc(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||hc;ic=A.current;y(A,a);y(B,B.current);return !0}function oc(a,b,c){var d=a.stateNode;if(!d)throw Error(n(169));c?(a=mc(a,b,ic),d.__reactInternalMemoizedMergedChildContext=a,x(B),x(A),y(A,a)):x(B);y(B,c);}var qc=Math.clz32?Math.clz32:pc,rc=Math.log,sc=Math.LN2;function pc(a){a>>>=0;return 0===a?32:31-(rc(a)/sc|0)|0}var tc=64,uc=4194304; + function vc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; + default:return a}}function wc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=vc(h):(f&=g,0!==f&&(d=vc(f)));}else g=c&~e,0!==g?d=vc(g):0!==f&&(d=vc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}function Bc(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-qc(b);a[b]=c;} + function Cc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0>=g;e-=g;Nd=1<<32-qc(b)+e|c<u?(t=w,w=null):t=w.sibling;var q=r(e,w,h[u],k);if(null===q){null===w&&(w=t);break}a&&w&&null===q.alternate&&b(e,w);g=f(q,g,u);null===m?l=q:m.sibling=q;m=q;w=t;}if(u===h.length)return c(e,w),I&&Pd(e,u),l;if(null===w){for(;uu?(q=m,m=null):q=m.sibling;var V=r(e,m,t.value,k);if(null===V){null===m&&(m=q);break}a&&m&&null===V.alternate&&b(e,m);g=f(V,g,u);null===w?l=V:w.sibling=V;w=V;m=q;}if(t.done)return c(e, + m),I&&Pd(e,u),l;if(null===m){for(;!t.done;u++,t=h.next())t=v(e,t.value,k),null!==t&&(g=f(t,g,u),null===w?l=t:w.sibling=t,w=t);I&&Pd(e,u);return l}for(m=d(e,m);!t.done;u++,t=h.next())t=z(m,e,u,t.value,k),null!==t&&(a&&null!==t.alternate&&m.delete(null===t.key?u:t.key),g=f(t,g,u),null===w?l=t:w.sibling=t,w=t);a&&m.forEach(function(a){return b(e,a)});I&&Pd(e,u);return l}function da(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ia&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!== + f){switch(f.$$typeof){case fa:a:{for(var k=f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ia){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===ra&&he(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=fe(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===ia?(d=ne(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=le(f.type,f.key,f.props,null,a.mode,h),h.ref=fe(a,d,f),h.return= + a,a=h);}return g(a);case ha:a:{for(l=f.key;null!==d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=me(f,a.mode,h);d.return=a;a=d;}return g(a);case ra:return l=f._init,da(a,d,l(f._payload),h)}if(Ea(f))return q(a,d,f,h);if(ua(f))return N(a,d,f,h);ge(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&& + 6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=ke(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return da}var oe=ie(!0),pe=ie(!1),qe={},re=gc(qe),se=gc(qe),te=gc(qe);function ue(a){if(a===qe)throw Error(n(174));return a}function ve(a,b){y(te,b);y(se,a);y(re,qe);a=Ga(b);x(re);y(re,a);}function we(){x(re);x(se);x(te);}function xe(a){var b=ue(te.current),c=ue(re.current);b=Ha(c,a.type,b);c!==b&&(y(se,a),y(re,b));}function ye(a){se.current===a&&(x(re),x(se));}var J=gc(0); + function ze(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||Ib(c)||Jb(c)))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Ae=[]; + function Be(){for(var a=0;ac?c:4;a(!0);var d=De.transition;De.transition={};try{a(!1),b();}finally{D=c,De.transition=d;}}function rf(){return Re().memoizedState}function sf(a,b,c){var d=zd(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};tf(a)?uf(b,c):(vf(a,b,c),c=H(),a=Ad(a,d,c),null!==a&&wf(a,b,d));} + function df(a,b,c){var d=zd(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(tf(a))uf(b,e);else {vf(a,b,e);var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(Rc(h,g))return}catch(k){}finally{}c=H();a=Ad(a,d,c);null!==a&&wf(a,b,d);}}function tf(a){var b=a.alternate;return a===K||null!==b&&b===K} + function uf(a,b){Ge=Fe=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function vf(a,b,c){null!==F&&0!==(a.mode&1)&&0===(G&2)?(a=b.interleaved,null===a?(c.next=c,null===md?md=[b]:md.push(b)):(c.next=a.next,a.next=c),b.interleaved=c):(a=b.pending,null===a?c.next=c:(c.next=a.next,a.next=c),b.pending=c);}function wf(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Dc(a,c);}} + var Oe={readContext:ld,useCallback:O,useContext:O,useEffect:O,useImperativeHandle:O,useInsertionEffect:O,useLayoutEffect:O,useMemo:O,useReducer:O,useRef:O,useState:O,useDebugValue:O,useDeferredValue:O,useTransition:O,useMutableSource:O,useSyncExternalStore:O,useId:O,unstable_isNewReconciler:!1},Le={readContext:ld,useCallback:function(a,b){Qe().memoizedState=[a,void 0===b?null:b];return a},useContext:ld,useEffect:hf,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ff(4194308, + 4,lf.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ff(4194308,4,a,b)},useInsertionEffect:function(a,b){return ff(4,2,a,b)},useMemo:function(a,b){var c=Qe();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Qe();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=sf.bind(null,K,a);return [d.memoizedState,a]},useRef:function(a){var b= + Qe();a={current:a};return b.memoizedState=a},useState:cf,useDebugValue:nf,useDeferredValue:function(a){var b=cf(a),c=b[0],d=b[1];hf(function(){var b=De.transition;De.transition={};try{d(a);}finally{De.transition=b;}},[a]);return c},useTransition:function(){var a=cf(!1),b=a[0];a=qf.bind(null,a[1]);Qe().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=K,e=Qe();if(I){if(void 0===c)throw Error(n(407));c=c();}else {c=b();if(null===F)throw Error(n(349)); + 0!==(Ee&30)||af(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;hf(Ye.bind(null,d,f,a),[a]);d.flags|=2048;Ze(9,$e.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Qe(),b=F.identifierPrefix;if(I){var c=Od;var d=Nd;c=(d&~(1<<32-qc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=He++;0Uf&&(b.flags|=128,d=!0,Qf(e,!1),b.lanes=4194304);}else {if(!d)if(a=ze(f),null!==a){if(b.flags|=128,d=!0,a=a.updateQueue,null!==a&&(b.updateQueue=a,b.flags|=4),Qf(e,!0),null===e.tail&&"hidden"===e.tailMode&&!f.alternate&&!I)return P(b),null}else 2*E()-e.renderingStartTime>Uf&&1073741824!==c&&(b.flags|=128,d=!0,Qf(e,!1),b.lanes=4194304);e.isBackwards?(f.sibling=b.child,b.child=f):(a=e.last,null!==a?a.sibling=f:b.child=f,e.last=f);}if(null!== + e.tail)return b=e.tail,e.rendering=b,e.tail=b.sibling,e.renderingStartTime=E(),b.sibling=null,a=J.current,y(J,d?a&1|2:a&1),b;P(b);return null;case 22:case 23:return Vf(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(Wf&1073741824)&&(P(b),Ua&&b.subtreeFlags&6&&(b.flags|=8192)):P(b),null;case 24:return null;case 25:return null}throw Error(n(156,b.tag));}var Xf=ea.ReactCurrentOwner,kd=!1; + function R(a,b,c,d){b.child=null===a?pe(b,null,c,d):oe(b,a.child,c,d);}function Yf(a,b,c,d,e){c=c.render;var f=b.ref;jd(b,e);d=Ke(a,b,c,d,f,e);c=Pe();if(null!==a&&!kd)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zf(a,b,e);I&&c&&Rd(b);b.flags|=1;R(a,b,d,e);return b.child} + function $f(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!ag(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,bg(a,b,f,d,e);a=le(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Zc;if(c(g,d)&&a.ref===b.ref)return Zf(a,b,e)}b.flags|=1;a=je(f,d);a.ref=b.ref;a.return=b;return b.child=a} + function bg(a,b,c,d,e){if(null!==a&&Zc(a.memoizedProps,d)&&a.ref===b.ref)if(kd=!1,0!==(a.lanes&e))0!==(a.flags&131072)&&(kd=!0);else return b.lanes=a.lanes,Zf(a,b,e);return cg(a,b,c,d,e)} + function dg(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null},y(eg,Wf),Wf|=c;else if(0!==(c&1073741824))b.memoizedState={baseLanes:0,cachePool:null},d=null!==f?f.baseLanes:c,y(eg,Wf),Wf|=d;else return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null},b.updateQueue=null,y(eg,Wf),Wf|=a,null;else null!==f?(d=f.baseLanes|c,b.memoizedState=null): + d=c,y(eg,Wf),Wf|=d;R(a,b,e,c);return b.child}function fg(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152;}function cg(a,b,c,d,e){var f=C(c)?ic:A.current;f=jc(b,f);jd(b,e);c=Ke(a,b,c,d,f,e);d=Pe();if(null!==a&&!kd)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zf(a,b,e);I&&d&&Rd(b);b.flags|=1;R(a,b,c,e);return b.child} + function gg(a,b,c,d,e){if(C(c)){var f=!0;nc(b);}else f=!1;jd(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),Dd(b,c,d),Fd(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=ld(l):(l=C(c)?ic:A.current,l=jc(b,l));var m=c.getDerivedStateFromProps,v="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;v||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!== + typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Ed(b,g,d,l);nd=!1;var r=b.memoizedState;g.state=r;ud(b,d,g,e);k=b.memoizedState;h!==d||r!==k||B.current||nd?("function"===typeof m&&(yd(b,c,m,d),k=b.memoizedState),(h=nd||Cd(b,c,h,d,r,k,l))?(v||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&& + (b.flags|=4194308)):("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1);}else {g=b.stateNode;pd(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:ad(b.type,h);g.props=l;v=b.pendingProps;r=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=ld(k):(k=C(c)?ic:A.current,k=jc(b,k));var z=c.getDerivedStateFromProps;(m="function"===typeof z||"function"=== + typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==v||r!==k)&&Ed(b,g,d,k);nd=!1;r=b.memoizedState;g.state=r;ud(b,d,g,e);var q=b.memoizedState;h!==v||r!==q||B.current||nd?("function"===typeof z&&(yd(b,c,z,d),q=b.memoizedState),(l=nd||Cd(b,c,l,d,r,q,k)||!1)?(m||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d, + q,k),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,q,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=q),g.props=d,g.state=q,g.context=k,d=l):("function"!== + typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1);}return hg(a,b,c,d,f,e)} + function hg(a,b,c,d,e,f){fg(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&oc(b,c,!1),Zf(a,b,f);d=b.stateNode;Xf.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=oe(b,a.child,null,f),b.child=oe(b,null,h,f)):R(a,b,h,f);b.memoizedState=d.state;e&&oc(b,c,!0);return b.child}function ig(a){var b=a.stateNode;b.pendingContext?lc(a,b.pendingContext,b.pendingContext!==b.context):b.context&&lc(a,b.context,!1);ve(a,b.containerInfo);} + function jg(a,b,c,d,e){de();ee(e);b.flags|=256;R(a,b,c,d);return b.child}var kg={dehydrated:null,treeContext:null,retryLane:0};function lg(a){return {baseLanes:a,cachePool:null}} + function mg(a,b,c){var d=b.pendingProps,e=J.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;y(J,e&1);if(null===a){ae(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:Jb(a)?b.lanes=8:b.lanes=1073741824,null;e=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,e={mode:"hidden",children:e},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=e): + f=ng(e,d,0,null),a=ne(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=lg(c),b.memoizedState=kg,a):og(b,e)}e=a.memoizedState;if(null!==e){h=e.dehydrated;if(null!==h){if(g){if(b.flags&256)return b.flags&=-257,pg(a,b,c,Error(n(422)));if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=ng({mode:"visible",children:d.children},e,0,null);f=ne(f,e,c,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&oe(b,a.child, + null,c);b.child.memoizedState=lg(c);b.memoizedState=kg;return f}if(0===(b.mode&1))b=pg(a,b,c,null);else if(Jb(h))b=pg(a,b,c,Error(n(419)));else if(d=0!==(c&a.childLanes),kd||d){d=F;if(null!==d){switch(c&-c){case 4:f=2;break;case 16:f=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:f=32;break;case 536870912:f= + 268435456;break;default:f=0;}d=0!==(f&(d.suspendedLanes|c))?0:f;0!==d&&d!==e.retryLane&&(e.retryLane=d,Ad(a,d,-1));}Tf();b=pg(a,b,c,Error(n(421)));}else Ib(h)?(b.flags|=128,b.child=a.child,b=qg.bind(null,a),Kb(h,b),b=null):(c=e.treeContext,p&&(Ud=Ob(h),Td=b,I=!0,Wd=null,Vd=!1,null!==c&&(Kd[Ld++]=Nd,Kd[Ld++]=Od,Kd[Ld++]=Md,Nd=c.id,Od=c.overflow,Md=b)),b=og(b,b.pendingProps.children),b.flags|=4096);return b}if(f)return d=rg(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState= + null===e?lg(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kg,d;c=sg(a,b,d.children,c);b.memoizedState=null;return c}if(f)return d=rg(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState=null===e?lg(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kg,d;c=sg(a,b,d.children,c);b.memoizedState=null;return c} + function og(a,b){b=ng({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function sg(a,b,c,d){var e=a.child;a=e.sibling;c=je(e,{mode:"visible",children:c});0===(b.mode&1)&&(c.lanes=d);c.return=b;c.sibling=null;null!==a&&(d=b.deletions,null===d?(b.deletions=[a],b.flags|=16):d.push(a));return b.child=c} + function rg(a,b,c,d,e){var f=b.mode;a=a.child;var g=a.sibling,h={mode:"hidden",children:c};0===(f&1)&&b.child!==a?(c=b.child,c.childLanes=0,c.pendingProps=h,b.deletions=null):(c=je(a,h),c.subtreeFlags=a.subtreeFlags&14680064);null!==g?d=je(g,d):(d=ne(d,f,e,null),d.flags|=2);d.return=b;c.return=b;c.sibling=d;b.child=c;return d}function pg(a,b,c,d){null!==d&&ee(d);oe(b,a.child,null,c);a=og(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a} + function tg(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);id(a.return,b,c);}function ug(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e);} + function vg(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;R(a,b,d.children,c);d=J.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else {if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&tg(a,c,b);else if(19===a.tag)tg(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return;}a.sibling.return=a.return;a=a.sibling;}d&=1;}y(J,d);if(0===(b.mode&1))b.memoizedState= + null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===ze(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);ug(b,!1,e,c,f);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===ze(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a;}ug(b,!0,c,null,f);break;case "together":ug(b,!1,null,null,void 0);break;default:b.memoizedState=null;}return b.child} + function Zf(a,b,c){null!==a&&(b.dependencies=a.dependencies);vd|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(n(153));if(null!==b.child){a=b.child;c=je(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=je(a,a.pendingProps),c.return=b;c.sibling=null;}return b.child} + function wg(a,b,c){switch(b.tag){case 3:ig(b);de();break;case 5:xe(b);break;case 1:C(b.type)&&nc(b);break;case 4:ve(b,b.stateNode.containerInfo);break;case 10:gd(b,b.type._context,b.memoizedProps.value);break;case 13:var d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return y(J,J.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return mg(a,b,c);y(J,J.current&1);a=Zf(a,b,c);return null!==a?a.sibling:null}y(J,J.current&1);break;case 19:d=0!==(c&b.childLanes);if(0!==(a.flags&128)){if(d)return vg(a, + b,c);b.flags|=128;}var e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);y(J,J.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,dg(a,b,c)}return Zf(a,b,c)} + function xg(a,b){Sd(b);switch(b.tag){case 1:return C(b.type)&&kc(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return we(),x(B),x(A),Be(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return ye(b),null;case 13:x(J);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(n(340));de();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return x(J),null;case 4:return we(),null;case 10:return hd(b.type._context),null;case 22:case 23:return Vf(), + null;case 24:return null;default:return null}}var yg=!1,zg=!1,Ag="function"===typeof WeakSet?WeakSet:Set,S=null;function Bg(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){T(a,b,d);}else c.current=null;}function Cg(a,b,c){try{c();}catch(d){T(a,b,d);}}var Dg=!1; + function Eg(a,b){Ia(a.containerInfo);for(S=b;null!==S;)if(a=S,b=a.child,0!==(a.subtreeFlags&1028)&&null!==b)b.return=a,S=b;else for(;null!==S;){a=S;try{var c=a.alternate;if(0!==(a.flags&1024))switch(a.tag){case 0:case 11:case 15:break;case 1:if(null!==c){var d=c.memoizedProps,e=c.memoizedState,f=a.stateNode,g=f.getSnapshotBeforeUpdate(a.elementType===a.type?d:ad(a.type,d),e);f.__reactInternalSnapshotBeforeUpdate=g;}break;case 3:Ua&&xb(a.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break; + default:throw Error(n(163));}}catch(h){T(a,a.return,h);}b=a.sibling;if(null!==b){b.return=a.return;S=b;break}S=a.return;}c=Dg;Dg=!1;return c}function Fg(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Cg(b,c,f);}e=e.next;}while(e!==d)}}function Gg(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}} + function Hg(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=Fa(c);break;default:a=c;}"function"===typeof b?b(a):b.current=a;}} + function Ig(a,b,c){if(Oc&&"function"===typeof Oc.onCommitFiberUnmount)try{Oc.onCommitFiberUnmount(Nc,b);}catch(g){}switch(b.tag){case 0:case 11:case 14:case 15:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var d=a=a.next;do{var e=d,f=e.destroy;e=e.tag;void 0!==f&&(0!==(e&2)?Cg(b,c,f):0!==(e&4)&&Cg(b,c,f));d=d.next;}while(d!==a)}break;case 1:Bg(b,c);a=b.stateNode;if("function"===typeof a.componentWillUnmount)try{a.props=b.memoizedProps,a.state=b.memoizedState,a.componentWillUnmount();}catch(g){T(b, + c,g);}break;case 5:Bg(b,c);break;case 4:Ua?Jg(a,b,c):Va&&Va&&(b=b.stateNode.containerInfo,c=zb(b),Cb(b,c));}}function Kg(a,b,c){for(var d=b;;)if(Ig(a,d,c),null===d.child||Ua&&4===d.tag){if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;}d.sibling.return=d.return;d=d.sibling;}else d.child.return=d,d=d.child;} + function Lg(a){var b=a.alternate;null!==b&&(a.alternate=null,Lg(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&Za(b));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Mg(a){return 5===a.tag||3===a.tag||4===a.tag} + function Ng(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Mg(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}} + function Og(a){if(Ua){a:{for(var b=a.return;null!==b;){if(Mg(b))break a;b=b.return;}throw Error(n(160));}var c=b;switch(c.tag){case 5:b=c.stateNode;c.flags&32&&(sb(b),c.flags&=-33);c=Ng(a);Pg(a,c,b);break;case 3:case 4:b=c.stateNode.containerInfo;c=Ng(a);Qg(a,c,b);break;default:throw Error(n(161));}}}function Qg(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?pb(c,a,b):kb(c,a);else if(4!==d&&(a=a.child,null!==a))for(Qg(a,b,c),a=a.sibling;null!==a;)Qg(a,b,c),a=a.sibling;} + function Pg(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?ob(c,a,b):jb(c,a);else if(4!==d&&(a=a.child,null!==a))for(Pg(a,b,c),a=a.sibling;null!==a;)Pg(a,b,c),a=a.sibling;} + function Jg(a,b,c){for(var d=b,e=!1,f,g;;){if(!e){e=d.return;a:for(;;){if(null===e)throw Error(n(160));f=e.stateNode;switch(e.tag){case 5:g=!1;break a;case 3:f=f.containerInfo;g=!0;break a;case 4:f=f.containerInfo;g=!0;break a}e=e.return;}e=!0;}if(5===d.tag||6===d.tag)Kg(a,d,c),g?rb(f,d.stateNode):qb(f,d.stateNode);else if(18===d.tag)g?Wb(f,d.stateNode):Vb(f,d.stateNode);else if(4===d.tag){if(null!==d.child){f=d.stateNode.containerInfo;g=!0;d.child.return=d;d=d.child;continue}}else if(Ig(a,d,c),null!== + d.child){d.child.return=d;d=d.child;continue}if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;4===d.tag&&(e=!1);}d.sibling.return=d.return;d=d.sibling;}} + function Rg(a,b){if(Ua){switch(b.tag){case 0:case 11:case 14:case 15:Fg(3,b,b.return);Gg(3,b);Fg(5,b,b.return);return;case 1:return;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps;a=null!==a?a.memoizedProps:d;var e=b.type,f=b.updateQueue;b.updateQueue=null;null!==f&&nb(c,f,e,a,d,b);}return;case 6:if(null===b.stateNode)throw Error(n(162));c=b.memoizedProps;lb(b.stateNode,null!==a?a.memoizedProps:c,c);return;case 3:p&&null!==a&&a.memoizedState.isDehydrated&&Tb(b.stateNode.containerInfo);return; + case 12:return;case 13:Sg(b);return;case 19:Sg(b);return;case 17:return}throw Error(n(163));}switch(b.tag){case 0:case 11:case 14:case 15:Fg(3,b,b.return);Gg(3,b);Fg(5,b,b.return);return;case 12:return;case 13:Sg(b);return;case 19:Sg(b);return;case 3:p&&null!==a&&a.memoizedState.isDehydrated&&Tb(b.stateNode.containerInfo);break;case 22:case 23:return}a:if(Va){switch(b.tag){case 1:case 5:case 6:break a;case 3:case 4:b=b.stateNode;Cb(b.containerInfo,b.pendingChildren);break a}throw Error(n(163));}} + function Sg(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Ag);b.forEach(function(b){var d=Tg.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}} + function Ug(a,b){for(S=b;null!==S;){b=S;var c=b.deletions;if(null!==c)for(var d=0;d";case bh:return ":has("+(ih(a)||"")+")";case ch:return '[role="'+a.value+'"]';case eh:return '"'+a.value+'"';case dh:return '[data-testname="'+a.value+'"]';default:throw Error(n(365));}} + function jh(a,b){var c=[];a=[a,0];for(var d=0;de&&(e=g);d&=~f;}d=e;d=E()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lh(d/1960))-d;if(10a?16:a;if(null===uh)var d=!1;else {a=uh;uh=null;vh=0;if(0!==(G&6))throw Error(n(331));var e=G;G|=4;for(S=a.current;null!==S;){var f=S,g=f.child;if(0!==(S.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kE()-Vg?Ih(a,0):qh|=c);Z(a,b);}function Vh(a,b){0===b&&(0===(a.mode&1)?b=1:(b=uc,uc<<=1,0===(uc&130023424)&&(uc=4194304)));var c=H();a=Ah(a,b);null!==a&&(Bc(a,b,c),Z(a,c));}function qg(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Vh(a,c);} + function Tg(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(n(314));}null!==d&&d.delete(b);Vh(a,c);}var Sh; + Sh=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||B.current)kd=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return kd=!1,wg(a,b,c);kd=0!==(a.flags&131072)?!0:!1;}else kd=!1,I&&0!==(b.flags&1048576)&&Qd(b,Jd,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;var e=jc(b,A.current);jd(b,c);e=Ke(null,b,d,a,e,c);var f=Pe();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof? + (b.tag=1,b.memoizedState=null,b.updateQueue=null,C(d)?(f=!0,nc(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,od(b),e.updater=Bd,b.stateNode=e,e._reactInternals=b,Fd(b,d,a,c),b=hg(null,b,d,!0,f,c)):(b.tag=0,I&&f&&Rd(b),R(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Wh(d);a=ad(d,a);switch(e){case 0:b=cg(null,b,d,a,c);break a;case 1:b=gg(null,b,d, + a,c);break a;case 11:b=Yf(null,b,d,a,c);break a;case 14:b=$f(null,b,d,ad(d.type,a),c);break a}throw Error(n(306,d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),cg(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),gg(a,b,d,e,c);case 3:a:{ig(b);if(null===a)throw Error(n(387));d=b.pendingProps;f=b.memoizedState;e=f.element;pd(a,b);ud(b,d,null,c);var g=b.memoizedState;d=g.element;if(p&&f.isDehydrated)if(f={element:d,isDehydrated:!1, + cache:g.cache,transitions:g.transitions},b.updateQueue.baseState=f,b.memoizedState=f,b.flags&256){e=Error(n(423));b=jg(a,b,d,c,e);break a}else if(d!==e){e=Error(n(424));b=jg(a,b,d,c,e);break a}else for(p&&(Ud=Nb(b.stateNode.containerInfo),Td=b,I=!0,Wd=null,Vd=!1),c=pe(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {de();if(d===e){b=Zf(a,b,c);break a}R(a,b,d,c);}b=b.child;}return b;case 5:return xe(b),null===a&&ae(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children, + Oa(d,e)?g=null:null!==f&&Oa(d,f)&&(b.flags|=32),fg(a,b),R(a,b,g,c),b.child;case 6:return null===a&&ae(b),null;case 13:return mg(a,b,c);case 4:return ve(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=oe(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),Yf(a,b,d,e,c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:return R(a,b,b.pendingProps.children,c),b.child;case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d= + b.type._context;e=b.pendingProps;f=b.memoizedProps;g=e.value;gd(b,d,g);if(null!==f)if(Rc(f.value,g)){if(f.children===e.children&&!B.current){b=Zf(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=qd(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|= + c);id(f.return,c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(n(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);id(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}R(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,jd(b,c),e=ld(e),d=d(e),b.flags|= + 1,R(a,b,d,c),b.child;case 14:return d=b.type,e=ad(d,b.pendingProps),e=ad(d.type,e),$f(a,b,d,e,c);case 15:return bg(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ad(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),b.tag=1,C(d)?(a=!0,nc(b)):a=!1,jd(b,c),Dd(b,d,e),Fd(b,d,e,c),hg(null,b,d,!0,a,c);case 19:return vg(a,b,c);case 22:return dg(a,b,c)}throw Error(n(156,b.tag));};function Dh(a,b){return Fc(a,b)} + function Xh(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Yd(a,b,c,d){return new Xh(a,b,c,d)}function ag(a){a=a.prototype;return !(!a||!a.isReactComponent)} + function Wh(a){if("function"===typeof a)return ag(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===na)return 11;if(a===qa)return 14}return 2} + function je(a,b){var c=a.alternate;null===c?(c=Yd(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; + c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} + function le(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)ag(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ia:return ne(c.children,e,f,b);case ja:g=8;e|=8;break;case ka:return a=Yd(12,c,b,e|2),a.elementType=ka,a.lanes=f,a;case oa:return a=Yd(13,c,b,e),a.elementType=oa,a.lanes=f,a;case pa:return a=Yd(19,c,b,e),a.elementType=pa,a.lanes=f,a;case sa:return ng(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case la:g=10;break a;case ma:g=9;break a;case na:g=11; + break a;case qa:g=14;break a;case ra:g=16;d=null;break a}throw Error(n(130,null==a?a:typeof a,""));}b=Yd(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function ne(a,b,c,d){a=Yd(7,a,d,b);a.lanes=c;return a}function ng(a,b,c,d){a=Yd(22,a,d,b);a.elementType=sa;a.lanes=c;a.stateNode={};return a}function ke(a,b,c){a=Yd(6,a,null,b);a.lanes=c;return a} + function me(a,b,c){b=Yd(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} + function Yh(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=Sa;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=Ac(0);this.expirationTimes=Ac(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=Ac(0);this.identifierPrefix=d;this.onRecoverableError=e;p&&(this.mutableSourceEagerHydrationData= + null);}function Zh(a,b,c,d,e,f,g,h,k){a=new Yh(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Yd(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null};od(f);return a} + function $h(a){if(!a)return hc;a=a._reactInternals;a:{if(ya(a)!==a||1!==a.tag)throw Error(n(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(C(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return;}while(null!==b);throw Error(n(171));}if(1===a.tag){var c=a.type;if(C(c))return mc(a,c,b)}return b} + function ai(a){var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(n(188));a=Object.keys(a).join(",");throw Error(n(268,a));}a=Ba(b);return null===a?null:a.stateNode}function bi(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c=l&&f>=v&&e<=m&&g<=r){a.splice(b,1);break}else if(!(d!==l||c.width!==k.width||rg)){v>f&&(k.height+=v-f,k.y=f);re)){l>d&&(k.width+= + l-d,k.x=d);mc&&(c=g)),g ")+"\n\nNo matching component was found for:\n ")+a.join(" > ")}return null}; + exports.getPublicRootInstance=function(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return Fa(a.child.stateNode);default:return a.child.stateNode}}; + exports.injectIntoDevTools=function(a){a={bundleType:a.bundleType,version:a.version,rendererPackageName:a.rendererPackageName,rendererConfig:a.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ea.ReactCurrentDispatcher,findHostInstanceByFiber:di,findFiberByHostInstance:a.findFiberByHostInstance|| + ei,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.0.0-fc46dba67-20220329"};if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)a=!1;else {var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)a=!0;else {try{Nc=b.inject(a),Oc=b;}catch(c){}a=b.checkDCE?!0:!1;}}return a};exports.isAlreadyRendering=function(){return !1}; + exports.observeVisibleRects=function(a,b,c,d){if(!bb)throw Error(n(363));a=kh(a,b);var e=ib(a,c,d).disconnect;return {disconnect:function(){e();}}};exports.registerMutableSourceForHydration=function(a,b){var c=b._getVersion;c=c(b._source);null==a.mutableSourceEagerHydrationData?a.mutableSourceEagerHydrationData=[b,c]:a.mutableSourceEagerHydrationData.push(b,c);};exports.runWithPriority=function(a,b){var c=D;try{return D=a,b()}finally{D=c;}};exports.shouldError=function(){return null}; + exports.shouldSuspend=function(){return !1};exports.updateContainer=function(a,b,c,d){var e=b.current,f=H(),g=zd(e);c=$h(c);null===b.context?b.context=c:b.pendingContext=c;b=qd(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);rd(e,b);a=Ad(e,g,f);null!==a&&sd(a,e,g);return g}; -/** - * Depth-of-field shader with bokeh - * ported from GLSL shader by Martins Upitis - * http://blenderartists.org/forum/showthread.php?237488-GLSL-depth-of-field-with-bokeh-v2-4-(update) - * - * Requires #define RINGS and SAMPLES integers - */ + return exports; + }; + return reactReconciler_production_min; +} -({ - uniforms: { - textureWidth: { - value: 1.0 - }, - textureHeight: { - value: 1.0 - }, - focalDepth: { - value: 1.0 - }, - focalLength: { - value: 24.0 - }, - fstop: { - value: 0.9 - }, - tColor: { - value: null - }, - tDepth: { - value: null - }, - maxblur: { - value: 1.0 - }, - showFocus: { - value: 0 - }, - manualdof: { - value: 0 - }, - vignetting: { - value: 0 - }, - depthblur: { - value: 0 - }, - threshold: { - value: 0.5 - }, - gain: { - value: 2.0 - }, - bias: { - value: 0.5 - }, - fringe: { - value: 0.7 - }, - znear: { - value: 0.1 - }, - zfar: { - value: 100 - }, - noise: { - value: 1 - }, - dithering: { - value: 0.0001 - }, - pentagon: { - value: 0 - }, - shaderFocus: { - value: 1 - }, - focusCoords: { - value: new Vector2() - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', 'varying vec2 vUv;', 'uniform sampler2D tColor;', 'uniform sampler2D tDepth;', 'uniform float textureWidth;', 'uniform float textureHeight;', 'uniform float focalDepth; //focal distance value in meters, but you may use autofocus option below', 'uniform float focalLength; //focal length in mm', 'uniform float fstop; //f-stop value', 'uniform bool showFocus; //show debug focus point and focal range (red = focal point, green = focal range)', '/*', 'make sure that these two values are the same for your camera, otherwise distances will be wrong.', '*/', 'uniform float znear; // camera clipping start', 'uniform float zfar; // camera clipping end', '//------------------------------------------', '//user variables', 'const int samples = SAMPLES; //samples on the first ring', 'const int rings = RINGS; //ring count', 'const int maxringsamples = rings * samples;', 'uniform bool manualdof; // manual dof calculation', 'float ndofstart = 1.0; // near dof blur start', 'float ndofdist = 2.0; // near dof blur falloff distance', 'float fdofstart = 1.0; // far dof blur start', 'float fdofdist = 3.0; // far dof blur falloff distance', 'float CoC = 0.03; //circle of confusion size in mm (35mm film = 0.03mm)', 'uniform bool vignetting; // use optical lens vignetting', 'float vignout = 1.3; // vignetting outer border', 'float vignin = 0.0; // vignetting inner border', 'float vignfade = 22.0; // f-stops till vignete fades', 'uniform bool shaderFocus;', '// disable if you use external focalDepth value', 'uniform vec2 focusCoords;', '// autofocus point on screen (0.0,0.0 - left lower corner, 1.0,1.0 - upper right)', '// if center of screen use vec2(0.5, 0.5);', 'uniform float maxblur;', '//clamp value of max blur (0.0 = no blur, 1.0 default)', 'uniform float threshold; // highlight threshold;', 'uniform float gain; // highlight gain;', 'uniform float bias; // bokeh edge bias', 'uniform float fringe; // bokeh chromatic aberration / fringing', 'uniform bool noise; //use noise instead of pattern for sample dithering', 'uniform float dithering;', 'uniform bool depthblur; // blur the depth buffer', 'float dbsize = 1.25; // depth blur size', '/*', 'next part is experimental', 'not looking good with small sample and ring count', 'looks okay starting from samples = 4, rings = 4', '*/', 'uniform bool pentagon; //use pentagon as bokeh shape?', 'float feather = 0.4; //pentagon shape feather', '//------------------------------------------', 'float penta(vec2 coords) {', ' //pentagonal shape', ' float scale = float(rings) - 1.3;', ' vec4 HS0 = vec4( 1.0, 0.0, 0.0, 1.0);', ' vec4 HS1 = vec4( 0.309016994, 0.951056516, 0.0, 1.0);', ' vec4 HS2 = vec4(-0.809016994, 0.587785252, 0.0, 1.0);', ' vec4 HS3 = vec4(-0.809016994,-0.587785252, 0.0, 1.0);', ' vec4 HS4 = vec4( 0.309016994,-0.951056516, 0.0, 1.0);', ' vec4 HS5 = vec4( 0.0 ,0.0 , 1.0, 1.0);', ' vec4 one = vec4( 1.0 );', ' vec4 P = vec4((coords),vec2(scale, scale));', ' vec4 dist = vec4(0.0);', ' float inorout = -4.0;', ' dist.x = dot( P, HS0 );', ' dist.y = dot( P, HS1 );', ' dist.z = dot( P, HS2 );', ' dist.w = dot( P, HS3 );', ' dist = smoothstep( -feather, feather, dist );', ' inorout += dot( dist, one );', ' dist.x = dot( P, HS4 );', ' dist.y = HS5.w - abs( P.z );', ' dist = smoothstep( -feather, feather, dist );', ' inorout += dist.x;', ' return clamp( inorout, 0.0, 1.0 );', '}', 'float bdepth(vec2 coords) {', ' // Depth buffer blur', ' float d = 0.0;', ' float kernel[9];', ' vec2 offset[9];', ' vec2 wh = vec2(1.0/textureWidth,1.0/textureHeight) * dbsize;', ' offset[0] = vec2(-wh.x,-wh.y);', ' offset[1] = vec2( 0.0, -wh.y);', ' offset[2] = vec2( wh.x -wh.y);', ' offset[3] = vec2(-wh.x, 0.0);', ' offset[4] = vec2( 0.0, 0.0);', ' offset[5] = vec2( wh.x, 0.0);', ' offset[6] = vec2(-wh.x, wh.y);', ' offset[7] = vec2( 0.0, wh.y);', ' offset[8] = vec2( wh.x, wh.y);', ' kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0;', ' kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0;', ' kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0;', ' for( int i=0; i<9; i++ ) {', ' float tmp = texture2D(tDepth, coords + offset[i]).r;', ' d += tmp * kernel[i];', ' }', ' return d;', '}', 'vec3 color(vec2 coords,float blur) {', ' //processing the sample', ' vec3 col = vec3(0.0);', ' vec2 texel = vec2(1.0/textureWidth,1.0/textureHeight);', ' col.r = texture2D(tColor,coords + vec2(0.0,1.0)*texel*fringe*blur).r;', ' col.g = texture2D(tColor,coords + vec2(-0.866,-0.5)*texel*fringe*blur).g;', ' col.b = texture2D(tColor,coords + vec2(0.866,-0.5)*texel*fringe*blur).b;', ' vec3 lumcoeff = vec3(0.299,0.587,0.114);', ' float lum = dot(col.rgb, lumcoeff);', ' float thresh = max((lum-threshold)*gain, 0.0);', ' return col+mix(vec3(0.0),col,thresh*blur);', '}', 'vec3 debugFocus(vec3 col, float blur, float depth) {', ' float edge = 0.002*depth; //distance based edge smoothing', ' float m = clamp(smoothstep(0.0,edge,blur),0.0,1.0);', ' float e = clamp(smoothstep(1.0-edge,1.0,blur),0.0,1.0);', ' col = mix(col,vec3(1.0,0.5,0.0),(1.0-m)*0.6);', ' col = mix(col,vec3(0.0,0.5,1.0),((1.0-e)-(1.0-m))*0.2);', ' return col;', '}', 'float linearize(float depth) {', ' return -zfar * znear / (depth * (zfar - znear) - zfar);', '}', 'float vignette() {', ' float dist = distance(vUv.xy, vec2(0.5,0.5));', ' dist = smoothstep(vignout+(fstop/vignfade), vignin+(fstop/vignfade), dist);', ' return clamp(dist,0.0,1.0);', '}', 'float gather(float i, float j, int ringsamples, inout vec3 col, float w, float h, float blur) {', ' float rings2 = float(rings);', ' float step = PI*2.0 / float(ringsamples);', ' float pw = cos(j*step)*i;', ' float ph = sin(j*step)*i;', ' float p = 1.0;', ' if (pentagon) {', ' p = penta(vec2(pw,ph));', ' }', ' col += color(vUv.xy + vec2(pw*w,ph*h), blur) * mix(1.0, i/rings2, bias) * p;', ' return 1.0 * mix(1.0, i /rings2, bias) * p;', '}', 'void main() {', ' //scene depth calculation', ' float depth = linearize(texture2D(tDepth,vUv.xy).x);', ' // Blur depth?', ' if ( depthblur ) {', ' depth = linearize(bdepth(vUv.xy));', ' }', ' //focal plane calculation', ' float fDepth = focalDepth;', ' if (shaderFocus) {', ' fDepth = linearize(texture2D(tDepth,focusCoords).x);', ' }', ' // dof blur factor calculation', ' float blur = 0.0;', ' if (manualdof) {', ' float a = depth-fDepth; // Focal plane', ' float b = (a-fdofstart)/fdofdist; // Far DoF', ' float c = (-a-ndofstart)/ndofdist; // Near Dof', ' blur = (a>0.0) ? b : c;', ' } else {', ' float f = focalLength; // focal length in mm', ' float d = fDepth*1000.0; // focal plane in mm', ' float o = depth*1000.0; // depth in mm', ' float a = (o*f)/(o-f);', ' float b = (d*f)/(d-f);', ' float c = (d-f)/(d*fstop*CoC);', ' blur = abs(a-b)*c;', ' }', ' blur = clamp(blur,0.0,1.0);', ' // calculation of pattern for dithering', ' vec2 noise = vec2(rand(vUv.xy), rand( vUv.xy + vec2( 0.4, 0.6 ) ) )*dithering*blur;', ' // getting blur x and y step factor', ' float w = (1.0/textureWidth)*blur*maxblur+noise.x;', ' float h = (1.0/textureHeight)*blur*maxblur+noise.y;', ' // calculation of final color', ' vec3 col = vec3(0.0);', ' if(blur < 0.05) {', ' //some optimization thingy', ' col = texture2D(tColor, vUv.xy).rgb;', ' } else {', ' col = texture2D(tColor, vUv.xy).rgb;', ' float s = 1.0;', ' int ringsamples;', ' for (int i = 1; i <= rings; i++) {', ' /*unboxstart*/', ' ringsamples = i * samples;', ' for (int j = 0 ; j < maxringsamples ; j++) {', ' if (j >= ringsamples) break;', ' s += gather(float(i), float(j), ringsamples, col, w, h, blur);', ' }', ' /*unboxend*/', ' }', ' col /= s; //divide by sample count', ' }', ' if (showFocus) {', ' col = debugFocus(col, blur, depth);', ' }', ' if (vignetting) {', ' col *= vignette();', ' }', ' gl_FragColor.rgb = col;', ' gl_FragColor.a = 1.0;', '} '].join('\n') -}); +var reactReconciler_development = {exports: {}}; /** - * Utility class for sampling weighted random points on the surface of a mesh. + * @license React + * react-reconciler.development.js * - * Building the sampler is a one-time O(n) operation. Once built, any number of - * random samples may be selected in O(logn) time. Memory usage is O(n). + * Copyright (c) Facebook, Inc. and its affiliates. * - * References: - * - http://www.joesfer.com/?p=84 - * - https://stackoverflow.com/a/4322940/1314762 + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -(function () { - var _face = new Triangle(); - - var _color = new Vector3(); - - function MeshSurfaceSampler(mesh) { - var geometry = mesh.geometry; - - if (!geometry.isBufferGeometry || geometry.attributes.position.itemSize !== 3) { - throw new Error('THREE.MeshSurfaceSampler: Requires BufferGeometry triangle mesh.'); - } - - if (geometry.index) { - console.warn('THREE.MeshSurfaceSampler: Converting geometry to non-indexed BufferGeometry.'); - geometry = geometry.toNonIndexed(); - } - - this.geometry = geometry; - this.randomFunction = Math.random; - this.positionAttribute = this.geometry.getAttribute('position'); - this.colorAttribute = this.geometry.getAttribute('color'); - this.weightAttribute = null; - this.distribution = null; - } - - MeshSurfaceSampler.prototype = { - constructor: MeshSurfaceSampler, - setWeightAttribute: function (name) { - this.weightAttribute = name ? this.geometry.getAttribute(name) : null; - return this; - }, - build: function () { - var positionAttribute = this.positionAttribute; - var weightAttribute = this.weightAttribute; - var faceWeights = new Float32Array(positionAttribute.count / 3); // Accumulate weights for each mesh face. - - for (let i = 0; i < positionAttribute.count; i += 3) { - var faceWeight = 1; - - if (weightAttribute) { - faceWeight = weightAttribute.getX(i) + weightAttribute.getX(i + 1) + weightAttribute.getX(i + 2); - } - - _face.a.fromBufferAttribute(positionAttribute, i); - - _face.b.fromBufferAttribute(positionAttribute, i + 1); - - _face.c.fromBufferAttribute(positionAttribute, i + 2); - - faceWeight *= _face.getArea(); - faceWeights[i / 3] = faceWeight; - } // Store cumulative total face weights in an array, where weight index - // corresponds to face index. - - - this.distribution = new Float32Array(positionAttribute.count / 3); - var cumulativeTotal = 0; - - for (let i = 0; i < faceWeights.length; i++) { - cumulativeTotal += faceWeights[i]; - this.distribution[i] = cumulativeTotal; - } - - return this; - }, - setRandomGenerator: function (randomFunction) { - this.randomFunction = randomFunction; - return this; - }, - sample: function (targetPosition, targetNormal, targetColor) { - var cumulativeTotal = this.distribution[this.distribution.length - 1]; - var faceIndex = this.binarySearch(this.randomFunction() * cumulativeTotal); - return this.sampleFace(faceIndex, targetPosition, targetNormal, targetColor); - }, - binarySearch: function (x) { - var dist = this.distribution; - var start = 0; - var end = dist.length - 1; - var index = -1; - - while (start <= end) { - var mid = Math.ceil((start + end) / 2); - - if (mid === 0 || dist[mid - 1] <= x && dist[mid] > x) { - index = mid; - break; - } else if (x < dist[mid]) { - end = mid - 1; - } else { - start = mid + 1; - } - } - - return index; - }, - sampleFace: function (faceIndex, targetPosition, targetNormal, targetColor) { - var u = this.randomFunction(); - var v = this.randomFunction(); - - if (u + v > 1) { - u = 1 - u; - v = 1 - v; - } - - _face.a.fromBufferAttribute(this.positionAttribute, faceIndex * 3); - - _face.b.fromBufferAttribute(this.positionAttribute, faceIndex * 3 + 1); - - _face.c.fromBufferAttribute(this.positionAttribute, faceIndex * 3 + 2); - - targetPosition.set(0, 0, 0).addScaledVector(_face.a, u).addScaledVector(_face.b, v).addScaledVector(_face.c, 1 - (u + v)); - - if (targetNormal !== undefined) { - _face.getNormal(targetNormal); - } - - if (targetColor !== undefined && this.colorAttribute !== undefined) { - _face.a.fromBufferAttribute(this.colorAttribute, faceIndex * 3); - - _face.b.fromBufferAttribute(this.colorAttribute, faceIndex * 3 + 1); - - _face.c.fromBufferAttribute(this.colorAttribute, faceIndex * 3 + 2); - - _color.set(0, 0, 0).addScaledVector(_face.a, u).addScaledVector(_face.b, v).addScaledVector(_face.c, 1 - (u + v)); - - targetColor.r = _color.x; - targetColor.g = _color.y; - targetColor.b = _color.z; - } - - return this; - } - }; - return MeshSurfaceSampler; -})(); - -var a$2 = { - c: null, - // center - u: [new Vector3(), new Vector3(), new Vector3()], - // basis vectors - e: [] // half width - -}; -var b$1 = { - c: null, - // center - u: [new Vector3(), new Vector3(), new Vector3()], - // basis vectors - e: [] // half width - -}; -var R$1 = [[], [], []]; -var AbsR = [[], [], []]; -var t$1 = []; -var xAxis = new Vector3(); -var yAxis = new Vector3(); -var zAxis = new Vector3(); -var v1 = new Vector3(); -var size = new Vector3(); -var closestPoint = new Vector3(); -var rotationMatrix = new Matrix3(); -var aabb$1 = new Box3(); -var matrix = new Matrix4(); -var inverse = new Matrix4(); -var localRay = new Ray(); // OBB - -function OBB(center = new Vector3(), halfSize = new Vector3(), rotation = new Matrix3()) { - this.center = center; - this.halfSize = halfSize; - this.rotation = rotation; -} - -Object.assign(OBB.prototype, { - set: function (center, halfSize, rotation) { - this.center = center; - this.halfSize = halfSize; - this.rotation = rotation; - return this; - }, - copy: function (obb) { - this.center.copy(obb.center); - this.halfSize.copy(obb.halfSize); - this.rotation.copy(obb.rotation); - return this; - }, - clone: function () { - return new this.constructor().copy(this); - }, - getSize: function (result) { - return result.copy(this.halfSize).multiplyScalar(2); - }, - - /** - * Reference: Closest Point on OBB to Point in Real-Time Collision Detection - * by Christer Ericson (chapter 5.1.4) - */ - clampPoint: function (point, result) { - var halfSize = this.halfSize; - v1.subVectors(point, this.center); - this.rotation.extractBasis(xAxis, yAxis, zAxis); // start at the center position of the OBB - - result.copy(this.center); // project the target onto the OBB axes and walk towards that point - - var x = MathUtils.clamp(v1.dot(xAxis), -halfSize.x, halfSize.x); - result.add(xAxis.multiplyScalar(x)); - var y = MathUtils.clamp(v1.dot(yAxis), -halfSize.y, halfSize.y); - result.add(yAxis.multiplyScalar(y)); - var z = MathUtils.clamp(v1.dot(zAxis), -halfSize.z, halfSize.z); - result.add(zAxis.multiplyScalar(z)); - return result; - }, - containsPoint: function (point) { - v1.subVectors(point, this.center); - this.rotation.extractBasis(xAxis, yAxis, zAxis); // project v1 onto each axis and check if these points lie inside the OBB - - return Math.abs(v1.dot(xAxis)) <= this.halfSize.x && Math.abs(v1.dot(yAxis)) <= this.halfSize.y && Math.abs(v1.dot(zAxis)) <= this.halfSize.z; - }, - intersectsBox3: function (box3) { - return this.intersectsOBB(obb$1.fromBox3(box3)); - }, - intersectsSphere: function (sphere) { - // find the point on the OBB closest to the sphere center - this.clampPoint(sphere.center, closestPoint); // if that point is inside the sphere, the OBB and sphere intersect - - return closestPoint.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; - }, - - /** - * Reference: OBB-OBB Intersection in Real-Time Collision Detection - * by Christer Ericson (chapter 4.4.1) - * - */ - intersectsOBB: function (obb, epsilon = Number.EPSILON) { - // prepare data structures (the code uses the same nomenclature like the reference) - a$2.c = this.center; - a$2.e[0] = this.halfSize.x; - a$2.e[1] = this.halfSize.y; - a$2.e[2] = this.halfSize.z; - this.rotation.extractBasis(a$2.u[0], a$2.u[1], a$2.u[2]); - b$1.c = obb.center; - b$1.e[0] = obb.halfSize.x; - b$1.e[1] = obb.halfSize.y; - b$1.e[2] = obb.halfSize.z; - obb.rotation.extractBasis(b$1.u[0], b$1.u[1], b$1.u[2]); // compute rotation matrix expressing b in a's coordinate frame - - for (let i = 0; i < 3; i++) { - for (let j = 0; j < 3; j++) { - R$1[i][j] = a$2.u[i].dot(b$1.u[j]); - } - } // compute translation vector - - - v1.subVectors(b$1.c, a$2.c); // bring translation into a's coordinate frame - - t$1[0] = v1.dot(a$2.u[0]); - t$1[1] = v1.dot(a$2.u[1]); - t$1[2] = v1.dot(a$2.u[2]); // compute common subexpressions. Add in an epsilon term to - // counteract arithmetic errors when two edges are parallel and - // their cross product is (near) null - - for (let i = 0; i < 3; i++) { - for (let j = 0; j < 3; j++) { - AbsR[i][j] = Math.abs(R$1[i][j]) + epsilon; - } - } - - var ra, rb; // test axes L = A0, L = A1, L = A2 - - for (let i = 0; i < 3; i++) { - ra = a$2.e[i]; - rb = b$1.e[0] * AbsR[i][0] + b$1.e[1] * AbsR[i][1] + b$1.e[2] * AbsR[i][2]; - if (Math.abs(t$1[i]) > ra + rb) return false; - } // test axes L = B0, L = B1, L = B2 - - - for (let i = 0; i < 3; i++) { - ra = a$2.e[0] * AbsR[0][i] + a$2.e[1] * AbsR[1][i] + a$2.e[2] * AbsR[2][i]; - rb = b$1.e[i]; - if (Math.abs(t$1[0] * R$1[0][i] + t$1[1] * R$1[1][i] + t$1[2] * R$1[2][i]) > ra + rb) return false; - } // test axis L = A0 x B0 - - - ra = a$2.e[1] * AbsR[2][0] + a$2.e[2] * AbsR[1][0]; - rb = b$1.e[1] * AbsR[0][2] + b$1.e[2] * AbsR[0][1]; - if (Math.abs(t$1[2] * R$1[1][0] - t$1[1] * R$1[2][0]) > ra + rb) return false; // test axis L = A0 x B1 - - ra = a$2.e[1] * AbsR[2][1] + a$2.e[2] * AbsR[1][1]; - rb = b$1.e[0] * AbsR[0][2] + b$1.e[2] * AbsR[0][0]; - if (Math.abs(t$1[2] * R$1[1][1] - t$1[1] * R$1[2][1]) > ra + rb) return false; // test axis L = A0 x B2 - - ra = a$2.e[1] * AbsR[2][2] + a$2.e[2] * AbsR[1][2]; - rb = b$1.e[0] * AbsR[0][1] + b$1.e[1] * AbsR[0][0]; - if (Math.abs(t$1[2] * R$1[1][2] - t$1[1] * R$1[2][2]) > ra + rb) return false; // test axis L = A1 x B0 - - ra = a$2.e[0] * AbsR[2][0] + a$2.e[2] * AbsR[0][0]; - rb = b$1.e[1] * AbsR[1][2] + b$1.e[2] * AbsR[1][1]; - if (Math.abs(t$1[0] * R$1[2][0] - t$1[2] * R$1[0][0]) > ra + rb) return false; // test axis L = A1 x B1 - - ra = a$2.e[0] * AbsR[2][1] + a$2.e[2] * AbsR[0][1]; - rb = b$1.e[0] * AbsR[1][2] + b$1.e[2] * AbsR[1][0]; - if (Math.abs(t$1[0] * R$1[2][1] - t$1[2] * R$1[0][1]) > ra + rb) return false; // test axis L = A1 x B2 - - ra = a$2.e[0] * AbsR[2][2] + a$2.e[2] * AbsR[0][2]; - rb = b$1.e[0] * AbsR[1][1] + b$1.e[1] * AbsR[1][0]; - if (Math.abs(t$1[0] * R$1[2][2] - t$1[2] * R$1[0][2]) > ra + rb) return false; // test axis L = A2 x B0 - - ra = a$2.e[0] * AbsR[1][0] + a$2.e[1] * AbsR[0][0]; - rb = b$1.e[1] * AbsR[2][2] + b$1.e[2] * AbsR[2][1]; - if (Math.abs(t$1[1] * R$1[0][0] - t$1[0] * R$1[1][0]) > ra + rb) return false; // test axis L = A2 x B1 - - ra = a$2.e[0] * AbsR[1][1] + a$2.e[1] * AbsR[0][1]; - rb = b$1.e[0] * AbsR[2][2] + b$1.e[2] * AbsR[2][0]; - if (Math.abs(t$1[1] * R$1[0][1] - t$1[0] * R$1[1][1]) > ra + rb) return false; // test axis L = A2 x B2 - - ra = a$2.e[0] * AbsR[1][2] + a$2.e[1] * AbsR[0][2]; - rb = b$1.e[0] * AbsR[2][1] + b$1.e[1] * AbsR[2][0]; - if (Math.abs(t$1[1] * R$1[0][2] - t$1[0] * R$1[1][2]) > ra + rb) return false; // since no separating axis is found, the OBBs must be intersecting - - return true; - }, - - /** - * Reference: Testing Box Against Plane in Real-Time Collision Detection - * by Christer Ericson (chapter 5.2.3) - */ - intersectsPlane: function (plane) { - this.rotation.extractBasis(xAxis, yAxis, zAxis); // compute the projection interval radius of this OBB onto L(t) = this->center + t * p.normal; - - const r = this.halfSize.x * Math.abs(plane.normal.dot(xAxis)) + this.halfSize.y * Math.abs(plane.normal.dot(yAxis)) + this.halfSize.z * Math.abs(plane.normal.dot(zAxis)); // compute distance of the OBB's center from the plane - - const d = plane.normal.dot(this.center) - plane.constant; // Intersection occurs when distance d falls within [-r,+r] interval - - return Math.abs(d) <= r; - }, - - /** - * Performs a ray/OBB intersection test and stores the intersection point - * to the given 3D vector. If no intersection is detected, *null* is returned. - */ - intersectRay: function (ray, result) { - // the idea is to perform the intersection test in the local space - // of the OBB. - this.getSize(size); - aabb$1.setFromCenterAndSize(v1.set(0, 0, 0), size); // create a 4x4 transformation matrix - - matrix4FromRotationMatrix(matrix, this.rotation); - matrix.setPosition(this.center); // transform ray to the local space of the OBB - - inverse.copy(matrix).invert(); - localRay.copy(ray).applyMatrix4(inverse); // perform ray <-> AABB intersection test - - if (localRay.intersectBox(aabb$1, result)) { - // transform the intersection point back to world space - return result.applyMatrix4(matrix); - } else { - return null; - } - }, - - /** - * Performs a ray/OBB intersection test. Returns either true or false if - * there is a intersection or not. - */ - intersectsRay: function (ray) { - return this.intersectRay(ray, v1) !== null; - }, - fromBox3: function (box3) { - box3.getCenter(this.center); - box3.getSize(this.halfSize).multiplyScalar(0.5); - this.rotation.identity(); - return this; - }, - equals: function (obb) { - return obb.center.equals(this.center) && obb.halfSize.equals(this.halfSize) && obb.rotation.equals(this.rotation); - }, - applyMatrix4: function (matrix) { - var e = matrix.elements; - var sx = v1.set(e[0], e[1], e[2]).length(); - var sy = v1.set(e[4], e[5], e[6]).length(); - var sz = v1.set(e[8], e[9], e[10]).length(); - var det = matrix.determinant(); - if (det < 0) sx = -sx; - rotationMatrix.setFromMatrix4(matrix); - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; - rotationMatrix.elements[0] *= invSX; - rotationMatrix.elements[1] *= invSX; - rotationMatrix.elements[2] *= invSX; - rotationMatrix.elements[3] *= invSY; - rotationMatrix.elements[4] *= invSY; - rotationMatrix.elements[5] *= invSY; - rotationMatrix.elements[6] *= invSZ; - rotationMatrix.elements[7] *= invSZ; - rotationMatrix.elements[8] *= invSZ; - this.rotation.multiply(rotationMatrix); - this.halfSize.x *= sx; - this.halfSize.y *= sy; - this.halfSize.z *= sz; - v1.setFromMatrixPosition(matrix); - this.center.add(v1); - return this; - } -}); - -function matrix4FromRotationMatrix(matrix4, matrix3) { - var e = matrix4.elements; - var me = matrix3.elements; - e[0] = me[0]; - e[1] = me[1]; - e[2] = me[2]; - e[3] = 0; - e[4] = me[3]; - e[5] = me[4]; - e[6] = me[5]; - e[7] = 0; - e[8] = me[6]; - e[9] = me[7]; - e[10] = me[8]; - e[11] = 0; - e[12] = 0; - e[13] = 0; - e[14] = 0; - e[15] = 1; -} - -var obb$1 = new OBB(); - -var Capsule = function () { - var _v1 = new Vector3(); - - var _v2 = new Vector3(); - - var _v3 = new Vector3(); - - var EPS = 1e-10; +var hasRequiredReactReconciler_development; - function Capsule(start, end, radius) { - this.start = start == undefined ? new Vector3(0, 0, 0) : start; - this.end = end == undefined ? new Vector3(0, 1, 0) : end; - this.radius = radius == undefined ? 1 : radius; - } +function requireReactReconciler_development () { + if (hasRequiredReactReconciler_development) return reactReconciler_development.exports; + hasRequiredReactReconciler_development = 1; - Object.assign(Capsule.prototype, { - clone: function () { - return new Capsule(this.start.clone(), this.end.clone(), this.radius); - }, - set: function (start, end, radius) { - this.start.copy(start); - this.end.copy(end); - this.radius = radius; - }, - copy: function (capsule) { - this.start.copy(capsule.start); - this.end.copy(capsule.end); - this.radius = capsule.radius; - }, - getCenter: function (target) { - return target.copy(this.end).add(this.start).multiplyScalar(0.5); - }, - translate: function (v) { - this.start.add(v); - this.end.add(v); - }, - checkAABBAxis: function (p1x, p1y, p2x, p2y, minx, maxx, miny, maxy, radius) { - return (minx - p1x < radius || minx - p2x < radius) && (p1x - maxx < radius || p2x - maxx < radius) && (miny - p1y < radius || miny - p2y < radius) && (p1y - maxy < radius || p2y - maxy < radius); - }, - intersectsBox: function (box) { - return this.checkAABBAxis(this.start.x, this.start.y, this.end.x, this.end.y, box.min.x, box.max.x, box.min.y, box.max.y, this.radius) && this.checkAABBAxis(this.start.x, this.start.z, this.end.x, this.end.z, box.min.x, box.max.x, box.min.z, box.max.z, this.radius) && this.checkAABBAxis(this.start.y, this.start.z, this.end.y, this.end.z, box.min.y, box.max.y, box.min.z, box.max.z, this.radius); - }, - lineLineMinimumPoints: function (line1, line2) { - var r = _v1.copy(line1.end).sub(line1.start); + if (process.env.NODE_ENV !== "production") { + reactReconciler_development.exports = function $$$reconciler($$$hostConfig) { + var exports = {}; - var s = _v2.copy(line2.end).sub(line2.start); + var React = React__default["default"]; + var Scheduler = scheduler$1.exports; - var w = _v3.copy(line2.start).sub(line1.start); + var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - var a = r.dot(s), - b = r.dot(r), - c = s.dot(s), - d = s.dot(w), - e = r.dot(w); - var t1, - t2, - divisor = b * c - a * a; + var suppressWarning = false; + function setSuppressWarning(newSuppressWarning) { + { + suppressWarning = newSuppressWarning; + } + } // In DEV, calls to console.warn and console.error get replaced + // by calls to these methods by a Babel plugin. + // + // In PROD (or in packages without access to React internals), + // they are left as they are instead. - if (Math.abs(divisor) < EPS) { - var d1 = -d / c; - var d2 = (a - d) / c; + function warn(format) { + { + if (!suppressWarning) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } - if (Math.abs(d1 - 0.5) < Math.abs(d2 - 0.5)) { - t1 = 0; - t2 = d1; - } else { - t1 = 1; - t2 = d2; - } - } else { - t1 = (d * a + e * c) / divisor; - t2 = (t1 * a - d) / c; - } + printWarning('warn', format, args); + } + } + } + function error(format) { + { + if (!suppressWarning) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } - t2 = Math.max(0, Math.min(1, t2)); - t1 = Math.max(0, Math.min(1, t1)); - var point1 = r.multiplyScalar(t1).add(line1.start); - var point2 = s.multiplyScalar(t2).add(line2.start); - return [point1, point2]; - } - }); - return Capsule; -}(); + printWarning('error', format, args); + } + } + } -(function () { - var _v1 = new Vector3(); + function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); - var _v2 = new Vector3(); + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion - var _plane = new Plane(); - var _line1 = new Line3(); + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix - var _line2 = new Line3(); + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging - var _sphere = new Sphere(); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } - var _capsule = new Capsule(); + var assign = Object.assign; - function Octree(box) { - this.triangles = []; - this.box = box; - this.subTrees = []; - } + /** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + * + * Note that this module is currently shared and assumed to be stateless. + * If this becomes an actual Map, that will break. + */ + function get(key) { + return key._reactInternals; + } + function set(key, value) { + key._reactInternals = value; + } - Object.assign(Octree.prototype, { - addTriangle: function (triangle) { - if (!this.bounds) this.bounds = new Box3(); - this.bounds.min.x = Math.min(this.bounds.min.x, triangle.a.x, triangle.b.x, triangle.c.x); - this.bounds.min.y = Math.min(this.bounds.min.y, triangle.a.y, triangle.b.y, triangle.c.y); - this.bounds.min.z = Math.min(this.bounds.min.z, triangle.a.z, triangle.b.z, triangle.c.z); - this.bounds.max.x = Math.max(this.bounds.max.x, triangle.a.x, triangle.b.x, triangle.c.x); - this.bounds.max.y = Math.max(this.bounds.max.y, triangle.a.y, triangle.b.y, triangle.c.y); - this.bounds.max.z = Math.max(this.bounds.max.z, triangle.a.z, triangle.b.z, triangle.c.z); - this.triangles.push(triangle); - return this; - }, - calcBox: function () { - this.box = this.bounds.clone(); // offset small ammount to account for regular grid + // ----------------------------------------------------------------------------- + var enablePersistentOffscreenHostContainer = false; // ----------------------------------------------------------------------------- + // the react-reconciler package. - this.box.min.x -= 0.01; - this.box.min.y -= 0.01; - this.box.min.z -= 0.01; - return this; - }, - split: function (level) { - if (!this.box) return; - - var subTrees = [], - halfsize = _v2.copy(this.box.max).sub(this.box.min).multiplyScalar(0.5), - box, - v, - triangle; - - for (let x = 0; x < 2; x++) { - for (let y = 0; y < 2; y++) { - for (let z = 0; z < 2; z++) { - box = new Box3(); - v = _v1.set(x, y, z); - box.min.copy(this.box.min).add(v.multiply(halfsize)); - box.max.copy(box.min).add(halfsize); - subTrees.push(new Octree(box)); - } - } - } + var enableNewReconciler = false; // Support legacy Primer support on internal FB www - while (triangle = this.triangles.pop()) { - for (let i = 0; i < subTrees.length; i++) { - if (subTrees[i].box.intersectsTriangle(triangle)) { - subTrees[i].triangles.push(triangle); - } - } - } + var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics. - for (let i = 0; i < subTrees.length; i++) { - var len = subTrees[i].triangles.length; + var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber - if (len > 8 && level < 16) { - subTrees[i].split(level + 1); - } + var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz + var warnAboutStringRefs = false; // ----------------------------------------------------------------------------- + // Debugging and DevTools + // ----------------------------------------------------------------------------- + // Adds user timing marks for e.g. state updates, suspense, and work loop stuff, + // for an experimental timeline tool. - if (len != 0) { - this.subTrees.push(subTrees[i]); - } - } + var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState - return this; - }, - build: function () { - this.calcBox(); - this.split(0); - return this; - }, - getRayTriangles: function (ray, triangles) { - for (let i = 0; i < this.subTrees.length; i++) { - var subTree = this.subTrees[i]; - if (!ray.intersectsBox(subTree.box)) continue; - - if (subTree.triangles.length > 0) { - for (let j = 0; j < subTree.triangles.length; j++) { - if (triangles.indexOf(subTree.triangles[j]) === -1) triangles.push(subTree.triangles[j]); - } - } else { - subTree.getRayTriangles(ray, triangles); - } - } + var enableProfilerTimer = true; // Record durations for commit and passive effects phases. - return triangles; - }, - triangleCapsuleIntersect: function (capsule, triangle) { - var point1, point2, line1, line2; - triangle.getPlane(_plane); - var d1 = _plane.distanceToPoint(capsule.start) - capsule.radius; - var d2 = _plane.distanceToPoint(capsule.end) - capsule.radius; + var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update". - if (d1 > 0 && d2 > 0 || d1 < -capsule.radius && d2 < -capsule.radius) { - return false; - } + var FunctionComponent = 0; + var ClassComponent = 1; + var IndeterminateComponent = 2; // Before we know whether it is function or class - var delta = Math.abs(d1 / (Math.abs(d1) + Math.abs(d2))); + var HostRoot = 3; // Root of a host tree. Could be nested inside another node. - var intersectPoint = _v1.copy(capsule.start).lerp(capsule.end, delta); + var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. - if (triangle.containsPoint(intersectPoint)) { - return { - normal: _plane.normal.clone(), - point: intersectPoint.clone(), - depth: Math.abs(Math.min(d1, d2)) - }; - } + var HostComponent = 5; + var HostText = 6; + var Fragment = 7; + var Mode = 8; + var ContextConsumer = 9; + var ContextProvider = 10; + var ForwardRef = 11; + var Profiler = 12; + var SuspenseComponent = 13; + var MemoComponent = 14; + var SimpleMemoComponent = 15; + var LazyComponent = 16; + var IncompleteClassComponent = 17; + var DehydratedFragment = 18; + var SuspenseListComponent = 19; + var ScopeComponent = 21; + var OffscreenComponent = 22; + var LegacyHiddenComponent = 23; + var CacheComponent = 24; + var TracingMarkerComponent = 25; - var r2 = capsule.radius * capsule.radius; - line1 = _line1.set(capsule.start, capsule.end); - var lines = [[triangle.a, triangle.b], [triangle.b, triangle.c], [triangle.c, triangle.a]]; + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. + var REACT_ELEMENT_TYPE = Symbol.for('react.element'); + var REACT_PORTAL_TYPE = Symbol.for('react.portal'); + var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); + var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); + var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); + var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); + var REACT_CONTEXT_TYPE = Symbol.for('react.context'); + var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); + var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); + var REACT_MEMO_TYPE = Symbol.for('react.memo'); + var REACT_LAZY_TYPE = Symbol.for('react.lazy'); + var REACT_SCOPE_TYPE = Symbol.for('react.scope'); + var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); + var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); + var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); + var REACT_CACHE_TYPE = Symbol.for('react.cache'); + var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker'); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } - for (let i = 0; i < lines.length; i++) { - line2 = _line2.set(lines[i][0], lines[i][1]); - [point1, point2] = capsule.lineLineMinimumPoints(line1, line2); + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (point1.distanceToSquared(point2) < r2) { - return { - normal: point1.clone().sub(point2).normalize(), - point: point2.clone(), - depth: capsule.radius - point1.distanceTo(point2) - }; - } - } + if (typeof maybeIterator === 'function') { + return maybeIterator; + } - return false; - }, - triangleSphereIntersect: function (sphere, triangle) { - triangle.getPlane(_plane); - if (!sphere.intersectsPlane(_plane)) return false; - var depth = Math.abs(_plane.distanceToSphere(sphere)); - var r2 = sphere.radius * sphere.radius - depth * depth; + return null; + } - var plainPoint = _plane.projectPoint(sphere.center, _v1); + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; - if (triangle.containsPoint(sphere.center)) { - return { - normal: _plane.normal.clone(), - point: plainPoint.clone(), - depth: Math.abs(_plane.distanceToSphere(sphere)) - }; - } + if (displayName) { + return displayName; + } - var lines = [[triangle.a, triangle.b], [triangle.b, triangle.c], [triangle.c, triangle.a]]; + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; + } // Keep in sync with react-reconciler/getComponentNameFromFiber - for (let i = 0; i < lines.length; i++) { - _line1.set(lines[i][0], lines[i][1]); - _line1.closestPointToPoint(plainPoint, true, _v2); + function getContextName(type) { + return type.displayName || 'Context'; + } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. - var d = _v2.distanceToSquared(sphere.center); - if (d < r2) { - return { - normal: sphere.center.clone().sub(_v2).normalize(), - point: _v2.clone(), - depth: sphere.radius - Math.sqrt(d) - }; - } - } + function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } - return false; - }, - getSphereTriangles: function (sphere, triangles) { - for (let i = 0; i < this.subTrees.length; i++) { - var subTree = this.subTrees[i]; - if (!sphere.intersectsBox(subTree.box)) continue; - - if (subTree.triangles.length > 0) { - for (let j = 0; j < subTree.triangles.length; j++) { - if (triangles.indexOf(subTree.triangles[j]) === -1) triangles.push(subTree.triangles[j]); - } - } else { - subTree.getSphereTriangles(sphere, triangles); - } - } - }, - getCapsuleTriangles: function (capsule, triangles) { - for (let i = 0; i < this.subTrees.length; i++) { - var subTree = this.subTrees[i]; - if (!capsule.intersectsBox(subTree.box)) continue; - - if (subTree.triangles.length > 0) { - for (let j = 0; j < subTree.triangles.length; j++) { - if (triangles.indexOf(subTree.triangles[j]) === -1) triangles.push(subTree.triangles[j]); - } - } else { - subTree.getCapsuleTriangles(capsule, triangles); - } - } - }, + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } - sphereIntersect(sphere) { - _sphere.copy(sphere); + if (typeof type === 'function') { + return type.displayName || type.name || null; + } - var triangles = [], - result, - hit = false; - this.getSphereTriangles(sphere, triangles); + if (typeof type === 'string') { + return type; + } - for (let i = 0; i < triangles.length; i++) { - if (result = this.triangleSphereIntersect(_sphere, triangles[i])) { - hit = true; + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; - _sphere.center.add(result.normal.multiplyScalar(result.depth)); - } - } + case REACT_PORTAL_TYPE: + return 'Portal'; - if (hit) { - var collisionVector = _sphere.center.clone().sub(sphere.center); + case REACT_PROFILER_TYPE: + return 'Profiler'; - var depth = collisionVector.length(); - return { - normal: collisionVector.normalize(), - depth: depth - }; - } + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; - return false; - }, + case REACT_SUSPENSE_TYPE: + return 'Suspense'; - capsuleIntersect: function (capsule) { - _capsule.copy(capsule); + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; - var triangles = [], - result, - hit = false; - this.getCapsuleTriangles(_capsule, triangles); + } - for (let i = 0; i < triangles.length; i++) { - if (result = this.triangleCapsuleIntersect(_capsule, triangles[i])) { - hit = true; + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; - _capsule.translate(result.normal.multiplyScalar(result.depth)); - } - } + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; - if (hit) { - var collisionVector = _capsule.getCenter(new Vector3()).sub(capsule.getCenter(_v1)); + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); - var depth = collisionVector.length(); - return { - normal: collisionVector.normalize(), - depth: depth - }; - } + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; - return false; - }, - rayIntersect: function (ray) { - if (ray.direction.length() === 0) return; - var triangles = [], - triangle, - position, - distance = 1e100, - result; - this.getRayTriangles(ray, triangles); - - for (let i = 0; i < triangles.length; i++) { - result = ray.intersectTriangle(triangles[i].a, triangles[i].b, triangles[i].c, true, _v1); - - if (result) { - var newdistance = result.sub(ray.origin).length(); - - if (distance > newdistance) { - position = result.clone().add(ray.origin); - distance = newdistance; - triangle = triangles[i]; - } - } - } + if (outerName !== null) { + return outerName; + } - return distance < 1e100 ? { - distance: distance, - triangle: triangle, - position: position - } : false; - }, - fromGraphNode: function (group) { - group.traverse(obj => { - if (obj.type === 'Mesh') { - obj.updateMatrix(); - obj.updateWorldMatrix(); - var geometry, - isTemp = false; - - if (obj.geometry.index) { - isTemp = true; - geometry = obj.geometry.clone().toNonIndexed(); - } else { - geometry = obj.geometry; - } + return getComponentNameFromType(type.type) || 'Memo'; - var positions = geometry.attributes.position.array; - var transform = obj.matrixWorld; - - for (let i = 0; i < positions.length; i += 9) { - var v1 = new Vector3(positions[i], positions[i + 1], positions[i + 2]); - var v2 = new Vector3(positions[i + 3], positions[i + 4], positions[i + 5]); - var v3 = new Vector3(positions[i + 6], positions[i + 7], positions[i + 8]); - v1.applyMatrix4(transform); - v2.applyMatrix4(transform); - v3.applyMatrix4(transform); - this.addTriangle(new Triangle(v1, v2, v3)); - } + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; - if (isTemp) { - geometry.dispose(); - } - } - }); - this.build(); - return this; - } - }); - return Octree; -})(); + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } -var Lut = function (colormap, numberofcolors) { - this.lut = []; - this.setColorMap(colormap, numberofcolors); - return this; -}; + // eslint-disable-next-line no-fallthrough + } + } -Lut.prototype = { - constructor: Lut, - lut: [], - map: [], - n: 256, - minV: 0, - maxV: 1, - set: function (value) { - if (value instanceof Lut) { - this.copy(value); - } + return null; + } - return this; - }, - setMin: function (min) { - this.minV = min; - return this; - }, - setMax: function (max) { - this.maxV = max; - return this; - }, - setColorMap: function (colormap, numberofcolors) { - this.map = ColorMapKeywords[colormap] || ColorMapKeywords.rainbow; - this.n = numberofcolors || 32; - var step = 1.0 / this.n; - this.lut.length = 0; - - for (let i = 0; i <= 1; i += step) { - for (let j = 0; j < this.map.length - 1; j++) { - if (i >= this.map[j][0] && i < this.map[j + 1][0]) { - var min = this.map[j][0]; - var max = this.map[j + 1][0]; - var minColor = new Color(this.map[j][1]); - var maxColor = new Color(this.map[j + 1][1]); - var color = minColor.lerp(maxColor, (i - min) / (max - min)); - this.lut.push(color); - } - } - } + function getWrappedName$1(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ''; + return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); + } // Keep in sync with shared/getComponentNameFromType - return this; - }, - copy: function (lut) { - this.lut = lut.lut; - this.map = lut.map; - this.n = lut.n; - this.minV = lut.minV; - this.maxV = lut.maxV; - return this; - }, - getColor: function (alpha) { - if (alpha <= this.minV) { - alpha = this.minV; - } else if (alpha >= this.maxV) { - alpha = this.maxV; - } - alpha = (alpha - this.minV) / (this.maxV - this.minV); - var colorPosition = Math.round(alpha * this.n); - colorPosition == this.n ? colorPosition -= 1 : colorPosition; - return this.lut[colorPosition]; - }, - addColorMap: function (colormapName, arrayOfColors) { - ColorMapKeywords[colormapName] = arrayOfColors; - }, - createCanvas: function () { - var canvas = document.createElement('canvas'); - canvas.width = 1; - canvas.height = this.n; - this.updateCanvas(canvas); - return canvas; - }, - updateCanvas: function (canvas) { - var ctx = canvas.getContext('2d', { - alpha: false - }); - var imageData = ctx.getImageData(0, 0, 1, this.n); - var data = imageData.data; - var k = 0; - var step = 1.0 / this.n; - - for (let i = 1; i >= 0; i -= step) { - for (let j = this.map.length - 1; j >= 0; j--) { - if (i < this.map[j][0] && i >= this.map[j - 1][0]) { - var min = this.map[j - 1][0]; - var max = this.map[j][0]; - var minColor = new Color(this.map[j - 1][1]); - var maxColor = new Color(this.map[j][1]); - var color = minColor.lerp(maxColor, (i - min) / (max - min)); - data[k * 4] = Math.round(color.r * 255); - data[k * 4 + 1] = Math.round(color.g * 255); - data[k * 4 + 2] = Math.round(color.b * 255); - data[k * 4 + 3] = 255; - k += 1; - } - } - } + function getContextName$1(type) { + return type.displayName || 'Context'; + } - ctx.putImageData(imageData, 0, 0); - return canvas; - } -}; -var ColorMapKeywords = { - rainbow: [[0.0, 0x0000ff], [0.2, 0x00ffff], [0.5, 0x00ff00], [0.8, 0xffff00], [1.0, 0xff0000]], - cooltowarm: [[0.0, 0x3c4ec2], [0.2, 0x9bbcff], [0.5, 0xdcdcdc], [0.8, 0xf6a385], [1.0, 0xb40426]], - blackbody: [[0.0, 0x000000], [0.2, 0x780000], [0.5, 0xe63200], [0.8, 0xffff00], [1.0, 0xffffff]], - grayscale: [[0.0, 0x000000], [0.2, 0x404040], [0.5, 0x7f7f80], [0.8, 0xbfbfbf], [1.0, 0xffffff]] -}; + function getComponentNameFromFiber(fiber) { + var tag = fiber.tag, + type = fiber.type; -let STATE; + switch (tag) { + case CacheComponent: + return 'Cache'; -(function (STATE) { - STATE[STATE["NONE"] = -1] = "NONE"; - STATE[STATE["ROTATE"] = 0] = "ROTATE"; - STATE[STATE["DOLLY"] = 1] = "DOLLY"; - STATE[STATE["PAN"] = 2] = "PAN"; - STATE[STATE["TOUCH_ROTATE"] = 3] = "TOUCH_ROTATE"; - STATE[STATE["TOUCH_PAN"] = 4] = "TOUCH_PAN"; - STATE[STATE["TOUCH_DOLLY_PAN"] = 5] = "TOUCH_DOLLY_PAN"; - STATE[STATE["TOUCH_DOLLY_ROTATE"] = 6] = "TOUCH_DOLLY_ROTATE"; -})(STATE || (STATE = {})); + case ContextConsumer: + var context = type; + return getContextName$1(context) + '.Consumer'; -new Vector3(); + case ContextProvider: + var provider = type; + return getContextName$1(provider._context) + '.Provider'; -// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). -// -// Orbit - left mouse / touch: one-finger move -// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish -// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move - -const moduloWrapAround = (offset, capacity) => (offset % capacity + capacity) % capacity; - -class OrbitControls$1 extends EventDispatcher { - // Set to false to disable this control - // "target" sets the location of focus, where the object orbits around - // How far you can dolly in and out ( PerspectiveCamera only ) - // How far you can zoom in and out ( OrthographicCamera only ) - // How far you can orbit vertically, upper and lower limits. - // Range is 0 to Math.PI radians. - // radians - // radians - // How far you can orbit horizontally, upper and lower limits. - // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) - // radians - // radians - // Set to true to enable damping (inertia) - // If damping is enabled, you must call controls.update() in your animation loop - // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. - // Set to false to disable zooming - // Set to false to disable rotating - // Set to false to disable panning - // if false, pan orthogonal to world-space direction camera.up - // pixels moved per arrow key push - // Set to true to automatically rotate around the target - // If auto-rotate is enabled, you must call controls.update() in your animation loop - // 30 seconds per orbit when fps is 60 - // true if you want to reverse the orbit to mouse drag from left to right = orbits left - // The four arrow keys - // Mouse buttons - // Touch fingers - // the target DOM element for key events - constructor(object, domElement) { - super(); + case DehydratedFragment: + return 'DehydratedFragment'; - _defineProperty$1(this, "object", void 0); + case ForwardRef: + return getWrappedName$1(type, type.render, 'ForwardRef'); - _defineProperty$1(this, "domElement", void 0); + case Fragment: + return 'Fragment'; - _defineProperty$1(this, "enabled", true); + case HostComponent: + // Host component type is the display name (e.g. "div", "View") + return type; - _defineProperty$1(this, "target", new Vector3()); + case HostPortal: + return 'Portal'; - _defineProperty$1(this, "minDistance", 0); + case HostRoot: + return 'Root'; - _defineProperty$1(this, "maxDistance", Infinity); + case HostText: + return 'Text'; - _defineProperty$1(this, "minZoom", 0); + case LazyComponent: + // Name comes from the type in this case; we don't have a tag. + return getComponentNameFromType(type); - _defineProperty$1(this, "maxZoom", Infinity); + case Mode: + if (type === REACT_STRICT_MODE_TYPE) { + // Don't be less specific than shared/getComponentNameFromType + return 'StrictMode'; + } - _defineProperty$1(this, "minPolarAngle", 0); + return 'Mode'; - _defineProperty$1(this, "maxPolarAngle", Math.PI); + case OffscreenComponent: + return 'Offscreen'; - _defineProperty$1(this, "minAzimuthAngle", -Infinity); + case Profiler: + return 'Profiler'; - _defineProperty$1(this, "maxAzimuthAngle", Infinity); + case ScopeComponent: + return 'Scope'; - _defineProperty$1(this, "enableDamping", false); + case SuspenseComponent: + return 'Suspense'; - _defineProperty$1(this, "dampingFactor", 0.05); + case SuspenseListComponent: + return 'SuspenseList'; - _defineProperty$1(this, "enableZoom", true); + case TracingMarkerComponent: + return 'TracingMarker'; + // The display name for this tags come from the user-provided type: - _defineProperty$1(this, "zoomSpeed", 1.0); + case ClassComponent: + case FunctionComponent: + case IncompleteClassComponent: + case IndeterminateComponent: + case MemoComponent: + case SimpleMemoComponent: + if (typeof type === 'function') { + return type.displayName || type.name || null; + } - _defineProperty$1(this, "enableRotate", true); + if (typeof type === 'string') { + return type; + } - _defineProperty$1(this, "rotateSpeed", 1.0); + break; - _defineProperty$1(this, "enablePan", true); + } - _defineProperty$1(this, "panSpeed", 1.0); + return null; + } - _defineProperty$1(this, "screenSpacePanning", true); + // Don't change these two values. They're used by React Dev Tools. + var NoFlags = + /* */ + 0; + var PerformedWork = + /* */ + 1; // You can change the rest (and add more). - _defineProperty$1(this, "keyPanSpeed", 7.0); + var Placement = + /* */ + 2; + var Update = + /* */ + 4; + var PlacementAndUpdate = + /* */ + Placement | Update; + var ChildDeletion = + /* */ + 16; + var ContentReset = + /* */ + 32; + var Callback = + /* */ + 64; + var DidCapture = + /* */ + 128; + var ForceClientRender = + /* */ + 256; + var Ref = + /* */ + 512; + var Snapshot = + /* */ + 1024; + var Passive = + /* */ + 2048; + var Hydrating = + /* */ + 4096; + var HydratingAndUpdate = + /* */ + Hydrating | Update; + var Visibility = + /* */ + 8192; + var StoreConsistency = + /* */ + 16384; + var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit) - _defineProperty$1(this, "autoRotate", false); + var HostEffectMask = + /* */ + 32767; // These are not really side effects, but we still reuse this field. - _defineProperty$1(this, "autoRotateSpeed", 2.0); + var Incomplete = + /* */ + 32768; + var ShouldCapture = + /* */ + 65536; + var ForceUpdateForLegacySuspense = + /* */ + 131072; + var Forked = + /* */ + 1048576; // Static tags describe aspects of a fiber that are not specific to a render, + // e.g. a fiber uses a passive effect (even if there are no updates on this particular render). + // This enables us to defer more work in the unmount case, + // since we can defer traversing the tree during layout to look for Passive effects, + // and instead rely on the static flag as a signal that there may be cleanup work. - _defineProperty$1(this, "reverseOrbit", false); + var RefStatic = + /* */ + 2097152; + var LayoutStatic = + /* */ + 4194304; + var PassiveStatic = + /* */ + 8388608; // These flags allow us to traverse to fibers that have effects on mount + // without traversing the entire tree after every commit for + // double invoking - _defineProperty$1(this, "keys", { - LEFT: 'ArrowLeft', - UP: 'ArrowUp', - RIGHT: 'ArrowRight', - BOTTOM: 'ArrowDown' - }); + var MountLayoutDev = + /* */ + 16777216; + var MountPassiveDev = + /* */ + 33554432; // Groups of flags that are used in the commit phase to skip over trees that + // don't contain effects, by checking subtreeFlags. - _defineProperty$1(this, "mouseButtons", { - LEFT: MOUSE.ROTATE, - MIDDLE: MOUSE.DOLLY, - RIGHT: MOUSE.PAN - }); + var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility + // flag logic (see #20043) + Update | Snapshot | ( 0); + var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; + var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask - _defineProperty$1(this, "touches", { - ONE: TOUCH.ROTATE, - TWO: TOUCH.DOLLY_PAN - }); + var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones. + // This allows certain concepts to persist without recalculating them, + // e.g. whether a subtree contains passive effects or portals. - _defineProperty$1(this, "target0", void 0); + var StaticMask = LayoutStatic | PassiveStatic | RefStatic; - _defineProperty$1(this, "position0", void 0); + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + function getNearestMountedFiber(fiber) { + var node = fiber; + var nearestMounted = fiber; - _defineProperty$1(this, "zoom0", void 0); + if (!fiber.alternate) { + // If there is no alternate, this might be a new tree that isn't inserted + // yet. If it is, then it will have a pending insertion effect on it. + var nextNode = node; - _defineProperty$1(this, "_domElementKeyEvents", null); + do { + node = nextNode; - _defineProperty$1(this, "getPolarAngle", void 0); + if ((node.flags & (Placement | Hydrating)) !== NoFlags) { + // This is an insertion or in-progress hydration. The nearest possible + // mounted fiber is the parent but we need to continue to figure out + // if that one is still mounted. + nearestMounted = node.return; + } - _defineProperty$1(this, "getAzimuthalAngle", void 0); + nextNode = node.return; + } while (nextNode); + } else { + while (node.return) { + node = node.return; + } + } - _defineProperty$1(this, "setPolarAngle", void 0); + if (node.tag === HostRoot) { + // TODO: Check if this was a nested HostRoot when used with + // renderContainerIntoSubtree. + return nearestMounted; + } // If we didn't hit the root, that means that we're in an disconnected tree + // that has been unmounted. - _defineProperty$1(this, "setAzimuthalAngle", void 0); - _defineProperty$1(this, "getDistance", void 0); + return null; + } + function isFiberMounted(fiber) { + return getNearestMountedFiber(fiber) === fiber; + } + function isMounted(component) { + { + var owner = ReactCurrentOwner.current; - _defineProperty$1(this, "listenToKeyEvents", void 0); + if (owner !== null && owner.tag === ClassComponent) { + var ownerFiber = owner; + var instance = ownerFiber.stateNode; - _defineProperty$1(this, "saveState", void 0); + if (!instance._warnedAboutRefsInRender) { + error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component'); + } - _defineProperty$1(this, "reset", void 0); + instance._warnedAboutRefsInRender = true; + } + } - _defineProperty$1(this, "update", void 0); + var fiber = get(component); - _defineProperty$1(this, "connect", void 0); + if (!fiber) { + return false; + } - _defineProperty$1(this, "dispose", void 0); + return getNearestMountedFiber(fiber) === fiber; + } - this.object = object; - this.domElement = domElement; // for reset + function assertIsMounted(fiber) { + if (getNearestMountedFiber(fiber) !== fiber) { + throw new Error('Unable to find node on an unmounted component.'); + } + } - this.target0 = this.target.clone(); - this.position0 = this.object.position.clone(); - this.zoom0 = this.object instanceof PerspectiveCamera ? this.object.zoom : 1; // - // public methods - // + function findCurrentFiberUsingSlowPath(fiber) { + var alternate = fiber.alternate; - this.getPolarAngle = () => spherical.phi; + if (!alternate) { + // If there is no alternate, then we only need to check if it is mounted. + var nearestMounted = getNearestMountedFiber(fiber); - this.getAzimuthalAngle = () => spherical.theta; + if (nearestMounted === null) { + throw new Error('Unable to find node on an unmounted component.'); + } - this.setPolarAngle = value => { - // use modulo wrapping to safeguard value - let phi = moduloWrapAround(value, 2 * Math.PI); - let currentPhi = spherical.phi; // convert to the equivalent shortest angle + if (nearestMounted !== fiber) { + return null; + } - if (currentPhi < 0) currentPhi += 2 * Math.PI; - if (phi < 0) phi += 2 * Math.PI; - let phiDist = Math.abs(phi - currentPhi); + return fiber; + } // If we have two possible branches, we'll walk backwards up to the root + // to see what path the root points to. On the way we may hit one of the + // special cases and we'll deal with them. - if (2 * Math.PI - phiDist < phiDist) { - if (phi < currentPhi) { - phi += 2 * Math.PI; - } else { - currentPhi += 2 * Math.PI; - } - } - sphericalDelta.phi = phi - currentPhi; - scope.update(); - }; + var a = fiber; + var b = alternate; - this.setAzimuthalAngle = value => { - // use modulo wrapping to safeguard value - let theta = moduloWrapAround(value, 2 * Math.PI); - let currentTheta = spherical.theta; // convert to the equivalent shortest angle + while (true) { + var parentA = a.return; - if (currentTheta < 0) currentTheta += 2 * Math.PI; - if (theta < 0) theta += 2 * Math.PI; - let thetaDist = Math.abs(theta - currentTheta); + if (parentA === null) { + // We're at the root. + break; + } - if (2 * Math.PI - thetaDist < thetaDist) { - if (theta < currentTheta) { - theta += 2 * Math.PI; - } else { - currentTheta += 2 * Math.PI; - } - } + var parentB = parentA.alternate; - sphericalDelta.theta = theta - currentTheta; - scope.update(); - }; + if (parentB === null) { + // There is no alternate. This is an unusual case. Currently, it only + // happens when a Suspense component is hidden. An extra fragment fiber + // is inserted in between the Suspense fiber and its children. Skip + // over this extra fragment fiber and proceed to the next parent. + var nextParent = parentA.return; - this.getDistance = () => scope.object.position.distanceTo(scope.target); + if (nextParent !== null) { + a = b = nextParent; + continue; + } // If there's no parent, we're at the root. - this.listenToKeyEvents = domElement => { - domElement.addEventListener('keydown', onKeyDown); - this._domElementKeyEvents = domElement; - }; - this.saveState = () => { - scope.target0.copy(scope.target); - scope.position0.copy(scope.object.position); - scope.zoom0 = scope.object instanceof PerspectiveCamera ? scope.object.zoom : 1; - }; + break; + } // If both copies of the parent fiber point to the same child, we can + // assume that the child is current. This happens when we bailout on low + // priority: the bailed out fiber's child reuses the current child. - this.reset = () => { - scope.target.copy(scope.target0); - scope.object.position.copy(scope.position0); - if (scope.object instanceof PerspectiveCamera) { - scope.object.zoom = scope.zoom0; - scope.object.updateProjectionMatrix(); - } + if (parentA.child === parentB.child) { + var child = parentA.child; - scope.dispatchEvent(changeEvent); - scope.update(); - state = STATE.NONE; - }; // this method is exposed, but perhaps it would be better if we can make it private... + while (child) { + if (child === a) { + // We've determined that A is the current branch. + assertIsMounted(parentA); + return fiber; + } + if (child === b) { + // We've determined that B is the current branch. + assertIsMounted(parentA); + return alternate; + } - this.update = (() => { - const offset = new Vector3(); // so camera.up is the orbit axis + child = child.sibling; + } // We should never have an alternate for any mounting node. So the only + // way this could possibly happen is if this was unmounted, if at all. - const quat = new Quaternion().setFromUnitVectors(object.up, new Vector3(0, 1, 0)); - const quatInverse = quat.clone().invert(); - const lastPosition = new Vector3(); - const lastQuaternion = new Quaternion(); - const twoPI = 2 * Math.PI; - return function update() { - const position = scope.object.position; - offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space - offset.applyQuaternion(quat); // angle from z-axis around y-axis + throw new Error('Unable to find node on an unmounted component.'); + } - spherical.setFromVector3(offset); + if (a.return !== b.return) { + // The return pointer of A and the return pointer of B point to different + // fibers. We assume that return pointers never criss-cross, so A must + // belong to the child set of A.return, and B must belong to the child + // set of B.return. + a = parentA; + b = parentB; + } else { + // The return pointers point to the same fiber. We'll have to use the + // default, slow path: scan the child sets of each parent alternate to see + // which child belongs to which set. + // + // Search parent A's child set + var didFindChild = false; + var _child = parentA.child; - if (scope.autoRotate && state === STATE.NONE) { - rotateLeft(getAutoRotationAngle()); - } + while (_child) { + if (_child === a) { + didFindChild = true; + a = parentA; + b = parentB; + break; + } - if (scope.enableDamping) { - spherical.theta += sphericalDelta.theta * scope.dampingFactor; - spherical.phi += sphericalDelta.phi * scope.dampingFactor; - } else { - spherical.theta += sphericalDelta.theta; - spherical.phi += sphericalDelta.phi; - } // restrict theta to be between desired limits + if (_child === b) { + didFindChild = true; + b = parentA; + a = parentB; + break; + } + _child = _child.sibling; + } - let min = scope.minAzimuthAngle; - let max = scope.maxAzimuthAngle; + if (!didFindChild) { + // Search parent B's child set + _child = parentB.child; - if (isFinite(min) && isFinite(max)) { - if (min < -Math.PI) min += twoPI;else if (min > Math.PI) min -= twoPI; - if (max < -Math.PI) max += twoPI;else if (max > Math.PI) max -= twoPI; + while (_child) { + if (_child === a) { + didFindChild = true; + a = parentB; + b = parentA; + break; + } - if (min <= max) { - spherical.theta = Math.max(min, Math.min(max, spherical.theta)); - } else { - spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta); - } - } // restrict phi to be between desired limits + if (_child === b) { + didFindChild = true; + b = parentB; + a = parentA; + break; + } + _child = _child.sibling; + } - spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi)); - spherical.makeSafe(); - spherical.radius *= scale; // restrict radius to be between desired limits + if (!didFindChild) { + throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.'); + } + } + } - spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location + if (a.alternate !== b) { + throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.'); + } + } // If the root is not a host container, we're in a disconnected tree. I.e. + // unmounted. - if (scope.enableDamping === true) { - scope.target.addScaledVector(panOffset, scope.dampingFactor); - } else { - scope.target.add(panOffset); - } - offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space + if (a.tag !== HostRoot) { + throw new Error('Unable to find node on an unmounted component.'); + } - offset.applyQuaternion(quatInverse); - position.copy(scope.target).add(offset); - scope.object.lookAt(scope.target); + if (a.stateNode.current === a) { + // We've determined that A is the current branch. + return fiber; + } // Otherwise B has to be current branch. - if (scope.enableDamping === true) { - sphericalDelta.theta *= 1 - scope.dampingFactor; - sphericalDelta.phi *= 1 - scope.dampingFactor; - panOffset.multiplyScalar(1 - scope.dampingFactor); - } else { - sphericalDelta.set(0, 0, 0); - panOffset.set(0, 0, 0); - } - scale = 1; // update condition is: - // min(camera displacement, camera rotation in radians)^2 > EPS - // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + return alternate; + } + function findCurrentHostFiber(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null; + } - if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) { - scope.dispatchEvent(changeEvent); - lastPosition.copy(scope.object.position); - lastQuaternion.copy(scope.object.quaternion); - zoomChanged = false; - return true; - } + function findCurrentHostFiberImpl(node) { + // Next we'll drill down this component to find the first HostComponent/Text. + if (node.tag === HostComponent || node.tag === HostText) { + return node; + } - return false; - }; - })(); // https://github.com/mrdoob/three.js/issues/20575 + var child = node.child; + while (child !== null) { + var match = findCurrentHostFiberImpl(child); - this.connect = domElement => { - if (domElement === document) { - console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'); - } + if (match !== null) { + return match; + } - scope.domElement = domElement; // disables touch scroll - // touch-action needs to be defined for pointer events to work on mobile - // https://stackoverflow.com/a/48254578 + child = child.sibling; + } - scope.domElement.style.touchAction = 'none'; - scope.domElement.addEventListener('contextmenu', onContextMenu); - scope.domElement.addEventListener('pointerdown', onPointerDown); - scope.domElement.addEventListener('pointercancel', onPointerCancel); - scope.domElement.addEventListener('wheel', onMouseWheel); - }; + return null; + } - this.dispose = () => { - var _scope$domElement, _scope$domElement2, _scope$domElement3, _scope$domElement4, _scope$domElement5, _scope$domElement6; + function findCurrentHostFiberWithNoPortals(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null; + } - (_scope$domElement = scope.domElement) === null || _scope$domElement === void 0 ? void 0 : _scope$domElement.removeEventListener('contextmenu', onContextMenu); - (_scope$domElement2 = scope.domElement) === null || _scope$domElement2 === void 0 ? void 0 : _scope$domElement2.removeEventListener('pointerdown', onPointerDown); - (_scope$domElement3 = scope.domElement) === null || _scope$domElement3 === void 0 ? void 0 : _scope$domElement3.removeEventListener('pointercancel', onPointerCancel); - (_scope$domElement4 = scope.domElement) === null || _scope$domElement4 === void 0 ? void 0 : _scope$domElement4.removeEventListener('wheel', onMouseWheel); - (_scope$domElement5 = scope.domElement) === null || _scope$domElement5 === void 0 ? void 0 : _scope$domElement5.ownerDocument.removeEventListener('pointermove', onPointerMove); - (_scope$domElement6 = scope.domElement) === null || _scope$domElement6 === void 0 ? void 0 : _scope$domElement6.ownerDocument.removeEventListener('pointerup', onPointerUp); + function findCurrentHostFiberWithNoPortalsImpl(node) { + // Next we'll drill down this component to find the first HostComponent/Text. + if (node.tag === HostComponent || node.tag === HostText) { + return node; + } - if (scope._domElementKeyEvents !== null) { - scope._domElementKeyEvents.removeEventListener('keydown', onKeyDown); - } //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? + var child = node.child; - }; // - // internals - // + while (child !== null) { + if (child.tag !== HostPortal) { + var match = findCurrentHostFiberWithNoPortalsImpl(child); + if (match !== null) { + return match; + } + } - const scope = this; - const changeEvent = { - type: 'change' - }; - const startEvent = { - type: 'start' - }; - const endEvent = { - type: 'end' - }; - const STATE = { - NONE: -1, - ROTATE: 0, - DOLLY: 1, - PAN: 2, - TOUCH_ROTATE: 3, - TOUCH_PAN: 4, - TOUCH_DOLLY_PAN: 5, - TOUCH_DOLLY_ROTATE: 6 - }; - let state = STATE.NONE; - const EPS = 0.000001; // current position in spherical coordinates - - const spherical = new Spherical(); - const sphericalDelta = new Spherical(); - let scale = 1; - const panOffset = new Vector3(); - let zoomChanged = false; - const rotateStart = new Vector2(); - const rotateEnd = new Vector2(); - const rotateDelta = new Vector2(); - const panStart = new Vector2(); - const panEnd = new Vector2(); - const panDelta = new Vector2(); - const dollyStart = new Vector2(); - const dollyEnd = new Vector2(); - const dollyDelta = new Vector2(); - const pointers = []; - const pointerPositions = {}; - - function getAutoRotationAngle() { - return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - } + child = child.sibling; + } - function getZoomScale() { - return Math.pow(0.95, scope.zoomSpeed); - } + return null; + } - function rotateLeft(angle) { - if (scope.reverseOrbit) { - sphericalDelta.theta += angle; - } else { - sphericalDelta.theta -= angle; - } - } + var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare - function rotateUp(angle) { - if (scope.reverseOrbit) { - sphericalDelta.phi += angle; - } else { - sphericalDelta.phi -= angle; - } - } + function isArray(a) { + return isArrayImpl(a); + } - const panLeft = (() => { - const v = new Vector3(); - return function panLeft(distance, objectMatrix) { - v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix + // This is a host config that's used for the `react-reconciler` package on npm. + // It is only used by third-party renderers. + // + // Its API lets you pass the host config as an argument. + // However, inside the `react-reconciler` we treat host config as a module. + // This file is a shim between two worlds. + // + // It works because the `react-reconciler` bundle is wrapped in something like: + // + // module.exports = function ($$$config) { + // /* reconciler code */ + // } + // + // So `$$$config` looks like a global variable, but it's + // really an argument to a top-level wrapping function. + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + // eslint-disable-line no-undef + var getPublicInstance = $$$hostConfig.getPublicInstance; + var getRootHostContext = $$$hostConfig.getRootHostContext; + var getChildHostContext = $$$hostConfig.getChildHostContext; + var prepareForCommit = $$$hostConfig.prepareForCommit; + var resetAfterCommit = $$$hostConfig.resetAfterCommit; + var createInstance = $$$hostConfig.createInstance; + var appendInitialChild = $$$hostConfig.appendInitialChild; + var finalizeInitialChildren = $$$hostConfig.finalizeInitialChildren; + var prepareUpdate = $$$hostConfig.prepareUpdate; + var shouldSetTextContent = $$$hostConfig.shouldSetTextContent; + var createTextInstance = $$$hostConfig.createTextInstance; + var scheduleTimeout = $$$hostConfig.scheduleTimeout; + var cancelTimeout = $$$hostConfig.cancelTimeout; + var noTimeout = $$$hostConfig.noTimeout; + $$$hostConfig.now; + var isPrimaryRenderer = $$$hostConfig.isPrimaryRenderer; + var warnsIfNotActing = $$$hostConfig.warnsIfNotActing; + var supportsMutation = $$$hostConfig.supportsMutation; + var supportsPersistence = $$$hostConfig.supportsPersistence; + var supportsHydration = $$$hostConfig.supportsHydration; + var getInstanceFromNode = $$$hostConfig.getInstanceFromNode; + $$$hostConfig.beforeActiveInstanceBlur; + $$$hostConfig.afterActiveInstanceBlur; + var preparePortalMount = $$$hostConfig.preparePortalMount; + $$$hostConfig.preparePortalMount; + $$$hostConfig.getInstanceFromScope; + var getCurrentEventPriority = $$$hostConfig.getCurrentEventPriority; + var detachDeletedInstance = $$$hostConfig.detachDeletedInstance; // ------------------- + // Microtasks + // (optional) + // ------------------- - v.multiplyScalar(-distance); - panOffset.add(v); - }; - })(); + var supportsMicrotasks = $$$hostConfig.supportsMicrotasks; + var scheduleMicrotask = $$$hostConfig.scheduleMicrotask; // ------------------- + // Test selectors + // (optional) + // ------------------- - const panUp = (() => { - const v = new Vector3(); - return function panUp(distance, objectMatrix) { - if (scope.screenSpacePanning === true) { - v.setFromMatrixColumn(objectMatrix, 1); - } else { - v.setFromMatrixColumn(objectMatrix, 0); - v.crossVectors(scope.object.up, v); - } + var supportsTestSelectors = $$$hostConfig.supportsTestSelectors; + var findFiberRoot = $$$hostConfig.findFiberRoot; + var getBoundingRect = $$$hostConfig.getBoundingRect; + var getTextContent = $$$hostConfig.getTextContent; + var isHiddenSubtree = $$$hostConfig.isHiddenSubtree; + var matchAccessibilityRole = $$$hostConfig.matchAccessibilityRole; + var setFocusIfFocusable = $$$hostConfig.setFocusIfFocusable; + var setupIntersectionObserver = $$$hostConfig.setupIntersectionObserver; // ------------------- + // Mutation + // (optional) + // ------------------- - v.multiplyScalar(distance); - panOffset.add(v); - }; - })(); // deltaX and deltaY are in pixels; right and down are positive + var appendChild = $$$hostConfig.appendChild; + var appendChildToContainer = $$$hostConfig.appendChildToContainer; + var commitTextUpdate = $$$hostConfig.commitTextUpdate; + var commitMount = $$$hostConfig.commitMount; + var commitUpdate = $$$hostConfig.commitUpdate; + var insertBefore = $$$hostConfig.insertBefore; + var insertInContainerBefore = $$$hostConfig.insertInContainerBefore; + var removeChild = $$$hostConfig.removeChild; + var removeChildFromContainer = $$$hostConfig.removeChildFromContainer; + var resetTextContent = $$$hostConfig.resetTextContent; + var hideInstance = $$$hostConfig.hideInstance; + var hideTextInstance = $$$hostConfig.hideTextInstance; + var unhideInstance = $$$hostConfig.unhideInstance; + var unhideTextInstance = $$$hostConfig.unhideTextInstance; + var clearContainer = $$$hostConfig.clearContainer; // ------------------- + // Persistence + // (optional) + // ------------------- + var cloneInstance = $$$hostConfig.cloneInstance; + var createContainerChildSet = $$$hostConfig.createContainerChildSet; + var appendChildToContainerChildSet = $$$hostConfig.appendChildToContainerChildSet; + var finalizeContainerChildren = $$$hostConfig.finalizeContainerChildren; + var replaceContainerChildren = $$$hostConfig.replaceContainerChildren; + $$$hostConfig.getOffscreenContainerType; + var getOffscreenContainerProps = $$$hostConfig.getOffscreenContainerProps; + var cloneHiddenInstance = $$$hostConfig.cloneHiddenInstance; + var cloneHiddenTextInstance = $$$hostConfig.cloneHiddenTextInstance; // ------------------- + // Hydration + // (optional) + // ------------------- - const pan = (() => { - const offset = new Vector3(); - return function pan(deltaX, deltaY) { - const element = scope.domElement; + var canHydrateInstance = $$$hostConfig.canHydrateInstance; + var canHydrateTextInstance = $$$hostConfig.canHydrateTextInstance; + var canHydrateSuspenseInstance = $$$hostConfig.canHydrateSuspenseInstance; + var isSuspenseInstancePending = $$$hostConfig.isSuspenseInstancePending; + var isSuspenseInstanceFallback = $$$hostConfig.isSuspenseInstanceFallback; + var registerSuspenseInstanceRetry = $$$hostConfig.registerSuspenseInstanceRetry; + var getNextHydratableSibling = $$$hostConfig.getNextHydratableSibling; + var getFirstHydratableChild = $$$hostConfig.getFirstHydratableChild; + var getFirstHydratableChildWithinContainer = $$$hostConfig.getFirstHydratableChildWithinContainer; + var getFirstHydratableChildWithinSuspenseInstance = $$$hostConfig.getFirstHydratableChildWithinSuspenseInstance; + var hydrateInstance = $$$hostConfig.hydrateInstance; + var hydrateTextInstance = $$$hostConfig.hydrateTextInstance; + var hydrateSuspenseInstance = $$$hostConfig.hydrateSuspenseInstance; + var getNextHydratableInstanceAfterSuspenseInstance = $$$hostConfig.getNextHydratableInstanceAfterSuspenseInstance; + var commitHydratedContainer = $$$hostConfig.commitHydratedContainer; + var commitHydratedSuspenseInstance = $$$hostConfig.commitHydratedSuspenseInstance; + var clearSuspenseBoundary = $$$hostConfig.clearSuspenseBoundary; + var clearSuspenseBoundaryFromContainer = $$$hostConfig.clearSuspenseBoundaryFromContainer; + var shouldDeleteUnhydratedTailInstances = $$$hostConfig.shouldDeleteUnhydratedTailInstances; + var didNotMatchHydratedContainerTextInstance = $$$hostConfig.didNotMatchHydratedContainerTextInstance; + var didNotMatchHydratedTextInstance = $$$hostConfig.didNotMatchHydratedTextInstance; + var didNotHydrateInstanceWithinContainer = $$$hostConfig.didNotHydrateInstanceWithinContainer; + var didNotHydrateInstanceWithinSuspenseInstance = $$$hostConfig.didNotHydrateInstanceWithinSuspenseInstance; + var didNotHydrateInstance = $$$hostConfig.didNotHydrateInstance; + var didNotFindHydratableInstanceWithinContainer = $$$hostConfig.didNotFindHydratableInstanceWithinContainer; + var didNotFindHydratableTextInstanceWithinContainer = $$$hostConfig.didNotFindHydratableTextInstanceWithinContainer; + var didNotFindHydratableSuspenseInstanceWithinContainer = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinContainer; + var didNotFindHydratableInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableInstanceWithinSuspenseInstance; + var didNotFindHydratableTextInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableTextInstanceWithinSuspenseInstance; + var didNotFindHydratableSuspenseInstanceWithinSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstanceWithinSuspenseInstance; + var didNotFindHydratableInstance = $$$hostConfig.didNotFindHydratableInstance; + var didNotFindHydratableTextInstance = $$$hostConfig.didNotFindHydratableTextInstance; + var didNotFindHydratableSuspenseInstance = $$$hostConfig.didNotFindHydratableSuspenseInstance; + var errorHydratingContainer = $$$hostConfig.errorHydratingContainer; - if (element && scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) { - // perspective - const position = scope.object.position; - offset.copy(position).sub(scope.target); - let targetDistance = offset.length(); // half of the fov is center to top of screen + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; - targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed + function disabledLog() {} - panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix); - panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix); - } else if (element && scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { - // orthographic - panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix); - panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix); - } else { - // camera neither orthographic nor perspective - console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.'); - scope.enablePan = false; - } - }; - })(); - - function dollyOut(dollyScale) { - if (scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) { - scale /= dollyScale; - } else if (scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { - scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale)); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - } else { - console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.'); - scope.enableZoom = false; - } - } + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 - function dollyIn(dollyScale) { - if (scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) { - scale *= dollyScale; - } else if (scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { - scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale)); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - } else { - console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.'); - scope.enableZoom = false; - } - } // - // event callbacks - update the object state - // + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } - function handleMouseDownRotate(event) { - rotateStart.set(event.clientX, event.clientY); - } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; - function handleMouseDownDolly(event) { - dollyStart.set(event.clientX, event.clientY); - } + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. - function handleMouseDownPan(event) { - panStart.set(event.clientX, event.clientY); - } + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } - function handleMouseMoveRotate(event) { - rotateEnd.set(event.clientX, event.clientY); - rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); - const element = scope.domElement; + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } + } - if (element) { - rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. - rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); - } - rotateStart.copy(rotateEnd); - scope.update(); - } + return '\n' + prefix + name; + } + } + var reentry = false; + var componentFrameCache; - function handleMouseMoveDolly(event) { - dollyEnd.set(event.clientX, event.clientY); - dollyDelta.subVectors(dollyEnd, dollyStart); + { + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } - if (dollyDelta.y > 0) { - dollyOut(getZoomScale()); - } else if (dollyDelta.y < 0) { - dollyIn(getZoomScale()); - } + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } - dollyStart.copy(dollyEnd); - scope.update(); - } + { + var frame = componentFrameCache.get(fn); - function handleMouseMovePan(event) { - panEnd.set(event.clientX, event.clientY); - panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); - pan(panDelta.x, panDelta.y); - panStart.copy(panEnd); - scope.update(); - } + if (frame !== undefined) { + return frame; + } + } - function handleMouseWheel(event) { - if (event.deltaY < 0) { - dollyIn(getZoomScale()); - } else if (event.deltaY > 0) { - dollyOut(getZoomScale()); - } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. - scope.update(); - } + Error.prepareStackTrace = undefined; + var previousDispatcher; - function handleKeyDown(event) { - let needsUpdate = false; + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. - switch (event.code) { - case scope.keys.UP: - pan(0, scope.keyPanSpeed); - needsUpdate = true; - break; + ReactCurrentDispatcher.current = null; + disableLogs(); + } - case scope.keys.BOTTOM: - pan(0, -scope.keyPanSpeed); - needsUpdate = true; - break; + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe - case scope.keys.LEFT: - pan(scope.keyPanSpeed, 0); - needsUpdate = true; - break; - case scope.keys.RIGHT: - pan(-scope.keyPanSpeed, 0); - needsUpdate = true; - break; - } + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); - if (needsUpdate) { - // prevent the browser from scrolling on cursor keys - event.preventDefault(); - scope.update(); - } - } + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } - function handleTouchStartRotate() { - if (pointers.length == 1) { - rotateStart.set(pointers[0].pageX, pointers[0].pageY); - } else { - const x = 0.5 * (pointers[0].pageX + pointers[1].pageX); - const y = 0.5 * (pointers[0].pageY + pointers[1].pageY); - rotateStart.set(x, y); - } - } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } - function handleTouchStartPan() { - if (pointers.length == 1) { - panStart.set(pointers[0].pageX, pointers[0].pageY); - } else { - const x = 0.5 * (pointers[0].pageX + pointers[1].pageX); - const y = 0.5 * (pointers[0].pageY + pointers[1].pageY); - panStart.set(x, y); - } - } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } - function handleTouchStartDolly() { - const dx = pointers[0].pageX - pointers[1].pageX; - const dy = pointers[0].pageY - pointers[1].pageY; - const distance = Math.sqrt(dx * dx + dy * dy); - dollyStart.set(0, distance); - } + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; - function handleTouchStartDollyPan() { - if (scope.enableZoom) handleTouchStartDolly(); - if (scope.enablePan) handleTouchStartPan(); - } + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } - function handleTouchStartDollyRotate() { - if (scope.enableZoom) handleTouchStartDolly(); - if (scope.enableRotate) handleTouchStartRotate(); - } + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. - function handleTouchMoveRotate(event) { - if (pointers.length == 1) { - rotateEnd.set(event.pageX, event.pageY); - } else { - const position = getSecondPointerPosition(event); - const x = 0.5 * (event.pageX + position.x); - const y = 0.5 * (event.pageY + position.y); - rotateEnd.set(x, y); - } + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. - rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); - const element = scope.domElement; - if (element) { - rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } - rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); - } + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. - rotateStart.copy(rotateEnd); - } - function handleTouchMovePan(event) { - if (pointers.length == 1) { - panEnd.set(event.pageX, event.pageY); - } else { - const position = getSecondPointerPosition(event); - const x = 0.5 * (event.pageX + position.x); - const y = 0.5 * (event.pageY + position.y); - panEnd.set(x, y); - } + return _frame; + } + } while (s >= 1 && c >= 0); + } - panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); - pan(panDelta.x, panDelta.y); - panStart.copy(panEnd); - } + break; + } + } + } + } finally { + reentry = false; - function handleTouchMoveDolly(event) { - const position = getSecondPointerPosition(event); - const dx = event.pageX - position.x; - const dy = event.pageY - position.y; - const distance = Math.sqrt(dx * dx + dy * dy); - dollyEnd.set(0, distance); - dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed)); - dollyOut(dollyDelta.y); - dollyStart.copy(dollyEnd); - } + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } - function handleTouchMoveDollyPan(event) { - if (scope.enableZoom) handleTouchMoveDolly(event); - if (scope.enablePan) handleTouchMovePan(event); - } + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. - function handleTouchMoveDollyRotate(event) { - if (scope.enableZoom) handleTouchMoveDolly(event); - if (scope.enableRotate) handleTouchMoveRotate(event); - } // - // event handlers - FSM: listen for events and reset state - // + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; - function onPointerDown(event) { - if (scope.enabled === false) return; + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } - if (pointers.length === 0) { - var _scope$domElement7, _scope$domElement8; + return syntheticFrame; + } - (_scope$domElement7 = scope.domElement) === null || _scope$domElement7 === void 0 ? void 0 : _scope$domElement7.ownerDocument.addEventListener('pointermove', onPointerMove); - (_scope$domElement8 = scope.domElement) === null || _scope$domElement8 === void 0 ? void 0 : _scope$domElement8.ownerDocument.addEventListener('pointerup', onPointerUp); - } + function describeClassComponentFrame(ctor, source, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } - addPointer(event); + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } - if (event.pointerType === 'touch') { - onTouchStart(event); - } else { - onMouseDown(event); - } - } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - function onPointerMove(event) { - if (scope.enabled === false) return; + if (type == null) { + return ''; + } - if (event.pointerType === 'touch') { - onTouchMove(event); - } else { - onMouseMove(event); - } - } + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } - function onPointerUp(event) { - removePointer(event); + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } - if (pointers.length === 0) { - var _scope$domElement9, _scope$domElement10, _scope$domElement11; + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); - (_scope$domElement9 = scope.domElement) === null || _scope$domElement9 === void 0 ? void 0 : _scope$domElement9.releasePointerCapture(event.pointerId); - (_scope$domElement10 = scope.domElement) === null || _scope$domElement10 === void 0 ? void 0 : _scope$domElement10.ownerDocument.removeEventListener('pointermove', onPointerMove); - (_scope$domElement11 = scope.domElement) === null || _scope$domElement11 === void 0 ? void 0 : _scope$domElement11.ownerDocument.removeEventListener('pointerup', onPointerUp); - } + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } - scope.dispatchEvent(endEvent); - state = STATE.NONE; - } + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); - function onPointerCancel(event) { - removePointer(event); - } + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - function onMouseDown(event) { - let mouseAction; + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; - switch (event.button) { - case 0: - mouseAction = scope.mouseButtons.LEFT; - break; + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } - case 1: - mouseAction = scope.mouseButtons.MIDDLE; - break; + return ''; + } - case 2: - mouseAction = scope.mouseButtons.RIGHT; - break; + var hasOwnProperty = Object.prototype.hasOwnProperty; - default: - mouseAction = -1; - } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - switch (mouseAction) { - case MOUSE.DOLLY: - if (scope.enableZoom === false) return; - handleMouseDownDolly(event); - state = STATE.DOLLY; - break; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } + } - case MOUSE.ROTATE: - if (event.ctrlKey || event.metaKey || event.shiftKey) { - if (scope.enablePan === false) return; - handleMouseDownPan(event); - state = STATE.PAN; - } else { - if (scope.enableRotate === false) return; - handleMouseDownRotate(event); - state = STATE.ROTATE; - } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); - break; + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. - case MOUSE.PAN: - if (event.ctrlKey || event.metaKey || event.shiftKey) { - if (scope.enableRotate === false) return; - handleMouseDownRotate(event); - state = STATE.ROTATE; - } else { - if (scope.enablePan === false) return; - handleMouseDownPan(event); - state = STATE.PAN; - } + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } - break; + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } - default: - state = STATE.NONE; - } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); - if (state !== STATE.NONE) { - scope.dispatchEvent(startEvent); - } - } + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); - function onMouseMove(event) { - if (scope.enabled === false) return; + setCurrentlyValidatingElement(null); + } - switch (state) { - case STATE.ROTATE: - if (scope.enableRotate === false) return; - handleMouseMoveRotate(event); - break; + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); - case STATE.DOLLY: - if (scope.enableZoom === false) return; - handleMouseMoveDolly(event); - break; + error('Failed %s type: %s', location, error$1.message); - case STATE.PAN: - if (scope.enablePan === false) return; - handleMouseMovePan(event); - break; - } - } + setCurrentlyValidatingElement(null); + } + } + } + } + } - function onMouseWheel(event) { - if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) { - return; - } + var valueStack = []; + var fiberStack; - event.preventDefault(); - scope.dispatchEvent(startEvent); - handleMouseWheel(event); - scope.dispatchEvent(endEvent); - } + { + fiberStack = []; + } - function onKeyDown(event) { - if (scope.enabled === false || scope.enablePan === false) return; - handleKeyDown(event); - } + var index = -1; - function onTouchStart(event) { - trackPointer(event); + function createCursor(defaultValue) { + return { + current: defaultValue + }; + } - switch (pointers.length) { - case 1: - switch (scope.touches.ONE) { - case TOUCH.ROTATE: - if (scope.enableRotate === false) return; - handleTouchStartRotate(); - state = STATE.TOUCH_ROTATE; - break; + function pop(cursor, fiber) { + if (index < 0) { + { + error('Unexpected pop.'); + } - case TOUCH.PAN: - if (scope.enablePan === false) return; - handleTouchStartPan(); - state = STATE.TOUCH_PAN; - break; + return; + } - default: - state = STATE.NONE; - } + { + if (fiber !== fiberStack[index]) { + error('Unexpected Fiber popped.'); + } + } - break; + cursor.current = valueStack[index]; + valueStack[index] = null; - case 2: - switch (scope.touches.TWO) { - case TOUCH.DOLLY_PAN: - if (scope.enableZoom === false && scope.enablePan === false) return; - handleTouchStartDollyPan(); - state = STATE.TOUCH_DOLLY_PAN; - break; + { + fiberStack[index] = null; + } - case TOUCH.DOLLY_ROTATE: - if (scope.enableZoom === false && scope.enableRotate === false) return; - handleTouchStartDollyRotate(); - state = STATE.TOUCH_DOLLY_ROTATE; - break; + index--; + } - default: - state = STATE.NONE; - } + function push(cursor, value, fiber) { + index++; + valueStack[index] = cursor.current; - break; + { + fiberStack[index] = fiber; + } - default: - state = STATE.NONE; - } + cursor.current = value; + } - if (state !== STATE.NONE) { - scope.dispatchEvent(startEvent); - } - } + var warnedAboutMissingGetChildContext; - function onTouchMove(event) { - trackPointer(event); + { + warnedAboutMissingGetChildContext = {}; + } - switch (state) { - case STATE.TOUCH_ROTATE: - if (scope.enableRotate === false) return; - handleTouchMoveRotate(event); - scope.update(); - break; + var emptyContextObject = {}; - case STATE.TOUCH_PAN: - if (scope.enablePan === false) return; - handleTouchMovePan(event); - scope.update(); - break; + { + Object.freeze(emptyContextObject); + } // A cursor to the current merged context object on the stack. - case STATE.TOUCH_DOLLY_PAN: - if (scope.enableZoom === false && scope.enablePan === false) return; - handleTouchMoveDollyPan(event); - scope.update(); - break; - case STATE.TOUCH_DOLLY_ROTATE: - if (scope.enableZoom === false && scope.enableRotate === false) return; - handleTouchMoveDollyRotate(event); - scope.update(); - break; + var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. - default: - state = STATE.NONE; - } - } + var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. + // We use this to get access to the parent context after we have already + // pushed the next context provider, and now need to merge their contexts. - function onContextMenu(event) { - if (scope.enabled === false) return; - event.preventDefault(); - } + var previousContext = emptyContextObject; - function addPointer(event) { - pointers.push(event); - } + function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) { + { + if (didPushOwnContextIfProvider && isContextProvider(Component)) { + // If the fiber is a context provider itself, when we read its context + // we may have already pushed its own child context on the stack. A context + // provider should not "see" its own child context. Therefore we read the + // previous (parent) context instead for a context provider. + return previousContext; + } - function removePointer(event) { - delete pointerPositions[event.pointerId]; + return contextStackCursor.current; + } + } - for (let i = 0; i < pointers.length; i++) { - if (pointers[i].pointerId == event.pointerId) { - pointers.splice(i, 1); - return; - } - } - } + function cacheContext(workInProgress, unmaskedContext, maskedContext) { + { + var instance = workInProgress.stateNode; + instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; + instance.__reactInternalMemoizedMaskedChildContext = maskedContext; + } + } - function trackPointer(event) { - let position = pointerPositions[event.pointerId]; + function getMaskedContext(workInProgress, unmaskedContext) { + { + var type = workInProgress.type; + var contextTypes = type.contextTypes; - if (position === undefined) { - position = new Vector2(); - pointerPositions[event.pointerId] = position; - } + if (!contextTypes) { + return emptyContextObject; + } // Avoid recreating masked context unless unmasked context has changed. + // Failing to do this will result in unnecessary calls to componentWillReceiveProps. + // This may trigger infinite loops if componentWillReceiveProps calls setState. - position.set(event.pageX, event.pageY); - } - function getSecondPointerPosition(event) { - const pointer = event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0]; - return pointerPositions[pointer.pointerId]; - } // connect events + var instance = workInProgress.stateNode; + if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { + return instance.__reactInternalMemoizedMaskedChildContext; + } - if (domElement !== undefined) this.connect(domElement); // force an update at start + var context = {}; - this.update(); - } + for (var key in contextTypes) { + context[key] = unmaskedContext[key]; + } -} // This set of controls performs orbiting, dollying (zooming), and panning. + { + var name = getComponentNameFromFiber(workInProgress) || 'Unknown'; + checkPropTypes(contextTypes, context, 'context', name); + } // Cache unmasked context so we can avoid recreating masked context unless necessary. + // Context is created before the class component is instantiated so check for instance. -({ - camera: new Matrix4(), - gizmos: new Matrix4() -}); //events -class Pass$1 { - constructor() { - _defineProperty$1(this, "enabled", true); + if (instance) { + cacheContext(workInProgress, unmaskedContext, context); + } - _defineProperty$1(this, "needsSwap", true); + return context; + } + } - _defineProperty$1(this, "clear", false); + function hasContextChanged() { + { + return didPerformWorkStackCursor.current; + } + } - _defineProperty$1(this, "renderToScreen", false); - } + function isContextProvider(type) { + { + var childContextTypes = type.childContextTypes; + return childContextTypes !== null && childContextTypes !== undefined; + } + } - setSize( - /* eslint-disable @typescript-eslint/no-unused-vars */ + function popContext(fiber) { + { + pop(didPerformWorkStackCursor, fiber); + pop(contextStackCursor, fiber); + } + } - /* eslint-disable no-unused-vars */ - width, height) {} + function popTopLevelContextObject(fiber) { + { + pop(didPerformWorkStackCursor, fiber); + pop(contextStackCursor, fiber); + } + } - render( - /* eslint-disable @typescript-eslint/no-unused-vars */ + function pushTopLevelContextObject(fiber, context, didChange) { + { + if (contextStackCursor.current !== emptyContextObject) { + throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } - /* eslint-disable no-unused-vars */ - renderer, writeBuffer, readBuffer, deltaTime, maskActive) { - console.error('THREE.Pass: .render() must be implemented in derived pass.'); - } + push(contextStackCursor, context, fiber); + push(didPerformWorkStackCursor, didChange, fiber); + } + } -} // Helper for passes that need to fill the viewport with a single quad. + function processChildContext(fiber, type, parentContext) { + { + var instance = fiber.stateNode; + var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. + // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== 'function') { + { + var componentName = getComponentNameFromFiber(fiber) || 'Unknown'; -class FullScreenQuad { - constructor(material) { - _defineProperty$1(this, "camera", new OrthographicCamera(-1, 1, 1, -1, 0, 1)); + if (!warnedAboutMissingGetChildContext[componentName]) { + warnedAboutMissingGetChildContext[componentName] = true; - _defineProperty$1(this, "geometry", new PlaneGeometry(2, 2)); + error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); + } + } - _defineProperty$1(this, "mesh", void 0); + return parentContext; + } - this.mesh = new Mesh(this.geometry, material); - } + var childContext = instance.getChildContext(); - get material() { - return this.mesh.material; - } + for (var contextKey in childContext) { + if (!(contextKey in childContextTypes)) { + throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); + } + } - set material(value) { - this.mesh.material = value; - } + { + var name = getComponentNameFromFiber(fiber) || 'Unknown'; + checkPropTypes(childContextTypes, childContext, 'child context', name); + } - dispose() { - this.mesh.geometry.dispose(); - } + return assign({}, parentContext, childContext); + } + } - render(renderer) { - renderer.render(this.mesh, this.camera); - } + function pushContextProvider(workInProgress) { + { + var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. + // If the instance does not exist yet, we will push null at first, + // and replace it on the stack later when invalidating the context. -} + var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later. + // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. -/** - * WebGL port of Subpixel Morphological Antialiasing (SMAA) v2.8 - * Preset: SMAA 1x Medium (with color edge detection) - * https://github.com/iryoku/smaa/releases/tag/v2.8 - */ + previousContext = contextStackCursor.current; + push(contextStackCursor, memoizedMergedChildContext, workInProgress); + push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress); + return true; + } + } -({ - defines: { - SMAA_THRESHOLD: '0.1' - }, - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2(1 / 1024, 1 / 512) - } - }, - vertexShader: ['uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 3 ];', 'void SMAAEdgeDetectionVS( vec2 texcoord ) {', ' vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 );', // WebGL port note: Changed sign in W component - ' vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 );', // WebGL port note: Changed sign in W component - ' vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 );', // WebGL port note: Changed sign in W component - '}', 'void main() {', ' vUv = uv;', ' SMAAEdgeDetectionVS( vUv );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 3 ];', 'vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) {', ' vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD );', // Calculate color deltas: - ' vec4 delta;', ' vec3 C = texture2D( colorTex, texcoord ).rgb;', ' vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb;', ' vec3 t = abs( C - Cleft );', ' delta.x = max( max( t.r, t.g ), t.b );', ' vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb;', ' t = abs( C - Ctop );', ' delta.y = max( max( t.r, t.g ), t.b );', // We do the usual threshold: - ' vec2 edges = step( threshold, delta.xy );', // Then discard if there is no edge: - ' if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 )', ' discard;', // Calculate right and bottom deltas: - ' vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb;', ' t = abs( C - Cright );', ' delta.z = max( max( t.r, t.g ), t.b );', ' vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb;', ' t = abs( C - Cbottom );', ' delta.w = max( max( t.r, t.g ), t.b );', // Calculate the maximum delta in the direct neighborhood: - ' float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w );', // Calculate left-left and top-top deltas: - ' vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb;', ' t = abs( C - Cleftleft );', ' delta.z = max( max( t.r, t.g ), t.b );', ' vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb;', ' t = abs( C - Ctoptop );', ' delta.w = max( max( t.r, t.g ), t.b );', // Calculate the final maximum delta: - ' maxDelta = max( max( maxDelta, delta.z ), delta.w );', // Local contrast adaptation in action: - ' edges.xy *= step( 0.5 * maxDelta, delta.xy );', ' return vec4( edges, 0.0, 0.0 );', '}', 'void main() {', ' gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse );', '}'].join('\n') -}); -({ - defines: { - SMAA_MAX_SEARCH_STEPS: '8', - SMAA_AREATEX_MAX_DISTANCE: '16', - SMAA_AREATEX_PIXEL_SIZE: '( 1.0 / vec2( 160.0, 560.0 ) )', - SMAA_AREATEX_SUBTEX_SIZE: '( 1.0 / 7.0 )' - }, - uniforms: { - tDiffuse: { - value: null - }, - tArea: { - value: null - }, - tSearch: { - value: null - }, - resolution: { - value: new Vector2(1 / 1024, 1 / 512) - } - }, - vertexShader: ['uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 3 ];', 'varying vec2 vPixcoord;', 'void SMAABlendingWeightCalculationVS( vec2 texcoord ) {', ' vPixcoord = texcoord / resolution;', // We will use these offsets for the searches later on (see @PSEUDO_GATHER4): - ' vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 );', // WebGL port note: Changed sign in Y and W components - ' vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 );', // WebGL port note: Changed sign in Y and W components - // And these for the searches, they indicate the ends of the loops: - ' vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS );', '}', 'void main() {', ' vUv = uv;', ' SMAABlendingWeightCalculationVS( vUv );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 )', 'uniform sampler2D tDiffuse;', 'uniform sampler2D tArea;', 'uniform sampler2D tSearch;', 'uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[3];', 'varying vec2 vPixcoord;', '#if __VERSION__ == 100', 'vec2 round( vec2 x ) {', ' return sign( x ) * floor( abs( x ) + 0.5 );', '}', '#endif', 'float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) {', // Not required if searchTex accesses are set to point: - // float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0); - // e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE + - // e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE; - ' e.r = bias + e.r * scale;', ' return 255.0 * texture2D( searchTex, e, 0.0 ).r;', '}', 'float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {', - /** - * @PSEUDO_GATHER4 - * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to - * sample between edge, thus fetching four edges in a row. - * Sampling with different offsets in each direction allows to disambiguate - * which edges are active from the four fetched ones. - */ - ' vec2 e = vec2( 0.0, 1.0 );', ' for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) {', // WebGL port note: Changed while to for - ' e = texture2D( edgesTex, texcoord, 0.0 ).rg;', ' texcoord -= vec2( 2.0, 0.0 ) * resolution;', ' if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break;', ' }', // We correct the previous (-0.25, -0.125) offset we applied: - ' texcoord.x += 0.25 * resolution.x;', // The searches are bias by 1, so adjust the coords accordingly: - ' texcoord.x += resolution.x;', // Disambiguate the length added by the last step: - ' texcoord.x += 2.0 * resolution.x;', // Undo last step - ' texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5);', ' return texcoord.x;', '}', 'float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {', ' vec2 e = vec2( 0.0, 1.0 );', ' for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) {', // WebGL port note: Changed while to for - ' e = texture2D( edgesTex, texcoord, 0.0 ).rg;', ' texcoord += vec2( 2.0, 0.0 ) * resolution;', ' if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break;', ' }', ' texcoord.x -= 0.25 * resolution.x;', ' texcoord.x -= resolution.x;', ' texcoord.x -= 2.0 * resolution.x;', ' texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 );', ' return texcoord.x;', '}', 'float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {', ' vec2 e = vec2( 1.0, 0.0 );', ' for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) {', // WebGL port note: Changed while to for - ' e = texture2D( edgesTex, texcoord, 0.0 ).rg;', ' texcoord += vec2( 0.0, 2.0 ) * resolution;', // WebGL port note: Changed sign - ' if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break;', ' }', ' texcoord.y -= 0.25 * resolution.y;', // WebGL port note: Changed sign - ' texcoord.y -= resolution.y;', // WebGL port note: Changed sign - ' texcoord.y -= 2.0 * resolution.y;', // WebGL port note: Changed sign - ' texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 );', // WebGL port note: Changed sign - ' return texcoord.y;', '}', 'float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {', ' vec2 e = vec2( 1.0, 0.0 );', ' for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) {', // WebGL port note: Changed while to for - ' e = texture2D( edgesTex, texcoord, 0.0 ).rg;', ' texcoord -= vec2( 0.0, 2.0 ) * resolution;', // WebGL port note: Changed sign - ' if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break;', ' }', ' texcoord.y += 0.25 * resolution.y;', // WebGL port note: Changed sign - ' texcoord.y += resolution.y;', // WebGL port note: Changed sign - ' texcoord.y += 2.0 * resolution.y;', // WebGL port note: Changed sign - ' texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 );', // WebGL port note: Changed sign - ' return texcoord.y;', '}', 'vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) {', // Rounding prevents precision errors of bilinear filtering: - ' vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist;', // We do a scale and bias for mapping to texel space: - ' texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE );', // Move to proper place, according to the subpixel offset: - ' texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;', ' return texture2D( areaTex, texcoord, 0.0 ).rg;', '}', 'vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) {', ' vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 );', ' vec2 e = texture2D( edgesTex, texcoord ).rg;', ' if ( e.g > 0.0 ) {', // Edge at north - ' vec2 d;', // Find the distance to the left: - ' vec2 coords;', ' coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x );', ' coords.y = offset[ 1 ].y;', // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET) - ' d.x = coords.x;', // Now fetch the left crossing edges, two at a time using bilinear - // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to - // discern what value each edge has: - ' float e1 = texture2D( edgesTex, coords, 0.0 ).r;', // Find the distance to the right: - ' coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y );', ' d.y = coords.x;', // We want the distances to be in pixel units (doing this here allow to - // better interleave arithmetic and memory accesses): - ' d = d / resolution.x - pixcoord.x;', // SMAAArea below needs a sqrt, as the areas texture is compressed - // quadratically: - ' vec2 sqrt_d = sqrt( abs( d ) );', // Fetch the right crossing edges: - ' coords.y -= 1.0 * resolution.y;', // WebGL port note: Added - ' float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r;', // Ok, we know how this pattern looks like, now it is time for getting - // the actual area: - ' weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) );', ' }', ' if ( e.r > 0.0 ) {', // Edge at west - ' vec2 d;', // Find the distance to the top: - ' vec2 coords;', ' coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z );', ' coords.x = offset[ 0 ].x;', // offset[1].x = texcoord.x - 0.25 * resolution.x; - ' d.x = coords.y;', // Fetch the top crossing edges: - ' float e1 = texture2D( edgesTex, coords, 0.0 ).g;', // Find the distance to the bottom: - ' coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w );', ' d.y = coords.y;', // We want the distances to be in pixel units: - ' d = d / resolution.y - pixcoord.y;', // SMAAArea below needs a sqrt, as the areas texture is compressed - // quadratically: - ' vec2 sqrt_d = sqrt( abs( d ) );', // Fetch the bottom crossing edges: - ' coords.y -= 1.0 * resolution.y;', // WebGL port note: Added - ' float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g;', // Get the area for this direction: - ' weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) );', ' }', ' return weights;', '}', 'void main() {', ' gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) );', '}'].join('\n') -}); -({ - uniforms: { - tDiffuse: { - value: null - }, - tColor: { - value: null - }, - resolution: { - value: new Vector2(1 / 1024, 1 / 512) - } - }, - vertexShader: ['uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 2 ];', 'void SMAANeighborhoodBlendingVS( vec2 texcoord ) {', ' vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 );', // WebGL port note: Changed sign in W component - ' vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 );', // WebGL port note: Changed sign in W component - '}', 'void main() {', ' vUv = uv;', ' SMAANeighborhoodBlendingVS( vUv );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform sampler2D tColor;', 'uniform vec2 resolution;', 'varying vec2 vUv;', 'varying vec4 vOffset[ 2 ];', 'vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) {', // Fetch the blending weights for current pixel: - ' vec4 a;', ' a.xz = texture2D( blendTex, texcoord ).xz;', ' a.y = texture2D( blendTex, offset[ 1 ].zw ).g;', ' a.w = texture2D( blendTex, offset[ 1 ].xy ).a;', // Is there any blending weight with a value greater than 0.0? - ' if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) {', ' return texture2D( colorTex, texcoord, 0.0 );', ' } else {', // Up to 4 lines can be crossing a pixel (one through each edge). We - // favor blending by choosing the line with the maximum weight for each - // direction: - ' vec2 offset;', ' offset.x = a.a > a.b ? a.a : -a.b;', // left vs. right - ' offset.y = a.g > a.r ? -a.g : a.r;', // top vs. bottom // WebGL port note: Changed signs - // Then we go in the direction that has the maximum weight: - ' if ( abs( offset.x ) > abs( offset.y )) {', // horizontal vs. vertical - ' offset.y = 0.0;', ' } else {', ' offset.x = 0.0;', ' }', // Fetch the opposite color and lerp by hand: - ' vec4 C = texture2D( colorTex, texcoord, 0.0 );', ' texcoord += sign( offset ) * resolution;', ' vec4 Cop = texture2D( colorTex, texcoord, 0.0 );', ' float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y );', // WebGL port note: Added gamma correction - ' C.xyz = pow(C.xyz, vec3(2.2));', ' Cop.xyz = pow(Cop.xyz, vec3(2.2));', ' vec4 mixed = mix(C, Cop, s);', ' mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2));', ' return mixed;', ' }', '}', 'void main() {', ' gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse );', '}'].join('\n') -}); + function invalidateContextProvider(workInProgress, type, didChange) { + { + var instance = workInProgress.stateNode; -/** - * Full-screen textured quad shader - */ -const CopyShader = { - uniforms: { - tDiffuse: { - value: null - }, - opacity: { - value: 1.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform float opacity;', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' gl_FragColor = opacity * texel;', '}'].join('\n') -}; + if (!instance) { + throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** - * References: - * http://john-chapman-graphics.blogspot.com/2013/01/ssao-tutorial.html - * https://learnopengl.com/Advanced-Lighting/SSAO - * https://github.com/McNopper/OpenGL/blob/master/Example28/shader/ssao.frag.glsl - */ + if (didChange) { + // Merge parent and own context. + // Skip this if we're not updating due to sCU. + // This avoids unnecessarily recomputing memoized values. + var mergedContext = processChildContext(workInProgress, type, previousContext); + instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. + // It is important to unwind the context in the reverse order. -const SSAOShader = { - defines: { - PERSPECTIVE_CAMERA: 1, - KERNEL_SIZE: 32 - }, - uniforms: { - tDiffuse: { - value: null - }, - tNormal: { - value: null - }, - tDepth: { - value: null - }, - tNoise: { - value: null - }, - kernel: { - value: null - }, - cameraNear: { - value: null - }, - cameraFar: { - value: null - }, - resolution: { - value: new Vector2() - }, - cameraProjectionMatrix: { - value: new Matrix4() - }, - cameraInverseProjectionMatrix: { - value: new Matrix4() - }, - kernelRadius: { - value: 8 - }, - minDistance: { - value: 0.005 - }, - maxDistance: { - value: 0.05 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform sampler2D tNormal;', 'uniform sampler2D tDepth;', 'uniform sampler2D tNoise;', 'uniform vec3 kernel[ KERNEL_SIZE ];', 'uniform vec2 resolution;', 'uniform float cameraNear;', 'uniform float cameraFar;', 'uniform mat4 cameraProjectionMatrix;', 'uniform mat4 cameraInverseProjectionMatrix;', 'uniform float kernelRadius;', 'uniform float minDistance;', // avoid artifacts caused by neighbour fragments with minimal depth difference - 'uniform float maxDistance;', // avoid the influence of fragments which are too far away - 'varying vec2 vUv;', '#include ', 'float getDepth( const in vec2 screenPosition ) {', ' return texture2D( tDepth, screenPosition ).x;', '}', 'float getLinearDepth( const in vec2 screenPosition ) {', ' #if PERSPECTIVE_CAMERA == 1', ' float fragCoordZ = texture2D( tDepth, screenPosition ).x;', ' float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );', ' return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );', ' #else', ' return texture2D( tDepth, screenPosition ).x;', ' #endif', '}', 'float getViewZ( const in float depth ) {', ' #if PERSPECTIVE_CAMERA == 1', ' return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );', ' #else', ' return orthographicDepthToViewZ( depth, cameraNear, cameraFar );', ' #endif', '}', 'vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {', ' float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];', ' vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );', ' clipPosition *= clipW; // unprojection.', ' return ( cameraInverseProjectionMatrix * clipPosition ).xyz;', '}', 'vec3 getViewNormal( const in vec2 screenPosition ) {', ' return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );', '}', 'void main() {', ' float depth = getDepth( vUv );', ' float viewZ = getViewZ( depth );', ' vec3 viewPosition = getViewPosition( vUv, depth, viewZ );', ' vec3 viewNormal = getViewNormal( vUv );', ' vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 );', ' vec3 random = texture2D( tNoise, vUv * noiseScale ).xyz;', // compute matrix used to reorient a kernel vector - ' vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) );', ' vec3 bitangent = cross( viewNormal, tangent );', ' mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal );', ' float occlusion = 0.0;', ' for ( int i = 0; i < KERNEL_SIZE; i ++ ) {', ' vec3 sampleVector = kernelMatrix * kernel[ i ];', // reorient sample vector in view space - ' vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius );', // calculate sample point - ' vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 );', // project point and calculate NDC - ' samplePointNDC /= samplePointNDC.w;', ' vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5;', // compute uv coordinates - ' float realDepth = getLinearDepth( samplePointUv );', // get linear depth from depth texture - ' float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar );', // compute linear depth of the sample view Z value - ' float delta = sampleDepth - realDepth;', ' if ( delta > minDistance && delta < maxDistance ) {', // if fragment is before sample point, increase occlusion - ' occlusion += 1.0;', ' }', ' }', ' occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 );', ' gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 );', '}'].join('\n') -}; -const SSAODepthShader = { - defines: { - PERSPECTIVE_CAMERA: 1 - }, - uniforms: { - tDepth: { - value: null - }, - cameraNear: { - value: null - }, - cameraFar: { - value: null - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDepth;', 'uniform float cameraNear;', 'uniform float cameraFar;', 'varying vec2 vUv;', '#include ', 'float getLinearDepth( const in vec2 screenPosition ) {', ' #if PERSPECTIVE_CAMERA == 1', ' float fragCoordZ = texture2D( tDepth, screenPosition ).x;', ' float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );', ' return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );', ' #else', ' return texture2D( tDepth, screenPosition ).x;', ' #endif', '}', 'void main() {', ' float depth = getLinearDepth( vUv );', ' gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );', '}'].join('\n') -}; -const SSAOBlurShader = { - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2() - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform vec2 resolution;', 'varying vec2 vUv;', 'void main() {', ' vec2 texelSize = ( 1.0 / resolution );', ' float result = 0.0;', ' for ( int i = - 2; i <= 2; i ++ ) {', ' for ( int j = - 2; j <= 2; j ++ ) {', ' vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize;', ' result += texture2D( tDiffuse, vUv + offset ).r;', ' }', ' }', ' gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 );', '}'].join('\n') -}; + pop(didPerformWorkStackCursor, workInProgress); + pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. -class SSAOPass extends Pass$1 { - constructor(scene, camera, width, height) { - super(); - this.width = width !== undefined ? width : 512; - this.height = height !== undefined ? height : 512; - this.clear = true; - this.camera = camera; - this.scene = scene; - this.kernelRadius = 8; - this.kernelSize = 32; - this.kernel = []; - this.noiseTexture = null; - this.output = 0; - this.minDistance = 0.005; - this.maxDistance = 0.1; - this._visibilityCache = new Map(); // - - this.generateSampleKernel(); - this.generateRandomKernelRotations(); // beauty render target - - const depthTexture = new DepthTexture(); - depthTexture.format = DepthStencilFormat; - depthTexture.type = UnsignedInt248Type; - this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height); // normal render target with depth buffer - - this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: NearestFilter, - magFilter: NearestFilter, - depthTexture: depthTexture - }); // ssao render target + push(contextStackCursor, mergedContext, workInProgress); + push(didPerformWorkStackCursor, didChange, workInProgress); + } else { + pop(didPerformWorkStackCursor, workInProgress); + push(didPerformWorkStackCursor, didChange, workInProgress); + } + } + } - this.ssaoRenderTarget = new WebGLRenderTarget(this.width, this.height); - this.blurRenderTarget = this.ssaoRenderTarget.clone(); // ssao material + function findCurrentUnmaskedContext(fiber) { + { + // Currently this is only used with renderSubtreeIntoContainer; not sure if it + // makes sense elsewhere + if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { + throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } - if (SSAOShader === undefined) { - console.error('THREE.SSAOPass: The pass relies on SSAOShader.'); - } + var node = fiber; - this.ssaoMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSAOShader.defines), - uniforms: UniformsUtils.clone(SSAOShader.uniforms), - vertexShader: SSAOShader.vertexShader, - fragmentShader: SSAOShader.fragmentShader, - blending: NoBlending - }); - this.ssaoMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.ssaoMaterial.uniforms['tNormal'].value = this.normalRenderTarget.texture; - this.ssaoMaterial.uniforms['tDepth'].value = this.normalRenderTarget.depthTexture; - this.ssaoMaterial.uniforms['tNoise'].value = this.noiseTexture; - this.ssaoMaterial.uniforms['kernel'].value = this.kernel; - this.ssaoMaterial.uniforms['cameraNear'].value = this.camera.near; - this.ssaoMaterial.uniforms['cameraFar'].value = this.camera.far; - this.ssaoMaterial.uniforms['resolution'].value.set(this.width, this.height); - this.ssaoMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssaoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); // normal material - - this.normalMaterial = new MeshNormalMaterial(); - this.normalMaterial.blending = NoBlending; // blur material - - this.blurMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSAOBlurShader.defines), - uniforms: UniformsUtils.clone(SSAOBlurShader.uniforms), - vertexShader: SSAOBlurShader.vertexShader, - fragmentShader: SSAOBlurShader.fragmentShader - }); - this.blurMaterial.uniforms['tDiffuse'].value = this.ssaoRenderTarget.texture; - this.blurMaterial.uniforms['resolution'].value.set(this.width, this.height); // material for rendering the depth - - this.depthRenderMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSAODepthShader.defines), - uniforms: UniformsUtils.clone(SSAODepthShader.uniforms), - vertexShader: SSAODepthShader.vertexShader, - fragmentShader: SSAODepthShader.fragmentShader, - blending: NoBlending - }); - this.depthRenderMaterial.uniforms['tDepth'].value = this.normalRenderTarget.depthTexture; - this.depthRenderMaterial.uniforms['cameraNear'].value = this.camera.near; - this.depthRenderMaterial.uniforms['cameraFar'].value = this.camera.far; // material for rendering the content of a render target - - this.copyMaterial = new ShaderMaterial({ - uniforms: UniformsUtils.clone(CopyShader.uniforms), - vertexShader: CopyShader.vertexShader, - fragmentShader: CopyShader.fragmentShader, - transparent: true, - depthTest: false, - depthWrite: false, - blendSrc: DstColorFactor, - blendDst: ZeroFactor, - blendEquation: AddEquation, - blendSrcAlpha: DstAlphaFactor, - blendDstAlpha: ZeroFactor, - blendEquationAlpha: AddEquation - }); - this.fsQuad = new FullScreenQuad(null); - this.originalClearColor = new Color(); - } + do { + switch (node.tag) { + case HostRoot: + return node.stateNode.context; - dispose() { - // dispose render targets - this.beautyRenderTarget.dispose(); - this.normalRenderTarget.dispose(); - this.ssaoRenderTarget.dispose(); - this.blurRenderTarget.dispose(); // dispose materials + case ClassComponent: + { + var Component = node.type; - this.normalMaterial.dispose(); - this.blurMaterial.dispose(); - this.copyMaterial.dispose(); - this.depthRenderMaterial.dispose(); // dipsose full screen quad + if (isContextProvider(Component)) { + return node.stateNode.__reactInternalMemoizedMergedChildContext; + } - this.fsQuad.dispose(); - } + break; + } + } - render(renderer, writeBuffer - /*, readBuffer, deltaTime, maskActive */ - ) { - if (renderer.capabilities.isWebGL2 === false) this.noiseTexture.format = LuminanceFormat; // render beauty + node = node.return; + } while (node !== null); - renderer.setRenderTarget(this.beautyRenderTarget); - renderer.clear(); - renderer.render(this.scene, this.camera); // render normals and depth (honor only meshes, points and lines do not contribute to SSAO) + throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } + } - this.overrideVisibility(); - this.renderOverride(renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0); - this.restoreVisibility(); // render SSAO + var LegacyRoot = 0; + var ConcurrentRoot = 1; - this.ssaoMaterial.uniforms['kernelRadius'].value = this.kernelRadius; - this.ssaoMaterial.uniforms['minDistance'].value = this.minDistance; - this.ssaoMaterial.uniforms['maxDistance'].value = this.maxDistance; - this.renderPass(renderer, this.ssaoMaterial, this.ssaoRenderTarget); // render blur + var NoMode = + /* */ + 0; // TODO: Remove ConcurrentMode by reading from the root tag instead - this.renderPass(renderer, this.blurMaterial, this.blurRenderTarget); // output result to screen + var ConcurrentMode = + /* */ + 1; + var ProfileMode = + /* */ + 2; + var StrictLegacyMode = + /* */ + 8; + var StrictEffectsMode = + /* */ + 16; - switch (this.output) { - case SSAOPass.OUTPUT.SSAO: - this.copyMaterial.uniforms['tDiffuse'].value = this.ssaoRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + // TODO: This is pretty well supported by browsers. Maybe we can drop it. + var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. + // Based on: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 - case SSAOPass.OUTPUT.Blur: - this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + var log = Math.log; + var LN2 = Math.LN2; - case SSAOPass.OUTPUT.Beauty: - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + function clz32Fallback(x) { + var asUint = x >>> 0; - case SSAOPass.OUTPUT.Depth: - this.renderPass(renderer, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); - break; + if (asUint === 0) { + return 32; + } - case SSAOPass.OUTPUT.Normal: - this.copyMaterial.uniforms['tDiffuse'].value = this.normalRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + return 31 - (log(asUint) / LN2 | 0) | 0; + } - case SSAOPass.OUTPUT.Default: - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget.texture; - this.copyMaterial.blending = CustomBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + // If those values are changed that package should be rebuilt and redeployed. - default: - console.warn('THREE.SSAOPass: Unknown output type.'); - } - } + var TotalLanes = 31; + var NoLanes = + /* */ + 0; + var NoLane = + /* */ + 0; + var SyncLane = + /* */ + 1; + var InputContinuousHydrationLane = + /* */ + 2; + var InputContinuousLane = + /* */ + 4; + var DefaultHydrationLane = + /* */ + 8; + var DefaultLane = + /* */ + 16; + var TransitionHydrationLane = + /* */ + 32; + var TransitionLanes = + /* */ + 4194240; + var TransitionLane1 = + /* */ + 64; + var TransitionLane2 = + /* */ + 128; + var TransitionLane3 = + /* */ + 256; + var TransitionLane4 = + /* */ + 512; + var TransitionLane5 = + /* */ + 1024; + var TransitionLane6 = + /* */ + 2048; + var TransitionLane7 = + /* */ + 4096; + var TransitionLane8 = + /* */ + 8192; + var TransitionLane9 = + /* */ + 16384; + var TransitionLane10 = + /* */ + 32768; + var TransitionLane11 = + /* */ + 65536; + var TransitionLane12 = + /* */ + 131072; + var TransitionLane13 = + /* */ + 262144; + var TransitionLane14 = + /* */ + 524288; + var TransitionLane15 = + /* */ + 1048576; + var TransitionLane16 = + /* */ + 2097152; + var RetryLanes = + /* */ + 130023424; + var RetryLane1 = + /* */ + 4194304; + var RetryLane2 = + /* */ + 8388608; + var RetryLane3 = + /* */ + 16777216; + var RetryLane4 = + /* */ + 33554432; + var RetryLane5 = + /* */ + 67108864; + var SomeRetryLane = RetryLane1; + var SelectiveHydrationLane = + /* */ + 134217728; + var NonIdleLanes = + /* */ + 268435455; + var IdleHydrationLane = + /* */ + 268435456; + var IdleLane = + /* */ + 536870912; + var OffscreenLane = + /* */ + 1073741824; // This function is used for the experimental timeline (react-devtools-timeline) + // It should be kept in sync with the Lanes values above. - renderPass(renderer, passMaterial, renderTarget, clearColor, clearAlpha) { - // save original state - renderer.getClearColor(this.originalClearColor); - const originalClearAlpha = renderer.getClearAlpha(); - const originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); // setup pass state + function getLabelForLane(lane) { + { + if (lane & SyncLane) { + return 'Sync'; + } - renderer.autoClear = false; + if (lane & InputContinuousHydrationLane) { + return 'InputContinuousHydration'; + } - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + if (lane & InputContinuousLane) { + return 'InputContinuous'; + } - this.fsQuad.material = passMaterial; - this.fsQuad.render(renderer); // restore original state + if (lane & DefaultHydrationLane) { + return 'DefaultHydration'; + } - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - } + if (lane & DefaultLane) { + return 'Default'; + } - renderOverride(renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { - renderer.getClearColor(this.originalClearColor); - const originalClearAlpha = renderer.getClearAlpha(); - const originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); - renderer.autoClear = false; - clearColor = overrideMaterial.clearColor || clearColor; - clearAlpha = overrideMaterial.clearAlpha || clearAlpha; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + if (lane & TransitionHydrationLane) { + return 'TransitionHydration'; + } - this.scene.overrideMaterial = overrideMaterial; - renderer.render(this.scene, this.camera); - this.scene.overrideMaterial = null; // restore original state + if (lane & TransitionLanes) { + return 'Transition'; + } - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - } + if (lane & RetryLanes) { + return 'Retry'; + } - setSize(width, height) { - this.width = width; - this.height = height; - this.beautyRenderTarget.setSize(width, height); - this.ssaoRenderTarget.setSize(width, height); - this.normalRenderTarget.setSize(width, height); - this.blurRenderTarget.setSize(width, height); - this.ssaoMaterial.uniforms['resolution'].value.set(width, height); - this.ssaoMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssaoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - this.blurMaterial.uniforms['resolution'].value.set(width, height); - } - - generateSampleKernel() { - const kernelSize = this.kernelSize; - const kernel = this.kernel; - - for (let i = 0; i < kernelSize; i++) { - const sample = new Vector3(); - sample.x = Math.random() * 2 - 1; - sample.y = Math.random() * 2 - 1; - sample.z = Math.random(); - sample.normalize(); - let scale = i / kernelSize; - scale = MathUtils.lerp(0.1, 1, scale * scale); - sample.multiplyScalar(scale); - kernel.push(sample); - } - } + if (lane & SelectiveHydrationLane) { + return 'SelectiveHydration'; + } - generateRandomKernelRotations() { - const width = 4, - height = 4; + if (lane & IdleHydrationLane) { + return 'IdleHydration'; + } - if (SimplexNoise === undefined) { - console.error('THREE.SSAOPass: The pass relies on SimplexNoise.'); - } + if (lane & IdleLane) { + return 'Idle'; + } - const simplex = new SimplexNoise(); - const size = width * height; - const data = new Float32Array(size); + if (lane & OffscreenLane) { + return 'Offscreen'; + } + } + } + var NoTimestamp = -1; + var nextTransitionLane = TransitionLane1; + var nextRetryLane = RetryLane1; - for (let i = 0; i < size; i++) { - const x = Math.random() * 2 - 1; - const y = Math.random() * 2 - 1; - const z = 0; - data[i] = simplex.noise3d(x, y, z); - } + function getHighestPriorityLanes(lanes) { + switch (getHighestPriorityLane(lanes)) { + case SyncLane: + return SyncLane; - this.noiseTexture = new DataTexture(data, width, height, RedFormat, FloatType); - this.noiseTexture.wrapS = RepeatWrapping; - this.noiseTexture.wrapT = RepeatWrapping; - this.noiseTexture.needsUpdate = true; - } + case InputContinuousHydrationLane: + return InputContinuousHydrationLane; - overrideVisibility() { - const scene = this.scene; - const cache = this._visibilityCache; - scene.traverse(function (object) { - cache.set(object, object.visible); - if (object.isPoints || object.isLine) object.visible = false; - }); - } + case InputContinuousLane: + return InputContinuousLane; - restoreVisibility() { - const scene = this.scene; - const cache = this._visibilityCache; - scene.traverse(function (object) { - const visible = cache.get(object); - object.visible = visible; - }); - cache.clear(); - } + case DefaultHydrationLane: + return DefaultHydrationLane; -} + case DefaultLane: + return DefaultLane; -SSAOPass.OUTPUT = { - Default: 0, - SSAO: 1, - Blur: 2, - Beauty: 3, - Depth: 4, - Normal: 5 -}; + case TransitionHydrationLane: + return TransitionHydrationLane; -var TexturePass = function (map, opacity) { - if (CopyShader === undefined) console.error('THREE.TexturePass relies on CopyShader'); - var shader = CopyShader; - this.map = map; - this.opacity = opacity !== undefined ? opacity : 1.0; - this.uniforms = UniformsUtils.clone(shader.uniforms); - this.material = new ShaderMaterial({ - uniforms: this.uniforms, - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - depthTest: false, - depthWrite: false - }); - this.needsSwap = false; - this.fsQuad = new FullScreenQuad(null); -}; + case TransitionLane1: + case TransitionLane2: + case TransitionLane3: + case TransitionLane4: + case TransitionLane5: + case TransitionLane6: + case TransitionLane7: + case TransitionLane8: + case TransitionLane9: + case TransitionLane10: + case TransitionLane11: + case TransitionLane12: + case TransitionLane13: + case TransitionLane14: + case TransitionLane15: + case TransitionLane16: + return lanes & TransitionLanes; -TexturePass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: TexturePass, - render: function (renderer, writeBuffer, readBuffer - /*, deltaTime, maskActive */ - ) { - var oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - this.fsQuad.material = this.material; - this.uniforms['opacity'].value = this.opacity; - this.uniforms['tDiffuse'].value = this.map; - this.material.transparent = this.opacity < 1.0; - renderer.setRenderTarget(this.renderToScreen ? null : readBuffer); - if (this.clear) renderer.clear(); - this.fsQuad.render(renderer); - renderer.autoClear = oldAutoClear; - } -}); + case RetryLane1: + case RetryLane2: + case RetryLane3: + case RetryLane4: + case RetryLane5: + return lanes & RetryLanes; -/** - * Luminosity - * http://en.wikipedia.org/wiki/Luminosity - */ -const LuminosityShader = { - uniforms: { - tDiffuse: { - value: null - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' float l = linearToRelativeLuminance( texel.rgb );', ' gl_FragColor = vec4( l, l, l, texel.w );', '}'].join('\n') -}; + case SelectiveHydrationLane: + return SelectiveHydrationLane; -/** - * Full-screen tone-mapping shader based on http://www.cis.rit.edu/people/faculty/ferwerda/publications/sig02_paper.pdf - */ -const ToneMapShader = { - uniforms: { - tDiffuse: { - value: null - }, - averageLuminance: { - value: 1.0 - }, - luminanceMap: { - value: null - }, - maxLuminance: { - value: 16.0 - }, - minLuminance: { - value: 0.01 - }, - middleGrey: { - value: 0.6 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'uniform float middleGrey;', 'uniform float minLuminance;', 'uniform float maxLuminance;', '#ifdef ADAPTED_LUMINANCE', ' uniform sampler2D luminanceMap;', '#else', ' uniform float averageLuminance;', '#endif', 'vec3 ToneMap( vec3 vColor ) {', ' #ifdef ADAPTED_LUMINANCE', // Get the calculated average luminance - ' float fLumAvg = texture2D(luminanceMap, vec2(0.5, 0.5)).r;', ' #else', ' float fLumAvg = averageLuminance;', ' #endif', // Calculate the luminance of the current pixel - ' float fLumPixel = linearToRelativeLuminance( vColor );', // Apply the modified operator (Eq. 4) - ' float fLumScaled = (fLumPixel * middleGrey) / max( minLuminance, fLumAvg );', ' float fLumCompressed = (fLumScaled * (1.0 + (fLumScaled / (maxLuminance * maxLuminance)))) / (1.0 + fLumScaled);', ' return fLumCompressed * vColor;', '}', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' gl_FragColor = vec4( ToneMap( texel.xyz ), texel.w );', '}'].join('\n') -}; + case IdleHydrationLane: + return IdleHydrationLane; -/** - * Generate a texture that represents the luminosity of the current scene, adapted over time - * to simulate the optic nerve responding to the amount of light it is receiving. - * Based on a GDC2007 presentation by Wolfgang Engel titled "Post-Processing Pipeline" - * - * Full-screen tone-mapping shader based on http://www.graphics.cornell.edu/~jaf/publications/sig02_paper.pdf - */ + case IdleLane: + return IdleLane; -var AdaptiveToneMappingPass = function (adaptive, resolution) { - this.resolution = resolution !== undefined ? resolution : 256; - this.needsInit = true; - this.adaptive = adaptive !== undefined ? !!adaptive : true; - this.luminanceRT = null; - this.previousLuminanceRT = null; - this.currentLuminanceRT = null; - if (CopyShader === undefined) console.error('THREE.AdaptiveToneMappingPass relies on CopyShader'); - var copyShader = CopyShader; - this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); - this.materialCopy = new ShaderMaterial({ - uniforms: this.copyUniforms, - vertexShader: copyShader.vertexShader, - fragmentShader: copyShader.fragmentShader, - blending: NoBlending, - depthTest: false - }); - if (LuminosityShader === undefined) console.error('THREE.AdaptiveToneMappingPass relies on LuminosityShader'); - this.materialLuminance = new ShaderMaterial({ - uniforms: UniformsUtils.clone(LuminosityShader.uniforms), - vertexShader: LuminosityShader.vertexShader, - fragmentShader: LuminosityShader.fragmentShader, - blending: NoBlending - }); - this.adaptLuminanceShader = { - defines: { - MIP_LEVEL_1X1: (Math.log(this.resolution) / Math.log(2.0)).toFixed(1) - }, - uniforms: { - lastLum: { - value: null - }, - currentLum: { - value: null - }, - minLuminance: { - value: 0.01 - }, - delta: { - value: 0.016 - }, - tau: { - value: 1.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['varying vec2 vUv;', 'uniform sampler2D lastLum;', 'uniform sampler2D currentLum;', 'uniform float minLuminance;', 'uniform float delta;', 'uniform float tau;', 'void main() {', ' vec4 lastLum = texture2D( lastLum, vUv, MIP_LEVEL_1X1 );', ' vec4 currentLum = texture2D( currentLum, vUv, MIP_LEVEL_1X1 );', ' float fLastLum = max( minLuminance, lastLum.r );', ' float fCurrentLum = max( minLuminance, currentLum.r );', //The adaption seems to work better in extreme lighting differences - //if the input luminance is squared. - ' fCurrentLum *= fCurrentLum;', // Adapt the luminance using Pattanaik's technique - ' float fAdaptedLum = fLastLum + (fCurrentLum - fLastLum) * (1.0 - exp(-delta * tau));', // "fAdaptedLum = sqrt(fAdaptedLum);", - ' gl_FragColor.r = fAdaptedLum;', '}'].join('\n') - }; - this.materialAdaptiveLum = new ShaderMaterial({ - uniforms: UniformsUtils.clone(this.adaptLuminanceShader.uniforms), - vertexShader: this.adaptLuminanceShader.vertexShader, - fragmentShader: this.adaptLuminanceShader.fragmentShader, - defines: Object.assign({}, this.adaptLuminanceShader.defines), - blending: NoBlending - }); - if (ToneMapShader === undefined) console.error('THREE.AdaptiveToneMappingPass relies on ToneMapShader'); - this.materialToneMap = new ShaderMaterial({ - uniforms: UniformsUtils.clone(ToneMapShader.uniforms), - vertexShader: ToneMapShader.vertexShader, - fragmentShader: ToneMapShader.fragmentShader, - blending: NoBlending - }); - this.fsQuad = new FullScreenQuad(null); -}; + case OffscreenLane: + return OffscreenLane; -AdaptiveToneMappingPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: AdaptiveToneMappingPass, - render: function (renderer, writeBuffer, readBuffer, deltaTime - /*, maskActive*/ - ) { - if (this.needsInit) { - this.reset(renderer); - this.luminanceRT.texture.type = readBuffer.texture.type; - this.previousLuminanceRT.texture.type = readBuffer.texture.type; - this.currentLuminanceRT.texture.type = readBuffer.texture.type; - this.needsInit = false; - } + default: + { + error('Should have found matching lanes. This is a bug in React.'); + } // This shouldn't be reachable, but as a fallback, return the entire bitmask. - if (this.adaptive) { - //Render the luminance of the current scene into a render target with mipmapping enabled - this.fsQuad.material = this.materialLuminance; - this.materialLuminance.uniforms.tDiffuse.value = readBuffer.texture; - renderer.setRenderTarget(this.currentLuminanceRT); - this.fsQuad.render(renderer); //Use the new luminance values, the previous luminance and the frame delta to - //adapt the luminance over time. - - this.fsQuad.material = this.materialAdaptiveLum; - this.materialAdaptiveLum.uniforms.delta.value = deltaTime; - this.materialAdaptiveLum.uniforms.lastLum.value = this.previousLuminanceRT.texture; - this.materialAdaptiveLum.uniforms.currentLum.value = this.currentLuminanceRT.texture; - renderer.setRenderTarget(this.luminanceRT); - this.fsQuad.render(renderer); //Copy the new adapted luminance value so that it can be used by the next frame. - - this.fsQuad.material = this.materialCopy; - this.copyUniforms.tDiffuse.value = this.luminanceRT.texture; - renderer.setRenderTarget(this.previousLuminanceRT); - this.fsQuad.render(renderer); - } - this.fsQuad.material = this.materialToneMap; - this.materialToneMap.uniforms.tDiffuse.value = readBuffer.texture; + return lanes; + } + } - if (this.renderToScreen) { - renderer.setRenderTarget(null); - this.fsQuad.render(renderer); - } else { - renderer.setRenderTarget(writeBuffer); - if (this.clear) renderer.clear(); - this.fsQuad.render(renderer); - } - }, - reset: function () { - // render targets - if (this.luminanceRT) { - this.luminanceRT.dispose(); - } + function getNextLanes(root, wipLanes) { + // Early bailout if there's no pending work left. + var pendingLanes = root.pendingLanes; - if (this.currentLuminanceRT) { - this.currentLuminanceRT.dispose(); - } + if (pendingLanes === NoLanes) { + return NoLanes; + } - if (this.previousLuminanceRT) { - this.previousLuminanceRT.dispose(); - } + var nextLanes = NoLanes; + var suspendedLanes = root.suspendedLanes; + var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished, + // even if the work is suspended. - var pars = { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }; // was RGB format. changed to RGBA format. see discussion in #8415 / #8450 + var nonIdlePendingLanes = pendingLanes & NonIdleLanes; - this.luminanceRT = new WebGLRenderTarget(this.resolution, this.resolution, pars); - this.luminanceRT.texture.name = 'AdaptiveToneMappingPass.l'; - this.luminanceRT.texture.generateMipmaps = false; - this.previousLuminanceRT = new WebGLRenderTarget(this.resolution, this.resolution, pars); - this.previousLuminanceRT.texture.name = 'AdaptiveToneMappingPass.pl'; - this.previousLuminanceRT.texture.generateMipmaps = false; // We only need mipmapping for the current luminosity because we want a down-sampled version to sample in our adaptive shader + if (nonIdlePendingLanes !== NoLanes) { + var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; - pars.minFilter = LinearMipmapLinearFilter; - pars.generateMipmaps = true; - this.currentLuminanceRT = new WebGLRenderTarget(this.resolution, this.resolution, pars); - this.currentLuminanceRT.texture.name = 'AdaptiveToneMappingPass.cl'; + if (nonIdleUnblockedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); + } else { + var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; - if (this.adaptive) { - this.materialToneMap.defines['ADAPTED_LUMINANCE'] = ''; - this.materialToneMap.uniforms.luminanceMap.value = this.luminanceRT.texture; - } //Put something in the adaptive luminance texture so that the scene can render initially + if (nonIdlePingedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); + } + } + } else { + // The only remaining work is Idle. + var unblockedLanes = pendingLanes & ~suspendedLanes; + if (unblockedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(unblockedLanes); + } else { + if (pingedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(pingedLanes); + } + } + } - this.fsQuad.material = new MeshBasicMaterial({ - color: 0x777777 - }); - this.materialLuminance.needsUpdate = true; - this.materialAdaptiveLum.needsUpdate = true; - this.materialToneMap.needsUpdate = true; // renderer.render( this.scene, this.camera, this.luminanceRT ); - // renderer.render( this.scene, this.camera, this.previousLuminanceRT ); - // renderer.render( this.scene, this.camera, this.currentLuminanceRT ); - }, - setAdaptive: function (adaptive) { - if (adaptive) { - this.adaptive = true; - this.materialToneMap.defines['ADAPTED_LUMINANCE'] = ''; - this.materialToneMap.uniforms.luminanceMap.value = this.luminanceRT.texture; - } else { - this.adaptive = false; - delete this.materialToneMap.defines['ADAPTED_LUMINANCE']; - this.materialToneMap.uniforms.luminanceMap.value = null; - } + if (nextLanes === NoLanes) { + // This should only be reachable if we're suspended + // TODO: Consider warning in this path if a fallback timer is not scheduled. + return NoLanes; + } // If we're already in the middle of a render, switching lanes will interrupt + // it and we'll lose our progress. We should only do this if the new lanes are + // higher priority. - this.materialToneMap.needsUpdate = true; - }, - setAdaptionRate: function (rate) { - if (rate) { - this.materialAdaptiveLum.uniforms.tau.value = Math.abs(rate); - } - }, - setMinLuminance: function (minLum) { - if (minLum) { - this.materialToneMap.uniforms.minLuminance.value = minLum; - this.materialAdaptiveLum.uniforms.minLuminance.value = minLum; - } - }, - setMaxLuminance: function (maxLum) { - if (maxLum) { - this.materialToneMap.uniforms.maxLuminance.value = maxLum; - } - }, - setAverageLuminance: function (avgLum) { - if (avgLum) { - this.materialToneMap.uniforms.averageLuminance.value = avgLum; - } - }, - setMiddleGrey: function (middleGrey) { - if (middleGrey) { - this.materialToneMap.uniforms.middleGrey.value = middleGrey; - } - }, - dispose: function () { - if (this.luminanceRT) { - this.luminanceRT.dispose(); - } - if (this.previousLuminanceRT) { - this.previousLuminanceRT.dispose(); - } + if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't + // bother waiting until the root is complete. + (wipLanes & suspendedLanes) === NoLanes) { + var nextLane = getHighestPriorityLane(nextLanes); + var wipLane = getHighestPriorityLane(wipLanes); - if (this.currentLuminanceRT) { - this.currentLuminanceRT.dispose(); - } + if ( // Tests whether the next lane is equal or lower priority than the wip + // one. This works because the bits decrease in priority as you go left. + nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The + // only difference between default updates and transition updates is that + // default updates do not support refresh transitions. + nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) { + // Keep working on the existing in-progress tree. Do not interrupt. + return wipLanes; + } + } - if (this.materialLuminance) { - this.materialLuminance.dispose(); - } + if ((nextLanes & InputContinuousLane) !== NoLanes) { + // When updates are sync by default, we entangle continuous priority updates + // and default updates, so they render in the same batch. The only reason + // they use separate lanes is because continuous updates should interrupt + // transitions, but default updates should not. + nextLanes |= pendingLanes & DefaultLane; + } // Check for entangled lanes and add them to the batch. + // + // A lane is said to be entangled with another when it's not allowed to render + // in a batch that does not also include the other lane. Typically we do this + // when multiple updates have the same source, and we only want to respond to + // the most recent event from that source. + // + // Note that we apply entanglements *after* checking for partial work above. + // This means that if a lane is entangled during an interleaved event while + // it's already rendering, we won't interrupt it. This is intentional, since + // entanglement is usually "best effort": we'll try our best to render the + // lanes in the same batch, but it's not worth throwing out partially + // completed work in order to do it. + // TODO: Reconsider this. The counter-argument is that the partial work + // represents an intermediate state, which we don't want to show to the user. + // And by spending extra time finishing it, we're increasing the amount of + // time it takes to show the final state, which is what they are actually + // waiting for. + // + // For those exceptions where entanglement is semantically important, like + // useMutableSource, we should ensure that there is no partial work at the + // time we apply the entanglement. - if (this.materialAdaptiveLum) { - this.materialAdaptiveLum.dispose(); - } - if (this.materialCopy) { - this.materialCopy.dispose(); - } + var entangledLanes = root.entangledLanes; - if (this.materialToneMap) { - this.materialToneMap.dispose(); - } - } -}); + if (entangledLanes !== NoLanes) { + var entanglements = root.entanglements; + var lanes = nextLanes & entangledLanes; -/** - * Luminosity - * http://en.wikipedia.org/wiki/Luminosity - */ + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + nextLanes |= entanglements[index]; + lanes &= ~lane; + } + } -const LuminosityHighPassShader = { - shaderID: 'luminosityHighPass', - uniforms: { - tDiffuse: { - value: null - }, - luminosityThreshold: { - value: 1.0 - }, - smoothWidth: { - value: 1.0 - }, - defaultColor: { - value: new Color(0x000000) - }, - defaultOpacity: { - value: 0.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform vec3 defaultColor;', 'uniform float defaultOpacity;', 'uniform float luminosityThreshold;', 'uniform float smoothWidth;', 'varying vec2 vUv;', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' vec3 luma = vec3( 0.299, 0.587, 0.114 );', ' float v = dot( texel.xyz, luma );', ' vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );', ' float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );', ' gl_FragColor = mix( outputColor, texel, alpha );', '}'].join('\n') -}; + return nextLanes; + } + function getMostRecentEventTime(root, lanes) { + var eventTimes = root.eventTimes; + var mostRecentEventTime = NoTimestamp; -/** - * UnrealBloomPass is inspired by the bloom pass of Unreal Engine. It creates a - * mip map chain of bloom textures and blurs them with different radii. Because - * of the weighted combination of mips, and because larger blurs are done on - * higher mips, this effect provides good quality and performance. - * - * Reference: - * - https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/ - */ + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + var eventTime = eventTimes[index]; -var UnrealBloomPass = function (resolution, strength, radius, threshold) { - this.strength = strength !== undefined ? strength : 1; - this.radius = radius; - this.threshold = threshold; - this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); // create color only once here, reuse it later inside the render function + if (eventTime > mostRecentEventTime) { + mostRecentEventTime = eventTime; + } - this.clearColor = new Color(0, 0, 0); // render targets + lanes &= ~lane; + } - var pars = { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }; - this.renderTargetsHorizontal = []; - this.renderTargetsVertical = []; - this.nMips = 5; - var resx = Math.round(this.resolution.x / 2); - var resy = Math.round(this.resolution.y / 2); - this.renderTargetBright = new WebGLRenderTarget(resx, resy, pars); - this.renderTargetBright.texture.name = 'UnrealBloomPass.bright'; - this.renderTargetBright.texture.generateMipmaps = false; - - for (let i = 0; i < this.nMips; i++) { - var renderTargetHorizonal = new WebGLRenderTarget(resx, resy, pars); - renderTargetHorizonal.texture.name = 'UnrealBloomPass.h' + i; - renderTargetHorizonal.texture.generateMipmaps = false; - this.renderTargetsHorizontal.push(renderTargetHorizonal); - var renderTargetVertical = new WebGLRenderTarget(resx, resy, pars); - renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i; - renderTargetVertical.texture.generateMipmaps = false; - this.renderTargetsVertical.push(renderTargetVertical); - resx = Math.round(resx / 2); - resy = Math.round(resy / 2); - } // luminosity high pass material - - - if (LuminosityHighPassShader === undefined) console.error('THREE.UnrealBloomPass relies on LuminosityHighPassShader'); - var highPassShader = LuminosityHighPassShader; - this.highPassUniforms = UniformsUtils.clone(highPassShader.uniforms); - this.highPassUniforms['luminosityThreshold'].value = threshold; - this.highPassUniforms['smoothWidth'].value = 0.01; - this.materialHighPassFilter = new ShaderMaterial({ - uniforms: this.highPassUniforms, - vertexShader: highPassShader.vertexShader, - fragmentShader: highPassShader.fragmentShader, - defines: {} - }); // Gaussian Blur Materials - - this.separableBlurMaterials = []; - var kernelSizeArray = [3, 5, 7, 9, 11]; - var resx = Math.round(this.resolution.x / 2); - var resy = Math.round(this.resolution.y / 2); - - for (let i = 0; i < this.nMips; i++) { - this.separableBlurMaterials.push(this.getSeperableBlurMaterial(kernelSizeArray[i])); - this.separableBlurMaterials[i].uniforms['texSize'].value = new Vector2(resx, resy); - resx = Math.round(resx / 2); - resy = Math.round(resy / 2); - } // Composite material - - - this.compositeMaterial = this.getCompositeMaterial(this.nMips); - this.compositeMaterial.uniforms['blurTexture1'].value = this.renderTargetsVertical[0].texture; - this.compositeMaterial.uniforms['blurTexture2'].value = this.renderTargetsVertical[1].texture; - this.compositeMaterial.uniforms['blurTexture3'].value = this.renderTargetsVertical[2].texture; - this.compositeMaterial.uniforms['blurTexture4'].value = this.renderTargetsVertical[3].texture; - this.compositeMaterial.uniforms['blurTexture5'].value = this.renderTargetsVertical[4].texture; - this.compositeMaterial.uniforms['bloomStrength'].value = strength; - this.compositeMaterial.uniforms['bloomRadius'].value = 0.1; - this.compositeMaterial.needsUpdate = true; - var bloomFactors = [1.0, 0.8, 0.6, 0.4, 0.2]; - this.compositeMaterial.uniforms['bloomFactors'].value = bloomFactors; - this.bloomTintColors = [new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1)]; - this.compositeMaterial.uniforms['bloomTintColors'].value = this.bloomTintColors; // copy material - - if (CopyShader === undefined) { - console.error('THREE.UnrealBloomPass relies on CopyShader'); - } - - var copyShader = CopyShader; - this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); - this.copyUniforms['opacity'].value = 1.0; - this.materialCopy = new ShaderMaterial({ - uniforms: this.copyUniforms, - vertexShader: copyShader.vertexShader, - fragmentShader: copyShader.fragmentShader, - blending: AdditiveBlending, - depthTest: false, - depthWrite: false, - transparent: true - }); - this.enabled = true; - this.needsSwap = false; - this._oldClearColor = new Color(); - this.oldClearAlpha = 1; - this.basic = new MeshBasicMaterial(); - this.fsQuad = new FullScreenQuad(null); -}; + return mostRecentEventTime; + } -UnrealBloomPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: UnrealBloomPass, - dispose: function () { - for (let i = 0; i < this.renderTargetsHorizontal.length; i++) { - this.renderTargetsHorizontal[i].dispose(); - } + function computeExpirationTime(lane, currentTime) { + switch (lane) { + case SyncLane: + case InputContinuousHydrationLane: + case InputContinuousLane: + // User interactions should expire slightly more quickly. + // + // NOTE: This is set to the corresponding constant as in Scheduler.js. + // When we made it larger, a product metric in www regressed, suggesting + // there's a user interaction that's being starved by a series of + // synchronous updates. If that theory is correct, the proper solution is + // to fix the starvation. However, this scenario supports the idea that + // expiration times are an important safeguard when starvation + // does happen. + return currentTime + 250; - for (let i = 0; i < this.renderTargetsVertical.length; i++) { - this.renderTargetsVertical[i].dispose(); - } + case DefaultHydrationLane: + case DefaultLane: + case TransitionHydrationLane: + case TransitionLane1: + case TransitionLane2: + case TransitionLane3: + case TransitionLane4: + case TransitionLane5: + case TransitionLane6: + case TransitionLane7: + case TransitionLane8: + case TransitionLane9: + case TransitionLane10: + case TransitionLane11: + case TransitionLane12: + case TransitionLane13: + case TransitionLane14: + case TransitionLane15: + case TransitionLane16: + return currentTime + 5000; - this.renderTargetBright.dispose(); - }, - setSize: function (width, height) { - var resx = Math.round(width / 2); - var resy = Math.round(height / 2); - this.renderTargetBright.setSize(resx, resy); - - for (let i = 0; i < this.nMips; i++) { - this.renderTargetsHorizontal[i].setSize(resx, resy); - this.renderTargetsVertical[i].setSize(resx, resy); - this.separableBlurMaterials[i].uniforms['texSize'].value = new Vector2(resx, resy); - resx = Math.round(resx / 2); - resy = Math.round(resy / 2); - } - }, - render: function (renderer, writeBuffer, readBuffer, deltaTime, maskActive) { - renderer.getClearColor(this._oldClearColor); - this.oldClearAlpha = renderer.getClearAlpha(); - var oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - renderer.setClearColor(this.clearColor, 0); - if (maskActive) renderer.state.buffers.stencil.setTest(false); // Render input to screen + case RetryLane1: + case RetryLane2: + case RetryLane3: + case RetryLane4: + case RetryLane5: + // TODO: Retries should be allowed to expire if they are CPU bound for + // too long, but when I made this change it caused a spike in browser + // crashes. There must be some other underlying bug; not super urgent but + // ideally should figure out why and fix it. Unfortunately we don't have + // a repro for the crashes, only detected via production metrics. + return NoTimestamp; - if (this.renderToScreen) { - this.fsQuad.material = this.basic; - this.basic.map = readBuffer.texture; - renderer.setRenderTarget(null); - renderer.clear(); - this.fsQuad.render(renderer); - } // 1. Extract Bright Areas - - - this.highPassUniforms['tDiffuse'].value = readBuffer.texture; - this.highPassUniforms['luminosityThreshold'].value = this.threshold; - this.fsQuad.material = this.materialHighPassFilter; - renderer.setRenderTarget(this.renderTargetBright); - renderer.clear(); - this.fsQuad.render(renderer); // 2. Blur All the mips progressively - - var inputRenderTarget = this.renderTargetBright; - - for (let i = 0; i < this.nMips; i++) { - this.fsQuad.material = this.separableBlurMaterials[i]; - this.separableBlurMaterials[i].uniforms['colorTexture'].value = inputRenderTarget.texture; - this.separableBlurMaterials[i].uniforms['direction'].value = UnrealBloomPass.BlurDirectionX; - renderer.setRenderTarget(this.renderTargetsHorizontal[i]); - renderer.clear(); - this.fsQuad.render(renderer); - this.separableBlurMaterials[i].uniforms['colorTexture'].value = this.renderTargetsHorizontal[i].texture; - this.separableBlurMaterials[i].uniforms['direction'].value = UnrealBloomPass.BlurDirectionY; - renderer.setRenderTarget(this.renderTargetsVertical[i]); - renderer.clear(); - this.fsQuad.render(renderer); - inputRenderTarget = this.renderTargetsVertical[i]; - } // Composite All the mips - - - this.fsQuad.material = this.compositeMaterial; - this.compositeMaterial.uniforms['bloomStrength'].value = this.strength; - this.compositeMaterial.uniforms['bloomRadius'].value = this.radius; - this.compositeMaterial.uniforms['bloomTintColors'].value = this.bloomTintColors; - renderer.setRenderTarget(this.renderTargetsHorizontal[0]); - renderer.clear(); - this.fsQuad.render(renderer); // Blend it additively over the input texture - - this.fsQuad.material = this.materialCopy; - this.copyUniforms['tDiffuse'].value = this.renderTargetsHorizontal[0].texture; - if (maskActive) renderer.state.buffers.stencil.setTest(true); + case SelectiveHydrationLane: + case IdleHydrationLane: + case IdleLane: + case OffscreenLane: + // Anything idle priority or lower should never expire. + return NoTimestamp; - if (this.renderToScreen) { - renderer.setRenderTarget(null); - this.fsQuad.render(renderer); - } else { - renderer.setRenderTarget(readBuffer); - this.fsQuad.render(renderer); - } // Restore renderer settings + default: + { + error('Should have found matching lanes. This is a bug in React.'); + } + return NoTimestamp; + } + } - renderer.setClearColor(this._oldClearColor, this.oldClearAlpha); - renderer.autoClear = oldAutoClear; - }, - getSeperableBlurMaterial: function (kernelRadius) { - return new ShaderMaterial({ - defines: { - KERNEL_RADIUS: kernelRadius, - SIGMA: kernelRadius - }, - uniforms: { - colorTexture: { - value: null - }, - texSize: { - value: new Vector2(0.5, 0.5) - }, - direction: { - value: new Vector2(0.5, 0.5) - } - }, - vertexShader: 'varying vec2 vUv;\n\ - void main() {\n\ - vUv = uv;\n\ - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\ - }', - fragmentShader: '#include \ - varying vec2 vUv;\n\ - uniform sampler2D colorTexture;\n\ - uniform vec2 texSize;\ - uniform vec2 direction;\ - \ - float gaussianPdf(in float x, in float sigma) {\ - return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\ - }\ - void main() {\n\ - vec2 invSize = 1.0 / texSize;\ - float fSigma = float(SIGMA);\ - float weightSum = gaussianPdf(0.0, fSigma);\ - vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\ - for( int i = 1; i < KERNEL_RADIUS; i ++ ) {\ - float x = float(i);\ - float w = gaussianPdf(x, fSigma);\ - vec2 uvOffset = direction * invSize * x;\ - vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\ - vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\ - diffuseSum += (sample1 + sample2) * w;\ - weightSum += 2.0 * w;\ - }\ - gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\n\ - }' - }); - }, - getCompositeMaterial: function (nMips) { - return new ShaderMaterial({ - defines: { - NUM_MIPS: nMips - }, - uniforms: { - blurTexture1: { - value: null - }, - blurTexture2: { - value: null - }, - blurTexture3: { - value: null - }, - blurTexture4: { - value: null - }, - blurTexture5: { - value: null - }, - dirtTexture: { - value: null - }, - bloomStrength: { - value: 1.0 - }, - bloomFactors: { - value: null - }, - bloomTintColors: { - value: null - }, - bloomRadius: { - value: 0.0 - } - }, - vertexShader: 'varying vec2 vUv;\n\ - void main() {\n\ - vUv = uv;\n\ - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\ - }', - fragmentShader: 'varying vec2 vUv;\ - uniform sampler2D blurTexture1;\ - uniform sampler2D blurTexture2;\ - uniform sampler2D blurTexture3;\ - uniform sampler2D blurTexture4;\ - uniform sampler2D blurTexture5;\ - uniform sampler2D dirtTexture;\ - uniform float bloomStrength;\ - uniform float bloomRadius;\ - uniform float bloomFactors[NUM_MIPS];\ - uniform vec3 bloomTintColors[NUM_MIPS];\ - \ - float lerpBloomFactor(const in float factor) { \ - float mirrorFactor = 1.2 - factor;\ - return mix(factor, mirrorFactor, bloomRadius);\ - }\ - \ - void main() {\ - gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + \ - lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + \ - lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + \ - lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + \ - lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );\ - }' - }); - } -}); -UnrealBloomPass.BlurDirectionX = new Vector2(1.0, 0.0); -UnrealBloomPass.BlurDirectionY = new Vector2(0.0, 1.0); - -var CubeTexturePass = function (camera, envMap, opacity) { - this.camera = camera; - this.needsSwap = false; - this.cubeShader = ShaderLib['cube']; - this.cubeMesh = new Mesh(new BoxGeometry(10, 10, 10), new ShaderMaterial({ - uniforms: UniformsUtils.clone(this.cubeShader.uniforms), - vertexShader: this.cubeShader.vertexShader, - fragmentShader: this.cubeShader.fragmentShader, - depthTest: false, - depthWrite: false, - side: BackSide - })); - Object.defineProperty(this.cubeMesh.material, 'envMap', { - get: function () { - return this.uniforms.envMap.value; - } - }); - this.envMap = envMap; - this.opacity = opacity !== undefined ? opacity : 1.0; - this.cubeScene = new Scene$1(); - this.cubeCamera = new PerspectiveCamera(); - this.cubeScene.add(this.cubeMesh); -}; + function markStarvedLanesAsExpired(root, currentTime) { + // TODO: This gets called every time we yield. We can optimize by storing + // the earliest expiration time on the root. Then use that to quickly bail out + // of this function. + var pendingLanes = root.pendingLanes; + var suspendedLanes = root.suspendedLanes; + var pingedLanes = root.pingedLanes; + var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their + // expiration time. If so, we'll assume the update is being starved and mark + // it as expired to force it to finish. -CubeTexturePass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: CubeTexturePass, - render: function (renderer, writeBuffer, readBuffer - /*, deltaTime, maskActive*/ - ) { - var oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - this.cubeCamera.projectionMatrix.copy(this.camera.projectionMatrix); - this.cubeCamera.quaternion.setFromRotationMatrix(this.camera.matrixWorld); - this.cubeMesh.material.uniforms.envMap.value = this.envMap; - this.cubeMesh.material.uniforms.flipEnvMap.value = this.envMap.isCubeTexture && this.envMap._needsFlipEnvMap ? -1 : 1; - this.cubeMesh.material.uniforms.opacity.value = this.opacity; - this.cubeMesh.material.transparent = this.opacity < 1.0; - renderer.setRenderTarget(this.renderToScreen ? null : readBuffer); - if (this.clear) renderer.clear(); - renderer.render(this.cubeScene, this.cubeCamera); - renderer.autoClear = oldAutoClear; - } -}); + var lanes = pendingLanes; -const SAOShader = { - defines: { - NUM_SAMPLES: 7, - NUM_RINGS: 4, - NORMAL_TEXTURE: 0, - DIFFUSE_TEXTURE: 0, - DEPTH_PACKING: 1, - PERSPECTIVE_CAMERA: 1 - }, - uniforms: { - tDepth: { - value: null - }, - tDiffuse: { - value: null - }, - tNormal: { - value: null - }, - size: { - value: new Vector2(512, 512) - }, - cameraNear: { - value: 1 - }, - cameraFar: { - value: 100 - }, - cameraProjectionMatrix: { - value: new Matrix4() - }, - cameraInverseProjectionMatrix: { - value: new Matrix4() - }, - scale: { - value: 1.0 - }, - intensity: { - value: 0.1 - }, - bias: { - value: 0.5 - }, - minResolution: { - value: 0.0 - }, - kernelRadius: { - value: 100.0 - }, - randomSeed: { - value: 0.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', 'varying vec2 vUv;', '#if DIFFUSE_TEXTURE == 1', 'uniform sampler2D tDiffuse;', '#endif', 'uniform sampler2D tDepth;', '#if NORMAL_TEXTURE == 1', 'uniform sampler2D tNormal;', '#endif', 'uniform float cameraNear;', 'uniform float cameraFar;', 'uniform mat4 cameraProjectionMatrix;', 'uniform mat4 cameraInverseProjectionMatrix;', 'uniform float scale;', 'uniform float intensity;', 'uniform float bias;', 'uniform float kernelRadius;', 'uniform float minResolution;', 'uniform vec2 size;', 'uniform float randomSeed;', '// RGBA depth', '#include ', 'vec4 getDefaultColor( const in vec2 screenPosition ) {', ' #if DIFFUSE_TEXTURE == 1', ' return texture2D( tDiffuse, vUv );', ' #else', ' return vec4( 1.0 );', ' #endif', '}', 'float getDepth( const in vec2 screenPosition ) {', ' #if DEPTH_PACKING == 1', ' return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );', ' #else', ' return texture2D( tDepth, screenPosition ).x;', ' #endif', '}', 'float getViewZ( const in float depth ) {', ' #if PERSPECTIVE_CAMERA == 1', ' return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );', ' #else', ' return orthographicDepthToViewZ( depth, cameraNear, cameraFar );', ' #endif', '}', 'vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {', ' float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];', ' vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );', ' clipPosition *= clipW; // unprojection.', ' return ( cameraInverseProjectionMatrix * clipPosition ).xyz;', '}', 'vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) {', ' #if NORMAL_TEXTURE == 1', ' return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );', ' #else', ' return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );', ' #endif', '}', 'float scaleDividedByCameraFar;', 'float minResolutionMultipliedByCameraFar;', 'float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {', ' vec3 viewDelta = sampleViewPosition - centerViewPosition;', ' float viewDistance = length( viewDelta );', ' float scaledScreenDistance = scaleDividedByCameraFar * viewDistance;', ' return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) );', '}', '// moving costly divides into consts', 'const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );', 'const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );', 'float getAmbientOcclusion( const in vec3 centerViewPosition ) {', ' // precompute some variables require in getOcclusion.', ' scaleDividedByCameraFar = scale / cameraFar;', ' minResolutionMultipliedByCameraFar = minResolution * cameraFar;', ' vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv );', ' // jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/', ' float angle = rand( vUv + randomSeed ) * PI2;', ' vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size;', ' vec2 radiusStep = radius;', ' float occlusionSum = 0.0;', ' float weightSum = 0.0;', ' for( int i = 0; i < NUM_SAMPLES; i ++ ) {', ' vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius;', ' radius += radiusStep;', ' angle += ANGLE_STEP;', ' float sampleDepth = getDepth( sampleUv );', ' if( sampleDepth >= ( 1.0 - EPSILON ) ) {', ' continue;', ' }', ' float sampleViewZ = getViewZ( sampleDepth );', ' vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ );', ' occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );', ' weightSum += 1.0;', ' }', ' if( weightSum == 0.0 ) discard;', ' return occlusionSum * ( intensity / weightSum );', '}', 'void main() {', ' float centerDepth = getDepth( vUv );', ' if( centerDepth >= ( 1.0 - EPSILON ) ) {', ' discard;', ' }', ' float centerViewZ = getViewZ( centerDepth );', ' vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ );', ' float ambientOcclusion = getAmbientOcclusion( viewPosition );', ' gl_FragColor = getDefaultColor( vUv );', ' gl_FragColor.xyz *= 1.0 - ambientOcclusion;', '}'].join('\n') -}; + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + var expirationTime = expirationTimes[index]; -const DepthLimitedBlurShader = { - defines: { - KERNEL_RADIUS: 4, - DEPTH_PACKING: 1, - PERSPECTIVE_CAMERA: 1 - }, - uniforms: { - tDiffuse: { - value: null - }, - size: { - value: new Vector2(512, 512) - }, - sampleUvOffsets: { - value: [new Vector2(0, 0)] - }, - sampleWeights: { - value: [1.0] - }, - tDepth: { - value: null - }, - cameraNear: { - value: 10 - }, - cameraFar: { - value: 1000 - }, - depthCutoff: { - value: 10 - } - }, - vertexShader: ['#include ', 'uniform vec2 size;', 'varying vec2 vUv;', 'varying vec2 vInvSize;', 'void main() {', ' vUv = uv;', ' vInvSize = 1.0 / size;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', '#include ', 'uniform sampler2D tDiffuse;', 'uniform sampler2D tDepth;', 'uniform float cameraNear;', 'uniform float cameraFar;', 'uniform float depthCutoff;', 'uniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ];', 'uniform float sampleWeights[ KERNEL_RADIUS + 1 ];', 'varying vec2 vUv;', 'varying vec2 vInvSize;', 'float getDepth( const in vec2 screenPosition ) {', ' #if DEPTH_PACKING == 1', ' return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );', ' #else', ' return texture2D( tDepth, screenPosition ).x;', ' #endif', '}', 'float getViewZ( const in float depth ) {', ' #if PERSPECTIVE_CAMERA == 1', ' return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );', ' #else', ' return orthographicDepthToViewZ( depth, cameraNear, cameraFar );', ' #endif', '}', 'void main() {', ' float depth = getDepth( vUv );', ' if( depth >= ( 1.0 - EPSILON ) ) {', ' discard;', ' }', ' float centerViewZ = -getViewZ( depth );', ' bool rBreak = false, lBreak = false;', ' float weightSum = sampleWeights[0];', ' vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum;', ' for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {', ' float sampleWeight = sampleWeights[i];', ' vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize;', ' vec2 sampleUv = vUv + sampleUvOffset;', ' float viewZ = -getViewZ( getDepth( sampleUv ) );', ' if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true;', ' if( ! rBreak ) {', ' diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;', ' weightSum += sampleWeight;', ' }', ' sampleUv = vUv - sampleUvOffset;', ' viewZ = -getViewZ( getDepth( sampleUv ) );', ' if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true;', ' if( ! lBreak ) {', ' diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;', ' weightSum += sampleWeight;', ' }', ' }', ' gl_FragColor = diffuseSum / weightSum;', '}'].join('\n') -}; -const BlurShaderUtils = { - createSampleWeights: (kernelRadius, stdDev) => { - const gaussian = (x, stdDev) => { - return Math.exp(-(x * x) / (2.0 * (stdDev * stdDev))) / (Math.sqrt(2.0 * Math.PI) * stdDev); - }; + if (expirationTime === NoTimestamp) { + // Found a pending lane with no expiration time. If it's not suspended, or + // if it's pinged, assume it's CPU-bound. Compute a new expiration time + // using the current time. + if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) { + // Assumes timestamps are monotonically increasing. + expirationTimes[index] = computeExpirationTime(lane, currentTime); + } + } else if (expirationTime <= currentTime) { + // This lane expired + root.expiredLanes |= lane; + } - const weights = []; + lanes &= ~lane; + } + } // This returns the highest priority pending lanes regardless of whether they + // are suspended. - for (let i = 0; i <= kernelRadius; i++) { - weights.push(gaussian(i, stdDev)); - } + function getHighestPriorityPendingLanes(root) { + return getHighestPriorityLanes(root.pendingLanes); + } + function getLanesToRetrySynchronouslyOnError(root) { + var everythingButOffscreen = root.pendingLanes & ~OffscreenLane; - return weights; - }, - createSampleOffsets: (kernelRadius, uvIncrement) => { - const offsets = []; + if (everythingButOffscreen !== NoLanes) { + return everythingButOffscreen; + } - for (let i = 0; i <= kernelRadius; i++) { - offsets.push(uvIncrement.clone().multiplyScalar(i)); - } + if (everythingButOffscreen & OffscreenLane) { + return OffscreenLane; + } - return offsets; - }, - configure: (shader, kernelRadius, stdDev, uvIncrement) => { - shader.defines['KERNEL_RADIUS'] = kernelRadius; - shader.uniforms['sampleUvOffsets'].value = BlurShaderUtils.createSampleOffsets(kernelRadius, uvIncrement); - shader.uniforms['sampleWeights'].value = BlurShaderUtils.createSampleWeights(kernelRadius, stdDev); - shader.needsUpdate = true; - } -}; + return NoLanes; + } + function includesSyncLane(lanes) { + return (lanes & SyncLane) !== NoLanes; + } + function includesNonIdleWork(lanes) { + return (lanes & NonIdleLanes) !== NoLanes; + } + function includesOnlyRetries(lanes) { + return (lanes & RetryLanes) === lanes; + } + function includesOnlyTransitions(lanes) { + return (lanes & TransitionLanes) === lanes; + } + function includesBlockingLane(root, lanes) { -/** - * SAO implementation inspired from bhouston previous SAO work - */ + var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane; + return (lanes & SyncDefaultLanes) !== NoLanes; + } + function includesExpiredLane(root, lanes) { + // This is a separate check from includesBlockingLane because a lane can + // expire after a render has already started. + return (lanes & root.expiredLanes) !== NoLanes; + } + function isTransitionLane(lane) { + return (lane & TransitionLanes) !== 0; + } + function claimNextTransitionLane() { + // Cycle through the lanes, assigning each new transition to the next lane. + // In most cases, this means every transition gets its own lane, until we + // run out of lanes and cycle back to the beginning. + var lane = nextTransitionLane; + nextTransitionLane <<= 1; -var SAOPass = function (scene, camera, depthTexture, useNormals, resolution) { - this.scene = scene; - this.camera = camera; - this.clear = true; - this.needsSwap = false; - this.supportsDepthTextureExtension = depthTexture !== undefined ? depthTexture : false; - this.supportsNormalTexture = useNormals !== undefined ? useNormals : false; - this.originalClearColor = new Color(); - this._oldClearColor = new Color(); - this.oldClearAlpha = 1; - this.params = { - output: 0, - saoBias: 0.5, - saoIntensity: 0.18, - saoScale: 1, - saoKernelRadius: 100, - saoMinResolution: 0, - saoBlur: true, - saoBlurRadius: 8, - saoBlurStdDev: 4, - saoBlurDepthCutoff: 0.01 - }; - this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); - this.saoRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }); - this.blurIntermediateRenderTarget = this.saoRenderTarget.clone(); - this.beautyRenderTarget = this.saoRenderTarget.clone(); - this.normalRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { - minFilter: NearestFilter, - magFilter: NearestFilter, - format: RGBAFormat - }); - this.depthRenderTarget = this.normalRenderTarget.clone(); + if ((nextTransitionLane & TransitionLanes) === 0) { + nextTransitionLane = TransitionLane1; + } - if (this.supportsDepthTextureExtension) { - var depthTexture = new DepthTexture(); - depthTexture.type = UnsignedShortType; - this.beautyRenderTarget.depthTexture = depthTexture; - this.beautyRenderTarget.depthBuffer = true; - } + return lane; + } + function claimNextRetryLane() { + var lane = nextRetryLane; + nextRetryLane <<= 1; - this.depthMaterial = new MeshDepthMaterial(); - this.depthMaterial.depthPacking = RGBADepthPacking; - this.depthMaterial.blending = NoBlending; - this.normalMaterial = new MeshNormalMaterial(); - this.normalMaterial.blending = NoBlending; + if ((nextRetryLane & RetryLanes) === 0) { + nextRetryLane = RetryLane1; + } - if (SAOShader === undefined) { - console.error('THREE.SAOPass relies on SAOShader'); - } + return lane; + } + function getHighestPriorityLane(lanes) { + return lanes & -lanes; + } + function pickArbitraryLane(lanes) { + // This wrapper function gets inlined. Only exists so to communicate that it + // doesn't matter which bit is selected; you can pick any bit without + // affecting the algorithms where its used. Here I'm using + // getHighestPriorityLane because it requires the fewest operations. + return getHighestPriorityLane(lanes); + } - this.saoMaterial = new ShaderMaterial({ - defines: Object.assign({}, SAOShader.defines), - fragmentShader: SAOShader.fragmentShader, - vertexShader: SAOShader.vertexShader, - uniforms: UniformsUtils.clone(SAOShader.uniforms) - }); - this.saoMaterial.extensions.derivatives = true; - this.saoMaterial.defines['DEPTH_PACKING'] = this.supportsDepthTextureExtension ? 0 : 1; - this.saoMaterial.defines['NORMAL_TEXTURE'] = this.supportsNormalTexture ? 1 : 0; - this.saoMaterial.defines['PERSPECTIVE_CAMERA'] = this.camera.isPerspectiveCamera ? 1 : 0; - this.saoMaterial.uniforms['tDepth'].value = this.supportsDepthTextureExtension ? depthTexture : this.depthRenderTarget.texture; - this.saoMaterial.uniforms['tNormal'].value = this.normalRenderTarget.texture; - this.saoMaterial.uniforms['size'].value.set(this.resolution.x, this.resolution.y); - this.saoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - this.saoMaterial.uniforms['cameraProjectionMatrix'].value = this.camera.projectionMatrix; - this.saoMaterial.blending = NoBlending; - - if (DepthLimitedBlurShader === undefined) { - console.error('THREE.SAOPass relies on DepthLimitedBlurShader'); - } - - this.vBlurMaterial = new ShaderMaterial({ - uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), - defines: Object.assign({}, DepthLimitedBlurShader.defines), - vertexShader: DepthLimitedBlurShader.vertexShader, - fragmentShader: DepthLimitedBlurShader.fragmentShader - }); - this.vBlurMaterial.defines['DEPTH_PACKING'] = this.supportsDepthTextureExtension ? 0 : 1; - this.vBlurMaterial.defines['PERSPECTIVE_CAMERA'] = this.camera.isPerspectiveCamera ? 1 : 0; - this.vBlurMaterial.uniforms['tDiffuse'].value = this.saoRenderTarget.texture; - this.vBlurMaterial.uniforms['tDepth'].value = this.supportsDepthTextureExtension ? depthTexture : this.depthRenderTarget.texture; - this.vBlurMaterial.uniforms['size'].value.set(this.resolution.x, this.resolution.y); - this.vBlurMaterial.blending = NoBlending; - this.hBlurMaterial = new ShaderMaterial({ - uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), - defines: Object.assign({}, DepthLimitedBlurShader.defines), - vertexShader: DepthLimitedBlurShader.vertexShader, - fragmentShader: DepthLimitedBlurShader.fragmentShader - }); - this.hBlurMaterial.defines['DEPTH_PACKING'] = this.supportsDepthTextureExtension ? 0 : 1; - this.hBlurMaterial.defines['PERSPECTIVE_CAMERA'] = this.camera.isPerspectiveCamera ? 1 : 0; - this.hBlurMaterial.uniforms['tDiffuse'].value = this.blurIntermediateRenderTarget.texture; - this.hBlurMaterial.uniforms['tDepth'].value = this.supportsDepthTextureExtension ? depthTexture : this.depthRenderTarget.texture; - this.hBlurMaterial.uniforms['size'].value.set(this.resolution.x, this.resolution.y); - this.hBlurMaterial.blending = NoBlending; - - if (CopyShader === undefined) { - console.error('THREE.SAOPass relies on CopyShader'); - } - - this.materialCopy = new ShaderMaterial({ - uniforms: UniformsUtils.clone(CopyShader.uniforms), - vertexShader: CopyShader.vertexShader, - fragmentShader: CopyShader.fragmentShader, - blending: NoBlending - }); - this.materialCopy.transparent = true; - this.materialCopy.depthTest = false; - this.materialCopy.depthWrite = false; - this.materialCopy.blending = CustomBlending; - this.materialCopy.blendSrc = DstColorFactor; - this.materialCopy.blendDst = ZeroFactor; - this.materialCopy.blendEquation = AddEquation; - this.materialCopy.blendSrcAlpha = DstAlphaFactor; - this.materialCopy.blendDstAlpha = ZeroFactor; - this.materialCopy.blendEquationAlpha = AddEquation; - - if (UnpackDepthRGBAShader === undefined) { - console.error('THREE.SAOPass relies on UnpackDepthRGBAShader'); - } - - this.depthCopy = new ShaderMaterial({ - uniforms: UniformsUtils.clone(UnpackDepthRGBAShader.uniforms), - vertexShader: UnpackDepthRGBAShader.vertexShader, - fragmentShader: UnpackDepthRGBAShader.fragmentShader, - blending: NoBlending - }); - this.fsQuad = new FullScreenQuad(null); -}; + function pickArbitraryLaneIndex(lanes) { + return 31 - clz32(lanes); + } -SAOPass.OUTPUT = { - Beauty: 1, - Default: 0, - SAO: 2, - Depth: 3, - Normal: 4 -}; -SAOPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: SAOPass, - render: function (renderer, writeBuffer, readBuffer - /*, deltaTime, maskActive*/ - ) { - // Rendering readBuffer first when rendering to screen - if (this.renderToScreen) { - this.materialCopy.blending = NoBlending; - this.materialCopy.uniforms['tDiffuse'].value = readBuffer.texture; - this.materialCopy.needsUpdate = true; - this.renderPass(renderer, this.materialCopy, null); - } + function laneToIndex(lane) { + return pickArbitraryLaneIndex(lane); + } - if (this.params.output === 1) { - return; - } + function includesSomeLane(a, b) { + return (a & b) !== NoLanes; + } + function isSubsetOfLanes(set, subset) { + return (set & subset) === subset; + } + function mergeLanes(a, b) { + return a | b; + } + function removeLanes(set, subset) { + return set & ~subset; + } + function intersectLanes(a, b) { + return a & b; + } // Seems redundant, but it changes the type from a single lane (used for + // updates) to a group of lanes (used for flushing work). - renderer.getClearColor(this._oldClearColor); - this.oldClearAlpha = renderer.getClearAlpha(); - var oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - renderer.setRenderTarget(this.depthRenderTarget); - renderer.clear(); - this.saoMaterial.uniforms['bias'].value = this.params.saoBias; - this.saoMaterial.uniforms['intensity'].value = this.params.saoIntensity; - this.saoMaterial.uniforms['scale'].value = this.params.saoScale; - this.saoMaterial.uniforms['kernelRadius'].value = this.params.saoKernelRadius; - this.saoMaterial.uniforms['minResolution'].value = this.params.saoMinResolution; - this.saoMaterial.uniforms['cameraNear'].value = this.camera.near; - this.saoMaterial.uniforms['cameraFar'].value = this.camera.far; // this.saoMaterial.uniforms['randomSeed'].value = Math.random(); - - var depthCutoff = this.params.saoBlurDepthCutoff * (this.camera.far - this.camera.near); - this.vBlurMaterial.uniforms['depthCutoff'].value = depthCutoff; - this.hBlurMaterial.uniforms['depthCutoff'].value = depthCutoff; - this.vBlurMaterial.uniforms['cameraNear'].value = this.camera.near; - this.vBlurMaterial.uniforms['cameraFar'].value = this.camera.far; - this.hBlurMaterial.uniforms['cameraNear'].value = this.camera.near; - this.hBlurMaterial.uniforms['cameraFar'].value = this.camera.far; - this.params.saoBlurRadius = Math.floor(this.params.saoBlurRadius); - - if (this.prevStdDev !== this.params.saoBlurStdDev || this.prevNumSamples !== this.params.saoBlurRadius) { - BlurShaderUtils.configure(this.vBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(0, 1)); - BlurShaderUtils.configure(this.hBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(1, 0)); - this.prevStdDev = this.params.saoBlurStdDev; - this.prevNumSamples = this.params.saoBlurRadius; - } // Rendering scene to depth texture - - - renderer.setClearColor(0x000000); - renderer.setRenderTarget(this.beautyRenderTarget); - renderer.clear(); - renderer.render(this.scene, this.camera); // Re-render scene if depth texture extension is not supported - - if (!this.supportsDepthTextureExtension) { - // Clear rule : far clipping plane in both RGBA and Basic encoding - this.renderOverride(renderer, this.depthMaterial, this.depthRenderTarget, 0x000000, 1.0); - } + function laneToLanes(lane) { + return lane; + } + function higherPriorityLane(a, b) { + // This works because the bit ranges decrease in priority as you go left. + return a !== NoLane && a < b ? a : b; + } + function createLaneMap(initial) { + // Intentionally pushing one by one. + // https://v8.dev/blog/elements-kinds#avoid-creating-holes + var laneMap = []; - if (this.supportsNormalTexture) { - // Clear rule : default normal is facing the camera - this.renderOverride(renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0); - } // Rendering SAO texture + for (var i = 0; i < TotalLanes; i++) { + laneMap.push(initial); + } + return laneMap; + } + function markRootUpdated(root, updateLane, eventTime) { + root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update + // could unblock them. Clear the suspended lanes so that we can try rendering + // them again. + // + // TODO: We really only need to unsuspend only lanes that are in the + // `subtreeLanes` of the updated fiber, or the update lanes of the return + // path. This would exclude suspended updates in an unrelated sibling tree, + // since there's no way for this update to unblock it. + // + // We don't do this if the incoming update is idle, because we never process + // idle updates until after all the regular updates have finished; there's no + // way it could unblock a transition. - this.renderPass(renderer, this.saoMaterial, this.saoRenderTarget, 0xffffff, 1.0); // Blurring SAO texture + if (updateLane !== IdleLane) { + root.suspendedLanes = NoLanes; + root.pingedLanes = NoLanes; + } - if (this.params.saoBlur) { - this.renderPass(renderer, this.vBlurMaterial, this.blurIntermediateRenderTarget, 0xffffff, 1.0); - this.renderPass(renderer, this.hBlurMaterial, this.saoRenderTarget, 0xffffff, 1.0); - } + var eventTimes = root.eventTimes; + var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most + // recent event, and we assume time is monotonically increasing. - var outputMaterial = this.materialCopy; // Setting up SAO rendering + eventTimes[index] = eventTime; + } + function markRootSuspended(root, suspendedLanes) { + root.suspendedLanes |= suspendedLanes; + root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times. - if (this.params.output === 3) { - if (this.supportsDepthTextureExtension) { - this.materialCopy.uniforms['tDiffuse'].value = this.beautyRenderTarget.depthTexture; - this.materialCopy.needsUpdate = true; - } else { - this.depthCopy.uniforms['tDiffuse'].value = this.depthRenderTarget.texture; - this.depthCopy.needsUpdate = true; - outputMaterial = this.depthCopy; - } - } else if (this.params.output === 4) { - this.materialCopy.uniforms['tDiffuse'].value = this.normalRenderTarget.texture; - this.materialCopy.needsUpdate = true; - } else { - this.materialCopy.uniforms['tDiffuse'].value = this.saoRenderTarget.texture; - this.materialCopy.needsUpdate = true; - } // Blending depends on output, only want a CustomBlending when showing SAO + var expirationTimes = root.expirationTimes; + var lanes = suspendedLanes; + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + expirationTimes[index] = NoTimestamp; + lanes &= ~lane; + } + } + function markRootPinged(root, pingedLanes, eventTime) { + root.pingedLanes |= root.suspendedLanes & pingedLanes; + } + function markRootFinished(root, remainingLanes) { + var noLongerPendingLanes = root.pendingLanes & ~remainingLanes; + root.pendingLanes = remainingLanes; // Let's try everything again - if (this.params.output === 0) { - outputMaterial.blending = CustomBlending; - } else { - outputMaterial.blending = NoBlending; - } // Rendering SAOPass result on top of previous pass + root.suspendedLanes = 0; + root.pingedLanes = 0; + root.expiredLanes &= remainingLanes; + root.mutableReadLanes &= remainingLanes; + root.entangledLanes &= remainingLanes; + var entanglements = root.entanglements; + var eventTimes = root.eventTimes; + var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work + var lanes = noLongerPendingLanes; - this.renderPass(renderer, outputMaterial, this.renderToScreen ? null : readBuffer); - renderer.setClearColor(this._oldClearColor, this.oldClearAlpha); - renderer.autoClear = oldAutoClear; - }, - renderPass: function (renderer, passMaterial, renderTarget, clearColor, clearAlpha) { - // save original state - renderer.getClearColor(this.originalClearColor); - var originalClearAlpha = renderer.getClearAlpha(); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); // setup pass state - - renderer.autoClear = false; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + while (lanes > 0) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; + entanglements[index] = NoLanes; + eventTimes[index] = NoTimestamp; + expirationTimes[index] = NoTimestamp; + lanes &= ~lane; + } + } + function markRootEntangled(root, entangledLanes) { + // In addition to entangling each of the given lanes with each other, we also + // have to consider _transitive_ entanglements. For each lane that is already + // entangled with *any* of the given lanes, that lane is now transitively + // entangled with *all* the given lanes. + // + // Translated: If C is entangled with A, then entangling A with B also + // entangles C with B. + // + // If this is hard to grasp, it might help to intentionally break this + // function and look at the tests that fail in ReactTransition-test.js. Try + // commenting out one of the conditions below. + var rootEntangledLanes = root.entangledLanes |= entangledLanes; + var entanglements = root.entanglements; + var lanes = rootEntangledLanes; - this.fsQuad.material = passMaterial; - this.fsQuad.render(renderer); // restore original state + while (lanes) { + var index = pickArbitraryLaneIndex(lanes); + var lane = 1 << index; - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - renderOverride: function (renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { - renderer.getClearColor(this.originalClearColor); - var originalClearAlpha = renderer.getClearAlpha(); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); - renderer.autoClear = false; - clearColor = overrideMaterial.clearColor || clearColor; - clearAlpha = overrideMaterial.clearAlpha || clearAlpha; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + if ( // Is this one of the newly entangled lanes? + lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes? + entanglements[index] & entangledLanes) { + entanglements[index] |= entangledLanes; + } - this.scene.overrideMaterial = overrideMaterial; - renderer.render(this.scene, this.camera); - this.scene.overrideMaterial = null; // restore original state + lanes &= ~lane; + } + } + function getBumpedLaneForHydration(root, renderLanes) { + var renderLane = getHighestPriorityLane(renderLanes); + var lane; - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - setSize: function (width, height) { - this.beautyRenderTarget.setSize(width, height); - this.saoRenderTarget.setSize(width, height); - this.blurIntermediateRenderTarget.setSize(width, height); - this.normalRenderTarget.setSize(width, height); - this.depthRenderTarget.setSize(width, height); - this.saoMaterial.uniforms['size'].value.set(width, height); - this.saoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - this.saoMaterial.uniforms['cameraProjectionMatrix'].value = this.camera.projectionMatrix; - this.saoMaterial.needsUpdate = true; - this.vBlurMaterial.uniforms['size'].value.set(width, height); - this.vBlurMaterial.needsUpdate = true; - this.hBlurMaterial.uniforms['size'].value.set(width, height); - this.hBlurMaterial.needsUpdate = true; - } -}); + switch (renderLane) { + case InputContinuousLane: + lane = InputContinuousHydrationLane; + break; -/** - * Dot screen shader - * based on glfx.js sepia shader - * https://github.com/evanw/glfx.js - */ + case DefaultLane: + lane = DefaultHydrationLane; + break; -({ - uniforms: { - tDiffuse: { - value: null - }, - tSize: { - value: new Vector2(256, 256) - }, - center: { - value: new Vector2(0.5, 0.5) - }, - angle: { - value: 1.57 - }, - scale: { - value: 1.0 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform vec2 center;', 'uniform float angle;', 'uniform float scale;', 'uniform vec2 tSize;', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'float pattern() {', ' float s = sin( angle ), c = cos( angle );', ' vec2 tex = vUv * tSize - center;', ' vec2 point = vec2( c * tex.x - s * tex.y, s * tex.x + c * tex.y ) * scale;', ' return ( sin( point.x ) * sin( point.y ) ) * 4.0;', '}', 'void main() {', ' vec4 color = texture2D( tDiffuse, vUv );', ' float average = ( color.r + color.g + color.b ) / 3.0;', ' gl_FragColor = vec4( vec3( average * 10.0 - 5.0 + pattern() ), color.a );', '}'].join('\n') -}); + case TransitionLane1: + case TransitionLane2: + case TransitionLane3: + case TransitionLane4: + case TransitionLane5: + case TransitionLane6: + case TransitionLane7: + case TransitionLane8: + case TransitionLane9: + case TransitionLane10: + case TransitionLane11: + case TransitionLane12: + case TransitionLane13: + case TransitionLane14: + case TransitionLane15: + case TransitionLane16: + case RetryLane1: + case RetryLane2: + case RetryLane3: + case RetryLane4: + case RetryLane5: + lane = TransitionHydrationLane; + break; -/** - * References: - * https://lettier.github.io/3d-game-shaders-for-beginners/screen-space-reflection.html - */ + case IdleLane: + lane = IdleHydrationLane; + break; -const SSRShader = { - defines: { - MAX_STEP: 0, - isPerspectiveCamera: true, - isDistanceAttenuation: true, - isFresnel: true, - isInfiniteThick: false, - isSelective: false - }, - uniforms: { - tDiffuse: { - value: null - }, - tNormal: { - value: null - }, - tMetalness: { - value: null - }, - tDepth: { - value: null - }, - cameraNear: { - value: null - }, - cameraFar: { - value: null - }, - resolution: { - value: new Vector2() - }, - cameraProjectionMatrix: { - value: new Matrix4() - }, - cameraInverseProjectionMatrix: { - value: new Matrix4() - }, - opacity: { - value: 0.5 - }, - maxDistance: { - value: 180 - }, - cameraRange: { - value: 0 - }, - surfDist: { - value: 0.007 - }, - thickTolerance: { - value: 0.03 - } - }, - vertexShader: - /* glsl */ - ` + default: + // Everything else is already either a hydration lane, or shouldn't + // be retried at a hydration lane. + lane = NoLane; + break; + } // Check if the lane we chose is suspended. If so, that indicates that we + // already attempted and failed to hydrate at that level. Also check if we're + // already rendering that lane, which is rare but could happen. - varying vec2 vUv; - void main() { + if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) { + // Give up trying to hydrate and fall back to client render. + return NoLane; + } + + return lane; + } + function addFiberToLanesMap(root, fiber, lanes) { - vUv = uv; + if (!isDevToolsPresent) { + return; + } - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - } + while (lanes > 0) { + var index = laneToIndex(lanes); + var lane = 1 << index; + var updaters = pendingUpdatersLaneMap[index]; + updaters.add(fiber); + lanes &= ~lane; + } + } + function movePendingFibersToMemoized(root, lanes) { - `, - fragmentShader: - /* glsl */ - ` - // precision highp float; - precision highp sampler2D; - varying vec2 vUv; - uniform sampler2D tDepth; - uniform sampler2D tNormal; - uniform sampler2D tMetalness; - uniform sampler2D tDiffuse; - uniform float cameraRange; - uniform vec2 resolution; - uniform float opacity; - uniform float cameraNear; - uniform float cameraFar; - uniform float maxDistance; - uniform float surfDist; - uniform mat4 cameraProjectionMatrix; - uniform mat4 cameraInverseProjectionMatrix; - uniform float thickTolerance; - #include - float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) { - //x0: point, x1: linePointA, x2: linePointB - //https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html - return length(cross(x0-x1,x0-x2))/length(x2-x1); - } - float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){ - // https://mathworld.wolfram.com/Point-PlaneDistance.html - //// https://en.wikipedia.org/wiki/Plane_(geometry) - //// http://paulbourke.net/geometry/pointlineplane/ - float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z; - float x0=point.x,y0=point.y,z0=point.z; - float x=planePoint.x,y=planePoint.y,z=planePoint.z; - float d=-(a*x+b*y+c*z); - float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c); - return distance; - } - float getDepth( const in vec2 uv ) { - return texture2D( tDepth, uv ).x; - } - float getViewZ( const in float depth ) { - #ifdef isPerspectiveCamera - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - #else - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - #endif - } - vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { - vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc - clipPosition *= clipW; //clip - return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view - } - vec3 getViewNormal( const in vec2 uv ) { - return unpackRGBToNormal( texture2D( tNormal, uv ).xyz ); - } - vec2 viewPositionToXY(vec3 viewPosition){ - vec2 xy; - vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1); - xy=clip.xy;//clip - float clipW=clip.w; - xy/=clipW;//NDC - xy=(xy+1.)/2.;//uv - xy*=resolution;//screen - return xy; - } - void main(){ - #ifdef isSelective - float metalness=texture2D(tMetalness,vUv).r; - if(metalness==0.) return; - #endif - - float depth = getDepth( vUv ); - float viewZ = getViewZ( depth ); - if(-viewZ>=cameraFar) return; - - float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3]; - vec3 viewPosition=getViewPosition( vUv, depth, clipW ); - - vec2 d0=gl_FragCoord.xy; - vec2 d1; - - vec3 viewNormal=getViewNormal( vUv ); - - #ifdef isPerspectiveCamera - vec3 viewIncidenceDir=normalize(viewPosition); - vec3 viewReflectDir=reflect(viewIncidenceDir,viewNormal); - #else - vec3 viewIncidenceDir=vec3(0,0,-1); - vec3 viewReflectDir=reflect(viewIncidenceDir,viewNormal); - #endif - - float maxReflectRayLen=maxDistance/dot(-viewIncidenceDir,viewNormal); - // dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html - // if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta) - // maxDistance/maxReflectRayLen=cos(theta) - // maxDistance/maxReflectRayLen==dot(a,b) - // maxReflectRayLen==maxDistance/dot(a,b) - - vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen; - #ifdef isPerspectiveCamera - if(d1viewPosition.z>-cameraNear){ - //https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx - float t=(-cameraNear-viewPosition.z)/viewReflectDir.z; - d1viewPosition=viewPosition+viewReflectDir*t; - } - #endif - d1=viewPositionToXY(d1viewPosition); - - float totalLen=length(d1-d0); - float xLen=d1.x-d0.x; - float yLen=d1.y-d0.y; - float totalStep=max(abs(xLen),abs(yLen)); - float xSpan=xLen/totalStep; - float ySpan=yLen/totalStep; - for(float i=0.;i=totalStep) break; - vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan); - if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break; - float s=length(xy-d0)/totalLen; - vec2 uv=xy/resolution; - - float d = getDepth(uv); - float vZ = getViewZ( d ); - if(-vZ>=cameraFar) continue; - float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3]; - vec3 vP=getViewPosition( uv, d, cW ); - - #ifdef isPerspectiveCamera - // https://www.comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf - float recipVPZ=1./viewPosition.z; - float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ)); - float sD=surfDist*cW; - #else - float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z); - float sD=surfDist; - #endif - if(viewReflectRayZ-sD>vZ) continue; - - #ifdef isInfiniteThick - if(viewReflectRayZ+thickTolerance*clipW=0.) continue; - float distance=pointPlaneDistance(vP,viewPosition,viewNormal); - if(distance>maxDistance) break; - #ifdef isDistanceAttenuation - float ratio=1.-(distance/maxDistance); - float attenuation=ratio*ratio; - op=opacity*attenuation; - #endif - #ifdef isFresnel - float fresnel=(dot(viewIncidenceDir,viewReflectDir)+1.)/2.; - op*=fresnel; - #endif - vec4 reflectColor=texture2D(tDiffuse,uv); - gl_FragColor.xyz=reflectColor.xyz; - gl_FragColor.a=op; - break; - } - } - } - ` -}; -const SSRDepthShader = { - defines: { - PERSPECTIVE_CAMERA: 1 - }, - uniforms: { - tDepth: { - value: null - }, - cameraNear: { - value: null - }, - cameraFar: { - value: null - } - }, - vertexShader: - /* glsl */ - ` + if (!isDevToolsPresent) { + return; + } - varying vec2 vUv; + var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; + var memoizedUpdaters = root.memoizedUpdaters; - void main() { + while (lanes > 0) { + var index = laneToIndex(lanes); + var lane = 1 << index; + var updaters = pendingUpdatersLaneMap[index]; - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + if (updaters.size > 0) { + updaters.forEach(function (fiber) { + var alternate = fiber.alternate; - } + if (alternate === null || !memoizedUpdaters.has(alternate)) { + memoizedUpdaters.add(fiber); + } + }); + updaters.clear(); + } - `, - fragmentShader: - /* glsl */ - ` + lanes &= ~lane; + } + } - uniform sampler2D tDepth; + var DiscreteEventPriority = SyncLane; + var ContinuousEventPriority = InputContinuousLane; + var DefaultEventPriority = DefaultLane; + var IdleEventPriority = IdleLane; + var currentUpdatePriority = NoLane; + function getCurrentUpdatePriority() { + return currentUpdatePriority; + } + function setCurrentUpdatePriority(newPriority) { + currentUpdatePriority = newPriority; + } + function runWithPriority(priority, fn) { + var previousPriority = currentUpdatePriority; - uniform float cameraNear; - uniform float cameraFar; + try { + currentUpdatePriority = priority; + return fn(); + } finally { + currentUpdatePriority = previousPriority; + } + } + function higherEventPriority(a, b) { + return a !== 0 && a < b ? a : b; + } + function lowerEventPriority(a, b) { + return a === 0 || a > b ? a : b; + } + function isHigherEventPriority(a, b) { + return a !== 0 && a < b; + } + function lanesToEventPriority(lanes) { + var lane = getHighestPriorityLane(lanes); - varying vec2 vUv; + if (!isHigherEventPriority(DiscreteEventPriority, lane)) { + return DiscreteEventPriority; + } - #include + if (!isHigherEventPriority(ContinuousEventPriority, lane)) { + return ContinuousEventPriority; + } - float getLinearDepth( const in vec2 uv ) { + if (includesNonIdleWork(lane)) { + return DefaultEventPriority; + } - #if PERSPECTIVE_CAMERA == 1 + return IdleEventPriority; + } - float fragCoordZ = texture2D( tDepth, uv ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + // This module only exists as an ESM wrapper around the external CommonJS + var scheduleCallback = Scheduler.unstable_scheduleCallback; + var cancelCallback = Scheduler.unstable_cancelCallback; + var shouldYield = Scheduler.unstable_shouldYield; + var requestPaint = Scheduler.unstable_requestPaint; + var now$1 = Scheduler.unstable_now; + var ImmediatePriority = Scheduler.unstable_ImmediatePriority; + var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; + var NormalPriority = Scheduler.unstable_NormalPriority; + var IdlePriority = Scheduler.unstable_IdlePriority; + // this doesn't actually exist on the scheduler, but it *does* + // on scheduler/unstable_mock, which we'll need for internal testing + var unstable_yieldValue = Scheduler.unstable_yieldValue; + var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue; - #else + var rendererID = null; + var injectedHook = null; + var injectedProfilingHooks = null; + var hasLoggedError = false; + var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined'; + function injectInternals(internals) { + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { + // No DevTools + return false; + } - return texture2D( tDepth, uv ).x; + var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; - #endif + if (hook.isDisabled) { + // This isn't a real property on the hook, but it can be set to opt out + // of DevTools integration and associated warnings and logs. + // https://github.com/facebook/react/issues/3877 + return true; + } - } + if (!hook.supportsFiber) { + { + error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools'); + } // DevTools exists, even though it doesn't support Fiber. - void main() { - float depth = getLinearDepth( vUv ); - float d = 1.0 - depth; - // d=(d-.999)*1000.; - gl_FragColor = vec4( vec3( d ), 1.0 ); + return true; + } - } + try { + if (enableSchedulingProfiler) { + // Conditionally inject these hooks only if Timeline profiler is supported by this build. + // This gives DevTools a way to feature detect that isn't tied to version number + // (since profiling and timeline are controlled by different feature flags). + internals = assign({}, internals, { + getLaneLabelMap: getLaneLabelMap, + injectProfilingHooks: injectProfilingHooks + }); + } - ` -}; -const SSRBlurShader = { - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2() - }, - opacity: { - value: 0.5 - } - }, - vertexShader: - /* glsl */ - ` + rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. - varying vec2 vUv; + injectedHook = hook; + } catch (err) { + // Catch all errors because it is unsafe to throw during initialization. + { + error('React instrumentation encountered an error: %s.', err); + } + } - void main() { + if (hook.checkDCE) { + // This is the real DevTools. + return true; + } else { + // This is likely a hook installed by Fast Refresh runtime. + return false; + } + } + function onScheduleRoot(root, children) { + { + if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') { + try { + injectedHook.onScheduleFiberRoot(rendererID, root, children); + } catch (err) { + if ( !hasLoggedError) { + hasLoggedError = true; - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + function onCommitRoot(root, eventPriority) { + if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { + try { + var didError = (root.current.flags & DidCapture) === DidCapture; - } + if (enableProfilerTimer) { + var schedulerPriority; - `, - fragmentShader: - /* glsl */ - ` + switch (eventPriority) { + case DiscreteEventPriority: + schedulerPriority = ImmediatePriority; + break; - uniform sampler2D tDiffuse; - uniform vec2 resolution; - varying vec2 vUv; - void main() { - //reverse engineering from PhotoShop blur filter, then change coefficient + case ContinuousEventPriority: + schedulerPriority = UserBlockingPriority; + break; - vec2 texelSize = ( 1.0 / resolution ); + case DefaultEventPriority: + schedulerPriority = NormalPriority; + break; - vec4 c=texture2D(tDiffuse,vUv); + case IdleEventPriority: + schedulerPriority = IdlePriority; + break; - vec2 offset; + default: + schedulerPriority = NormalPriority; + break; + } - offset=(vec2(-1,0))*texelSize; - vec4 cl=texture2D(tDiffuse,vUv+offset); + injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError); + } + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; - offset=(vec2(1,0))*texelSize; - vec4 cr=texture2D(tDiffuse,vUv+offset); + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + function onPostCommitRoot(root) { + if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') { + try { + injectedHook.onPostCommitFiberRoot(rendererID, root); + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; - offset=(vec2(0,-1))*texelSize; - vec4 cb=texture2D(tDiffuse,vUv+offset); + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + function onCommitUnmount(fiber) { + if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') { + try { + injectedHook.onCommitFiberUnmount(rendererID, fiber); + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; - offset=(vec2(0,1))*texelSize; - vec4 ct=texture2D(tDiffuse,vUv+offset); + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + function setIsStrictModeForDevtools(newIsStrictMode) { + { + if (typeof unstable_yieldValue === 'function') { + // We're in a test because Scheduler.unstable_yieldValue only exists + // in SchedulerMock. To reduce the noise in strict mode tests, + // suppress warnings and disable scheduler yielding during the double render + unstable_setDisableYieldValue(newIsStrictMode); + setSuppressWarning(newIsStrictMode); + } - // float coeCenter=.5; - // float coeSide=.125; - float coeCenter=.2; - float coeSide=.2; - float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide; - vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a; - gl_FragColor=vec4(rgb,a); + if (injectedHook && typeof injectedHook.setStrictMode === 'function') { + try { + injectedHook.setStrictMode(rendererID, newIsStrictMode); + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; - } - ` -}; + error('React instrumentation encountered an error: %s', err); + } + } + } + } + } + } // Profiler API hooks -var SSRPass = function ({ - renderer, - scene, - camera, - width, - height, - selects, - encoding, - isPerspectiveCamera = true, - isBouncing = false, - morphTargets = false, - groundReflector -}) { - this.width = width !== undefined ? width : 512; - this.height = height !== undefined ? height : 512; - this.clear = true; - this.renderer = renderer; - this.scene = scene; - this.camera = camera; - this.groundReflector = groundReflector; - this.opacity = SSRShader.uniforms.opacity.value; - this.output = 0; - this.maxDistance = SSRShader.uniforms.maxDistance.value; - this.surfDist = SSRShader.uniforms.surfDist.value; - this.encoding = encoding; - this.tempColor = new Color(); - this._selects = selects; - this.isSelective = Array.isArray(this._selects); - Object.defineProperty(this, 'selects', { - get() { - return this._selects; - }, + function injectProfilingHooks(profilingHooks) { + injectedProfilingHooks = profilingHooks; + } - set(val) { - if (this._selects === val) return; - this._selects = val; + function getLaneLabelMap() { + { + var map = new Map(); + var lane = 1; - if (Array.isArray(val)) { - this.isSelective = true; - this.ssrMaterial.defines.isSelective = true; - this.ssrMaterial.needsUpdate = true; - } else { - this.isSelective = false; - this.ssrMaterial.defines.isSelective = false; - this.ssrMaterial.needsUpdate = true; - } - } + for (var index = 0; index < TotalLanes; index++) { + var label = getLabelForLane(lane); + map.set(lane, label); + lane *= 2; + } - }); - this._isBouncing = isBouncing; ///todo: don't need defineProperty + return map; + } + } - Object.defineProperty(this, 'isBouncing', { - get() { - return this._isBouncing; - }, + function markCommitStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') { + injectedProfilingHooks.markCommitStarted(lanes); + } + } + } + function markCommitStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') { + injectedProfilingHooks.markCommitStopped(); + } + } + } + function markComponentRenderStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') { + injectedProfilingHooks.markComponentRenderStarted(fiber); + } + } + } + function markComponentRenderStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') { + injectedProfilingHooks.markComponentRenderStopped(); + } + } + } + function markComponentPassiveEffectMountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') { + injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); + } + } + } + function markComponentPassiveEffectMountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') { + injectedProfilingHooks.markComponentPassiveEffectMountStopped(); + } + } + } + function markComponentPassiveEffectUnmountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') { + injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); + } + } + } + function markComponentPassiveEffectUnmountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') { + injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); + } + } + } + function markComponentLayoutEffectMountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') { + injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); + } + } + } + function markComponentLayoutEffectMountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') { + injectedProfilingHooks.markComponentLayoutEffectMountStopped(); + } + } + } + function markComponentLayoutEffectUnmountStarted(fiber) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') { + injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); + } + } + } + function markComponentLayoutEffectUnmountStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') { + injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); + } + } + } + function markComponentErrored(fiber, thrownValue, lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') { + injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); + } + } + } + function markComponentSuspended(fiber, wakeable, lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') { + injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); + } + } + } + function markLayoutEffectsStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') { + injectedProfilingHooks.markLayoutEffectsStarted(lanes); + } + } + } + function markLayoutEffectsStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') { + injectedProfilingHooks.markLayoutEffectsStopped(); + } + } + } + function markPassiveEffectsStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') { + injectedProfilingHooks.markPassiveEffectsStarted(lanes); + } + } + } + function markPassiveEffectsStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') { + injectedProfilingHooks.markPassiveEffectsStopped(); + } + } + } + function markRenderStarted(lanes) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') { + injectedProfilingHooks.markRenderStarted(lanes); + } + } + } + function markRenderYielded() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') { + injectedProfilingHooks.markRenderYielded(); + } + } + } + function markRenderStopped() { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') { + injectedProfilingHooks.markRenderStopped(); + } + } + } + function markRenderScheduled(lane) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') { + injectedProfilingHooks.markRenderScheduled(lane); + } + } + } + function markForceUpdateScheduled(fiber, lane) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') { + injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); + } + } + } + function markStateUpdateScheduled(fiber, lane) { + { + if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') { + injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); + } + } + } - set(val) { - if (this._isBouncing === val) return; - this._isBouncing = val; + /** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ + function is(x, y) { + return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare + ; + } - if (val) { - this.ssrMaterial.uniforms['tDiffuse'].value = this.prevRenderTarget.texture; - } else { - this.ssrMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - } - } + var objectIs = typeof Object.is === 'function' ? Object.is : is; - }); - this.isBlur = true; - this._isDistanceAttenuation = SSRShader.defines.isDistanceAttenuation; - Object.defineProperty(this, 'isDistanceAttenuation', { - get() { - return this._isDistanceAttenuation; - }, + var syncQueue = null; + var includesLegacySyncCallbacks = false; + var isFlushingSyncQueue = false; + function scheduleSyncCallback(callback) { + // Push this callback into an internal queue. We'll flush these either in + // the next tick, or earlier if something calls `flushSyncCallbackQueue`. + if (syncQueue === null) { + syncQueue = [callback]; + } else { + // Push onto existing queue. Don't need to schedule a callback because + // we already scheduled one when we created the queue. + syncQueue.push(callback); + } + } + function scheduleLegacySyncCallback(callback) { + includesLegacySyncCallbacks = true; + scheduleSyncCallback(callback); + } + function flushSyncCallbacksOnlyInLegacyMode() { + // Only flushes the queue if there's a legacy sync callback scheduled. + // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So + // it might make more sense for the queue to be a list of roots instead of a + // list of generic callbacks. Then we can have two: one for legacy roots, one + // for concurrent roots. And this method would only flush the legacy ones. + if (includesLegacySyncCallbacks) { + flushSyncCallbacks(); + } + } + function flushSyncCallbacks() { + if (!isFlushingSyncQueue && syncQueue !== null) { + // Prevent re-entrance. + isFlushingSyncQueue = true; + var i = 0; + var previousUpdatePriority = getCurrentUpdatePriority(); - set(val) { - if (this._isDistanceAttenuation === val) return; - this._isDistanceAttenuation = val; - this.ssrMaterial.defines.isDistanceAttenuation = val; - this.ssrMaterial.needsUpdate = true; - } + try { + var isSync = true; + var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this + // queue is in the render or commit phases. - }); - this._isFresnel = SSRShader.defines.isFresnel; - Object.defineProperty(this, 'isFresnel', { - get() { - return this._isFresnel; - }, + setCurrentUpdatePriority(DiscreteEventPriority); - set(val) { - if (this._isFresnel === val) return; - this._isFresnel = val; - this.ssrMaterial.defines.isFresnel = val; - this.ssrMaterial.needsUpdate = true; - } + for (; i < queue.length; i++) { + var callback = queue[i]; - }); - this._isInfiniteThick = SSRShader.defines.isInfiniteThick; - Object.defineProperty(this, 'isInfiniteThick', { - get() { - return this._isInfiniteThick; - }, + do { + callback = callback(isSync); + } while (callback !== null); + } - set(val) { - if (this._isInfiniteThick === val) return; - this._isInfiniteThick = val; - this.ssrMaterial.defines.isInfiniteThick = val; - this.ssrMaterial.needsUpdate = true; - } + syncQueue = null; + includesLegacySyncCallbacks = false; + } catch (error) { + // If something throws, leave the remaining callbacks on the queue. + if (syncQueue !== null) { + syncQueue = syncQueue.slice(i + 1); + } // Resume flushing in the next tick - }); - this.thickTolerance = SSRShader.uniforms.thickTolerance.value; // beauty render target with depth buffer - - var depthTexture = new DepthTexture(); - depthTexture.type = UnsignedShortType; - depthTexture.minFilter = NearestFilter; - depthTexture.maxFilter = NearestFilter; - this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat, - depthTexture: depthTexture, - depthBuffer: true - }); //for bouncing - - this.prevRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }); // normal render target - - this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: NearestFilter, - magFilter: NearestFilter, - format: RGBAFormat, - type: HalfFloatType - }); // metalness render target - // if (this.isSelective) { - - this.metalnessRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: NearestFilter, - magFilter: NearestFilter, - format: RGBAFormat - }); // } - // ssr render target - - this.ssrRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }); - this.blurRenderTarget = this.ssrRenderTarget.clone(); - this.blurRenderTarget2 = this.ssrRenderTarget.clone(); // this.blurRenderTarget3 = this.ssrRenderTarget.clone(); - // ssr material - - if (SSRShader === undefined) { - console.error('THREE.SSRPass: The pass relies on SSRShader.'); - } - - this.ssrMaterial = new ShaderMaterial({ - defines: Object.assign({ - MAX_STEP: Math.sqrt(window.innerWidth * window.innerWidth + window.innerHeight * window.innerHeight) - }, SSRShader.defines), - uniforms: UniformsUtils.clone(SSRShader.uniforms), - vertexShader: SSRShader.vertexShader, - fragmentShader: SSRShader.fragmentShader, - blending: NoBlending - }); - if (!isPerspectiveCamera) { - this.ssrMaterial.defines.isPerspectiveCamera = isPerspectiveCamera; - this.ssrMaterial.needsUpdate = true; - } + scheduleCallback(ImmediatePriority, flushSyncCallbacks); + throw error; + } finally { + setCurrentUpdatePriority(previousUpdatePriority); + isFlushingSyncQueue = false; + } + } - this.ssrMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.ssrMaterial.uniforms['tNormal'].value = this.normalRenderTarget.texture; // if (this.isSelective) { + return null; + } - this.ssrMaterial.defines.isSelective = this.isSelective; - this.ssrMaterial.needsUpdate = true; - this.ssrMaterial.uniforms['tMetalness'].value = this.metalnessRenderTarget.texture; // } + // This is imported by the event replaying implementation in React DOM. It's + // in a separate file to break a circular dependency between the renderer and + // the reconciler. + function isRootDehydrated(root) { + var currentState = root.current.memoizedState; + return currentState.isDehydrated; + } - this.ssrMaterial.uniforms['tDepth'].value = this.beautyRenderTarget.depthTexture; - this.ssrMaterial.uniforms['cameraNear'].value = this.camera.near; - this.ssrMaterial.uniforms['cameraFar'].value = this.camera.far; - this.ssrMaterial.uniforms['surfDist'].value = this.surfDist; - this.ssrMaterial.uniforms['resolution'].value.set(this.width, this.height); - this.ssrMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssrMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); // normal material + var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; + var NoTransition = null; + function requestCurrentTransition() { + return ReactCurrentBatchConfig.transition; + } - this.normalMaterial = new MeshNormalMaterial({ - morphTargets - }); - this.normalMaterial.blending = NoBlending; // if (this.isSelective) { - // metalnessOn material - - this.metalnessOnMaterial = new MeshBasicMaterial({ - color: 'white' - }); // metalnessOff material - - this.metalnessOffMaterial = new MeshBasicMaterial({ - color: 'black' - }); // } - // blur material - - this.blurMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSRBlurShader.defines), - uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), - vertexShader: SSRBlurShader.vertexShader, - fragmentShader: SSRBlurShader.fragmentShader - }); - this.blurMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.blurMaterial.uniforms['resolution'].value.set(this.width, this.height); // blur material 2 - - this.blurMaterial2 = new ShaderMaterial({ - defines: Object.assign({}, SSRBlurShader.defines), - uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), - vertexShader: SSRBlurShader.vertexShader, - fragmentShader: SSRBlurShader.fragmentShader - }); - this.blurMaterial2.uniforms['tDiffuse'].value = this.blurRenderTarget.texture; - this.blurMaterial2.uniforms['resolution'].value.set(this.width, this.height); // // blur material 3 - // this.blurMaterial3 = new ShaderMaterial({ - // defines: Object.assign({}, SSRBlurShader.defines), - // uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), - // vertexShader: SSRBlurShader.vertexShader, - // fragmentShader: SSRBlurShader.fragmentShader - // }); - // this.blurMaterial3.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture; - // this.blurMaterial3.uniforms['resolution'].value.set(this.width, this.height); - // material for rendering the depth - - this.depthRenderMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSRDepthShader.defines), - uniforms: UniformsUtils.clone(SSRDepthShader.uniforms), - vertexShader: SSRDepthShader.vertexShader, - fragmentShader: SSRDepthShader.fragmentShader, - blending: NoBlending - }); - this.depthRenderMaterial.uniforms['tDepth'].value = this.beautyRenderTarget.depthTexture; - this.depthRenderMaterial.uniforms['cameraNear'].value = this.camera.near; - this.depthRenderMaterial.uniforms['cameraFar'].value = this.camera.far; // material for rendering the content of a render target - - this.copyMaterial = new ShaderMaterial({ - uniforms: UniformsUtils.clone(CopyShader.uniforms), - vertexShader: CopyShader.vertexShader, - fragmentShader: CopyShader.fragmentShader, - transparent: true, - depthTest: false, - depthWrite: false, - blendSrc: SrcAlphaFactor, - blendDst: OneMinusSrcAlphaFactor, - blendEquation: AddEquation, - blendSrcAlpha: SrcAlphaFactor, - blendDstAlpha: OneMinusSrcAlphaFactor, - blendEquationAlpha: AddEquation // premultipliedAlpha:true, + /** + * Performs equality by iterating through keys on an object and returning false + * when any key has values which are not strictly equal between the arguments. + * Returns true when the values of all keys are strictly equal. + */ - }); - this.fsQuad = new FullScreenQuad(null); - this.originalClearColor = new Color(); -}; + function shallowEqual(objA, objB) { + if (objectIs(objA, objB)) { + return true; + } -SSRPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: SSRPass, - dispose: function () { - // dispose render targets - this.beautyRenderTarget.dispose(); - this.prevRenderTarget.dispose(); - this.normalRenderTarget.dispose(); // if (this.isSelective) + if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { + return false; + } - this.metalnessRenderTarget.dispose(); - this.ssrRenderTarget.dispose(); - this.blurRenderTarget.dispose(); - this.blurRenderTarget2.dispose(); // this.blurRenderTarget3.dispose(); - // dispose materials + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); - this.normalMaterial.dispose(); // if (this.isSelective) { + if (keysA.length !== keysB.length) { + return false; + } // Test for A's keys different from B. - this.metalnessOnMaterial.dispose(); - this.metalnessOffMaterial.dispose(); // } - this.blurMaterial.dispose(); - this.blurMaterial2.dispose(); - this.copyMaterial.dispose(); - this.depthRenderMaterial.dispose(); // dipsose full screen quad + for (var i = 0; i < keysA.length; i++) { + var currentKey = keysA[i]; - this.fsQuad.dispose(); - }, - render: function (renderer, writeBuffer - /*, readBuffer, deltaTime, maskActive */ - ) { - // render beauty and depth - if (this.encoding) this.beautyRenderTarget.texture.encoding = this.encoding; - renderer.setRenderTarget(this.beautyRenderTarget); - renderer.clear(); - - if (this.groundReflector) { - this.groundReflector.doRender(this.renderer, this.scene, this.camera); - this.groundReflector.visible = true; - } + if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) { + return false; + } + } - renderer.render(this.scene, this.camera); - if (this.groundReflector) this.groundReflector.visible = false; // render normals - - this.renderOverride(renderer, this.normalMaterial, this.normalRenderTarget, 0, 0); // render metalnesses - - if (this.isSelective) { - this.renderMetalness(renderer, this.metalnessOnMaterial, this.metalnessRenderTarget, 0, 0); - } // render SSR - - - this.ssrMaterial.uniforms['opacity'].value = this.opacity; - this.ssrMaterial.uniforms['maxDistance'].value = this.maxDistance; - this.ssrMaterial.uniforms['surfDist'].value = this.surfDist; - this.ssrMaterial.uniforms['thickTolerance'].value = this.thickTolerance; - this.renderPass(renderer, this.ssrMaterial, this.ssrRenderTarget); // render blur - - if (this.isBlur) { - this.renderPass(renderer, this.blurMaterial, this.blurRenderTarget); - this.renderPass(renderer, this.blurMaterial2, this.blurRenderTarget2); // this.renderPass(renderer, this.blurMaterial3, this.blurRenderTarget3); - } // output result to screen - - - switch (this.output) { - case SSRPass.OUTPUT.Default: - if (this.isBouncing) { - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); - if (this.isBlur) this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;else this.copyMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.copyMaterial.blending = NormalBlending; - this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); - this.copyMaterial.uniforms['tDiffuse'].value = this.prevRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - } else { - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - if (this.isBlur) this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;else this.copyMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.copyMaterial.blending = NormalBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - } + return true; + } - break; + function describeFiber(fiber) { + fiber._debugOwner ? fiber._debugOwner.type : null ; + fiber._debugSource ; - case SSRPass.OUTPUT.SSR: - if (this.isBlur) this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;else this.copyMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - - if (this.isBouncing) { - if (this.isBlur) this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;else this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); - this.copyMaterial.uniforms['tDiffuse'].value = this.ssrRenderTarget.texture; - this.copyMaterial.blending = NormalBlending; - this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); - } + switch (fiber.tag) { + case HostComponent: + return describeBuiltInComponentFrame(fiber.type); - break; + case LazyComponent: + return describeBuiltInComponentFrame('Lazy'); - case SSRPass.OUTPUT.Beauty: - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + case SuspenseComponent: + return describeBuiltInComponentFrame('Suspense'); - case SSRPass.OUTPUT.Depth: - this.renderPass(renderer, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); - break; + case SuspenseListComponent: + return describeBuiltInComponentFrame('SuspenseList'); - case SSRPass.OUTPUT.Normal: - this.copyMaterial.uniforms['tDiffuse'].value = this.normalRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + case FunctionComponent: + case IndeterminateComponent: + case SimpleMemoComponent: + return describeFunctionComponentFrame(fiber.type); - case SSRPass.OUTPUT.Metalness: - this.copyMaterial.uniforms['tDiffuse'].value = this.metalnessRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; + case ForwardRef: + return describeFunctionComponentFrame(fiber.type.render); - default: - console.warn('THREE.SSRPass: Unknown output type.'); - } - }, - renderPass: function (renderer, passMaterial, renderTarget, clearColor, clearAlpha) { - // save original state - this.originalClearColor.copy(renderer.getClearColor(this.tempColor)); - var originalClearAlpha = renderer.getClearAlpha(this.tempColor); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); // setup pass state - - renderer.autoClear = false; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + case ClassComponent: + return describeClassComponentFrame(fiber.type); - this.fsQuad.material = passMaterial; - this.fsQuad.render(renderer); // restore original state + default: + return ''; + } + } - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - renderOverride: function (renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { - this.originalClearColor.copy(renderer.getClearColor(this.tempColor)); - var originalClearAlpha = renderer.getClearAlpha(this.tempColor); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); - renderer.autoClear = false; - clearColor = overrideMaterial.clearColor || clearColor; - clearAlpha = overrideMaterial.clearAlpha || clearAlpha; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + function getStackByFiberInDevAndProd(workInProgress) { + try { + var info = ''; + var node = workInProgress; - this.scene.overrideMaterial = overrideMaterial; - renderer.render(this.scene, this.camera); - this.scene.overrideMaterial = null; // restore original state + do { + info += describeFiber(node); + node = node.return; + } while (node); - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - renderMetalness: function (renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { - this.originalClearColor.copy(renderer.getClearColor(this.tempColor)); - var originalClearAlpha = renderer.getClearAlpha(this.tempColor); - var originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); - renderer.autoClear = false; - clearColor = overrideMaterial.clearColor || clearColor; - clearAlpha = overrideMaterial.clearAlpha || clearAlpha; - - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } + return info; + } catch (x) { + return '\nError generating stack: ' + x.message + '\n' + x.stack; + } + } - this.scene.traverseVisible(child => { - child._SSRPassMaterialBack = child.material; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + var current = null; + var isRendering = false; + function getCurrentFiberOwnerNameInDevOrNull() { + { + if (current === null) { + return null; + } - if (this._selects.includes(child)) { - child.material = this.metalnessOnMaterial; - } else { - child.material = this.metalnessOffMaterial; - } - }); - renderer.render(this.scene, this.camera); - this.scene.traverseVisible(child => { - child.material = child._SSRPassMaterialBack; - }); // restore original state + var owner = current._debugOwner; - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - }, - setSize: function (width, height) { - this.width = width; - this.height = height; - this.ssrMaterial.defines.MAX_STEP = Math.sqrt(width * width + height * height); - this.ssrMaterial.needsUpdate = true; - this.beautyRenderTarget.setSize(width, height); - this.prevRenderTarget.setSize(width, height); - this.ssrRenderTarget.setSize(width, height); - this.normalRenderTarget.setSize(width, height); // if (this.isSelective) - - this.metalnessRenderTarget.setSize(width, height); - this.blurRenderTarget.setSize(width, height); - this.blurRenderTarget2.setSize(width, height); // this.blurRenderTarget3.setSize(width, height); - - this.ssrMaterial.uniforms['resolution'].value.set(width, height); - this.ssrMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssrMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - this.blurMaterial.uniforms['resolution'].value.set(width, height); - this.blurMaterial2.uniforms['resolution'].value.set(width, height); - } -}); -SSRPass.OUTPUT = { - Default: 0, - SSR: 1, - Beauty: 3, - Depth: 4, - Normal: 5, - Metalness: 7 -}; + if (owner !== null && typeof owner !== 'undefined') { + return getComponentNameFromFiber(owner); + } + } -/** - * - * Supersample Anti-Aliasing Render Pass - * - * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results. - * - * References: https://en.wikipedia.org/wiki/Supersampling - * - */ + return null; + } -var SSAARenderPass = function (scene, camera, clearColor, clearAlpha) { - this.scene = scene; - this.camera = camera; - this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16. - - this.unbiased = true; // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black. - - this.clearColor = clearColor !== undefined ? clearColor : 0x000000; - this.clearAlpha = clearAlpha !== undefined ? clearAlpha : 0; - this._oldClearColor = new Color(); - if (CopyShader === undefined) console.error('THREE.SSAARenderPass relies on CopyShader'); - var copyShader = CopyShader; - this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); - this.copyMaterial = new ShaderMaterial({ - uniforms: this.copyUniforms, - vertexShader: copyShader.vertexShader, - fragmentShader: copyShader.fragmentShader, - premultipliedAlpha: true, - transparent: true, - blending: AdditiveBlending, - depthTest: false, - depthWrite: false - }); - this.fsQuad = new FullScreenQuad(this.copyMaterial); -}; + function getCurrentFiberStackInDev() { + { + if (current === null) { + return ''; + } // Safe because if current fiber exists, we are reconciling, + // and it is guaranteed to be the work-in-progress version. -SSAARenderPass.prototype = Object.assign(Object.create(Pass$1.prototype), { - constructor: SSAARenderPass, - dispose: function () { - if (this.sampleRenderTarget) { - this.sampleRenderTarget.dispose(); - this.sampleRenderTarget = null; - } - }, - setSize: function (width, height) { - if (this.sampleRenderTarget) this.sampleRenderTarget.setSize(width, height); - }, - render: function (renderer, writeBuffer, readBuffer) { - if (!this.sampleRenderTarget) { - this.sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, { - minFilter: LinearFilter, - magFilter: LinearFilter, - format: RGBAFormat - }); - this.sampleRenderTarget.texture.name = 'SSAARenderPass.sample'; - } - var jitterOffsets = SSAARenderPass.JitterVectors[Math.max(0, Math.min(this.sampleLevel, 5))]; - var autoClear = renderer.autoClear; - renderer.autoClear = false; - renderer.getClearColor(this._oldClearColor); - var oldClearAlpha = renderer.getClearAlpha(); - var baseSampleWeight = 1.0 / jitterOffsets.length; - var roundingRange = 1 / 32; - this.copyUniforms['tDiffuse'].value = this.sampleRenderTarget.texture; - var width = readBuffer.width, - height = readBuffer.height; // render the scene multiple times, each slightly jitter offset from the last and accumulate the results. - - for (let i = 0; i < jitterOffsets.length; i++) { - var jitterOffset = jitterOffsets[i]; - - if (this.camera.setViewOffset) { - this.camera.setViewOffset(width, height, jitterOffset[0] * 0.0625, jitterOffset[1] * 0.0625, // 0.0625 = 1 / 16 - width, height); - } + return getStackByFiberInDevAndProd(current); + } + } - var sampleWeight = baseSampleWeight; + function resetCurrentFiber() { + { + ReactDebugCurrentFrame$1.getCurrentStack = null; + current = null; + isRendering = false; + } + } + function setCurrentFiber(fiber) { + { + ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev; + current = fiber; + isRendering = false; + } + } + function setIsRendering(rendering) { + { + isRendering = rendering; + } + } - if (this.unbiased) { - // the theory is that equal weights for each sample lead to an accumulation of rounding errors. - // The following equation varies the sampleWeight per sample so that it is uniformly distributed - // across a range of values whose rounding errors cancel each other out. - var uniformCenteredDistribution = -0.5 + (i + 0.5) / jitterOffsets.length; - sampleWeight += roundingRange * uniformCenteredDistribution; - } + var ReactStrictModeWarnings = { + recordUnsafeLifecycleWarnings: function (fiber, instance) {}, + flushPendingUnsafeLifecycleWarnings: function () {}, + recordLegacyContextWarning: function (fiber, instance) {}, + flushLegacyContextWarning: function () {}, + discardPendingWarnings: function () {} + }; - this.copyUniforms['opacity'].value = sampleWeight; - renderer.setClearColor(this.clearColor, this.clearAlpha); - renderer.setRenderTarget(this.sampleRenderTarget); - renderer.clear(); - renderer.render(this.scene, this.camera); - renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer); + { + var findStrictRoot = function (fiber) { + var maybeStrictRoot = null; + var node = fiber; - if (i === 0) { - renderer.setClearColor(0x000000, 0.0); - renderer.clear(); - } + while (node !== null) { + if (node.mode & StrictLegacyMode) { + maybeStrictRoot = node; + } - this.fsQuad.render(renderer); - } + node = node.return; + } - if (this.camera.clearViewOffset) this.camera.clearViewOffset(); - renderer.autoClear = autoClear; - renderer.setClearColor(this._oldClearColor, oldClearAlpha); - } -}); // These jitter vectors are specified in integers because it is easier. -// I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5) -// before being used, thus these integers need to be scaled by 1/16. -// -// Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 + return maybeStrictRoot; + }; -SSAARenderPass.JitterVectors = [[[0, 0]], [[4, 4], [-4, -4]], [[-2, -6], [6, -2], [-6, 2], [2, 6]], [[1, -3], [-1, 3], [5, 1], [-3, -5], [-5, 5], [-7, -1], [3, 7], [7, -7]], [[1, 1], [-1, -3], [-3, 2], [4, -1], [-5, -2], [2, 5], [5, 3], [3, -5], [-2, 6], [0, -7], [-4, -6], [-6, 4], [-8, 0], [7, -4], [6, 7], [-7, -8]], [[-4, -7], [-7, -5], [-3, -5], [-5, -4], [-1, -4], [-2, -2], [-6, -1], [-4, 0], [-7, 1], [-1, 2], [-6, 3], [-3, 3], [-7, 6], [-3, 6], [-5, 7], [-1, 7], [5, -7], [1, -6], [6, -5], [4, -4], [2, -3], [7, -2], [1, -1], [4, -1], [2, 1], [6, 2], [0, 4], [4, 4], [2, 5], [7, 5], [5, 6], [3, 7]]]; + var setToSortedString = function (set) { + var array = []; + set.forEach(function (value) { + array.push(value); + }); + return array.sort().join(', '); + }; -/** - * - * Temporal Anti-Aliasing Render Pass - * - * When there is no motion in the scene, the TAA render pass accumulates jittered camera samples across frames to create a high quality anti-aliased result. - * - * References: - * - * TODO: Add support for motion vector pas so that accumulation of samples across frames can occur on dynamics scenes. - * - */ + var pendingComponentWillMountWarnings = []; + var pendingUNSAFE_ComponentWillMountWarnings = []; + var pendingComponentWillReceivePropsWarnings = []; + var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; + var pendingComponentWillUpdateWarnings = []; + var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. -var TAARenderPass = function (scene, camera, clearColor, clearAlpha) { - if (SSAARenderPass === undefined) { - console.error('THREE.TAARenderPass relies on SSAARenderPass'); - } + var didWarnAboutUnsafeLifecycles = new Set(); - SSAARenderPass.call(this, scene, camera, clearColor, clearAlpha); - this.sampleLevel = 0; - this.accumulate = false; -}; + ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) { + // Dedupe strategy: Warn once per component. + if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { + return; + } -TAARenderPass.JitterVectors = SSAARenderPass.JitterVectors; -TAARenderPass.prototype = Object.assign(Object.create(SSAARenderPass.prototype), { - constructor: TAARenderPass, - render: function (renderer, writeBuffer, readBuffer, deltaTime) { - if (!this.accumulate) { - SSAARenderPass.prototype.render.call(this, renderer, writeBuffer, readBuffer, deltaTime); - this.accumulateIndex = -1; - return; - } + if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components. + instance.componentWillMount.__suppressDeprecationWarning !== true) { + pendingComponentWillMountWarnings.push(fiber); + } - var jitterOffsets = TAARenderPass.JitterVectors[5]; + if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') { + pendingUNSAFE_ComponentWillMountWarnings.push(fiber); + } - if (!this.sampleRenderTarget) { - this.sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, this.params); - this.sampleRenderTarget.texture.name = 'TAARenderPass.sample'; - } + if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { + pendingComponentWillReceivePropsWarnings.push(fiber); + } - if (!this.holdRenderTarget) { - this.holdRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, this.params); - this.holdRenderTarget.texture.name = 'TAARenderPass.hold'; - } + if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') { + pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); + } - if (this.accumulate && this.accumulateIndex === -1) { - SSAARenderPass.prototype.render.call(this, renderer, this.holdRenderTarget, readBuffer, deltaTime); - this.accumulateIndex = 0; - } + if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { + pendingComponentWillUpdateWarnings.push(fiber); + } - var autoClear = renderer.autoClear; - renderer.autoClear = false; - var sampleWeight = 1.0 / jitterOffsets.length; + if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') { + pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); + } + }; - if (this.accumulateIndex >= 0 && this.accumulateIndex < jitterOffsets.length) { - this.copyUniforms['opacity'].value = sampleWeight; - this.copyUniforms['tDiffuse'].value = writeBuffer.texture; // render the scene multiple times, each slightly jitter offset from the last and accumulate the results. + ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () { + // We do an initial pass to gather component names + var componentWillMountUniqueNames = new Set(); - var numSamplesPerFrame = Math.pow(2, this.sampleLevel); + if (pendingComponentWillMountWarnings.length > 0) { + pendingComponentWillMountWarnings.forEach(function (fiber) { + componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingComponentWillMountWarnings = []; + } - for (let i = 0; i < numSamplesPerFrame; i++) { - var j = this.accumulateIndex; - var jitterOffset = jitterOffsets[j]; + var UNSAFE_componentWillMountUniqueNames = new Set(); - if (this.camera.setViewOffset) { - this.camera.setViewOffset(readBuffer.width, readBuffer.height, jitterOffset[0] * 0.0625, jitterOffset[1] * 0.0625, // 0.0625 = 1 / 16 - readBuffer.width, readBuffer.height); - } + if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { + pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) { + UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingUNSAFE_ComponentWillMountWarnings = []; + } - renderer.setRenderTarget(writeBuffer); - renderer.clear(); - renderer.render(this.scene, this.camera); - renderer.setRenderTarget(this.sampleRenderTarget); - if (this.accumulateIndex === 0) renderer.clear(); - this.fsQuad.render(renderer); - this.accumulateIndex++; - if (this.accumulateIndex >= jitterOffsets.length) break; - } + var componentWillReceivePropsUniqueNames = new Set(); - if (this.camera.clearViewOffset) this.camera.clearViewOffset(); - } + if (pendingComponentWillReceivePropsWarnings.length > 0) { + pendingComponentWillReceivePropsWarnings.forEach(function (fiber) { + componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingComponentWillReceivePropsWarnings = []; + } - var accumulationWeight = this.accumulateIndex * sampleWeight; + var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); - if (accumulationWeight > 0) { - this.copyUniforms['opacity'].value = 1.0; - this.copyUniforms['tDiffuse'].value = this.sampleRenderTarget.texture; - renderer.setRenderTarget(writeBuffer); - renderer.clear(); - this.fsQuad.render(renderer); - } + if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { + pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) { + UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingUNSAFE_ComponentWillReceivePropsWarnings = []; + } - if (accumulationWeight < 1.0) { - this.copyUniforms['opacity'].value = 1.0 - accumulationWeight; - this.copyUniforms['tDiffuse'].value = this.holdRenderTarget.texture; - renderer.setRenderTarget(writeBuffer); - if (accumulationWeight === 0) renderer.clear(); - this.fsQuad.render(renderer); - } + var componentWillUpdateUniqueNames = new Set(); - renderer.autoClear = autoClear; - } -}); + if (pendingComponentWillUpdateWarnings.length > 0) { + pendingComponentWillUpdateWarnings.forEach(function (fiber) { + componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingComponentWillUpdateWarnings = []; + } -/** - * Convolution shader - * ported from o3d sample to WebGL / GLSL - * http://o3d.googlecode.com/svn/trunk/samples/convolution.html - */ + var UNSAFE_componentWillUpdateUniqueNames = new Set(); -({ - defines: { - KERNEL_SIZE_FLOAT: '25.0', - KERNEL_SIZE_INT: '25' - }, - uniforms: { - tDiffuse: { - value: null - }, - uImageIncrement: { - value: new Vector2(0.001953125, 0.0) - }, - cKernel: { - value: [] - } - }, - vertexShader: ['uniform vec2 uImageIncrement;', 'varying vec2 vUv;', 'void main() {', ' vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform float cKernel[ KERNEL_SIZE_INT ];', 'uniform sampler2D tDiffuse;', 'uniform vec2 uImageIncrement;', 'varying vec2 vUv;', 'void main() {', ' vec2 imageCoord = vUv;', ' vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );', ' for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {', ' sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];', ' imageCoord += uImageIncrement;', ' }', ' gl_FragColor = sum;', '}'].join('\n'), - buildKernel: function (sigma) { - // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway. - function gauss(x, sigma) { - return Math.exp(-(x * x) / (2.0 * sigma * sigma)); - } + if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { + pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) { + UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutUnsafeLifecycles.add(fiber.type); + }); + pendingUNSAFE_ComponentWillUpdateWarnings = []; + } // Finally, we flush all the warnings + // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' - const kMaxKernelSize = 25; - const kernelSize = Math.min(2 * Math.ceil(sigma * 3.0) + 1, kMaxKernelSize); - const halfWidth = (kernelSize - 1) * 0.5; - const values = new Array(kernelSize); - let sum = 0.0; - for (let i = 0; i < kernelSize; ++i) { - values[i] = gauss(i - halfWidth, sigma); - sum += values[i]; - } // normalize the kernel + if (UNSAFE_componentWillMountUniqueNames.size > 0) { + var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); + error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames); + } - for (let i = 0; i < kernelSize; ++i) values[i] /= sum; + if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { + var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames); - return values; - } -}); + error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames); + } -/*********************************/ + if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { + var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames); -/********** INTERPOLATION ********/ + error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2); + } -/*********************************/ -// Spline Interpolation -// Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation + if (componentWillMountUniqueNames.size > 0) { + var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); + warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3); + } -class GLTFCubicSplineInterpolant extends Interpolant { - constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { - super(parameterPositions, sampleValues, sampleSize, resultBuffer); - } + if (componentWillReceivePropsUniqueNames.size > 0) { + var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames); - copySampleValue_(index) { - // Copies a sample value to the result buffer. See description of glTF - // CUBICSPLINE values layout in interpolate_() function below. - const result = this.resultBuffer, - values = this.sampleValues, - valueSize = this.valueSize, - offset = index * valueSize * 3 + valueSize; + warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4); + } - for (let i = 0; i !== valueSize; i++) { - result[i] = values[offset + i]; - } + if (componentWillUpdateUniqueNames.size > 0) { + var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); - return result; - } + warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5); + } + }; -} + var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. -GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; -GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; + var didWarnAboutLegacyContext = new Set(); -GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) { - const result = this.resultBuffer; - const values = this.sampleValues; - const stride = this.valueSize; - const stride2 = stride * 2; - const stride3 = stride * 3; - const td = t1 - t0; - const p = (t - t0) / td; - const pp = p * p; - const ppp = pp * p; - const offset1 = i1 * stride3; - const offset0 = offset1 - stride3; - const s2 = -2 * ppp + 3 * pp; - const s3 = ppp - pp; - const s0 = 1 - s2; - const s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations: - // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] + ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) { + var strictRoot = findStrictRoot(fiber); - for (let i = 0; i !== stride; i++) { - const p0 = values[offset0 + i + stride]; // splineVertex_k + if (strictRoot === null) { + error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.'); - const m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k) + return; + } // Dedup strategy: Warn once per component. - const p1 = values[offset1 + i + stride]; // splineVertex_k+1 - const m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k) + if (didWarnAboutLegacyContext.has(fiber.type)) { + return; + } - result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; - } + var warningsForRoot = pendingLegacyContextWarning.get(strictRoot); - return result; -}; + if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') { + if (warningsForRoot === undefined) { + warningsForRoot = []; + pendingLegacyContextWarning.set(strictRoot, warningsForRoot); + } -new Quaternion(); + warningsForRoot.push(fiber); + } + }; -new Vector3(0, 1, 0); -new Vector3(0, 0, 1); + ReactStrictModeWarnings.flushLegacyContextWarning = function () { + pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) { + if (fiberArray.length === 0) { + return; + } -class VRButton { - static createButton(renderer, sessionInit = {}) { - const button = document.createElement('button'); + var firstFiber = fiberArray[0]; + var uniqueNames = new Set(); + fiberArray.forEach(function (fiber) { + uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); + didWarnAboutLegacyContext.add(fiber.type); + }); + var sortedNames = setToSortedString(uniqueNames); - function - /*device*/ - showEnterVR() { - let currentSession = null; + try { + setCurrentFiber(firstFiber); - async function onSessionStarted(session) { - session.addEventListener('end', onSessionEnded); - await renderer.xr.setSession(session); - button.textContent = 'EXIT VR'; - currentSession = session; - } + error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames); + } finally { + resetCurrentFiber(); + } + }); + }; - function - /*event*/ - onSessionEnded() { - currentSession.removeEventListener('end', onSessionEnded); - button.textContent = 'ENTER VR'; - currentSession = null; - } // + ReactStrictModeWarnings.discardPendingWarnings = function () { + pendingComponentWillMountWarnings = []; + pendingUNSAFE_ComponentWillMountWarnings = []; + pendingComponentWillReceivePropsWarnings = []; + pendingUNSAFE_ComponentWillReceivePropsWarnings = []; + pendingComponentWillUpdateWarnings = []; + pendingUNSAFE_ComponentWillUpdateWarnings = []; + pendingLegacyContextWarning = new Map(); + }; + } + /* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ + // $FlowFixMe only called in DEV, so void return is not possible. + function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } + } // $FlowFixMe only called in DEV, so void return is not possible. - button.style.display = ''; - button.style.cursor = 'pointer'; - button.style.left = 'calc(50% - 50px)'; - button.style.width = '100px'; - button.textContent = 'ENTER VR'; - button.onmouseenter = () => { - button.style.opacity = '1.0'; - }; + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } - button.onmouseleave = () => { - button.style.opacity = '0.5'; - }; + function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); - button.onclick = () => { - if (currentSession === null) { - var _xr; - - // WebXR's requestReferenceSpace only works if the corresponding feature - // was requested at session creation time. For simplicity, just ask for - // the interesting ones as optional features, but be aware that the - // requestReferenceSpace call will fail if it turns out to be unavailable. - // ('local' is always available for immersive sessions and doesn't need to - // be requested separately.) - const optionalFeatures = [sessionInit.optionalFeatures, 'local-floor', 'bounded-floor', 'hand-tracking'].flat().filter(Boolean); - (_xr = navigator.xr) === null || _xr === void 0 ? void 0 : _xr.requestSession('immersive-vr', { ...sessionInit, - optionalFeatures - }).then(onSessionStarted); - } else { - currentSession.end(); - } - }; - } + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } + } + function checkPropStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); - function disableButton() { - button.style.display = ''; - button.style.cursor = 'auto'; - button.style.left = 'calc(50% - 75px)'; - button.style.width = '150px'; - button.onmouseenter = null; - button.onmouseleave = null; - button.onclick = null; - } + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } + } - function showWebXRNotFound() { - disableButton(); - button.textContent = 'VR NOT SUPPORTED'; - } + function resolveDefaultProps(Component, baseProps) { + if (Component && Component.defaultProps) { + // Resolve default props. Taken from ReactElement + var props = assign({}, baseProps); + var defaultProps = Component.defaultProps; - function stylizeElement(element) { - element.style.position = 'absolute'; - element.style.bottom = '20px'; - element.style.padding = '12px 6px'; - element.style.border = '1px solid #fff'; - element.style.borderRadius = '4px'; - element.style.background = 'rgba(0,0,0,0.1)'; - element.style.color = '#fff'; - element.style.font = 'normal 13px sans-serif'; - element.style.textAlign = 'center'; - element.style.opacity = '0.5'; - element.style.outline = 'none'; - element.style.zIndex = '999'; - } + for (var propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } - if ('xr' in navigator) { - stylizeElement(button); - button.id = 'VRButton'; - button.style.display = 'none' // Query for session mode - ; - navigator.xr.isSessionSupported('immersive-vr').then(supported => { - supported ? showEnterVR() : showWebXRNotFound(); + return props; + } - if (supported && VRButton.xrSessionIsGranted) { - button.click(); - } - }); - return button; - } else { - const message = document.createElement('a'); + return baseProps; + } - if (window.isSecureContext === false) { - message.href = document.location.href.replace(/^http:/, 'https:'); - message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message - } else { - message.href = 'https://immersiveweb.dev/'; - message.innerHTML = 'WEBXR NOT AVAILABLE'; - } + var valueCursor = createCursor(null); + var rendererSigil; - message.style.left = 'calc(50% - 90px)'; - message.style.width = '180px'; - message.style.textDecoration = 'none'; - stylizeElement(message); - return message; - } - } + { + // Use this to detect multiple renderers using the same context + rendererSigil = {}; + } - static registerSessionGrantedListener() { - if ('xr' in navigator) { - navigator.xr.addEventListener('sessiongranted', () => { - VRButton.xrSessionIsGranted = true; - }); - } - } + var currentlyRenderingFiber = null; + var lastContextDependency = null; + var lastFullyObservedContext = null; + var isDisallowedContextReadInDEV = false; + function resetContextDependencies() { + // This is called right before React yields execution, to ensure `readContext` + // cannot be called outside the render phase. + currentlyRenderingFiber = null; + lastContextDependency = null; + lastFullyObservedContext = null; -} + { + isDisallowedContextReadInDEV = false; + } + } + function enterDisallowedContextReadInDEV() { + { + isDisallowedContextReadInDEV = true; + } + } + function exitDisallowedContextReadInDEV() { + { + isDisallowedContextReadInDEV = false; + } + } + function pushProvider(providerFiber, context, nextValue) { + if (isPrimaryRenderer) { + push(valueCursor, context._currentValue, providerFiber); + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } -_defineProperty$1(VRButton, "xrSessionIsGranted", false); + context._currentRenderer = rendererSigil; + } + } else { + push(valueCursor, context._currentValue2, providerFiber); + context._currentValue2 = nextValue; -/** - * @webxr-input-profiles/motion-controllers 1.0.0 https://github.com/immersive-web/webxr-input-profiles - */ -const MotionControllerConstants = { - Handedness: Object.freeze({ - NONE: 'none', - LEFT: 'left', - RIGHT: 'right' - }), - ComponentState: Object.freeze({ - DEFAULT: 'default', - TOUCHED: 'touched', - PRESSED: 'pressed' - }), - ComponentProperty: Object.freeze({ - BUTTON: 'button', - X_AXIS: 'xAxis', - Y_AXIS: 'yAxis', - STATE: 'state' - }), - ComponentType: Object.freeze({ - TRIGGER: 'trigger', - SQUEEZE: 'squeeze', - TOUCHPAD: 'touchpad', - THUMBSTICK: 'thumbstick', - BUTTON: 'button' - }), - ButtonTouchThreshold: 0.05, - AxisTouchThreshold: 0.1, - VisualResponseProperty: Object.freeze({ - TRANSFORM: 'transform', - VISIBILITY: 'visibility' - }) -}; -/** @constant {Object} */ + { + if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + context._currentRenderer2 = rendererSigil; + } + } + } + function popProvider(context, providerFiber) { + var currentValue = valueCursor.current; + pop(valueCursor, providerFiber); -({ - xAxis: 0, - yAxis: 0, - button: 0, - state: MotionControllerConstants.ComponentState.DEFAULT -}); + if (isPrimaryRenderer) { + { + context._currentValue = currentValue; + } + } else { + { + context._currentValue2 = currentValue; + } + } + } + function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { + // Update the child lanes of all the ancestors, including the alternates. + var node = parent; -new Matrix4(); + while (node !== null) { + var alternate = node.alternate; -new Vector3(); + if (!isSubsetOfLanes(node.childLanes, renderLanes)) { + node.childLanes = mergeLanes(node.childLanes, renderLanes); -/** - * Experimenting of primitive geometry creation using Surface Parametric equations - */ + if (alternate !== null) { + alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); + } + } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) { + alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); + } -const ParametricGeometries = { - klein: function (v, u, target) { - u *= Math.PI; - v *= 2 * Math.PI; - u = u * 2; - let x, y, z; + if (node === propagationRoot) { + break; + } - if (u < Math.PI) { - x = 3 * Math.cos(u) * (1 + Math.sin(u)) + 2 * (1 - Math.cos(u) / 2) * Math.cos(u) * Math.cos(v); - z = -8 * Math.sin(u) - 2 * (1 - Math.cos(u) / 2) * Math.sin(u) * Math.cos(v); - } else { - x = 3 * Math.cos(u) * (1 + Math.sin(u)) + 2 * (1 - Math.cos(u) / 2) * Math.cos(v + Math.PI); - z = -8 * Math.sin(u); - } + node = node.return; + } - y = -2 * (1 - Math.cos(u) / 2) * Math.sin(v); - target.set(x, y, z); - }, - plane: function (width, height) { - return (u, v, target) => { - const x = u * width; - const y = 0; - const z = v * height; - target.set(x, y, z); - }; - }, - mobius: function (u, t, target) { - // flat mobius strip - // http://www.wolframalpha.com/input/?i=M%C3%B6bius+strip+parametric+equations&lk=1&a=ClashPrefs_*Surface.MoebiusStrip.SurfaceProperty.ParametricEquations- - u = u - 0.5; - const v = 2 * Math.PI * t; - let x, y, z; - const a = 2; - x = Math.cos(v) * (a + u * Math.cos(v / 2)); - y = Math.sin(v) * (a + u * Math.cos(v / 2)); - z = u * Math.sin(v / 2); - target.set(x, y, z); - }, - mobius3d: function (u, t, target) { - // volumetric mobius strip - u *= Math.PI; - t *= 2 * Math.PI; - u = u * 2; - const phi = u / 2; - const major = 2.25, - a = 0.125, - b = 0.65; - let x, y, z; - x = a * Math.cos(t) * Math.cos(phi) - b * Math.sin(t) * Math.sin(phi); - z = a * Math.cos(t) * Math.sin(phi) + b * Math.sin(t) * Math.cos(phi); - y = (major + x) * Math.sin(u); - x = (major + x) * Math.cos(u); - target.set(x, y, z); - } -}; -/********************************************* - * - * Parametric Replacement for TubeGeometry - * - *********************************************/ - -ParametricGeometries.TubeGeometry = function (path, segments, radius, segmentsRadius, closed) { - this.path = path; - this.segments = segments || 64; - this.radius = radius || 1; - this.segmentsRadius = segmentsRadius || 8; - this.closed = closed || false; - const scope = this, - numpoints = this.segments + 1; - const frames = path.computeFrenetFrames(segments, closed), - tangents = frames.tangents, - normals = frames.normals, - binormals = frames.binormals; // proxy internals - - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; - const position = new Vector3(); - - const ParametricTube = (u, v, target) => { - v *= 2 * Math.PI; - let i = u * (numpoints - 1); - i = Math.floor(i); - path.getPointAt(u, position); - const normal = normals[i]; - const binormal = binormals[i]; - const cx = -scope.radius * Math.cos(v); // TODO: Hack: Negating it so it faces outside. - - const cy = scope.radius * Math.sin(v); - position.x += cx * normal.x + cy * binormal.x; - position.y += cx * normal.y + cy * binormal.y; - position.z += cx * normal.z + cy * binormal.z; - target.copy(position); - }; + { + if (node !== propagationRoot) { + error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } + } + } + function propagateContextChange(workInProgress, context, renderLanes) { + { + propagateContextChange_eager(workInProgress, context, renderLanes); + } + } - ParametricGeometry.call(this, ParametricTube, segments, segmentsRadius); -}; + function propagateContextChange_eager(workInProgress, context, renderLanes) { -ParametricGeometries.TubeGeometry.prototype = Object.create(BufferGeometry.prototype); -ParametricGeometries.TubeGeometry.prototype.constructor = ParametricGeometries.TubeGeometry; -/********************************************* - * - * Parametric Replacement for TorusKnotGeometry - * - *********************************************/ + var fiber = workInProgress.child; -ParametricGeometries.TorusKnotGeometry = function (radius, tube, segmentsT, segmentsR, p, q) { - this.radius = radius || 200; - this.tube = tube || 40; - this.segmentsT = segmentsT || 64; - this.segmentsR = segmentsR || 8; - this.p = p || 2; - this.q = q || 3; + if (fiber !== null) { + // Set the return pointer of the child to the work-in-progress fiber. + fiber.return = workInProgress; + } - class TorusKnotCurve extends Curve { - constructor() { - super(); - } + while (fiber !== null) { + var nextFiber = void 0; // Visit this fiber. - getPoint(t, optionalTarget) { - const point = optionalTarget || new Vector3(); - t *= Math.PI * 2; - const r = 0.5; - const x = (1 + r * Math.cos(q * t)) * Math.cos(p * t); - const y = (1 + r * Math.cos(q * t)) * Math.sin(p * t); - const z = r * Math.sin(q * t); - return point.set(x, y, z).multiplyScalar(radius); - } + var list = fiber.dependencies; - } + if (list !== null) { + nextFiber = fiber.child; + var dependency = list.firstContext; - const segments = segmentsT; - const radiusSegments = segmentsR; - const extrudePath = new TorusKnotCurve(); - ParametricGeometries.TubeGeometry.call(this, extrudePath, segments, tube, radiusSegments, true, false); -}; + while (dependency !== null) { + // Check if the context matches. + if (dependency.context === context) { + // Match! Schedule an update on this fiber. + if (fiber.tag === ClassComponent) { + // Schedule a force update on the work-in-progress. + var lane = pickArbitraryLane(renderLanes); + var update = createUpdate(NoTimestamp, lane); + update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the + // update to the current fiber, too, which means it will persist even if + // this render is thrown away. Since it's a race condition, not sure it's + // worth fixing. + // Inlined `enqueueUpdate` to remove interleaved update check -ParametricGeometries.TorusKnotGeometry.prototype = Object.create(BufferGeometry.prototype); -ParametricGeometries.TorusKnotGeometry.prototype.constructor = ParametricGeometries.TorusKnotGeometry; -/********************************************* - * - * Parametric Replacement for SphereGeometry - * - *********************************************/ + var updateQueue = fiber.updateQueue; -ParametricGeometries.SphereGeometry = function (size, u, v) { - function sphere(u, v, target) { - u *= Math.PI; - v *= 2 * Math.PI; - const x = size * Math.sin(u) * Math.cos(v); - const y = size * Math.sin(u) * Math.sin(v); - const z = size * Math.cos(u); - target.set(x, y, z); - } + if (updateQueue === null) ; else { + var sharedQueue = updateQueue.shared; + var pending = sharedQueue.pending; - ParametricGeometry.call(this, sphere, u, v); -}; + if (pending === null) { + // This is the first update. Create a circular list. + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } -ParametricGeometries.SphereGeometry.prototype = Object.create(BufferGeometry.prototype); -ParametricGeometries.SphereGeometry.prototype.constructor = ParametricGeometries.SphereGeometry; -/********************************************* - * - * Parametric Replacement for PlaneGeometry - * - *********************************************/ + sharedQueue.pending = update; + } + } -ParametricGeometries.PlaneGeometry = function (width, depth, segmentsWidth, segmentsDepth) { - function plane(u, v, target) { - const x = u * width; - const y = 0; - const z = v * depth; - target.set(x, y, z); - } + fiber.lanes = mergeLanes(fiber.lanes, renderLanes); + var alternate = fiber.alternate; - ParametricGeometry.call(this, plane, segmentsWidth, segmentsDepth); -}; + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, renderLanes); + } -ParametricGeometries.PlaneGeometry.prototype = Object.create(BufferGeometry.prototype); -ParametricGeometries.PlaneGeometry.prototype.constructor = ParametricGeometries.PlaneGeometry; + scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too. -new Vector3(); + list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the + // dependency list. -const inverseProjectionMatrix = new Matrix4(); -class Frustum { - constructor(data) { - data = data || {}; - this.vertices = { - near: [new Vector3(), new Vector3(), new Vector3(), new Vector3()], - far: [new Vector3(), new Vector3(), new Vector3(), new Vector3()] - }; + break; + } - if (data.projectionMatrix !== undefined) { - this.setFromProjectionMatrix(data.projectionMatrix, data.maxFar || 10000); - } - } + dependency = dependency.next; + } + } else if (fiber.tag === ContextProvider) { + // Don't scan deeper if this is a matching provider + nextFiber = fiber.type === workInProgress.type ? null : fiber.child; + } else if ( fiber.tag === DehydratedFragment) { + // If a dehydrated suspense boundary is in this subtree, we don't know + // if it will have any context consumers in it. The best we can do is + // mark it as having updates. + var parentSuspense = fiber.return; - setFromProjectionMatrix(projectionMatrix, maxFar) { - const isOrthographic = projectionMatrix.elements[2 * 4 + 3] === 0; - inverseProjectionMatrix.copy(projectionMatrix).invert(); // 3 --- 0 vertices.near/far order - // | | - // 2 --- 1 - // clip space spans from [-1, 1] + if (parentSuspense === null) { + throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.'); + } - this.vertices.near[0].set(1, 1, -1); - this.vertices.near[1].set(1, -1, -1); - this.vertices.near[2].set(-1, -1, -1); - this.vertices.near[3].set(-1, 1, -1); - this.vertices.near.forEach(v => { - v.applyMatrix4(inverseProjectionMatrix); - }); - this.vertices.far[0].set(1, 1, 1); - this.vertices.far[1].set(1, -1, 1); - this.vertices.far[2].set(-1, -1, 1); - this.vertices.far[3].set(-1, 1, 1); - this.vertices.far.forEach(v => { - v.applyMatrix4(inverseProjectionMatrix); - const absZ = Math.abs(v.z); - - if (isOrthographic) { - v.z *= Math.min(maxFar / absZ, 1.0); - } else { - v.multiplyScalar(Math.min(maxFar / absZ, 1.0)); - } - }); - return this.vertices; - } + parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); + var _alternate = parentSuspense.alternate; - split(breaks, target) { - while (breaks.length > target.length) { - target.push(new Frustum()); - } + if (_alternate !== null) { + _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes); + } // This is intentionally passing this fiber as the parent + // because we want to schedule this fiber as having work + // on its children. We'll use the childLanes on + // this fiber to indicate that a context has changed. - target.length = breaks.length; - for (let i = 0; i < breaks.length; i++) { - const cascade = target[i]; + scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress); + nextFiber = fiber.sibling; + } else { + // Traverse down. + nextFiber = fiber.child; + } - if (i === 0) { - for (let j = 0; j < 4; j++) { - cascade.vertices.near[j].copy(this.vertices.near[j]); - } - } else { - for (let j = 0; j < 4; j++) { - cascade.vertices.near[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i - 1]); - } - } + if (nextFiber !== null) { + // Set the return pointer of the child to the work-in-progress fiber. + nextFiber.return = fiber; + } else { + // No child. Traverse to next sibling. + nextFiber = fiber; - if (i === breaks - 1) { - for (let j = 0; j < 4; j++) { - cascade.vertices.far[j].copy(this.vertices.far[j]); - } - } else { - for (let j = 0; j < 4; j++) { - cascade.vertices.far[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i]); - } - } - } - } + while (nextFiber !== null) { + if (nextFiber === workInProgress) { + // We're back to the root of this subtree. Exit. + nextFiber = null; + break; + } - toSpace(cameraMatrix, target) { - for (let i = 0; i < 4; i++) { - target.vertices.near[i].copy(this.vertices.near[i]).applyMatrix4(cameraMatrix); - target.vertices.far[i].copy(this.vertices.far[i]).applyMatrix4(cameraMatrix); - } - } + var sibling = nextFiber.sibling; -} + if (sibling !== null) { + // Set the return pointer of the sibling to the work-in-progress fiber. + sibling.return = nextFiber.return; + nextFiber = sibling; + break; + } // No more siblings. Traverse up. -({ - lights_fragment_begin: - /* glsl */ - ` -GeometricContext geometry; -geometry.position = - vViewPosition; -geometry.normal = normal; -geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + nextFiber = nextFiber.return; + } + } -#ifdef CLEARCOAT + fiber = nextFiber; + } + } + function prepareToReadContext(workInProgress, renderLanes) { + currentlyRenderingFiber = workInProgress; + lastContextDependency = null; + lastFullyObservedContext = null; + var dependencies = workInProgress.dependencies; - geometry.clearcoatNormal = clearcoatNormal; + if (dependencies !== null) { + { + var firstContext = dependencies.firstContext; -#endif + if (firstContext !== null) { + if (includesSomeLane(dependencies.lanes, renderLanes)) { + // Context list has a pending update. Mark that this fiber performed work. + markWorkInProgressReceivedUpdate(); + } // Reset the work-in-progress list -IncidentLight directLight; -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + dependencies.firstContext = null; + } + } + } + } + function readContext(context) { + { + // This warning would fire if you read context inside a Hook like useMemo. + // Unlike the class check below, it's not enforced in production for perf. + if (isDisallowedContextReadInDEV) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif + var value = isPrimaryRenderer ? context._currentValue : context._currentValue2; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + if (lastFullyObservedContext === context) ; else { + var contextItem = { + context: context, + memoizedValue: value, + next: null + }; - pointLight = pointLights[ i ]; + if (lastContextDependency === null) { + if (currentlyRenderingFiber === null) { + throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } // This is the first dependency for this component. Create a new list. - getPointLightInfo( pointLight, geometry, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif + lastContextDependency = contextItem; + currentlyRenderingFiber.dependencies = { + lanes: NoLanes, + firstContext: contextItem + }; + } else { + // Append a new context item. + lastContextDependency = lastContextDependency.next = contextItem; + } + } - RE_Direct( directLight, geometry, material, reflectedLight ); + return value; + } + // An array of all update queues that received updates during the current + // render. When this render exits, either because it finishes or because it is + // interrupted, the interleaved updates will be transferred onto the main part + // of the queue. + var interleavedQueues = null; + function pushInterleavedQueue(queue) { + if (interleavedQueues === null) { + interleavedQueues = [queue]; + } else { + interleavedQueues.push(queue); + } } - #pragma unroll_loop_end + function enqueueInterleavedUpdates() { + // Transfer the interleaved updates onto the main queue. Each queue has a + // `pending` field and an `interleaved` field. When they are not null, they + // point to the last node in a circular linked list. We need to append the + // interleaved list to the end of the pending list by joining them into a + // single, circular list. + if (interleavedQueues !== null) { + for (var i = 0; i < interleavedQueues.length; i++) { + var queue = interleavedQueues[i]; + var lastInterleavedUpdate = queue.interleaved; -#endif + if (lastInterleavedUpdate !== null) { + queue.interleaved = null; + var firstInterleavedUpdate = lastInterleavedUpdate.next; + var lastPendingUpdate = queue.pending; -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + if (lastPendingUpdate !== null) { + var firstPendingUpdate = lastPendingUpdate.next; + lastPendingUpdate.next = firstInterleavedUpdate; + lastInterleavedUpdate.next = firstPendingUpdate; + } - SpotLight spotLight; - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif + queue.pending = lastInterleavedUpdate; + } + } - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + interleavedQueues = null; + } + } - spotLight = spotLights[ i ]; + var UpdateState = 0; + var ReplaceState = 1; + var ForceUpdate = 2; + var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. + // It should only be read right after calling `processUpdateQueue`, via + // `checkHasForceUpdateAfterProcessing`. - getSpotLightInfo( spotLight, geometry, directLight ); + var hasForceUpdate = false; + var didWarnUpdateInsideUpdate; + var currentlyProcessingQueue; - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; - #endif + { + didWarnUpdateInsideUpdate = false; + currentlyProcessingQueue = null; + } - RE_Direct( directLight, geometry, material, reflectedLight ); + function initializeUpdateQueue(fiber) { + var queue = { + baseState: fiber.memoizedState, + firstBaseUpdate: null, + lastBaseUpdate: null, + shared: { + pending: null, + interleaved: null, + lanes: NoLanes + }, + effects: null + }; + fiber.updateQueue = queue; + } + function cloneUpdateQueue(current, workInProgress) { + // Clone the update queue from current. Unless it's already a clone. + var queue = workInProgress.updateQueue; + var currentQueue = current.updateQueue; + if (queue === currentQueue) { + var clone = { + baseState: currentQueue.baseState, + firstBaseUpdate: currentQueue.firstBaseUpdate, + lastBaseUpdate: currentQueue.lastBaseUpdate, + shared: currentQueue.shared, + effects: currentQueue.effects + }; + workInProgress.updateQueue = clone; + } } - #pragma unroll_loop_end + function createUpdate(eventTime, lane) { + var update = { + eventTime: eventTime, + lane: lane, + tag: UpdateState, + payload: null, + callback: null, + next: null + }; + return update; + } + function enqueueUpdate(fiber, update, lane) { + var updateQueue = fiber.updateQueue; -#endif + if (updateQueue === null) { + // Only occurs if the fiber has been unmounted. + return; + } -#if ( NUM_DIR_LIGHTS > 0) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES ) + var sharedQueue = updateQueue.shared; - DirectionalLight directionalLight; - float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear); - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif + if (isInterleavedUpdate(fiber)) { + var interleaved = sharedQueue.interleaved; - #if defined( USE_SHADOWMAP ) && defined( CSM_FADE ) - vec2 cascade; - float cascadeCenter; - float closestEdge; - float margin; - float csmx; - float csmy; + if (interleaved === null) { + // This is the first update. Create a circular list. + update.next = update; // At the end of the current render, this queue's interleaved updates will + // be transferred to the pending queue. - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + pushInterleavedQueue(sharedQueue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, geometry, directLight ); + sharedQueue.interleaved = update; + } else { + var pending = sharedQueue.pending; - // NOTE: Depth gets larger away from the camera. - // cascade.x is closer, cascade.y is further - cascade = CSM_cascades[ i ]; - cascadeCenter = ( cascade.x + cascade.y ) / 2.0; - closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; - margin = 0.25 * pow( closestEdge, 2.0 ); - csmx = cascade.x - margin / 2.0; - csmy = cascade.y + margin / 2.0; - if( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS && linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) { + if (pending === null) { + // This is the first update. Create a circular list. + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } - float dist = min( linearDepth - csmx, csmy - linearDepth ); - float ratio = clamp( dist / margin, 0.0, 1.0 ); - if( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) { + sharedQueue.pending = update; + } - vec3 prevColor = directLight.color; - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + { + if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) { + error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); - bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter; - directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); + didWarnUpdateInsideUpdate = true; + } + } + } + function entangleTransitions(root, fiber, lane) { + var updateQueue = fiber.updateQueue; - } + if (updateQueue === null) { + // Only occurs if the fiber has been unmounted. + return; + } - ReflectedLight prevLight = reflectedLight; - RE_Direct( directLight, geometry, material, reflectedLight ); + var sharedQueue = updateQueue.shared; - bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter; - float blendRatio = shouldBlend ? ratio : 1.0; + if (isTransitionLane(lane)) { + var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must + // have finished. We can remove them from the shared queue, which represents + // a superset of the actually pending lanes. In some cases we may entangle + // more than we need to, but that's OK. In fact it's worse if we *don't* + // entangle when we should. - reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); - reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio ); - reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio ); - reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio ); + queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. - } + var newQueueLanes = mergeLanes(queueLanes, lane); + sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if + // the lane finished since the last time we entangled it. So we need to + // entangle it again, just to be sure. + markRootEntangled(root, newQueueLanes); + } } - #pragma unroll_loop_end - #else - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, geometry, directLight ); - - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - - directionalLightShadow = directionalLightShadows[ i ]; - if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + function enqueueCapturedUpdate(workInProgress, capturedUpdate) { + // Captured updates are updates that are thrown by a child during the render + // phase. They should be discarded if the render is aborted. Therefore, + // we should only put them on the work-in-progress queue, not the current one. + var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone. - #endif + var current = workInProgress.alternate; - if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometry, material, reflectedLight ); + if (current !== null) { + var currentQueue = current.updateQueue; - } - #pragma unroll_loop_end + if (queue === currentQueue) { + // The work-in-progress queue is the same as current. This happens when + // we bail out on a parent fiber that then captures an error thrown by + // a child. Since we want to append the update only to the work-in + // -progress queue, we need to clone the updates. We usually clone during + // processUpdateQueue, but that didn't happen in this case because we + // skipped over the parent when we bailed out. + var newFirst = null; + var newLast = null; + var firstBaseUpdate = queue.firstBaseUpdate; - #endif + if (firstBaseUpdate !== null) { + // Loop through the updates and clone them. + var update = firstBaseUpdate; -#endif + do { + var clone = { + eventTime: update.eventTime, + lane: update.lane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; + if (newLast === null) { + newFirst = newLast = clone; + } else { + newLast.next = clone; + newLast = clone; + } -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES ) + update = update.next; + } while (update !== null); // Append the captured update the end of the cloned list. - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + if (newLast === null) { + newFirst = newLast = capturedUpdate; + } else { + newLast.next = capturedUpdate; + newLast = capturedUpdate; + } + } else { + // There are no base updates. + newFirst = newLast = capturedUpdate; + } - directionalLight = directionalLights[ i ]; + queue = { + baseState: currentQueue.baseState, + firstBaseUpdate: newFirst, + lastBaseUpdate: newLast, + shared: currentQueue.shared, + effects: currentQueue.effects + }; + workInProgress.updateQueue = queue; + return; + } + } // Append the update to the end of the list. - getDirectionalLightInfo( directionalLight, geometry, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif + var lastBaseUpdate = queue.lastBaseUpdate; - RE_Direct( directLight, geometry, material, reflectedLight ); + if (lastBaseUpdate === null) { + queue.firstBaseUpdate = capturedUpdate; + } else { + lastBaseUpdate.next = capturedUpdate; + } + queue.lastBaseUpdate = capturedUpdate; } - #pragma unroll_loop_end - -#endif -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) { + switch (update.tag) { + case ReplaceState: + { + var payload = update.payload; - RectAreaLight rectAreaLight; + if (typeof payload === 'function') { + // Updater function + { + enterDisallowedContextReadInDEV(); + } - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + var nextState = payload.call(instance, prevState, nextProps); - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight ); + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - } - #pragma unroll_loop_end + try { + payload.call(instance, prevState, nextProps); + } finally { + setIsStrictModeForDevtools(false); + } + } -#endif + exitDisallowedContextReadInDEV(); + } -#if defined( RE_IndirectDiffuse ) + return nextState; + } // State object - vec3 iblIrradiance = vec3( 0.0 ); - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + return payload; + } - irradiance += getLightProbeIrradiance( lightProbe, geometry.normal ); + case CaptureUpdate: + { + workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture; + } + // Intentional fallthrough - #if ( NUM_HEMI_LIGHTS > 0 ) + case UpdateState: + { + var _payload = update.payload; + var partialState; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + if (typeof _payload === 'function') { + // Updater function + { + enterDisallowedContextReadInDEV(); + } - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); + partialState = _payload.call(instance, prevState, nextProps); - } - #pragma unroll_loop_end + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - #endif + try { + _payload.call(instance, prevState, nextProps); + } finally { + setIsStrictModeForDevtools(false); + } + } -#endif + exitDisallowedContextReadInDEV(); + } + } else { + // Partial state object + partialState = _payload; + } -#if defined( RE_IndirectSpecular ) + if (partialState === null || partialState === undefined) { + // Null and undefined are treated as no-ops. + return prevState; + } // Merge the partial state and the previous state. - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); -#endif -`, - lights_pars_begin: - /* glsl */ - ` -#if defined( USE_CSM ) && defined( CSM_CASCADES ) -uniform vec2 CSM_cascades[CSM_CASCADES]; -uniform float cameraNear; -uniform float shadowFar; -#endif - ` + ShaderChunk.lights_pars_begin -}); + return assign({}, prevState, partialState); + } -new Matrix4(); + case ForceUpdate: + { + hasForceUpdate = true; + return prevState; + } + } -new Frustum(); + return prevState; + } -new Vector3(); + function processUpdateQueue(workInProgress, props, instance, renderLanes) { + // This is always non-null on a ClassComponent or HostRoot + var queue = workInProgress.updateQueue; + hasForceUpdate = false; -new Box3(); + { + currentlyProcessingQueue = queue.shared; + } -/** - * This is a class to check whether objects are in a selection area in 3D space - */ + var firstBaseUpdate = queue.firstBaseUpdate; + var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue. -(() => { - const frustum = new Frustum$1(); - const center = new Vector3(); - const tmpPoint = new Vector3(); - const vecNear = new Vector3(); - const vecTopLeft = new Vector3(); - const vecTopRight = new Vector3(); - const vecDownRight = new Vector3(); - const vecDownLeft = new Vector3(); - const vecFarTopLeft = new Vector3(); - const vecFarTopRight = new Vector3(); - const vecFarDownRight = new Vector3(); - const vecFarDownLeft = new Vector3(); - const vectemp1 = new Vector3(); - const vectemp2 = new Vector3(); - const vectemp3 = new Vector3(); - - class SelectionBox { - constructor(camera, scene, deep) { - this.camera = camera; - this.scene = scene; - this.startPoint = new Vector3(); - this.endPoint = new Vector3(); - this.collection = []; - this.deep = deep || Number.MAX_VALUE; - } + var pendingQueue = queue.shared.pending; - select(startPoint, endPoint) { - this.startPoint = startPoint || this.startPoint; - this.endPoint = endPoint || this.endPoint; - this.collection = []; - this.updateFrustum(this.startPoint, this.endPoint); - this.searchChildInFrustum(frustum, this.scene); - return this.collection; - } + if (pendingQueue !== null) { + queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first + // and last so that it's non-circular. - updateFrustum(startPoint, endPoint) { - startPoint = startPoint || this.startPoint; - endPoint = endPoint || this.endPoint; // Avoid invalid frustum + var lastPendingUpdate = pendingQueue; + var firstPendingUpdate = lastPendingUpdate.next; + lastPendingUpdate.next = null; // Append pending updates to base queue - if (startPoint.x === endPoint.x) { - endPoint.x += Number.EPSILON; - } + if (lastBaseUpdate === null) { + firstBaseUpdate = firstPendingUpdate; + } else { + lastBaseUpdate.next = firstPendingUpdate; + } - if (startPoint.y === endPoint.y) { - endPoint.y += Number.EPSILON; - } + lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then + // we need to transfer the updates to that queue, too. Because the base + // queue is a singly-linked list with no cycles, we can append to both + // lists and take advantage of structural sharing. + // TODO: Pass `current` as argument - this.camera.updateProjectionMatrix(); - this.camera.updateMatrixWorld(); - - if (this.camera.isPerspectiveCamera) { - tmpPoint.copy(startPoint); - tmpPoint.x = Math.min(startPoint.x, endPoint.x); - tmpPoint.y = Math.max(startPoint.y, endPoint.y); - endPoint.x = Math.max(startPoint.x, endPoint.x); - endPoint.y = Math.min(startPoint.y, endPoint.y); - vecNear.setFromMatrixPosition(this.camera.matrixWorld); - vecTopLeft.copy(tmpPoint); - vecTopRight.set(endPoint.x, tmpPoint.y, 0); - vecDownRight.copy(endPoint); - vecDownLeft.set(tmpPoint.x, endPoint.y, 0); - vecTopLeft.unproject(this.camera); - vecTopRight.unproject(this.camera); - vecDownRight.unproject(this.camera); - vecDownLeft.unproject(this.camera); - vectemp1.copy(vecTopLeft).sub(vecNear); - vectemp2.copy(vecTopRight).sub(vecNear); - vectemp3.copy(vecDownRight).sub(vecNear); - vectemp1.normalize(); - vectemp2.normalize(); - vectemp3.normalize(); - vectemp1.multiplyScalar(this.deep); - vectemp2.multiplyScalar(this.deep); - vectemp3.multiplyScalar(this.deep); - vectemp1.add(vecNear); - vectemp2.add(vecNear); - vectemp3.add(vecNear); - var planes = frustum.planes; - planes[0].setFromCoplanarPoints(vecNear, vecTopLeft, vecTopRight); - planes[1].setFromCoplanarPoints(vecNear, vecTopRight, vecDownRight); - planes[2].setFromCoplanarPoints(vecDownRight, vecDownLeft, vecNear); - planes[3].setFromCoplanarPoints(vecDownLeft, vecTopLeft, vecNear); - planes[4].setFromCoplanarPoints(vecTopRight, vecDownRight, vecDownLeft); - planes[5].setFromCoplanarPoints(vectemp3, vectemp2, vectemp1); - planes[5].normal.multiplyScalar(-1); - } else if (this.camera.isOrthographicCamera) { - const left = Math.min(startPoint.x, endPoint.x); - const top = Math.max(startPoint.y, endPoint.y); - const right = Math.max(startPoint.x, endPoint.x); - const down = Math.min(startPoint.y, endPoint.y); - vecTopLeft.set(left, top, -1); - vecTopRight.set(right, top, -1); - vecDownRight.set(right, down, -1); - vecDownLeft.set(left, down, -1); - vecFarTopLeft.set(left, top, 1); - vecFarTopRight.set(right, top, 1); - vecFarDownRight.set(right, down, 1); - vecFarDownLeft.set(left, down, 1); - vecTopLeft.unproject(this.camera); - vecTopRight.unproject(this.camera); - vecDownRight.unproject(this.camera); - vecDownLeft.unproject(this.camera); - vecFarTopLeft.unproject(this.camera); - vecFarTopRight.unproject(this.camera); - vecFarDownRight.unproject(this.camera); - vecFarDownLeft.unproject(this.camera); - var planes = frustum.planes; - planes[0].setFromCoplanarPoints(vecTopLeft, vecFarTopLeft, vecFarTopRight); - planes[1].setFromCoplanarPoints(vecTopRight, vecFarTopRight, vecFarDownRight); - planes[2].setFromCoplanarPoints(vecFarDownRight, vecFarDownLeft, vecDownLeft); - planes[3].setFromCoplanarPoints(vecFarDownLeft, vecFarTopLeft, vecTopLeft); - planes[4].setFromCoplanarPoints(vecTopRight, vecDownRight, vecDownLeft); - planes[5].setFromCoplanarPoints(vecFarDownRight, vecFarTopRight, vecFarTopLeft); - planes[5].normal.multiplyScalar(-1); - } else { - console.error('THREE.SelectionBox: Unsupported camera type.'); - } - } + var current = workInProgress.alternate; - searchChildInFrustum(frustum, object) { - if (object.isMesh || object.isLine || object.isPoints) { - if (object.material !== undefined) { - if (object.geometry.boundingSphere === null) object.geometry.computeBoundingSphere(); - center.copy(object.geometry.boundingSphere.center); - center.applyMatrix4(object.matrixWorld); + if (current !== null) { + // This is always non-null on a ClassComponent or HostRoot + var currentQueue = current.updateQueue; + var currentLastBaseUpdate = currentQueue.lastBaseUpdate; - if (frustum.containsPoint(center)) { - this.collection.push(object); - } - } - } + if (currentLastBaseUpdate !== lastBaseUpdate) { + if (currentLastBaseUpdate === null) { + currentQueue.firstBaseUpdate = firstPendingUpdate; + } else { + currentLastBaseUpdate.next = firstPendingUpdate; + } - if (object.children.length > 0) { - for (let x = 0; x < object.children.length; x++) { - this.searchChildInFrustum(frustum, object.children[x]); - } - } - } + currentQueue.lastBaseUpdate = lastPendingUpdate; + } + } + } // These values may change as we process the queue. - } - return SelectionBox; -})(); + if (firstBaseUpdate !== null) { + // Iterate through the list of updates to compute the result. + var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes + // from the original lanes. -new Euler(); -new Vector3(); // generate transformation from FBX transform data + var newLanes = NoLanes; + var newBaseState = null; + var newFirstBaseUpdate = null; + var newLastBaseUpdate = null; + var update = firstBaseUpdate; -class Font$1 { - constructor(data) { - _defineProperty$1(this, "data", void 0); + do { + var updateLane = update.lane; + var updateEventTime = update.eventTime; - this.data = data; - } + if (!isSubsetOfLanes(renderLanes, updateLane)) { + // Priority is insufficient. Skip this update. If this is the first + // skipped update, the previous update/state is the new base + // update/state. + var clone = { + eventTime: updateEventTime, + lane: updateLane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; - generateShapes(text, size = 100) { - const shapes = []; - const paths = createPaths(text, size, this.data); + if (newLastBaseUpdate === null) { + newFirstBaseUpdate = newLastBaseUpdate = clone; + newBaseState = newState; + } else { + newLastBaseUpdate = newLastBaseUpdate.next = clone; + } // Update the remaining priority in the queue. - for (let p = 0, pl = paths.length; p < pl; p++) { - Array.prototype.push.apply(shapes, paths[p].toShapes(false)); - } - return shapes; - } + newLanes = mergeLanes(newLanes, updateLane); + } else { + // This update does have sufficient priority. + if (newLastBaseUpdate !== null) { + var _clone = { + eventTime: updateEventTime, + // This update is going to be committed so we never want uncommit + // it. Using NoLane works because 0 is a subset of all bitmasks, so + // this will never be skipped by the check above. + lane: NoLane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; + newLastBaseUpdate = newLastBaseUpdate.next = _clone; + } // Process this update. -} -_defineProperty$1(Font$1, "isFont", void 0); + newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance); + var callback = update.callback; -_defineProperty$1(Font$1, "type", void 0); + if (callback !== null && // If the update was already committed, we should not queue its + // callback again. + update.lane !== NoLane) { + workInProgress.flags |= Callback; + var effects = queue.effects; -function createPaths(text, size, data) { - const chars = Array.from(text); - const scale = size / data.resolution; - const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale; - const paths = []; - let offsetX = 0, - offsetY = 0; + if (effects === null) { + queue.effects = [update]; + } else { + effects.push(update); + } + } + } - for (let i = 0; i < chars.length; i++) { - const char = chars[i]; + update = update.next; - if (char === '\n') { - offsetX = 0; - offsetY -= line_height; - } else { - const ret = createPath(char, scale, offsetX, offsetY, data); + if (update === null) { + pendingQueue = queue.shared.pending; - if (ret) { - offsetX += ret.offsetX; - paths.push(ret.path); - } - } - } + if (pendingQueue === null) { + break; + } else { + // An update was scheduled from inside a reducer. Add the new + // pending updates to the end of the list and keep processing. + var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we + // unravel them when transferring them to the base queue. - return paths; -} + var _firstPendingUpdate = _lastPendingUpdate.next; + _lastPendingUpdate.next = null; + update = _firstPendingUpdate; + queue.lastBaseUpdate = _lastPendingUpdate; + queue.shared.pending = null; + } + } + } while (true); -function createPath(char, scale, offsetX, offsetY, data) { - const glyph = data.glyphs[char] || data.glyphs['?']; + if (newLastBaseUpdate === null) { + newBaseState = newState; + } - if (!glyph) { - console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.'); - return; - } + queue.baseState = newBaseState; + queue.firstBaseUpdate = newFirstBaseUpdate; + queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to + // process them during this render, but we do need to track which lanes + // are remaining. - const path = new ShapePath(); - let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; + var lastInterleaved = queue.shared.interleaved; - if (glyph.o) { - const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' ')); + if (lastInterleaved !== null) { + var interleaved = lastInterleaved; - for (let i = 0, l = outline.length; i < l;) { - const action = outline[i++]; + do { + newLanes = mergeLanes(newLanes, interleaved.lane); + interleaved = interleaved.next; + } while (interleaved !== lastInterleaved); + } else if (firstBaseUpdate === null) { + // `queue.lanes` is used for entangling transitions. We can set it back to + // zero once the queue is empty. + queue.shared.lanes = NoLanes; + } // Set the remaining expiration time to be whatever is remaining in the queue. + // This should be fine because the only two other things that contribute to + // expiration time are props and context. We're already in the middle of the + // begin phase by the time we start processing the queue, so we've already + // dealt with the props. Context in components that specify + // shouldComponentUpdate is tricky; but we'll have to account for + // that regardless. - switch (action) { - case 'm': - // moveTo - x = parseInt(outline[i++]) * scale + offsetX; - y = parseInt(outline[i++]) * scale + offsetY; - path.moveTo(x, y); - break; - case 'l': - // lineTo - x = parseInt(outline[i++]) * scale + offsetX; - y = parseInt(outline[i++]) * scale + offsetY; - path.lineTo(x, y); - break; + markSkippedUpdateLanes(newLanes); + workInProgress.lanes = newLanes; + workInProgress.memoizedState = newState; + } - case 'q': - // quadraticCurveTo - cpx = parseInt(outline[i++]) * scale + offsetX; - cpy = parseInt(outline[i++]) * scale + offsetY; - cpx1 = parseInt(outline[i++]) * scale + offsetX; - cpy1 = parseInt(outline[i++]) * scale + offsetY; - path.quadraticCurveTo(cpx1, cpy1, cpx, cpy); - break; + { + currentlyProcessingQueue = null; + } + } - case 'b': - // bezierCurveTo - cpx = parseInt(outline[i++]) * scale + offsetX; - cpy = parseInt(outline[i++]) * scale + offsetY; - cpx1 = parseInt(outline[i++]) * scale + offsetX; - cpy1 = parseInt(outline[i++]) * scale + offsetY; - cpx2 = parseInt(outline[i++]) * scale + offsetX; - cpy2 = parseInt(outline[i++]) * scale + offsetY; - path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy); - break; - } - } - } + function callCallback(callback, context) { + if (typeof callback !== 'function') { + throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback)); + } - return { - offsetX: glyph.ha * scale, - path - }; -} + callback.call(context); + } -(function () { - var classCallCheck = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError('Cannot call a class as a function'); - } - }; + function resetHasForceUpdateBeforeProcessing() { + hasForceUpdate = false; + } + function checkHasForceUpdateAfterProcessing() { + return hasForceUpdate; + } + function commitUpdateQueue(finishedWork, finishedQueue, instance) { + // Commit the effects + var effects = finishedQueue.effects; + finishedQueue.effects = null; - var createClass = function () { - function defineProperties(target, props) { - for (let i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ('value' in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } + if (effects !== null) { + for (var i = 0; i < effects.length; i++) { + var effect = effects[i]; + var callback = effect.callback; - return function (Constructor, protoProps, staticProps) { - if (protoProps) defineProperties(Constructor.prototype, protoProps); - if (staticProps) defineProperties(Constructor, staticProps); - return Constructor; - }; - }(); - - var XboneInf = function XboneInf() { - classCallCheck(this, XboneInf); - this.boneName = ''; - this.BoneIndex = 0; - this.Indeces = []; - this.Weights = []; - this.initMatrix = null; - this.OffsetMatrix = null; - }; + if (callback !== null) { + effect.callback = null; + callCallback(callback, instance); + } + } + } + } - var XAnimationInfo = function XAnimationInfo() { - classCallCheck(this, XAnimationInfo); - this.animeName = ''; - this.boneName = ''; - this.targetBone = null; - this.keyType = 4; - this.frameStartLv = 0; - this.keyFrames = []; - this.InverseMx = null; - }; + var fakeInternalInstance = {}; // React.Component uses a shared frozen object by default. + // We'll use it to determine whether we need to initialize legacy refs. - var XAnimationObj = function () { - function XAnimationObj(_flags) { - classCallCheck(this, XAnimationObj); - this.fps = 30; - this.name = 'xanimation'; - this.length = 0; - this.hierarchy = []; - this.putFlags = _flags; - - if (this.putFlags.putPos === undefined) { - this.putFlags.putPos = true; - } + var emptyRefsObject = new React.Component().refs; + var didWarnAboutStateAssignmentForComponent; + var didWarnAboutUninitializedState; + var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; + var didWarnAboutLegacyLifecyclesAndDerivedState; + var didWarnAboutUndefinedDerivedState; + var warnOnUndefinedDerivedState; + var warnOnInvalidCallback; + var didWarnAboutDirectlyAssigningPropsToState; + var didWarnAboutContextTypeAndContextTypes; + var didWarnAboutInvalidateContextType; - if (this.putFlags.putRot === undefined) { - this.putFlags.putRot = true; - } + { + didWarnAboutStateAssignmentForComponent = new Set(); + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutContextTypeAndContextTypes = new Set(); + didWarnAboutInvalidateContextType = new Set(); + var didWarnOnInvalidCallback = new Set(); - if (this.putFlags.putScl === undefined) { - this.putFlags.putScl = true; - } - } + warnOnInvalidCallback = function (callback, callerName) { + if (callback === null || typeof callback === 'function') { + return; + } - createClass(XAnimationObj, [{ - key: 'make', - value: function make(XAnimationInfoArray) { - for (let i = 0; i < XAnimationInfoArray.length; i++) { - this.hierarchy.push(this.makeBonekeys(XAnimationInfoArray[i])); - } + var key = callerName + '_' + callback; - this.length = this.hierarchy[0].keys[this.hierarchy[0].keys.length - 1].time; - } - }, { - key: 'clone', - value: function clone() { - return Object.assign({}, this); - } - }, { - key: 'makeBonekeys', - value: function makeBonekeys(XAnimationInfo) { - var refObj = {}; - refObj.name = XAnimationInfo.boneName; - refObj.parent = ''; - refObj.keys = this.keyFrameRefactor(XAnimationInfo); - - refObj.copy = function () { - return Object.assign({}, this); - }; + if (!didWarnOnInvalidCallback.has(key)) { + didWarnOnInvalidCallback.add(key); - return refObj; - } - }, { - key: 'keyFrameRefactor', - value: function keyFrameRefactor(XAnimationInfo) { - var keys = []; + error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); + } + }; - for (let i = 0; i < XAnimationInfo.keyFrames.length; i++) { - var keyframe = {}; - keyframe.time = XAnimationInfo.keyFrames[i].time * this.fps; + warnOnUndefinedDerivedState = function (type, partialState) { + if (partialState === undefined) { + var componentName = getComponentNameFromType(type) || 'Component'; - if (XAnimationInfo.keyFrames[i].pos && this.putFlags.putPos) { - keyframe.pos = XAnimationInfo.keyFrames[i].pos; - } + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { + didWarnAboutUndefinedDerivedState.add(componentName); - if (XAnimationInfo.keyFrames[i].rot && this.putFlags.putRot) { - keyframe.rot = XAnimationInfo.keyFrames[i].rot; - } + error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); + } + } + }; // This is so gross but it's at least non-critical and can be removed if + // it causes problems. This is meant to give a nicer error message for + // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, + // ...)) which otherwise throws a "_processChildContext is not a function" + // exception. - if (XAnimationInfo.keyFrames[i].scl && this.putFlags.putScl) { - keyframe.scl = XAnimationInfo.keyFrames[i].scl; - } - if (XAnimationInfo.keyFrames[i].matrix) { - keyframe.matrix = XAnimationInfo.keyFrames[i].matrix; + Object.defineProperty(fakeInternalInstance, '_processChildContext', { + enumerable: false, + value: function () { + throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).'); + } + }); + Object.freeze(fakeInternalInstance); + } - if (this.putFlags.putPos) { - keyframe.pos = new Vector3().setFromMatrixPosition(keyframe.matrix); - } + function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) { + var prevState = workInProgress.memoizedState; + var partialState = getDerivedStateFromProps(nextProps, prevState); - if (this.putFlags.putRot) { - keyframe.rot = new Quaternion().setFromRotationMatrix(keyframe.matrix); - } + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - if (this.putFlags.putScl) { - keyframe.scl = new Vector3().setFromMatrixScale(keyframe.matrix); - } - } + try { + // Invoke the function an extra time to help detect side-effects. + partialState = getDerivedStateFromProps(nextProps, prevState); + } finally { + setIsStrictModeForDevtools(false); + } + } - keys.push(keyframe); - } + warnOnUndefinedDerivedState(ctor, partialState); + } // Merge the partial state and the previous state. - return keys; - } - }]); - return XAnimationObj; - }(); - - var XKeyFrameInfo = function XKeyFrameInfo() { - classCallCheck(this, XKeyFrameInfo); - this.index = 0; - this.Frame = 0; - this.time = 0.0; - this.matrix = null; - }; - var XLoader = function () { - function XLoader(manager) { - Loader.call(this, manager); - classCallCheck(this, XLoader); - this.debug = false; - this.texloader = new TextureLoader(this.manager); - this.url = ''; - this._putMatLength = 0; - this._nowMat = null; - this._nowFrameName = ''; - this.frameHierarchie = []; - this.Hierarchies = {}; - this.HieStack = []; - this._currentObject = {}; - this._currentFrame = {}; - this._data = null; - this.onLoad = null; - this.IsUvYReverse = true; - this.Meshes = []; - this.animations = []; - this.animTicksPerSecond = 30; - this._currentGeo = null; - this._currentAnime = null; - this._currentAnimeFrames = null; - } + var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); + workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the + // base state. - createClass(XLoader, [{ - key: '_setArgOption', - value: function _setArgOption(_arg) { - var _start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (workInProgress.lanes === NoLanes) { + // Queue is always non-null for classes + var updateQueue = workInProgress.updateQueue; + updateQueue.baseState = memoizedState; + } + } - if (!_arg) { - return; - } + var classComponentUpdater = { + isMounted: isMounted, + enqueueSetState: function (inst, payload, callback) { + var fiber = get(inst); + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + var update = createUpdate(eventTime, lane); + update.payload = payload; - for (let i = _start; i < _arg.length; i++) { - switch (i) { - case 0: - this.url = _arg[i]; - break; + if (callback !== undefined && callback !== null) { + { + warnOnInvalidCallback(callback, 'setState'); + } - case 1: - this.options = _arg[i]; - break; - } - } + update.callback = callback; + } - if (this.options === undefined) { - this.options = {}; - } - } - }, { - key: 'load', - value: function load(_arg, onLoad, onProgress, onError) { - var _this = this; + enqueueUpdate(fiber, update); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - this._setArgOption(_arg); + if (root !== null) { + entangleTransitions(root, fiber, lane); + } - var loader = new FileLoader(this.manager); - loader.setPath(this.path); - loader.setResponseType('arraybuffer'); - loader.setRequestHeader(this.requestHeader); - loader.setWithCredentials(this.withCredentials); - loader.load(this.url, function (response) { - try { - _this.parse(response, onLoad); - } catch (e) { - if (onError) { - onError(e); - } else { - console.error(e); - } + { + markStateUpdateScheduled(fiber, lane); + } + }, + enqueueReplaceState: function (inst, payload, callback) { + var fiber = get(inst); + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + var update = createUpdate(eventTime, lane); + update.tag = ReplaceState; + update.payload = payload; - _this.manager.itemError(_this.url); - } - }, onProgress, onError); - } - }, { - key: '_readLine', - value: function _readLine(line) { - var readed = 0; + if (callback !== undefined && callback !== null) { + { + warnOnInvalidCallback(callback, 'replaceState'); + } - while (true) { - var find = -1; - find = line.indexOf('//', readed); + update.callback = callback; + } - if (find === -1) { - find = line.indexOf('#', readed); - } + enqueueUpdate(fiber, update); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - if (find > -1 && find < 2) { - var foundNewLine = -1; - foundNewLine = line.indexOf('\r\n', readed); + if (root !== null) { + entangleTransitions(root, fiber, lane); + } - if (foundNewLine > 0) { - readed = foundNewLine + 2; - } else { - foundNewLine = line.indexOf('\r', readed); + { + markStateUpdateScheduled(fiber, lane); + } + }, + enqueueForceUpdate: function (inst, callback) { + var fiber = get(inst); + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + var update = createUpdate(eventTime, lane); + update.tag = ForceUpdate; - if (foundNewLine > 0) { - readed = foundNewLine + 1; - } else { - readed = line.indexOf('\n', readed) + 1; - } - } - } else { - break; - } - } + if (callback !== undefined && callback !== null) { + { + warnOnInvalidCallback(callback, 'forceUpdate'); + } - return line.substr(readed); - } - }, { - key: '_readLine', - value: function _readLine(line) { - var readed = 0; + update.callback = callback; + } - while (true) { - var find = -1; - find = line.indexOf('//', readed); + enqueueUpdate(fiber, update); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - if (find === -1) { - find = line.indexOf('#', readed); - } + if (root !== null) { + entangleTransitions(root, fiber, lane); + } - if (find > -1 && find < 2) { - var foundNewLine = -1; - foundNewLine = line.indexOf('\r\n', readed); + { + markForceUpdateScheduled(fiber, lane); + } + } + }; - if (foundNewLine > 0) { - readed = foundNewLine + 2; - } else { - foundNewLine = line.indexOf('\r', readed); + function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) { + var instance = workInProgress.stateNode; - if (foundNewLine > 0) { - readed = foundNewLine + 1; - } else { - readed = line.indexOf('\n', readed) + 1; - } - } - } else { - break; - } - } + if (typeof instance.shouldComponentUpdate === 'function') { + var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); - return line.substr(readed); - } - }, { - key: '_isBinary', - value: function _isBinary(binData) { - var reader = new DataView(binData); - var face_size = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8; - var n_faces = reader.getUint32(80, true); - var expect = 80 + 32 / 8 + n_faces * face_size; - - if (expect === reader.byteLength) { - return true; - } + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - var fileLength = reader.byteLength; + try { + // Invoke the function an extra time to help detect side-effects. + shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); + } finally { + setIsStrictModeForDevtools(false); + } + } - for (let index = 0; index < fileLength; index++) { - if (reader.getUint8(index, false) > 127) { - return true; - } - } + if (shouldUpdate === undefined) { + error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component'); + } + } - return false; - } - }, { - key: '_ensureBinary', - value: function _ensureBinary(buf) { - if (typeof buf === 'string') { - var array_buffer = new Uint8Array(buf.length); - - for (let i = 0; i < buf.length; i++) { - array_buffer[i] = buf.charCodeAt(i) & 0xff; - } + return shouldUpdate; + } - return array_buffer.buffer || array_buffer; - } else { - return buf; - } - } - }, { - key: '_ensureString', - value: function _ensureString(buf) { - if (typeof buf !== 'string') { - return LoaderUtils.decodeText(new Uint8Array(buf)); - } else { - return buf; - } - } - }, { - key: 'parse', - value: function _parse(data, onLoad) { - var binData = this._ensureBinary(data); - - this._data = this._ensureString(data); - this.onLoad = onLoad; - return this._isBinary(binData) ? this._parseBinary(binData) : this._parseASCII(); - } - }, { - key: '_parseBinary', - value: function _parseBinary(data) { - return this._parseASCII(LoaderUtils.decodeText(new Uint8Array(data))); - } - }, { - key: '_parseASCII', - value: function _parseASCII() { - var path; - - if (this.resourcePath !== '') { - path = this.resourcePath; - } else if (this.path !== '') { - path = this.path; - } else { - path = LoaderUtils.extractUrlBase(this.url); - } + if (ctor.prototype && ctor.prototype.isPureReactComponent) { + return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); + } - this.texloader.setPath(path).setCrossOrigin(this.crossOrigin); - var endRead = 16; - this.Hierarchies.children = []; + return true; + } - this._hierarchieParse(this.Hierarchies, endRead); + function checkClassInstance(workInProgress, ctor, newProps) { + var instance = workInProgress.stateNode; - this._changeRoot(); + { + var name = getComponentNameFromType(ctor) || 'Component'; + var renderPresent = instance.render; - this._currentObject = this.Hierarchies.children.shift(); + if (!renderPresent) { + if (ctor.prototype && typeof ctor.prototype.render === 'function') { + error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); + } else { + error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); + } + } - this._mainloop(); - } - }, { - key: '_hierarchieParse', - value: function _hierarchieParse(_parent, _end) { - var endRead = _end; + if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { + error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); + } - while (true) { - var find1 = this._data.indexOf('{', endRead) + 1; + if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { + error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); + } - var findEnd = this._data.indexOf('}', endRead); + if (instance.propTypes) { + error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); + } - var findNext = this._data.indexOf('{', find1) + 1; + if (instance.contextType) { + error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); + } - if (find1 > 0 && findEnd > find1) { - var _currentObject = {}; - _currentObject.children = []; + { + if (instance.contextTypes) { + error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); + } - var nameData = this._readLine(this._data.substr(endRead, find1 - endRead - 1)).trim(); + if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { + didWarnAboutContextTypeAndContextTypes.add(ctor); - var word = nameData.split(/ /g); + error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); + } + } - if (word.length > 0) { - _currentObject.type = word[0]; + if (typeof instance.componentShouldUpdate === 'function') { + error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); + } - if (word.length >= 2) { - _currentObject.name = word[1]; - } else { - _currentObject.name = word[0] + this.Hierarchies.children.length; - } - } else { - _currentObject.name = nameData; - _currentObject.type = ''; - } + if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { + error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); + } - if (_currentObject.type === 'Animation') { - _currentObject.data = this._data.substr(findNext, findEnd - findNext).trim(); + if (typeof instance.componentDidUnmount === 'function') { + error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); + } - var refs = this._hierarchieParse(_currentObject, findEnd + 1); + if (typeof instance.componentDidReceiveProps === 'function') { + error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); + } - endRead = refs.end; - _currentObject.children = refs.parent.children; - } else { - var DataEnder = this._data.lastIndexOf(';', findNext > 0 ? Math.min(findNext, findEnd) : findEnd); + if (typeof instance.componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); + } - _currentObject.data = this._data.substr(find1, DataEnder - find1).trim(); + if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); + } - if (findNext <= 0 || findEnd < findNext) { - endRead = findEnd + 1; - } else { - var nextStart = Math.max(DataEnder + 1, find1); + var hasMutatedProps = instance.props !== newProps; - var _refs = this._hierarchieParse(_currentObject, nextStart); + if (instance.props !== undefined && hasMutatedProps) { + error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); + } - endRead = _refs.end; - _currentObject.children = _refs.parent.children; - } - } + if (instance.defaultProps) { + error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); + } - _currentObject.parent = _parent; + if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - if (_currentObject.type != 'template') { - _parent.children.push(_currentObject); - } - } else { - endRead = find1 === -1 ? this._data.length : findEnd + 1; - break; - } - } + error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); + } - return { - parent: _parent, - end: endRead - }; - } - }, { - key: '_mainloop', - value: function _mainloop() { - var _this2 = this; + if (typeof instance.getDerivedStateFromProps === 'function') { + error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } - this._mainProc(); + if (typeof instance.getDerivedStateFromError === 'function') { + error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } - if (this._currentObject.parent || this._currentObject.children.length > 0 || !this._currentObject.worked) { - setTimeout(function () { - _this2._mainloop(); - }, 1); - } else { - setTimeout(function () { - _this2.onLoad({ - models: _this2.Meshes, - animations: _this2.animations - }); - }, 1); - } - } - }, { - key: '_mainProc', - value: function _mainProc() { - var breakFlag = false; - - while (true) { - if (!this._currentObject.worked) { - switch (this._currentObject.type) { - case 'template': - break; + if (typeof ctor.getSnapshotBeforeUpdate === 'function') { + error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); + } - case 'AnimTicksPerSecond': - this.animTicksPerSecond = parseInt(this._currentObject.data); - break; + var _state = instance.state; - case 'Frame': - this._setFrame(); + if (_state && (typeof _state !== 'object' || isArray(_state))) { + error('%s.state: must be set to an object or null', name); + } - break; + if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { + error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); + } + } + } - case 'FrameTransformMatrix': - this._setFrameTransformMatrix(); + function adoptClassInstance(workInProgress, instance) { + instance.updater = classComponentUpdater; + workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates - break; + set(instance, workInProgress); - case 'Mesh': - this._changeRoot(); - - this._currentGeo = {}; - this._currentGeo.name = this._currentObject.name.trim(); - this._currentGeo.parentName = this._getParentName(this._currentObject).trim(); - this._currentGeo.VertexSetedBoneCount = []; - this._currentGeo.GeometryData = { - vertices: [], - normals: [], - uvs: [], - skinIndices: [], - skinWeights: [], - indices: [], - materialIndices: [] - }; - this._currentGeo.Materials = []; - this._currentGeo.normalVectors = []; - this._currentGeo.BoneInfs = []; - this._currentGeo.baseFrame = this._currentFrame; - - this._makeBoneFrom_CurrentFrame(); - - this._readVertexDatas(); - - breakFlag = true; - break; + { + instance._reactInternalInstance = fakeInternalInstance; + } + } - case 'MeshNormals': - this._readVertexDatas(); + function constructClassInstance(workInProgress, ctor, props) { + var isLegacyContextConsumer = false; + var unmaskedContext = emptyContextObject; + var context = emptyContextObject; + var contextType = ctor.contextType; - break; + { + if ('contextType' in ctor) { + var isValid = // Allow null for conditional declaration + contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a - case 'MeshTextureCoords': - this._setMeshTextureCoords(); + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { + didWarnAboutInvalidateContextType.add(ctor); + var addendum = ''; - break; + if (contextType === undefined) { + addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; + } else if (typeof contextType !== 'object') { + addendum = ' However, it is set to a ' + typeof contextType + '.'; + } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { + addendum = ' Did you accidentally pass the Context.Provider instead?'; + } else if (contextType._context !== undefined) { + // + addendum = ' Did you accidentally pass the Context.Consumer instead?'; + } else { + addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; + } - case 'VertexDuplicationIndices': - break; + error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); + } + } + } - case 'MeshMaterialList': - this._setMeshMaterialList(); + if (typeof contextType === 'object' && contextType !== null) { + context = readContext(contextType); + } else { + unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); + var contextTypes = ctor.contextTypes; + isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined; + context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; + } - break; + var instance = new ctor(props, context); // Instantiate twice to help detect side-effects. - case 'Material': - this._setMaterial(); + { + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); - break; + try { + instance = new ctor(props, context); // eslint-disable-line no-new + } finally { + setIsStrictModeForDevtools(false); + } + } + } - case 'SkinWeights': - this._setSkinWeights(); + var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null; + adoptClassInstance(workInProgress, instance); - break; + { + if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { + var componentName = getComponentNameFromType(ctor) || 'Component'; - case 'AnimationSet': - this._changeRoot(); + if (!didWarnAboutUninitializedState.has(componentName)) { + didWarnAboutUninitializedState.add(componentName); - this._currentAnime = {}; - this._currentAnime.name = this._currentObject.name.trim(); - this._currentAnime.AnimeFrames = []; - break; + error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); + } + } // If new component APIs are defined, "unsafe" lifecycles won't be called. + // Warn about these lifecycles if they are present. + // Don't warn about react-lifecycles-compat polyfilled methods though. - case 'Animation': - if (this._currentAnimeFrames) { - this._currentAnime.AnimeFrames.push(this._currentAnimeFrames); - } - this._currentAnimeFrames = new XAnimationInfo(); - this._currentAnimeFrames.boneName = this._currentObject.data.trim(); - break; + if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { + var foundWillMountName = null; + var foundWillReceivePropsName = null; + var foundWillUpdateName = null; - case 'AnimationKey': - this._readAnimationKey(); + if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { + foundWillMountName = 'componentWillMount'; + } else if (typeof instance.UNSAFE_componentWillMount === 'function') { + foundWillMountName = 'UNSAFE_componentWillMount'; + } - breakFlag = true; - break; - } + if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { + foundWillReceivePropsName = 'componentWillReceiveProps'; + } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { + foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; + } - this._currentObject.worked = true; - } + if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { + foundWillUpdateName = 'componentWillUpdate'; + } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { + foundWillUpdateName = 'UNSAFE_componentWillUpdate'; + } - if (this._currentObject.children.length > 0) { - this._currentObject = this._currentObject.children.shift(); + if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { + var _componentName = getComponentNameFromType(ctor) || 'Component'; - if (this.debug) { - console.log('processing ' + this._currentObject.name); - } + var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; - if (breakFlag) break; - } else { - if (this._currentObject.worked) { - if (this._currentObject.parent && !this._currentObject.parent.parent) { - this._changeRoot(); - } - } + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { + didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); - if (this._currentObject.parent) { - this._currentObject = this._currentObject.parent; - } else { - breakFlag = true; - } + error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); + } + } + } + } // Cache unmasked context so we can avoid recreating masked context unless necessary. + // ReactFiberContext usually updates this cache but can't for newly-created instances. - if (breakFlag) break; - } - } - return; - } - }, { - key: '_changeRoot', - value: function _changeRoot() { - if (this._currentGeo != null && this._currentGeo.name) { - this._makeOutputGeometry(); - } + if (isLegacyContextConsumer) { + cacheContext(workInProgress, unmaskedContext, context); + } - this._currentGeo = {}; + return instance; + } - if (this._currentAnime != null && this._currentAnime.name) { - if (this._currentAnimeFrames) { - this._currentAnime.AnimeFrames.push(this._currentAnimeFrames); + function callComponentWillMount(workInProgress, instance) { + var oldState = instance.state; - this._currentAnimeFrames = null; - } + if (typeof instance.componentWillMount === 'function') { + instance.componentWillMount(); + } - this._makeOutputAnimation(); - } + if (typeof instance.UNSAFE_componentWillMount === 'function') { + instance.UNSAFE_componentWillMount(); + } - this._currentAnime = {}; - } - }, { - key: '_getParentName', - value: function _getParentName(_obj) { - if (_obj.parent) { - if (_obj.parent.name) { - return _obj.parent.name; - } else { - return this._getParentName(_obj.parent); - } - } else { - return ''; - } - } - }, { - key: '_setFrame', - value: function _setFrame() { - this._nowFrameName = this._currentObject.name.trim(); - this._currentFrame = {}; - this._currentFrame.name = this._nowFrameName; - this._currentFrame.children = []; - - if (this._currentObject.parent && this._currentObject.parent.name) { - this._currentFrame.parentName = this._currentObject.parent.name; - } + if (oldState !== instance.state) { + { + error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component'); + } - this.frameHierarchie.push(this._nowFrameName); - this.HieStack[this._nowFrameName] = this._currentFrame; - } - }, { - key: '_setFrameTransformMatrix', - value: function _setFrameTransformMatrix() { - this._currentFrame.FrameTransformMatrix = new Matrix4(); + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } + } - var data = this._currentObject.data.split(','); + function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) { + var oldState = instance.state; - this._ParseMatrixData(this._currentFrame.FrameTransformMatrix, data); + if (typeof instance.componentWillReceiveProps === 'function') { + instance.componentWillReceiveProps(newProps, nextContext); + } - this._makeBoneFrom_CurrentFrame(); - } - }, { - key: '_makeBoneFrom_CurrentFrame', - value: function _makeBoneFrom_CurrentFrame() { - if (!this._currentFrame.FrameTransformMatrix) { - return; - } + if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { + instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); + } - var b = new Bone(); - b.name = this._currentFrame.name; - b.applyMatrix4(this._currentFrame.FrameTransformMatrix); - b.matrixWorld = b.matrix; - b.FrameTransformMatrix = this._currentFrame.FrameTransformMatrix; - this._currentFrame.putBone = b; - - if (this._currentFrame.parentName) { - for (let frame in this.HieStack) { - if (this.HieStack[frame].name === this._currentFrame.parentName) { - this.HieStack[frame].putBone.add(this._currentFrame.putBone); - } - } - } - } - }, { - key: '_readVertexDatas', - value: function _readVertexDatas() { - var endRead = 0; - var mode = 0; - var mode_local = 0; - var maxLength = 0; - - while (true) { - var changeMode = false; - - if (mode_local === 0) { - var refO = this._readInt1(endRead); - - endRead = refO.endRead; - mode_local = 1; - maxLength = this._currentObject.data.indexOf(';;', endRead) + 1; - - if (maxLength <= 0) { - maxLength = this._currentObject.data.length; - } - } else { - var find = 0; + if (instance.state !== oldState) { + { + var componentName = getComponentNameFromFiber(workInProgress) || 'Component'; - switch (mode) { - case 0: - find = this._currentObject.data.indexOf(',', endRead) + 1; - break; + if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { + didWarnAboutStateAssignmentForComponent.add(componentName); - case 1: - find = this._currentObject.data.indexOf(';,', endRead) + 1; - break; - } + error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName); + } + } - if (find === 0 || find > maxLength) { - find = maxLength; - mode_local = 0; - changeMode = true; - } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } + } // Invokes the mount life-cycles on a previously never rendered instance. - switch (this._currentObject.type) { - case 'Mesh': - switch (mode) { - case 0: - this._readVertex1(this._currentObject.data.substr(endRead, find - endRead)); - break; + function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { + { + checkClassInstance(workInProgress, ctor, newProps); + } - case 1: - this._readFace1(this._currentObject.data.substr(endRead, find - endRead)); + var instance = workInProgress.stateNode; + instance.props = newProps; + instance.state = workInProgress.memoizedState; + instance.refs = emptyRefsObject; + initializeUpdateQueue(workInProgress); + var contextType = ctor.contextType; - break; - } + if (typeof contextType === 'object' && contextType !== null) { + instance.context = readContext(contextType); + } else { + var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); + instance.context = getMaskedContext(workInProgress, unmaskedContext); + } - break; + { + if (instance.state === newProps) { + var componentName = getComponentNameFromType(ctor) || 'Component'; - case 'MeshNormals': - switch (mode) { - case 0: - this._readNormalVector1(this._currentObject.data.substr(endRead, find - endRead)); + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { + didWarnAboutDirectlyAssigningPropsToState.add(componentName); - break; - } + error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); + } + } - break; - } + if (workInProgress.mode & StrictLegacyMode) { + ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance); + } - endRead = find + 1; + { + ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance); + } + } - if (changeMode) { - mode++; - } - } + instance.state = workInProgress.memoizedState; + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - if (endRead >= this._currentObject.data.length) { - break; - } - } - } - }, { - key: '_readInt1', - value: function _readInt1(start) { - var find = this._currentObject.data.indexOf(';', start); + if (typeof getDerivedStateFromProps === 'function') { + applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); + instance.state = workInProgress.memoizedState; + } // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. - return { - refI: parseInt(this._currentObject.data.substr(start, find - start)), - endRead: find + 1 - }; - } - }, { - key: '_readVertex1', - value: function _readVertex1(line) { - var data = this._readLine(line.trim()).substr(0, line.length - 2).split(';'); - this._currentGeo.GeometryData.vertices.push(parseFloat(data[0]), parseFloat(data[1]), parseFloat(data[2])); + if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { + callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's + // process them now. - this._currentGeo.GeometryData.skinIndices.push(0, 0, 0, 0); + processUpdateQueue(workInProgress, newProps, instance, renderLanes); + instance.state = workInProgress.memoizedState; + } - this._currentGeo.GeometryData.skinWeights.push(1, 0, 0, 0); + if (typeof instance.componentDidMount === 'function') { + var fiberFlags = Update; - this._currentGeo.VertexSetedBoneCount.push(0); - } - }, { - key: '_readFace1', - value: function _readFace1(line) { - var data = this._readLine(line.trim()).substr(2, line.length - 4).split(','); + { + fiberFlags |= LayoutStatic; + } - this._currentGeo.GeometryData.indices.push(parseInt(data[0], 10), parseInt(data[1], 10), parseInt(data[2], 10)); - } - }, { - key: '_readNormalVector1', - value: function _readNormalVector1(line) { - var data = this._readLine(line.trim()).substr(0, line.length - 2).split(';'); + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } - this._currentGeo.GeometryData.normals.push(parseFloat(data[0]), parseFloat(data[1]), parseFloat(data[2])); - } - }, { - key: '_buildGeometry', - value: function _buildGeometry() { - var bufferGeometry = new BufferGeometry(); - var position = []; - var normals = []; - var uvs = []; - var skinIndices = []; - var skinWeights = []; // - - var data = this._currentGeo.GeometryData; - - for (let i = 0, l = data.indices.length; i < l; i++) { - var stride2 = data.indices[i] * 2; - var stride3 = data.indices[i] * 3; - var stride4 = data.indices[i] * 4; - position.push(data.vertices[stride3], data.vertices[stride3 + 1], data.vertices[stride3 + 2]); - normals.push(data.normals[stride3], data.normals[stride3 + 1], data.normals[stride3 + 2]); - skinIndices.push(data.skinIndices[stride4], data.skinIndices[stride4 + 1], data.skinIndices[stride4 + 2], data.skinIndices[stride4 + 3]); - skinWeights.push(data.skinWeights[stride4], data.skinWeights[stride4 + 1], data.skinWeights[stride4 + 2], data.skinWeights[stride4 + 3]); - uvs.push(data.uvs[stride2], data.uvs[stride2 + 1]); - } // - - - bufferGeometry.setAttribute('position', new Float32BufferAttribute(position, 3)); - bufferGeometry.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - bufferGeometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); - bufferGeometry.setAttribute('skinIndex', new Uint16BufferAttribute(skinIndices, 4)); - bufferGeometry.setAttribute('skinWeight', new Float32BufferAttribute(skinWeights, 4)); - - this._computeGroups(bufferGeometry, data.materialIndices); - - return bufferGeometry; - } - }, { - key: '_computeGroups', - value: function _computeGroups(bufferGeometry, materialIndices) { - var group; - var groups = []; - var materialIndex = undefined; - - for (let i = 0; i < materialIndices.length; i++) { - var currentMaterialIndex = materialIndices[i]; - - if (currentMaterialIndex !== materialIndex) { - materialIndex = currentMaterialIndex; - - if (group !== undefined) { - group.count = i * 3 - group.start; - groups.push(group); - } + workInProgress.flags |= fiberFlags; + } + } - group = { - start: i * 3, - materialIndex: materialIndex - }; - } - } + function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) { + var instance = workInProgress.stateNode; + var oldProps = workInProgress.memoizedProps; + instance.props = oldProps; + var oldContext = instance.context; + var contextType = ctor.contextType; + var nextContext = emptyContextObject; - if (group !== undefined) { - group.count = i * 3 - group.start; - groups.push(group); - } + if (typeof contextType === 'object' && contextType !== null) { + nextContext = readContext(contextType); + } else { + var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); + nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext); + } - bufferGeometry.groups = groups; - } - }, { - key: '_setMeshTextureCoords', - value: function _setMeshTextureCoords() { - var endRead = 0; - var mode = 0; - var mode_local = 0; - - while (true) { - switch (mode) { - case 0: - if (mode_local === 0) { - var refO = this._readInt1(0); - - endRead = refO.endRead; - mode_local = 1; - } else { - var find = this._currentObject.data.indexOf(',', endRead) + 1; + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what + // ever the previously attempted to render - not the "current". However, + // during componentDidUpdate we pass the "current" props. + // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. - if (find === 0) { - find = this._currentObject.data.length; - mode = 2; - mode_local = 0; - } + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { + if (oldProps !== newProps || oldContext !== nextContext) { + callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); + } + } - var line = this._currentObject.data.substr(endRead, find - endRead); + resetHasForceUpdateBeforeProcessing(); + var oldState = workInProgress.memoizedState; + var newState = instance.state = oldState; + processUpdateQueue(workInProgress, newProps, instance, renderLanes); + newState = workInProgress.memoizedState; - var data = this._readLine(line.trim()).split(';'); + if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { + // If an update was already in progress, we should schedule an Update + // effect even though we're bailing out, so that cWU/cDU are called. + if (typeof instance.componentDidMount === 'function') { + var fiberFlags = Update; - if (this.IsUvYReverse) { - this._currentGeo.GeometryData.uvs.push(parseFloat(data[0]), 1 - parseFloat(data[1])); - } else { - this._currentGeo.GeometryData.uvs.push(parseFloat(data[0]), parseFloat(data[1])); - } + { + fiberFlags |= LayoutStatic; + } - endRead = find + 1; - } + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } - break; - } + workInProgress.flags |= fiberFlags; + } - if (endRead >= this._currentObject.data.length) { - break; - } - } - } - }, { - key: '_setMeshMaterialList', - value: function _setMeshMaterialList() { - var endRead = 0; - var mode = 0; - var mode_local = 0; - - while (true) { - if (mode_local < 2) { - var refO = this._readInt1(endRead); - - endRead = refO.endRead; - mode_local++; - } else { - var find = this._currentObject.data.indexOf(';', endRead); + return false; + } - if (find === -1) { - find = this._currentObject.data.length; - mode = 3; - mode_local = 0; - } + if (typeof getDerivedStateFromProps === 'function') { + applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); + newState = workInProgress.memoizedState; + } - var line = this._currentObject.data.substr(endRead, find - endRead); + var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext); - var data = this._readLine(line.trim()).split(','); + if (shouldUpdate) { + // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { + if (typeof instance.componentWillMount === 'function') { + instance.componentWillMount(); + } - for (let i = 0; i < data.length; i++) { - this._currentGeo.GeometryData.materialIndices[i] = parseInt(data[i]); - } + if (typeof instance.UNSAFE_componentWillMount === 'function') { + instance.UNSAFE_componentWillMount(); + } + } - endRead = this._currentObject.data.length; - } + if (typeof instance.componentDidMount === 'function') { + var _fiberFlags = Update; - if (endRead >= this._currentObject.data.length || mode >= 3) { - break; - } - } - } - }, { - key: '_setMaterial', - value: function _setMaterial() { - var _nowMat = new MeshPhongMaterial({ - color: Math.random() * 0xffffff - }); + { + _fiberFlags |= LayoutStatic; + } - _nowMat.side = FrontSide; - _nowMat.name = this._currentObject.name; - var endRead = 0; + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + _fiberFlags |= MountLayoutDev; + } - var find = this._currentObject.data.indexOf(';;', endRead); + workInProgress.flags |= _fiberFlags; + } + } else { + // If an update was already in progress, we should schedule an Update + // effect even though we're bailing out, so that cWU/cDU are called. + if (typeof instance.componentDidMount === 'function') { + var _fiberFlags2 = Update; - var line = this._currentObject.data.substr(endRead, find - endRead); + { + _fiberFlags2 |= LayoutStatic; + } - var data = this._readLine(line.trim()).split(';'); + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + _fiberFlags2 |= MountLayoutDev; + } - _nowMat.color.r = parseFloat(data[0]); - _nowMat.color.g = parseFloat(data[1]); - _nowMat.color.b = parseFloat(data[2]); - endRead = find + 2; - find = this._currentObject.data.indexOf(';', endRead); - line = this._currentObject.data.substr(endRead, find - endRead); - _nowMat.shininess = parseFloat(this._readLine(line)); - endRead = find + 1; - find = this._currentObject.data.indexOf(';;', endRead); - line = this._currentObject.data.substr(endRead, find - endRead); + workInProgress.flags |= _fiberFlags2; + } // If shouldComponentUpdate returned false, we should still update the + // memoized state to indicate that this work can be reused. - var data2 = this._readLine(line.trim()).split(';'); - _nowMat.specular.r = parseFloat(data2[0]); - _nowMat.specular.g = parseFloat(data2[1]); - _nowMat.specular.b = parseFloat(data2[2]); - endRead = find + 2; - find = this._currentObject.data.indexOf(';;', endRead); + workInProgress.memoizedProps = newProps; + workInProgress.memoizedState = newState; + } // Update the existing instance's state, props, and context pointers even + // if shouldComponentUpdate returns false. - if (find === -1) { - find = this._currentObject.data.length; - } - line = this._currentObject.data.substr(endRead, find - endRead); + instance.props = newProps; + instance.state = newState; + instance.context = nextContext; + return shouldUpdate; + } // Invokes the update life-cycles and returns false if it shouldn't rerender. - var data3 = this._readLine(line.trim()).split(';'); - _nowMat.emissive.r = parseFloat(data3[0]); - _nowMat.emissive.g = parseFloat(data3[1]); - _nowMat.emissive.b = parseFloat(data3[2]); - var localObject = null; + function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) { + var instance = workInProgress.stateNode; + cloneUpdateQueue(current, workInProgress); + var unresolvedOldProps = workInProgress.memoizedProps; + var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps); + instance.props = oldProps; + var unresolvedNewProps = workInProgress.pendingProps; + var oldContext = instance.context; + var contextType = ctor.contextType; + var nextContext = emptyContextObject; - while (true) { - if (this._currentObject.children.length > 0) { - localObject = this._currentObject.children.shift(); + if (typeof contextType === 'object' && contextType !== null) { + nextContext = readContext(contextType); + } else { + var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); + nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); + } - if (this.debug) { - console.log('processing ' + localObject.name); - } + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what + // ever the previously attempted to render - not the "current". However, + // during componentDidUpdate we pass the "current" props. + // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. - var fileName = localObject.data.substr(1, localObject.data.length - 2); + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { + if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { + callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); + } + } - switch (localObject.type) { - case 'TextureFilename': - _nowMat.map = this.texloader.load(fileName); - break; + resetHasForceUpdateBeforeProcessing(); + var oldState = workInProgress.memoizedState; + var newState = instance.state = oldState; + processUpdateQueue(workInProgress, newProps, instance, renderLanes); + newState = workInProgress.memoizedState; - case 'BumpMapFilename': - _nowMat.bumpMap = this.texloader.load(fileName); - _nowMat.bumpScale = 0.05; - break; + if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation )) { + // If an update was already in progress, we should schedule an Update + // effect even though we're bailing out, so that cWU/cDU are called. + if (typeof instance.componentDidUpdate === 'function') { + if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { + workInProgress.flags |= Update; + } + } - case 'NormalMapFilename': - _nowMat.normalMap = this.texloader.load(fileName); - _nowMat.normalScale = new Vector2(2, 2); - break; + if (typeof instance.getSnapshotBeforeUpdate === 'function') { + if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { + workInProgress.flags |= Snapshot; + } + } - case 'EmissiveMapFilename': - _nowMat.emissiveMap = this.texloader.load(fileName); - break; + return false; + } - case 'LightMapFilename': - _nowMat.lightMap = this.texloader.load(fileName); - break; - } - } else { - break; - } - } + if (typeof getDerivedStateFromProps === 'function') { + applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); + newState = workInProgress.memoizedState; + } - this._currentGeo.Materials.push(_nowMat); - } - }, { - key: '_setSkinWeights', - value: function _setSkinWeights() { - var boneInf = new XboneInf(); - var endRead = 0; + var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice, + // both before and after `shouldComponentUpdate` has been called. Not ideal, + // but I'm loath to refactor this function. This only happens for memoized + // components so it's not that common. + enableLazyContextPropagation ; - var find = this._currentObject.data.indexOf(';', endRead); + if (shouldUpdate) { + // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) { + if (typeof instance.componentWillUpdate === 'function') { + instance.componentWillUpdate(newProps, newState, nextContext); + } - var line = this._currentObject.data.substr(endRead, find - endRead); + if (typeof instance.UNSAFE_componentWillUpdate === 'function') { + instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); + } + } - endRead = find + 1; - boneInf.boneName = line.substr(1, line.length - 2); - boneInf.BoneIndex = this._currentGeo.BoneInfs.length; - find = this._currentObject.data.indexOf(';', endRead); - endRead = find + 1; - find = this._currentObject.data.indexOf(';', endRead); - line = this._currentObject.data.substr(endRead, find - endRead); + if (typeof instance.componentDidUpdate === 'function') { + workInProgress.flags |= Update; + } - var data = this._readLine(line.trim()).split(','); + if (typeof instance.getSnapshotBeforeUpdate === 'function') { + workInProgress.flags |= Snapshot; + } + } else { + // If an update was already in progress, we should schedule an Update + // effect even though we're bailing out, so that cWU/cDU are called. + if (typeof instance.componentDidUpdate === 'function') { + if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { + workInProgress.flags |= Update; + } + } - for (let i = 0; i < data.length; i++) { - boneInf.Indeces.push(parseInt(data[i])); - } + if (typeof instance.getSnapshotBeforeUpdate === 'function') { + if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { + workInProgress.flags |= Snapshot; + } + } // If shouldComponentUpdate returned false, we should still update the + // memoized props/state to indicate that this work can be reused. - endRead = find + 1; - find = this._currentObject.data.indexOf(';', endRead); - line = this._currentObject.data.substr(endRead, find - endRead); - var data2 = this._readLine(line.trim()).split(','); + workInProgress.memoizedProps = newProps; + workInProgress.memoizedState = newState; + } // Update the existing instance's state, props, and context pointers even + // if shouldComponentUpdate returns false. - for (let _i = 0; _i < data2.length; _i++) { - boneInf.Weights.push(parseFloat(data2[_i])); - } - endRead = find + 1; - find = this._currentObject.data.indexOf(';', endRead); + instance.props = newProps; + instance.state = newState; + instance.context = nextContext; + return shouldUpdate; + } - if (find <= 0) { - find = this._currentObject.data.length; - } + // TODO: Use the unified fiber stack module instead of this local one? + // Intentionally not using it yet to derisk the initial implementation, because + // the way we push/pop these values is a bit unusual. If there's a mistake, I'd + // rather the ids be wrong than crash the whole reconciler. + var forkStack = []; + var forkStackIndex = 0; + var treeForkProvider = null; + var treeForkCount = 0; + var idStack = []; + var idStackIndex = 0; + var treeContextProvider = null; + var treeContextId = 1; + var treeContextOverflow = ''; + function isForkedChild(workInProgress) { + warnIfNotHydrating(); + return (workInProgress.flags & Forked) !== NoFlags; + } + function getForksAtLevel(workInProgress) { + warnIfNotHydrating(); + return treeForkCount; + } + function getTreeId() { + var overflow = treeContextOverflow; + var idWithLeadingBit = treeContextId; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; + } + function pushTreeFork(workInProgress, totalChildren) { + // This is called right after we reconcile an array (or iterator) of child + // fibers, because that's the only place where we know how many children in + // the whole set without doing extra work later, or storing addtional + // information on the fiber. + // + // That's why this function is separate from pushTreeId — it's called during + // the render phase of the fork parent, not the child, which is where we push + // the other context values. + // + // In the Fizz implementation this is much simpler because the child is + // rendered in the same callstack as the parent. + // + // It might be better to just add a `forks` field to the Fiber type. It would + // make this module simpler. + warnIfNotHydrating(); + forkStack[forkStackIndex++] = treeForkCount; + forkStack[forkStackIndex++] = treeForkProvider; + treeForkProvider = workInProgress; + treeForkCount = totalChildren; + } + function pushTreeId(workInProgress, totalChildren, index) { + warnIfNotHydrating(); + idStack[idStackIndex++] = treeContextId; + idStack[idStackIndex++] = treeContextOverflow; + idStack[idStackIndex++] = treeContextProvider; + treeContextProvider = workInProgress; + var baseIdWithLeadingBit = treeContextId; + var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part + // of the id; we use it to account for leading 0s. - line = this._currentObject.data.substr(endRead, find - endRead); + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index + 1; + var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into + // consideration the leading 1 we use to mark the end of the sequence. - var data3 = this._readLine(line.trim()).split(','); + if (length > 30) { + // We overflowed the bitwise-safe range. Fall back to slower algorithm. + // This branch assumes the length of the base id is greater than 5; it won't + // work for smaller ids, because you need 5 bits per character. + // + // We encode the id in multiple steps: first the base id, then the + // remaining digits. + // + // Each 5 bit sequence corresponds to a single base 32 character. So for + // example, if the current id is 23 bits long, we can convert 20 of those + // bits into a string of 4 characters, with 3 bits left over. + // + // First calculate how many bits in the base id represent a complete + // sequence of characters. + var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. - boneInf.OffsetMatrix = new Matrix4(); + var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. - this._ParseMatrixData(boneInf.OffsetMatrix, data3); + var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. - this._currentGeo.BoneInfs.push(boneInf); - } - }, { - key: '_makePutBoneList', - value: function _makePutBoneList(_RootName, _bones) { - var putting = false; - - for (let frame in this.HieStack) { - if (this.HieStack[frame].name === _RootName || putting) { - putting = true; - var b = new Bone(); - b.name = this.HieStack[frame].name; - b.applyMatrix4(this.HieStack[frame].FrameTransformMatrix); - b.matrixWorld = b.matrix; - b.FrameTransformMatrix = this.HieStack[frame].FrameTransformMatrix; - b.pos = new Vector3().setFromMatrixPosition(b.FrameTransformMatrix).toArray(); - b.rotq = new Quaternion().setFromRotationMatrix(b.FrameTransformMatrix).toArray(); - b.scl = new Vector3().setFromMatrixScale(b.FrameTransformMatrix).toArray(); - - if (this.HieStack[frame].parentName && this.HieStack[frame].parentName.length > 0) { - for (let i = 0; i < _bones.length; i++) { - if (this.HieStack[frame].parentName === _bones[i].name) { - _bones[i].add(b); - - b.parent = i; - break; - } - } - } + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because + // we made more room, this time it won't overflow. - _bones.push(b); - } - } - } - }, { - key: '_makeOutputGeometry', - value: function _makeOutputGeometry() { - var mesh = null; + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + treeContextId = 1 << restOfLength | id; + treeContextOverflow = overflow; + } else { + // Normal path + var newBits = slot << baseLength; - if (this._currentGeo.BoneInfs.length > 0) { - var putBones = []; + var _id = newBits | baseId; - this._makePutBoneList(this._currentGeo.baseFrame.parentName, putBones); + var _overflow = baseOverflow; + treeContextId = 1 << length | _id; + treeContextOverflow = _overflow; + } + } + function pushMaterializedTreeId(workInProgress) { + warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear + // in its children. - for (let bi = 0; bi < this._currentGeo.BoneInfs.length; bi++) { - var boneIndex = 0; + var returnFiber = workInProgress.return; - for (let bb = 0; bb < putBones.length; bb++) { - if (putBones[bb].name === this._currentGeo.BoneInfs[bi].boneName) { - boneIndex = bb; - putBones[bb].OffsetMatrix = new Matrix4(); - putBones[bb].OffsetMatrix.copy(this._currentGeo.BoneInfs[bi].OffsetMatrix); - break; - } - } + if (returnFiber !== null) { + var numberOfForks = 1; + var slotIndex = 0; + pushTreeFork(workInProgress, numberOfForks); + pushTreeId(workInProgress, numberOfForks, slotIndex); + } + } - for (let vi = 0; vi < this._currentGeo.BoneInfs[bi].Indeces.length; vi++) { - var nowVertexID = this._currentGeo.BoneInfs[bi].Indeces[vi]; - var nowVal = this._currentGeo.BoneInfs[bi].Weights[vi]; - var stride = nowVertexID * 4; - - switch (this._currentGeo.VertexSetedBoneCount[nowVertexID]) { - case 0: - this._currentGeo.GeometryData.skinIndices[stride] = boneIndex; - this._currentGeo.GeometryData.skinWeights[stride] = nowVal; - break; - - case 1: - this._currentGeo.GeometryData.skinIndices[stride + 1] = boneIndex; - this._currentGeo.GeometryData.skinWeights[stride + 1] = nowVal; - break; - - case 2: - this._currentGeo.GeometryData.skinIndices[stride + 2] = boneIndex; - this._currentGeo.GeometryData.skinWeights[stride + 2] = nowVal; - break; - - case 3: - this._currentGeo.GeometryData.skinIndices[stride + 3] = boneIndex; - this._currentGeo.GeometryData.skinWeights[stride + 3] = nowVal; - break; - } + function getBitLength(number) { + return 32 - clz32(number); + } - this._currentGeo.VertexSetedBoneCount[nowVertexID]++; + function getLeadingBit(id) { + return 1 << getBitLength(id) - 1; + } - if (this._currentGeo.VertexSetedBoneCount[nowVertexID] > 4) { - console.log('warn! over 4 bone weight! :' + nowVertexID); - } - } - } + function popTreeContext(workInProgress) { + // Restore the previous values. + // This is a bit more complicated than other context-like modules in Fiber + // because the same Fiber may appear on the stack multiple times and for + // different reasons. We have to keep popping until the work-in-progress is + // no longer at the top of the stack. + while (workInProgress === treeForkProvider) { + treeForkProvider = forkStack[--forkStackIndex]; + forkStack[forkStackIndex] = null; + treeForkCount = forkStack[--forkStackIndex]; + forkStack[forkStackIndex] = null; + } - for (let sk = 0; sk < this._currentGeo.Materials.length; sk++) { - this._currentGeo.Materials[sk].skinning = true; - } + while (workInProgress === treeContextProvider) { + treeContextProvider = idStack[--idStackIndex]; + idStack[idStackIndex] = null; + treeContextOverflow = idStack[--idStackIndex]; + idStack[idStackIndex] = null; + treeContextId = idStack[--idStackIndex]; + idStack[idStackIndex] = null; + } + } + function getSuspendedTreeContext() { + warnIfNotHydrating(); - var offsetList = []; + if (treeContextProvider !== null) { + return { + id: treeContextId, + overflow: treeContextOverflow + }; + } else { + return null; + } + } + function restoreSuspendedTreeContext(workInProgress, suspendedContext) { + warnIfNotHydrating(); + idStack[idStackIndex++] = treeContextId; + idStack[idStackIndex++] = treeContextOverflow; + idStack[idStackIndex++] = treeContextProvider; + treeContextId = suspendedContext.id; + treeContextOverflow = suspendedContext.overflow; + treeContextProvider = workInProgress; + } - for (let _bi = 0; _bi < putBones.length; _bi++) { - if (putBones[_bi].OffsetMatrix) { - offsetList.push(putBones[_bi].OffsetMatrix); - } else { - offsetList.push(new Matrix4()); - } - } + function warnIfNotHydrating() { + { + if (!getIsHydrating()) { + error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.'); + } + } + } - var bufferGeometry = this._buildGeometry(); + // This may have been an insertion or a hydration. - mesh = new SkinnedMesh(bufferGeometry, this._currentGeo.Materials.length === 1 ? this._currentGeo.Materials[0] : this._currentGeo.Materials); + var hydrationParentFiber = null; + var nextHydratableInstance = null; + var isHydrating = false; + var didSuspend = false; // Hydration errors that were thrown inside this boundary - this._initSkeleton(mesh, putBones, offsetList); - } else { - var _bufferGeometry = this._buildGeometry(); + var hydrationErrors = null; - mesh = new Mesh(_bufferGeometry, this._currentGeo.Materials.length === 1 ? this._currentGeo.Materials[0] : this._currentGeo.Materials); - } + function warnIfHydrating() { + { + if (isHydrating) { + error('We should not be hydrating here. This is a bug in React. Please file a bug.'); + } + } + } - mesh.name = this._currentGeo.name; - var worldBaseMx = new Matrix4(); - var currentMxFrame = this._currentGeo.baseFrame.putBone; + function markDidSuspendWhileHydratingDEV() { + { + didSuspend = true; + } + } - if (currentMxFrame && currentMxFrame.parent) { - while (true) { - currentMxFrame = currentMxFrame.parent; + function enterHydrationState(fiber) { + if (!supportsHydration) { + return false; + } - if (currentMxFrame) { - worldBaseMx.multiply(currentMxFrame.FrameTransformMatrix); - } else { - break; - } - } + var parentInstance = fiber.stateNode.containerInfo; + nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); + hydrationParentFiber = fiber; + isHydrating = true; + hydrationErrors = null; + didSuspend = false; + return true; + } - mesh.applyMatrix4(worldBaseMx); - } + function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) { + if (!supportsHydration) { + return false; + } - this.Meshes.push(mesh); - } - }, { - key: '_initSkeleton', - value: function _initSkeleton(mesh, boneList, boneInverses) { - var bones = [], - bone, - gbone; - var i, il; - - for (i = 0, il = boneList.length; i < il; i++) { - gbone = boneList[i]; - bone = new Bone(); - bones.push(bone); - bone.name = gbone.name; - bone.position.fromArray(gbone.pos); - bone.quaternion.fromArray(gbone.rotq); - if (gbone.scl !== undefined) bone.scale.fromArray(gbone.scl); - } + nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); + hydrationParentFiber = fiber; + isHydrating = true; + hydrationErrors = null; + didSuspend = false; - for (i = 0, il = boneList.length; i < il; i++) { - gbone = boneList[i]; + if (treeContext !== null) { + restoreSuspendedTreeContext(fiber, treeContext); + } - if (gbone.parent !== -1 && gbone.parent !== null && bones[gbone.parent] !== undefined) { - bones[gbone.parent].add(bones[i]); - } else { - mesh.add(bones[i]); - } - } + return true; + } - mesh.updateMatrixWorld(true); - var skeleton = new Skeleton(bones, boneInverses); - mesh.bind(skeleton, mesh.matrixWorld); - } - }, { - key: '_readAnimationKey', - value: function _readAnimationKey() { - var endRead = 0; - - var find = this._currentObject.data.indexOf(';', endRead); - - var line = this._currentObject.data.substr(endRead, find - endRead); - - endRead = find + 1; - var nowKeyType = parseInt(this._readLine(line)); - find = this._currentObject.data.indexOf(';', endRead); - endRead = find + 1; - line = this._currentObject.data.substr(endRead); - - var data = this._readLine(line.trim()).split(';;,'); - - for (let i = 0; i < data.length; i++) { - var data2 = data[i].split(';'); - var keyInfo = new XKeyFrameInfo(); - keyInfo.type = nowKeyType; - keyInfo.Frame = parseInt(data2[0]); - keyInfo.index = this._currentAnimeFrames.keyFrames.length; - keyInfo.time = keyInfo.Frame; - - if (nowKeyType != 4) { - var frameFound = false; - - for (let mm = 0; mm < this._currentAnimeFrames.keyFrames.length; mm++) { - if (this._currentAnimeFrames.keyFrames[mm].Frame === keyInfo.Frame) { - keyInfo = this._currentAnimeFrames.keyFrames[mm]; - frameFound = true; - break; - } - } + function warnUnhydratedInstance(returnFiber, instance) { + { + switch (returnFiber.tag) { + case HostRoot: + didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance); + break; - var frameValue = data2[2].split(','); + case HostComponent: + didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance); + break; - switch (nowKeyType) { - case 0: - keyInfo.rot = new Quaternion(parseFloat(frameValue[1]), parseFloat(frameValue[2]), parseFloat(frameValue[3]), parseFloat(frameValue[0]) * -1); - break; + case SuspenseComponent: + var suspenseState = returnFiber.memoizedState; + if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance); + break; + } + } + } - case 1: - keyInfo.scl = new Vector3(parseFloat(frameValue[0]), parseFloat(frameValue[1]), parseFloat(frameValue[2])); - break; + function deleteHydratableInstance(returnFiber, instance) { + warnUnhydratedInstance(returnFiber, instance); + var childToDelete = createFiberFromHostInstanceForDeletion(); + childToDelete.stateNode = instance; + childToDelete.return = returnFiber; + var deletions = returnFiber.deletions; - case 2: - keyInfo.pos = new Vector3(parseFloat(frameValue[0]), parseFloat(frameValue[1]), parseFloat(frameValue[2])); - break; - } + if (deletions === null) { + returnFiber.deletions = [childToDelete]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(childToDelete); + } + } - if (!frameFound) { - this._currentAnimeFrames.keyFrames.push(keyInfo); - } - } else { - keyInfo.matrix = new Matrix4(); + function warnNonhydratedInstance(returnFiber, fiber) { + { + if (didSuspend) { + // Inside a boundary that already suspended. We're currently rendering the + // siblings of a suspended node. The mismatch may be due to the missing + // data, so it's probably a false positive. + return; + } - this._ParseMatrixData(keyInfo.matrix, data2[2].split(',')); + switch (returnFiber.tag) { + case HostRoot: + { + var parentContainer = returnFiber.stateNode.containerInfo; - this._currentAnimeFrames.keyFrames.push(keyInfo); - } - } - } - }, { - key: '_makeOutputAnimation', - value: function _makeOutputAnimation() { - var animationObj = new XAnimationObj(this.options); - animationObj.fps = this.animTicksPerSecond; - animationObj.name = this._currentAnime.name; - animationObj.make(this._currentAnime.AnimeFrames); - this.animations.push(animationObj); - } - }, { - key: 'assignAnimation', - value: function assignAnimation(_model, _animation) { - var model = _model; - var animation = _animation; - - if (!model) { - model = this.Meshes[0]; - } + switch (fiber.tag) { + case HostComponent: + var type = fiber.type; + var props = fiber.pendingProps; + didNotFindHydratableInstanceWithinContainer(parentContainer, type, props); + break; - if (!animation) { - animation = this.animations[0]; - } + case HostText: + var text = fiber.pendingProps; + didNotFindHydratableTextInstanceWithinContainer(parentContainer, text); + break; - if (!model || !animation) { - return null; - } + case SuspenseComponent: + didNotFindHydratableSuspenseInstanceWithinContainer(parentContainer); + break; + } - var put = {}; - put.fps = animation.fps; - put.name = animation.name; - put.length = animation.length; - put.hierarchy = []; - - for (let b = 0; b < model.skeleton.bones.length; b++) { - var findAnimation = false; - - for (let i = 0; i < animation.hierarchy.length; i++) { - if (model.skeleton.bones[b].name === animation.hierarchy[i].name) { - findAnimation = true; - var c_key = animation.hierarchy[i].copy(); - c_key.parent = -1; - - if (model.skeleton.bones[b].parent && model.skeleton.bones[b].parent.type === 'Bone') { - for (let bb = 0; bb < put.hierarchy.length; bb++) { - if (put.hierarchy[bb].name === model.skeleton.bones[b].parent.name) { - c_key.parent = bb; - c_key.parentName = model.skeleton.bones[b].parent.name; - } - } - } + break; + } - put.hierarchy.push(c_key); - break; - } - } + case HostComponent: + { + var parentType = returnFiber.type; + var parentProps = returnFiber.memoizedProps; + var parentInstance = returnFiber.stateNode; - if (!findAnimation) { - var _c_key = animation.hierarchy[0].copy(); + switch (fiber.tag) { + case HostComponent: + var _type = fiber.type; + var _props = fiber.pendingProps; + didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props); + break; - _c_key.name = model.skeleton.bones[b].name; - _c_key.parent = -1; + case HostText: + var _text = fiber.pendingProps; + didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text); + break; - for (let k = 0; k < _c_key.keys.length; k++) { - if (_c_key.keys[k].pos) { - _c_key.keys[k].pos.set(0, 0, 0); - } + case SuspenseComponent: + didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance); + break; + } - if (_c_key.keys[k].scl) { - _c_key.keys[k].scl.set(1, 1, 1); - } + break; + } - if (_c_key.keys[k].rot) { - _c_key.keys[k].rot.set(0, 0, 0, 1); - } - } + case SuspenseComponent: + { + var suspenseState = returnFiber.memoizedState; + var _parentInstance = suspenseState.dehydrated; + if (_parentInstance !== null) switch (fiber.tag) { + case HostComponent: + var _type2 = fiber.type; + var _props2 = fiber.pendingProps; + didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2, _props2); + break; - put.hierarchy.push(_c_key); - } - } + case HostText: + var _text2 = fiber.pendingProps; + didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2); + break; - if (!model.geometry.animations) { - model.geometry.animations = []; - } + case SuspenseComponent: + didNotFindHydratableSuspenseInstanceWithinSuspenseInstance(_parentInstance); + break; + } + break; + } - model.geometry.animations.push(AnimationClip.parseAnimation(put, model.skeleton.bones)); + default: + return; + } + } + } - if (!model.animationMixer) { - model.animationMixer = new AnimationMixer(model); - } + function insertNonHydratedInstance(returnFiber, fiber) { + fiber.flags = fiber.flags & ~Hydrating | Placement; + warnNonhydratedInstance(returnFiber, fiber); + } - return put; - } - }, { - key: '_ParseMatrixData', - value: function _ParseMatrixData(targetMatrix, data) { - targetMatrix.set(parseFloat(data[0]), parseFloat(data[4]), parseFloat(data[8]), parseFloat(data[12]), parseFloat(data[1]), parseFloat(data[5]), parseFloat(data[9]), parseFloat(data[13]), parseFloat(data[2]), parseFloat(data[6]), parseFloat(data[10]), parseFloat(data[14]), parseFloat(data[3]), parseFloat(data[7]), parseFloat(data[11]), parseFloat(data[15])); - } - }]); - return XLoader; - }(); + function tryHydrate(fiber, nextInstance) { + switch (fiber.tag) { + case HostComponent: + { + var type = fiber.type; + var props = fiber.pendingProps; + var instance = canHydrateInstance(nextInstance, type, props); - return XLoader; -})(); + if (instance !== null) { + fiber.stateNode = instance; + hydrationParentFiber = fiber; + nextHydratableInstance = getFirstHydratableChild(instance); + return true; + } -var api$3 = {}; + return false; + } -var version = {}; + case HostText: + { + var text = fiber.pendingProps; + var textInstance = canHydrateTextInstance(nextInstance, text); -Object.defineProperty(version, "__esModule", { value: true }); -version.VERSION = void 0; -// needs a separate module as this is required inside chevrotain productive code -// and also in the entry point for webpack(api.ts). -// A separate file avoids cyclic dependencies and webpack errors. -version.VERSION = "10.1.2"; + if (textInstance !== null) { + fiber.stateNode = textInstance; + hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate. -var parser = {}; + nextHydratableInstance = null; + return true; + } -/** Used for built-in method references. */ + return false; + } -var objectProto$l = Object.prototype; + case SuspenseComponent: + { + { + var suspenseInstance = canHydrateSuspenseInstance(nextInstance); -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype$6(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$l; + if (suspenseInstance !== null) { + var suspenseState = { + dehydrated: suspenseInstance, + treeContext: getSuspendedTreeContext(), + retryLane: OffscreenLane + }; + fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. + // This simplifies the code for getHostSibling and deleting nodes, + // since it doesn't have to consider all Suspense boundaries and + // check if they're dehydrated ones or not. - return value === proto; -} + var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); + dehydratedFragment.return = fiber; + fiber.child = dehydratedFragment; + hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into + // it during the first pass. Instead, we'll reenter it later. -var _isPrototype = isPrototype$6; + nextHydratableInstance = null; + return true; + } + } -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ + return false; + } -function overArg$3(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} + default: + return false; + } + } -var _overArg = overArg$3; + function shouldClientRenderOnMismatch(fiber) { + return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags; + } -var overArg$2 = _overArg; + function throwOnHydrationMismatch(fiber) { + throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.'); + } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys$1 = overArg$2(Object.keys, Object); + function tryToClaimNextHydratableInstance(fiber) { + if (!isHydrating) { + return; + } -var _nativeKeys = nativeKeys$1; + var nextInstance = nextHydratableInstance; -var isPrototype$5 = _isPrototype, - nativeKeys = _nativeKeys; + if (!nextInstance) { + if (shouldClientRenderOnMismatch(fiber)) { + warnNonhydratedInstance(hydrationParentFiber, fiber); + throwOnHydrationMismatch(); + } // Nothing to hydrate. Make it an insertion. -/** Used for built-in method references. */ -var objectProto$k = Object.prototype; -/** Used to check objects for own properties. */ -var hasOwnProperty$i = objectProto$k.hasOwnProperty; + insertNonHydratedInstance(hydrationParentFiber, fiber); + isHydrating = false; + hydrationParentFiber = fiber; + return; + } -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys$2(object) { - if (!isPrototype$5(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$i.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; -} + var firstAttemptedInstance = nextInstance; -var _baseKeys = baseKeys$2; + if (!tryHydrate(fiber, nextInstance)) { + if (shouldClientRenderOnMismatch(fiber)) { + warnNonhydratedInstance(hydrationParentFiber, fiber); + throwOnHydrationMismatch(); + } // If we can't hydrate this instance let's try the next one. + // We use this as a heuristic. It's based on intuition and not data so it + // might be flawed or unnecessary. -/** Detect free variable `global` from Node.js. */ -var freeGlobal$3 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + nextInstance = getNextHydratableSibling(firstAttemptedInstance); + var prevHydrationParentFiber = hydrationParentFiber; -var _freeGlobal = freeGlobal$3; + if (!nextInstance || !tryHydrate(fiber, nextInstance)) { + // Nothing to hydrate. Make it an insertion. + insertNonHydratedInstance(hydrationParentFiber, fiber); + isHydrating = false; + hydrationParentFiber = fiber; + return; + } // We matched the next one, we'll now assume that the first one was + // superfluous and we'll delete it. Since we can't eagerly delete it + // we'll have to schedule a deletion. To do that, this node needs a dummy + // fiber associated with it. -var freeGlobal$2 = _freeGlobal; -/** Detect free variable `self`. */ -var freeSelf$2 = typeof self == 'object' && self && self.Object === Object && self; + deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); + } + } -/** Used as a reference to the global object. */ -var root$a = freeGlobal$2 || freeSelf$2 || Function('return this')(); + function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { + if (!supportsHydration) { + throw new Error('Expected prepareToHydrateHostInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -var _root = root$a; + var instance = fiber.stateNode; + var shouldWarnIfMismatchDev = !didSuspend; + var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component. -var root$9 = _root; + fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there + // is a new ref we mark this as an update. -/** Built-in value references. */ -var Symbol$9 = root$9.Symbol; + if (updatePayload !== null) { + return true; + } -var _Symbol = Symbol$9; + return false; + } -var Symbol$8 = _Symbol; + function prepareToHydrateHostTextInstance(fiber) { + if (!supportsHydration) { + throw new Error('Expected prepareToHydrateHostTextInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** Used for built-in method references. */ -var objectProto$j = Object.prototype; + var textInstance = fiber.stateNode; + var textContent = fiber.memoizedProps; + var shouldWarnIfMismatchDev = !didSuspend; + var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber, shouldWarnIfMismatchDev); -/** Used to check objects for own properties. */ -var hasOwnProperty$h = objectProto$j.hasOwnProperty; + if (shouldUpdate) { + // We assume that prepareToHydrateHostTextInstance is called in a context where the + // hydration parent is the parent host component of this host text. + var returnFiber = hydrationParentFiber; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$j.toString; + if (returnFiber !== null) { + var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; -/** Built-in value references. */ -var symToStringTag$1 = Symbol$8 ? Symbol$8.toStringTag : undefined; + switch (returnFiber.tag) { + case HostRoot: + { + var parentContainer = returnFiber.stateNode.containerInfo; + didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. + isConcurrentMode); + break; + } -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag$1(value) { - var isOwn = hasOwnProperty$h.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; + case HostComponent: + { + var parentType = returnFiber.type; + var parentProps = returnFiber.memoizedProps; + var parentInstance = returnFiber.stateNode; + didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. + isConcurrentMode); + break; + } + } + } + } - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString$1.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - return result; -} + return shouldUpdate; + } -var _getRawTag = getRawTag$1; + function prepareToHydrateHostSuspenseInstance(fiber) { + if (!supportsHydration) { + throw new Error('Expected prepareToHydrateHostSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** Used for built-in method references. */ + var suspenseState = fiber.memoizedState; + var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; -var objectProto$i = Object.prototype; + if (!suspenseInstance) { + throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto$i.toString; + hydrateSuspenseInstance(suspenseInstance, fiber); + } -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString$3(value) { - return nativeObjectToString.call(value); -} + function skipPastDehydratedSuspenseInstance(fiber) { + if (!supportsHydration) { + throw new Error('Expected skipPastDehydratedSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -var _objectToString = objectToString$3; + var suspenseState = fiber.memoizedState; + var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; -var Symbol$7 = _Symbol, - getRawTag = _getRawTag, - objectToString$2 = _objectToString; + if (!suspenseInstance) { + throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; + return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); + } -/** Built-in value references. */ -var symToStringTag = Symbol$7 ? Symbol$7.toStringTag : undefined; + function popToNextHostParent(fiber) { + var parent = fiber.return; -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag$7(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString$2(value); -} + while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) { + parent = parent.return; + } -var _baseGetTag = baseGetTag$7; + hydrationParentFiber = parent; + } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ + function popHydrationState(fiber) { + if (!supportsHydration) { + return false; + } -function isObject$b(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} + if (fiber !== hydrationParentFiber) { + // We're deeper than the current hydration context, inside an inserted + // tree. + return false; + } -var isObject_1 = isObject$b; + if (!isHydrating) { + // If we're not currently hydrating but we're in a hydration context, then + // we were an insertion and now need to pop up reenter hydration of our + // siblings. + popToNextHostParent(fiber); + isHydrating = true; + return false; + } // If we have any remaining hydratable nodes, we need to delete them now. + // We only do this deeper than head and body since they tend to have random + // other nodes in them. We also ignore components with pure text content in + // side of them. We also don't delete anything inside the root container. -var baseGetTag$6 = _baseGetTag, - isObject$a = isObject_1; -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]', - funcTag$4 = '[object Function]', - genTag$3 = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; + if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) { + var nextInstance = nextHydratableInstance; -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction$4(value) { - if (!isObject$a(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag$6(value); - return tag == funcTag$4 || tag == genTag$3 || tag == asyncTag || tag == proxyTag; -} + if (nextInstance) { + if (shouldClientRenderOnMismatch(fiber)) { + warnIfUnhydratedTailNodes(fiber); + throwOnHydrationMismatch(); + } else { + while (nextInstance) { + deleteHydratableInstance(fiber, nextInstance); + nextInstance = getNextHydratableSibling(nextInstance); + } + } + } + } -var isFunction_1 = isFunction$4; + popToNextHostParent(fiber); -var root$8 = _root; + if (fiber.tag === SuspenseComponent) { + nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); + } else { + nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; + } -/** Used to detect overreaching core-js shims. */ -var coreJsData$2 = root$8['__core-js_shared__']; + return true; + } -var _coreJsData = coreJsData$2; + function hasUnhydratedTailNodes() { + return isHydrating && nextHydratableInstance !== null; + } -var coreJsData$1 = _coreJsData; + function warnIfUnhydratedTailNodes(fiber) { + var nextInstance = nextHydratableInstance; -/** Used to detect methods masquerading as native. */ -var maskSrcKey$1 = (function() { - var uid = /[^.]+$/.exec(coreJsData$1 && coreJsData$1.keys && coreJsData$1.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); + while (nextInstance) { + warnUnhydratedInstance(fiber, nextInstance); + nextInstance = getNextHydratableSibling(nextInstance); + } + } -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked$2(func) { - return !!maskSrcKey$1 && (maskSrcKey$1 in func); -} + function resetHydrationState() { + if (!supportsHydration) { + return; + } -var _isMasked = isMasked$2; + hydrationParentFiber = null; + nextHydratableInstance = null; + isHydrating = false; + didSuspend = false; + } -/** Used for built-in method references. */ + function upgradeHydrationErrorsToRecoverable() { + if (hydrationErrors !== null) { + // Successfully completed a forced client render. The errors that occurred + // during the hydration attempt are now recovered. We will log them in + // commit phase, once the entire tree has finished. + queueRecoverableErrors(hydrationErrors); + hydrationErrors = null; + } + } -var funcProto$2 = Function.prototype; + function getIsHydrating() { + return isHydrating; + } -/** Used to resolve the decompiled source of functions. */ -var funcToString$2 = funcProto$2.toString; + function queueHydrationError(error) { + if (hydrationErrors === null) { + hydrationErrors = [error]; + } else { + hydrationErrors.push(error); + } + } -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ -function toSource$3(func) { - if (func != null) { - try { - return funcToString$2.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; -} + var didWarnAboutMaps; + var didWarnAboutGenerators; + var didWarnAboutStringRefs; + var ownerHasKeyUseWarning; + var ownerHasFunctionTypeWarning; -var _toSource = toSource$3; + var warnForMissingKey = function (child, returnFiber) {}; -var isFunction$3 = isFunction_1, - isMasked$1 = _isMasked, - isObject$9 = isObject_1, - toSource$2 = _toSource; + { + didWarnAboutMaps = false; + didWarnAboutGenerators = false; + didWarnAboutStringRefs = {}; + /** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g; + ownerHasKeyUseWarning = {}; + ownerHasFunctionTypeWarning = {}; -/** Used to detect host constructors (Safari). */ -var reIsHostCtor$1 = /^\[object .+?Constructor\]$/; + warnForMissingKey = function (child, returnFiber) { + if (child === null || typeof child !== 'object') { + return; + } -/** Used for built-in method references. */ -var funcProto$1 = Function.prototype, - objectProto$h = Object.prototype; + if (!child._store || child._store.validated || child.key != null) { + return; + } -/** Used to resolve the decompiled source of functions. */ -var funcToString$1 = funcProto$1.toString; + if (typeof child._store !== 'object') { + throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.'); + } -/** Used to check objects for own properties. */ -var hasOwnProperty$g = objectProto$h.hasOwnProperty; + child._store.validated = true; + var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; -/** Used to detect if a method is native. */ -var reIsNative$1 = RegExp('^' + - funcToString$1.call(hasOwnProperty$g).replace(reRegExpChar$1, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); + if (ownerHasKeyUseWarning[componentName]) { + return; + } -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative$2(value) { - if (!isObject$9(value) || isMasked$1(value)) { - return false; - } - var pattern = isFunction$3(value) ? reIsNative$1 : reIsHostCtor$1; - return pattern.test(toSource$2(value)); -} + ownerHasKeyUseWarning[componentName] = true; -var _baseIsNative = baseIsNative$2; + error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.'); + }; + } -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ + function coerceRef(returnFiber, current, element) { + var mixedRef = element.ref; -function getValue$2(object, key) { - return object == null ? undefined : object[key]; -} + if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') { + { + // TODO: Clean this up once we turn on the string ref warning for + // everyone, because the strict mode case will no longer be relevant + if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs + // because these cannot be automatically converted to an arrow function + // using a codemod. Therefore, we don't have to warn about string refs again. + !(element._owner && element._self && element._owner.stateNode !== element._self)) { + var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; -var _getValue = getValue$2; + if (!didWarnAboutStringRefs[componentName]) { + { + error('A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', mixedRef); + } -var baseIsNative$1 = _baseIsNative, - getValue$1 = _getValue; + didWarnAboutStringRefs[componentName] = true; + } + } + } -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative$8(object, key) { - var value = getValue$1(object, key); - return baseIsNative$1(value) ? value : undefined; -} + if (element._owner) { + var owner = element._owner; + var inst; -var _getNative = getNative$8; + if (owner) { + var ownerFiber = owner; -var getNative$7 = _getNative, - root$7 = _root; + if (ownerFiber.tag !== ClassComponent) { + throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref'); + } -/* Built-in method references that are verified to be native. */ -var DataView$2 = getNative$7(root$7, 'DataView'); + inst = ownerFiber.stateNode; + } -var _DataView = DataView$2; + if (!inst) { + throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.'); + } // Assigning this to a const so Flow knows it won't change in the closure -var getNative$6 = _getNative, - root$6 = _root; -/* Built-in method references that are verified to be native. */ -var Map$5 = getNative$6(root$6, 'Map'); + var resolvedInst = inst; -var _Map = Map$5; + { + checkPropStringCoercion(mixedRef, 'ref'); + } -var getNative$5 = _getNative, - root$5 = _root; + var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref -/* Built-in method references that are verified to be native. */ -var Promise$2 = getNative$5(root$5, 'Promise'); + if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) { + return current.ref; + } -var _Promise = Promise$2; + var ref = function (value) { + var refs = resolvedInst.refs; -var getNative$4 = _getNative, - root$4 = _root; + if (refs === emptyRefsObject) { + // This is a lazy pooled frozen object, so we need to initialize. + refs = resolvedInst.refs = {}; + } -/* Built-in method references that are verified to be native. */ -var Set$3 = getNative$4(root$4, 'Set'); + if (value === null) { + delete refs[stringRef]; + } else { + refs[stringRef] = value; + } + }; -var _Set = Set$3; + ref._stringRef = stringRef; + return ref; + } else { + if (typeof mixedRef !== 'string') { + throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.'); + } -var getNative$3 = _getNative, - root$3 = _root; + if (!element._owner) { + throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.'); + } + } + } -/* Built-in method references that are verified to be native. */ -var WeakMap$2 = getNative$3(root$3, 'WeakMap'); + return mixedRef; + } -var _WeakMap = WeakMap$2; + function throwOnInvalidObjectType(returnFiber, newChild) { + var childString = Object.prototype.toString.call(newChild); + throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); + } -var DataView$1 = _DataView, - Map$4 = _Map, - Promise$1 = _Promise, - Set$2 = _Set, - WeakMap$1 = _WeakMap, - baseGetTag$5 = _baseGetTag, - toSource$1 = _toSource; + function warnOnFunctionType(returnFiber) { + { + var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; -/** `Object#toString` result references. */ -var mapTag$6 = '[object Map]', - objectTag$3 = '[object Object]', - promiseTag = '[object Promise]', - setTag$6 = '[object Set]', - weakMapTag$2 = '[object WeakMap]'; + if (ownerHasFunctionTypeWarning[componentName]) { + return; + } -var dataViewTag$4 = '[object DataView]'; + ownerHasFunctionTypeWarning[componentName] = true; -/** Used to detect maps, sets, and weakmaps. */ -var dataViewCtorString = toSource$1(DataView$1), - mapCtorString = toSource$1(Map$4), - promiseCtorString = toSource$1(Promise$1), - setCtorString = toSource$1(Set$2), - weakMapCtorString = toSource$1(WeakMap$1); + error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.'); + } + } -/** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -var getTag$6 = baseGetTag$5; - -// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. -if ((DataView$1 && getTag$6(new DataView$1(new ArrayBuffer(1))) != dataViewTag$4) || - (Map$4 && getTag$6(new Map$4) != mapTag$6) || - (Promise$1 && getTag$6(Promise$1.resolve()) != promiseTag) || - (Set$2 && getTag$6(new Set$2) != setTag$6) || - (WeakMap$1 && getTag$6(new WeakMap$1) != weakMapTag$2)) { - getTag$6 = function(value) { - var result = baseGetTag$5(value), - Ctor = result == objectTag$3 ? value.constructor : undefined, - ctorString = Ctor ? toSource$1(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$4; - case mapCtorString: return mapTag$6; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$6; - case weakMapCtorString: return weakMapTag$2; - } - } - return result; - }; -} + function resolveLazy(lazyType) { + var payload = lazyType._payload; + var init = lazyType._init; + return init(payload); + } // This wrapper function exists because I expect to clone the code in each path + // to be able to optimize each path individually by branching early. This needs + // a compiler or we can do it manually. Helpers that don't need this branching + // live outside of this function. -var _getTag = getTag$6; -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ + function ChildReconciler(shouldTrackSideEffects) { + function deleteChild(returnFiber, childToDelete) { + if (!shouldTrackSideEffects) { + // Noop. + return; + } -function isObjectLike$c(value) { - return value != null && typeof value == 'object'; -} + var deletions = returnFiber.deletions; -var isObjectLike_1 = isObjectLike$c; + if (deletions === null) { + returnFiber.deletions = [childToDelete]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(childToDelete); + } + } -var baseGetTag$4 = _baseGetTag, - isObjectLike$b = isObjectLike_1; + function deleteRemainingChildren(returnFiber, currentFirstChild) { + if (!shouldTrackSideEffects) { + // Noop. + return null; + } // TODO: For the shouldClone case, this could be micro-optimized a bit by + // assuming that after the first child we've already added everything. -/** `Object#toString` result references. */ -var argsTag$5 = '[object Arguments]'; -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments$1(value) { - return isObjectLike$b(value) && baseGetTag$4(value) == argsTag$5; -} + var childToDelete = currentFirstChild; -var _baseIsArguments = baseIsArguments$1; + while (childToDelete !== null) { + deleteChild(returnFiber, childToDelete); + childToDelete = childToDelete.sibling; + } -var baseIsArguments = _baseIsArguments, - isObjectLike$a = isObjectLike_1; + return null; + } -/** Used for built-in method references. */ -var objectProto$g = Object.prototype; + function mapRemainingChildren(returnFiber, currentFirstChild) { + // Add the remaining children to a temporary map so that we can find them by + // keys quickly. Implicit (null) keys get added to this set with their index + // instead. + var existingChildren = new Map(); + var existingChild = currentFirstChild; -/** Used to check objects for own properties. */ -var hasOwnProperty$f = objectProto$g.hasOwnProperty; + while (existingChild !== null) { + if (existingChild.key !== null) { + existingChildren.set(existingChild.key, existingChild); + } else { + existingChildren.set(existingChild.index, existingChild); + } -/** Built-in value references. */ -var propertyIsEnumerable$3 = objectProto$g.propertyIsEnumerable; + existingChild = existingChild.sibling; + } -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments$6 = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike$a(value) && hasOwnProperty$f.call(value, 'callee') && - !propertyIsEnumerable$3.call(value, 'callee'); -}; + return existingChildren; + } -var isArguments_1 = isArguments$6; + function useFiber(fiber, pendingProps) { + // We currently set sibling to null and index to 0 here because it is easy + // to forget to do before returning it. E.g. for the single child case. + var clone = createWorkInProgress(fiber, pendingProps); + clone.index = 0; + clone.sibling = null; + return clone; + } -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ + function placeChild(newFiber, lastPlacedIndex, newIndex) { + newFiber.index = newIndex; -var isArray$m = Array.isArray; + if (!shouldTrackSideEffects) { + // During hydration, the useId algorithm needs to know which fibers are + // part of a list of children (arrays, iterators). + newFiber.flags |= Forked; + return lastPlacedIndex; + } -var isArray_1$1 = isArray$m; + var current = newFiber.alternate; -/** Used as references for various `Number` constants. */ + if (current !== null) { + var oldIndex = current.index; -var MAX_SAFE_INTEGER$3 = 9007199254740991; + if (oldIndex < lastPlacedIndex) { + // This is a move. + newFiber.flags |= Placement; + return lastPlacedIndex; + } else { + // This item can stay in place. + return oldIndex; + } + } else { + // This is an insertion. + newFiber.flags |= Placement; + return lastPlacedIndex; + } + } -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength$5(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$3; -} + function placeSingleChild(newFiber) { + // This is simpler for the single child case. We only need to do a + // placement for inserting new children. + if (shouldTrackSideEffects && newFiber.alternate === null) { + newFiber.flags |= Placement; + } -var isLength_1 = isLength$5; + return newFiber; + } -var isFunction$2 = isFunction_1, - isLength$4 = isLength_1; + function updateTextNode(returnFiber, current, textContent, lanes) { + if (current === null || current.tag !== HostText) { + // Insert + var created = createFiberFromText(textContent, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } else { + // Update + var existing = useFiber(current, textContent); + existing.return = returnFiber; + return existing; + } + } -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike$c(value) { - return value != null && isLength$4(value.length) && !isFunction$2(value); -} + function updateElement(returnFiber, current, element, lanes) { + var elementType = element.type; -var isArrayLike_1 = isArrayLike$c; + if (elementType === REACT_FRAGMENT_TYPE) { + return updateFragment(returnFiber, current, element.props.children, lanes, element.key); + } -var isBuffer$4 = {exports: {}}; + if (current !== null) { + if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path: + isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type. + // We need to do this after the Hot Reloading check above, + // because hot reloading has different semantics than prod because + // it doesn't resuspend. So we can't let the call below suspend. + typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) { + // Move based on index + var existing = useFiber(current, element.props); + existing.ref = coerceRef(returnFiber, current, element); + existing.return = returnFiber; -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ + { + existing._debugSource = element._source; + existing._debugOwner = element._owner; + } -function stubFalse() { - return false; -} + return existing; + } + } // Insert -var stubFalse_1 = stubFalse; -(function (module, exports) { - var root = _root, - stubFalse = stubFalse_1; + var created = createFiberFromElement(element, returnFiber.mode, lanes); + created.ref = coerceRef(returnFiber, current, element); + created.return = returnFiber; + return created; + } - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; + function updatePortal(returnFiber, current, portal, lanes) { + if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) { + // Insert + var created = createFiberFromPortal(portal, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } else { + // Update + var existing = useFiber(current, portal.children || []); + existing.return = returnFiber; + return existing; + } + } - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + function updateFragment(returnFiber, current, fragment, lanes, key) { + if (current === null || current.tag !== Fragment) { + // Insert + var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key); + created.return = returnFiber; + return created; + } else { + // Update + var existing = useFiber(current, fragment); + existing.return = returnFiber; + return existing; + } + } - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + function createChild(returnFiber, newChild, lanes) { + if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { + // Text nodes don't have keys. If the previous node is implicitly keyed + // we can continue to replace it without aborting even if it is not a text + // node. + var created = createFiberFromText('' + newChild, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined; + if (typeof newChild === 'object' && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: + { + var _created = createFiberFromElement(newChild, returnFiber.mode, lanes); - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + _created.ref = coerceRef(returnFiber, null, newChild); + _created.return = returnFiber; + return _created; + } - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; + case REACT_PORTAL_TYPE: + { + var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes); - module.exports = isBuffer; -} (isBuffer$4, isBuffer$4.exports)); + _created2.return = returnFiber; + return _created2; + } -var baseGetTag$3 = _baseGetTag, - isLength$3 = isLength_1, - isObjectLike$9 = isObjectLike_1; + case REACT_LAZY_TYPE: + { + { + var payload = newChild._payload; + var init = newChild._init; + return createChild(returnFiber, init(payload), lanes); + } + } + } -/** `Object#toString` result references. */ -var argsTag$4 = '[object Arguments]', - arrayTag$2 = '[object Array]', - boolTag$3 = '[object Boolean]', - dateTag$3 = '[object Date]', - errorTag$2 = '[object Error]', - funcTag$3 = '[object Function]', - mapTag$5 = '[object Map]', - numberTag$3 = '[object Number]', - objectTag$2 = '[object Object]', - regexpTag$4 = '[object RegExp]', - setTag$5 = '[object Set]', - stringTag$4 = '[object String]', - weakMapTag$1 = '[object WeakMap]'; - -var arrayBufferTag$3 = '[object ArrayBuffer]', - dataViewTag$3 = '[object DataView]', - float32Tag$2 = '[object Float32Array]', - float64Tag$2 = '[object Float64Array]', - int8Tag$2 = '[object Int8Array]', - int16Tag$2 = '[object Int16Array]', - int32Tag$2 = '[object Int32Array]', - uint8Tag$2 = '[object Uint8Array]', - uint8ClampedTag$2 = '[object Uint8ClampedArray]', - uint16Tag$2 = '[object Uint16Array]', - uint32Tag$2 = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] = -typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] = -typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] = -typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] = -typedArrayTags[uint32Tag$2] = true; -typedArrayTags[argsTag$4] = typedArrayTags[arrayTag$2] = -typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$3] = -typedArrayTags[dataViewTag$3] = typedArrayTags[dateTag$3] = -typedArrayTags[errorTag$2] = typedArrayTags[funcTag$3] = -typedArrayTags[mapTag$5] = typedArrayTags[numberTag$3] = -typedArrayTags[objectTag$2] = typedArrayTags[regexpTag$4] = -typedArrayTags[setTag$5] = typedArrayTags[stringTag$4] = -typedArrayTags[weakMapTag$1] = false; + if (isArray(newChild) || getIteratorFn(newChild)) { + var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null); -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray$1(value) { - return isObjectLike$9(value) && - isLength$3(value.length) && !!typedArrayTags[baseGetTag$3(value)]; -} + _created3.return = returnFiber; + return _created3; + } -var _baseIsTypedArray = baseIsTypedArray$1; + throwOnInvalidObjectType(returnFiber, newChild); + } -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ + { + if (typeof newChild === 'function') { + warnOnFunctionType(returnFiber); + } + } -function baseUnary$6(func) { - return function(value) { - return func(value); - }; -} + return null; + } -var _baseUnary = baseUnary$6; + function updateSlot(returnFiber, oldFiber, newChild, lanes) { + // Update the fiber if the keys match, otherwise return null. + var key = oldFiber !== null ? oldFiber.key : null; -var _nodeUtil = {exports: {}}; + if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { + // Text nodes don't have keys. If the previous node is implicitly keyed + // we can continue to replace it without aborting even if it is not a text + // node. + if (key !== null) { + return null; + } -(function (module, exports) { - var freeGlobal = _freeGlobal; + return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes); + } - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; + if (typeof newChild === 'object' && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: + { + if (newChild.key === key) { + return updateElement(returnFiber, oldFiber, newChild, lanes); + } else { + return null; + } + } - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + case REACT_PORTAL_TYPE: + { + if (newChild.key === key) { + return updatePortal(returnFiber, oldFiber, newChild, lanes); + } else { + return null; + } + } - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + case REACT_LAZY_TYPE: + { + { + var payload = newChild._payload; + var init = newChild._init; + return updateSlot(returnFiber, oldFiber, init(payload), lanes); + } + } + } - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; + if (isArray(newChild) || getIteratorFn(newChild)) { + if (key !== null) { + return null; + } - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; + return updateFragment(returnFiber, oldFiber, newChild, lanes, null); + } - if (types) { - return types; + throwOnInvalidObjectType(returnFiber, newChild); } - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - module.exports = nodeUtil; -} (_nodeUtil, _nodeUtil.exports)); + { + if (typeof newChild === 'function') { + warnOnFunctionType(returnFiber); + } + } -var baseIsTypedArray = _baseIsTypedArray, - baseUnary$5 = _baseUnary, - nodeUtil$3 = _nodeUtil.exports; + return null; + } -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil$3 && nodeUtil$3.isTypedArray; + function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) { + if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { + // Text nodes don't have keys, so we neither have to check the old nor + // new node for the key. If both are text nodes, they match. + var matchedFiber = existingChildren.get(newIdx) || null; + return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes); + } -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray$3 = nodeIsTypedArray ? baseUnary$5(nodeIsTypedArray) : baseIsTypedArray; + if (typeof newChild === 'object' && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: + { + var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; -var isTypedArray_1 = isTypedArray$3; + return updateElement(returnFiber, _matchedFiber, newChild, lanes); + } -var baseKeys$1 = _baseKeys, - getTag$5 = _getTag, - isArguments$5 = isArguments_1, - isArray$l = isArray_1$1, - isArrayLike$b = isArrayLike_1, - isBuffer$3 = isBuffer$4.exports, - isPrototype$4 = _isPrototype, - isTypedArray$2 = isTypedArray_1; + case REACT_PORTAL_TYPE: + { + var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; -/** `Object#toString` result references. */ -var mapTag$4 = '[object Map]', - setTag$4 = '[object Set]'; + return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); + } -/** Used for built-in method references. */ -var objectProto$f = Object.prototype; + case REACT_LAZY_TYPE: + { + var payload = newChild._payload; + var init = newChild._init; + return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes); + } -/** Used to check objects for own properties. */ -var hasOwnProperty$e = objectProto$f.hasOwnProperty; + } -/** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ -function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike$b(value) && - (isArray$l(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer$3(value) || isTypedArray$2(value) || isArguments$5(value))) { - return !value.length; - } - var tag = getTag$5(value); - if (tag == mapTag$4 || tag == setTag$4) { - return !value.size; - } - if (isPrototype$4(value)) { - return !baseKeys$1(value).length; - } - for (var key in value) { - if (hasOwnProperty$e.call(value, key)) { - return false; - } - } - return true; -} + if (isArray(newChild) || getIteratorFn(newChild)) { + var _matchedFiber3 = existingChildren.get(newIdx) || null; -var isEmpty_1$1 = isEmpty; + return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null); + } -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ + throwOnInvalidObjectType(returnFiber, newChild); + } -function arrayMap$7(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); + { + if (typeof newChild === 'function') { + warnOnFunctionType(returnFiber); + } + } - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} + return null; + } + /** + * Warns if there is a duplicate or missing key + */ -var _arrayMap = arrayMap$7; -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ + function warnOnInvalidKey(child, knownKeys, returnFiber) { + { + if (typeof child !== 'object' || child === null) { + return knownKeys; + } -function listCacheClear$2() { - this.__data__ = []; - this.size = 0; -} + switch (child.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + warnForMissingKey(child, returnFiber); + var key = child.key; -var _listCacheClear = listCacheClear$2; + if (typeof key !== 'string') { + break; + } -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ + if (knownKeys === null) { + knownKeys = new Set(); + knownKeys.add(key); + break; + } -function eq$6(value, other) { - return value === other || (value !== value && other !== other); -} + if (!knownKeys.has(key)) { + knownKeys.add(key); + break; + } -var eq_1 = eq$6; + error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key); -var eq$5 = eq_1; + break; -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf$5(array, key) { - var length = array.length; - while (length--) { - if (eq$5(array[length][0], key)) { - return length; - } - } - return -1; -} + case REACT_LAZY_TYPE: + { + var payload = child._payload; + var init = child._init; + warnOnInvalidKey(init(payload), knownKeys, returnFiber); + break; + } + } + } -var _assocIndexOf = assocIndexOf$5; + return knownKeys; + } -var assocIndexOf$4 = _assocIndexOf; + function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) { + // This algorithm can't optimize by searching from both ends since we + // don't have backpointers on fibers. I'm trying to see how far we can get + // with that model. If it ends up not being worth the tradeoffs, we can + // add it later. + // Even with a two ended optimization, we'd want to optimize for the case + // where there are few changes and brute force the comparison instead of + // going for the Map. It'd like to explore hitting that path first in + // forward-only mode and only go for the Map once we notice that we need + // lots of look ahead. This doesn't handle reversal as well as two ended + // search but that's unusual. Besides, for the two ended optimization to + // work on Iterables, we'd need to copy the whole set. + // In this first iteration, we'll just live with hitting the bad case + // (adding everything to a Map) in for every insert/move. + // If you change this code, also update reconcileChildrenIterator() which + // uses the same algorithm. + { + // First, validate keys. + var knownKeys = null; -/** Used for built-in method references. */ -var arrayProto$1 = Array.prototype; + for (var i = 0; i < newChildren.length; i++) { + var child = newChildren[i]; + knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); + } + } -/** Built-in value references. */ -var splice$1 = arrayProto$1.splice; + var resultingFirstChild = null; + var previousNewFiber = null; + var oldFiber = currentFirstChild; + var lastPlacedIndex = 0; + var newIdx = 0; + var nextOldFiber = null; -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete$2(key) { - var data = this.__data__, - index = assocIndexOf$4(data, key); + for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { + if (oldFiber.index > newIdx) { + nextOldFiber = oldFiber; + oldFiber = null; + } else { + nextOldFiber = oldFiber.sibling; + } - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice$1.call(data, index, 1); - } - --this.size; - return true; -} + var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes); -var _listCacheDelete = listCacheDelete$2; + if (newFiber === null) { + // TODO: This breaks on empty slots like null children. That's + // unfortunate because it triggers the slow path all the time. We need + // a better way to communicate whether this was a miss or null, + // boolean, undefined, etc. + if (oldFiber === null) { + oldFiber = nextOldFiber; + } -var assocIndexOf$3 = _assocIndexOf; + break; + } -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet$2(key) { - var data = this.__data__, - index = assocIndexOf$3(data, key); + if (shouldTrackSideEffects) { + if (oldFiber && newFiber.alternate === null) { + // We matched the slot, but we didn't reuse the existing fiber, so we + // need to delete the existing child. + deleteChild(returnFiber, oldFiber); + } + } - return index < 0 ? undefined : data[index][1]; -} + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); -var _listCacheGet = listCacheGet$2; + if (previousNewFiber === null) { + // TODO: Move out of the loop. This only happens for the first run. + resultingFirstChild = newFiber; + } else { + // TODO: Defer siblings if we're not at the right index for this slot. + // I.e. if we had null values before, then we want to defer this + // for each null value. However, we also don't want to call updateSlot + // with the previous one. + previousNewFiber.sibling = newFiber; + } -var assocIndexOf$2 = _assocIndexOf; + previousNewFiber = newFiber; + oldFiber = nextOldFiber; + } -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas$2(key) { - return assocIndexOf$2(this.__data__, key) > -1; -} + if (newIdx === newChildren.length) { + // We've reached the end of the new children. We can delete the rest. + deleteRemainingChildren(returnFiber, oldFiber); -var _listCacheHas = listCacheHas$2; + if (getIsHydrating()) { + var numberOfForks = newIdx; + pushTreeFork(returnFiber, numberOfForks); + } -var assocIndexOf$1 = _assocIndexOf; + return resultingFirstChild; + } -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet$2(key, value) { - var data = this.__data__, - index = assocIndexOf$1(data, key); + if (oldFiber === null) { + // If we don't have any more existing children we can choose a fast path + // since the rest will all be insertions. + for (; newIdx < newChildren.length; newIdx++) { + var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes); - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} + if (_newFiber === null) { + continue; + } -var _listCacheSet = listCacheSet$2; + lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); -var listCacheClear$1 = _listCacheClear, - listCacheDelete$1 = _listCacheDelete, - listCacheGet$1 = _listCacheGet, - listCacheHas$1 = _listCacheHas, - listCacheSet$1 = _listCacheSet; + if (previousNewFiber === null) { + // TODO: Move out of the loop. This only happens for the first run. + resultingFirstChild = _newFiber; + } else { + previousNewFiber.sibling = _newFiber; + } -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache$5(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + previousNewFiber = _newFiber; + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + if (getIsHydrating()) { + var _numberOfForks = newIdx; + pushTreeFork(returnFiber, _numberOfForks); + } -// Add methods to `ListCache`. -ListCache$5.prototype.clear = listCacheClear$1; -ListCache$5.prototype['delete'] = listCacheDelete$1; -ListCache$5.prototype.get = listCacheGet$1; -ListCache$5.prototype.has = listCacheHas$1; -ListCache$5.prototype.set = listCacheSet$1; + return resultingFirstChild; + } // Add all children to a key map for quick lookups. -var _ListCache = ListCache$5; -var ListCache$4 = _ListCache; + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. -/** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ -function stackClear$1() { - this.__data__ = new ListCache$4; - this.size = 0; -} + for (; newIdx < newChildren.length; newIdx++) { + var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes); -var _stackClear = stackClear$1; + if (_newFiber2 !== null) { + if (shouldTrackSideEffects) { + if (_newFiber2.alternate !== null) { + // The new fiber is a work in progress, but if there exists a + // current, that means that we reused the fiber. We need to delete + // it from the child list so that we don't add it to the deletion + // list. + existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key); + } + } -/** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ + lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); -function stackDelete$1(key) { - var data = this.__data__, - result = data['delete'](key); + if (previousNewFiber === null) { + resultingFirstChild = _newFiber2; + } else { + previousNewFiber.sibling = _newFiber2; + } - this.size = data.size; - return result; -} + previousNewFiber = _newFiber2; + } + } -var _stackDelete = stackDelete$1; + if (shouldTrackSideEffects) { + // Any existing children that weren't consumed above were deleted. We need + // to add them to the deletion list. + existingChildren.forEach(function (child) { + return deleteChild(returnFiber, child); + }); + } -/** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ + if (getIsHydrating()) { + var _numberOfForks2 = newIdx; + pushTreeFork(returnFiber, _numberOfForks2); + } -function stackGet$1(key) { - return this.__data__.get(key); -} + return resultingFirstChild; + } -var _stackGet = stackGet$1; + function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) { + // This is the same implementation as reconcileChildrenArray(), + // but using the iterator instead. + var iteratorFn = getIteratorFn(newChildrenIterable); -/** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ + if (typeof iteratorFn !== 'function') { + throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.'); + } -function stackHas$1(key) { - return this.__data__.has(key); -} + { + // We don't support rendering Generators because it's a mutation. + // See https://github.com/facebook/react/issues/12995 + if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag + newChildrenIterable[Symbol.toStringTag] === 'Generator') { + if (!didWarnAboutGenerators) { + error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); + } -var _stackHas = stackHas$1; + didWarnAboutGenerators = true; + } // Warn about using Maps as children -var getNative$2 = _getNative; -/* Built-in method references that are verified to be native. */ -var nativeCreate$5 = getNative$2(Object, 'create'); + if (newChildrenIterable.entries === iteratorFn) { + if (!didWarnAboutMaps) { + error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); + } -var _nativeCreate = nativeCreate$5; + didWarnAboutMaps = true; + } // First, validate keys. + // We'll get a different iterator later for the main pass. -var nativeCreate$4 = _nativeCreate; -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear$2() { - this.__data__ = nativeCreate$4 ? nativeCreate$4(null) : {}; - this.size = 0; -} + var _newChildren = iteratorFn.call(newChildrenIterable); -var _hashClear = hashClear$2; + if (_newChildren) { + var knownKeys = null; -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ + var _step = _newChildren.next(); -function hashDelete$2(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; -} + for (; !_step.done; _step = _newChildren.next()) { + var child = _step.value; + knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); + } + } + } -var _hashDelete = hashDelete$2; + var newChildren = iteratorFn.call(newChildrenIterable); -var nativeCreate$3 = _nativeCreate; + if (newChildren == null) { + throw new Error('An iterable object provided no iterator.'); + } -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$3 = '__lodash_hash_undefined__'; + var resultingFirstChild = null; + var previousNewFiber = null; + var oldFiber = currentFirstChild; + var lastPlacedIndex = 0; + var newIdx = 0; + var nextOldFiber = null; + var step = newChildren.next(); -/** Used for built-in method references. */ -var objectProto$e = Object.prototype; + for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { + if (oldFiber.index > newIdx) { + nextOldFiber = oldFiber; + oldFiber = null; + } else { + nextOldFiber = oldFiber.sibling; + } -/** Used to check objects for own properties. */ -var hasOwnProperty$d = objectProto$e.hasOwnProperty; + var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet$2(key) { - var data = this.__data__; - if (nativeCreate$3) { - var result = data[key]; - return result === HASH_UNDEFINED$3 ? undefined : result; - } - return hasOwnProperty$d.call(data, key) ? data[key] : undefined; -} + if (newFiber === null) { + // TODO: This breaks on empty slots like null children. That's + // unfortunate because it triggers the slow path all the time. We need + // a better way to communicate whether this was a miss or null, + // boolean, undefined, etc. + if (oldFiber === null) { + oldFiber = nextOldFiber; + } -var _hashGet = hashGet$2; + break; + } -var nativeCreate$2 = _nativeCreate; + if (shouldTrackSideEffects) { + if (oldFiber && newFiber.alternate === null) { + // We matched the slot, but we didn't reuse the existing fiber, so we + // need to delete the existing child. + deleteChild(returnFiber, oldFiber); + } + } -/** Used for built-in method references. */ -var objectProto$d = Object.prototype; + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); -/** Used to check objects for own properties. */ -var hasOwnProperty$c = objectProto$d.hasOwnProperty; + if (previousNewFiber === null) { + // TODO: Move out of the loop. This only happens for the first run. + resultingFirstChild = newFiber; + } else { + // TODO: Defer siblings if we're not at the right index for this slot. + // I.e. if we had null values before, then we want to defer this + // for each null value. However, we also don't want to call updateSlot + // with the previous one. + previousNewFiber.sibling = newFiber; + } -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas$2(key) { - var data = this.__data__; - return nativeCreate$2 ? (data[key] !== undefined) : hasOwnProperty$c.call(data, key); -} + previousNewFiber = newFiber; + oldFiber = nextOldFiber; + } -var _hashHas = hashHas$2; + if (step.done) { + // We've reached the end of the new children. We can delete the rest. + deleteRemainingChildren(returnFiber, oldFiber); -var nativeCreate$1 = _nativeCreate; + if (getIsHydrating()) { + var numberOfForks = newIdx; + pushTreeFork(returnFiber, numberOfForks); + } -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + return resultingFirstChild; + } -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet$2(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate$1 && value === undefined) ? HASH_UNDEFINED$2 : value; - return this; -} + if (oldFiber === null) { + // If we don't have any more existing children we can choose a fast path + // since the rest will all be insertions. + for (; !step.done; newIdx++, step = newChildren.next()) { + var _newFiber3 = createChild(returnFiber, step.value, lanes); -var _hashSet = hashSet$2; + if (_newFiber3 === null) { + continue; + } -var hashClear$1 = _hashClear, - hashDelete$1 = _hashDelete, - hashGet$1 = _hashGet, - hashHas$1 = _hashHas, - hashSet$1 = _hashSet; + lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash$2(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + if (previousNewFiber === null) { + // TODO: Move out of the loop. This only happens for the first run. + resultingFirstChild = _newFiber3; + } else { + previousNewFiber.sibling = _newFiber3; + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + previousNewFiber = _newFiber3; + } + + if (getIsHydrating()) { + var _numberOfForks3 = newIdx; + pushTreeFork(returnFiber, _numberOfForks3); + } -// Add methods to `Hash`. -Hash$2.prototype.clear = hashClear$1; -Hash$2.prototype['delete'] = hashDelete$1; -Hash$2.prototype.get = hashGet$1; -Hash$2.prototype.has = hashHas$1; -Hash$2.prototype.set = hashSet$1; + return resultingFirstChild; + } // Add all children to a key map for quick lookups. -var _Hash = Hash$2; -var Hash$1 = _Hash, - ListCache$3 = _ListCache, - Map$3 = _Map; + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear$2() { - this.size = 0; - this.__data__ = { - 'hash': new Hash$1, - 'map': new (Map$3 || ListCache$3), - 'string': new Hash$1 - }; -} + for (; !step.done; newIdx++, step = newChildren.next()) { + var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes); -var _mapCacheClear = mapCacheClear$2; + if (_newFiber4 !== null) { + if (shouldTrackSideEffects) { + if (_newFiber4.alternate !== null) { + // The new fiber is a work in progress, but if there exists a + // current, that means that we reused the fiber. We need to delete + // it from the child list so that we don't add it to the deletion + // list. + existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key); + } + } -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ + lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); -function isKeyable$2(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); -} + if (previousNewFiber === null) { + resultingFirstChild = _newFiber4; + } else { + previousNewFiber.sibling = _newFiber4; + } -var _isKeyable = isKeyable$2; + previousNewFiber = _newFiber4; + } + } -var isKeyable$1 = _isKeyable; + if (shouldTrackSideEffects) { + // Any existing children that weren't consumed above were deleted. We need + // to add them to the deletion list. + existingChildren.forEach(function (child) { + return deleteChild(returnFiber, child); + }); + } -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData$5(map, key) { - var data = map.__data__; - return isKeyable$1(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} + if (getIsHydrating()) { + var _numberOfForks4 = newIdx; + pushTreeFork(returnFiber, _numberOfForks4); + } -var _getMapData = getMapData$5; + return resultingFirstChild; + } -var getMapData$4 = _getMapData; + function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) { + // There's no need to check for keys on text nodes since we don't have a + // way to define them. + if (currentFirstChild !== null && currentFirstChild.tag === HostText) { + // We already have an existing node so let's just update it and delete + // the rest. + deleteRemainingChildren(returnFiber, currentFirstChild.sibling); + var existing = useFiber(currentFirstChild, textContent); + existing.return = returnFiber; + return existing; + } // The existing first child is not a text node so we need to create one + // and delete the existing ones. -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete$2(key) { - var result = getMapData$4(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; -} -var _mapCacheDelete = mapCacheDelete$2; + deleteRemainingChildren(returnFiber, currentFirstChild); + var created = createFiberFromText(textContent, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } -var getMapData$3 = _getMapData; + function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) { + var key = element.key; + var child = currentFirstChild; -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet$2(key) { - return getMapData$3(this, key).get(key); -} + while (child !== null) { + // TODO: If key === null and child.key === null, then this only applies to + // the first item in the list. + if (child.key === key) { + var elementType = element.type; -var _mapCacheGet = mapCacheGet$2; + if (elementType === REACT_FRAGMENT_TYPE) { + if (child.tag === Fragment) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, element.props.children); + existing.return = returnFiber; -var getMapData$2 = _getMapData; + { + existing._debugSource = element._source; + existing._debugOwner = element._owner; + } -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas$2(key) { - return getMapData$2(this, key).has(key); -} + return existing; + } + } else { + if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path: + isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type. + // We need to do this after the Hot Reloading check above, + // because hot reloading has different semantics than prod because + // it doesn't resuspend. So we can't let the call below suspend. + typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) { + deleteRemainingChildren(returnFiber, child.sibling); -var _mapCacheHas = mapCacheHas$2; + var _existing = useFiber(child, element.props); -var getMapData$1 = _getMapData; + _existing.ref = coerceRef(returnFiber, child, element); + _existing.return = returnFiber; -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet$2(key, value) { - var data = getMapData$1(this, key), - size = data.size; + { + _existing._debugSource = element._source; + _existing._debugOwner = element._owner; + } - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; -} + return _existing; + } + } // Didn't match. -var _mapCacheSet = mapCacheSet$2; -var mapCacheClear$1 = _mapCacheClear, - mapCacheDelete$1 = _mapCacheDelete, - mapCacheGet$1 = _mapCacheGet, - mapCacheHas$1 = _mapCacheHas, - mapCacheSet$1 = _mapCacheSet; + deleteRemainingChildren(returnFiber, child); + break; + } else { + deleteChild(returnFiber, child); + } -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache$4(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + child = child.sibling; + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + if (element.type === REACT_FRAGMENT_TYPE) { + var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key); + created.return = returnFiber; + return created; + } else { + var _created4 = createFiberFromElement(element, returnFiber.mode, lanes); -// Add methods to `MapCache`. -MapCache$4.prototype.clear = mapCacheClear$1; -MapCache$4.prototype['delete'] = mapCacheDelete$1; -MapCache$4.prototype.get = mapCacheGet$1; -MapCache$4.prototype.has = mapCacheHas$1; -MapCache$4.prototype.set = mapCacheSet$1; + _created4.ref = coerceRef(returnFiber, currentFirstChild, element); + _created4.return = returnFiber; + return _created4; + } + } -var _MapCache = MapCache$4; + function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) { + var key = portal.key; + var child = currentFirstChild; -var ListCache$2 = _ListCache, - Map$2 = _Map, - MapCache$3 = _MapCache; + while (child !== null) { + // TODO: If key === null and child.key === null, then this only applies to + // the first item in the list. + if (child.key === key) { + if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, portal.children || []); + existing.return = returnFiber; + return existing; + } else { + deleteRemainingChildren(returnFiber, child); + break; + } + } else { + deleteChild(returnFiber, child); + } -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE$3 = 200; + child = child.sibling; + } -/** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ -function stackSet$1(key, value) { - var data = this.__data__; - if (data instanceof ListCache$2) { - var pairs = data.__data__; - if (!Map$2 || (pairs.length < LARGE_ARRAY_SIZE$3 - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache$3(pairs); - } - data.set(key, value); - this.size = data.size; - return this; -} + var created = createFiberFromPortal(portal, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } // This API will tag the children with the side-effect of the reconciliation + // itself. They will be added to the side-effect list as we pass through the + // children and the parent. -var _stackSet = stackSet$1; -var ListCache$1 = _ListCache, - stackClear = _stackClear, - stackDelete = _stackDelete, - stackGet = _stackGet, - stackHas = _stackHas, - stackSet = _stackSet; + function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) { + // This function is not recursive. + // If the top level item is an array, we treat it as a set of children, + // not as a fragment. Nested arrays on the other hand will be treated as + // fragment nodes. Recursion happens at the normal flow. + // Handle top level unkeyed fragments as if they were arrays. + // This leads to an ambiguity between <>{[...]} and <>.... + // We treat the ambiguous cases above the same. + var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; -/** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Stack$3(entries) { - var data = this.__data__ = new ListCache$1(entries); - this.size = data.size; -} + if (isUnkeyedTopLevelFragment) { + newChild = newChild.props.children; + } // Handle object types -// Add methods to `Stack`. -Stack$3.prototype.clear = stackClear; -Stack$3.prototype['delete'] = stackDelete; -Stack$3.prototype.get = stackGet; -Stack$3.prototype.has = stackHas; -Stack$3.prototype.set = stackSet; -var _Stack = Stack$3; + if (typeof newChild === 'object' && newChild !== null) { + switch (newChild.$$typeof) { + case REACT_ELEMENT_TYPE: + return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes)); -/** Used to stand-in for `undefined` hash values. */ + case REACT_PORTAL_TYPE: + return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes)); -var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + case REACT_LAZY_TYPE: + { + var payload = newChild._payload; + var init = newChild._init; // TODO: This function is supposed to be non-recursive. -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd$2(value) { - this.__data__.set(value, HASH_UNDEFINED$1); - return this; -} + return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes); + } -var _setCacheAdd = setCacheAdd$2; + } -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ + if (isArray(newChild)) { + return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes); + } -function setCacheHas$2(value) { - return this.__data__.has(value); -} + if (getIteratorFn(newChild)) { + return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes); + } -var _setCacheHas = setCacheHas$2; + throwOnInvalidObjectType(returnFiber, newChild); + } -var MapCache$2 = _MapCache, - setCacheAdd$1 = _setCacheAdd, - setCacheHas$1 = _setCacheHas; + if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { + return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes)); + } -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache$4(values) { - var index = -1, - length = values == null ? 0 : values.length; + { + if (typeof newChild === 'function') { + warnOnFunctionType(returnFiber); + } + } // Remaining cases are all treated as empty. - this.__data__ = new MapCache$2; - while (++index < length) { - this.add(values[index]); - } -} -// Add methods to `SetCache`. -SetCache$4.prototype.add = SetCache$4.prototype.push = setCacheAdd$1; -SetCache$4.prototype.has = setCacheHas$1; + return deleteRemainingChildren(returnFiber, currentFirstChild); + } -var _SetCache = SetCache$4; + return reconcileChildFibers; + } -/** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ + var reconcileChildFibers = ChildReconciler(true); + var mountChildFibers = ChildReconciler(false); + function cloneChildFibers(current, workInProgress) { + if (current !== null && workInProgress.child !== current.child) { + throw new Error('Resuming work not yet implemented.'); + } -function arraySome$2(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; + if (workInProgress.child === null) { + return; + } - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; -} + var currentChild = workInProgress.child; + var newChild = createWorkInProgress(currentChild, currentChild.pendingProps); + workInProgress.child = newChild; + newChild.return = workInProgress; -var _arraySome = arraySome$2; + while (currentChild.sibling !== null) { + currentChild = currentChild.sibling; + newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps); + newChild.return = workInProgress; + } -/** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ + newChild.sibling = null; + } // Reset a workInProgress child set to prepare it for a second pass. -function cacheHas$4(cache, key) { - return cache.has(key); -} + function resetChildFibers(workInProgress, lanes) { + var child = workInProgress.child; -var _cacheHas = cacheHas$4; + while (child !== null) { + resetWorkInProgress(child, lanes); + child = child.sibling; + } + } -var SetCache$3 = _SetCache, - arraySome$1 = _arraySome, - cacheHas$3 = _cacheHas; + var NO_CONTEXT = {}; + var contextStackCursor$1 = createCursor(NO_CONTEXT); + var contextFiberStackCursor = createCursor(NO_CONTEXT); + var rootInstanceStackCursor = createCursor(NO_CONTEXT); -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; + function requiredContext(c) { + if (c === NO_CONTEXT) { + throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.'); + } -/** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ -function equalArrays$2(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5, - arrLength = array.length, - othLength = other.length; + return c; + } - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new SetCache$3 : undefined; + function getRootHostContainer() { + var rootInstance = requiredContext(rootInstanceStackCursor.current); + return rootInstance; + } - stack.set(array, other); - stack.set(other, array); + function pushHostContainer(fiber, nextRootInstance) { + // Push current root instance onto the stack; + // This allows us to reset root when portals are popped. + push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. + // This enables us to pop only Fibers that provide unique contexts. - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; + push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. + // However, we can't just call getRootHostContext() and push it because + // we'd have a different number of entries on the stack depending on + // whether getRootHostContext() throws somewhere in renderer code or not. + // So we push an empty value first. This lets us safely unwind on errors. - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome$1(other, function(othValue, othIndex) { - if (!cacheHas$3(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; -} + push(contextStackCursor$1, NO_CONTEXT, fiber); + var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. -var _equalArrays = equalArrays$2; + pop(contextStackCursor$1, fiber); + push(contextStackCursor$1, nextRootContext, fiber); + } -var root$2 = _root; + function popHostContainer(fiber) { + pop(contextStackCursor$1, fiber); + pop(contextFiberStackCursor, fiber); + pop(rootInstanceStackCursor, fiber); + } -/** Built-in value references. */ -var Uint8Array$3 = root$2.Uint8Array; + function getHostContext() { + var context = requiredContext(contextStackCursor$1.current); + return context; + } -var _Uint8Array = Uint8Array$3; + function pushHostContext(fiber) { + var rootInstance = requiredContext(rootInstanceStackCursor.current); + var context = requiredContext(contextStackCursor$1.current); + var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique. -/** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ + if (context === nextContext) { + return; + } // Track the context and the Fiber that provided it. + // This enables us to pop only Fibers that provide unique contexts. -function mapToArray$1(map) { - var index = -1, - result = Array(map.size); - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; -} + push(contextFiberStackCursor, fiber, fiber); + push(contextStackCursor$1, nextContext, fiber); + } -var _mapToArray = mapToArray$1; + function popHostContext(fiber) { + // Do not pop unless this Fiber provided the current context. + // pushHostContext() only pushes Fibers that provide unique contexts. + if (contextFiberStackCursor.current !== fiber) { + return; + } -/** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ + pop(contextStackCursor$1, fiber); + pop(contextFiberStackCursor, fiber); + } -function setToArray$3(set) { - var index = -1, - result = Array(set.size); + var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is + // inherited deeply down the subtree. The upper bits only affect + // this immediate suspense boundary and gets reset each new + // boundary or suspense list. - set.forEach(function(value) { - result[++index] = value; - }); - return result; -} + var SubtreeSuspenseContextMask = 1; // Subtree Flags: + // InvisibleParentSuspenseContext indicates that one of our parent Suspense + // boundaries is not currently showing visible main content. + // Either because it is already showing a fallback or is not mounted at all. + // We can use this to determine if it is desirable to trigger a fallback at + // the parent. If not, then we might need to trigger undesirable boundaries + // and/or suspend the commit to avoid hiding the parent content. -var _setToArray = setToArray$3; + var InvisibleParentSuspenseContext = 1; // Shallow Flags: + // ForceSuspenseFallback can be used by SuspenseList to force newly added + // items into their fallback state during one of the render passes. -var Symbol$6 = _Symbol, - Uint8Array$2 = _Uint8Array, - eq$4 = eq_1, - equalArrays$1 = _equalArrays, - mapToArray = _mapToArray, - setToArray$2 = _setToArray; + var ForceSuspenseFallback = 2; + var suspenseStackCursor = createCursor(DefaultSuspenseContext); + function hasSuspenseContext(parentContext, flag) { + return (parentContext & flag) !== 0; + } + function setDefaultShallowSuspenseContext(parentContext) { + return parentContext & SubtreeSuspenseContextMask; + } + function setShallowSuspenseContext(parentContext, shallowContext) { + return parentContext & SubtreeSuspenseContextMask | shallowContext; + } + function addSubtreeSuspenseContext(parentContext, subtreeContext) { + return parentContext | subtreeContext; + } + function pushSuspenseContext(fiber, newContext) { + push(suspenseStackCursor, newContext, fiber); + } + function popSuspenseContext(fiber) { + pop(suspenseStackCursor, fiber); + } -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; + function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { + // If it was the primary children that just suspended, capture and render the + // fallback. Otherwise, don't capture and bubble to the next boundary. + var nextState = workInProgress.memoizedState; -/** `Object#toString` result references. */ -var boolTag$2 = '[object Boolean]', - dateTag$2 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$3 = '[object Map]', - numberTag$2 = '[object Number]', - regexpTag$3 = '[object RegExp]', - setTag$3 = '[object Set]', - stringTag$3 = '[object String]', - symbolTag$5 = '[object Symbol]'; - -var arrayBufferTag$2 = '[object ArrayBuffer]', - dataViewTag$2 = '[object DataView]'; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto$2 = Symbol$6 ? Symbol$6.prototype : undefined, - symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; + if (nextState !== null) { + if (nextState.dehydrated !== null) { + // A dehydrated boundary always captures. + return true; + } -/** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalByTag$1(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$2: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; + return false; + } - case arrayBufferTag$2: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array$2(object), new Uint8Array$2(other))) { - return false; - } - return true; + workInProgress.memoizedProps; // Regular boundaries always capture. - case boolTag$2: - case dateTag$2: - case numberTag$2: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq$4(+object, +other); + { + return true; + } // If it's a boundary we should avoid, then we prefer to bubble up to the + } + function findFirstSuspended(row) { + var node = row; - case errorTag$1: - return object.name == other.name && object.message == other.message; + while (node !== null) { + if (node.tag === SuspenseComponent) { + var state = node.memoizedState; - case regexpTag$3: - case stringTag$3: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); + if (state !== null) { + var dehydrated = state.dehydrated; - case mapTag$3: - var convert = mapToArray; + if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) { + return node; + } + } + } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't + // keep track of whether it suspended or not. + node.memoizedProps.revealOrder !== undefined) { + var didSuspend = (node.flags & DidCapture) !== NoFlags; - case setTag$3: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4; - convert || (convert = setToArray$2); + if (didSuspend) { + return node; + } + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$2; + if (node === row) { + return null; + } - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays$1(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; + while (node.sibling === null) { + if (node.return === null || node.return === row) { + return null; + } - case symbolTag$5: - if (symbolValueOf$1) { - return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); - } - } - return false; -} + node = node.return; + } -var _equalByTag = equalByTag$1; + node.sibling.return = node.return; + node = node.sibling; + } -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ + return null; + } -function arrayPush$5(array, values) { - var index = -1, - length = values.length, - offset = array.length; + var NoFlags$1 = + /* */ + 0; // Represents whether effect should fire. - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} + var HasEffect = + /* */ + 1; // Represents the phase in which the effect (not the clean-up) fires. -var _arrayPush = arrayPush$5; + var Insertion = + /* */ + 2; + var Layout = + /* */ + 4; + var Passive$1 = + /* */ + 8; -var arrayPush$4 = _arrayPush, - isArray$k = isArray_1$1; + // and should be reset before starting a new render. + // This tracks which mutable sources need to be reset after a render. -/** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ -function baseGetAllKeys$3(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray$k(object) ? result : arrayPush$4(result, symbolsFunc(object)); -} + var workInProgressSources = []; + function resetWorkInProgressVersions() { + for (var i = 0; i < workInProgressSources.length; i++) { + var mutableSource = workInProgressSources[i]; -var _baseGetAllKeys = baseGetAllKeys$3; + if (isPrimaryRenderer) { + mutableSource._workInProgressVersionPrimary = null; + } else { + mutableSource._workInProgressVersionSecondary = null; + } + } -/** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ + workInProgressSources.length = 0; + } + // This ensures that the version used for server rendering matches the one + // that is eventually read during hydration. + // If they don't match there's a potential tear and a full deopt render is required. -function arrayFilter$3(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + function registerMutableSourceForHydration(root, mutableSource) { + var getVersion = mutableSource._getVersion; + var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished. + // Retaining it forever may interfere with GC. - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; -} + if (root.mutableSourceEagerHydrationData == null) { + root.mutableSourceEagerHydrationData = [mutableSource, version]; + } else { + root.mutableSourceEagerHydrationData.push(mutableSource, version); + } + } -var _arrayFilter = arrayFilter$3; + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, + ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; + var didWarnAboutMismatchedHooksForComponent; + var didWarnUncachedGetSnapshot; -/** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ + { + didWarnAboutMismatchedHooksForComponent = new Set(); + } -function stubArray$3() { - return []; -} + // These are set right before calling the component. + var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from + // the work-in-progress hook. -var stubArray_1 = stubArray$3; + var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The + // current hook list is the list that belongs to the current fiber. The + // work-in-progress hook list is a new list that will be added to the + // work-in-progress fiber. -var arrayFilter$2 = _arrayFilter, - stubArray$2 = stubArray_1; + var currentHook = null; + var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This + // does not get reset if we do another render pass; only when we're completely + // finished evaluating this component. This is an optimization so we know + // whether we need to clear render phase updates after a throw. -/** Used for built-in method references. */ -var objectProto$c = Object.prototype; + var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This + // gets reset after each attempt. + // TODO: Maybe there's some way to consolidate this with + // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`. -/** Built-in value references. */ -var propertyIsEnumerable$2 = objectProto$c.propertyIsEnumerable; + var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component. -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeGetSymbols$2 = Object.getOwnPropertySymbols; + var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during + // hydration). This counter is global, so client ids are not stable across + // render attempts. -/** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ -var getSymbols$4 = !nativeGetSymbols$2 ? stubArray$2 : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter$2(nativeGetSymbols$2(object), function(symbol) { - return propertyIsEnumerable$2.call(object, symbol); - }); -}; + var globalClientIdCounter = 0; + var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook -var _getSymbols = getSymbols$4; + var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. + // The list stores the order of hooks used during the initial render (mount). + // Subsequent renders (updates) reference this list. -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ + var hookTypesDev = null; + var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore + // the dependencies for Hooks that need them (e.g. useEffect or useMemo). + // When true, such Hooks will always be "remounted". Only used during hot reload. -function baseTimes$2(n, iteratee) { - var index = -1, - result = Array(n); + var ignorePreviousDependencies = false; - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} + function mountHookTypesDev() { + { + var hookName = currentHookNameInDev; -var _baseTimes = baseTimes$2; + if (hookTypesDev === null) { + hookTypesDev = [hookName]; + } else { + hookTypesDev.push(hookName); + } + } + } -/** Used as references for various `Number` constants. */ + function updateHookTypesDev() { + { + var hookName = currentHookNameInDev; -var MAX_SAFE_INTEGER$2 = 9007199254740991; + if (hookTypesDev !== null) { + hookTypesUpdateIndexDev++; -/** Used to detect unsigned integer values. */ -var reIsUint$1 = /^(?:0|[1-9]\d*)$/; + if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { + warnOnHookMismatchInDev(hookName); + } + } + } + } -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex$5(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$2 : length; + function checkDepsAreArrayDev(deps) { + { + if (deps !== undefined && deps !== null && !isArray(deps)) { + // Verify deps, but only on mount to avoid extra checks. + // It's unlikely their type would change as usually you define them inline. + error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps); + } + } + } - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint$1.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} + function warnOnHookMismatchInDev(currentHookName) { + { + var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1); -var _isIndex = isIndex$5; + if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { + didWarnAboutMismatchedHooksForComponent.add(componentName); -var baseTimes$1 = _baseTimes, - isArguments$4 = isArguments_1, - isArray$j = isArray_1$1, - isBuffer$2 = isBuffer$4.exports, - isIndex$4 = _isIndex, - isTypedArray$1 = isTypedArray_1; + if (hookTypesDev !== null) { + var table = ''; + var secondColumnStart = 30; -/** Used for built-in method references. */ -var objectProto$b = Object.prototype; + for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { + var oldHookName = hookTypesDev[i]; + var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; + var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up + // lol @ IE not supporting String#repeat -/** Used to check objects for own properties. */ -var hasOwnProperty$b = objectProto$b.hasOwnProperty; + while (row.length < secondColumnStart) { + row += ' '; + } -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys$3(value, inherited) { - var isArr = isArray$j(value), - isArg = !isArr && isArguments$4(value), - isBuff = !isArr && !isArg && isBuffer$2(value), - isType = !isArr && !isArg && !isBuff && isTypedArray$1(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes$1(value.length, String) : [], - length = result.length; + row += newHookName + '\n'; + table += row; + } - for (var key in value) { - if ((inherited || hasOwnProperty$b.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex$4(key, length) - ))) { - result.push(key); - } - } - return result; -} + error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table); + } + } + } + } -var _arrayLikeKeys = arrayLikeKeys$3; + function throwInvalidHookError() { + throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); + } -var arrayLikeKeys$2 = _arrayLikeKeys, - baseKeys = _baseKeys, - isArrayLike$a = isArrayLike_1; + function areHookInputsEqual(nextDeps, prevDeps) { + { + if (ignorePreviousDependencies) { + // Only true when this component is being hot reloaded. + return false; + } + } -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys$9(object) { - return isArrayLike$a(object) ? arrayLikeKeys$2(object) : baseKeys(object); -} + if (prevDeps === null) { + { + error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); + } -var keys_1 = keys$9; + return false; + } -var baseGetAllKeys$2 = _baseGetAllKeys, - getSymbols$3 = _getSymbols, - keys$8 = keys_1; + { + // Don't bother comparing lengths in prod because these arrays should be + // passed inline. + if (nextDeps.length !== prevDeps.length) { + error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]"); + } + } -/** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ -function getAllKeys$2(object) { - return baseGetAllKeys$2(object, keys$8, getSymbols$3); -} + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { + if (objectIs(nextDeps[i], prevDeps[i])) { + continue; + } -var _getAllKeys = getAllKeys$2; + return false; + } -var getAllKeys$1 = _getAllKeys; + return true; + } -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$3 = 1; + function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) { + renderLanes = nextRenderLanes; + currentlyRenderingFiber$1 = workInProgress; -/** Used for built-in method references. */ -var objectProto$a = Object.prototype; + { + hookTypesDev = current !== null ? current._debugHookTypes : null; + hookTypesUpdateIndexDev = -1; // Used for hot reloading: -/** Used to check objects for own properties. */ -var hasOwnProperty$a = objectProto$a.hasOwnProperty; + ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; + } -/** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalObjects$1(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3, - objProps = getAllKeys$1(object), - objLength = objProps.length, - othProps = getAllKeys$1(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) { - return false; - } - } - // Check that cyclic values are equal. - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; + workInProgress.memoizedState = null; + workInProgress.updateQueue = null; + workInProgress.lanes = NoLanes; // The following should have already been reset + // currentHook = null; + // workInProgressHook = null; + // didScheduleRenderPhaseUpdate = false; + // localIdCounter = 0; + // TODO Warn if no hooks are used at all during mount, then some are used during update. + // Currently we will identify the update render as a mount because memoizedState === null. + // This is tricky because it's valid for certain types of components (e.g. React.lazy) + // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used. + // Non-stateful hooks (e.g. context) don't get added to memoizedState, + // so memoizedState would be null during updates and mounts. - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; -} + { + if (current !== null && current.memoizedState !== null) { + ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; + } else if (hookTypesDev !== null) { + // This dispatcher handles an edge case where a component is updating, + // but no stateful hooks have been used. + // We want to match the production code behavior (which will use HooksDispatcherOnMount), + // but with the extra DEV validation to ensure hooks ordering hasn't changed. + // This dispatcher does that. + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; + } else { + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; + } + } -var _equalObjects = equalObjects$1; + var children = Component(props, secondArg); // Check if there was a render phase update -var Stack$2 = _Stack, - equalArrays = _equalArrays, - equalByTag = _equalByTag, - equalObjects = _equalObjects, - getTag$4 = _getTag, - isArray$i = isArray_1$1, - isBuffer$1 = isBuffer$4.exports, - isTypedArray = isTypedArray_1; + if (didScheduleRenderPhaseUpdateDuringThisPass) { + // Keep rendering in a loop for as long as render phase updates continue to + // be scheduled. Use a counter to prevent infinite loops. + var numberOfReRenders = 0; -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$2 = 1; + do { + didScheduleRenderPhaseUpdateDuringThisPass = false; + localIdCounter = 0; -/** `Object#toString` result references. */ -var argsTag$3 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$1 = '[object Object]'; + if (numberOfReRenders >= RE_RENDER_LIMIT) { + throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); + } -/** Used for built-in method references. */ -var objectProto$9 = Object.prototype; + numberOfReRenders += 1; -/** Used to check objects for own properties. */ -var hasOwnProperty$9 = objectProto$9.hasOwnProperty; + { + // Even when hot reloading, allow dependencies to stabilize + // after first render to prevent infinite render phase updates. + ignorePreviousDependencies = false; + } // Start over from the beginning of the list -/** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function baseIsEqualDeep$1(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray$i(object), - othIsArr = isArray$i(other), - objTag = objIsArr ? arrayTag$1 : getTag$4(object), - othTag = othIsArr ? arrayTag$1 : getTag$4(other); - objTag = objTag == argsTag$3 ? objectTag$1 : objTag; - othTag = othTag == argsTag$3 ? objectTag$1 : othTag; + currentHook = null; + workInProgressHook = null; + workInProgress.updateQueue = null; - var objIsObj = objTag == objectTag$1, - othIsObj = othTag == objectTag$1, - isSameTag = objTag == othTag; + { + // Also validate hook order for cascading updates. + hookTypesUpdateIndexDev = -1; + } - if (isSameTag && isBuffer$1(object)) { - if (!isBuffer$1(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack$2); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) { - var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); + ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ; + children = Component(props, secondArg); + } while (didScheduleRenderPhaseUpdateDuringThisPass); + } // We can assume the previous dispatcher is always this one, since we set it + // at the beginning of the render phase and there's no re-entrance. - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - stack || (stack = new Stack$2); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack$2); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); -} + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; -var _baseIsEqualDeep = baseIsEqualDeep$1; + { + workInProgress._debugHookTypes = hookTypesDev; + } // This check uses currentHook so that it works the same in DEV and prod bundles. + // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. -var baseIsEqualDeep = _baseIsEqualDeep, - isObjectLike$8 = isObjectLike_1; -/** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ -function baseIsEqual$2(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike$8(value) && !isObjectLike$8(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual$2, stack); -} + var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; + renderLanes = NoLanes; + currentlyRenderingFiber$1 = null; + currentHook = null; + workInProgressHook = null; -var _baseIsEqual = baseIsEqual$2; + { + currentHookNameInDev = null; + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last + // render. If this fires, it suggests that we incorrectly reset the static + // flags in some other part of the codebase. This has happened before, for + // example, in the SuspenseList implementation. -var Stack$1 = _Stack, - baseIsEqual$1 = _baseIsEqual; + if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird + // and creates false positives. To make this work in legacy mode, we'd + // need to mark fibers that commit in an incomplete state, somehow. For + // now I'll disable the warning that most of the bugs that would trigger + // it are either exclusive to concurrent mode or exist in both. + (current.mode & ConcurrentMode) !== NoMode) { + error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.'); + } + } -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; + didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook + // localIdCounter = 0; -/** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ -function baseIsMatch$1(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; + if (didRenderTooFewHooks) { + throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.'); + } - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; + return children; + } + function checkDidRenderIdHook() { + // This should be called immediately after every renderWithHooks call. + // Conceptually, it's part of the return value of renderWithHooks; it's only a + // separate function to avoid using an array tuple. + var didRenderIdHook = localIdCounter !== 0; + localIdCounter = 0; + return didRenderIdHook; + } + function bailoutHooks(current, workInProgress, lanes) { + workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the + // complete phase (bubbleProperties). - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack$1; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual$1(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack) - : result - )) { - return false; - } - } - } - return true; -} + if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { + workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update); + } else { + workInProgress.flags &= ~(Passive | Update); + } -var _baseIsMatch = baseIsMatch$1; + current.lanes = removeLanes(current.lanes, lanes); + } + function resetHooksAfterThrow() { + // We can assume the previous dispatcher is always this one, since we set it + // at the beginning of the render phase and there's no re-entrance. + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; -var isObject$8 = isObject_1; + if (didScheduleRenderPhaseUpdate) { + // There were render phase updates. These are only valid for this render + // phase, which we are now aborting. Remove the updates from the queues so + // they do not persist to the next render. Do not remove updates from hooks + // that weren't processed. + // + // Only reset the updates from the queue if it has a clone. If it does + // not have a clone, that means it wasn't processed, and the updates were + // scheduled before we entered the render phase. + var hook = currentlyRenderingFiber$1.memoizedState; -/** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ -function isStrictComparable$2(value) { - return value === value && !isObject$8(value); -} + while (hook !== null) { + var queue = hook.queue; -var _isStrictComparable = isStrictComparable$2; + if (queue !== null) { + queue.pending = null; + } -var isStrictComparable$1 = _isStrictComparable, - keys$7 = keys_1; + hook = hook.next; + } -/** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ -function getMatchData$1(object) { - var result = keys$7(object), - length = result.length; + didScheduleRenderPhaseUpdate = false; + } - while (length--) { - var key = result[length], - value = object[key]; + renderLanes = NoLanes; + currentlyRenderingFiber$1 = null; + currentHook = null; + workInProgressHook = null; - result[length] = [key, value, isStrictComparable$1(value)]; - } - return result; -} + { + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; + currentHookNameInDev = null; + isUpdatingOpaqueValueInRenderPhase = false; + } -var _getMatchData = getMatchData$1; + didScheduleRenderPhaseUpdateDuringThisPass = false; + localIdCounter = 0; + } -/** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ + function mountWorkInProgressHook() { + var hook = { + memoizedState: null, + baseState: null, + baseQueue: null, + queue: null, + next: null + }; -function matchesStrictComparable$2(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; -} + if (workInProgressHook === null) { + // This is the first hook in the list + currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook; + } else { + // Append to the end of the list + workInProgressHook = workInProgressHook.next = hook; + } -var _matchesStrictComparable = matchesStrictComparable$2; + return workInProgressHook; + } -var baseIsMatch = _baseIsMatch, - getMatchData = _getMatchData, - matchesStrictComparable$1 = _matchesStrictComparable; + function updateWorkInProgressHook() { + // This function is used both for updates and for re-renders triggered by a + // render phase update. It assumes there is either a current hook we can + // clone, or a work-in-progress hook from a previous render pass that we can + // use as a base. When we reach the end of the base list, we must switch to + // the dispatcher used for mounts. + var nextCurrentHook; -/** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ -function baseMatches$1(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable$1(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; -} + if (currentHook === null) { + var current = currentlyRenderingFiber$1.alternate; -var _baseMatches = baseMatches$1; + if (current !== null) { + nextCurrentHook = current.memoizedState; + } else { + nextCurrentHook = null; + } + } else { + nextCurrentHook = currentHook.next; + } -var baseGetTag$2 = _baseGetTag, - isObjectLike$7 = isObjectLike_1; + var nextWorkInProgressHook; -/** `Object#toString` result references. */ -var symbolTag$4 = '[object Symbol]'; + if (workInProgressHook === null) { + nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState; + } else { + nextWorkInProgressHook = workInProgressHook.next; + } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol$6(value) { - return typeof value == 'symbol' || - (isObjectLike$7(value) && baseGetTag$2(value) == symbolTag$4); -} + if (nextWorkInProgressHook !== null) { + // There's already a work-in-progress. Reuse it. + workInProgressHook = nextWorkInProgressHook; + nextWorkInProgressHook = workInProgressHook.next; + currentHook = nextCurrentHook; + } else { + // Clone from the current hook. + if (nextCurrentHook === null) { + throw new Error('Rendered more hooks than during the previous render.'); + } -var isSymbol_1 = isSymbol$6; + currentHook = nextCurrentHook; + var newHook = { + memoizedState: currentHook.memoizedState, + baseState: currentHook.baseState, + baseQueue: currentHook.baseQueue, + queue: currentHook.queue, + next: null + }; -var isArray$h = isArray_1$1, - isSymbol$5 = isSymbol_1; + if (workInProgressHook === null) { + // This is the first hook in the list. + currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook; + } else { + // Append to the end of the list. + workInProgressHook = workInProgressHook.next = newHook; + } + } -/** Used to match property names within property paths. */ -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; + return workInProgressHook; + } -/** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ -function isKey$3(value, object) { - if (isArray$h(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol$5(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); -} + function createFunctionComponentUpdateQueue() { + return { + lastEffect: null, + stores: null + }; + } -var _isKey = isKey$3; + function basicStateReducer(state, action) { + // $FlowFixMe: Flow doesn't like mixed types + return typeof action === 'function' ? action(state) : action; + } -var MapCache$1 = _MapCache; + function mountReducer(reducer, initialArg, init) { + var hook = mountWorkInProgressHook(); + var initialState; -/** Error message constants. */ -var FUNC_ERROR_TEXT$1 = 'Expected a function'; + if (init !== undefined) { + initialState = init(initialArg); + } else { + initialState = initialArg; + } -/** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ -function memoize$1(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT$1); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; + hook.memoizedState = hook.baseState = initialState; + var queue = { + pending: null, + interleaved: null, + lanes: NoLanes, + dispatch: null, + lastRenderedReducer: reducer, + lastRenderedState: initialState + }; + hook.queue = queue; + var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue); + return [hook.memoizedState, dispatch]; + } - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize$1.Cache || MapCache$1); - return memoized; -} + function updateReducer(reducer, initialArg, init) { + var hook = updateWorkInProgressHook(); + var queue = hook.queue; -// Expose `MapCache`. -memoize$1.Cache = MapCache$1; + if (queue === null) { + throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); + } -var memoize_1 = memoize$1; + queue.lastRenderedReducer = reducer; + var current = currentHook; // The last rebase update that is NOT part of the base state. -var memoize = memoize_1; + var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet. -/** Used as the maximum memoize cache size. */ -var MAX_MEMOIZE_SIZE = 500; + var pendingQueue = queue.pending; -/** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ -function memoizeCapped$1(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); + if (pendingQueue !== null) { + // We have new updates that haven't been processed yet. + // We'll add them to the base queue. + if (baseQueue !== null) { + // Merge the pending queue and the base queue. + var baseFirst = baseQueue.next; + var pendingFirst = pendingQueue.next; + baseQueue.next = pendingFirst; + pendingQueue.next = baseFirst; + } - var cache = result.cache; - return result; -} + { + if (current.baseQueue !== baseQueue) { + // Internal invariant that should never happen, but feasibly could in + // the future if we implement resuming, or some form of that. + error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.'); + } + } -var _memoizeCapped = memoizeCapped$1; + current.baseQueue = baseQueue = pendingQueue; + queue.pending = null; + } -var memoizeCapped = _memoizeCapped; + if (baseQueue !== null) { + // We have a queue to process. + var first = baseQueue.next; + var newState = current.baseState; + var newBaseState = null; + var newBaseQueueFirst = null; + var newBaseQueueLast = null; + var update = first; -/** Used to match property names within property paths. */ -var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + do { + var updateLane = update.lane; -/** Used to match backslashes in property paths. */ -var reEscapeChar = /\\(\\)?/g; + if (!isSubsetOfLanes(renderLanes, updateLane)) { + // Priority is insufficient. Skip this update. If this is the first + // skipped update, the previous update/state is the new base + // update/state. + var clone = { + lane: updateLane, + action: update.action, + hasEagerState: update.hasEagerState, + eagerState: update.eagerState, + next: null + }; -/** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ -var stringToPath$1 = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; -}); + if (newBaseQueueLast === null) { + newBaseQueueFirst = newBaseQueueLast = clone; + newBaseState = newState; + } else { + newBaseQueueLast = newBaseQueueLast.next = clone; + } // Update the remaining priority in the queue. + // TODO: Don't need to accumulate this. Instead, we can remove + // renderLanes from the original lanes. -var _stringToPath = stringToPath$1; -var Symbol$5 = _Symbol, - arrayMap$6 = _arrayMap, - isArray$g = isArray_1$1, - isSymbol$4 = isSymbol_1; + currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane); + markSkippedUpdateLanes(updateLane); + } else { + // This update does have sufficient priority. + if (newBaseQueueLast !== null) { + var _clone = { + // This update is going to be committed so we never want uncommit + // it. Using NoLane works because 0 is a subset of all bitmasks, so + // this will never be skipped by the check above. + lane: NoLane, + action: update.action, + hasEagerState: update.hasEagerState, + eagerState: update.eagerState, + next: null + }; + newBaseQueueLast = newBaseQueueLast.next = _clone; + } // Process this update. -/** Used as references for various `Number` constants. */ -var INFINITY$5 = 1 / 0; -/** Used to convert symbols to primitives and strings. */ -var symbolProto$1 = Symbol$5 ? Symbol$5.prototype : undefined, - symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; + if (update.hasEagerState) { + // If this update is a state update (not a reducer) and was processed eagerly, + // we can use the eagerly computed state + newState = update.eagerState; + } else { + var action = update.action; + newState = reducer(newState, action); + } + } -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString$1(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray$g(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap$6(value, baseToString$1) + ''; - } - if (isSymbol$4(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$5) ? '-0' : result; -} + update = update.next; + } while (update !== null && update !== first); -var _baseToString = baseToString$1; + if (newBaseQueueLast === null) { + newBaseState = newState; + } else { + newBaseQueueLast.next = newBaseQueueFirst; + } // Mark that the fiber performed work, but only if the new state is + // different from the current state. -var baseToString = _baseToString; -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString$2(value) { - return value == null ? '' : baseToString(value); -} + if (!objectIs(newState, hook.memoizedState)) { + markWorkInProgressReceivedUpdate(); + } -var toString_1 = toString$2; + hook.memoizedState = newState; + hook.baseState = newBaseState; + hook.baseQueue = newBaseQueueLast; + queue.lastRenderedState = newState; + } // Interleaved updates are stored on a separate queue. We aren't going to + // process them during this render, but we do need to track which lanes + // are remaining. -var isArray$f = isArray_1$1, - isKey$2 = _isKey, - stringToPath = _stringToPath, - toString$1 = toString_1; -/** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ -function castPath$4(value, object) { - if (isArray$f(value)) { - return value; - } - return isKey$2(value, object) ? [value] : stringToPath(toString$1(value)); -} + var lastInterleaved = queue.interleaved; -var _castPath = castPath$4; + if (lastInterleaved !== null) { + var interleaved = lastInterleaved; -var isSymbol$3 = isSymbol_1; + do { + var interleavedLane = interleaved.lane; + currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane); + markSkippedUpdateLanes(interleavedLane); + interleaved = interleaved.next; + } while (interleaved !== lastInterleaved); + } else if (baseQueue === null) { + // `queue.lanes` is used for entangling transitions. We can set it back to + // zero once the queue is empty. + queue.lanes = NoLanes; + } -/** Used as references for various `Number` constants. */ -var INFINITY$4 = 1 / 0; + var dispatch = queue.dispatch; + return [hook.memoizedState, dispatch]; + } -/** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ -function toKey$7(value) { - if (typeof value == 'string' || isSymbol$3(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$4) ? '-0' : result; -} + function rerenderReducer(reducer, initialArg, init) { + var hook = updateWorkInProgressHook(); + var queue = hook.queue; -var _toKey = toKey$7; + if (queue === null) { + throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); + } -var castPath$3 = _castPath, - toKey$6 = _toKey; + queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous + // work-in-progress hook. -/** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ -function baseGet$3(object, path) { - path = castPath$3(path, object); + var dispatch = queue.dispatch; + var lastRenderPhaseUpdate = queue.pending; + var newState = hook.memoizedState; - var index = 0, - length = path.length; + if (lastRenderPhaseUpdate !== null) { + // The queue doesn't persist past this render pass. + queue.pending = null; + var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; + var update = firstRenderPhaseUpdate; - while (object != null && index < length) { - object = object[toKey$6(path[index++])]; - } - return (index && index == length) ? object : undefined; -} + do { + // Process this render phase update. We don't have to check the + // priority because it will always be the same as the current + // render's. + var action = update.action; + newState = reducer(newState, action); + update = update.next; + } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is + // different from the current state. -var _baseGet = baseGet$3; -var baseGet$2 = _baseGet; + if (!objectIs(newState, hook.memoizedState)) { + markWorkInProgressReceivedUpdate(); + } -/** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ -function get$1(object, path, defaultValue) { - var result = object == null ? undefined : baseGet$2(object, path); - return result === undefined ? defaultValue : result; -} + hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to + // the base state unless the queue is empty. + // TODO: Not sure if this is the desired semantics, but it's what we + // do for gDSFP. I can't remember why. -var get_1 = get$1; + if (hook.baseQueue === null) { + hook.baseState = newState; + } -/** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ + queue.lastRenderedState = newState; + } -function baseHasIn$1(object, key) { - return object != null && key in Object(object); -} + return [newState, dispatch]; + } -var _baseHasIn = baseHasIn$1; + function mountMutableSource(source, getSnapshot, subscribe) { + { + return undefined; + } + } -var castPath$2 = _castPath, - isArguments$3 = isArguments_1, - isArray$e = isArray_1$1, - isIndex$3 = _isIndex, - isLength$2 = isLength_1, - toKey$5 = _toKey; + function updateMutableSource(source, getSnapshot, subscribe) { + { + return undefined; + } + } -/** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ -function hasPath$2(object, path, hasFunc) { - path = castPath$2(path, object); + function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var fiber = currentlyRenderingFiber$1; + var hook = mountWorkInProgressHook(); + var nextSnapshot; + var isHydrating = getIsHydrating(); - var index = -1, - length = path.length, - result = false; + if (isHydrating) { + if (getServerSnapshot === undefined) { + throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); + } - while (++index < length) { - var key = toKey$5(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength$2(length) && isIndex$3(key, length) && - (isArray$e(object) || isArguments$3(object)); -} + nextSnapshot = getServerSnapshot(); -var _hasPath = hasPath$2; + { + if (!didWarnUncachedGetSnapshot) { + if (nextSnapshot !== getServerSnapshot()) { + error('The result of getServerSnapshot should be cached to avoid an infinite loop'); -var baseHasIn = _baseHasIn, - hasPath$1 = _hasPath; + didWarnUncachedGetSnapshot = true; + } + } + } + } else { + nextSnapshot = getSnapshot(); -/** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ -function hasIn$1(object, path) { - return object != null && hasPath$1(object, path, baseHasIn); -} + { + if (!didWarnUncachedGetSnapshot) { + var cachedSnapshot = getSnapshot(); -var hasIn_1 = hasIn$1; + if (!objectIs(nextSnapshot, cachedSnapshot)) { + error('The result of getSnapshot should be cached to avoid an infinite loop'); -var baseIsEqual = _baseIsEqual, - get = get_1, - hasIn = hasIn_1, - isKey$1 = _isKey, - isStrictComparable = _isStrictComparable, - matchesStrictComparable = _matchesStrictComparable, - toKey$4 = _toKey; + didWarnUncachedGetSnapshot = true; + } + } + } // Unless we're rendering a blocking lane, schedule a consistency check. + // Right before committing, we will walk the tree and check if any of the + // stores were mutated. + // + // We won't do this if we're hydrating server-rendered content, because if + // the content is stale, it's already visible anyway. Instead we'll patch + // it up in a passive effect. -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; -/** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ -function baseMatchesProperty$1(path, srcValue) { - if (isKey$1(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey$4(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; -} + var root = getWorkInProgressRoot(); -var _baseMatchesProperty = baseMatchesProperty$1; + if (root === null) { + throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); + } -/** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ + if (!includesBlockingLane(root, renderLanes)) { + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); + } + } // Read the current snapshot from the store on every render. This breaks the + // normal rules of React, and only works because store updates are + // always synchronous. -function identity$4(value) { - return value; -} -var identity_1 = identity$4; + hook.memoizedState = nextSnapshot; + var inst = { + value: nextSnapshot, + getSnapshot: getSnapshot + }; + hook.queue = inst; // Schedule an effect to subscribe to the store. -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ + mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update + // this whenever subscribe, getSnapshot, or value changes. Because there's no + // clean-up function, and we track the deps correctly, we can call pushEffect + // directly, without storing any additional state. For the same reason, we + // don't need to set a static flag, either. + // TODO: We can move this to the passive phase once we add a pre-commit + // consistency check. See the next comment. -function baseProperty$1(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; -} + fiber.flags |= Passive; + pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); + return nextSnapshot; + } -var _baseProperty = baseProperty$1; + function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var fiber = currentlyRenderingFiber$1; + var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the + // normal rules of React, and only works because store updates are + // always synchronous. -var baseGet$1 = _baseGet; + var nextSnapshot = getSnapshot(); -/** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function basePropertyDeep$1(path) { - return function(object) { - return baseGet$1(object, path); - }; -} + { + if (!didWarnUncachedGetSnapshot) { + var cachedSnapshot = getSnapshot(); -var _basePropertyDeep = basePropertyDeep$1; + if (!objectIs(nextSnapshot, cachedSnapshot)) { + error('The result of getSnapshot should be cached to avoid an infinite loop'); -var baseProperty = _baseProperty, - basePropertyDeep = _basePropertyDeep, - isKey = _isKey, - toKey$3 = _toKey; + didWarnUncachedGetSnapshot = true; + } + } + } -/** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ -function property$1(path) { - return isKey(path) ? baseProperty(toKey$3(path)) : basePropertyDeep(path); -} + var prevSnapshot = hook.memoizedState; + var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot); -var property_1 = property$1; + if (snapshotChanged) { + hook.memoizedState = nextSnapshot; + markWorkInProgressReceivedUpdate(); + } -var baseMatches = _baseMatches, - baseMatchesProperty = _baseMatchesProperty, - identity$3 = identity_1, - isArray$d = isArray_1$1, - property = property_1; + var inst = hook.queue; + updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the + // commit phase if there was an interleaved mutation. In concurrent mode + // this can happen all the time, but even in synchronous mode, an earlier + // effect may have mutated the store. -/** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ -function baseIteratee$a(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity$3; - } - if (typeof value == 'object') { - return isArray$d(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); -} + if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by + // checking whether we scheduled a subscription effect above. + workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) { + fiber.flags |= Passive; + pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check. + // Right before committing, we will walk the tree and check if any of the + // stores were mutated. -var _baseIteratee = baseIteratee$a; + var root = getWorkInProgressRoot(); -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ + if (root === null) { + throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); + } -function createBaseFor$1(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; + if (!includesBlockingLane(root, renderLanes)) { + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); + } + } - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; -} + return nextSnapshot; + } -var _createBaseFor = createBaseFor$1; + function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) { + fiber.flags |= StoreConsistency; + var check = { + getSnapshot: getSnapshot, + value: renderedSnapshot + }; + var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; -var createBaseFor = _createBaseFor; + if (componentUpdateQueue === null) { + componentUpdateQueue = createFunctionComponentUpdateQueue(); + currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; + componentUpdateQueue.stores = [check]; + } else { + var stores = componentUpdateQueue.stores; -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor$1 = createBaseFor(); + if (stores === null) { + componentUpdateQueue.stores = [check]; + } else { + stores.push(check); + } + } + } -var _baseFor = baseFor$1; + function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) { + // These are updated in the passive phase + inst.value = nextSnapshot; + inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could + // have been in an event that fired before the passive effects, or it could + // have been in a layout effect. In that case, we would have used the old + // snapsho and getSnapshot values to bail out. We need to check one more time. -var baseFor = _baseFor, - keys$6 = keys_1; + if (checkIfSnapshotChanged(inst)) { + // Force a re-render. + forceStoreRerender(fiber); + } + } -/** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn$1(object, iteratee) { - return object && baseFor(object, iteratee, keys$6); -} + function subscribeToStore(fiber, inst, subscribe) { + var handleStoreChange = function () { + // The store changed. Check if the snapshot changed since the last time we + // read from the store. + if (checkIfSnapshotChanged(inst)) { + // Force a re-render. + forceStoreRerender(fiber); + } + }; // Subscribe to the store and return a clean-up function. -var _baseForOwn = baseForOwn$1; -var isArrayLike$9 = isArrayLike_1; + return subscribe(handleStoreChange); + } -/** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseEach$1(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike$9(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); + function checkIfSnapshotChanged(inst) { + var latestGetSnapshot = inst.getSnapshot; + var prevValue = inst.value; - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; -} + try { + var nextValue = latestGetSnapshot(); + return !objectIs(prevValue, nextValue); + } catch (error) { + return true; + } + } -var _createBaseEach = createBaseEach$1; + function forceStoreRerender(fiber) { + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } -var baseForOwn = _baseForOwn, - createBaseEach = _createBaseEach; + function mountState(initialState) { + var hook = mountWorkInProgressHook(); -/** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ -var baseEach$7 = createBaseEach(baseForOwn); + if (typeof initialState === 'function') { + // $FlowFixMe: Flow doesn't like mixed types + initialState = initialState(); + } -var _baseEach = baseEach$7; + hook.memoizedState = hook.baseState = initialState; + var queue = { + pending: null, + interleaved: null, + lanes: NoLanes, + dispatch: null, + lastRenderedReducer: basicStateReducer, + lastRenderedState: initialState + }; + hook.queue = queue; + var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue); + return [hook.memoizedState, dispatch]; + } -var baseEach$6 = _baseEach, - isArrayLike$8 = isArrayLike_1; + function updateState(initialState) { + return updateReducer(basicStateReducer); + } -/** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function baseMap$1(collection, iteratee) { - var index = -1, - result = isArrayLike$8(collection) ? Array(collection.length) : []; + function rerenderState(initialState) { + return rerenderReducer(basicStateReducer); + } - baseEach$6(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; -} + function pushEffect(tag, create, destroy, deps) { + var effect = { + tag: tag, + create: create, + destroy: destroy, + deps: deps, + // Circular + next: null + }; + var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; -var _baseMap = baseMap$1; + if (componentUpdateQueue === null) { + componentUpdateQueue = createFunctionComponentUpdateQueue(); + currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; + componentUpdateQueue.lastEffect = effect.next = effect; + } else { + var lastEffect = componentUpdateQueue.lastEffect; -var arrayMap$5 = _arrayMap, - baseIteratee$9 = _baseIteratee, - baseMap = _baseMap, - isArray$c = isArray_1$1; + if (lastEffect === null) { + componentUpdateQueue.lastEffect = effect.next = effect; + } else { + var firstEffect = lastEffect.next; + lastEffect.next = effect; + effect.next = firstEffect; + componentUpdateQueue.lastEffect = effect; + } + } -/** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ -function map$1(collection, iteratee) { - var func = isArray$c(collection) ? arrayMap$5 : baseMap; - return func(collection, baseIteratee$9(iteratee)); -} + return effect; + } -var map_1$4 = map$1; + function mountRef(initialValue) { + var hook = mountWorkInProgressHook(); -/** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ + { + var _ref2 = { + current: initialValue + }; + hook.memoizedState = _ref2; + return _ref2; + } + } -function arrayEach$2(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; + function updateRef(initialValue) { + var hook = updateWorkInProgressHook(); + return hook.memoizedState; + } - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; -} + function mountEffectImpl(fiberFlags, hookFlags, create, deps) { + var hook = mountWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + currentlyRenderingFiber$1.flags |= fiberFlags; + hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps); + } -var _arrayEach = arrayEach$2; + function updateEffectImpl(fiberFlags, hookFlags, create, deps) { + var hook = updateWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + var destroy = undefined; -var identity$2 = identity_1; + if (currentHook !== null) { + var prevEffect = currentHook.memoizedState; + destroy = prevEffect.destroy; -/** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ -function castFunction$1(value) { - return typeof value == 'function' ? value : identity$2; -} + if (nextDeps !== null) { + var prevDeps = prevEffect.deps; -var _castFunction = castFunction$1; + if (areHookInputsEqual(nextDeps, prevDeps)) { + hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps); + return; + } + } + } -var arrayEach$1 = _arrayEach, - baseEach$5 = _baseEach, - castFunction = _castFunction, - isArray$b = isArray_1$1; + currentlyRenderingFiber$1.flags |= fiberFlags; + hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps); + } -/** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. - * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ -function forEach(collection, iteratee) { - var func = isArray$b(collection) ? arrayEach$1 : baseEach$5; - return func(collection, castFunction(iteratee)); -} + function mountEffect(create, deps) { + if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { + return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps); + } else { + return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps); + } + } -var forEach_1$4 = forEach; + function updateEffect(create, deps) { + return updateEffectImpl(Passive, Passive$1, create, deps); + } -var arrayMap$4 = _arrayMap; + function mountInsertionEffect(create, deps) { + return mountEffectImpl(Update, Insertion, create, deps); + } -/** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ -function baseValues$1(object, props) { - return arrayMap$4(props, function(key) { - return object[key]; - }); -} + function updateInsertionEffect(create, deps) { + return updateEffectImpl(Update, Insertion, create, deps); + } -var _baseValues = baseValues$1; + function mountLayoutEffect(create, deps) { + var fiberFlags = Update; -var baseValues = _baseValues, - keys$5 = keys_1; + { + fiberFlags |= LayoutStatic; + } -/** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ -function values$1(object) { - return object == null ? [] : baseValues(object, keys$5(object)); -} + if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } -var values_1$1 = values$1; + return mountEffectImpl(fiberFlags, Layout, create, deps); + } -/** Used for built-in method references. */ + function updateLayoutEffect(create, deps) { + return updateEffectImpl(Update, Layout, create, deps); + } -var objectProto$8 = Object.prototype; + function imperativeHandleEffect(create, ref) { + if (typeof ref === 'function') { + var refCallback = ref; -/** Used to check objects for own properties. */ -var hasOwnProperty$8 = objectProto$8.hasOwnProperty; + var _inst = create(); -/** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ -function baseHas$1(object, key) { - return object != null && hasOwnProperty$8.call(object, key); -} + refCallback(_inst); + return function () { + refCallback(null); + }; + } else if (ref !== null && ref !== undefined) { + var refObject = ref; -var _baseHas = baseHas$1; + { + if (!refObject.hasOwnProperty('current')) { + error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}'); + } + } -var baseHas = _baseHas, - hasPath = _hasPath; + var _inst2 = create(); -/** - * Checks if `path` is a direct property of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true - * - * _.has(other, 'a'); - * // => false - */ -function has$1(object, path) { - return object != null && hasPath(object, path, baseHas); -} + refObject.current = _inst2; + return function () { + refObject.current = null; + }; + } + } -var has_1 = has$1; + function mountImperativeHandle(ref, create, deps) { + { + if (typeof create !== 'function') { + error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); + } + } // TODO: If deps are provided, should we skip comparing the ref itself? -var getNative$1 = _getNative; -var defineProperty$2 = (function() { - try { - var func = getNative$1(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} -}()); + var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; + var fiberFlags = Update; -var _defineProperty = defineProperty$2; + { + fiberFlags |= LayoutStatic; + } -var defineProperty$1 = _defineProperty; + if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } -/** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function baseAssignValue$3(object, key, value) { - if (key == '__proto__' && defineProperty$1) { - defineProperty$1(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } -} + return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); + } -var _baseAssignValue = baseAssignValue$3; + function updateImperativeHandle(ref, create, deps) { + { + if (typeof create !== 'function') { + error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); + } + } // TODO: If deps are provided, should we skip comparing the ref itself? -var baseAssignValue$2 = _baseAssignValue, - eq$3 = eq_1; -/** Used for built-in method references. */ -var objectProto$7 = Object.prototype; + var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; + return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); + } -/** Used to check objects for own properties. */ -var hasOwnProperty$7 = objectProto$7.hasOwnProperty; + function mountDebugValue(value, formatterFn) {// This hook is normally a no-op. + // The react-debug-hooks package injects its own implementation + // so that e.g. DevTools can display custom hook values. + } -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue$4(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$7.call(object, key) && eq$3(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue$2(object, key, value); - } -} + var updateDebugValue = mountDebugValue; -var _assignValue = assignValue$4; + function mountCallback(callback, deps) { + var hook = mountWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + hook.memoizedState = [callback, nextDeps]; + return callback; + } -var assignValue$3 = _assignValue, - baseAssignValue$1 = _baseAssignValue; + function updateCallback(callback, deps) { + var hook = updateWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + var prevState = hook.memoizedState; -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ -function copyObject$5(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; - var index = -1, - length = props.length; + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } - while (++index < length) { - var key = props[index]; + hook.memoizedState = [callback, nextDeps]; + return callback; + } - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + function mountMemo(nextCreate, deps) { + var hook = mountWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + var nextValue = nextCreate(); + hook.memoizedState = [nextValue, nextDeps]; + return nextValue; + } - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue$1(object, key, newValue); - } else { - assignValue$3(object, key, newValue); - } - } - return object; -} + function updateMemo(nextCreate, deps) { + var hook = updateWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + var prevState = hook.memoizedState; -var _copyObject = copyObject$5; + if (prevState !== null) { + // Assume these are defined. If they're not, areHookInputsEqual will warn. + if (nextDeps !== null) { + var prevDeps = prevState[1]; -var copyObject$4 = _copyObject, - keys$4 = keys_1; + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } -/** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ -function baseAssign$1(object, source) { - return object && copyObject$4(source, keys$4(source), object); -} + var nextValue = nextCreate(); + hook.memoizedState = [nextValue, nextDeps]; + return nextValue; + } -var _baseAssign = baseAssign$1; + function mountDeferredValue(value) { + var _mountState = mountState(value), + prevValue = _mountState[0], + setValue = _mountState[1]; -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ + mountEffect(function () { + var prevTransition = ReactCurrentBatchConfig$1.transition; + ReactCurrentBatchConfig$1.transition = {}; -function nativeKeysIn$2(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; -} + try { + setValue(value); + } finally { + ReactCurrentBatchConfig$1.transition = prevTransition; + } + }, [value]); + return prevValue; + } -var _nativeKeysIn = nativeKeysIn$2; + function updateDeferredValue(value) { + var _updateState = updateState(), + prevValue = _updateState[0], + setValue = _updateState[1]; -var isObject$7 = isObject_1, - isPrototype$3 = _isPrototype, - nativeKeysIn$1 = _nativeKeysIn; + updateEffect(function () { + var prevTransition = ReactCurrentBatchConfig$1.transition; + ReactCurrentBatchConfig$1.transition = {}; -/** Used for built-in method references. */ -var objectProto$6 = Object.prototype; + try { + setValue(value); + } finally { + ReactCurrentBatchConfig$1.transition = prevTransition; + } + }, [value]); + return prevValue; + } -/** Used to check objects for own properties. */ -var hasOwnProperty$6 = objectProto$6.hasOwnProperty; + function rerenderDeferredValue(value) { + var _rerenderState = rerenderState(), + prevValue = _rerenderState[0], + setValue = _rerenderState[1]; -/** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeysIn$2(object) { - if (!isObject$7(object)) { - return nativeKeysIn$1(object); - } - var isProto = isPrototype$3(object), - result = []; + updateEffect(function () { + var prevTransition = ReactCurrentBatchConfig$1.transition; + ReactCurrentBatchConfig$1.transition = {}; - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$6.call(object, key)))) { - result.push(key); - } - } - return result; -} + try { + setValue(value); + } finally { + ReactCurrentBatchConfig$1.transition = prevTransition; + } + }, [value]); + return prevValue; + } -var _baseKeysIn = baseKeysIn$2; + function startTransition(setPending, callback, options) { + var previousPriority = getCurrentUpdatePriority(); + setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); + setPending(true); + var prevTransition = ReactCurrentBatchConfig$1.transition; + ReactCurrentBatchConfig$1.transition = {}; + var currentTransition = ReactCurrentBatchConfig$1.transition; -var arrayLikeKeys$1 = _arrayLikeKeys, - baseKeysIn$1 = _baseKeysIn, - isArrayLike$7 = isArrayLike_1; + { + ReactCurrentBatchConfig$1.transition._updatedFibers = new Set(); + } -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn$5(object) { - return isArrayLike$7(object) ? arrayLikeKeys$1(object, true) : baseKeysIn$1(object); -} + try { + setPending(false); + callback(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$1.transition = prevTransition; -var keysIn_1 = keysIn$5; + { + if (prevTransition === null && currentTransition._updatedFibers) { + var updatedFibersCount = currentTransition._updatedFibers.size; -var copyObject$3 = _copyObject, - keysIn$4 = keysIn_1; + if (updatedFibersCount > 10) { + warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); + } -/** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ -function baseAssignIn$1(object, source) { - return object && copyObject$3(source, keysIn$4(source), object); -} + currentTransition._updatedFibers.clear(); + } + } + } + } -var _baseAssignIn = baseAssignIn$1; + function mountTransition() { + var _mountState2 = mountState(false), + isPending = _mountState2[0], + setPending = _mountState2[1]; // The `start` method never changes. -var _cloneBuffer = {exports: {}}; -(function (module, exports) { - var root = _root; + var start = startTransition.bind(null, setPending); + var hook = mountWorkInProgressHook(); + hook.memoizedState = start; + return [isPending, start]; + } - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; + function updateTransition() { + var _updateState2 = updateState(), + isPending = _updateState2[0]; - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + var hook = updateWorkInProgressHook(); + var start = hook.memoizedState; + return [isPending, start]; + } - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + function rerenderTransition() { + var _rerenderState2 = rerenderState(), + isPending = _rerenderState2[0]; - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; + var hook = updateWorkInProgressHook(); + var start = hook.memoizedState; + return [isPending, start]; + } - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); + var isUpdatingOpaqueValueInRenderPhase = false; + function getIsUpdatingOpaqueValueInRenderPhaseInDEV() { + { + return isUpdatingOpaqueValueInRenderPhase; } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; } - module.exports = cloneBuffer; -} (_cloneBuffer, _cloneBuffer.exports)); - -/** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ + function mountId() { + var hook = mountWorkInProgressHook(); + var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we + // should do this in Fiber, too? Deferring this decision for now because + // there's no other place to store the prefix except for an internal field on + // the public createRoot object, which the fiber tree does not currently have + // a reference to. -function copyArray$1(source, array) { - var index = -1, - length = source.length; + var identifierPrefix = root.identifierPrefix; + var id; - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; -} + if (getIsHydrating()) { + var treeId = getTreeId(); // Use a captial R prefix for server-generated ids. -var _copyArray = copyArray$1; + id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end + // that represents the position of this useId hook among all the useId + // hooks for this fiber. -var copyObject$2 = _copyObject, - getSymbols$2 = _getSymbols; + var localId = localIdCounter++; -/** - * Copies own symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ -function copySymbols$1(source, object) { - return copyObject$2(source, getSymbols$2(source), object); -} + if (localId > 0) { + id += 'H' + localId.toString(32); + } -var _copySymbols = copySymbols$1; + id += ':'; + } else { + // Use a lowercase r prefix for client-generated ids. + var globalClientId = globalClientIdCounter++; + id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':'; + } -var overArg$1 = _overArg; + hook.memoizedState = id; + return id; + } -/** Built-in value references. */ -var getPrototype$3 = overArg$1(Object.getPrototypeOf, Object); + function updateId() { + var hook = updateWorkInProgressHook(); + var id = hook.memoizedState; + return id; + } -var _getPrototype = getPrototype$3; + function dispatchReducerAction(fiber, queue, action) { + { + if (typeof arguments[3] === 'function') { + error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); + } + } -var arrayPush$3 = _arrayPush, - getPrototype$2 = _getPrototype, - getSymbols$1 = _getSymbols, - stubArray$1 = stubArray_1; + var lane = requestUpdateLane(fiber); + var update = { + lane: lane, + action: action, + hasEagerState: false, + eagerState: null, + next: null + }; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + if (isRenderPhaseUpdate(fiber)) { + enqueueRenderPhaseUpdate(queue, update); + } else { + enqueueUpdate$1(fiber, queue, update); + var eventTime = requestEventTime(); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); -/** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ -var getSymbolsIn$3 = !nativeGetSymbols$1 ? stubArray$1 : function(object) { - var result = []; - while (object) { - arrayPush$3(result, getSymbols$1(object)); - object = getPrototype$2(object); - } - return result; -}; + if (root !== null) { + entangleTransitionUpdate(root, queue, lane); + } + } -var _getSymbolsIn = getSymbolsIn$3; + markUpdateInDevTools(fiber, lane); + } -var copyObject$1 = _copyObject, - getSymbolsIn$2 = _getSymbolsIn; + function dispatchSetState(fiber, queue, action) { + { + if (typeof arguments[3] === 'function') { + error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); + } + } -/** - * Copies own and inherited symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ -function copySymbolsIn$1(source, object) { - return copyObject$1(source, getSymbolsIn$2(source), object); -} + var lane = requestUpdateLane(fiber); + var update = { + lane: lane, + action: action, + hasEagerState: false, + eagerState: null, + next: null + }; -var _copySymbolsIn = copySymbolsIn$1; + if (isRenderPhaseUpdate(fiber)) { + enqueueRenderPhaseUpdate(queue, update); + } else { + enqueueUpdate$1(fiber, queue, update); + var alternate = fiber.alternate; -var baseGetAllKeys$1 = _baseGetAllKeys, - getSymbolsIn$1 = _getSymbolsIn, - keysIn$3 = keysIn_1; + if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) { + // The queue is currently empty, which means we can eagerly compute the + // next state before entering the render phase. If the new state is the + // same as the current state, we may be able to bail out entirely. + var lastRenderedReducer = queue.lastRenderedReducer; -/** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ -function getAllKeysIn$3(object) { - return baseGetAllKeys$1(object, keysIn$3, getSymbolsIn$1); -} + if (lastRenderedReducer !== null) { + var prevDispatcher; -var _getAllKeysIn = getAllKeysIn$3; + { + prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + } -/** Used for built-in method references. */ + try { + var currentState = queue.lastRenderedState; + var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute + // it, on the update object. If the reducer hasn't changed by the + // time we enter the render phase, then the eager state can be used + // without calling the reducer again. -var objectProto$5 = Object.prototype; + update.hasEagerState = true; + update.eagerState = eagerState; -/** Used to check objects for own properties. */ -var hasOwnProperty$5 = objectProto$5.hasOwnProperty; + if (objectIs(eagerState, currentState)) { + // Fast path. We can bail out without scheduling React to re-render. + // It's still possible that we'll need to rebase this update later, + // if the component re-renders for a different reason and by that + // time the reducer has changed. + return; + } + } catch (error) {// Suppress the error. It will throw again in the render phase. + } finally { + { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + } + } + } -/** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ -function initCloneArray$1(array) { - var length = array.length, - result = new array.constructor(length); + var eventTime = requestEventTime(); + var root = scheduleUpdateOnFiber(fiber, lane, eventTime); - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty$5.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; -} + if (root !== null) { + entangleTransitionUpdate(root, queue, lane); + } + } -var _initCloneArray = initCloneArray$1; + markUpdateInDevTools(fiber, lane); + } -var Uint8Array$1 = _Uint8Array; + function isRenderPhaseUpdate(fiber) { + var alternate = fiber.alternate; + return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1; + } -/** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ -function cloneArrayBuffer$3(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); - return result; -} + function enqueueRenderPhaseUpdate(queue, update) { + // This is a render phase update. Stash it in a lazily-created map of + // queue -> linked list of updates. After this render pass, we'll restart + // and apply the stashed updates on top of the work-in-progress hook. + didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; + var pending = queue.pending; -var _cloneArrayBuffer = cloneArrayBuffer$3; + if (pending === null) { + // This is the first update. Create a circular list. + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } -var cloneArrayBuffer$2 = _cloneArrayBuffer; + queue.pending = update; + } -/** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ -function cloneDataView$1(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer$2(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); -} + function enqueueUpdate$1(fiber, queue, update, lane) { + if (isInterleavedUpdate(fiber)) { + var interleaved = queue.interleaved; -var _cloneDataView = cloneDataView$1; + if (interleaved === null) { + // This is the first update. Create a circular list. + update.next = update; // At the end of the current render, this queue's interleaved updates will + // be transferred to the pending queue. -/** Used to match `RegExp` flags from their coerced string values. */ + pushInterleavedQueue(queue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } -var reFlags = /\w*$/; + queue.interleaved = update; + } else { + var pending = queue.pending; -/** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ -function cloneRegExp$1(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; -} + if (pending === null) { + // This is the first update. Create a circular list. + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } + + queue.pending = update; + } + } -var _cloneRegExp = cloneRegExp$1; + function entangleTransitionUpdate(root, queue, lane) { + if (isTransitionLane(lane)) { + var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they + // must have finished. We can remove them from the shared queue, which + // represents a superset of the actually pending lanes. In some cases we + // may entangle more than we need to, but that's OK. In fact it's worse if + // we *don't* entangle when we should. -var Symbol$4 = _Symbol; + queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$4 ? Symbol$4.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + var newQueueLanes = mergeLanes(queueLanes, lane); + queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if + // the lane finished since the last time we entangled it. So we need to + // entangle it again, just to be sure. -/** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ -function cloneSymbol$1(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; -} + markRootEntangled(root, newQueueLanes); + } + } -var _cloneSymbol = cloneSymbol$1; + function markUpdateInDevTools(fiber, lane, action) { -var cloneArrayBuffer$1 = _cloneArrayBuffer; + { + markStateUpdateScheduled(fiber, lane); + } + } -/** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ -function cloneTypedArray$1(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer$1(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); -} + var ContextOnlyDispatcher = { + readContext: readContext, + useCallback: throwInvalidHookError, + useContext: throwInvalidHookError, + useEffect: throwInvalidHookError, + useImperativeHandle: throwInvalidHookError, + useInsertionEffect: throwInvalidHookError, + useLayoutEffect: throwInvalidHookError, + useMemo: throwInvalidHookError, + useReducer: throwInvalidHookError, + useRef: throwInvalidHookError, + useState: throwInvalidHookError, + useDebugValue: throwInvalidHookError, + useDeferredValue: throwInvalidHookError, + useTransition: throwInvalidHookError, + useMutableSource: throwInvalidHookError, + useSyncExternalStore: throwInvalidHookError, + useId: throwInvalidHookError, + unstable_isNewReconciler: enableNewReconciler + }; -var _cloneTypedArray = cloneTypedArray$1; + var HooksDispatcherOnMountInDEV = null; + var HooksDispatcherOnMountWithHookTypesInDEV = null; + var HooksDispatcherOnUpdateInDEV = null; + var HooksDispatcherOnRerenderInDEV = null; + var InvalidNestedHooksDispatcherOnMountInDEV = null; + var InvalidNestedHooksDispatcherOnUpdateInDEV = null; + var InvalidNestedHooksDispatcherOnRerenderInDEV = null; -var cloneArrayBuffer = _cloneArrayBuffer, - cloneDataView = _cloneDataView, - cloneRegExp = _cloneRegExp, - cloneSymbol = _cloneSymbol, - cloneTypedArray = _cloneTypedArray; + { + var warnInvalidContextAccess = function () { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + }; -/** `Object#toString` result references. */ -var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - mapTag$2 = '[object Map]', - numberTag$1 = '[object Number]', - regexpTag$2 = '[object RegExp]', - setTag$2 = '[object Set]', - stringTag$2 = '[object String]', - symbolTag$3 = '[object Symbol]'; - -var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$1 = '[object DataView]', - float32Tag$1 = '[object Float32Array]', - float64Tag$1 = '[object Float64Array]', - int8Tag$1 = '[object Int8Array]', - int16Tag$1 = '[object Int16Array]', - int32Tag$1 = '[object Int32Array]', - uint8Tag$1 = '[object Uint8Array]', - uint8ClampedTag$1 = '[object Uint8ClampedArray]', - uint16Tag$1 = '[object Uint16Array]', - uint32Tag$1 = '[object Uint32Array]'; + var warnInvalidHookAccess = function () { + error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); + }; -/** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ -function initCloneByTag$1(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag$1: - return cloneArrayBuffer(object); + HooksDispatcherOnMountInDEV = { + readContext: function (context) { + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + mountHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + return mountLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case boolTag$1: - case dateTag$1: - return new Ctor(+object); + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case dataViewTag$1: - return cloneDataView(object, isDeep); + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + mountHookTypesDev(); + return mountRef(initialValue); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case float32Tag$1: case float64Tag$1: - case int8Tag$1: case int16Tag$1: case int32Tag$1: - case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: - return cloneTypedArray(object, isDeep); + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + mountHookTypesDev(); + return mountDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + mountHookTypesDev(); + return mountDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + mountHookTypesDev(); + return mountTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + mountHookTypesDev(); + return mountMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + mountHookTypesDev(); + return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + mountHookTypesDev(); + return mountId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; - case mapTag$2: - return new Ctor; + HooksDispatcherOnMountWithHookTypesInDEV = { + readContext: function (context) { + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + updateHookTypesDev(); + return mountCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + updateHookTypesDev(); + return mountEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + updateHookTypesDev(); + return mountImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + updateHookTypesDev(); + return mountInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + updateHookTypesDev(); + return mountLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case numberTag$1: - case stringTag$2: - return new Ctor(object); + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case regexpTag$2: - return cloneRegExp(object); + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + updateHookTypesDev(); + return mountRef(initialValue); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; - case setTag$2: - return new Ctor; + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + updateHookTypesDev(); + return mountDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + updateHookTypesDev(); + return mountDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + updateHookTypesDev(); + return mountTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + updateHookTypesDev(); + return mountMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + updateHookTypesDev(); + return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + updateHookTypesDev(); + return mountId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; - case symbolTag$3: - return cloneSymbol(object); - } -} + HooksDispatcherOnUpdateInDEV = { + readContext: function (context) { + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -var _initCloneByTag = initCloneByTag$1; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -var isObject$6 = isObject_1; + try { + return updateReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + updateHookTypesDev(); + return updateRef(); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/** Built-in value references. */ -var objectCreate = Object.create; + try { + return updateState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + updateHookTypesDev(); + return updateDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + updateHookTypesDev(); + return updateTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; -/** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ -var baseCreate$1 = (function() { - function object() {} - return function(proto) { - if (!isObject$6(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; -}()); + HooksDispatcherOnRerenderInDEV = { + readContext: function (context) { + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; -var _baseCreate = baseCreate$1; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; -var baseCreate = _baseCreate, - getPrototype$1 = _getPrototype, - isPrototype$2 = _isPrototype; + try { + return rerenderReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + updateHookTypesDev(); + return updateRef(); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; -/** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ -function initCloneObject$1(object) { - return (typeof object.constructor == 'function' && !isPrototype$2(object)) - ? baseCreate(getPrototype$1(object)) - : {}; -} + try { + return rerenderState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + updateHookTypesDev(); + return rerenderDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + updateHookTypesDev(); + return rerenderTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; -var _initCloneObject = initCloneObject$1; + InvalidNestedHooksDispatcherOnMountInDEV = { + readContext: function (context) { + warnInvalidContextAccess(); + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + warnInvalidHookAccess(); + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; -var getTag$3 = _getTag, - isObjectLike$6 = isObjectLike_1; + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + warnInvalidHookAccess(); + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; -/** `Object#toString` result references. */ -var mapTag$1 = '[object Map]'; + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountRef(initialValue); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + warnInvalidHookAccess(); + mountHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; -/** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ -function baseIsMap$1(value) { - return isObjectLike$6(value) && getTag$3(value) == mapTag$1; -} + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + warnInvalidHookAccess(); + mountHookTypesDev(); + return mountId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; -var _baseIsMap = baseIsMap$1; + InvalidNestedHooksDispatcherOnUpdateInDEV = { + readContext: function (context) { + warnInvalidContextAccess(); + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -var baseIsMap = _baseIsMap, - baseUnary$4 = _baseUnary, - nodeUtil$2 = _nodeUtil.exports; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/* Node.js helper references. */ -var nodeIsMap = nodeUtil$2 && nodeUtil$2.isMap; + try { + return updateReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateRef(); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/** - * Checks if `value` is classified as a `Map` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - * @example - * - * _.isMap(new Map); - * // => true - * - * _.isMap(new WeakMap); - * // => false - */ -var isMap$1 = nodeIsMap ? baseUnary$4(nodeIsMap) : baseIsMap; + try { + return updateState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; -var isMap_1 = isMap$1; + InvalidNestedHooksDispatcherOnRerenderInDEV = { + readContext: function (context) { + warnInvalidContextAccess(); + return readContext(context); + }, + useCallback: function (callback, deps) { + currentHookNameInDev = 'useCallback'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateCallback(callback, deps); + }, + useContext: function (context) { + currentHookNameInDev = 'useContext'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return readContext(context); + }, + useEffect: function (create, deps) { + currentHookNameInDev = 'useEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateEffect(create, deps); + }, + useImperativeHandle: function (ref, create, deps) { + currentHookNameInDev = 'useImperativeHandle'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateImperativeHandle(ref, create, deps); + }, + useInsertionEffect: function (create, deps) { + currentHookNameInDev = 'useInsertionEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateInsertionEffect(create, deps); + }, + useLayoutEffect: function (create, deps) { + currentHookNameInDev = 'useLayoutEffect'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateLayoutEffect(create, deps); + }, + useMemo: function (create, deps) { + currentHookNameInDev = 'useMemo'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -var getTag$2 = _getTag, - isObjectLike$5 = isObjectLike_1; + try { + return updateMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function (reducer, initialArg, init) { + currentHookNameInDev = 'useReducer'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/** `Object#toString` result references. */ -var setTag$1 = '[object Set]'; + try { + return rerenderReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function (initialValue) { + currentHookNameInDev = 'useRef'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateRef(); + }, + useState: function (initialState) { + currentHookNameInDev = 'useState'; + warnInvalidHookAccess(); + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; -/** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ -function baseIsSet$1(value) { - return isObjectLike$5(value) && getTag$2(value) == setTag$1; -} + try { + return rerenderState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function (value, formatterFn) { + currentHookNameInDev = 'useDebugValue'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateDebugValue(); + }, + useDeferredValue: function (value) { + currentHookNameInDev = 'useDeferredValue'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return rerenderDeferredValue(value); + }, + useTransition: function () { + currentHookNameInDev = 'useTransition'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return rerenderTransition(); + }, + useMutableSource: function (source, getSnapshot, subscribe) { + currentHookNameInDev = 'useMutableSource'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateMutableSource(); + }, + useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { + currentHookNameInDev = 'useSyncExternalStore'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateSyncExternalStore(subscribe, getSnapshot); + }, + useId: function () { + currentHookNameInDev = 'useId'; + warnInvalidHookAccess(); + updateHookTypesDev(); + return updateId(); + }, + unstable_isNewReconciler: enableNewReconciler + }; + } -var _baseIsSet = baseIsSet$1; + var now$2 = Scheduler.unstable_now; + var commitTime = 0; + var layoutEffectStartTime = -1; + var profilerStartTime = -1; + var passiveEffectStartTime = -1; + /** + * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect). + * + * The overall sequence is: + * 1. render + * 2. commit (and call `onRender`, `onCommit`) + * 3. check for nested updates + * 4. flush passive effects (and call `onPostCommit`) + * + * Nested updates are identified in step 3 above, + * but step 4 still applies to the work that was just committed. + * We use two flags to track nested updates then: + * one tracks whether the upcoming update is a nested update, + * and the other tracks whether the current update was a nested update. + * The first value gets synced to the second at the start of the render phase. + */ -var baseIsSet = _baseIsSet, - baseUnary$3 = _baseUnary, - nodeUtil$1 = _nodeUtil.exports; + var currentUpdateIsNested = false; + var nestedUpdateScheduled = false; -/* Node.js helper references. */ -var nodeIsSet = nodeUtil$1 && nodeUtil$1.isSet; + function isCurrentUpdateNested() { + return currentUpdateIsNested; + } -/** - * Checks if `value` is classified as a `Set` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - * @example - * - * _.isSet(new Set); - * // => true - * - * _.isSet(new WeakSet); - * // => false - */ -var isSet$1 = nodeIsSet ? baseUnary$3(nodeIsSet) : baseIsSet; - -var isSet_1 = isSet$1; - -var Stack = _Stack, - arrayEach = _arrayEach, - assignValue$2 = _assignValue, - baseAssign = _baseAssign, - baseAssignIn = _baseAssignIn, - cloneBuffer = _cloneBuffer.exports, - copyArray = _copyArray, - copySymbols = _copySymbols, - copySymbolsIn = _copySymbolsIn, - getAllKeys = _getAllKeys, - getAllKeysIn$2 = _getAllKeysIn, - getTag$1 = _getTag, - initCloneArray = _initCloneArray, - initCloneByTag = _initCloneByTag, - initCloneObject = _initCloneObject, - isArray$a = isArray_1$1, - isBuffer = isBuffer$4.exports, - isMap = isMap_1, - isObject$5 = isObject_1, - isSet = isSet_1, - keys$3 = keys_1, - keysIn$2 = keysIn_1; - -/** Used to compose bitmasks for cloning. */ -var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG$1 = 4; + function markNestedUpdateScheduled() { + { + nestedUpdateScheduled = true; + } + } -/** `Object#toString` result references. */ -var argsTag$2 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag$2 = '[object Function]', - genTag$2 = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag$1 = '[object RegExp]', - setTag = '[object Set]', - stringTag$1 = '[object String]', - symbolTag$2 = '[object Symbol]', - weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values supported by `_.clone`. */ -var cloneableTags = {}; -cloneableTags[argsTag$2] = cloneableTags[arrayTag] = -cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = -cloneableTags[boolTag] = cloneableTags[dateTag] = -cloneableTags[float32Tag] = cloneableTags[float64Tag] = -cloneableTags[int8Tag] = cloneableTags[int16Tag] = -cloneableTags[int32Tag] = cloneableTags[mapTag] = -cloneableTags[numberTag] = cloneableTags[objectTag] = -cloneableTags[regexpTag$1] = cloneableTags[setTag] = -cloneableTags[stringTag$1] = cloneableTags[symbolTag$2] = -cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = -cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; -cloneableTags[errorTag] = cloneableTags[funcTag$2] = -cloneableTags[weakMapTag] = false; + function resetNestedUpdateFlag() { + { + currentUpdateIsNested = false; + nestedUpdateScheduled = false; + } + } -/** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} bitmask The bitmask flags. - * 1 - Deep clone - * 2 - Flatten inherited properties - * 4 - Clone symbols - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ -function baseClone$1(value, bitmask, customizer, key, object, stack) { - var result, - isDeep = bitmask & CLONE_DEEP_FLAG, - isFlat = bitmask & CLONE_FLAT_FLAG, - isFull = bitmask & CLONE_SYMBOLS_FLAG$1; + function syncNestedUpdateFlag() { + { + currentUpdateIsNested = nestedUpdateScheduled; + nestedUpdateScheduled = false; + } + } - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject$5(value)) { - return value; - } - var isArr = isArray$a(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag$1(value), - isFunc = tag == funcTag$2 || tag == genTag$2; + function getCommitTime() { + return commitTime; + } - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag$2 || (isFunc && !object)) { - result = (isFlat || isFunc) ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat - ? copySymbolsIn(value, baseAssignIn(result, value)) - : copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); + function recordCommitTime() { - if (isSet(value)) { - value.forEach(function(subValue) { - result.add(baseClone$1(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key) { - result.set(key, baseClone$1(subValue, bitmask, customizer, key, value, stack)); - }); - } + commitTime = now$2(); + } - var keysFunc = isFull - ? (isFlat ? getAllKeysIn$2 : getAllKeys) - : (isFlat ? keysIn$2 : keys$3); + function startProfilerTimer(fiber) { - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue$2(result, key, baseClone$1(subValue, bitmask, customizer, key, value, stack)); - }); - return result; -} + profilerStartTime = now$2(); -var _baseClone = baseClone$1; + if (fiber.actualStartTime < 0) { + fiber.actualStartTime = now$2(); + } + } -var baseClone = _baseClone; + function stopProfilerTimerIfRunning(fiber) { -/** Used to compose bitmasks for cloning. */ -var CLONE_SYMBOLS_FLAG = 4; + profilerStartTime = -1; + } -/** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ -function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); -} + function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { -var clone_1$1 = clone; + if (profilerStartTime >= 0) { + var elapsedTime = now$2() - profilerStartTime; + fiber.actualDuration += elapsedTime; -var api$2 = {}; + if (overrideBaseTime) { + fiber.selfBaseDuration = elapsedTime; + } -var print = {}; + profilerStartTime = -1; + } + } -Object.defineProperty(print, "__esModule", { value: true }); -print.PRINT_WARNING = print.PRINT_ERROR = void 0; -function PRINT_ERROR(msg) { - /* istanbul ignore else - can't override global.console in node.js */ - if (console && console.error) { - console.error("Error: ".concat(msg)); - } -} -print.PRINT_ERROR = PRINT_ERROR; -function PRINT_WARNING(msg) { - /* istanbul ignore else - can't override global.console in node.js*/ - if (console && console.warn) { - // TODO: modify docs accordingly - console.warn("Warning: ".concat(msg)); - } -} -print.PRINT_WARNING = PRINT_WARNING; - -var timer$1 = {}; - -Object.defineProperty(timer$1, "__esModule", { value: true }); -timer$1.timer = void 0; -function timer(func) { - var start = new Date().getTime(); - var val = func(); - var end = new Date().getTime(); - var total = end - start; - return { time: total, value: val }; -} -timer$1.timer = timer; - -var toFastProperties$1 = {}; - -Object.defineProperty(toFastProperties$1, "__esModule", { value: true }); -toFastProperties$1.toFastProperties = void 0; -// based on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216 -function toFastProperties(toBecomeFast) { - function FakeConstructor() { } - // If our object is used as a constructor it would receive - FakeConstructor.prototype = toBecomeFast; - var fakeInstance = new FakeConstructor(); - function fakeAccess() { - return typeof fakeInstance.bar; - } - // help V8 understand this is a "real" prototype by actually using - // the fake instance. - fakeAccess(); - fakeAccess(); - return toBecomeFast; -} -toFastProperties$1.toFastProperties = toFastProperties; - -(function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.toFastProperties = exports.timer = exports.PRINT_ERROR = exports.PRINT_WARNING = void 0; - var print_1 = print; - Object.defineProperty(exports, "PRINT_WARNING", { enumerable: true, get: function () { return print_1.PRINT_WARNING; } }); - Object.defineProperty(exports, "PRINT_ERROR", { enumerable: true, get: function () { return print_1.PRINT_ERROR; } }); - var timer_1 = timer$1; - Object.defineProperty(exports, "timer", { enumerable: true, get: function () { return timer_1.timer; } }); - var to_fast_properties_1 = toFastProperties$1; - Object.defineProperty(exports, "toFastProperties", { enumerable: true, get: function () { return to_fast_properties_1.toFastProperties; } }); - -} (api$2)); - -var follow = {}; - -var rest = {}; + function recordLayoutEffectDuration(fiber) { -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ + if (layoutEffectStartTime >= 0) { + var elapsedTime = now$2() - layoutEffectStartTime; + layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor + // Or the root (for the DevTools Profiler to read) -function baseSlice$3(array, start, end) { - var index = -1, - length = array.length; + var parentFiber = fiber.return; - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + root.effectDuration += elapsedTime; + return; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.effectDuration += elapsedTime; + return; + } + + parentFiber = parentFiber.return; + } + } + } -var _baseSlice = baseSlice$3; + function recordPassiveEffectDuration(fiber) { -/** Used to match a single whitespace character. */ + if (passiveEffectStartTime >= 0) { + var elapsedTime = now$2() - passiveEffectStartTime; + passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor + // Or the root (for the DevTools Profiler to read) -var reWhitespace = /\s/; + var parentFiber = fiber.return; -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ -function trimmedEndIndex$1(string) { - var index = string.length; + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; - while (index-- && reWhitespace.test(string.charAt(index))) {} - return index; -} + if (root !== null) { + root.passiveEffectDuration += elapsedTime; + } -var _trimmedEndIndex = trimmedEndIndex$1; + return; -var trimmedEndIndex = _trimmedEndIndex; + case Profiler: + var parentStateNode = parentFiber.stateNode; -/** Used to match leading whitespace. */ -var reTrimStart = /^\s+/; + if (parentStateNode !== null) { + // Detached fibers have their state node cleared out. + // In this case, the return pointer is also cleared out, + // so we won't be able to report the time spent in this Profiler's subtree. + parentStateNode.passiveEffectDuration += elapsedTime; + } -/** - * The base implementation of `_.trim`. - * - * @private - * @param {string} string The string to trim. - * @returns {string} Returns the trimmed string. - */ -function baseTrim$1(string) { - return string - ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') - : string; -} + return; + } -var _baseTrim = baseTrim$1; + parentFiber = parentFiber.return; + } + } + } -var baseTrim = _baseTrim, - isObject$4 = isObject_1, - isSymbol$2 = isSymbol_1; + function startLayoutEffectTimer() { -/** Used as references for various `Number` constants. */ -var NAN = 0 / 0; + layoutEffectStartTime = now$2(); + } + + function startPassiveEffectTimer() { -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + passiveEffectStartTime = now$2(); + } -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + function transferActualDuration(fiber) { + // Transfer time spent rendering these children so we don't lose it + // after we rerender. This is used as a helper in special cases + // where we should count the work of multiple passes. + var child = fiber.child; -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; + while (child) { + fiber.actualDuration += child.actualDuration; + child = child.sibling; + } + } -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; + function createCapturedValue(value, source) { + // If the value is an error, call this function immediately after it is thrown + // so the stack is accurate. + return { + value: value, + source: source, + stack: getStackByFiberInDevAndProd(source) + }; + } -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber$1(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol$2(value)) { - return NAN; - } - if (isObject$4(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject$4(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); -} + // This module is forked in different environments. + // By default, return `true` to log errors to the console. + // Forks can return `false` if this isn't desirable. + function showErrorDialog(boundary, errorInfo) { + return true; + } -var toNumber_1 = toNumber$1; + function logCapturedError(boundary, errorInfo) { + try { + var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging. + // This enables renderers like ReactNative to better manage redbox behavior. -var toNumber = toNumber_1; + if (logError === false) { + return; + } -/** Used as references for various `Number` constants. */ -var INFINITY$3 = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308; + var error = errorInfo.value; -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite$1(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY$3 || value === -INFINITY$3) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; -} + if (true) { + var source = errorInfo.source; + var stack = errorInfo.stack; + var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling + // `preventDefault()` in window `error` handler. + // We record this information as an expando on the error. -var toFinite_1 = toFinite$1; + if (error != null && error._suppressLogging) { + if (boundary.tag === ClassComponent) { + // The error is recoverable and was silenced. + // Ignore it and don't print the stack addendum. + // This is handy for testing error boundaries without noise. + return; + } // The error is fatal. Since the silencing might have + // been accidental, we'll surface it anyway. + // However, the browser would have silenced the original error + // so we'll print it first, and then print the stack addendum. -var toFinite = toFinite_1; -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger$5(value) { - var result = toFinite(value), - remainder = result % 1; + console['error'](error); // Don't transform to our wrapper + // For a more detailed description of this block, see: + // https://github.com/facebook/react/pull/13384 + } - return result === result ? (remainder ? result - remainder : result) : 0; -} + var componentName = source ? getComponentNameFromFiber(source) : null; + var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:'; + var errorBoundaryMessage; -var toInteger_1 = toInteger$5; + if (boundary.tag === HostRoot) { + errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.'; + } else { + var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous'; + errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + "."); + } -var baseSlice$2 = _baseSlice, - toInteger$4 = toInteger_1; + var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. + // We don't include the original error message and JS stack because the browser + // has already printed it. Even if the application swallows the error, it is still + // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. -/** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ -function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger$4(n); - return baseSlice$2(array, n < 0 ? 0 : n, length); -} + console['error'](combinedMessage); // Don't transform to our wrapper + } + } catch (e) { + // This method must not throw, or React internal state will get messed up. + // If console.error is overridden, or logCapturedError() shows a dialog that throws, + // we want to report this error outside of the normal stack as a last resort. + // https://github.com/facebook/react/issues/13188 + setTimeout(function () { + throw e; + }); + } + } -var drop_1$2 = drop; + var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map; -var api$1 = {}; + function createRootErrorUpdate(fiber, errorInfo, lane) { + var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null. -var model$1 = {}; + update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property + // being called "element". -var baseGetTag$1 = _baseGetTag, - isArray$9 = isArray_1$1, - isObjectLike$4 = isObjectLike_1; + update.payload = { + element: null + }; + var error = errorInfo.value; -/** `Object#toString` result references. */ -var stringTag = '[object String]'; + update.callback = function () { + onUncaughtError(error); + logCapturedError(fiber, errorInfo); + }; -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString$1(value) { - return typeof value == 'string' || - (!isArray$9(value) && isObjectLike$4(value) && baseGetTag$1(value) == stringTag); -} + return update; + } -var isString_1$1 = isString$1; + function createClassErrorUpdate(fiber, errorInfo, lane) { + var update = createUpdate(NoTimestamp, lane); + update.tag = CaptureUpdate; + var getDerivedStateFromError = fiber.type.getDerivedStateFromError; -var baseGetTag = _baseGetTag, - isObjectLike$3 = isObjectLike_1; + if (typeof getDerivedStateFromError === 'function') { + var error$1 = errorInfo.value; -/** `Object#toString` result references. */ -var regexpTag = '[object RegExp]'; + update.payload = function () { + return getDerivedStateFromError(error$1); + }; -/** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ -function baseIsRegExp$1(value) { - return isObjectLike$3(value) && baseGetTag(value) == regexpTag; -} + update.callback = function () { + { + markFailedErrorBoundaryForHotReloading(fiber); + } -var _baseIsRegExp = baseIsRegExp$1; + logCapturedError(fiber, errorInfo); + }; + } -var baseIsRegExp = _baseIsRegExp, - baseUnary$2 = _baseUnary, - nodeUtil = _nodeUtil.exports; + var inst = fiber.stateNode; -/* Node.js helper references. */ -var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; + if (inst !== null && typeof inst.componentDidCatch === 'function') { + update.callback = function callback() { + { + markFailedErrorBoundaryForHotReloading(fiber); + } -/** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ -var isRegExp = nodeIsRegExp ? baseUnary$2(nodeIsRegExp) : baseIsRegExp; + logCapturedError(fiber, errorInfo); -var isRegExp_1$1 = isRegExp; + if (typeof getDerivedStateFromError !== 'function') { + // To preserve the preexisting retry behavior of error boundaries, + // we keep track of which ones already failed during this batch. + // This gets reset before we yield back to the browser. + // TODO: Warn in strict mode if getDerivedStateFromError is + // not defined. + markLegacyErrorBoundaryAsFailed(this); + } -var assignValue$1 = _assignValue, - castPath$1 = _castPath, - isIndex$2 = _isIndex, - isObject$3 = isObject_1, - toKey$2 = _toKey; + var error$1 = errorInfo.value; + var stack = errorInfo.stack; + this.componentDidCatch(error$1, { + componentStack: stack !== null ? stack : '' + }); -/** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ -function baseSet$1(object, path, value, customizer) { - if (!isObject$3(object)) { - return object; - } - path = castPath$1(path, object); + { + if (typeof getDerivedStateFromError !== 'function') { + // If componentDidCatch is the only error boundary method defined, + // then it needs to call setState to recover from errors. + // If no state update is scheduled then the boundary will swallow the error. + if (!includesSomeLane(fiber.lanes, SyncLane)) { + error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown'); + } + } + } + }; + } - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; + return update; + } - while (nested != null && ++index < length) { - var key = toKey$2(path[index]), - newValue = value; + function attachPingListener(root, wakeable, lanes) { + // Attach a ping listener + // + // The data might resolve before we have a chance to commit the fallback. Or, + // in the case of a refresh, we'll never commit a fallback. So we need to + // attach a listener now. When it resolves ("pings"), we can decide whether to + // try rendering the tree again. + // + // Only attach a listener if one does not already exist for the lanes + // we're currently rendering (which acts like a "thread ID" here). + // + // We only need to do this in concurrent mode. Legacy Suspense always + // commits fallbacks synchronously, so there are no pings. + var pingCache = root.pingCache; + var threadIDs; - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } + if (pingCache === null) { + pingCache = root.pingCache = new PossiblyWeakMap$1(); + threadIDs = new Set(); + pingCache.set(wakeable, threadIDs); + } else { + threadIDs = pingCache.get(wakeable); - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject$3(objValue) - ? objValue - : (isIndex$2(path[index + 1]) ? [] : {}); - } - } - assignValue$1(nested, key, newValue); - nested = nested[key]; - } - return object; -} + if (threadIDs === undefined) { + threadIDs = new Set(); + pingCache.set(wakeable, threadIDs); + } + } -var _baseSet = baseSet$1; + if (!threadIDs.has(lanes)) { + // Memoize using the thread ID to prevent redundant listeners. + threadIDs.add(lanes); + var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes); -var baseGet = _baseGet, - baseSet = _baseSet, - castPath = _castPath; + { + if (isDevToolsPresent) { + // If we have pending work still, restore the original updaters + restorePendingUpdaters(root, lanes); + } + } -/** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ -function basePickBy$3(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; + wakeable.then(ping, ping); + } + } - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); + function attachRetryListener(suspenseBoundary, root, wakeable, lanes) { + // Retry listener + // + // If the fallback does commit, we need to attach a different type of + // listener. This one schedules an update on the Suspense boundary to turn + // the fallback state off. + // + // Stash the wakeable on the boundary fiber so we can access it in the + // commit phase. + // + // When the wakeable resolves, we'll attempt to render the boundary + // again ("retry"). + var wakeables = suspenseBoundary.updateQueue; - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; -} + if (wakeables === null) { + var updateQueue = new Set(); + updateQueue.add(wakeable); + suspenseBoundary.updateQueue = updateQueue; + } else { + wakeables.add(wakeable); + } + } -var _basePickBy = basePickBy$3; + function resetSuspendedComponent(sourceFiber, rootRenderLanes) { + // A legacy mode Suspense quirk, only relevant to hook components. -var arrayMap$3 = _arrayMap, - baseIteratee$8 = _baseIteratee, - basePickBy$2 = _basePickBy, - getAllKeysIn$1 = _getAllKeysIn; -/** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ -function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap$3(getAllKeysIn$1(object), function(prop) { - return [prop]; - }); - predicate = baseIteratee$8(predicate); - return basePickBy$2(object, props, function(value, path) { - return predicate(value, path[0]); - }); -} + var tag = sourceFiber.tag; -var pickBy_1$1 = pickBy; + if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) { + var currentSource = sourceFiber.alternate; -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ + if (currentSource) { + sourceFiber.updateQueue = currentSource.updateQueue; + sourceFiber.memoizedState = currentSource.memoizedState; + sourceFiber.lanes = currentSource.lanes; + } else { + sourceFiber.updateQueue = null; + sourceFiber.memoizedState = null; + } + } + } -function apply$3(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} + function getNearestSuspenseBoundaryToCapture(returnFiber) { + var node = returnFiber; -var _apply = apply$3; + do { + if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) { + return node; + } // This boundary already captured during this render. Continue to the next + // boundary. -var apply$2 = _apply; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax$5 = Math.max; + node = node.return; + } while (node !== null); -/** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ -function overRest$1(func, start, transform) { - start = nativeMax$5(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax$5(args.length - start, 0), - array = Array(length); + return null; + } - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply$2(func, this, otherArgs); - }; -} + function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) { + // This marks a Suspense boundary so that when we're unwinding the stack, + // it captures the suspended "exception" and does a second (fallback) pass. + if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { + // Legacy Mode Suspense + // + // If the boundary is in legacy mode, we should *not* + // suspend the commit. Pretend as if the suspended component rendered + // null and keep rendering. When the Suspense boundary completes, + // we'll do a second pass to render the fallback. + if (suspenseBoundary === returnFiber) { + // Special case where we suspended while reconciling the children of + // a Suspense boundary's inner Offscreen wrapper fiber. This happens + // when a React.lazy component is a direct child of a + // Suspense boundary. + // + // Suspense boundaries are implemented as multiple fibers, but they + // are a single conceptual unit. The legacy mode behavior where we + // pretend the suspended fiber committed as `null` won't work, + // because in this case the "suspended" fiber is the inner + // Offscreen wrapper. + // + // Because the contents of the boundary haven't started rendering + // yet (i.e. nothing in the tree has partially rendered) we can + // switch to the regular, concurrent mode behavior: mark the + // boundary with ShouldCapture and enter the unwind phase. + suspenseBoundary.flags |= ShouldCapture; + } else { + suspenseBoundary.flags |= DidCapture; + sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete. + // But we shouldn't call any lifecycle methods or callbacks. Remove + // all lifecycle effect tags. -var _overRest = overRest$1; + sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ + if (supportsPersistence && enablePersistentOffscreenHostContainer) { + // Another legacy Suspense quirk. In persistent mode, if this is the + // initial mount, override the props of the host container to hide + // its contents. + var currentSuspenseBoundary = suspenseBoundary.alternate; -function constant$2(value) { - return function() { - return value; - }; -} + if (currentSuspenseBoundary === null) { + var offscreenFiber = suspenseBoundary.child; + var offscreenContainer = offscreenFiber.child; -var constant_1 = constant$2; + if (offscreenContainer !== null) { + var children = offscreenContainer.memoizedProps.children; + var containerProps = getOffscreenContainerProps('hidden', children); + offscreenContainer.pendingProps = containerProps; + offscreenContainer.memoizedProps = containerProps; + } + } + } -var constant$1 = constant_1, - defineProperty = _defineProperty, - identity$1 = identity_1; + if (sourceFiber.tag === ClassComponent) { + var currentSourceFiber = sourceFiber.alternate; -/** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var baseSetToString$1 = !defineProperty ? identity$1 : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant$1(string), - 'writable': true - }); -}; + if (currentSourceFiber === null) { + // This is a new mount. Change the tag so it's not mistaken for a + // completed class component. For example, we should not call + // componentWillUnmount if it is deleted. + sourceFiber.tag = IncompleteClassComponent; + } else { + // When we try rendering again, we should not reuse the current fiber, + // since it's known to be in an inconsistent state. Use a force update to + // prevent a bail out. + var update = createUpdate(NoTimestamp, SyncLane); + update.tag = ForceUpdate; + enqueueUpdate(sourceFiber, update); + } + } // The source fiber did not complete. Mark it with Sync priority to + // indicate that it still has pending work. -var _baseSetToString = baseSetToString$1; -/** Used to detect hot functions by number of calls within a span of milliseconds. */ + sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); + } -var HOT_COUNT = 800, - HOT_SPAN = 16; + return suspenseBoundary; + } // Confirmed that the boundary is in a concurrent mode tree. Continue + // with the normal suspend path. + // + // After this we'll use a set of heuristics to determine whether this + // render pass will run to completion or restart or "suspend" the commit. + // The actual logic for this is spread out in different places. + // + // This first principle is that if we're going to suspend when we complete + // a root, then we should also restart if we get an update or ping that + // might unsuspend it, and vice versa. The only reason to suspend is + // because you think you might want to restart before committing. However, + // it doesn't make sense to restart only while in the period we're suspended. + // + // Restarting too aggressively is also not good because it starves out any + // intermediate loading state. So we use heuristics to determine when. + // Suspense Heuristics + // + // If nothing threw a Promise or all the same fallbacks are already showing, + // then don't suspend/restart. + // + // If this is an initial render of a new tree of Suspense boundaries and + // those trigger a fallback, then don't suspend/restart. We want to ensure + // that we can show the initial loading state as quickly as possible. + // + // If we hit a "Delayed" case, such as when we'd switch from content back into + // a fallback, then we should always suspend/restart. Transitions apply + // to this case. If none is defined, JND is used instead. + // + // If we're already showing a fallback and it gets "retried", allowing us to show + // another level, but there's still an inner boundary that would show a fallback, + // then we suspend/restart for 500ms since the last time we showed a fallback + // anywhere in the tree. This effectively throttles progressive loading into a + // consistent train of commits. This also gives us an opportunity to restart to + // get to the completed state slightly earlier. + // + // If there's ambiguity due to batching it's resolved in preference of: + // 1) "delayed", 2) "initial render", 3) "retry". + // + // We want to ensure that a "busy" state doesn't get force committed. We want to + // ensure that new initial loading states can commit as soon as possible. -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeNow = Date.now; -/** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ -function shortOut$1(func) { - var count = 0, - lastCalled = 0; + suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in + // the begin phase to prevent an early bailout. - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); + suspenseBoundary.lanes = rootRenderLanes; + return suspenseBoundary; + } - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; -} + function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) { + // The source fiber did not complete. + sourceFiber.flags |= Incomplete; -var _shortOut = shortOut$1; + { + if (isDevToolsPresent) { + // If we have pending work still, restore the original updaters + restorePendingUpdaters(root, rootRenderLanes); + } + } -var baseSetToString = _baseSetToString, - shortOut = _shortOut; + if (value !== null && typeof value === 'object' && typeof value.then === 'function') { + // This is a wakeable. The component suspended. + var wakeable = value; + resetSuspendedComponent(sourceFiber); -/** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var setToString$1 = shortOut(baseSetToString); -var _setToString = setToString$1; + var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); -var identity = identity_1, - overRest = _overRest, - setToString = _setToString; + if (suspenseBoundary !== null) { + suspenseBoundary.flags &= ~ForceClientRender; + markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always + // commits fallbacks synchronously, so there are no pings. -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest$5(func, start) { - return setToString(overRest(func, start, identity), func + ''); -} + if (suspenseBoundary.mode & ConcurrentMode) { + attachPingListener(root, wakeable, rootRenderLanes); + } -var _baseRest = baseRest$5; + attachRetryListener(suspenseBoundary, root, wakeable); + return; + } else { + // No boundary was found. Unless this is a sync update, this is OK. + // We can suspend and wait for more data to arrive. + if (!includesSyncLane(rootRenderLanes)) { + // This is not a sync update. Suspend. Since we're not activating a + // Suspense boundary, this will unwind all the way to the root without + // performing a second pass to render a fallback. (This is arguably how + // refresh transitions should work, too, since we're not going to commit + // the fallbacks anyway.) + // + // This case also applies to initial hydration. + attachPingListener(root, wakeable, rootRenderLanes); + renderDidSuspendDelayIfPossible(); + return; + } // This is a sync/discrete update. We treat this case like an error + // because discrete renders are expected to produce a complete tree + // synchronously to maintain consistency with external state. -var eq$2 = eq_1, - isArrayLike$6 = isArrayLike_1, - isIndex$1 = _isIndex, - isObject$2 = isObject_1; -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall$4(value, index, object) { - if (!isObject$2(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike$6(object) && isIndex$1(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq$2(object[index], value); - } - return false; -} + var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path. + // The error will be caught by the nearest suspense boundary. -var _isIterateeCall = isIterateeCall$4; + value = uncaughtSuspenseError; + } + } else { + // This is a regular error, not a Suspense wakeable. + if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { + markDidSuspendWhileHydratingDEV(); -var baseRest$4 = _baseRest, - isIterateeCall$3 = _isIterateeCall; + var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by + // discarding the dehydrated content and switching to a client render. + // Instead of surfacing the error, find the nearest Suspense boundary + // and render it again without hydration. -/** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ -function createAssigner$1(assigner) { - return baseRest$4(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall$3(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); -} -var _createAssigner = createAssigner$1; + if (_suspenseBoundary !== null) { + if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) { + // Set a flag to indicate that we should try rendering the normal + // children again, not the fallback. + _suspenseBoundary.flags |= ForceClientRender; + } -var assignValue = _assignValue, - copyObject = _copyObject, - createAssigner = _createAssigner, - isArrayLike$5 = isArrayLike_1, - isPrototype$1 = _isPrototype, - keys$2 = keys_1; + markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should + // still log it so it can be fixed. -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; + queueHydrationError(value); + return; + } + } + } // We didn't find a boundary that could handle this type of exception. Start + // over and traverse parent path again, this time treating the exception + // as an error. -/** Used to check objects for own properties. */ -var hasOwnProperty$4 = objectProto$4.hasOwnProperty; -/** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } - */ -var assign$2 = createAssigner(function(object, source) { - if (isPrototype$1(source) || isArrayLike$5(source)) { - copyObject(source, keys$2(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty$4.call(source, key)) { - assignValue(object, key, source[key]); - } - } -}); + renderDidError(value); + value = createCapturedValue(value, sourceFiber); + var workInProgress = returnFiber; -var assign_1$3 = assign$2; + do { + switch (workInProgress.tag) { + case HostRoot: + { + var _errorInfo = value; + workInProgress.flags |= ShouldCapture; + var lane = pickArbitraryLane(rootRenderLanes); + workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); + var update = createRootErrorUpdate(workInProgress, _errorInfo, lane); + enqueueCapturedUpdate(workInProgress, update); + return; + } -var __extends$4 = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$9 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(model$1, "__esModule", { value: true }); -model$1.serializeProduction = model$1.serializeGrammar = model$1.Terminal = model$1.Alternation = model$1.RepetitionWithSeparator = model$1.Repetition = model$1.RepetitionMandatoryWithSeparator = model$1.RepetitionMandatory = model$1.Option = model$1.Alternative = model$1.Rule = model$1.NonTerminal = model$1.AbstractProduction = void 0; -var map_1$3 = __importDefault$9(map_1$4); -var forEach_1$3 = __importDefault$9(forEach_1$4); -var isString_1 = __importDefault$9(isString_1$1); -var isRegExp_1 = __importDefault$9(isRegExp_1$1); -var pickBy_1 = __importDefault$9(pickBy_1$1); -var assign_1$2 = __importDefault$9(assign_1$3); -// TODO: duplicated code to avoid extracting another sub-package -- how to avoid? -function tokenLabel(tokType) { - if (hasTokenLabel(tokType)) { - return tokType.LABEL; - } - else { - return tokType.name; - } -} -// TODO: duplicated code to avoid extracting another sub-package -- how to avoid? -function hasTokenLabel(obj) { - return (0, isString_1.default)(obj.LABEL) && obj.LABEL !== ""; -} -var AbstractProduction = /** @class */ (function () { - function AbstractProduction(_definition) { - this._definition = _definition; - } - Object.defineProperty(AbstractProduction.prototype, "definition", { - get: function () { - return this._definition; - }, - set: function (value) { - this._definition = value; - }, - enumerable: false, - configurable: true - }); - AbstractProduction.prototype.accept = function (visitor) { - visitor.visit(this); - (0, forEach_1$3.default)(this.definition, function (prod) { - prod.accept(visitor); - }); - }; - return AbstractProduction; -}()); -model$1.AbstractProduction = AbstractProduction; -var NonTerminal = /** @class */ (function (_super) { - __extends$4(NonTerminal, _super); - function NonTerminal(options) { - var _this = _super.call(this, []) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - Object.defineProperty(NonTerminal.prototype, "definition", { - get: function () { - if (this.referencedRule !== undefined) { - return this.referencedRule.definition; - } - return []; - }, - set: function (definition) { - // immutable - }, - enumerable: false, - configurable: true - }); - NonTerminal.prototype.accept = function (visitor) { - visitor.visit(this); - // don't visit children of a reference, we will get cyclic infinite loops if we do so - }; - return NonTerminal; -}(AbstractProduction)); -model$1.NonTerminal = NonTerminal; -var Rule = /** @class */ (function (_super) { - __extends$4(Rule, _super); - function Rule(options) { - var _this = _super.call(this, options.definition) || this; - _this.orgText = ""; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return Rule; -}(AbstractProduction)); -model$1.Rule = Rule; -var Alternative = /** @class */ (function (_super) { - __extends$4(Alternative, _super); - function Alternative(options) { - var _this = _super.call(this, options.definition) || this; - _this.ignoreAmbiguities = false; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return Alternative; -}(AbstractProduction)); -model$1.Alternative = Alternative; -var Option = /** @class */ (function (_super) { - __extends$4(Option, _super); - function Option(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return Option; -}(AbstractProduction)); -model$1.Option = Option; -var RepetitionMandatory = /** @class */ (function (_super) { - __extends$4(RepetitionMandatory, _super); - function RepetitionMandatory(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionMandatory; -}(AbstractProduction)); -model$1.RepetitionMandatory = RepetitionMandatory; -var RepetitionMandatoryWithSeparator = /** @class */ (function (_super) { - __extends$4(RepetitionMandatoryWithSeparator, _super); - function RepetitionMandatoryWithSeparator(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionMandatoryWithSeparator; -}(AbstractProduction)); -model$1.RepetitionMandatoryWithSeparator = RepetitionMandatoryWithSeparator; -var Repetition = /** @class */ (function (_super) { - __extends$4(Repetition, _super); - function Repetition(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return Repetition; -}(AbstractProduction)); -model$1.Repetition = Repetition; -var RepetitionWithSeparator = /** @class */ (function (_super) { - __extends$4(RepetitionWithSeparator, _super); - function RepetitionWithSeparator(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionWithSeparator; -}(AbstractProduction)); -model$1.RepetitionWithSeparator = RepetitionWithSeparator; -var Alternation = /** @class */ (function (_super) { - __extends$4(Alternation, _super); - function Alternation(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - _this.ignoreAmbiguities = false; - _this.hasPredicates = false; - (0, assign_1$2.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - return _this; - } - Object.defineProperty(Alternation.prototype, "definition", { - get: function () { - return this._definition; - }, - set: function (value) { - this._definition = value; - }, - enumerable: false, - configurable: true - }); - return Alternation; -}(AbstractProduction)); -model$1.Alternation = Alternation; -var Terminal = /** @class */ (function () { - function Terminal(options) { - this.idx = 1; - (0, assign_1$2.default)(this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; })); - } - Terminal.prototype.accept = function (visitor) { - visitor.visit(this); - }; - return Terminal; -}()); -model$1.Terminal = Terminal; -function serializeGrammar(topRules) { - return (0, map_1$3.default)(topRules, serializeProduction); -} -model$1.serializeGrammar = serializeGrammar; -function serializeProduction(node) { - function convertDefinition(definition) { - return (0, map_1$3.default)(definition, serializeProduction); - } - /* istanbul ignore else */ - if (node instanceof NonTerminal) { - var serializedNonTerminal = { - type: "NonTerminal", - name: node.nonTerminalName, - idx: node.idx - }; - if ((0, isString_1.default)(node.label)) { - serializedNonTerminal.label = node.label; - } - return serializedNonTerminal; - } - else if (node instanceof Alternative) { - return { - type: "Alternative", - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Option) { - return { - type: "Option", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof RepetitionMandatory) { - return { - type: "RepetitionMandatory", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof RepetitionMandatoryWithSeparator) { - return { - type: "RepetitionMandatoryWithSeparator", - idx: node.idx, - separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof RepetitionWithSeparator) { - return { - type: "RepetitionWithSeparator", - idx: node.idx, - separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Repetition) { - return { - type: "Repetition", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Alternation) { - return { - type: "Alternation", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Terminal) { - var serializedTerminal = { - type: "Terminal", - name: node.terminalType.name, - label: tokenLabel(node.terminalType), - idx: node.idx - }; - if ((0, isString_1.default)(node.label)) { - serializedTerminal.terminalLabel = node.label; - } - var pattern = node.terminalType.PATTERN; - if (node.terminalType.PATTERN) { - serializedTerminal.pattern = (0, isRegExp_1.default)(pattern) - ? pattern.source - : pattern; - } - return serializedTerminal; - } - else if (node instanceof Rule) { - return { - type: "Rule", - name: node.name, - orgText: node.orgText, - definition: convertDefinition(node.definition) - }; - } - else { - throw Error("non exhaustive match"); - } -} -model$1.serializeProduction = serializeProduction; + case ClassComponent: + // Capture and retry + var errorInfo = value; + var ctor = workInProgress.type; + var instance = workInProgress.stateNode; -var visitor = {}; + if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) { + workInProgress.flags |= ShouldCapture; -Object.defineProperty(visitor, "__esModule", { value: true }); -visitor.GAstVisitor = void 0; -var model_1$2 = model$1; -var GAstVisitor = /** @class */ (function () { - function GAstVisitor() { - } - GAstVisitor.prototype.visit = function (node) { - var nodeAny = node; - switch (nodeAny.constructor) { - case model_1$2.NonTerminal: - return this.visitNonTerminal(nodeAny); - case model_1$2.Alternative: - return this.visitAlternative(nodeAny); - case model_1$2.Option: - return this.visitOption(nodeAny); - case model_1$2.RepetitionMandatory: - return this.visitRepetitionMandatory(nodeAny); - case model_1$2.RepetitionMandatoryWithSeparator: - return this.visitRepetitionMandatoryWithSeparator(nodeAny); - case model_1$2.RepetitionWithSeparator: - return this.visitRepetitionWithSeparator(nodeAny); - case model_1$2.Repetition: - return this.visitRepetition(nodeAny); - case model_1$2.Alternation: - return this.visitAlternation(nodeAny); - case model_1$2.Terminal: - return this.visitTerminal(nodeAny); - case model_1$2.Rule: - return this.visitRule(nodeAny); - /* istanbul ignore next */ - default: - throw Error("non exhaustive match"); - } - }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitNonTerminal = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitAlternative = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitOption = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRepetition = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRepetitionMandatory = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitAlternation = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitTerminal = function (node) { }; - /* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */ - GAstVisitor.prototype.visitRule = function (node) { }; - return GAstVisitor; -}()); -visitor.GAstVisitor = GAstVisitor; + var _lane = pickArbitraryLane(rootRenderLanes); -var helpers = {}; + workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state -var baseEach$4 = _baseEach; + var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane); -/** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ -function baseSome$1(collection, predicate) { - var result; + enqueueCapturedUpdate(workInProgress, _update); + return; + } - baseEach$4(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; -} + break; + } -var _baseSome = baseSome$1; + workInProgress = workInProgress.return; + } while (workInProgress !== null); + } -var arraySome = _arraySome, - baseIteratee$7 = _baseIteratee, - baseSome = _baseSome, - isArray$8 = isArray_1$1, - isIterateeCall$2 = _isIterateeCall; + function getSuspendedCache() { + { + return null; + } // This function is called when a Suspense boundary suspends. It returns the + } -/** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ -function some(collection, predicate, guard) { - var func = isArray$8(collection) ? arraySome : baseSome; - if (guard && isIterateeCall$2(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, baseIteratee$7(predicate)); -} + function markUpdate(workInProgress) { + // Tag the fiber with an update effect. This turns a Placement into + // a PlacementAndUpdate. + workInProgress.flags |= Update; + } -var some_1$2 = some; + function markRef(workInProgress) { + workInProgress.flags |= Ref; -/** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ + { + workInProgress.flags |= RefStatic; + } + } -function arrayEvery$1(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; + function hadNoMutationsEffects(current, completedWork) { + var didBailout = current !== null && current.child === completedWork.child; - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; -} + if (didBailout) { + return true; + } -var _arrayEvery = arrayEvery$1; + if ((completedWork.flags & ChildDeletion) !== NoFlags) { + return false; + } // TODO: If we move the `hadNoMutationsEffects` call after `bubbleProperties` + // then we only have to check the `completedWork.subtreeFlags`. -var baseEach$3 = _baseEach; -/** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ -function baseEvery$1(collection, predicate) { - var result = true; - baseEach$3(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; -} + var child = completedWork.child; -var _baseEvery = baseEvery$1; + while (child !== null) { + if ((child.flags & MutationMask) !== NoFlags || (child.subtreeFlags & MutationMask) !== NoFlags) { + return false; + } -var arrayEvery = _arrayEvery, - baseEvery = _baseEvery, - baseIteratee$6 = _baseIteratee, - isArray$7 = isArray_1$1, - isIterateeCall$1 = _isIterateeCall; + child = child.sibling; + } -/** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false - */ -function every(collection, predicate, guard) { - var func = isArray$7(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall$1(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, baseIteratee$6(predicate)); -} + return true; + } -var every_1$1 = every; + var appendAllChildren; + var updateHostContainer; + var updateHostComponent; + var updateHostText; -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ + if (supportsMutation) { + // Mutation mode + appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { + // We only have the top Fiber that was created but we need recurse down its + // children to find all the terminal nodes. + var node = workInProgress.child; -function baseFindIndex$3(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); + while (node !== null) { + if (node.tag === HostComponent || node.tag === HostText) { + appendInitialChild(parent, node.stateNode); + } else if (node.tag === HostPortal) ; else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} + if (node === workInProgress) { + return; + } -var _baseFindIndex = baseFindIndex$3; + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress) { + return; + } -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ + node = node.return; + } -function baseIsNaN$2(value) { - return value !== value; -} + node.sibling.return = node.return; + node = node.sibling; + } + }; -var _baseIsNaN = baseIsNaN$2; + updateHostContainer = function (current, workInProgress) {// Noop + }; -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ + updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) { + // If we have an alternate, that means this is an update and we need to + // schedule a side-effect to do the updates. + var oldProps = current.memoizedProps; -function strictIndexOf$1(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; + if (oldProps === newProps) { + // In mutation mode, this is sufficient for a bailout because + // we won't touch this node even if children changed. + return; + } // If we get updated because one of our children updated, we don't + // have newProps so we'll have to reuse them. + // TODO: Split the update API as separate for the props vs. children. + // Even better would be if children weren't special cased at all tho. - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} -var _strictIndexOf = strictIndexOf$1; + var instance = workInProgress.stateNode; + var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host + // component is hitting the resume path. Figure out why. Possibly + // related to `hidden`. -var baseFindIndex$2 = _baseFindIndex, - baseIsNaN$1 = _baseIsNaN, - strictIndexOf = _strictIndexOf; + var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component. -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf$4(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex$2(array, baseIsNaN$1, fromIndex); -} + workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there + // is a new ref we mark this as an update. All the work is done in commitWork. -var _baseIndexOf = baseIndexOf$4; + if (updatePayload) { + markUpdate(workInProgress); + } + }; -var baseIndexOf$3 = _baseIndexOf, - isArrayLike$4 = isArrayLike_1, - isString = isString_1$1, - toInteger$3 = toInteger_1, - values = values_1$1; + updateHostText = function (current, workInProgress, oldText, newText) { + // If the text differs, mark it as an update. All the work in done in commitWork. + if (oldText !== newText) { + markUpdate(workInProgress); + } + }; + } else if (supportsPersistence) { + // Persistent host tree mode + appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { + // We only have the top Fiber that was created but we need recurse down its + // children to find all the terminal nodes. + var node = workInProgress.child; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax$4 = Math.max; + while (node !== null) { + // eslint-disable-next-line no-labels + if (node.tag === HostComponent) { + var instance = node.stateNode; -/** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ -function includes(collection, value, fromIndex, guard) { - collection = isArrayLike$4(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger$3(fromIndex) : 0; + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. + var props = node.memoizedProps; + var type = node.type; + instance = cloneHiddenInstance(instance, type, props, node); + } - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax$4(length + fromIndex, 0); - } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf$3(collection, value, fromIndex) > -1); -} + appendInitialChild(parent, instance); + } else if (node.tag === HostText) { + var _instance = node.stateNode; -var includes_1$2 = includes; + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. + var text = node.memoizedProps; + _instance = cloneHiddenTextInstance(_instance, text, node); + } -var __importDefault$8 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(helpers, "__esModule", { value: true }); -helpers.getProductionDslName = helpers.isBranchingProd = helpers.isOptionalProd = helpers.isSequenceProd = void 0; -var some_1$1 = __importDefault$8(some_1$2); -var every_1 = __importDefault$8(every_1$1); -var includes_1$1 = __importDefault$8(includes_1$2); -var model_1$1 = model$1; -function isSequenceProd(prod) { - return (prod instanceof model_1$1.Alternative || - prod instanceof model_1$1.Option || - prod instanceof model_1$1.Repetition || - prod instanceof model_1$1.RepetitionMandatory || - prod instanceof model_1$1.RepetitionMandatoryWithSeparator || - prod instanceof model_1$1.RepetitionWithSeparator || - prod instanceof model_1$1.Terminal || - prod instanceof model_1$1.Rule); -} -helpers.isSequenceProd = isSequenceProd; -function isOptionalProd(prod, alreadyVisited) { - if (alreadyVisited === void 0) { alreadyVisited = []; } - var isDirectlyOptional = prod instanceof model_1$1.Option || - prod instanceof model_1$1.Repetition || - prod instanceof model_1$1.RepetitionWithSeparator; - if (isDirectlyOptional) { - return true; - } - // note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another - // empty optional top rule - // may be indirectly optional ((A?B?C?) | (D?E?F?)) - if (prod instanceof model_1$1.Alternation) { - // for OR its enough for just one of the alternatives to be optional - return (0, some_1$1.default)(prod.definition, function (subProd) { - return isOptionalProd(subProd, alreadyVisited); - }); - } - else if (prod instanceof model_1$1.NonTerminal && (0, includes_1$1.default)(alreadyVisited, prod)) { - // avoiding stack overflow due to infinite recursion - return false; - } - else if (prod instanceof model_1$1.AbstractProduction) { - if (prod instanceof model_1$1.NonTerminal) { - alreadyVisited.push(prod); - } - return (0, every_1.default)(prod.definition, function (subProd) { - return isOptionalProd(subProd, alreadyVisited); - }); - } - else { - return false; - } -} -helpers.isOptionalProd = isOptionalProd; -function isBranchingProd(prod) { - return prod instanceof model_1$1.Alternation; -} -helpers.isBranchingProd = isBranchingProd; -function getProductionDslName(prod) { - /* istanbul ignore else */ - if (prod instanceof model_1$1.NonTerminal) { - return "SUBRULE"; - } - else if (prod instanceof model_1$1.Option) { - return "OPTION"; - } - else if (prod instanceof model_1$1.Alternation) { - return "OR"; - } - else if (prod instanceof model_1$1.RepetitionMandatory) { - return "AT_LEAST_ONE"; - } - else if (prod instanceof model_1$1.RepetitionMandatoryWithSeparator) { - return "AT_LEAST_ONE_SEP"; - } - else if (prod instanceof model_1$1.RepetitionWithSeparator) { - return "MANY_SEP"; - } - else if (prod instanceof model_1$1.Repetition) { - return "MANY"; - } - else if (prod instanceof model_1$1.Terminal) { - return "CONSUME"; - } - else { - throw Error("non exhaustive match"); - } -} -helpers.getProductionDslName = getProductionDslName; - -(function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isSequenceProd = exports.isBranchingProd = exports.isOptionalProd = exports.getProductionDslName = exports.GAstVisitor = exports.serializeProduction = exports.serializeGrammar = exports.Alternative = exports.Alternation = exports.RepetitionWithSeparator = exports.RepetitionMandatoryWithSeparator = exports.RepetitionMandatory = exports.Repetition = exports.Option = exports.NonTerminal = exports.Terminal = exports.Rule = void 0; - var model_1 = model$1; - Object.defineProperty(exports, "Rule", { enumerable: true, get: function () { return model_1.Rule; } }); - Object.defineProperty(exports, "Terminal", { enumerable: true, get: function () { return model_1.Terminal; } }); - Object.defineProperty(exports, "NonTerminal", { enumerable: true, get: function () { return model_1.NonTerminal; } }); - Object.defineProperty(exports, "Option", { enumerable: true, get: function () { return model_1.Option; } }); - Object.defineProperty(exports, "Repetition", { enumerable: true, get: function () { return model_1.Repetition; } }); - Object.defineProperty(exports, "RepetitionMandatory", { enumerable: true, get: function () { return model_1.RepetitionMandatory; } }); - Object.defineProperty(exports, "RepetitionMandatoryWithSeparator", { enumerable: true, get: function () { return model_1.RepetitionMandatoryWithSeparator; } }); - Object.defineProperty(exports, "RepetitionWithSeparator", { enumerable: true, get: function () { return model_1.RepetitionWithSeparator; } }); - Object.defineProperty(exports, "Alternation", { enumerable: true, get: function () { return model_1.Alternation; } }); - Object.defineProperty(exports, "Alternative", { enumerable: true, get: function () { return model_1.Alternative; } }); - Object.defineProperty(exports, "serializeGrammar", { enumerable: true, get: function () { return model_1.serializeGrammar; } }); - Object.defineProperty(exports, "serializeProduction", { enumerable: true, get: function () { return model_1.serializeProduction; } }); - var visitor_1 = visitor; - Object.defineProperty(exports, "GAstVisitor", { enumerable: true, get: function () { return visitor_1.GAstVisitor; } }); - var helpers_1 = helpers; - Object.defineProperty(exports, "getProductionDslName", { enumerable: true, get: function () { return helpers_1.getProductionDslName; } }); - Object.defineProperty(exports, "isOptionalProd", { enumerable: true, get: function () { return helpers_1.isOptionalProd; } }); - Object.defineProperty(exports, "isBranchingProd", { enumerable: true, get: function () { return helpers_1.isBranchingProd; } }); - Object.defineProperty(exports, "isSequenceProd", { enumerable: true, get: function () { return helpers_1.isSequenceProd; } }); - -} (api$1)); - -var __importDefault$7 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(rest, "__esModule", { value: true }); -rest.RestWalker = void 0; -var drop_1$1 = __importDefault$7(drop_1$2); -var forEach_1$2 = __importDefault$7(forEach_1$4); -var gast_1$4 = api$1; -/** - * A Grammar Walker that computes the "remaining" grammar "after" a productions in the grammar. - */ -var RestWalker = /** @class */ (function () { - function RestWalker() { - } - RestWalker.prototype.walk = function (prod, prevRest) { - var _this = this; - if (prevRest === void 0) { prevRest = []; } - (0, forEach_1$2.default)(prod.definition, function (subProd, index) { - var currRest = (0, drop_1$1.default)(prod.definition, index + 1); - /* istanbul ignore else */ - if (subProd instanceof gast_1$4.NonTerminal) { - _this.walkProdRef(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Terminal) { - _this.walkTerminal(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Alternative) { - _this.walkFlat(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Option) { - _this.walkOption(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.RepetitionMandatory) { - _this.walkAtLeastOne(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.RepetitionMandatoryWithSeparator) { - _this.walkAtLeastOneSep(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.RepetitionWithSeparator) { - _this.walkManySep(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Repetition) { - _this.walkMany(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_1$4.Alternation) { - _this.walkOr(subProd, currRest, prevRest); - } - else { - throw Error("non exhaustive match"); - } - }); - }; - RestWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { }; - RestWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { }; - RestWalker.prototype.walkFlat = function (flatProd, currRest, prevRest) { - // ABCDEF => after the D the rest is EF - var fullOrRest = currRest.concat(prevRest); - this.walk(flatProd, fullOrRest); - }; - RestWalker.prototype.walkOption = function (optionProd, currRest, prevRest) { - // ABC(DE)?F => after the (DE)? the rest is F - var fullOrRest = currRest.concat(prevRest); - this.walk(optionProd, fullOrRest); - }; - RestWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { - // ABC(DE)+F => after the (DE)+ the rest is (DE)?F - var fullAtLeastOneRest = [ - new gast_1$4.Option({ definition: atLeastOneProd.definition }) - ].concat(currRest, prevRest); - this.walk(atLeastOneProd, fullAtLeastOneRest); - }; - RestWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) { - // ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F - var fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest); - this.walk(atLeastOneSepProd, fullAtLeastOneSepRest); - }; - RestWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { - // ABC(DE)*F => after the (DE)* the rest is (DE)?F - var fullManyRest = [ - new gast_1$4.Option({ definition: manyProd.definition }) - ].concat(currRest, prevRest); - this.walk(manyProd, fullManyRest); - }; - RestWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { - // ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F - var fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest); - this.walk(manySepProd, fullManySepRest); - }; - RestWalker.prototype.walkOr = function (orProd, currRest, prevRest) { - var _this = this; - // ABC(D|E|F)G => when finding the (D|E|F) the rest is G - var fullOrRest = currRest.concat(prevRest); - // walk all different alternatives - (0, forEach_1$2.default)(orProd.definition, function (alt) { - // wrapping each alternative in a single definition wrapper - // to avoid errors in computing the rest of that alternative in the invocation to computeInProdFollows - // (otherwise for OR([alt1,alt2]) alt2 will be considered in 'rest' of alt1 - var prodWrapper = new gast_1$4.Alternative({ definition: [alt] }); - _this.walk(prodWrapper, fullOrRest); - }); - }; - return RestWalker; -}()); -rest.RestWalker = RestWalker; -function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) { - var repSepRest = [ - new gast_1$4.Option({ - definition: [ - new gast_1$4.Terminal({ terminalType: repSepProd.separator }) - ].concat(repSepProd.definition) - }) - ]; - var fullRepSepRest = repSepRest.concat(currRest, prevRest); - return fullRepSepRest; -} + appendInitialChild(parent, _instance); + } else if (node.tag === HostPortal) ; else if (node.tag === OffscreenComponent && node.memoizedState !== null) { + // The children in this boundary are hidden. Toggle their visibility + // before appending. + var child = node.child; -var first$2 = {}; + if (child !== null) { + child.return = node; + } -var Symbol$3 = _Symbol, - isArguments$2 = isArguments_1, - isArray$6 = isArray_1$1; + { + appendAllChildren(parent, node, true, true); + } + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } // $FlowFixMe This is correct but Flow is confused by the labeled break. -/** Built-in value references. */ -var spreadableSymbol$2 = Symbol$3 ? Symbol$3.isConcatSpreadable : undefined; -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable$3(value) { - return isArray$6(value) || isArguments$2(value) || - !!(spreadableSymbol$2 && value && value[spreadableSymbol$2]); -} + node = node; -var _isFlattenable = isFlattenable$3; + if (node === workInProgress) { + return; + } -var arrayPush$2 = _arrayPush, - isFlattenable$2 = _isFlattenable; + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress) { + return; + } -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten$5(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; + node = node.return; + } - predicate || (predicate = isFlattenable$2); - result || (result = []); + node.sibling.return = node.return; + node = node.sibling; + } + }; // An unfortunate fork of appendAllChildren because we have two different parent types. - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten$5(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush$2(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; -} -var _baseFlatten = baseFlatten$5; + var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) { + // We only have the top Fiber that was created but we need recurse down its + // children to find all the terminal nodes. + var node = workInProgress.child; -var baseFlatten$4 = _baseFlatten; + while (node !== null) { + // eslint-disable-next-line no-labels + if (node.tag === HostComponent) { + var instance = node.stateNode; -/** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ -function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten$4(array, 1) : []; -} + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. + var props = node.memoizedProps; + var type = node.type; + instance = cloneHiddenInstance(instance, type, props, node); + } -var flatten_1$3 = flatten; + appendChildToContainerChildSet(containerChildSet, instance); + } else if (node.tag === HostText) { + var _instance2 = node.stateNode; -var baseIndexOf$2 = _baseIndexOf; + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. + var text = node.memoizedProps; + _instance2 = cloneHiddenTextInstance(_instance2, text, node); + } -/** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludes$3(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf$2(array, value, 0) > -1; -} + appendChildToContainerChildSet(containerChildSet, _instance2); + } else if (node.tag === HostPortal) ; else if (node.tag === OffscreenComponent && node.memoizedState !== null) { + // The children in this boundary are hidden. Toggle their visibility + // before appending. + var child = node.child; -var _arrayIncludes = arrayIncludes$3; + if (child !== null) { + child.return = node; + } -/** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ + { + appendAllChildrenToContainer(containerChildSet, node, true, true); + } + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } // $FlowFixMe This is correct but Flow is confused by the labeled break. -function arrayIncludesWith$3(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; -} + node = node; -var _arrayIncludesWith = arrayIncludesWith$3; + if (node === workInProgress) { + return; + } -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress) { + return; + } -function noop$1() { - // No operation performed. -} + node = node.return; + } -var noop_1 = noop$1; + node.sibling.return = node.return; + node = node.sibling; + } + }; -var Set$1 = _Set, - noop = noop_1, - setToArray$1 = _setToArray; + updateHostContainer = function (current, workInProgress) { + var portalOrRoot = workInProgress.stateNode; + var childrenUnchanged = hadNoMutationsEffects(current, workInProgress); -/** Used as references for various `Number` constants. */ -var INFINITY$2 = 1 / 0; + if (childrenUnchanged) ; else { + var container = portalOrRoot.containerInfo; + var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set. -/** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ -var createSet$1 = !(Set$1 && (1 / setToArray$1(new Set$1([,-0]))[1]) == INFINITY$2) ? noop : function(values) { - return new Set$1(values); -}; + appendAllChildrenToContainer(newChildSet, workInProgress, false, false); + portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container. -var _createSet = createSet$1; + markUpdate(workInProgress); + finalizeContainerChildren(container, newChildSet); + } + }; -var SetCache$2 = _SetCache, - arrayIncludes$2 = _arrayIncludes, - arrayIncludesWith$2 = _arrayIncludesWith, - cacheHas$2 = _cacheHas, - createSet = _createSet, - setToArray = _setToArray; + updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) { + var currentInstance = current.stateNode; + var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates. + // This guarantees that we can reuse all of them. -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE$2 = 200; + var childrenUnchanged = hadNoMutationsEffects(current, workInProgress); -/** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ -function baseUniq$1(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes$2, - length = array.length, - isCommon = true, - result = [], - seen = result; + if (childrenUnchanged && oldProps === newProps) { + // No changes, just reuse the existing instance. + // Note that this might release a previous clone. + workInProgress.stateNode = currentInstance; + return; + } - if (comparator) { - isCommon = false; - includes = arrayIncludesWith$2; - } - else if (length >= LARGE_ARRAY_SIZE$2) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas$2; - seen = new SetCache$2; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + var recyclableInstance = workInProgress.stateNode; + var currentHostContext = getHostContext(); + var updatePayload = null; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; -} + if (oldProps !== newProps) { + updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext); + } -var _baseUniq = baseUniq$1; + if (childrenUnchanged && updatePayload === null) { + // No changes, just reuse the existing instance. + // Note that this might release a previous clone. + workInProgress.stateNode = currentInstance; + return; + } -var baseUniq = _baseUniq; + var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance); -/** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ -function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; -} + if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) { + markUpdate(workInProgress); + } -var uniq_1$2 = uniq; + workInProgress.stateNode = newInstance; -var __importDefault$6 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(first$2, "__esModule", { value: true }); -first$2.firstForTerminal = first$2.firstForBranching = first$2.firstForSequence = first$2.first = void 0; -var flatten_1$2 = __importDefault$6(flatten_1$3); -var uniq_1$1 = __importDefault$6(uniq_1$2); -var map_1$2 = __importDefault$6(map_1$4); -var gast_1$3 = api$1; -var gast_2 = api$1; -function first$1(prod) { - /* istanbul ignore else */ - if (prod instanceof gast_1$3.NonTerminal) { - // this could in theory cause infinite loops if - // (1) prod A refs prod B. - // (2) prod B refs prod A - // (3) AB can match the empty set - // in other words a cycle where everything is optional so the first will keep - // looking ahead for the next optional part and will never exit - // currently there is no safeguard for this unique edge case because - // (1) not sure a grammar in which this can happen is useful for anything (productive) - return first$1(prod.referencedRule); - } - else if (prod instanceof gast_1$3.Terminal) { - return firstForTerminal(prod); - } - else if ((0, gast_2.isSequenceProd)(prod)) { - return firstForSequence(prod); - } - else if ((0, gast_2.isBranchingProd)(prod)) { - return firstForBranching(prod); - } - else { - throw Error("non exhaustive match"); - } -} -first$2.first = first$1; -function firstForSequence(prod) { - var firstSet = []; - var seq = prod.definition; - var nextSubProdIdx = 0; - var hasInnerProdsRemaining = seq.length > nextSubProdIdx; - var currSubProd; - // so we enter the loop at least once (if the definition is not empty - var isLastInnerProdOptional = true; - // scan a sequence until it's end or until we have found a NONE optional production in it - while (hasInnerProdsRemaining && isLastInnerProdOptional) { - currSubProd = seq[nextSubProdIdx]; - isLastInnerProdOptional = (0, gast_2.isOptionalProd)(currSubProd); - firstSet = firstSet.concat(first$1(currSubProd)); - nextSubProdIdx = nextSubProdIdx + 1; - hasInnerProdsRemaining = seq.length > nextSubProdIdx; - } - return (0, uniq_1$1.default)(firstSet); -} -first$2.firstForSequence = firstForSequence; -function firstForBranching(prod) { - var allAlternativesFirsts = (0, map_1$2.default)(prod.definition, function (innerProd) { - return first$1(innerProd); - }); - return (0, uniq_1$1.default)((0, flatten_1$2.default)(allAlternativesFirsts)); -} -first$2.firstForBranching = firstForBranching; -function firstForTerminal(terminal) { - return [terminal.terminalType]; -} -first$2.firstForTerminal = firstForTerminal; + if (childrenUnchanged) { + // If there are no other effects in this tree, we need to flag this node as having one. + // Even though we're not going to use it for anything. + // Otherwise parents won't know that there are new children to propagate upwards. + markUpdate(workInProgress); + } else { + // If children might have changed, we have to add them all to the set. + appendAllChildren(newInstance, workInProgress, false, false); + } + }; -var constants = {}; + updateHostText = function (current, workInProgress, oldText, newText) { + if (oldText !== newText) { + // If the text content differs, we'll create a new text instance for it. + var rootContainerInstance = getRootHostContainer(); + var currentHostContext = getHostContext(); + workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress); // We'll have to mark it as having an effect, even though we won't use the effect for anything. + // This lets the parents know that at least one of their children has changed. -Object.defineProperty(constants, "__esModule", { value: true }); -constants.IN = void 0; -// TODO: can this be removed? where is it used? -constants.IN = "_~IN~_"; + markUpdate(workInProgress); + } else { + workInProgress.stateNode = current.stateNode; + } + }; + } else { + // No host operations + updateHostContainer = function (current, workInProgress) {// Noop + }; -var __extends$3 = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$5 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(follow, "__esModule", { value: true }); -follow.buildInProdFollowPrefix = follow.buildBetweenProdsFollowPrefix = follow.computeAllProdsFollows = follow.ResyncFollowsWalker = void 0; -var rest_1$1 = rest; -var first_1$2 = first$2; -var forEach_1$1 = __importDefault$5(forEach_1$4); -var assign_1$1 = __importDefault$5(assign_1$3); -var constants_1 = constants; -var gast_1$2 = api$1; -// This ResyncFollowsWalker computes all of the follows required for RESYNC -// (skipping reference production). -var ResyncFollowsWalker = /** @class */ (function (_super) { - __extends$3(ResyncFollowsWalker, _super); - function ResyncFollowsWalker(topProd) { - var _this = _super.call(this) || this; - _this.topProd = topProd; - _this.follows = {}; - return _this; - } - ResyncFollowsWalker.prototype.startWalking = function () { - this.walk(this.topProd); - return this.follows; - }; - ResyncFollowsWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { - // do nothing! just like in the public sector after 13:00 - }; - ResyncFollowsWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { - var followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) + - this.topProd.name; - var fullRest = currRest.concat(prevRest); - var restProd = new gast_1$2.Alternative({ definition: fullRest }); - var t_in_topProd_follows = (0, first_1$2.first)(restProd); - this.follows[followName] = t_in_topProd_follows; - }; - return ResyncFollowsWalker; -}(rest_1$1.RestWalker)); -follow.ResyncFollowsWalker = ResyncFollowsWalker; -function computeAllProdsFollows(topProductions) { - var reSyncFollows = {}; - (0, forEach_1$1.default)(topProductions, function (topProd) { - var currRefsFollow = new ResyncFollowsWalker(topProd).startWalking(); - (0, assign_1$1.default)(reSyncFollows, currRefsFollow); - }); - return reSyncFollows; -} -follow.computeAllProdsFollows = computeAllProdsFollows; -function buildBetweenProdsFollowPrefix(inner, occurenceInParent) { - return inner.name + occurenceInParent + constants_1.IN; -} -follow.buildBetweenProdsFollowPrefix = buildBetweenProdsFollowPrefix; -function buildInProdFollowPrefix(terminal) { - var terminalName = terminal.terminalType.name; - return terminalName + terminal.idx + constants_1.IN; -} -follow.buildInProdFollowPrefix = buildInProdFollowPrefix; + updateHostComponent = function (current, workInProgress, type, newProps, rootContainerInstance) {// Noop + }; -var tokens_public = {}; + updateHostText = function (current, workInProgress, oldText, newText) {// Noop + }; + } -/** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ + function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { + if (getIsHydrating()) { + // If we're hydrating, we should consume as many items as we can + // so we don't leave any behind. + return; + } -function isUndefined(value) { - return value === undefined; -} + switch (renderState.tailMode) { + case 'hidden': + { + // Any insertions at the end of the tail list after this point + // should be invisible. If there are already mounted boundaries + // anything before them are not considered for collapsing. + // Therefore we need to go through the whole tail to find if + // there are any. + var tailNode = renderState.tail; + var lastTailNode = null; -var isUndefined_1$1 = isUndefined; + while (tailNode !== null) { + if (tailNode.alternate !== null) { + lastTailNode = tailNode; + } -var lexer_public = {}; + tailNode = tailNode.sibling; + } // Next we're simply going to delete all insertions after the + // last rendered item. -var lexer = {}; -var regexpToAst = {exports: {}}; + if (lastTailNode === null) { + // All remaining items in the tail are insertions. + renderState.tail = null; + } else { + // Detach the insertion after the last node that was already + // inserted. + lastTailNode.sibling = null; + } -(function (module) { -(function(root, factory) { - // istanbul ignore next - if (module.exports) { - module.exports = factory(); - } else { - // istanbul ignore next - root.regexpToAst = factory(); - } - })( - typeof self !== "undefined" - ? // istanbul ignore next - self - : commonjsGlobal, - function() { - // references - // https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983 - // https://www.ecma-international.org/ecma-262/8.0/index.html#prod-Pattern - function RegExpParser() {} - - RegExpParser.prototype.saveState = function() { - return { - idx: this.idx, - input: this.input, - groupIdx: this.groupIdx - } - }; + break; + } - RegExpParser.prototype.restoreState = function(newState) { - this.idx = newState.idx; - this.input = newState.input; - this.groupIdx = newState.groupIdx; - }; + case 'collapsed': + { + // Any insertions at the end of the tail list after this point + // should be invisible. If there are already mounted boundaries + // anything before them are not considered for collapsing. + // Therefore we need to go through the whole tail to find if + // there are any. + var _tailNode = renderState.tail; + var _lastTailNode = null; - RegExpParser.prototype.pattern = function(input) { - // parser state - this.idx = 0; - this.input = input; - this.groupIdx = 0; - - this.consumeChar("/"); - var value = this.disjunction(); - this.consumeChar("/"); - - var flags = { - type: "Flags", - loc: { begin: this.idx, end: input.length }, - global: false, - ignoreCase: false, - multiLine: false, - unicode: false, - sticky: false - }; + while (_tailNode !== null) { + if (_tailNode.alternate !== null) { + _lastTailNode = _tailNode; + } - while (this.isRegExpFlag()) { - switch (this.popChar()) { - case "g": - addFlag(flags, "global"); - break - case "i": - addFlag(flags, "ignoreCase"); - break - case "m": - addFlag(flags, "multiLine"); - break - case "u": - addFlag(flags, "unicode"); - break - case "y": - addFlag(flags, "sticky"); - break - } - } + _tailNode = _tailNode.sibling; + } // Next we're simply going to delete all insertions after the + // last rendered item. - if (this.idx !== this.input.length) { - throw Error( - "Redundant input: " + this.input.substring(this.idx) - ) - } - return { - type: "Pattern", - flags: flags, - value: value, - loc: this.loc(0) - } - }; - RegExpParser.prototype.disjunction = function() { - var alts = []; - var begin = this.idx; + if (_lastTailNode === null) { + // All remaining items in the tail are insertions. + if (!hasRenderedATailFallback && renderState.tail !== null) { + // We suspended during the head. We want to show at least one + // row at the tail. So we'll keep on and cut off the rest. + renderState.tail.sibling = null; + } else { + renderState.tail = null; + } + } else { + // Detach the insertion after the last node that was already + // inserted. + _lastTailNode.sibling = null; + } - alts.push(this.alternative()); + break; + } + } + } - while (this.peekChar() === "|") { - this.consumeChar("|"); - alts.push(this.alternative()); - } + function bubbleProperties(completedWork) { + var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child; + var newChildLanes = NoLanes; + var subtreeFlags = NoFlags; - return { type: "Disjunction", value: alts, loc: this.loc(begin) } - }; + if (!didBailout) { + // Bubble up the earliest expiration time. + if ( (completedWork.mode & ProfileMode) !== NoMode) { + // In profiling mode, resetChildExpirationTime is also used to reset + // profiler durations. + var actualDuration = completedWork.actualDuration; + var treeBaseDuration = completedWork.selfBaseDuration; + var child = completedWork.child; - RegExpParser.prototype.alternative = function() { - var terms = []; - var begin = this.idx; + while (child !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes)); + subtreeFlags |= child.subtreeFlags; + subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will + // only be updated if work is done on the fiber (i.e. it doesn't bailout). + // When work is done, it should bubble to the parent's actualDuration. If + // the fiber has not been cloned though, (meaning no work was done), then + // this value will reflect the amount of time spent working on a previous + // render. In that case it should not bubble. We determine whether it was + // cloned by comparing the child pointer. - while (this.isTerm()) { - terms.push(this.term()); - } + actualDuration += child.actualDuration; + treeBaseDuration += child.treeBaseDuration; + child = child.sibling; + } - return { type: "Alternative", value: terms, loc: this.loc(begin) } - }; + completedWork.actualDuration = actualDuration; + completedWork.treeBaseDuration = treeBaseDuration; + } else { + var _child = completedWork.child; - RegExpParser.prototype.term = function() { - if (this.isAssertion()) { - return this.assertion() - } else { - return this.atom() - } - }; + while (_child !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes)); + subtreeFlags |= _child.subtreeFlags; + subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code + // smell because it assumes the commit phase is never concurrent with + // the render phase. Will address during refactor to alternate model. - RegExpParser.prototype.assertion = function() { - var begin = this.idx; - switch (this.popChar()) { - case "^": - return { - type: "StartAnchor", - loc: this.loc(begin) - } - case "$": - return { type: "EndAnchor", loc: this.loc(begin) } - // '\b' or '\B' - case "\\": - switch (this.popChar()) { - case "b": - return { - type: "WordBoundary", - loc: this.loc(begin) - } - case "B": - return { - type: "NonWordBoundary", - loc: this.loc(begin) - } - } - // istanbul ignore next - throw Error("Invalid Assertion Escape") - // '(?=' or '(?!' - case "(": - this.consumeChar("?"); - - var type; - switch (this.popChar()) { - case "=": - type = "Lookahead"; - break - case "!": - type = "NegativeLookahead"; - break - } - ASSERT_EXISTS(type); + _child.return = completedWork; + _child = _child.sibling; + } + } - var disjunction = this.disjunction(); + completedWork.subtreeFlags |= subtreeFlags; + } else { + // Bubble up the earliest expiration time. + if ( (completedWork.mode & ProfileMode) !== NoMode) { + // In profiling mode, resetChildExpirationTime is also used to reset + // profiler durations. + var _treeBaseDuration = completedWork.selfBaseDuration; + var _child2 = completedWork.child; - this.consumeChar(")"); + while (_child2 !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, + // so we should bubble those up even during a bailout. All the other + // flags have a lifetime only of a single render + commit, so we should + // ignore them. - return { - type: type, - value: disjunction, - loc: this.loc(begin) - } - } - // istanbul ignore next - ASSERT_NEVER_REACH_HERE(); - }; + subtreeFlags |= _child2.subtreeFlags & StaticMask; + subtreeFlags |= _child2.flags & StaticMask; + _treeBaseDuration += _child2.treeBaseDuration; + _child2 = _child2.sibling; + } - RegExpParser.prototype.quantifier = function(isBacktracking) { - var range; - var begin = this.idx; - switch (this.popChar()) { - case "*": - range = { - atLeast: 0, - atMost: Infinity - }; - break - case "+": - range = { - atLeast: 1, - atMost: Infinity - }; - break - case "?": - range = { - atLeast: 0, - atMost: 1 - }; - break - case "{": - var atLeast = this.integerIncludingZero(); - switch (this.popChar()) { - case "}": - range = { - atLeast: atLeast, - atMost: atLeast - }; - break - case ",": - var atMost; - if (this.isDigit()) { - atMost = this.integerIncludingZero(); - range = { - atLeast: atLeast, - atMost: atMost - }; - } else { - range = { - atLeast: atLeast, - atMost: Infinity - }; - } - this.consumeChar("}"); - break - } - // throwing exceptions from "ASSERT_EXISTS" during backtracking - // causes severe performance degradations - if (isBacktracking === true && range === undefined) { - return undefined - } - ASSERT_EXISTS(range); - break - } + completedWork.treeBaseDuration = _treeBaseDuration; + } else { + var _child3 = completedWork.child; - // throwing exceptions from "ASSERT_EXISTS" during backtracking - // causes severe performance degradations - if (isBacktracking === true && range === undefined) { - return undefined - } + while (_child3 !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, + // so we should bubble those up even during a bailout. All the other + // flags have a lifetime only of a single render + commit, so we should + // ignore them. - ASSERT_EXISTS(range); + subtreeFlags |= _child3.subtreeFlags & StaticMask; + subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code + // smell because it assumes the commit phase is never concurrent with + // the render phase. Will address during refactor to alternate model. - if (this.peekChar(0) === "?") { - this.consumeChar("?"); - range.greedy = false; - } else { - range.greedy = true; - } + _child3.return = completedWork; + _child3 = _child3.sibling; + } + } - range.type = "Quantifier"; - range.loc = this.loc(begin); - return range - }; + completedWork.subtreeFlags |= subtreeFlags; + } - RegExpParser.prototype.atom = function() { - var atom; - var begin = this.idx; - switch (this.peekChar()) { - case ".": - atom = this.dotAll(); - break - case "\\": - atom = this.atomEscape(); - break - case "[": - atom = this.characterClass(); - break - case "(": - atom = this.group(); - break - } + completedWork.childLanes = newChildLanes; + return didBailout; + } - if (atom === undefined && this.isPatternCharacter()) { - atom = this.patternCharacter(); - } + function completeWork(current, workInProgress, renderLanes) { + var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing + // to the current tree provider fiber is just as fast and less error-prone. + // Ideally we would have a special version of the work loop only + // for hydration. - ASSERT_EXISTS(atom); + popTreeContext(workInProgress); - atom.loc = this.loc(begin); + switch (workInProgress.tag) { + case IndeterminateComponent: + case LazyComponent: + case SimpleMemoComponent: + case FunctionComponent: + case ForwardRef: + case Fragment: + case Mode: + case Profiler: + case ContextConsumer: + case MemoComponent: + bubbleProperties(workInProgress); + return null; - if (this.isQuantifier()) { - atom.quantifier = this.quantifier(); - } + case ClassComponent: + { + var Component = workInProgress.type; - return atom - }; + if (isContextProvider(Component)) { + popContext(workInProgress); + } - RegExpParser.prototype.dotAll = function() { - this.consumeChar("."); - return { - type: "Set", - complement: true, - value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")] - } - }; + bubbleProperties(workInProgress); + return null; + } - RegExpParser.prototype.atomEscape = function() { - this.consumeChar("\\"); - - switch (this.peekChar()) { - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - return this.decimalEscapeAtom() - case "d": - case "D": - case "s": - case "S": - case "w": - case "W": - return this.characterClassEscape() - case "f": - case "n": - case "r": - case "t": - case "v": - return this.controlEscapeAtom() - case "c": - return this.controlLetterEscapeAtom() - case "0": - return this.nulCharacterAtom() - case "x": - return this.hexEscapeSequenceAtom() - case "u": - return this.regExpUnicodeEscapeSequenceAtom() - default: - return this.identityEscapeAtom() - } - }; + case HostRoot: + { + var fiberRoot = workInProgress.stateNode; - RegExpParser.prototype.decimalEscapeAtom = function() { - var value = this.positiveInteger(); + popHostContainer(workInProgress); + popTopLevelContextObject(workInProgress); + resetWorkInProgressVersions(); - return { type: "GroupBackReference", value: value } - }; + if (fiberRoot.pendingContext) { + fiberRoot.context = fiberRoot.pendingContext; + fiberRoot.pendingContext = null; + } - RegExpParser.prototype.characterClassEscape = function() { - var set; - var complement = false; - switch (this.popChar()) { - case "d": - set = digitsCharCodes; - break - case "D": - set = digitsCharCodes; - complement = true; - break - case "s": - set = whitespaceCodes; - break - case "S": - set = whitespaceCodes; - complement = true; - break - case "w": - set = wordCharCodes; - break - case "W": - set = wordCharCodes; - complement = true; - break - } + if (current === null || current.child === null) { + // If we hydrated, pop so that we can delete any remaining children + // that weren't hydrated. + var wasHydrated = popHydrationState(workInProgress); - ASSERT_EXISTS(set); + if (wasHydrated) { + // If we hydrated, then we'll need to schedule an update for + // the commit side-effects on the root. + markUpdate(workInProgress); + } else { + if (current !== null) { + var prevState = current.memoizedState; - return { type: "Set", value: set, complement: complement } - }; + if ( // Check if this is a client root + !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error) + (workInProgress.flags & ForceClientRender) !== NoFlags) { + // Schedule an effect to clear this container at the start of the + // next commit. This handles the case of React rendering into a + // container with previous children. It's also safe to do for + // updates too, because current.child would only be null if the + // previous render was null (so the container would already + // be empty). + workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been + // recoverable errors during first hydration attempt. If so, add + // them to a queue so we can log them in the commit phase. - RegExpParser.prototype.controlEscapeAtom = function() { - var escapeCode; - switch (this.popChar()) { - case "f": - escapeCode = cc("\f"); - break - case "n": - escapeCode = cc("\n"); - break - case "r": - escapeCode = cc("\r"); - break - case "t": - escapeCode = cc("\t"); - break - case "v": - escapeCode = cc("\v"); - break + upgradeHydrationErrorsToRecoverable(); + } } - ASSERT_EXISTS(escapeCode); + } + } - return { type: "Character", value: escapeCode } - }; + updateHostContainer(current, workInProgress); + bubbleProperties(workInProgress); + return null; + } - RegExpParser.prototype.controlLetterEscapeAtom = function() { - this.consumeChar("c"); - var letter = this.popChar(); - if (/[a-zA-Z]/.test(letter) === false) { - throw Error("Invalid ") - } + case HostComponent: + { + popHostContext(workInProgress); + var rootContainerInstance = getRootHostContainer(); + var type = workInProgress.type; - var letterCode = letter.toUpperCase().charCodeAt(0) - 64; - return { type: "Character", value: letterCode } - }; + if (current !== null && workInProgress.stateNode != null) { + updateHostComponent(current, workInProgress, type, newProps, rootContainerInstance); - RegExpParser.prototype.nulCharacterAtom = function() { - // TODO implement '[lookahead ∉ DecimalDigit]' - // TODO: for the deprecated octal escape sequence - this.consumeChar("0"); - return { type: "Character", value: cc("\0") } - }; + if (current.ref !== workInProgress.ref) { + markRef(workInProgress); + } + } else { + if (!newProps) { + if (workInProgress.stateNode === null) { + throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); + } // This can happen when we abort work. - RegExpParser.prototype.hexEscapeSequenceAtom = function() { - this.consumeChar("x"); - return this.parseHexDigits(2) - }; - RegExpParser.prototype.regExpUnicodeEscapeSequenceAtom = function() { - this.consumeChar("u"); - return this.parseHexDigits(4) - }; + bubbleProperties(workInProgress); + return null; + } - RegExpParser.prototype.identityEscapeAtom = function() { - // TODO: implement "SourceCharacter but not UnicodeIDContinue" - // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments - var escapedChar = this.popChar(); - return { type: "Character", value: cc(escapedChar) } - }; + var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context + // "stack" as the parent. Then append children as we go in beginWork + // or completeWork depending on whether we want to add them top->down or + // bottom->up. Top->down is faster in IE11. - RegExpParser.prototype.classPatternCharacterAtom = function() { - switch (this.peekChar()) { - // istanbul ignore next - case "\n": - // istanbul ignore next - case "\r": - // istanbul ignore next - case "\u2028": - // istanbul ignore next - case "\u2029": - // istanbul ignore next - case "\\": - // istanbul ignore next - case "]": - throw Error("TBD") - default: - var nextChar = this.popChar(); - return { type: "Character", value: cc(nextChar) } - } - }; + var _wasHydrated = popHydrationState(workInProgress); - RegExpParser.prototype.characterClass = function() { - var set = []; - var complement = false; - this.consumeChar("["); - if (this.peekChar(0) === "^") { - this.consumeChar("^"); - complement = true; + if (_wasHydrated) { + // TODO: Move this and createInstance step into the beginPhase + // to consolidate. + if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) { + // If changes to the hydrated node need to be applied at the + // commit-phase we mark this as such. + markUpdate(workInProgress); } + } else { + var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress); + appendAllChildren(instance, workInProgress, false, false); + workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount. + // (eg DOM renderer supports auto-focus for certain elements). + // Make sure such renderers get scheduled for later work. - while (this.isClassAtom()) { - var from = this.classAtom(); - var isFromSingleChar = from.type === "Character"; - if (isFromSingleChar && this.isRangeDash()) { - this.consumeChar("-"); - var to = this.classAtom(); - var isToSingleChar = to.type === "Character"; - - // a range can only be used when both sides are single characters - if (isToSingleChar) { - if (to.value < from.value) { - throw Error("Range out of order in character class") - } - set.push({ from: from.value, to: to.value }); - } else { - // literal dash - insertToSet(from.value, set); - set.push(cc("-")); - insertToSet(to.value, set); - } - } else { - insertToSet(from.value, set); - } + if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) { + markUpdate(workInProgress); } + } - this.consumeChar("]"); + if (workInProgress.ref !== null) { + // If there is a ref on a host node we need to schedule a callback + markRef(workInProgress); + } + } - return { type: "Set", complement: complement, value: set } - }; + bubbleProperties(workInProgress); + return null; + } - RegExpParser.prototype.classAtom = function() { - switch (this.peekChar()) { - // istanbul ignore next - case "]": - // istanbul ignore next - case "\n": - // istanbul ignore next - case "\r": - // istanbul ignore next - case "\u2028": - // istanbul ignore next - case "\u2029": - throw Error("TBD") - case "\\": - return this.classEscape() - default: - return this.classPatternCharacterAtom() - } - }; + case HostText: + { + var newText = newProps; - RegExpParser.prototype.classEscape = function() { - this.consumeChar("\\"); - switch (this.peekChar()) { - // Matches a backspace. - // (Not to be confused with \b word boundary outside characterClass) - case "b": - this.consumeChar("b"); - return { type: "Character", value: cc("\u0008") } - case "d": - case "D": - case "s": - case "S": - case "w": - case "W": - return this.characterClassEscape() - case "f": - case "n": - case "r": - case "t": - case "v": - return this.controlEscapeAtom() - case "c": - return this.controlLetterEscapeAtom() - case "0": - return this.nulCharacterAtom() - case "x": - return this.hexEscapeSequenceAtom() - case "u": - return this.regExpUnicodeEscapeSequenceAtom() - default: - return this.identityEscapeAtom() - } - }; + if (current && workInProgress.stateNode != null) { + var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need + // to schedule a side-effect to do the updates. - RegExpParser.prototype.group = function() { - var capturing = true; - this.consumeChar("("); - switch (this.peekChar(0)) { - case "?": - this.consumeChar("?"); - this.consumeChar(":"); - capturing = false; - break - default: - this.groupIdx++; - break - } - var value = this.disjunction(); - this.consumeChar(")"); + updateHostText(current, workInProgress, oldText, newText); + } else { + if (typeof newText !== 'string') { + if (workInProgress.stateNode === null) { + throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); + } // This can happen when we abort work. - var groupAst = { - type: "Group", - capturing: capturing, - value: value - }; + } - if (capturing) { - groupAst.idx = this.groupIdx; - } + var _rootContainerInstance = getRootHostContainer(); - return groupAst - }; + var _currentHostContext = getHostContext(); - RegExpParser.prototype.positiveInteger = function() { - var number = this.popChar(); + var _wasHydrated2 = popHydrationState(workInProgress); - // istanbul ignore next - can't ever get here due to previous lookahead checks - // still implementing this error checking in case this ever changes. - if (decimalPatternNoZero.test(number) === false) { - throw Error("Expecting a positive integer") + if (_wasHydrated2) { + if (prepareToHydrateHostTextInstance(workInProgress)) { + markUpdate(workInProgress); } + } else { + workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress); + } + } - while (decimalPattern.test(this.peekChar(0))) { - number += this.popChar(); - } + bubbleProperties(workInProgress); + return null; + } - return parseInt(number, 10) - }; + case SuspenseComponent: + { + popSuspenseContext(workInProgress); + var nextState = workInProgress.memoizedState; - RegExpParser.prototype.integerIncludingZero = function() { - var number = this.popChar(); - if (decimalPattern.test(number) === false) { - throw Error("Expecting an integer") - } + { + if ( hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) { + warnIfUnhydratedTailNodes(workInProgress); + resetHydrationState(); + workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture; + return workInProgress; + } - while (decimalPattern.test(this.peekChar(0))) { - number += this.popChar(); - } + if (nextState !== null && nextState.dehydrated !== null) { + // We might be inside a hydration state the first time we're picking up this + // Suspense boundary, and also after we've reentered it for further hydration. + var _wasHydrated3 = popHydrationState(workInProgress); - return parseInt(number, 10) - }; + if (current === null) { + if (!_wasHydrated3) { + throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.'); + } - RegExpParser.prototype.patternCharacter = function() { - var nextChar = this.popChar(); - switch (nextChar) { - // istanbul ignore next - case "\n": - // istanbul ignore next - case "\r": - // istanbul ignore next - case "\u2028": - // istanbul ignore next - case "\u2029": - // istanbul ignore next - case "^": - // istanbul ignore next - case "$": - // istanbul ignore next - case "\\": - // istanbul ignore next - case ".": - // istanbul ignore next - case "*": - // istanbul ignore next - case "+": - // istanbul ignore next - case "?": - // istanbul ignore next - case "(": - // istanbul ignore next - case ")": - // istanbul ignore next - case "[": - // istanbul ignore next - case "|": - // istanbul ignore next - throw Error("TBD") - default: - return { type: "Character", value: cc(nextChar) } - } - }; - RegExpParser.prototype.isRegExpFlag = function() { - switch (this.peekChar(0)) { - case "g": - case "i": - case "m": - case "u": - case "y": - return true - default: - return false - } - }; + prepareToHydrateHostSuspenseInstance(workInProgress); + bubbleProperties(workInProgress); - RegExpParser.prototype.isRangeDash = function() { - return this.peekChar() === "-" && this.isClassAtom(1) - }; + { + if ((workInProgress.mode & ProfileMode) !== NoMode) { + var isTimedOutSuspense = nextState !== null; - RegExpParser.prototype.isDigit = function() { - return decimalPattern.test(this.peekChar(0)) - }; + if (isTimedOutSuspense) { + // Don't count time spent in a timed out Suspense subtree as part of the base duration. + var primaryChildFragment = workInProgress.child; - RegExpParser.prototype.isClassAtom = function(howMuch) { - if (howMuch === undefined) { - howMuch = 0; - } + if (primaryChildFragment !== null) { + // $FlowFixMe Flow doesn't support type casting in combination with the -= operator + workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration; + } + } + } + } - switch (this.peekChar(howMuch)) { - case "]": - case "\n": - case "\r": - case "\u2028": - case "\u2029": - return false - default: - return true - } - }; + return null; + } else { + // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration + // state since we're now exiting out of it. popHydrationState doesn't do that for us. + resetHydrationState(); - RegExpParser.prototype.isTerm = function() { - return this.isAtom() || this.isAssertion() - }; + if ((workInProgress.flags & DidCapture) === NoFlags) { + // This boundary did not suspend so it's now hydrated and unsuspended. + workInProgress.memoizedState = null; + } // If nothing suspended, we need to schedule an effect to mark this boundary + // as having hydrated so events know that they're free to be invoked. + // It's also a signal to replay events and the suspense callback. + // If something suspended, schedule an effect to attach retry listeners. + // So we might as well always mark this. - RegExpParser.prototype.isAtom = function() { - if (this.isPatternCharacter()) { - return true - } - switch (this.peekChar(0)) { - case ".": - case "\\": // atomEscape - case "[": // characterClass - // TODO: isAtom must be called before isAssertion - disambiguate - case "(": // group - return true - default: - return false - } - }; + workInProgress.flags |= Update; + bubbleProperties(workInProgress); + + { + if ((workInProgress.mode & ProfileMode) !== NoMode) { + var _isTimedOutSuspense = nextState !== null; + + if (_isTimedOutSuspense) { + // Don't count time spent in a timed out Suspense subtree as part of the base duration. + var _primaryChildFragment = workInProgress.child; - RegExpParser.prototype.isAssertion = function() { - switch (this.peekChar(0)) { - case "^": - case "$": - return true - // '\b' or '\B' - case "\\": - switch (this.peekChar(1)) { - case "b": - case "B": - return true - default: - return false + if (_primaryChildFragment !== null) { + // $FlowFixMe Flow doesn't support type casting in combination with the -= operator + workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration; } - // '(?=' or '(?!' - case "(": - return ( - this.peekChar(1) === "?" && - (this.peekChar(2) === "=" || this.peekChar(2) === "!") - ) - default: - return false - } - }; + } + } + } - RegExpParser.prototype.isQuantifier = function() { - var prevState = this.saveState(); - try { - return this.quantifier(true) !== undefined - } catch (e) { - return false - } finally { - this.restoreState(prevState); + return null; } - }; + } // Successfully completed this tree. If this was a forced client render, + // there may have been recoverable errors during first hydration + // attempt. If so, add them to a queue so we can log them in the + // commit phase. - RegExpParser.prototype.isPatternCharacter = function() { - switch (this.peekChar()) { - case "^": - case "$": - case "\\": - case ".": - case "*": - case "+": - case "?": - case "(": - case ")": - case "[": - case "|": - case "/": - case "\n": - case "\r": - case "\u2028": - case "\u2029": - return false - default: - return true - } - }; - RegExpParser.prototype.parseHexDigits = function(howMany) { - var hexString = ""; - for (var i = 0; i < howMany; i++) { - var hexChar = this.popChar(); - if (hexDigitPattern.test(hexChar) === false) { - throw Error("Expecting a HexDecimal digits") - } - hexString += hexChar; - } - var charCode = parseInt(hexString, 16); - return { type: "Character", value: charCode } - }; + upgradeHydrationErrorsToRecoverable(); + } - RegExpParser.prototype.peekChar = function(howMuch) { - if (howMuch === undefined) { - howMuch = 0; - } - return this.input[this.idx + howMuch] - }; + if ((workInProgress.flags & DidCapture) !== NoFlags) { + // Something suspended. Re-render with the fallback children. + workInProgress.lanes = renderLanes; // Do not reset the effect list. - RegExpParser.prototype.popChar = function() { - var nextChar = this.peekChar(0); - this.consumeChar(); - return nextChar - }; + if ( (workInProgress.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress); + } // Don't bubble properties in this case. - RegExpParser.prototype.consumeChar = function(char) { - if (char !== undefined && this.input[this.idx] !== char) { - throw Error( - "Expected: '" + - char + - "' but found: '" + - this.input[this.idx] + - "' at offset: " + - this.idx - ) - } - if (this.idx >= this.input.length) { - throw Error("Unexpected end of input") - } - this.idx++; - }; + return workInProgress; + } + + var nextDidTimeout = nextState !== null; + var prevDidTimeout = false; + + if (current === null) { + popHydrationState(workInProgress); + } else { + var _prevState = current.memoizedState; + prevDidTimeout = _prevState !== null; + } + // an effect to toggle the subtree's visibility. When we switch from + // fallback -> primary, the inner Offscreen fiber schedules this effect + // as part of its normal complete phase. But when we switch from + // primary -> fallback, the inner Offscreen fiber does not have a complete + // phase. So we need to schedule its effect here. + // + // We also use this flag to connect/disconnect the effects, but the same + // logic applies: when re-connecting, the Offscreen fiber's complete + // phase will handle scheduling the effect. It's only when the fallback + // is active that we have to do anything special. - RegExpParser.prototype.loc = function(begin) { - return { begin: begin, end: this.idx } - }; - // consts and utilities - var hexDigitPattern = /[0-9a-fA-F]/; - var decimalPattern = /[0-9]/; - var decimalPatternNoZero = /[1-9]/; + if (nextDidTimeout && !prevDidTimeout) { + var _offscreenFiber = workInProgress.child; + _offscreenFiber.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything + // in the concurrent tree already suspended during this render. + // This is a known bug. - function cc(char) { - return char.charCodeAt(0) - } + if ((workInProgress.mode & ConcurrentMode) !== NoMode) { + // TODO: Move this back to throwException because this is too late + // if this is a large tree which is common for initial loads. We + // don't know if we should restart a render or not until we get + // this marker, and this is too late. + // If this render already had a ping or lower pri updates, + // and this is the first time we know we're going to suspend we + // should be able to immediately restart from within throwException. + var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback); - function insertToSet(item, set) { - if (item.length !== undefined) { - item.forEach(function(subItem) { - set.push(subItem); - }); + if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) { + // If this was in an invisible tree or a new render, then showing + // this boundary is ok. + renderDidSuspend(); } else { - set.push(item); + // Otherwise, we're going to have to hide content so we should + // suspend for longer if possible. + renderDidSuspendDelayIfPossible(); } + } } - function addFlag(flagObj, flagKey) { - if (flagObj[flagKey] === true) { - throw "duplicate flag " + flagKey - } - - flagObj[flagKey] = true; - } + var wakeables = workInProgress.updateQueue; - function ASSERT_EXISTS(obj) { - // istanbul ignore next - if (obj === undefined) { - throw Error("Internal Error - Should never get here!") - } + if (wakeables !== null) { + // Schedule an effect to attach a retry listener to the promise. + // TODO: Move to passive phase + workInProgress.flags |= Update; } - // istanbul ignore next - function ASSERT_NEVER_REACH_HERE() { - throw Error("Internal Error - Should never get here!") - } + bubbleProperties(workInProgress); - var i; - var digitsCharCodes = []; - for (i = cc("0"); i <= cc("9"); i++) { - digitsCharCodes.push(i); - } + { + if ((workInProgress.mode & ProfileMode) !== NoMode) { + if (nextDidTimeout) { + // Don't count time spent in a timed out Suspense subtree as part of the base duration. + var _primaryChildFragment2 = workInProgress.child; - var wordCharCodes = [cc("_")].concat(digitsCharCodes); - for (i = cc("a"); i <= cc("z"); i++) { - wordCharCodes.push(i); + if (_primaryChildFragment2 !== null) { + // $FlowFixMe Flow doesn't support type casting in combination with the -= operator + workInProgress.treeBaseDuration -= _primaryChildFragment2.treeBaseDuration; + } + } + } } - for (i = cc("A"); i <= cc("Z"); i++) { - wordCharCodes.push(i); - } + return null; + } - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes - var whitespaceCodes = [ - cc(" "), - cc("\f"), - cc("\n"), - cc("\r"), - cc("\t"), - cc("\v"), - cc("\t"), - cc("\u00a0"), - cc("\u1680"), - cc("\u2000"), - cc("\u2001"), - cc("\u2002"), - cc("\u2003"), - cc("\u2004"), - cc("\u2005"), - cc("\u2006"), - cc("\u2007"), - cc("\u2008"), - cc("\u2009"), - cc("\u200a"), - cc("\u2028"), - cc("\u2029"), - cc("\u202f"), - cc("\u205f"), - cc("\u3000"), - cc("\ufeff") - ]; - - function BaseRegExpVisitor() {} - - BaseRegExpVisitor.prototype.visitChildren = function(node) { - for (var key in node) { - var child = node[key]; - /* istanbul ignore else */ - if (node.hasOwnProperty(key)) { - if (child.type !== undefined) { - this.visit(child); - } else if (Array.isArray(child)) { - child.forEach(function(subChild) { - this.visit(subChild); - }, this); - } - } - } - }; + case HostPortal: + popHostContainer(workInProgress); + updateHostContainer(current, workInProgress); - BaseRegExpVisitor.prototype.visit = function(node) { - switch (node.type) { - case "Pattern": - this.visitPattern(node); - break - case "Flags": - this.visitFlags(node); - break - case "Disjunction": - this.visitDisjunction(node); - break - case "Alternative": - this.visitAlternative(node); - break - case "StartAnchor": - this.visitStartAnchor(node); - break - case "EndAnchor": - this.visitEndAnchor(node); - break - case "WordBoundary": - this.visitWordBoundary(node); - break - case "NonWordBoundary": - this.visitNonWordBoundary(node); - break - case "Lookahead": - this.visitLookahead(node); - break - case "NegativeLookahead": - this.visitNegativeLookahead(node); - break - case "Character": - this.visitCharacter(node); - break - case "Set": - this.visitSet(node); - break - case "Group": - this.visitGroup(node); - break - case "GroupBackReference": - this.visitGroupBackReference(node); - break - case "Quantifier": - this.visitQuantifier(node); - break - } + if (current === null) { + preparePortalMount(workInProgress.stateNode.containerInfo); + } - this.visitChildren(node); - }; + bubbleProperties(workInProgress); + return null; - BaseRegExpVisitor.prototype.visitPattern = function(node) {}; + case ContextProvider: + // Pop provider fiber + var context = workInProgress.type._context; + popProvider(context, workInProgress); + bubbleProperties(workInProgress); + return null; - BaseRegExpVisitor.prototype.visitFlags = function(node) {}; + case IncompleteClassComponent: + { + // Same as class component case. I put it down here so that the tags are + // sequential to ensure this switch is compiled to a jump table. + var _Component = workInProgress.type; - BaseRegExpVisitor.prototype.visitDisjunction = function(node) {}; + if (isContextProvider(_Component)) { + popContext(workInProgress); + } - BaseRegExpVisitor.prototype.visitAlternative = function(node) {}; + bubbleProperties(workInProgress); + return null; + } - // Assertion - BaseRegExpVisitor.prototype.visitStartAnchor = function(node) {}; + case SuspenseListComponent: + { + popSuspenseContext(workInProgress); + var renderState = workInProgress.memoizedState; - BaseRegExpVisitor.prototype.visitEndAnchor = function(node) {}; + if (renderState === null) { + // We're running in the default, "independent" mode. + // We don't do anything in this mode. + bubbleProperties(workInProgress); + return null; + } - BaseRegExpVisitor.prototype.visitWordBoundary = function(node) {}; + var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags; + var renderedTail = renderState.rendering; - BaseRegExpVisitor.prototype.visitNonWordBoundary = function(node) {}; + if (renderedTail === null) { + // We just rendered the head. + if (!didSuspendAlready) { + // This is the first pass. We need to figure out if anything is still + // suspended in the rendered set. + // If new content unsuspended, but there's still some content that + // didn't. Then we need to do a second pass that forces everything + // to keep showing their fallbacks. + // We might be suspended if something in this render pass suspended, or + // something in the previous committed pass suspended. Otherwise, + // there's no chance so we can skip the expensive call to + // findFirstSuspended. + var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags); - BaseRegExpVisitor.prototype.visitLookahead = function(node) {}; + if (!cannotBeSuspended) { + var row = workInProgress.child; - BaseRegExpVisitor.prototype.visitNegativeLookahead = function(node) {}; + while (row !== null) { + var suspended = findFirstSuspended(row); - // atoms - BaseRegExpVisitor.prototype.visitCharacter = function(node) {}; + if (suspended !== null) { + didSuspendAlready = true; + workInProgress.flags |= DidCapture; + cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as + // part of the second pass. In that case nothing will subscribe to + // its thenables. Instead, we'll transfer its thenables to the + // SuspenseList so that it can retry if they resolve. + // There might be multiple of these in the list but since we're + // going to wait for all of them anyway, it doesn't really matter + // which ones gets to ping. In theory we could get clever and keep + // track of how many dependencies remain but it gets tricky because + // in the meantime, we can add/remove/change items and dependencies. + // We might bail out of the loop before finding any but that + // doesn't matter since that means that the other boundaries that + // we did find already has their listeners attached. - BaseRegExpVisitor.prototype.visitSet = function(node) {}; + var newThenables = suspended.updateQueue; - BaseRegExpVisitor.prototype.visitGroup = function(node) {}; + if (newThenables !== null) { + workInProgress.updateQueue = newThenables; + workInProgress.flags |= Update; + } // Rerender the whole list, but this time, we'll force fallbacks + // to stay in place. + // Reset the effect flags before doing the second pass since that's now invalid. + // Reset the child fibers to their original state. - BaseRegExpVisitor.prototype.visitGroupBackReference = function(node) {}; - BaseRegExpVisitor.prototype.visitQuantifier = function(node) {}; + workInProgress.subtreeFlags = NoFlags; + resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately + // rerender the children. - return { - RegExpParser: RegExpParser, - BaseRegExpVisitor: BaseRegExpVisitor, - VERSION: "0.5.0" - } - } - ); -} (regexpToAst)); + pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case. -var first = {exports: {}}; + return workInProgress.child; + } -/** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ + row = row.sibling; + } + } -function head$1(array) { - return (array && array.length) ? array[0] : undefined; -} + if (renderState.tail !== null && now$1() > getRenderTargetTime()) { + // We have already passed our CPU deadline but we still have rows + // left in the tail. We'll just give up further attempts to render + // the main content and only render fallbacks. + workInProgress.flags |= DidCapture; + didSuspendAlready = true; + cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this + // to get it started back up to attempt the next item. While in terms + // of priority this work has the same priority as this current render, + // it's not part of the same transition once the transition has + // committed. If it's sync, we still want to yield so that it can be + // painted. Conceptually, this is really the same as pinging. + // We can use any RetryLane even if it's the one currently rendering + // since we're leaving it behind on this node. -var head_1 = head$1; + workInProgress.lanes = SomeRetryLane; + } + } else { + cutOffTailIfNeeded(renderState, false); + } // Next we're going to render the tail. -(function (module) { - module.exports = head_1; -} (first)); + } else { + // Append the rendered row to the child list. + if (!didSuspendAlready) { + var _suspended = findFirstSuspended(renderedTail); -/** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ + if (_suspended !== null) { + workInProgress.flags |= DidCapture; + didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't + // get lost if this row ends up dropped during a second pass. -function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + var _newThenables = _suspended.updateQueue; - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } - } - return result; -} + if (_newThenables !== null) { + workInProgress.updateQueue = _newThenables; + workInProgress.flags |= Update; + } -var compact_1 = compact; + cutOffTailIfNeeded(renderState, true); // This might have been modified. -var baseEach$2 = _baseEach; + if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating. + ) { + // We're done. + bubbleProperties(workInProgress); + return null; + } + } else if ( // The time it took to render last row is greater than the remaining + // time we have to render. So rendering one more row would likely + // exceed it. + now$1() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) { + // We have now passed our CPU deadline and we'll just give up further + // attempts to render the main content and only render fallbacks. + // The assumption is that this is usually faster. + workInProgress.flags |= DidCapture; + didSuspendAlready = true; + cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this + // to get it started back up to attempt the next item. While in terms + // of priority this work has the same priority as this current render, + // it's not part of the same transition once the transition has + // committed. If it's sync, we still want to yield so that it can be + // painted. Conceptually, this is really the same as pinging. + // We can use any RetryLane even if it's the one currently rendering + // since we're leaving it behind on this node. -/** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ -function baseFilter$2(collection, predicate) { - var result = []; - baseEach$2(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; -} + workInProgress.lanes = SomeRetryLane; + } + } -var _baseFilter = baseFilter$2; + if (renderState.isBackwards) { + // The effect list of the backwards tail will have been added + // to the end. This breaks the guarantee that life-cycles fire in + // sibling order but that isn't a strong guarantee promised by React. + // Especially since these might also just pop in during future commits. + // Append to the beginning of the list. + renderedTail.sibling = workInProgress.child; + workInProgress.child = renderedTail; + } else { + var previousSibling = renderState.last; -/** Error message constants. */ + if (previousSibling !== null) { + previousSibling.sibling = renderedTail; + } else { + workInProgress.child = renderedTail; + } -var FUNC_ERROR_TEXT = 'Expected a function'; + renderState.last = renderedTail; + } + } -/** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ -function negate$1(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; -} + if (renderState.tail !== null) { + // We still have tail rows to render. + // Pop a row. + var next = renderState.tail; + renderState.rendering = next; + renderState.tail = next.sibling; + renderState.renderingStartTime = now$1(); + next.sibling = null; // Restore the context. + // TODO: We can probably just avoid popping it instead and only + // setting it the first time we go from not suspended to suspended. -var negate_1 = negate$1; + var suspenseContext = suspenseStackCursor.current; -var arrayFilter$1 = _arrayFilter, - baseFilter$1 = _baseFilter, - baseIteratee$5 = _baseIteratee, - isArray$5 = isArray_1$1, - negate = negate_1; + if (didSuspendAlready) { + suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); + } else { + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + } -/** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] - */ -function reject(collection, predicate) { - var func = isArray$5(collection) ? arrayFilter$1 : baseFilter$1; - return func(collection, negate(baseIteratee$5(predicate))); -} + pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. + // Don't bubble properties in this case. -var reject_1 = reject; + return next; + } -var SetCache$1 = _SetCache, - arrayIncludes$1 = _arrayIncludes, - arrayIncludesWith$1 = _arrayIncludesWith, - arrayMap$2 = _arrayMap, - baseUnary$1 = _baseUnary, - cacheHas$1 = _cacheHas; + bubbleProperties(workInProgress); + return null; + } -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE$1 = 200; + case ScopeComponent: + { -/** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ -function baseDifference$2(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes$1, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; + break; + } - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap$2(values, baseUnary$1(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith$1; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE$1) { - includes = cacheHas$1; - isCommon = false; - values = new SetCache$1(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); + case OffscreenComponent: + case LegacyHiddenComponent: + { + popRenderLanes(workInProgress); + var _nextState = workInProgress.memoizedState; + var nextIsHidden = _nextState !== null; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; -} + if (current !== null) { + var _prevState2 = current.memoizedState; + var prevIsHidden = _prevState2 !== null; -var _baseDifference = baseDifference$2; + if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding — it only pre-renders. + !enableLegacyHidden )) { + workInProgress.flags |= Visibility; + } + } -var isArrayLike$3 = isArrayLike_1, - isObjectLike$2 = isObjectLike_1; + if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) { + bubbleProperties(workInProgress); + } else { + // Don't bubble properties for hidden children unless we're rendering + // at offscreen priority. + if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) { + bubbleProperties(workInProgress); -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject$3(value) { - return isObjectLike$2(value) && isArrayLike$3(value); -} + if (supportsMutation) { + // Check if there was an insertion or update in the hidden subtree. + // If so, we need to hide those nodes in the commit phase, so + // schedule a visibility effect. + if ( workInProgress.subtreeFlags & (Placement | Update)) { + workInProgress.flags |= Visibility; + } + } + } + } -var isArrayLikeObject_1 = isArrayLikeObject$3; + return null; + } -var baseDifference$1 = _baseDifference, - baseFlatten$3 = _baseFlatten, - baseRest$3 = _baseRest, - isArrayLikeObject$2 = isArrayLikeObject_1; + case CacheComponent: + { -/** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ -var difference = baseRest$3(function(array, values) { - return isArrayLikeObject$2(array) - ? baseDifference$1(array, baseFlatten$3(values, 1, isArrayLikeObject$2, true)) - : []; -}); + return null; + } -var difference_1 = difference; + case TracingMarkerComponent: + { -var baseIndexOf$1 = _baseIndexOf, - toInteger$2 = toInteger_1; + return null; + } + } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax$3 = Math.max; + throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); + } -/** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ -function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger$2(fromIndex); - if (index < 0) { - index = nativeMax$3(length + index, 0); - } - return baseIndexOf$1(array, value, index); -} + var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; + var didReceiveUpdate = false; + var didWarnAboutBadClass; + var didWarnAboutModulePatternComponent; + var didWarnAboutContextTypeOnFunctionComponent; + var didWarnAboutGetDerivedStateOnFunctionComponent; + var didWarnAboutFunctionRefs; + var didWarnAboutReassigningProps; + var didWarnAboutRevealOrder; + var didWarnAboutTailOptions; -var indexOf_1 = indexOf; + { + didWarnAboutBadClass = {}; + didWarnAboutModulePatternComponent = {}; + didWarnAboutContextTypeOnFunctionComponent = {}; + didWarnAboutGetDerivedStateOnFunctionComponent = {}; + didWarnAboutFunctionRefs = {}; + didWarnAboutReassigningProps = false; + didWarnAboutRevealOrder = {}; + didWarnAboutTailOptions = {}; + } -var baseIteratee$4 = _baseIteratee, - isArrayLike$2 = isArrayLike_1, - keys$1 = keys_1; + function reconcileChildren(current, workInProgress, nextChildren, renderLanes) { + if (current === null) { + // If this is a fresh new component that hasn't been rendered yet, we + // won't update its child set by applying minimal side-effects. Instead, + // we will add them all to the child before it gets rendered. That means + // we can optimize this reconciliation pass by not tracking side-effects. + workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); + } else { + // If the current child is the same as the work in progress, it means that + // we haven't yet started any work on these children. Therefore, we use + // the clone algorithm to create a copy of all the current children. + // If we had any progressed work already, that is invalid at this point so + // let's throw it out. + workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes); + } + } -/** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ -function createFind$1(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike$2(collection)) { - var iteratee = baseIteratee$4(predicate); - collection = keys$1(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; -} + function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) { + // This function is fork of reconcileChildren. It's used in cases where we + // want to reconcile without matching against the existing set. This has the + // effect of all current children being unmounted; even if the type and key + // are the same, the old child is unmounted and a new child is created. + // + // To do this, we're going to go through the reconcile algorithm twice. In + // the first pass, we schedule a deletion for all the current children by + // passing null. + workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we + // pass null in place of where we usually pass the current child set. This has + // the effect of remounting all children regardless of whether their + // identities match. -var _createFind = createFind$1; + workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); + } -var baseFindIndex$1 = _baseFindIndex, - baseIteratee$3 = _baseIteratee, - toInteger$1 = toInteger_1; + function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) { + // TODO: current can be non-null here even if the component + // hasn't yet mounted. This happens after the first render suspends. + // We'll need to figure out if this is fine or can cause issues. + { + if (workInProgress.type !== workInProgress.elementType) { + // Lazy component props can't be validated in createElement + // because they're only guaranteed to be resolved here. + var innerPropTypes = Component.propTypes; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax$2 = Math.max; + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(Component)); + } + } + } -/** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ -function findIndex$1(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger$1(fromIndex); - if (index < 0) { - index = nativeMax$2(length + index, 0); - } - return baseFindIndex$1(array, baseIteratee$3(predicate), index); -} + var render = Component.render; + var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent -var findIndex_1 = findIndex$1; + var nextChildren; + var hasId; + prepareToReadContext(workInProgress, renderLanes); -var createFind = _createFind, - findIndex = findIndex_1; + { + markComponentRenderStarted(workInProgress); + } -/** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ -var find = createFind(findIndex); + { + ReactCurrentOwner$1.current = workInProgress; + setIsRendering(true); + nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); + hasId = checkDidRenderIdHook(); -var find_1 = find; + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); -var arrayFilter = _arrayFilter, - baseFilter = _baseFilter, - baseIteratee$2 = _baseIteratee, - isArray$4 = isArray_1$1; + try { + nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } -/** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] - */ -function filter(collection, predicate) { - var func = isArray$4(collection) ? arrayFilter : baseFilter; - return func(collection, baseIteratee$2(predicate)); -} + setIsRendering(false); + } -var filter_1 = filter; + { + markComponentRenderStopped(); + } -var baseRest$2 = _baseRest, - eq$1 = eq_1, - isIterateeCall = _isIterateeCall, - keysIn$1 = keysIn_1; + if (current !== null && !didReceiveUpdate) { + bailoutHooks(current, workInProgress, renderLanes); + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress); + } // React DevTools reads this flag. -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$3.hasOwnProperty; -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var defaults = baseRest$2(function(object, sources) { - object = Object(object); + workInProgress.flags |= PerformedWork; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; + function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { + if (current === null) { + var type = Component.type; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } + if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. + Component.defaultProps === undefined) { + var resolvedType = type; - while (++index < length) { - var source = sources[index]; - var props = keysIn$1(source); - var propsIndex = -1; - var propsLength = props.length; - - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - - if (value === undefined || - (eq$1(value, objectProto$3[key]) && !hasOwnProperty$3.call(object, key))) { - object[key] = source[key]; - } - } - } + { + resolvedType = resolveFunctionForHotReloading(type); + } // If this is a plain function component without default props, + // and with only the default shallow comparison, we upgrade it + // to a SimpleMemoComponent to allow fast path updates. - return object; -}); -var defaults_1 = defaults; + workInProgress.tag = SimpleMemoComponent; + workInProgress.type = resolvedType; -/** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ + { + validateFunctionComponentInDev(workInProgress, type); + } -function arrayReduce$1(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; + return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes); + } - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; -} + { + var innerPropTypes = type.propTypes; -var _arrayReduce = arrayReduce$1; + if (innerPropTypes) { + // Inner memo component props aren't currently validated in createElement. + // We could move it there, but we'd still need this for lazy code path. + checkPropTypes(innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(type)); + } + } -/** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ + var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes); + child.ref = workInProgress.ref; + child.return = workInProgress; + workInProgress.child = child; + return child; + } -function baseReduce$1(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; -} + { + var _type = Component.type; + var _innerPropTypes = _type.propTypes; -var _baseReduce = baseReduce$1; + if (_innerPropTypes) { + // Inner memo component props aren't currently validated in createElement. + // We could move it there, but we'd still need this for lazy code path. + checkPropTypes(_innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(_type)); + } + } -var arrayReduce = _arrayReduce, - baseEach$1 = _baseEach, - baseIteratee$1 = _baseIteratee, - baseReduce = _baseReduce, - isArray$3 = isArray_1$1; + var currentChild = current.child; // This is always exactly one child -/** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ -function reduce(collection, iteratee, accumulator) { - var func = isArray$3(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; + var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); - return func(collection, baseIteratee$1(iteratee), accumulator, initAccum, baseEach$1); -} + if (!hasScheduledUpdateOrContext) { + // This will be the props with resolved defaultProps, + // unlike current.memoizedProps which will be the unresolved ones. + var prevProps = currentChild.memoizedProps; // Default to shallow comparison -var reduce_1$1 = reduce; + var compare = Component.compare; + compare = compare !== null ? compare : shallowEqual; -var reg_exp = {}; + if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) { + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } + } // React DevTools reads this flag. -var reg_exp_parser = {}; -Object.defineProperty(reg_exp_parser, "__esModule", { value: true }); -reg_exp_parser.clearRegExpParserCache = reg_exp_parser.getRegExpAst = void 0; -var regexp_to_ast_1 = regexpToAst.exports; -var regExpAstCache = {}; -var regExpParser = new regexp_to_ast_1.RegExpParser(); -function getRegExpAst(regExp) { - var regExpStr = regExp.toString(); - if (regExpAstCache.hasOwnProperty(regExpStr)) { - return regExpAstCache[regExpStr]; - } - else { - var regExpAst = regExpParser.pattern(regExpStr); - regExpAstCache[regExpStr] = regExpAst; - return regExpAst; - } -} -reg_exp_parser.getRegExpAst = getRegExpAst; -function clearRegExpParserCache() { - regExpAstCache = {}; -} -reg_exp_parser.clearRegExpParserCache = clearRegExpParserCache; + workInProgress.flags |= PerformedWork; + var newChild = createWorkInProgress(currentChild, nextProps); + newChild.ref = workInProgress.ref; + newChild.return = workInProgress; + workInProgress.child = newChild; + return newChild; + } -var hasRequiredReg_exp; + function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { + // TODO: current can be non-null here even if the component + // hasn't yet mounted. This happens when the inner render suspends. + // We'll need to figure out if this is fine or can cause issues. + { + if (workInProgress.type !== workInProgress.elementType) { + // Lazy component props can't be validated in createElement + // because they're only guaranteed to be resolved here. + var outerMemoType = workInProgress.elementType; -function requireReg_exp () { - if (hasRequiredReg_exp) return reg_exp; - hasRequiredReg_exp = 1; - (function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.canMatchCharCode = exports.firstCharOptimizedIndices = exports.getOptimizedStartCodesIndices = exports.failedOptimizationPrefixMsg = void 0; - var regexp_to_ast_1 = regexpToAst.exports; - var isArray_1 = __importDefault(isArray_1$1); - var every_1 = __importDefault(every_1$1); - var forEach_1 = __importDefault(forEach_1$4); - var find_1$1 = __importDefault(find_1); - var values_1 = __importDefault(values_1$1); - var includes_1 = __importDefault(includes_1$2); - var utils_1 = api$2; - var reg_exp_parser_1 = reg_exp_parser; - var lexer_1 = requireLexer(); - var complementErrorMessage = "Complement Sets are not supported for first char optimization"; - exports.failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n'; - function getOptimizedStartCodesIndices(regExp, ensureOptimizations) { - if (ensureOptimizations === void 0) { ensureOptimizations = false; } - try { - var ast = (0, reg_exp_parser_1.getRegExpAst)(regExp); - var firstChars = firstCharOptimizedIndices(ast.value, {}, ast.flags.ignoreCase); - return firstChars; - } - catch (e) { - /* istanbul ignore next */ - // Testing this relies on the regexp-to-ast library having a bug... */ - // TODO: only the else branch needs to be ignored, try to fix with newer prettier / tsc - if (e.message === complementErrorMessage) { - if (ensureOptimizations) { - (0, utils_1.PRINT_WARNING)("".concat(exports.failedOptimizationPrefixMsg) + - "\tUnable to optimize: < ".concat(regExp.toString(), " >\n") + - "\tComplement Sets cannot be automatically optimized.\n" + - "\tThis will disable the lexer's first char optimizations.\n" + - "\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details."); - } - } - else { - var msgSuffix = ""; - if (ensureOptimizations) { - msgSuffix = - "\n\tThis will disable the lexer's first char optimizations.\n" + - "\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details."; - } - (0, utils_1.PRINT_ERROR)("".concat(exports.failedOptimizationPrefixMsg, "\n") + - "\tFailed parsing: < ".concat(regExp.toString(), " >\n") + - "\tUsing the regexp-to-ast library version: ".concat(regexp_to_ast_1.VERSION, "\n") + - "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" + - msgSuffix); - } - } - return []; - } - exports.getOptimizedStartCodesIndices = getOptimizedStartCodesIndices; - function firstCharOptimizedIndices(ast, result, ignoreCase) { - switch (ast.type) { - case "Disjunction": - for (var i = 0; i < ast.value.length; i++) { - firstCharOptimizedIndices(ast.value[i], result, ignoreCase); - } - break; - case "Alternative": - var terms = ast.value; - for (var i = 0; i < terms.length; i++) { - var term = terms[i]; - // skip terms that cannot effect the first char results - switch (term.type) { - case "EndAnchor": - // A group back reference cannot affect potential starting char. - // because if a back reference is the first production than automatically - // the group being referenced has had to come BEFORE so its codes have already been added - case "GroupBackReference": - // assertions do not affect potential starting codes - case "Lookahead": - case "NegativeLookahead": - case "StartAnchor": - case "WordBoundary": - case "NonWordBoundary": - continue; - } - var atom = term; - switch (atom.type) { - case "Character": - addOptimizedIdxToResult(atom.value, result, ignoreCase); - break; - case "Set": - if (atom.complement === true) { - throw Error(complementErrorMessage); - } - (0, forEach_1.default)(atom.value, function (code) { - if (typeof code === "number") { - addOptimizedIdxToResult(code, result, ignoreCase); - } - else { - // range - var range = code; - // cannot optimize when ignoreCase is - if (ignoreCase === true) { - for (var rangeCode = range.from; rangeCode <= range.to; rangeCode++) { - addOptimizedIdxToResult(rangeCode, result, ignoreCase); - } - } - // Optimization (2 orders of magnitude less work for very large ranges) - else { - // handle unoptimized values - for (var rangeCode = range.from; rangeCode <= range.to && rangeCode < lexer_1.minOptimizationVal; rangeCode++) { - addOptimizedIdxToResult(rangeCode, result, ignoreCase); - } - // Less common charCode where we optimize for faster init time, by using larger "buckets" - if (range.to >= lexer_1.minOptimizationVal) { - var minUnOptVal = range.from >= lexer_1.minOptimizationVal - ? range.from - : lexer_1.minOptimizationVal; - var maxUnOptVal = range.to; - var minOptIdx = (0, lexer_1.charCodeToOptimizedIndex)(minUnOptVal); - var maxOptIdx = (0, lexer_1.charCodeToOptimizedIndex)(maxUnOptVal); - for (var currOptIdx = minOptIdx; currOptIdx <= maxOptIdx; currOptIdx++) { - result[currOptIdx] = currOptIdx; - } - } - } - } - }); - break; - case "Group": - firstCharOptimizedIndices(atom.value, result, ignoreCase); - break; - /* istanbul ignore next */ - default: - throw Error("Non Exhaustive Match"); - } - // reached a mandatory production, no more **start** codes can be found on this alternative - var isOptionalQuantifier = atom.quantifier !== undefined && atom.quantifier.atLeast === 0; - if ( - // A group may be optional due to empty contents /(?:)/ - // or if everything inside it is optional /((a)?)/ - (atom.type === "Group" && isWholeOptional(atom) === false) || - // If this term is not a group it may only be optional if it has an optional quantifier - (atom.type !== "Group" && isOptionalQuantifier === false)) { - break; - } - } - break; - /* istanbul ignore next */ - default: - throw Error("non exhaustive match!"); - } - // console.log(Object.keys(result).length) - return (0, values_1.default)(result); - } - exports.firstCharOptimizedIndices = firstCharOptimizedIndices; - function addOptimizedIdxToResult(code, result, ignoreCase) { - var optimizedCharIdx = (0, lexer_1.charCodeToOptimizedIndex)(code); - result[optimizedCharIdx] = optimizedCharIdx; - if (ignoreCase === true) { - handleIgnoreCase(code, result); - } - } - function handleIgnoreCase(code, result) { - var char = String.fromCharCode(code); - var upperChar = char.toUpperCase(); - /* istanbul ignore else */ - if (upperChar !== char) { - var optimizedCharIdx = (0, lexer_1.charCodeToOptimizedIndex)(upperChar.charCodeAt(0)); - result[optimizedCharIdx] = optimizedCharIdx; - } - else { - var lowerChar = char.toLowerCase(); - if (lowerChar !== char) { - var optimizedCharIdx = (0, lexer_1.charCodeToOptimizedIndex)(lowerChar.charCodeAt(0)); - result[optimizedCharIdx] = optimizedCharIdx; - } - } - } - function findCode(setNode, targetCharCodes) { - return (0, find_1$1.default)(setNode.value, function (codeOrRange) { - if (typeof codeOrRange === "number") { - return (0, includes_1.default)(targetCharCodes, codeOrRange); - } - else { - // range - var range_1 = codeOrRange; - return ((0, find_1$1.default)(targetCharCodes, function (targetCode) { return range_1.from <= targetCode && targetCode <= range_1.to; }) !== undefined); - } - }); - } - function isWholeOptional(ast) { - var quantifier = ast.quantifier; - if (quantifier && quantifier.atLeast === 0) { - return true; - } - if (!ast.value) { - return false; - } - return (0, isArray_1.default)(ast.value) - ? (0, every_1.default)(ast.value, isWholeOptional) - : isWholeOptional(ast.value); - } - var CharCodeFinder = /** @class */ (function (_super) { - __extends(CharCodeFinder, _super); - function CharCodeFinder(targetCharCodes) { - var _this = _super.call(this) || this; - _this.targetCharCodes = targetCharCodes; - _this.found = false; - return _this; - } - CharCodeFinder.prototype.visitChildren = function (node) { - // No need to keep looking... - if (this.found === true) { - return; - } - // switch lookaheads as they do not actually consume any characters thus - // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match. - switch (node.type) { - case "Lookahead": - this.visitLookahead(node); - return; - case "NegativeLookahead": - this.visitNegativeLookahead(node); - return; - } - _super.prototype.visitChildren.call(this, node); - }; - CharCodeFinder.prototype.visitCharacter = function (node) { - if ((0, includes_1.default)(this.targetCharCodes, node.value)) { - this.found = true; - } - }; - CharCodeFinder.prototype.visitSet = function (node) { - if (node.complement) { - if (findCode(node, this.targetCharCodes) === undefined) { - this.found = true; - } - } - else { - if (findCode(node, this.targetCharCodes) !== undefined) { - this.found = true; - } - } - }; - return CharCodeFinder; - }(regexp_to_ast_1.BaseRegExpVisitor)); - function canMatchCharCode(charCodes, pattern) { - if (pattern instanceof RegExp) { - var ast = (0, reg_exp_parser_1.getRegExpAst)(pattern); - var charCodeFinder = new CharCodeFinder(charCodes); - charCodeFinder.visit(ast); - return charCodeFinder.found; - } - else { - return ((0, find_1$1.default)(pattern, function (char) { - return (0, includes_1.default)(charCodes, char.charCodeAt(0)); - }) !== undefined); - } - } - exports.canMatchCharCode = canMatchCharCode; - -} (reg_exp)); - return reg_exp; -} + if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { + // We warn when you define propTypes on lazy() + // so let's just skip over it to find memo() outer wrapper. + // Inner props for memo are validated later. + var lazyComponent = outerMemoType; + var payload = lazyComponent._payload; + var init = lazyComponent._init; -var hasRequiredLexer; + try { + outerMemoType = init(payload); + } catch (x) { + outerMemoType = null; + } // Inner propTypes will be validated in the function component path. -function requireLexer () { - if (hasRequiredLexer) return lexer; - hasRequiredLexer = 1; - (function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.charCodeToOptimizedIndex = exports.minOptimizationVal = exports.buildLineBreakIssueMessage = exports.LineTerminatorOptimizedTester = exports.isShortPattern = exports.isCustomPattern = exports.cloneEmptyGroups = exports.performWarningRuntimeChecks = exports.performRuntimeChecks = exports.addStickyFlag = exports.addStartOfInput = exports.findUnreachablePatterns = exports.findModesThatDoNotExist = exports.findInvalidGroupType = exports.findDuplicatePatterns = exports.findUnsupportedFlags = exports.findStartOfInputAnchor = exports.findEmptyMatchRegExps = exports.findEndOfInputAnchor = exports.findInvalidPatterns = exports.findMissingPatterns = exports.validatePatterns = exports.analyzeTokenTypes = exports.enableSticky = exports.disableSticky = exports.SUPPORT_STICKY = exports.MODES = exports.DEFAULT_MODE = void 0; - var regexp_to_ast_1 = regexpToAst.exports; - var lexer_public_1 = requireLexer_public(); - var first_1 = __importDefault(first.exports); - var isEmpty_1 = __importDefault(isEmpty_1$1); - var compact_1$1 = __importDefault(compact_1); - var isArray_1 = __importDefault(isArray_1$1); - var values_1 = __importDefault(values_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var reject_1$1 = __importDefault(reject_1); - var difference_1$1 = __importDefault(difference_1); - var indexOf_1$1 = __importDefault(indexOf_1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var isString_1 = __importDefault(isString_1$1); - var isFunction_1$1 = __importDefault(isFunction_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var find_1$1 = __importDefault(find_1); - var has_1$1 = __importDefault(has_1); - var keys_1$1 = __importDefault(keys_1); - var isRegExp_1 = __importDefault(isRegExp_1$1); - var filter_1$1 = __importDefault(filter_1); - var defaults_1$1 = __importDefault(defaults_1); - var reduce_1 = __importDefault(reduce_1$1); - var includes_1 = __importDefault(includes_1$2); - var utils_1 = api$2; - var reg_exp_1 = requireReg_exp(); - var reg_exp_parser_1 = reg_exp_parser; - var PATTERN = "PATTERN"; - exports.DEFAULT_MODE = "defaultMode"; - exports.MODES = "modes"; - exports.SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean"; - function disableSticky() { - exports.SUPPORT_STICKY = false; - } - exports.disableSticky = disableSticky; - function enableSticky() { - exports.SUPPORT_STICKY = true; - } - exports.enableSticky = enableSticky; - function analyzeTokenTypes(tokenTypes, options) { - options = (0, defaults_1$1.default)(options, { - useSticky: exports.SUPPORT_STICKY, - debug: false, - safeMode: false, - positionTracking: "full", - lineTerminatorCharacters: ["\r", "\n"], - tracer: function (msg, action) { return action(); } - }); - var tracer = options.tracer; - tracer("initCharCodeToOptimizedIndexMap", function () { - initCharCodeToOptimizedIndexMap(); - }); - var onlyRelevantTypes; - tracer("Reject Lexer.NA", function () { - onlyRelevantTypes = (0, reject_1$1.default)(tokenTypes, function (currType) { - return currType[PATTERN] === lexer_public_1.Lexer.NA; - }); - }); - var hasCustom = false; - var allTransformedPatterns; - tracer("Transform Patterns", function () { - hasCustom = false; - allTransformedPatterns = (0, map_1.default)(onlyRelevantTypes, function (currType) { - var currPattern = currType[PATTERN]; - /* istanbul ignore else */ - if ((0, isRegExp_1.default)(currPattern)) { - var regExpSource = currPattern.source; - if (regExpSource.length === 1 && - // only these regExp meta characters which can appear in a length one regExp - regExpSource !== "^" && - regExpSource !== "$" && - regExpSource !== "." && - !currPattern.ignoreCase) { - return regExpSource; - } - else if (regExpSource.length === 2 && - regExpSource[0] === "\\" && - // not a meta character - !(0, includes_1.default)([ - "d", - "D", - "s", - "S", - "t", - "r", - "n", - "t", - "0", - "c", - "b", - "B", - "f", - "v", - "w", - "W" - ], regExpSource[1])) { - // escaped meta Characters: /\+/ /\[/ - // or redundant escaping: /\a/ - // without the escaping "\" - return regExpSource[1]; - } - else { - return options.useSticky - ? addStickyFlag(currPattern) - : addStartOfInput(currPattern); - } - } - else if ((0, isFunction_1$1.default)(currPattern)) { - hasCustom = true; - // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object - return { exec: currPattern }; - } - else if (typeof currPattern === "object") { - hasCustom = true; - // ICustomPattern - return currPattern; - } - else if (typeof currPattern === "string") { - if (currPattern.length === 1) { - return currPattern; - } - else { - var escapedRegExpString = currPattern.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); - var wrappedRegExp = new RegExp(escapedRegExpString); - return options.useSticky - ? addStickyFlag(wrappedRegExp) - : addStartOfInput(wrappedRegExp); - } - } - else { - throw Error("non exhaustive match"); - } - }); - }); - var patternIdxToType; - var patternIdxToGroup; - var patternIdxToLongerAltIdxArr; - var patternIdxToPushMode; - var patternIdxToPopMode; - tracer("misc mapping", function () { - patternIdxToType = (0, map_1.default)(onlyRelevantTypes, function (currType) { return currType.tokenTypeIdx; }); - patternIdxToGroup = (0, map_1.default)(onlyRelevantTypes, function (clazz) { - var groupName = clazz.GROUP; - /* istanbul ignore next */ - if (groupName === lexer_public_1.Lexer.SKIPPED) { - return undefined; - } - else if ((0, isString_1.default)(groupName)) { - return groupName; - } - else if ((0, isUndefined_1.default)(groupName)) { - return false; - } - else { - throw Error("non exhaustive match"); - } - }); - patternIdxToLongerAltIdxArr = (0, map_1.default)(onlyRelevantTypes, function (clazz) { - var longerAltType = clazz.LONGER_ALT; - if (longerAltType) { - var longerAltIdxArr = (0, isArray_1.default)(longerAltType) - ? (0, map_1.default)(longerAltType, function (type) { return (0, indexOf_1$1.default)(onlyRelevantTypes, type); }) - : [(0, indexOf_1$1.default)(onlyRelevantTypes, longerAltType)]; - return longerAltIdxArr; - } - }); - patternIdxToPushMode = (0, map_1.default)(onlyRelevantTypes, function (clazz) { return clazz.PUSH_MODE; }); - patternIdxToPopMode = (0, map_1.default)(onlyRelevantTypes, function (clazz) { - return (0, has_1$1.default)(clazz, "POP_MODE"); - }); - }); - var patternIdxToCanLineTerminator; - tracer("Line Terminator Handling", function () { - var lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters); - patternIdxToCanLineTerminator = (0, map_1.default)(onlyRelevantTypes, function (tokType) { return false; }); - if (options.positionTracking !== "onlyOffset") { - patternIdxToCanLineTerminator = (0, map_1.default)(onlyRelevantTypes, function (tokType) { - if ((0, has_1$1.default)(tokType, "LINE_BREAKS")) { - return !!tokType.LINE_BREAKS; - } - else { - return (checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false && - (0, reg_exp_1.canMatchCharCode)(lineTerminatorCharCodes, tokType.PATTERN)); - } - }); - } - }); - var patternIdxToIsCustom; - var patternIdxToShort; - var emptyGroups; - var patternIdxToConfig; - tracer("Misc Mapping #2", function () { - patternIdxToIsCustom = (0, map_1.default)(onlyRelevantTypes, isCustomPattern); - patternIdxToShort = (0, map_1.default)(allTransformedPatterns, isShortPattern); - emptyGroups = (0, reduce_1.default)(onlyRelevantTypes, function (acc, clazz) { - var groupName = clazz.GROUP; - if ((0, isString_1.default)(groupName) && !(groupName === lexer_public_1.Lexer.SKIPPED)) { - acc[groupName] = []; - } - return acc; - }, {}); - patternIdxToConfig = (0, map_1.default)(allTransformedPatterns, function (x, idx) { - return { - pattern: allTransformedPatterns[idx], - longerAlt: patternIdxToLongerAltIdxArr[idx], - canLineTerminator: patternIdxToCanLineTerminator[idx], - isCustom: patternIdxToIsCustom[idx], - short: patternIdxToShort[idx], - group: patternIdxToGroup[idx], - push: patternIdxToPushMode[idx], - pop: patternIdxToPopMode[idx], - tokenTypeIdx: patternIdxToType[idx], - tokenType: onlyRelevantTypes[idx] - }; - }); - }); - var canBeOptimized = true; - var charCodeToPatternIdxToConfig = []; - if (!options.safeMode) { - tracer("First Char Optimization", function () { - charCodeToPatternIdxToConfig = (0, reduce_1.default)(onlyRelevantTypes, function (result, currTokType, idx) { - if (typeof currTokType.PATTERN === "string") { - var charCode = currTokType.PATTERN.charCodeAt(0); - var optimizedIdx = charCodeToOptimizedIndex(charCode); - addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]); - } - else if ((0, isArray_1.default)(currTokType.START_CHARS_HINT)) { - var lastOptimizedIdx_1; - (0, forEach_1.default)(currTokType.START_CHARS_HINT, function (charOrInt) { - var charCode = typeof charOrInt === "string" - ? charOrInt.charCodeAt(0) - : charOrInt; - var currOptimizedIdx = charCodeToOptimizedIndex(charCode); - // Avoid adding the config multiple times - /* istanbul ignore else */ - // - Difficult to check this scenario effects as it is only a performance - // optimization that does not change correctness - if (lastOptimizedIdx_1 !== currOptimizedIdx) { - lastOptimizedIdx_1 = currOptimizedIdx; - addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]); - } - }); - } - else if ((0, isRegExp_1.default)(currTokType.PATTERN)) { - if (currTokType.PATTERN.unicode) { - canBeOptimized = false; - if (options.ensureOptimizations) { - (0, utils_1.PRINT_ERROR)("".concat(reg_exp_1.failedOptimizationPrefixMsg) + - "\tUnable to analyze < ".concat(currTokType.PATTERN.toString(), " > pattern.\n") + - "\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\n" + - "\tThis will disable the lexer's first char optimizations.\n" + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE"); - } - } - else { - var optimizedCodes = (0, reg_exp_1.getOptimizedStartCodesIndices)(currTokType.PATTERN, options.ensureOptimizations); - /* istanbul ignore if */ - // start code will only be empty given an empty regExp or failure of regexp-to-ast library - // the first should be a different validation and the second cannot be tested. - if ((0, isEmpty_1.default)(optimizedCodes)) { - // we cannot understand what codes may start possible matches - // The optimization correctness requires knowing start codes for ALL patterns. - // Not actually sure this is an error, no debug message - canBeOptimized = false; - } - (0, forEach_1.default)(optimizedCodes, function (code) { - addToMapOfArrays(result, code, patternIdxToConfig[idx]); - }); - } - } - else { - if (options.ensureOptimizations) { - (0, utils_1.PRINT_ERROR)("".concat(reg_exp_1.failedOptimizationPrefixMsg) + - "\tTokenType: <".concat(currTokType.name, "> is using a custom token pattern without providing parameter.\n") + - "\tThis will disable the lexer's first char optimizations.\n" + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE"); - } - canBeOptimized = false; - } - return result; - }, []); - }); - } - return { - emptyGroups: emptyGroups, - patternIdxToConfig: patternIdxToConfig, - charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig, - hasCustom: hasCustom, - canBeOptimized: canBeOptimized - }; - } - exports.analyzeTokenTypes = analyzeTokenTypes; - function validatePatterns(tokenTypes, validModesNames) { - var errors = []; - var missingResult = findMissingPatterns(tokenTypes); - errors = errors.concat(missingResult.errors); - var invalidResult = findInvalidPatterns(missingResult.valid); - var validTokenTypes = invalidResult.valid; - errors = errors.concat(invalidResult.errors); - errors = errors.concat(validateRegExpPattern(validTokenTypes)); - errors = errors.concat(findInvalidGroupType(validTokenTypes)); - errors = errors.concat(findModesThatDoNotExist(validTokenTypes, validModesNames)); - errors = errors.concat(findUnreachablePatterns(validTokenTypes)); - return errors; - } - exports.validatePatterns = validatePatterns; - function validateRegExpPattern(tokenTypes) { - var errors = []; - var withRegExpPatterns = (0, filter_1$1.default)(tokenTypes, function (currTokType) { - return (0, isRegExp_1.default)(currTokType[PATTERN]); - }); - errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns)); - errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns)); - errors = errors.concat(findUnsupportedFlags(withRegExpPatterns)); - errors = errors.concat(findDuplicatePatterns(withRegExpPatterns)); - errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns)); - return errors; - } - function findMissingPatterns(tokenTypes) { - var tokenTypesWithMissingPattern = (0, filter_1$1.default)(tokenTypes, function (currType) { - return !(0, has_1$1.default)(currType, PATTERN); - }); - var errors = (0, map_1.default)(tokenTypesWithMissingPattern, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- missing static 'PATTERN' property", - type: lexer_public_1.LexerDefinitionErrorType.MISSING_PATTERN, - tokenTypes: [currType] - }; - }); - var valid = (0, difference_1$1.default)(tokenTypes, tokenTypesWithMissingPattern); - return { errors: errors, valid: valid }; - } - exports.findMissingPatterns = findMissingPatterns; - function findInvalidPatterns(tokenTypes) { - var tokenTypesWithInvalidPattern = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return (!(0, isRegExp_1.default)(pattern) && - !(0, isFunction_1$1.default)(pattern) && - !(0, has_1$1.default)(pattern, "exec") && - !(0, isString_1.default)(pattern)); - }); - var errors = (0, map_1.default)(tokenTypesWithInvalidPattern, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' can only be a RegExp, a" + - " Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", - type: lexer_public_1.LexerDefinitionErrorType.INVALID_PATTERN, - tokenTypes: [currType] - }; - }); - var valid = (0, difference_1$1.default)(tokenTypes, tokenTypesWithInvalidPattern); - return { errors: errors, valid: valid }; - } - exports.findInvalidPatterns = findInvalidPatterns; - var end_of_input = /[^\\][$]/; - function findEndOfInputAnchor(tokenTypes) { - var EndAnchorFinder = /** @class */ (function (_super) { - __extends(EndAnchorFinder, _super); - function EndAnchorFinder() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.found = false; - return _this; - } - EndAnchorFinder.prototype.visitEndAnchor = function (node) { - this.found = true; - }; - return EndAnchorFinder; - }(regexp_to_ast_1.BaseRegExpVisitor)); - var invalidRegex = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType.PATTERN; - try { - var regexpAst = (0, reg_exp_parser_1.getRegExpAst)(pattern); - var endAnchorVisitor = new EndAnchorFinder(); - endAnchorVisitor.visit(regexpAst); - return endAnchorVisitor.found; - } - catch (e) { - // old behavior in case of runtime exceptions with regexp-to-ast. - /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ - return end_of_input.test(pattern.source); - } - }); - var errors = (0, map_1.default)(invalidRegex, function (currType) { - return { - message: "Unexpected RegExp Anchor Error:\n" + - "\tToken Type: ->" + - currType.name + - "<- static 'PATTERN' cannot contain end of input anchor '$'\n" + - "\tSee chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS" + - "\tfor details.", - type: lexer_public_1.LexerDefinitionErrorType.EOI_ANCHOR_FOUND, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findEndOfInputAnchor = findEndOfInputAnchor; - function findEmptyMatchRegExps(tokenTypes) { - var matchesEmptyString = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType.PATTERN; - return pattern.test(""); - }); - var errors = (0, map_1.default)(matchesEmptyString, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' must not match an empty string", - type: lexer_public_1.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findEmptyMatchRegExps = findEmptyMatchRegExps; - var start_of_input = /[^\\[][\^]|^\^/; - function findStartOfInputAnchor(tokenTypes) { - var StartAnchorFinder = /** @class */ (function (_super) { - __extends(StartAnchorFinder, _super); - function StartAnchorFinder() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.found = false; - return _this; - } - StartAnchorFinder.prototype.visitStartAnchor = function (node) { - this.found = true; - }; - return StartAnchorFinder; - }(regexp_to_ast_1.BaseRegExpVisitor)); - var invalidRegex = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType.PATTERN; - try { - var regexpAst = (0, reg_exp_parser_1.getRegExpAst)(pattern); - var startAnchorVisitor = new StartAnchorFinder(); - startAnchorVisitor.visit(regexpAst); - return startAnchorVisitor.found; - } - catch (e) { - // old behavior in case of runtime exceptions with regexp-to-ast. - /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ - return start_of_input.test(pattern.source); - } - }); - var errors = (0, map_1.default)(invalidRegex, function (currType) { - return { - message: "Unexpected RegExp Anchor Error:\n" + - "\tToken Type: ->" + - currType.name + - "<- static 'PATTERN' cannot contain start of input anchor '^'\n" + - "\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS" + - "\tfor details.", - type: lexer_public_1.LexerDefinitionErrorType.SOI_ANCHOR_FOUND, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findStartOfInputAnchor = findStartOfInputAnchor; - function findUnsupportedFlags(tokenTypes) { - var invalidFlags = (0, filter_1$1.default)(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return pattern instanceof RegExp && (pattern.multiline || pattern.global); - }); - var errors = (0, map_1.default)(invalidFlags, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", - type: lexer_public_1.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findUnsupportedFlags = findUnsupportedFlags; - // This can only test for identical duplicate RegExps, not semantically equivalent ones. - function findDuplicatePatterns(tokenTypes) { - var found = []; - var identicalPatterns = (0, map_1.default)(tokenTypes, function (outerType) { - return (0, reduce_1.default)(tokenTypes, function (result, innerType) { - if (outerType.PATTERN.source === innerType.PATTERN.source && - !(0, includes_1.default)(found, innerType) && - innerType.PATTERN !== lexer_public_1.Lexer.NA) { - // this avoids duplicates in the result, each Token Type may only appear in one "set" - // in essence we are creating Equivalence classes on equality relation. - found.push(innerType); - result.push(innerType); - return result; - } - return result; - }, []); - }); - identicalPatterns = (0, compact_1$1.default)(identicalPatterns); - var duplicatePatterns = (0, filter_1$1.default)(identicalPatterns, function (currIdenticalSet) { - return currIdenticalSet.length > 1; - }); - var errors = (0, map_1.default)(duplicatePatterns, function (setOfIdentical) { - var tokenTypeNames = (0, map_1.default)(setOfIdentical, function (currType) { - return currType.name; - }); - var dupPatternSrc = (0, first_1.default)(setOfIdentical).PATTERN; - return { - message: "The same RegExp pattern ->".concat(dupPatternSrc, "<-") + - "has been used in all of the following Token Types: ".concat(tokenTypeNames.join(", "), " <-"), - type: lexer_public_1.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, - tokenTypes: setOfIdentical - }; - }); - return errors; - } - exports.findDuplicatePatterns = findDuplicatePatterns; - function findInvalidGroupType(tokenTypes) { - var invalidTypes = (0, filter_1$1.default)(tokenTypes, function (clazz) { - if (!(0, has_1$1.default)(clazz, "GROUP")) { - return false; - } - var group = clazz.GROUP; - return group !== lexer_public_1.Lexer.SKIPPED && group !== lexer_public_1.Lexer.NA && !(0, isString_1.default)(group); - }); - var errors = (0, map_1.default)(invalidTypes, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", - type: lexer_public_1.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, - tokenTypes: [currType] - }; - }); - return errors; - } - exports.findInvalidGroupType = findInvalidGroupType; - function findModesThatDoNotExist(tokenTypes, validModes) { - var invalidModes = (0, filter_1$1.default)(tokenTypes, function (clazz) { - return (clazz.PUSH_MODE !== undefined && !(0, includes_1.default)(validModes, clazz.PUSH_MODE)); - }); - var errors = (0, map_1.default)(invalidModes, function (tokType) { - var msg = "Token Type: ->".concat(tokType.name, "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->").concat(tokType.PUSH_MODE, "<-") + - "which does not exist"; - return { - message: msg, - type: lexer_public_1.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, - tokenTypes: [tokType] - }; - }); - return errors; - } - exports.findModesThatDoNotExist = findModesThatDoNotExist; - function findUnreachablePatterns(tokenTypes) { - var errors = []; - var canBeTested = (0, reduce_1.default)(tokenTypes, function (result, tokType, idx) { - var pattern = tokType.PATTERN; - if (pattern === lexer_public_1.Lexer.NA) { - return result; - } - // a more comprehensive validation for all forms of regExps would require - // deeper regExp analysis capabilities - if ((0, isString_1.default)(pattern)) { - result.push({ str: pattern, idx: idx, tokenType: tokType }); - } - else if ((0, isRegExp_1.default)(pattern) && noMetaChar(pattern)) { - result.push({ str: pattern.source, idx: idx, tokenType: tokType }); - } - return result; - }, []); - (0, forEach_1.default)(tokenTypes, function (tokType, testIdx) { - (0, forEach_1.default)(canBeTested, function (_a) { - var str = _a.str, idx = _a.idx, tokenType = _a.tokenType; - if (testIdx < idx && testTokenType(str, tokType.PATTERN)) { - var msg = "Token: ->".concat(tokenType.name, "<- can never be matched.\n") + - "Because it appears AFTER the Token Type ->".concat(tokType.name, "<-") + - "in the lexer's definition.\n" + - "See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE"; - errors.push({ - message: msg, - type: lexer_public_1.LexerDefinitionErrorType.UNREACHABLE_PATTERN, - tokenTypes: [tokType, tokenType] - }); - } - }); - }); - return errors; - } - exports.findUnreachablePatterns = findUnreachablePatterns; - function testTokenType(str, pattern) { - /* istanbul ignore else */ - if ((0, isRegExp_1.default)(pattern)) { - var regExpArray = pattern.exec(str); - return regExpArray !== null && regExpArray.index === 0; - } - else if ((0, isFunction_1$1.default)(pattern)) { - // maintain the API of custom patterns - return pattern(str, 0, [], {}); - } - else if ((0, has_1$1.default)(pattern, "exec")) { - // maintain the API of custom patterns - return pattern.exec(str, 0, [], {}); - } - else if (typeof pattern === "string") { - return pattern === str; - } - else { - throw Error("non exhaustive match"); - } - } - function noMetaChar(regExp) { - //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp - var metaChars = [ - ".", - "\\", - "[", - "]", - "|", - "^", - "$", - "(", - ")", - "?", - "*", - "+", - "{" - ]; - return ((0, find_1$1.default)(metaChars, function (char) { return regExp.source.indexOf(char) !== -1; }) === undefined); - } - function addStartOfInput(pattern) { - var flags = pattern.ignoreCase ? "i" : ""; - // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. - // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) - return new RegExp("^(?:".concat(pattern.source, ")"), flags); - } - exports.addStartOfInput = addStartOfInput; - function addStickyFlag(pattern) { - var flags = pattern.ignoreCase ? "iy" : "y"; - // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. - // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) - return new RegExp("".concat(pattern.source), flags); - } - exports.addStickyFlag = addStickyFlag; - function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { - var errors = []; - // some run time checks to help the end users. - if (!(0, has_1$1.default)(lexerDefinition, exports.DEFAULT_MODE)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized without a <" + - exports.DEFAULT_MODE + - "> property in its definition\n", - type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE - }); - } - if (!(0, has_1$1.default)(lexerDefinition, exports.MODES)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized without a <" + - exports.MODES + - "> property in its definition\n", - type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY - }); - } - if ((0, has_1$1.default)(lexerDefinition, exports.MODES) && - (0, has_1$1.default)(lexerDefinition, exports.DEFAULT_MODE) && - !(0, has_1$1.default)(lexerDefinition.modes, lexerDefinition.defaultMode)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized with a ".concat(exports.DEFAULT_MODE, ": <").concat(lexerDefinition.defaultMode, ">") + - "which does not exist\n", - type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST - }); - } - if ((0, has_1$1.default)(lexerDefinition, exports.MODES)) { - (0, forEach_1.default)(lexerDefinition.modes, function (currModeValue, currModeName) { - (0, forEach_1.default)(currModeValue, function (currTokType, currIdx) { - if ((0, isUndefined_1.default)(currTokType)) { - errors.push({ - message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" + - "<".concat(currModeName, "> at index: <").concat(currIdx, ">\n"), - type: lexer_public_1.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED - }); - } - }); - }); - } - return errors; - } - exports.performRuntimeChecks = performRuntimeChecks; - function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { - var warnings = []; - var hasAnyLineBreak = false; - var allTokenTypes = (0, compact_1$1.default)((0, flatten_1.default)((0, values_1.default)(lexerDefinition.modes))); - var concreteTokenTypes = (0, reject_1$1.default)(allTokenTypes, function (currType) { return currType[PATTERN] === lexer_public_1.Lexer.NA; }); - var terminatorCharCodes = getCharCodes(lineTerminatorCharacters); - if (trackLines) { - (0, forEach_1.default)(concreteTokenTypes, function (tokType) { - var currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes); - if (currIssue !== false) { - var message = buildLineBreakIssueMessage(tokType, currIssue); - var warningDescriptor = { - message: message, - type: currIssue.issue, - tokenType: tokType - }; - warnings.push(warningDescriptor); - } - else { - // we don't want to attempt to scan if the user explicitly specified the line_breaks option. - if ((0, has_1$1.default)(tokType, "LINE_BREAKS")) { - if (tokType.LINE_BREAKS === true) { - hasAnyLineBreak = true; - } - } - else { - if ((0, reg_exp_1.canMatchCharCode)(terminatorCharCodes, tokType.PATTERN)) { - hasAnyLineBreak = true; - } - } - } - }); - } - if (trackLines && !hasAnyLineBreak) { - warnings.push({ - message: "Warning: No LINE_BREAKS Found.\n" + - "\tThis Lexer has been defined to track line and column information,\n" + - "\tBut none of the Token Types can be identified as matching a line terminator.\n" + - "\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n" + - "\tfor details.", - type: lexer_public_1.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS - }); - } - return warnings; - } - exports.performWarningRuntimeChecks = performWarningRuntimeChecks; - function cloneEmptyGroups(emptyGroups) { - var clonedResult = {}; - var groupKeys = (0, keys_1$1.default)(emptyGroups); - (0, forEach_1.default)(groupKeys, function (currKey) { - var currGroupValue = emptyGroups[currKey]; - /* istanbul ignore else */ - if ((0, isArray_1.default)(currGroupValue)) { - clonedResult[currKey] = []; - } - else { - throw Error("non exhaustive match"); - } - }); - return clonedResult; - } - exports.cloneEmptyGroups = cloneEmptyGroups; - // TODO: refactor to avoid duplication - function isCustomPattern(tokenType) { - var pattern = tokenType.PATTERN; - /* istanbul ignore else */ - if ((0, isRegExp_1.default)(pattern)) { - return false; - } - else if ((0, isFunction_1$1.default)(pattern)) { - // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object - return true; - } - else if ((0, has_1$1.default)(pattern, "exec")) { - // ICustomPattern - return true; - } - else if ((0, isString_1.default)(pattern)) { - return false; - } - else { - throw Error("non exhaustive match"); - } - } - exports.isCustomPattern = isCustomPattern; - function isShortPattern(pattern) { - if ((0, isString_1.default)(pattern) && pattern.length === 1) { - return pattern.charCodeAt(0); - } - else { - return false; - } - } - exports.isShortPattern = isShortPattern; - /** - * Faster than using a RegExp for default newline detection during lexing. - */ - exports.LineTerminatorOptimizedTester = { - // implements /\n|\r\n?/g.test - test: function (text) { - var len = text.length; - for (var i = this.lastIndex; i < len; i++) { - var c = text.charCodeAt(i); - if (c === 10) { - this.lastIndex = i + 1; - return true; - } - else if (c === 13) { - if (text.charCodeAt(i + 1) === 10) { - this.lastIndex = i + 2; - } - else { - this.lastIndex = i + 1; - } - return true; - } - } - return false; - }, - lastIndex: 0 - }; - function checkLineBreaksIssues(tokType, lineTerminatorCharCodes) { - if ((0, has_1$1.default)(tokType, "LINE_BREAKS")) { - // if the user explicitly declared the line_breaks option we will respect their choice - // and assume it is correct. - return false; - } - else { - /* istanbul ignore else */ - if ((0, isRegExp_1.default)(tokType.PATTERN)) { - try { - // TODO: why is the casting suddenly needed? - (0, reg_exp_1.canMatchCharCode)(lineTerminatorCharCodes, tokType.PATTERN); - } - catch (e) { - /* istanbul ignore next - to test this we would have to mock to throw an error */ - return { - issue: lexer_public_1.LexerDefinitionErrorType.IDENTIFY_TERMINATOR, - errMsg: e.message - }; - } - return false; - } - else if ((0, isString_1.default)(tokType.PATTERN)) { - // string literal patterns can always be analyzed to detect line terminator usage - return false; - } - else if (isCustomPattern(tokType)) { - // custom token types - return { issue: lexer_public_1.LexerDefinitionErrorType.CUSTOM_LINE_BREAK }; - } - else { - throw Error("non exhaustive match"); - } - } - } - function buildLineBreakIssueMessage(tokType, details) { - /* istanbul ignore else */ - if (details.issue === lexer_public_1.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) { - return ("Warning: unable to identify line terminator usage in pattern.\n" + - "\tThe problem is in the <".concat(tokType.name, "> Token Type\n") + - "\t Root cause: ".concat(details.errMsg, ".\n") + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR"); - } - else if (details.issue === lexer_public_1.LexerDefinitionErrorType.CUSTOM_LINE_BREAK) { - return ("Warning: A Custom Token Pattern should specify the option.\n" + - "\tThe problem is in the <".concat(tokType.name, "> Token Type\n") + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK"); - } - else { - throw Error("non exhaustive match"); - } - } - exports.buildLineBreakIssueMessage = buildLineBreakIssueMessage; - function getCharCodes(charsOrCodes) { - var charCodes = (0, map_1.default)(charsOrCodes, function (numOrString) { - if ((0, isString_1.default)(numOrString)) { - return numOrString.charCodeAt(0); - } - else { - return numOrString; - } - }); - return charCodes; - } - function addToMapOfArrays(map, key, value) { - if (map[key] === undefined) { - map[key] = [value]; - } - else { - map[key].push(value); - } - } - exports.minOptimizationVal = 256; - /** - * We are mapping charCode above ASCI (256) into buckets each in the size of 256. - * This is because ASCI are the most common start chars so each one of those will get its own - * possible token configs vector. - * - * Tokens starting with charCodes "above" ASCI are uncommon, so we can "afford" - * to place these into buckets of possible token configs, What we gain from - * this is avoiding the case of creating an optimization 'charCodeToPatternIdxToConfig' - * which would contain 10,000+ arrays of small size (e.g unicode Identifiers scenario). - * Our 'charCodeToPatternIdxToConfig' max size will now be: - * 256 + (2^16 / 2^8) - 1 === 511 - * - * note the hack for fast division integer part extraction - * See: https://stackoverflow.com/a/4228528 - */ - var charCodeToOptimizedIdxMap = []; - function charCodeToOptimizedIndex(charCode) { - return charCode < exports.minOptimizationVal - ? charCode - : charCodeToOptimizedIdxMap[charCode]; - } - exports.charCodeToOptimizedIndex = charCodeToOptimizedIndex; - /** - * This is a compromise between cold start / hot running performance - * Creating this array takes ~3ms on a modern machine, - * But if we perform the computation at runtime as needed the CSS Lexer benchmark - * performance degrades by ~10% - * - * TODO: Perhaps it should be lazy initialized only if a charCode > 255 is used. - */ - function initCharCodeToOptimizedIndexMap() { - if ((0, isEmpty_1.default)(charCodeToOptimizedIdxMap)) { - charCodeToOptimizedIdxMap = new Array(65536); - for (var i = 0; i < 65536; i++) { - charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i; - } - } - } - -} (lexer)); - return lexer; -} -/** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ + var outerPropTypes = outerMemoType && outerMemoType.propTypes; -function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; -} + if (outerPropTypes) { + checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps) + 'prop', getComponentNameFromType(outerMemoType)); + } + } + } + } -var last_1$1 = last; + if (current !== null) { + var prevProps = current.memoizedProps; -var tokens = {}; + if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload. + workInProgress.type === current.type )) { + didReceiveUpdate = false; -(function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isTokenType = exports.hasExtendingTokensTypesMapProperty = exports.hasExtendingTokensTypesProperty = exports.hasCategoriesProperty = exports.hasShortKeyProperty = exports.singleAssignCategoriesToksMap = exports.assignCategoriesMapProp = exports.assignCategoriesTokensProp = exports.assignTokenDefaultProps = exports.expandCategories = exports.augmentTokenTypes = exports.tokenIdxToClass = exports.tokenShortNameIdx = exports.tokenStructuredMatcherNoCategories = exports.tokenStructuredMatcher = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var compact_1$1 = __importDefault(compact_1); - var isArray_1 = __importDefault(isArray_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var difference_1$1 = __importDefault(difference_1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var has_1$1 = __importDefault(has_1); - var includes_1 = __importDefault(includes_1$2); - var clone_1 = __importDefault(clone_1$1); - function tokenStructuredMatcher(tokInstance, tokConstructor) { - var instanceType = tokInstance.tokenTypeIdx; - if (instanceType === tokConstructor.tokenTypeIdx) { - return true; - } - else { - return (tokConstructor.isParent === true && - tokConstructor.categoryMatchesMap[instanceType] === true); - } - } - exports.tokenStructuredMatcher = tokenStructuredMatcher; - // Optimized tokenMatcher in case our grammar does not use token categories - // Being so tiny it is much more likely to be in-lined and this avoid the function call overhead - function tokenStructuredMatcherNoCategories(token, tokType) { - return token.tokenTypeIdx === tokType.tokenTypeIdx; - } - exports.tokenStructuredMatcherNoCategories = tokenStructuredMatcherNoCategories; - exports.tokenShortNameIdx = 1; - exports.tokenIdxToClass = {}; - function augmentTokenTypes(tokenTypes) { - // collect the parent Token Types as well. - var tokenTypesAndParents = expandCategories(tokenTypes); - // add required tokenType and categoryMatches properties - assignTokenDefaultProps(tokenTypesAndParents); - // fill up the categoryMatches - assignCategoriesMapProp(tokenTypesAndParents); - assignCategoriesTokensProp(tokenTypesAndParents); - (0, forEach_1.default)(tokenTypesAndParents, function (tokType) { - tokType.isParent = tokType.categoryMatches.length > 0; - }); - } - exports.augmentTokenTypes = augmentTokenTypes; - function expandCategories(tokenTypes) { - var result = (0, clone_1.default)(tokenTypes); - var categories = tokenTypes; - var searching = true; - while (searching) { - categories = (0, compact_1$1.default)((0, flatten_1.default)((0, map_1.default)(categories, function (currTokType) { return currTokType.CATEGORIES; }))); - var newCategories = (0, difference_1$1.default)(categories, result); - result = result.concat(newCategories); - if ((0, isEmpty_1.default)(newCategories)) { - searching = false; - } - else { - categories = newCategories; - } + if (!checkScheduledUpdateOrContext(current, renderLanes)) { + // The pending lanes were cleared at the beginning of beginWork. We're + // about to bail out, but there might be other lanes that weren't + // included in the current render. Usually, the priority level of the + // remaining updates is accumulated during the evaluation of the + // component (i.e. when processing the update queue). But since since + // we're bailing out early *without* evaluating the component, we need + // to account for it here, too. Reset to the value of the current fiber. + // NOTE: This only applies to SimpleMemoComponent, not MemoComponent, + // because a MemoComponent fiber does not have hooks or an update queue; + // rather, it wraps around an inner component, which may or may not + // contains hooks. + // TODO: Move the reset at in beginWork out of the common path so that + // this is no longer necessary. + workInProgress.lanes = current.lanes; + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { + // This is a special case that only exists for legacy mode. + // See https://github.com/facebook/react/pull/19216. + didReceiveUpdate = true; + } } - return result; - } - exports.expandCategories = expandCategories; - function assignTokenDefaultProps(tokenTypes) { - (0, forEach_1.default)(tokenTypes, function (currTokType) { - if (!hasShortKeyProperty(currTokType)) { - exports.tokenIdxToClass[exports.tokenShortNameIdx] = currTokType; - currTokType.tokenTypeIdx = exports.tokenShortNameIdx++; - } - // CATEGORIES? : TokenType | TokenType[] - if (hasCategoriesProperty(currTokType) && - !(0, isArray_1.default)(currTokType.CATEGORIES) - // && - // !isUndefined(currTokType.CATEGORIES.PATTERN) - ) { - currTokType.CATEGORIES = [currTokType.CATEGORIES]; - } - if (!hasCategoriesProperty(currTokType)) { - currTokType.CATEGORIES = []; - } - if (!hasExtendingTokensTypesProperty(currTokType)) { - currTokType.categoryMatches = []; - } - if (!hasExtendingTokensTypesMapProperty(currTokType)) { - currTokType.categoryMatchesMap = {}; - } - }); - } - exports.assignTokenDefaultProps = assignTokenDefaultProps; - function assignCategoriesTokensProp(tokenTypes) { - (0, forEach_1.default)(tokenTypes, function (currTokType) { - // avoid duplications - currTokType.categoryMatches = []; - (0, forEach_1.default)(currTokType.categoryMatchesMap, function (val, key) { - currTokType.categoryMatches.push(exports.tokenIdxToClass[key].tokenTypeIdx); - }); - }); - } - exports.assignCategoriesTokensProp = assignCategoriesTokensProp; - function assignCategoriesMapProp(tokenTypes) { - (0, forEach_1.default)(tokenTypes, function (currTokType) { - singleAssignCategoriesToksMap([], currTokType); - }); - } - exports.assignCategoriesMapProp = assignCategoriesMapProp; - function singleAssignCategoriesToksMap(path, nextNode) { - (0, forEach_1.default)(path, function (pathNode) { - nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true; - }); - (0, forEach_1.default)(nextNode.CATEGORIES, function (nextCategory) { - var newPath = path.concat(nextNode); - // avoids infinite loops due to cyclic categories. - if (!(0, includes_1.default)(newPath, nextCategory)) { - singleAssignCategoriesToksMap(newPath, nextCategory); - } - }); - } - exports.singleAssignCategoriesToksMap = singleAssignCategoriesToksMap; - function hasShortKeyProperty(tokType) { - return (0, has_1$1.default)(tokType, "tokenTypeIdx"); - } - exports.hasShortKeyProperty = hasShortKeyProperty; - function hasCategoriesProperty(tokType) { - return (0, has_1$1.default)(tokType, "CATEGORIES"); - } - exports.hasCategoriesProperty = hasCategoriesProperty; - function hasExtendingTokensTypesProperty(tokType) { - return (0, has_1$1.default)(tokType, "categoryMatches"); - } - exports.hasExtendingTokensTypesProperty = hasExtendingTokensTypesProperty; - function hasExtendingTokensTypesMapProperty(tokType) { - return (0, has_1$1.default)(tokType, "categoryMatchesMap"); - } - exports.hasExtendingTokensTypesMapProperty = hasExtendingTokensTypesMapProperty; - function isTokenType(tokType) { - return (0, has_1$1.default)(tokType, "tokenTypeIdx"); + } + + return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes); } - exports.isTokenType = isTokenType; - -} (tokens)); -var lexer_errors_public = {}; + function updateOffscreenComponent(current, workInProgress, renderLanes) { + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; + var prevState = current !== null ? current.memoizedState : null; -Object.defineProperty(lexer_errors_public, "__esModule", { value: true }); -lexer_errors_public.defaultLexerErrorProvider = void 0; -lexer_errors_public.defaultLexerErrorProvider = { - buildUnableToPopLexerModeMessage: function (token) { - return "Unable to pop Lexer Mode after encountering Token ->".concat(token.image, "<- The Mode Stack is empty"); - }, - buildUnexpectedCharactersMessage: function (fullText, startOffset, length, line, column) { - return ("unexpected character: ->".concat(fullText.charAt(startOffset), "<- at offset: ").concat(startOffset, ",") + " skipped ".concat(length, " characters.")); - } -}; + if (nextProps.mode === 'hidden' || enableLegacyHidden ) { + // Rendering a hidden tree. + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + // In legacy sync mode, don't defer the subtree. Render it now. + var nextState = { + baseLanes: NoLanes, + cachePool: null + }; + workInProgress.memoizedState = nextState; -var hasRequiredLexer_public; + pushRenderLanes(workInProgress, renderLanes); + } else if (!includesSomeLane(renderLanes, OffscreenLane)) { + var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out + // and resume this tree later. -function requireLexer_public () { - if (hasRequiredLexer_public) return lexer_public; - hasRequiredLexer_public = 1; - (function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Lexer = exports.LexerDefinitionErrorType = void 0; - var lexer_1 = requireLexer(); - var noop_1$1 = __importDefault(noop_1); - var isEmpty_1 = __importDefault(isEmpty_1$1); - var isArray_1 = __importDefault(isArray_1$1); - var last_1 = __importDefault(last_1$1); - var reject_1$1 = __importDefault(reject_1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var keys_1$1 = __importDefault(keys_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var identity_1$1 = __importDefault(identity_1); - var assign_1 = __importDefault(assign_1$3); - var reduce_1 = __importDefault(reduce_1$1); - var clone_1 = __importDefault(clone_1$1); - var utils_1 = api$2; - var tokens_1 = tokens; - var lexer_errors_public_1 = lexer_errors_public; - var reg_exp_parser_1 = reg_exp_parser; - (function (LexerDefinitionErrorType) { - LexerDefinitionErrorType[LexerDefinitionErrorType["MISSING_PATTERN"] = 0] = "MISSING_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_PATTERN"] = 1] = "INVALID_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["EOI_ANCHOR_FOUND"] = 2] = "EOI_ANCHOR_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["UNSUPPORTED_FLAGS_FOUND"] = 3] = "UNSUPPORTED_FLAGS_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["DUPLICATE_PATTERNS_FOUND"] = 4] = "DUPLICATE_PATTERNS_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_GROUP_TYPE_FOUND"] = 5] = "INVALID_GROUP_TYPE_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["PUSH_MODE_DOES_NOT_EXIST"] = 6] = "PUSH_MODE_DOES_NOT_EXIST"; - LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"] = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"; - LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"] = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"; - LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"] = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"; - LexerDefinitionErrorType[LexerDefinitionErrorType["LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"] = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"; - LexerDefinitionErrorType[LexerDefinitionErrorType["SOI_ANCHOR_FOUND"] = 11] = "SOI_ANCHOR_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["EMPTY_MATCH_PATTERN"] = 12] = "EMPTY_MATCH_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["NO_LINE_BREAKS_FLAGS"] = 13] = "NO_LINE_BREAKS_FLAGS"; - LexerDefinitionErrorType[LexerDefinitionErrorType["UNREACHABLE_PATTERN"] = 14] = "UNREACHABLE_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["IDENTIFY_TERMINATOR"] = 15] = "IDENTIFY_TERMINATOR"; - LexerDefinitionErrorType[LexerDefinitionErrorType["CUSTOM_LINE_BREAK"] = 16] = "CUSTOM_LINE_BREAK"; - })(exports.LexerDefinitionErrorType || (exports.LexerDefinitionErrorType = {})); - var DEFAULT_LEXER_CONFIG = { - deferDefinitionErrorsHandling: false, - positionTracking: "full", - lineTerminatorsPattern: /\n|\r\n?/g, - lineTerminatorCharacters: ["\n", "\r"], - ensureOptimizations: false, - safeMode: false, - errorMessageProvider: lexer_errors_public_1.defaultLexerErrorProvider, - traceInitPerf: false, - skipValidations: false - }; - Object.freeze(DEFAULT_LEXER_CONFIG); - var Lexer = /** @class */ (function () { - function Lexer(lexerDefinition, config) { - if (config === void 0) { config = DEFAULT_LEXER_CONFIG; } - var _this = this; - this.lexerDefinition = lexerDefinition; - this.lexerDefinitionErrors = []; - this.lexerDefinitionWarning = []; - this.patternIdxToConfig = {}; - this.charCodeToPatternIdxToConfig = {}; - this.modes = []; - this.emptyGroups = {}; - this.trackStartLines = true; - this.trackEndLines = true; - this.hasCustom = false; - this.canModeBeOptimized = {}; - // Duplicated from the parser's perf trace trait to allow future extraction - // of the lexer to a separate package. - this.TRACE_INIT = function (phaseDesc, phaseImpl) { - // No need to optimize this using NOOP pattern because - // It is not called in a hot spot... - if (_this.traceInitPerf === true) { - _this.traceInitIndent++; - var indent = new Array(_this.traceInitIndent + 1).join("\t"); - if (_this.traceInitIndent < _this.traceInitMaxIdent) { - console.log("".concat(indent, "--> <").concat(phaseDesc, ">")); - } - var _a = (0, utils_1.timer)(phaseImpl), time = _a.time, value = _a.value; - /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */ - var traceMethod = time > 10 ? console.warn : console.log; - if (_this.traceInitIndent < _this.traceInitMaxIdent) { - traceMethod("".concat(indent, "<-- <").concat(phaseDesc, "> time: ").concat(time, "ms")); - } - _this.traceInitIndent--; - return value; - } - else { - return phaseImpl(); - } - }; - if (typeof config === "boolean") { - throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\n" + - "a boolean 2nd argument is no longer supported"); - } - // todo: defaults func? - this.config = (0, assign_1.default)({}, DEFAULT_LEXER_CONFIG, config); - var traceInitVal = this.config.traceInitPerf; - if (traceInitVal === true) { - this.traceInitMaxIdent = Infinity; - this.traceInitPerf = true; - } - else if (typeof traceInitVal === "number") { - this.traceInitMaxIdent = traceInitVal; - this.traceInitPerf = true; - } - this.traceInitIndent = -1; - this.TRACE_INIT("Lexer Constructor", function () { - var actualDefinition; - var hasOnlySingleMode = true; - _this.TRACE_INIT("Lexer Config handling", function () { - if (_this.config.lineTerminatorsPattern === - DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) { - // optimized built-in implementation for the defaults definition of lineTerminators - _this.config.lineTerminatorsPattern = lexer_1.LineTerminatorOptimizedTester; - } - else { - if (_this.config.lineTerminatorCharacters === - DEFAULT_LEXER_CONFIG.lineTerminatorCharacters) { - throw Error("Error: Missing property on the Lexer config.\n" + - "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS"); - } - } - if (config.safeMode && config.ensureOptimizations) { - throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.'); - } - _this.trackStartLines = /full|onlyStart/i.test(_this.config.positionTracking); - _this.trackEndLines = /full/i.test(_this.config.positionTracking); - // Convert SingleModeLexerDefinition into a IMultiModeLexerDefinition. - if ((0, isArray_1.default)(lexerDefinition)) { - actualDefinition = { - modes: { defaultMode: (0, clone_1.default)(lexerDefinition) }, - defaultMode: lexer_1.DEFAULT_MODE - }; - } - else { - // no conversion needed, input should already be a IMultiModeLexerDefinition - hasOnlySingleMode = false; - actualDefinition = (0, clone_1.default)(lexerDefinition); - } - }); - if (_this.config.skipValidations === false) { - _this.TRACE_INIT("performRuntimeChecks", function () { - _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat((0, lexer_1.performRuntimeChecks)(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters)); - }); - _this.TRACE_INIT("performWarningRuntimeChecks", function () { - _this.lexerDefinitionWarning = _this.lexerDefinitionWarning.concat((0, lexer_1.performWarningRuntimeChecks)(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters)); - }); - } - // for extra robustness to avoid throwing an none informative error message - actualDefinition.modes = actualDefinition.modes - ? actualDefinition.modes - : {}; - // an error of undefined TokenTypes will be detected in "performRuntimeChecks" above. - // this transformation is to increase robustness in the case of partially invalid lexer definition. - (0, forEach_1.default)(actualDefinition.modes, function (currModeValue, currModeName) { - actualDefinition.modes[currModeName] = (0, reject_1$1.default)(currModeValue, function (currTokType) { return (0, isUndefined_1.default)(currTokType); }); - }); - var allModeNames = (0, keys_1$1.default)(actualDefinition.modes); - (0, forEach_1.default)(actualDefinition.modes, function (currModDef, currModName) { - _this.TRACE_INIT("Mode: <".concat(currModName, "> processing"), function () { - _this.modes.push(currModName); - if (_this.config.skipValidations === false) { - _this.TRACE_INIT("validatePatterns", function () { - _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat((0, lexer_1.validatePatterns)(currModDef, allModeNames)); - }); - } - // If definition errors were encountered, the analysis phase may fail unexpectedly/ - // Considering a lexer with definition errors may never be used, there is no point - // to performing the analysis anyhow... - if ((0, isEmpty_1.default)(_this.lexerDefinitionErrors)) { - (0, tokens_1.augmentTokenTypes)(currModDef); - var currAnalyzeResult_1; - _this.TRACE_INIT("analyzeTokenTypes", function () { - currAnalyzeResult_1 = (0, lexer_1.analyzeTokenTypes)(currModDef, { - lineTerminatorCharacters: _this.config.lineTerminatorCharacters, - positionTracking: config.positionTracking, - ensureOptimizations: config.ensureOptimizations, - safeMode: config.safeMode, - tracer: _this.TRACE_INIT - }); - }); - _this.patternIdxToConfig[currModName] = - currAnalyzeResult_1.patternIdxToConfig; - _this.charCodeToPatternIdxToConfig[currModName] = - currAnalyzeResult_1.charCodeToPatternIdxToConfig; - _this.emptyGroups = (0, assign_1.default)({}, _this.emptyGroups, currAnalyzeResult_1.emptyGroups); - _this.hasCustom = currAnalyzeResult_1.hasCustom || _this.hasCustom; - _this.canModeBeOptimized[currModName] = - currAnalyzeResult_1.canBeOptimized; - } - }); - }); - _this.defaultMode = actualDefinition.defaultMode; - if (!(0, isEmpty_1.default)(_this.lexerDefinitionErrors) && - !_this.config.deferDefinitionErrorsHandling) { - var allErrMessages = (0, map_1.default)(_this.lexerDefinitionErrors, function (error) { - return error.message; - }); - var allErrMessagesString = allErrMessages.join("-----------------------\n"); - throw new Error("Errors detected in definition of Lexer:\n" + allErrMessagesString); - } - // Only print warning if there are no errors, This will avoid pl - (0, forEach_1.default)(_this.lexerDefinitionWarning, function (warningDescriptor) { - (0, utils_1.PRINT_WARNING)(warningDescriptor.message); - }); - _this.TRACE_INIT("Choosing sub-methods implementations", function () { - // Choose the relevant internal implementations for this specific parser. - // These implementations should be in-lined by the JavaScript engine - // to provide optimal performance in each scenario. - if (lexer_1.SUPPORT_STICKY) { - _this.chopInput = identity_1$1.default; - _this.match = _this.matchWithTest; - } - else { - _this.updateLastIndex = noop_1$1.default; - _this.match = _this.matchWithExec; - } - if (hasOnlySingleMode) { - _this.handleModes = noop_1$1.default; - } - if (_this.trackStartLines === false) { - _this.computeNewColumn = identity_1$1.default; - } - if (_this.trackEndLines === false) { - _this.updateTokenEndLineColumnLocation = noop_1$1.default; - } - if (/full/i.test(_this.config.positionTracking)) { - _this.createTokenInstance = _this.createFullToken; - } - else if (/onlyStart/i.test(_this.config.positionTracking)) { - _this.createTokenInstance = _this.createStartOnlyToken; - } - else if (/onlyOffset/i.test(_this.config.positionTracking)) { - _this.createTokenInstance = _this.createOffsetOnlyToken; - } - else { - throw Error("Invalid config option: \"".concat(_this.config.positionTracking, "\"")); - } - if (_this.hasCustom) { - _this.addToken = _this.addTokenUsingPush; - _this.handlePayload = _this.handlePayloadWithCustom; - } - else { - _this.addToken = _this.addTokenUsingMemberAccess; - _this.handlePayload = _this.handlePayloadNoCustom; - } - }); - _this.TRACE_INIT("Failed Optimization Warnings", function () { - var unOptimizedModes = (0, reduce_1.default)(_this.canModeBeOptimized, function (cannotBeOptimized, canBeOptimized, modeName) { - if (canBeOptimized === false) { - cannotBeOptimized.push(modeName); - } - return cannotBeOptimized; - }, []); - if (config.ensureOptimizations && !(0, isEmpty_1.default)(unOptimizedModes)) { - throw Error("Lexer Modes: < ".concat(unOptimizedModes.join(", "), " > cannot be optimized.\n") + - '\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n' + - "\t Or inspect the console log for details on how to resolve these issues."); - } - }); - _this.TRACE_INIT("clearRegExpParserCache", function () { - (0, reg_exp_parser_1.clearRegExpParserCache)(); - }); - _this.TRACE_INIT("toFastProperties", function () { - (0, utils_1.toFastProperties)(_this); - }); - }); - } - Lexer.prototype.tokenize = function (text, initialMode) { - if (initialMode === void 0) { initialMode = this.defaultMode; } - if (!(0, isEmpty_1.default)(this.lexerDefinitionErrors)) { - var allErrMessages = (0, map_1.default)(this.lexerDefinitionErrors, function (error) { - return error.message; - }); - var allErrMessagesString = allErrMessages.join("-----------------------\n"); - throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" + - allErrMessagesString); - } - return this.tokenizeInternal(text, initialMode); - }; - // There is quite a bit of duplication between this and "tokenizeInternalLazy" - // This is intentional due to performance considerations. - // this method also used quite a bit of `!` none null assertions because it is too optimized - // for `tsc` to always understand it is "safe" - Lexer.prototype.tokenizeInternal = function (text, initialMode) { - var _this = this; - var i, j, k, matchAltImage, longerAlt, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, msg, match; - var orgText = text; - var orgLength = orgText.length; - var offset = 0; - var matchedTokensIndex = 0; - // initializing the tokensArray to the "guessed" size. - // guessing too little will still reduce the number of array re-sizes on pushes. - // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory - // but would still have a faster runtime by avoiding (All but one) array resizing. - var guessedNumberOfTokens = this.hasCustom - ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements. - : Math.floor(text.length / 10); - var matchedTokens = new Array(guessedNumberOfTokens); - var errors = []; - var line = this.trackStartLines ? 1 : undefined; - var column = this.trackStartLines ? 1 : undefined; - var groups = (0, lexer_1.cloneEmptyGroups)(this.emptyGroups); - var trackLines = this.trackStartLines; - var lineTerminatorPattern = this.config.lineTerminatorsPattern; - var currModePatternsLength = 0; - var patternIdxToConfig = []; - var currCharCodeToPatternIdxToConfig = []; - var modeStack = []; - var emptyArray = []; - Object.freeze(emptyArray); - var getPossiblePatterns; - function getPossiblePatternsSlow() { - return patternIdxToConfig; - } - function getPossiblePatternsOptimized(charCode) { - var optimizedCharIdx = (0, lexer_1.charCodeToOptimizedIndex)(charCode); - var possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx]; - if (possiblePatterns === undefined) { - return emptyArray; - } - else { - return possiblePatterns; - } - } - var pop_mode = function (popToken) { - // TODO: perhaps avoid this error in the edge case there is no more input? - if (modeStack.length === 1 && - // if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition" - // So no error should occur. - popToken.tokenType.PUSH_MODE === undefined) { - // if we try to pop the last mode there lexer will no longer have ANY mode. - // thus the pop is ignored, an error will be created and the lexer will continue parsing in the previous mode. - var msg_1 = _this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken); - errors.push({ - offset: popToken.startOffset, - line: popToken.startLine, - column: popToken.startColumn, - length: popToken.image.length, - message: msg_1 - }); - } - else { - modeStack.pop(); - var newMode = (0, last_1.default)(modeStack); - patternIdxToConfig = _this.patternIdxToConfig[newMode]; - currCharCodeToPatternIdxToConfig = - _this.charCodeToPatternIdxToConfig[newMode]; - currModePatternsLength = patternIdxToConfig.length; - var modeCanBeOptimized = _this.canModeBeOptimized[newMode] && _this.config.safeMode === false; - if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { - getPossiblePatterns = getPossiblePatternsOptimized; - } - else { - getPossiblePatterns = getPossiblePatternsSlow; - } - } - }; - function push_mode(newMode) { - modeStack.push(newMode); - currCharCodeToPatternIdxToConfig = - this.charCodeToPatternIdxToConfig[newMode]; - patternIdxToConfig = this.patternIdxToConfig[newMode]; - currModePatternsLength = patternIdxToConfig.length; - currModePatternsLength = patternIdxToConfig.length; - var modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false; - if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { - getPossiblePatterns = getPossiblePatternsOptimized; - } - else { - getPossiblePatterns = getPossiblePatternsSlow; - } - } - // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not - // seem to matter performance wise. - push_mode.call(this, initialMode); - var currConfig; - while (offset < orgLength) { - matchedImage = null; - var nextCharCode = orgText.charCodeAt(offset); - var chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode); - var chosenPatternsLength = chosenPatternIdxToConfig.length; - for (i = 0; i < chosenPatternsLength; i++) { - currConfig = chosenPatternIdxToConfig[i]; - var currPattern = currConfig.pattern; - payload = null; - // manually in-lined because > 600 chars won't be in-lined in V8 - var singleCharCode = currConfig.short; - if (singleCharCode !== false) { - if (nextCharCode === singleCharCode) { - // single character string - matchedImage = currPattern; - } - } - else if (currConfig.isCustom === true) { - match = currPattern.exec(orgText, offset, matchedTokens, groups); - if (match !== null) { - matchedImage = match[0]; - if (match.payload !== undefined) { - payload = match.payload; - } - } - else { - matchedImage = null; - } - } - else { - this.updateLastIndex(currPattern, offset); - matchedImage = this.match(currPattern, text, offset); - } - if (matchedImage !== null) { - // even though this pattern matched we must try a another longer alternative. - // this can be used to prioritize keywords over identifiers - longerAlt = currConfig.longerAlt; - if (longerAlt !== undefined) { - // TODO: micro optimize, avoid extra prop access - // by saving/linking longerAlt on the original config? - var longerAltLength = longerAlt.length; - for (k = 0; k < longerAltLength; k++) { - var longerAltConfig = patternIdxToConfig[longerAlt[k]]; - var longerAltPattern = longerAltConfig.pattern; - altPayload = null; - // single Char can never be a longer alt so no need to test it. - // manually in-lined because > 600 chars won't be in-lined in V8 - if (longerAltConfig.isCustom === true) { - match = longerAltPattern.exec(orgText, offset, matchedTokens, groups); - if (match !== null) { - matchAltImage = match[0]; - if (match.payload !== undefined) { - altPayload = match.payload; - } - } - else { - matchAltImage = null; - } - } - else { - this.updateLastIndex(longerAltPattern, offset); - matchAltImage = this.match(longerAltPattern, text, offset); - } - if (matchAltImage && matchAltImage.length > matchedImage.length) { - matchedImage = matchAltImage; - payload = altPayload; - currConfig = longerAltConfig; - // Exit the loop early after matching one of the longer alternatives - // The first matched alternative takes precedence - break; - } - } - } - break; - } - } - // successful match - if (matchedImage !== null) { - imageLength = matchedImage.length; - group = currConfig.group; - if (group !== undefined) { - tokType = currConfig.tokenTypeIdx; - // TODO: "offset + imageLength" and the new column may be computed twice in case of "full" location information inside - // createFullToken method - newToken = this.createTokenInstance(matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength); - this.handlePayload(newToken, payload); - // TODO: optimize NOOP in case there are no special groups? - if (group === false) { - matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken); - } - else { - groups[group].push(newToken); - } - } - text = this.chopInput(text, imageLength); - offset = offset + imageLength; - // TODO: with newlines the column may be assigned twice - column = this.computeNewColumn(column, imageLength); - if (trackLines === true && currConfig.canLineTerminator === true) { - var numOfLTsInMatch = 0; - var foundTerminator = void 0; - var lastLTEndOffset = void 0; - lineTerminatorPattern.lastIndex = 0; - do { - foundTerminator = lineTerminatorPattern.test(matchedImage); - if (foundTerminator === true) { - lastLTEndOffset = lineTerminatorPattern.lastIndex - 1; - numOfLTsInMatch++; - } - } while (foundTerminator === true); - if (numOfLTsInMatch !== 0) { - line = line + numOfLTsInMatch; - column = imageLength - lastLTEndOffset; - this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength); - } - } - // will be NOOP if no modes present - this.handleModes(currConfig, pop_mode, push_mode, newToken); - } - else { - // error recovery, drop characters until we identify a valid token's start point - var errorStartOffset = offset; - var errorLine = line; - var errorColumn = column; - var foundResyncPoint = false; - while (!foundResyncPoint && offset < orgLength) { - // drop chars until we succeed in matching something - orgText.charCodeAt(offset); - // Identity Func (when sticky flag is enabled) - text = this.chopInput(text, 1); - offset++; - for (j = 0; j < currModePatternsLength; j++) { - var currConfig_1 = patternIdxToConfig[j]; - var currPattern = currConfig_1.pattern; - // manually in-lined because > 600 chars won't be in-lined in V8 - var singleCharCode = currConfig_1.short; - if (singleCharCode !== false) { - if (orgText.charCodeAt(offset) === singleCharCode) { - // single character string - foundResyncPoint = true; - } - } - else if (currConfig_1.isCustom === true) { - foundResyncPoint = - currPattern.exec(orgText, offset, matchedTokens, groups) !== null; - } - else { - this.updateLastIndex(currPattern, offset); - foundResyncPoint = currPattern.exec(text) !== null; - } - if (foundResyncPoint === true) { - break; - } - } - } - errLength = offset - errorStartOffset; - // at this point we either re-synced or reached the end of the input text - msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText, errorStartOffset, errLength, errorLine, errorColumn); - errors.push({ - offset: errorStartOffset, - line: errorLine, - column: errorColumn, - length: errLength, - message: msg - }); - } - } - // if we do have custom patterns which push directly into the - // TODO: custom tokens should not push directly?? - if (!this.hasCustom) { - // if we guessed a too large size for the tokens array this will shrink it to the right size. - matchedTokens.length = matchedTokensIndex; - } - return { - tokens: matchedTokens, - groups: groups, - errors: errors - }; - }; - Lexer.prototype.handleModes = function (config, pop_mode, push_mode, newToken) { - if (config.pop === true) { - // need to save the PUSH_MODE property as if the mode is popped - // patternIdxToPopMode is updated to reflect the new mode after popping the stack - var pushMode = config.push; - pop_mode(newToken); - if (pushMode !== undefined) { - push_mode.call(this, pushMode); - } - } - else if (config.push !== undefined) { - push_mode.call(this, config.push); - } - }; - Lexer.prototype.chopInput = function (text, length) { - return text.substring(length); - }; - Lexer.prototype.updateLastIndex = function (regExp, newLastIndex) { - regExp.lastIndex = newLastIndex; - }; - // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler - Lexer.prototype.updateTokenEndLineColumnLocation = function (newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) { - var lastCharIsLT, fixForEndingInLT; - if (group !== undefined) { - // a none skipped multi line Token, need to update endLine/endColumn - lastCharIsLT = lastLTIdx === imageLength - 1; - fixForEndingInLT = lastCharIsLT ? -1 : 0; - if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) { - // if a token ends in a LT that last LT only affects the line numbering of following Tokens - newToken.endLine = line + fixForEndingInLT; - // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd) - // inclusive to exclusive range. - newToken.endColumn = column - 1 + -fixForEndingInLT; - } - // else single LT in the last character of a token, no need to modify the endLine/EndColumn - } - }; - Lexer.prototype.computeNewColumn = function (oldColumn, imageLength) { - return oldColumn + imageLength; - }; - Lexer.prototype.createOffsetOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType) { - return { - image: image, - startOffset: startOffset, - tokenTypeIdx: tokenTypeIdx, - tokenType: tokenType - }; - }; - Lexer.prototype.createStartOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) { - return { - image: image, - startOffset: startOffset, - startLine: startLine, - startColumn: startColumn, - tokenTypeIdx: tokenTypeIdx, - tokenType: tokenType - }; - }; - Lexer.prototype.createFullToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) { - return { - image: image, - startOffset: startOffset, - endOffset: startOffset + imageLength - 1, - startLine: startLine, - endLine: startLine, - startColumn: startColumn, - endColumn: startColumn + imageLength - 1, - tokenTypeIdx: tokenTypeIdx, - tokenType: tokenType - }; - }; - Lexer.prototype.addTokenUsingPush = function (tokenVector, index, tokenToAdd) { - tokenVector.push(tokenToAdd); - return index; - }; - Lexer.prototype.addTokenUsingMemberAccess = function (tokenVector, index, tokenToAdd) { - tokenVector[index] = tokenToAdd; - index++; - return index; - }; - Lexer.prototype.handlePayloadNoCustom = function (token, payload) { }; - Lexer.prototype.handlePayloadWithCustom = function (token, payload) { - if (payload !== null) { - token.payload = payload; - } - }; - Lexer.prototype.matchWithTest = function (pattern, text, offset) { - var found = pattern.test(text); - if (found === true) { - return text.substring(offset, pattern.lastIndex); - } - return null; - }; - Lexer.prototype.matchWithExec = function (pattern, text) { - var regExpArray = pattern.exec(text); - return regExpArray !== null ? regExpArray[0] : null; - }; - Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will" + - "be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace."; - Lexer.NA = /NOT_APPLICABLE/; - return Lexer; - }()); - exports.Lexer = Lexer; - -} (lexer_public)); - return lexer_public; -} - -(function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.tokenMatcher = exports.createTokenInstance = exports.EOF = exports.createToken = exports.hasTokenLabel = exports.tokenName = exports.tokenLabel = void 0; - var isString_1 = __importDefault(isString_1$1); - var has_1$1 = __importDefault(has_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var lexer_public_1 = requireLexer_public(); - var tokens_1 = tokens; - function tokenLabel(tokType) { - if (hasTokenLabel(tokType)) { - return tokType.LABEL; - } - else { - return tokType.name; - } - } - exports.tokenLabel = tokenLabel; - function tokenName(tokType) { - return tokType.name; - } - exports.tokenName = tokenName; - function hasTokenLabel(obj) { - return (0, isString_1.default)(obj.LABEL) && obj.LABEL !== ""; - } - exports.hasTokenLabel = hasTokenLabel; - var PARENT = "parent"; - var CATEGORIES = "categories"; - var LABEL = "label"; - var GROUP = "group"; - var PUSH_MODE = "push_mode"; - var POP_MODE = "pop_mode"; - var LONGER_ALT = "longer_alt"; - var LINE_BREAKS = "line_breaks"; - var START_CHARS_HINT = "start_chars_hint"; - function createToken(config) { - return createTokenInternal(config); - } - exports.createToken = createToken; - function createTokenInternal(config) { - var pattern = config.pattern; - var tokenType = {}; - tokenType.name = config.name; - if (!(0, isUndefined_1.default)(pattern)) { - tokenType.PATTERN = pattern; - } - if ((0, has_1$1.default)(config, PARENT)) { - throw ("The parent property is no longer supported.\n" + - "See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details."); - } - if ((0, has_1$1.default)(config, CATEGORIES)) { - // casting to ANY as this will be fixed inside `augmentTokenTypes`` - tokenType.CATEGORIES = config[CATEGORIES]; - } - (0, tokens_1.augmentTokenTypes)([tokenType]); - if ((0, has_1$1.default)(config, LABEL)) { - tokenType.LABEL = config[LABEL]; - } - if ((0, has_1$1.default)(config, GROUP)) { - tokenType.GROUP = config[GROUP]; - } - if ((0, has_1$1.default)(config, POP_MODE)) { - tokenType.POP_MODE = config[POP_MODE]; - } - if ((0, has_1$1.default)(config, PUSH_MODE)) { - tokenType.PUSH_MODE = config[PUSH_MODE]; - } - if ((0, has_1$1.default)(config, LONGER_ALT)) { - tokenType.LONGER_ALT = config[LONGER_ALT]; - } - if ((0, has_1$1.default)(config, LINE_BREAKS)) { - tokenType.LINE_BREAKS = config[LINE_BREAKS]; - } - if ((0, has_1$1.default)(config, START_CHARS_HINT)) { - tokenType.START_CHARS_HINT = config[START_CHARS_HINT]; - } - return tokenType; - } - exports.EOF = createToken({ name: "EOF", pattern: lexer_public_1.Lexer.NA }); - (0, tokens_1.augmentTokenTypes)([exports.EOF]); - function createTokenInstance(tokType, image, startOffset, endOffset, startLine, endLine, startColumn, endColumn) { - return { - image: image, - startOffset: startOffset, - endOffset: endOffset, - startLine: startLine, - endLine: endLine, - startColumn: startColumn, - endColumn: endColumn, - tokenTypeIdx: tokType.tokenTypeIdx, - tokenType: tokType - }; - } - exports.createTokenInstance = createTokenInstance; - function tokenMatcher(token, tokType) { - return (0, tokens_1.tokenStructuredMatcher)(token, tokType); - } - exports.tokenMatcher = tokenMatcher; - -} (tokens_public)); + var nextBaseLanes; -var errors_public = {}; + if (prevState !== null) { + var prevBaseLanes = prevState.baseLanes; + nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes); + } else { + nextBaseLanes = renderLanes; + } // Schedule this fiber to re-render at offscreen priority. Then bailout. -(function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.defaultGrammarValidatorErrorProvider = exports.defaultGrammarResolverErrorProvider = exports.defaultParserErrorProvider = void 0; - var tokens_public_1 = tokens_public; - var first_1 = __importDefault(first.exports); - var map_1 = __importDefault(map_1$4); - var reduce_1 = __importDefault(reduce_1$1); - var gast_1 = api$1; - var gast_2 = api$1; - exports.defaultParserErrorProvider = { - buildMismatchTokenMessage: function (_a) { - var expected = _a.expected, actual = _a.actual; _a.previous; _a.ruleName; - var hasLabel = (0, tokens_public_1.hasTokenLabel)(expected); - var expectedMsg = hasLabel - ? "--> ".concat((0, tokens_public_1.tokenLabel)(expected), " <--") - : "token of type --> ".concat(expected.name, " <--"); - var msg = "Expecting ".concat(expectedMsg, " but found --> '").concat(actual.image, "' <--"); - return msg; - }, - buildNotAllInputParsedMessage: function (_a) { - var firstRedundant = _a.firstRedundant; _a.ruleName; - return "Redundant input, expecting EOF but found: " + firstRedundant.image; - }, - buildNoViableAltMessage: function (_a) { - var expectedPathsPerAlt = _a.expectedPathsPerAlt, actual = _a.actual; _a.previous; var customUserDescription = _a.customUserDescription; _a.ruleName; - var errPrefix = "Expecting: "; - // TODO: issue: No Viable Alternative Error may have incomplete details. #502 - var actualText = (0, first_1.default)(actual).image; - var errSuffix = "\nbut found: '" + actualText + "'"; - if (customUserDescription) { - return errPrefix + customUserDescription + errSuffix; - } - else { - var allLookAheadPaths = (0, reduce_1.default)(expectedPathsPerAlt, function (result, currAltPaths) { return result.concat(currAltPaths); }, []); - var nextValidTokenSequences = (0, map_1.default)(allLookAheadPaths, function (currPath) { - return "[".concat((0, map_1.default)(currPath, function (currTokenType) { return (0, tokens_public_1.tokenLabel)(currTokenType); }).join(", "), "]"); - }); - var nextValidSequenceItems = (0, map_1.default)(nextValidTokenSequences, function (itemMsg, idx) { return " ".concat(idx + 1, ". ").concat(itemMsg); }); - var calculatedDescription = "one of these possible Token sequences:\n".concat(nextValidSequenceItems.join("\n")); - return errPrefix + calculatedDescription + errSuffix; - } - }, - buildEarlyExitMessage: function (_a) { - var expectedIterationPaths = _a.expectedIterationPaths, actual = _a.actual, customUserDescription = _a.customUserDescription; _a.ruleName; - var errPrefix = "Expecting: "; - // TODO: issue: No Viable Alternative Error may have incomplete details. #502 - var actualText = (0, first_1.default)(actual).image; - var errSuffix = "\nbut found: '" + actualText + "'"; - if (customUserDescription) { - return errPrefix + customUserDescription + errSuffix; - } - else { - var nextValidTokenSequences = (0, map_1.default)(expectedIterationPaths, function (currPath) { - return "[".concat((0, map_1.default)(currPath, function (currTokenType) { return (0, tokens_public_1.tokenLabel)(currTokenType); }).join(","), "]"); - }); - var calculatedDescription = "expecting at least one iteration which starts with one of these possible Token sequences::\n " + - "<".concat(nextValidTokenSequences.join(" ,"), ">"); - return errPrefix + calculatedDescription + errSuffix; - } - } - }; - Object.freeze(exports.defaultParserErrorProvider); - exports.defaultGrammarResolverErrorProvider = { - buildRuleNotFoundError: function (topLevelRule, undefinedRule) { - var msg = "Invalid grammar, reference to a rule which is not defined: ->" + - undefinedRule.nonTerminalName + - "<-\n" + - "inside top level rule: ->" + - topLevelRule.name + - "<-"; - return msg; - } - }; - exports.defaultGrammarValidatorErrorProvider = { - buildDuplicateFoundError: function (topLevelRule, duplicateProds) { - function getExtraProductionArgument(prod) { - if (prod instanceof gast_1.Terminal) { - return prod.terminalType.name; - } - else if (prod instanceof gast_1.NonTerminal) { - return prod.nonTerminalName; - } - else { - return ""; - } - } - var topLevelName = topLevelRule.name; - var duplicateProd = (0, first_1.default)(duplicateProds); - var index = duplicateProd.idx; - var dslName = (0, gast_2.getProductionDslName)(duplicateProd); - var extraArgument = getExtraProductionArgument(duplicateProd); - var hasExplicitIndex = index > 0; - var msg = "->".concat(dslName).concat(hasExplicitIndex ? index : "", "<- ").concat(extraArgument ? "with argument: ->".concat(extraArgument, "<-") : "", "\n appears more than once (").concat(duplicateProds.length, " times) in the top level rule: ->").concat(topLevelName, "<-. \n For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES \n "); - // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings... - msg = msg.replace(/[ \t]+/g, " "); - msg = msg.replace(/\s\s+/g, "\n"); - return msg; - }, - buildNamespaceConflictError: function (rule) { - var errMsg = "Namespace conflict found in grammar.\n" + - "The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <".concat(rule.name, ">.\n") + - "To resolve this make sure each Terminal and Non-Terminal names are unique\n" + - "This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\n" + - "and Non-Terminal names start with a lower case letter."; - return errMsg; - }, - buildAlternationPrefixAmbiguityError: function (options) { - var pathMsg = (0, map_1.default)(options.prefixPath, function (currTok) { - return (0, tokens_public_1.tokenLabel)(currTok); - }).join(", "); - var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; - var errMsg = "Ambiguous alternatives: <".concat(options.ambiguityIndices.join(" ,"), "> due to common lookahead prefix\n") + - "in inside <").concat(options.topLevelRule.name, "> Rule,\n") + - "<".concat(pathMsg, "> may appears as a prefix path in all these alternatives.\n") + - "See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\n" + - "For Further details."; - return errMsg; - }, - buildAlternationAmbiguityError: function (options) { - var pathMsg = (0, map_1.default)(options.prefixPath, function (currtok) { - return (0, tokens_public_1.tokenLabel)(currtok); - }).join(", "); - var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; - var currMessage = "Ambiguous Alternatives Detected: <".concat(options.ambiguityIndices.join(" ,"), "> in ") + - " inside <".concat(options.topLevelRule.name, "> Rule,\n") + - "<".concat(pathMsg, "> may appears as a prefix path in all these alternatives.\n"); - currMessage = - currMessage + - "See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\n" + - "For Further details."; - return currMessage; - }, - buildEmptyRepetitionError: function (options) { - var dslName = (0, gast_2.getProductionDslName)(options.repetition); - if (options.repetition.idx !== 0) { - dslName += options.repetition.idx; - } - var errMsg = "The repetition <".concat(dslName, "> within Rule <").concat(options.topLevelRule.name, "> can never consume any tokens.\n") + - "This could lead to an infinite loop."; - return errMsg; - }, - // TODO: remove - `errors_public` from nyc.config.js exclude - // once this method is fully removed from this file - buildTokenNameError: function (options) { - /* istanbul ignore next */ - return "deprecated"; - }, - buildEmptyAlternationError: function (options) { - var errMsg = "Ambiguous empty alternative: <".concat(options.emptyChoiceIdx + 1, ">") + - " in inside <").concat(options.topLevelRule.name, "> Rule.\n") + - "Only the last alternative may be an empty alternative."; - return errMsg; - }, - buildTooManyAlternativesError: function (options) { - var errMsg = "An Alternation cannot have more than 256 alternatives:\n" + - " inside <").concat(options.topLevelRule.name, "> Rule.\n has ").concat(options.alternation.definition.length + 1, " alternatives."); - return errMsg; - }, - buildLeftRecursionError: function (options) { - var ruleName = options.topLevelRule.name; - var pathNames = (0, map_1.default)(options.leftRecursionPath, function (currRule) { return currRule.name; }); - var leftRecursivePath = "".concat(ruleName, " --> ").concat(pathNames - .concat([ruleName]) - .join(" --> ")); - var errMsg = "Left Recursion found in grammar.\n" + - "rule: <".concat(ruleName, "> can be invoked from itself (directly or indirectly)\n") + - "without consuming any Tokens. The grammar path that causes this is: \n ".concat(leftRecursivePath, "\n") + - " To fix this refactor your grammar to remove the left recursion.\n" + - "see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring."; - return errMsg; - }, - // TODO: remove - `errors_public` from nyc.config.js exclude - // once this method is fully removed from this file - buildInvalidRuleNameError: function (options) { - /* istanbul ignore next */ - return "deprecated"; - }, - buildDuplicateRuleNameError: function (options) { - var ruleName; - if (options.topLevelRule instanceof gast_1.Rule) { - ruleName = options.topLevelRule.name; - } - else { - ruleName = options.topLevelRule; - } - var errMsg = "Duplicate definition, rule: ->".concat(ruleName, "<- is already defined in the grammar: ->").concat(options.grammarName, "<-"); - return errMsg; - } - }; - -} (errors_public)); -var gast_resolver_public = {}; + workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane); + var _nextState = { + baseLanes: nextBaseLanes, + cachePool: spawnedCachePool + }; + workInProgress.memoizedState = _nextState; + workInProgress.updateQueue = null; + // to avoid a push/pop misalignment. + -var resolver = {}; + pushRenderLanes(workInProgress, nextBaseLanes); -var hasRequiredResolver; + return null; + } else { + // This is the second render. The surrounding visible content has already + // committed. Now we resume rendering the hidden tree. + // Rendering at offscreen, so we can clear the base lanes. + var _nextState2 = { + baseLanes: NoLanes, + cachePool: null + }; + workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out. -function requireResolver () { - if (hasRequiredResolver) return resolver; - hasRequiredResolver = 1; - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(resolver, "__esModule", { value: true }); - resolver.GastRefResolverVisitor = resolver.resolveGrammar = void 0; - var parser_1 = requireParser(); - var forEach_1 = __importDefault(forEach_1$4); - var values_1 = __importDefault(values_1$1); - var gast_1 = api$1; - function resolveGrammar(topLevels, errMsgProvider) { - var refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider); - refResolver.resolveRefs(); - return refResolver.errors; - } - resolver.resolveGrammar = resolveGrammar; - var GastRefResolverVisitor = /** @class */ (function (_super) { - __extends(GastRefResolverVisitor, _super); - function GastRefResolverVisitor(nameToTopRule, errMsgProvider) { - var _this = _super.call(this) || this; - _this.nameToTopRule = nameToTopRule; - _this.errMsgProvider = errMsgProvider; - _this.errors = []; - return _this; - } - GastRefResolverVisitor.prototype.resolveRefs = function () { - var _this = this; - (0, forEach_1.default)((0, values_1.default)(this.nameToTopRule), function (prod) { - _this.currTopLevel = prod; - prod.accept(_this); - }); - }; - GastRefResolverVisitor.prototype.visitNonTerminal = function (node) { - var ref = this.nameToTopRule[node.nonTerminalName]; - if (!ref) { - var msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node); - this.errors.push({ - message: msg, - type: parser_1.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, - ruleName: this.currTopLevel.name, - unresolvedRefName: node.nonTerminalName - }); - } - else { - node.referencedRule = ref; - } - }; - return GastRefResolverVisitor; - }(gast_1.GAstVisitor)); - resolver.GastRefResolverVisitor = GastRefResolverVisitor; - - return resolver; -} + var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes; -var checks = {}; + pushRenderLanes(workInProgress, subtreeRenderLanes); + } + } else { + // Rendering a visible tree. + var _subtreeRenderLanes; -/** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ + if (prevState !== null) { + // We're going from hidden -> visible. + _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes); -function arrayAggregator$1(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; -} + workInProgress.memoizedState = null; + } else { + // We weren't previously hidden, and we still aren't, so there's nothing + // special to do. Need to push to the stack regardless, though, to avoid + // a push/pop misalignment. + _subtreeRenderLanes = renderLanes; + } -var _arrayAggregator = arrayAggregator$1; + pushRenderLanes(workInProgress, _subtreeRenderLanes); + } -var baseEach = _baseEach; + { + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } + } -/** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ -function baseAggregator$1(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; -} + function updateFragment(current, workInProgress, renderLanes) { + var nextChildren = workInProgress.pendingProps; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } -var _baseAggregator = baseAggregator$1; + function updateMode(current, workInProgress, renderLanes) { + var nextChildren = workInProgress.pendingProps.children; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } -var arrayAggregator = _arrayAggregator, - baseAggregator = _baseAggregator, - baseIteratee = _baseIteratee, - isArray$2 = isArray_1$1; + function updateProfiler(current, workInProgress, renderLanes) { + { + workInProgress.flags |= Update; -/** - * Creates a function like `_.groupBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ -function createAggregator$1(setter, initializer) { - return function(collection, iteratee) { - var func = isArray$2(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; + { + // Reset effect durations for the next eventual effect phase. + // These are reset during render to allow the DevTools commit hook a chance to read them, + var stateNode = workInProgress.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + } - return func(collection, setter, baseIteratee(iteratee), accumulator); - }; -} + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; + } -var _createAggregator = createAggregator$1; + function markRef$1(current, workInProgress) { + var ref = workInProgress.ref; -var baseAssignValue = _baseAssignValue, - createAggregator = _createAggregator; + if (current === null && ref !== null || current !== null && current.ref !== ref) { + // Schedule a Ref effect + workInProgress.flags |= Ref; -/** Used for built-in method references. */ -var objectProto$2 = Object.prototype; + { + workInProgress.flags |= RefStatic; + } + } + } -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$2.hasOwnProperty; + function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) { + { + if (workInProgress.type !== workInProgress.elementType) { + // Lazy component props can't be validated in createElement + // because they're only guaranteed to be resolved here. + var innerPropTypes = Component.propTypes; -/** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } - * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ -var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty$2.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); - } -}); + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(Component)); + } + } + } -var groupBy_1$1 = groupBy; + var context; -var baseFlatten$2 = _baseFlatten, - map = map_1$4; + { + var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); + context = getMaskedContext(workInProgress, unmaskedContext); + } -/** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ -function flatMap(collection, iteratee) { - return baseFlatten$2(map(collection, iteratee), 1); -} + var nextChildren; + var hasId; + prepareToReadContext(workInProgress, renderLanes); -var flatMap_1 = flatMap; + { + markComponentRenderStarted(workInProgress); + } -var lookahead = {}; + { + ReactCurrentOwner$1.current = workInProgress; + setIsRendering(true); + nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); + hasId = checkDidRenderIdHook(); -var interpreter = {}; + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); -var baseSlice$1 = _baseSlice, - toInteger = toInteger_1; + try { + nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } -/** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] - * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ -function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice$1(array, 0, n < 0 ? 0 : n); -} + setIsRendering(false); + } -var dropRight_1$1 = dropRight; + { + markComponentRenderStopped(); + } -/* istanbul ignore next */ var __extends$2 = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$4 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(interpreter, "__esModule", { value: true }); -interpreter.nextPossibleTokensAfter = interpreter.possiblePathsFrom = interpreter.NextTerminalAfterAtLeastOneSepWalker = interpreter.NextTerminalAfterAtLeastOneWalker = interpreter.NextTerminalAfterManySepWalker = interpreter.NextTerminalAfterManyWalker = interpreter.AbstractNextTerminalAfterProductionWalker = interpreter.NextAfterTokenWalker = interpreter.AbstractNextPossibleTokensWalker = void 0; -var rest_1 = rest; -var first_1$1 = __importDefault$4(first.exports); -var isEmpty_1 = __importDefault$4(isEmpty_1$1); -var dropRight_1 = __importDefault$4(dropRight_1$1); -var drop_1 = __importDefault$4(drop_1$2); -var last_1 = __importDefault$4(last_1$1); -var forEach_1 = __importDefault$4(forEach_1$4); -var clone_1 = __importDefault$4(clone_1$1); -var first_2 = first$2; -var gast_1$1 = api$1; -var AbstractNextPossibleTokensWalker = /** @class */ (function (_super) { - __extends$2(AbstractNextPossibleTokensWalker, _super); - function AbstractNextPossibleTokensWalker(topProd, path) { - var _this = _super.call(this) /* istanbul ignore next */ || this; - _this.topProd = topProd; - _this.path = path; - _this.possibleTokTypes = []; - _this.nextProductionName = ""; - _this.nextProductionOccurrence = 0; - _this.found = false; - _this.isAtEndOfPath = false; - return _this; - } - AbstractNextPossibleTokensWalker.prototype.startWalking = function () { - this.found = false; - if (this.path.ruleStack[0] !== this.topProd.name) { - throw Error("The path does not start with the walker's top Rule!"); - } - // immutable for the win - this.ruleStack = (0, clone_1.default)(this.path.ruleStack).reverse(); // intelij bug requires assertion - this.occurrenceStack = (0, clone_1.default)(this.path.occurrenceStack).reverse(); // intelij bug requires assertion - // already verified that the first production is valid, we now seek the 2nd production - this.ruleStack.pop(); - this.occurrenceStack.pop(); - this.updateExpectedNext(); - this.walk(this.topProd); - return this.possibleTokTypes; - }; - AbstractNextPossibleTokensWalker.prototype.walk = function (prod, prevRest) { - if (prevRest === void 0) { prevRest = []; } - // stop scanning once we found the path - if (!this.found) { - _super.prototype.walk.call(this, prod, prevRest); - } - }; - AbstractNextPossibleTokensWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { - // found the next production, need to keep walking in it - if (refProd.referencedRule.name === this.nextProductionName && - refProd.idx === this.nextProductionOccurrence) { - var fullRest = currRest.concat(prevRest); - this.updateExpectedNext(); - this.walk(refProd.referencedRule, fullRest); - } - }; - AbstractNextPossibleTokensWalker.prototype.updateExpectedNext = function () { - // need to consume the Terminal - if ((0, isEmpty_1.default)(this.ruleStack)) { - // must reset nextProductionXXX to avoid walking down another Top Level production while what we are - // really seeking is the last Terminal... - this.nextProductionName = ""; - this.nextProductionOccurrence = 0; - this.isAtEndOfPath = true; - } - else { - this.nextProductionName = this.ruleStack.pop(); - this.nextProductionOccurrence = this.occurrenceStack.pop(); - } - }; - return AbstractNextPossibleTokensWalker; -}(rest_1.RestWalker)); -interpreter.AbstractNextPossibleTokensWalker = AbstractNextPossibleTokensWalker; -var NextAfterTokenWalker = /** @class */ (function (_super) { - __extends$2(NextAfterTokenWalker, _super); - function NextAfterTokenWalker(topProd, path) { - var _this = _super.call(this, topProd, path) /* istanbul ignore next */ || this; - _this.path = path; - _this.nextTerminalName = ""; - _this.nextTerminalOccurrence = 0; - _this.nextTerminalName = _this.path.lastTok.name; - _this.nextTerminalOccurrence = _this.path.lastTokOccurrence; - return _this; - } - NextAfterTokenWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { - if (this.isAtEndOfPath && - terminal.terminalType.name === this.nextTerminalName && - terminal.idx === this.nextTerminalOccurrence && - !this.found) { - var fullRest = currRest.concat(prevRest); - var restProd = new gast_1$1.Alternative({ definition: fullRest }); - this.possibleTokTypes = (0, first_2.first)(restProd); - this.found = true; - } - }; - return NextAfterTokenWalker; -}(AbstractNextPossibleTokensWalker)); -interpreter.NextAfterTokenWalker = NextAfterTokenWalker; -/** - * This walker only "walks" a single "TOP" level in the Grammar Ast, this means - * it never "follows" production refs - */ -var AbstractNextTerminalAfterProductionWalker = /** @class */ (function (_super) { - __extends$2(AbstractNextTerminalAfterProductionWalker, _super); - function AbstractNextTerminalAfterProductionWalker(topRule, occurrence) { - var _this = _super.call(this) /* istanbul ignore next */ || this; - _this.topRule = topRule; - _this.occurrence = occurrence; - _this.result = { - token: undefined, - occurrence: undefined, - isEndOfRule: undefined - }; - return _this; - } - AbstractNextTerminalAfterProductionWalker.prototype.startWalking = function () { - this.walk(this.topRule); - return this.result; - }; - return AbstractNextTerminalAfterProductionWalker; -}(rest_1.RestWalker)); -interpreter.AbstractNextTerminalAfterProductionWalker = AbstractNextTerminalAfterProductionWalker; -var NextTerminalAfterManyWalker = /** @class */ (function (_super) { - __extends$2(NextTerminalAfterManyWalker, _super); - function NextTerminalAfterManyWalker() { - return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this; - } - NextTerminalAfterManyWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { - if (manyProd.idx === this.occurrence) { - var firstAfterMany = (0, first_1$1.default)(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterMany === undefined; - if (firstAfterMany instanceof gast_1$1.Terminal) { - this.result.token = firstAfterMany.terminalType; - this.result.occurrence = firstAfterMany.idx; - } - } - else { - _super.prototype.walkMany.call(this, manyProd, currRest, prevRest); - } - }; - return NextTerminalAfterManyWalker; -}(AbstractNextTerminalAfterProductionWalker)); -interpreter.NextTerminalAfterManyWalker = NextTerminalAfterManyWalker; -var NextTerminalAfterManySepWalker = /** @class */ (function (_super) { - __extends$2(NextTerminalAfterManySepWalker, _super); - function NextTerminalAfterManySepWalker() { - return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this; - } - NextTerminalAfterManySepWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { - if (manySepProd.idx === this.occurrence) { - var firstAfterManySep = (0, first_1$1.default)(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterManySep === undefined; - if (firstAfterManySep instanceof gast_1$1.Terminal) { - this.result.token = firstAfterManySep.terminalType; - this.result.occurrence = firstAfterManySep.idx; - } - } - else { - _super.prototype.walkManySep.call(this, manySepProd, currRest, prevRest); - } - }; - return NextTerminalAfterManySepWalker; -}(AbstractNextTerminalAfterProductionWalker)); -interpreter.NextTerminalAfterManySepWalker = NextTerminalAfterManySepWalker; -var NextTerminalAfterAtLeastOneWalker = /** @class */ (function (_super) { - __extends$2(NextTerminalAfterAtLeastOneWalker, _super); - function NextTerminalAfterAtLeastOneWalker() { - return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this; - } - NextTerminalAfterAtLeastOneWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { - if (atLeastOneProd.idx === this.occurrence) { - var firstAfterAtLeastOne = (0, first_1$1.default)(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterAtLeastOne === undefined; - if (firstAfterAtLeastOne instanceof gast_1$1.Terminal) { - this.result.token = firstAfterAtLeastOne.terminalType; - this.result.occurrence = firstAfterAtLeastOne.idx; - } - } - else { - _super.prototype.walkAtLeastOne.call(this, atLeastOneProd, currRest, prevRest); - } - }; - return NextTerminalAfterAtLeastOneWalker; -}(AbstractNextTerminalAfterProductionWalker)); -interpreter.NextTerminalAfterAtLeastOneWalker = NextTerminalAfterAtLeastOneWalker; -// TODO: reduce code duplication in the AfterWalkers -var NextTerminalAfterAtLeastOneSepWalker = /** @class */ (function (_super) { - __extends$2(NextTerminalAfterAtLeastOneSepWalker, _super); - function NextTerminalAfterAtLeastOneSepWalker() { - return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this; - } - NextTerminalAfterAtLeastOneSepWalker.prototype.walkAtLeastOneSep = function (atleastOneSepProd, currRest, prevRest) { - if (atleastOneSepProd.idx === this.occurrence) { - var firstAfterfirstAfterAtLeastOneSep = (0, first_1$1.default)(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === undefined; - if (firstAfterfirstAfterAtLeastOneSep instanceof gast_1$1.Terminal) { - this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType; - this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx; - } - } - else { - _super.prototype.walkAtLeastOneSep.call(this, atleastOneSepProd, currRest, prevRest); - } - }; - return NextTerminalAfterAtLeastOneSepWalker; -}(AbstractNextTerminalAfterProductionWalker)); -interpreter.NextTerminalAfterAtLeastOneSepWalker = NextTerminalAfterAtLeastOneSepWalker; -function possiblePathsFrom(targetDef, maxLength, currPath) { - if (currPath === void 0) { currPath = []; } - // avoid side effects - currPath = (0, clone_1.default)(currPath); - var result = []; - var i = 0; - // TODO: avoid inner funcs - function remainingPathWith(nextDef) { - return nextDef.concat((0, drop_1.default)(targetDef, i + 1)); - } - // TODO: avoid inner funcs - function getAlternativesForProd(definition) { - var alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath); - return result.concat(alternatives); - } - /** - * Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the - * following (rest) of the targetDef. - * - * For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the - * the optional production. - */ - while (currPath.length < maxLength && i < targetDef.length) { - var prod = targetDef[i]; - /* istanbul ignore else */ - if (prod instanceof gast_1$1.Alternative) { - return getAlternativesForProd(prod.definition); - } - else if (prod instanceof gast_1$1.NonTerminal) { - return getAlternativesForProd(prod.definition); - } - else if (prod instanceof gast_1$1.Option) { - result = getAlternativesForProd(prod.definition); - } - else if (prod instanceof gast_1$1.RepetitionMandatory) { - var newDef = prod.definition.concat([ - new gast_1$1.Repetition({ - definition: prod.definition - }) - ]); - return getAlternativesForProd(newDef); - } - else if (prod instanceof gast_1$1.RepetitionMandatoryWithSeparator) { - var newDef = [ - new gast_1$1.Alternative({ definition: prod.definition }), - new gast_1$1.Repetition({ - definition: [new gast_1$1.Terminal({ terminalType: prod.separator })].concat(prod.definition) - }) - ]; - return getAlternativesForProd(newDef); - } - else if (prod instanceof gast_1$1.RepetitionWithSeparator) { - var newDef = prod.definition.concat([ - new gast_1$1.Repetition({ - definition: [new gast_1$1.Terminal({ terminalType: prod.separator })].concat(prod.definition) - }) - ]); - result = getAlternativesForProd(newDef); - } - else if (prod instanceof gast_1$1.Repetition) { - var newDef = prod.definition.concat([ - new gast_1$1.Repetition({ - definition: prod.definition - }) - ]); - result = getAlternativesForProd(newDef); - } - else if (prod instanceof gast_1$1.Alternation) { - (0, forEach_1.default)(prod.definition, function (currAlt) { - // TODO: this is a limited check for empty alternatives - // It would prevent a common case of infinite loops during parser initialization. - // However **in-directly** empty alternatives may still cause issues. - if ((0, isEmpty_1.default)(currAlt.definition) === false) { - result = getAlternativesForProd(currAlt.definition); - } - }); - return result; - } - else if (prod instanceof gast_1$1.Terminal) { - currPath.push(prod.terminalType); - } - else { - throw Error("non exhaustive match"); - } - i++; - } - result.push({ - partialPath: currPath, - suffixDef: (0, drop_1.default)(targetDef, i) - }); - return result; -} -interpreter.possiblePathsFrom = possiblePathsFrom; -function nextPossibleTokensAfter(initialDef, tokenVector, tokMatcher, maxLookAhead) { - var EXIT_NON_TERMINAL = "EXIT_NONE_TERMINAL"; - // to avoid creating a new Array each time. - var EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL]; - var EXIT_ALTERNATIVE = "EXIT_ALTERNATIVE"; - var foundCompletePath = false; - var tokenVectorLength = tokenVector.length; - var minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1; - var result = []; - var possiblePaths = []; - possiblePaths.push({ - idx: -1, - def: initialDef, - ruleStack: [], - occurrenceStack: [] - }); - while (!(0, isEmpty_1.default)(possiblePaths)) { - var currPath = possiblePaths.pop(); - // skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead) - if (currPath === EXIT_ALTERNATIVE) { - if (foundCompletePath && - (0, last_1.default)(possiblePaths).idx <= minimalAlternativesIndex) { - // remove irrelevant alternative - possiblePaths.pop(); - } - continue; - } - var currDef = currPath.def; - var currIdx = currPath.idx; - var currRuleStack = currPath.ruleStack; - var currOccurrenceStack = currPath.occurrenceStack; - // For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT - if ((0, isEmpty_1.default)(currDef)) { - continue; - } - var prod = currDef[0]; - /* istanbul ignore else */ - if (prod === EXIT_NON_TERMINAL) { - var nextPath = { - idx: currIdx, - def: (0, drop_1.default)(currDef), - ruleStack: (0, dropRight_1.default)(currRuleStack), - occurrenceStack: (0, dropRight_1.default)(currOccurrenceStack) - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_1$1.Terminal) { - /* istanbul ignore else */ - if (currIdx < tokenVectorLength - 1) { - var nextIdx = currIdx + 1; - var actualToken = tokenVector[nextIdx]; - if (tokMatcher(actualToken, prod.terminalType)) { - var nextPath = { - idx: nextIdx, - def: (0, drop_1.default)(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - // end of the line - } - else if (currIdx === tokenVectorLength - 1) { - // IGNORE ABOVE ELSE - result.push({ - nextTokenType: prod.terminalType, - nextTokenOccurrence: prod.idx, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }); - foundCompletePath = true; - } - else { - throw Error("non exhaustive match"); - } - } - else if (prod instanceof gast_1$1.NonTerminal) { - var newRuleStack = (0, clone_1.default)(currRuleStack); - newRuleStack.push(prod.nonTerminalName); - var newOccurrenceStack = (0, clone_1.default)(currOccurrenceStack); - newOccurrenceStack.push(prod.idx); - var nextPath = { - idx: currIdx, - def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, (0, drop_1.default)(currDef)), - ruleStack: newRuleStack, - occurrenceStack: newOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_1$1.Option) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: (0, drop_1.default)(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWithout); - // required marker to avoid backtracking paths whose higher priority alternatives already matched - possiblePaths.push(EXIT_ALTERNATIVE); - var nextPathWith = { - idx: currIdx, - def: prod.definition.concat((0, drop_1.default)(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof gast_1$1.RepetitionMandatory) { - // TODO:(THE NEW operators here take a while...) (convert once?) - var secondIteration = new gast_1$1.Repetition({ - definition: prod.definition, - idx: prod.idx - }); - var nextDef = prod.definition.concat([secondIteration], (0, drop_1.default)(currDef)); - var nextPath = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_1$1.RepetitionMandatoryWithSeparator) { - // TODO:(THE NEW operators here take a while...) (convert once?) - var separatorGast = new gast_1$1.Terminal({ - terminalType: prod.separator - }); - var secondIteration = new gast_1$1.Repetition({ - definition: [separatorGast].concat(prod.definition), - idx: prod.idx - }); - var nextDef = prod.definition.concat([secondIteration], (0, drop_1.default)(currDef)); - var nextPath = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_1$1.RepetitionWithSeparator) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: (0, drop_1.default)(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWithout); - // required marker to avoid backtracking paths whose higher priority alternatives already matched - possiblePaths.push(EXIT_ALTERNATIVE); - var separatorGast = new gast_1$1.Terminal({ - terminalType: prod.separator - }); - var nthRepetition = new gast_1$1.Repetition({ - definition: [separatorGast].concat(prod.definition), - idx: prod.idx - }); - var nextDef = prod.definition.concat([nthRepetition], (0, drop_1.default)(currDef)); - var nextPathWith = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof gast_1$1.Repetition) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: (0, drop_1.default)(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWithout); - // required marker to avoid backtracking paths whose higher priority alternatives already matched - possiblePaths.push(EXIT_ALTERNATIVE); - // TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis? - var nthRepetition = new gast_1$1.Repetition({ - definition: prod.definition, - idx: prod.idx - }); - var nextDef = prod.definition.concat([nthRepetition], (0, drop_1.default)(currDef)); - var nextPathWith = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof gast_1$1.Alternation) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - for (var i = prod.definition.length - 1; i >= 0; i--) { - var currAlt = prod.definition[i]; - var currAltPath = { - idx: currIdx, - def: currAlt.definition.concat((0, drop_1.default)(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(currAltPath); - possiblePaths.push(EXIT_ALTERNATIVE); - } - } - else if (prod instanceof gast_1$1.Alternative) { - possiblePaths.push({ - idx: currIdx, - def: prod.definition.concat((0, drop_1.default)(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }); - } - else if (prod instanceof gast_1$1.Rule) { - // last because we should only encounter at most a single one of these per invocation. - possiblePaths.push(expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack)); - } - else { - throw Error("non exhaustive match"); - } - } - return result; -} -interpreter.nextPossibleTokensAfter = nextPossibleTokensAfter; -function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) { - var newRuleStack = (0, clone_1.default)(currRuleStack); - newRuleStack.push(topRule.name); - var newCurrOccurrenceStack = (0, clone_1.default)(currOccurrenceStack); - // top rule is always assumed to have been called with occurrence index 1 - newCurrOccurrenceStack.push(1); - return { - idx: currIdx, - def: topRule.definition, - ruleStack: newRuleStack, - occurrenceStack: newCurrOccurrenceStack - }; -} + if (current !== null && !didReceiveUpdate) { + bailoutHooks(current, workInProgress, renderLanes); + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } -(function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.areTokenCategoriesNotUsed = exports.isStrictPrefixOfPath = exports.containsPath = exports.getLookaheadPathsForOptionalProd = exports.getLookaheadPathsForOr = exports.lookAheadSequenceFromAlternatives = exports.buildSingleAlternativeLookaheadFunction = exports.buildAlternativesLookAheadFunc = exports.buildLookaheadFuncForOptionalProd = exports.buildLookaheadFuncForOr = exports.getProdType = exports.PROD_TYPE = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var every_1 = __importDefault(every_1$1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var has_1$1 = __importDefault(has_1); - var reduce_1 = __importDefault(reduce_1$1); - var interpreter_1 = interpreter; - var rest_1 = rest; - var tokens_1 = tokens; - var gast_1 = api$1; - var gast_2 = api$1; - var PROD_TYPE; - (function (PROD_TYPE) { - PROD_TYPE[PROD_TYPE["OPTION"] = 0] = "OPTION"; - PROD_TYPE[PROD_TYPE["REPETITION"] = 1] = "REPETITION"; - PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY"] = 2] = "REPETITION_MANDATORY"; - PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY_WITH_SEPARATOR"] = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR"; - PROD_TYPE[PROD_TYPE["REPETITION_WITH_SEPARATOR"] = 4] = "REPETITION_WITH_SEPARATOR"; - PROD_TYPE[PROD_TYPE["ALTERNATION"] = 5] = "ALTERNATION"; - })(PROD_TYPE = exports.PROD_TYPE || (exports.PROD_TYPE = {})); - function getProdType(prod) { - /* istanbul ignore else */ - if (prod instanceof gast_1.Option) { - return PROD_TYPE.OPTION; - } - else if (prod instanceof gast_1.Repetition) { - return PROD_TYPE.REPETITION; - } - else if (prod instanceof gast_1.RepetitionMandatory) { - return PROD_TYPE.REPETITION_MANDATORY; - } - else if (prod instanceof gast_1.RepetitionMandatoryWithSeparator) { - return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR; - } - else if (prod instanceof gast_1.RepetitionWithSeparator) { - return PROD_TYPE.REPETITION_WITH_SEPARATOR; - } - else if (prod instanceof gast_1.Alternation) { - return PROD_TYPE.ALTERNATION; - } - else { - throw Error("non exhaustive match"); - } - } - exports.getProdType = getProdType; - function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) { - var lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead); - var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths) - ? tokens_1.tokenStructuredMatcherNoCategories - : tokens_1.tokenStructuredMatcher; - return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher, dynamicTokensEnabled); - } - exports.buildLookaheadFuncForOr = buildLookaheadFuncForOr; - /** - * When dealing with an Optional production (OPTION/MANY/2nd iteration of AT_LEAST_ONE/...) we need to compare - * the lookahead "inside" the production and the lookahead immediately "after" it in the same top level rule (context free). - * - * Example: given a production: - * ABC(DE)?DF - * - * The optional '(DE)?' should only be entered if we see 'DE'. a single Token 'D' is not sufficient to distinguish between the two - * alternatives. - * - * @returns A Lookahead function which will return true IFF the parser should parse the Optional production. - */ - function buildLookaheadFuncForOptionalProd(occurrence, ruleGrammar, k, dynamicTokensEnabled, prodType, lookaheadBuilder) { - var lookAheadPaths = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k); - var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths) - ? tokens_1.tokenStructuredMatcherNoCategories - : tokens_1.tokenStructuredMatcher; - return lookaheadBuilder(lookAheadPaths[0], tokenMatcher, dynamicTokensEnabled); - } - exports.buildLookaheadFuncForOptionalProd = buildLookaheadFuncForOptionalProd; - function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { - var numOfAlts = alts.length; - var areAllOneTokenLookahead = (0, every_1.default)(alts, function (currAlt) { - return (0, every_1.default)(currAlt, function (currPath) { - return currPath.length === 1; - }); - }); - // This version takes into account the predicates as well. - if (hasPredicates) { - /** - * @returns {number} - The chosen alternative index - */ - return function (orAlts) { - // unfortunately the predicates must be extracted every single time - // as they cannot be cached due to references to parameters(vars) which are no longer valid. - // note that in the common case of no predicates, no cpu time will be wasted on this (see else block) - var predicates = (0, map_1.default)(orAlts, function (currAlt) { return currAlt.GATE; }); - for (var t = 0; t < numOfAlts; t++) { - var currAlt = alts[t]; - var currNumOfPaths = currAlt.length; - var currPredicate = predicates[t]; - if (currPredicate !== undefined && currPredicate.call(this) === false) { - // if the predicate does not match there is no point in checking the paths - continue; - } - nextPath: for (var j = 0; j < currNumOfPaths; j++) { - var currPath = currAlt[j]; - var currPathLength = currPath.length; - for (var i = 0; i < currPathLength; i++) { - var nextToken = this.LA(i + 1); - if (tokenMatcher(nextToken, currPath[i]) === false) { - // mismatch in current path - // try the next pth - continue nextPath; - } - } - // found a full path that matches. - // this will also work for an empty ALT as the loop will be skipped - return t; - } - // none of the paths for the current alternative matched - // try the next alternative - } - // none of the alternatives could be matched - return undefined; - }; - } - else if (areAllOneTokenLookahead && !dynamicTokensEnabled) { - // optimized (common) case of all the lookaheads paths requiring only - // a single token lookahead. These Optimizations cannot work if dynamically defined Tokens are used. - var singleTokenAlts = (0, map_1.default)(alts, function (currAlt) { - return (0, flatten_1.default)(currAlt); - }); - var choiceToAlt_1 = (0, reduce_1.default)(singleTokenAlts, function (result, currAlt, idx) { - (0, forEach_1.default)(currAlt, function (currTokType) { - if (!(0, has_1$1.default)(result, currTokType.tokenTypeIdx)) { - result[currTokType.tokenTypeIdx] = idx; - } - (0, forEach_1.default)(currTokType.categoryMatches, function (currExtendingType) { - if (!(0, has_1$1.default)(result, currExtendingType)) { - result[currExtendingType] = idx; - } - }); - }); - return result; - }, {}); - /** - * @returns {number} - The chosen alternative index - */ - return function () { - var nextToken = this.LA(1); - return choiceToAlt_1[nextToken.tokenTypeIdx]; - }; - } - else { - // optimized lookahead without needing to check the predicates at all. - // this causes code duplication which is intentional to improve performance. - /** - * @returns {number} - The chosen alternative index - */ - return function () { - for (var t = 0; t < numOfAlts; t++) { - var currAlt = alts[t]; - var currNumOfPaths = currAlt.length; - nextPath: for (var j = 0; j < currNumOfPaths; j++) { - var currPath = currAlt[j]; - var currPathLength = currPath.length; - for (var i = 0; i < currPathLength; i++) { - var nextToken = this.LA(i + 1); - if (tokenMatcher(nextToken, currPath[i]) === false) { - // mismatch in current path - // try the next pth - continue nextPath; - } - } - // found a full path that matches. - // this will also work for an empty ALT as the loop will be skipped - return t; - } - // none of the paths for the current alternative matched - // try the next alternative - } - // none of the alternatives could be matched - return undefined; - }; - } - } - exports.buildAlternativesLookAheadFunc = buildAlternativesLookAheadFunc; - function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled) { - var areAllOneTokenLookahead = (0, every_1.default)(alt, function (currPath) { - return currPath.length === 1; - }); - var numOfPaths = alt.length; - // optimized (common) case of all the lookaheads paths requiring only - // a single token lookahead. - if (areAllOneTokenLookahead && !dynamicTokensEnabled) { - var singleTokensTypes = (0, flatten_1.default)(alt); - if (singleTokensTypes.length === 1 && - (0, isEmpty_1.default)(singleTokensTypes[0].categoryMatches)) { - var expectedTokenType = singleTokensTypes[0]; - var expectedTokenUniqueKey_1 = expectedTokenType.tokenTypeIdx; - return function () { - return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey_1; - }; - } - else { - var choiceToAlt_2 = (0, reduce_1.default)(singleTokensTypes, function (result, currTokType, idx) { - result[currTokType.tokenTypeIdx] = true; - (0, forEach_1.default)(currTokType.categoryMatches, function (currExtendingType) { - result[currExtendingType] = true; - }); - return result; - }, []); - return function () { - var nextToken = this.LA(1); - return choiceToAlt_2[nextToken.tokenTypeIdx] === true; - }; - } - } - else { - return function () { - nextPath: for (var j = 0; j < numOfPaths; j++) { - var currPath = alt[j]; - var currPathLength = currPath.length; - for (var i = 0; i < currPathLength; i++) { - var nextToken = this.LA(i + 1); - if (tokenMatcher(nextToken, currPath[i]) === false) { - // mismatch in current path - // try the next pth - continue nextPath; - } - } - // found a full path that matches. - return true; - } - // none of the paths matched - return false; - }; - } - } - exports.buildSingleAlternativeLookaheadFunction = buildSingleAlternativeLookaheadFunction; - var RestDefinitionFinderWalker = /** @class */ (function (_super) { - __extends(RestDefinitionFinderWalker, _super); - function RestDefinitionFinderWalker(topProd, targetOccurrence, targetProdType) { - var _this = _super.call(this) || this; - _this.topProd = topProd; - _this.targetOccurrence = targetOccurrence; - _this.targetProdType = targetProdType; - return _this; - } - RestDefinitionFinderWalker.prototype.startWalking = function () { - this.walk(this.topProd); - return this.restDef; - }; - RestDefinitionFinderWalker.prototype.checkIsTarget = function (node, expectedProdType, currRest, prevRest) { - if (node.idx === this.targetOccurrence && - this.targetProdType === expectedProdType) { - this.restDef = currRest.concat(prevRest); - return true; - } - // performance optimization, do not iterate over the entire Grammar ast after we have found the target - return false; - }; - RestDefinitionFinderWalker.prototype.walkOption = function (optionProd, currRest, prevRest) { - if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) { - _super.prototype.walkOption.call(this, optionProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { - if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) { - _super.prototype.walkOption.call(this, atLeastOneProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) { - if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) { - _super.prototype.walkOption.call(this, atLeastOneSepProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { - if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) { - _super.prototype.walkOption.call(this, manyProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { - if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) { - _super.prototype.walkOption.call(this, manySepProd, currRest, prevRest); - } - }; - return RestDefinitionFinderWalker; - }(rest_1.RestWalker)); - /** - * Returns the definition of a target production in a top level level rule. - */ - var InsideDefinitionFinderVisitor = /** @class */ (function (_super) { - __extends(InsideDefinitionFinderVisitor, _super); - function InsideDefinitionFinderVisitor(targetOccurrence, targetProdType, targetRef) { - var _this = _super.call(this) || this; - _this.targetOccurrence = targetOccurrence; - _this.targetProdType = targetProdType; - _this.targetRef = targetRef; - _this.result = []; - return _this; - } - InsideDefinitionFinderVisitor.prototype.checkIsTarget = function (node, expectedProdName) { - if (node.idx === this.targetOccurrence && - this.targetProdType === expectedProdName && - (this.targetRef === undefined || node === this.targetRef)) { - this.result = node.definition; - } - }; - InsideDefinitionFinderVisitor.prototype.visitOption = function (node) { - this.checkIsTarget(node, PROD_TYPE.OPTION); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetition = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatory = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetitionWithSeparator = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR); - }; - InsideDefinitionFinderVisitor.prototype.visitAlternation = function (node) { - this.checkIsTarget(node, PROD_TYPE.ALTERNATION); - }; - return InsideDefinitionFinderVisitor; - }(gast_2.GAstVisitor)); - function initializeArrayOfArrays(size) { - var result = new Array(size); - for (var i = 0; i < size; i++) { - result[i] = []; - } - return result; - } - /** - * A sort of hash function between a Path in the grammar and a string. - * Note that this returns multiple "hashes" to support the scenario of token categories. - * - A single path with categories may match multiple **actual** paths. - */ - function pathToHashKeys(path) { - var keys = [""]; - for (var i = 0; i < path.length; i++) { - var tokType = path[i]; - var longerKeys = []; - for (var j = 0; j < keys.length; j++) { - var currShorterKey = keys[j]; - longerKeys.push(currShorterKey + "_" + tokType.tokenTypeIdx); - for (var t = 0; t < tokType.categoryMatches.length; t++) { - var categoriesKeySuffix = "_" + tokType.categoryMatches[t]; - longerKeys.push(currShorterKey + categoriesKeySuffix); - } - } - keys = longerKeys; - } - return keys; - } - /** - * Imperative style due to being called from a hot spot - */ - function isUniquePrefixHash(altKnownPathsKeys, searchPathKeys, idx) { - for (var currAltIdx = 0; currAltIdx < altKnownPathsKeys.length; currAltIdx++) { - // We only want to test vs the other alternatives - if (currAltIdx === idx) { - continue; - } - var otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx]; - for (var searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) { - var searchKey = searchPathKeys[searchIdx]; - if (otherAltKnownPathsKeys[searchKey] === true) { - return false; - } - } - } - // None of the SearchPathKeys were found in any of the other alternatives - return true; - } - function lookAheadSequenceFromAlternatives(altsDefs, k) { - var partialAlts = (0, map_1.default)(altsDefs, function (currAlt) { - return (0, interpreter_1.possiblePathsFrom)([currAlt], 1); - }); - var finalResult = initializeArrayOfArrays(partialAlts.length); - var altsHashes = (0, map_1.default)(partialAlts, function (currAltPaths) { - var dict = {}; - (0, forEach_1.default)(currAltPaths, function (item) { - var keys = pathToHashKeys(item.partialPath); - (0, forEach_1.default)(keys, function (currKey) { - dict[currKey] = true; - }); - }); - return dict; - }); - var newData = partialAlts; - // maxLookahead loop - for (var pathLength = 1; pathLength <= k; pathLength++) { - var currDataset = newData; - newData = initializeArrayOfArrays(currDataset.length); - var _loop_1 = function (altIdx) { - var currAltPathsAndSuffixes = currDataset[altIdx]; - // paths in current alternative loop - for (var currPathIdx = 0; currPathIdx < currAltPathsAndSuffixes.length; currPathIdx++) { - var currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath; - var suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef; - var prefixKeys = pathToHashKeys(currPathPrefix); - var isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx); - // End of the line for this path. - if (isUnique || (0, isEmpty_1.default)(suffixDef) || currPathPrefix.length === k) { - var currAltResult = finalResult[altIdx]; - // TODO: Can we implement a containsPath using Maps/Dictionaries? - if (containsPath(currAltResult, currPathPrefix) === false) { - currAltResult.push(currPathPrefix); - // Update all new keys for the current path. - for (var j = 0; j < prefixKeys.length; j++) { - var currKey = prefixKeys[j]; - altsHashes[altIdx][currKey] = true; - } - } - } - // Expand longer paths - else { - var newPartialPathsAndSuffixes = (0, interpreter_1.possiblePathsFrom)(suffixDef, pathLength + 1, currPathPrefix); - newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes); - // Update keys for new known paths - (0, forEach_1.default)(newPartialPathsAndSuffixes, function (item) { - var prefixKeys = pathToHashKeys(item.partialPath); - (0, forEach_1.default)(prefixKeys, function (key) { - altsHashes[altIdx][key] = true; - }); - }); - } - } - }; - // alternatives loop - for (var altIdx = 0; altIdx < currDataset.length; altIdx++) { - _loop_1(altIdx); - } - } - return finalResult; - } - exports.lookAheadSequenceFromAlternatives = lookAheadSequenceFromAlternatives; - function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) { - var visitor = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd); - ruleGrammar.accept(visitor); - return lookAheadSequenceFromAlternatives(visitor.result, k); - } - exports.getLookaheadPathsForOr = getLookaheadPathsForOr; - function getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k) { - var insideDefVisitor = new InsideDefinitionFinderVisitor(occurrence, prodType); - ruleGrammar.accept(insideDefVisitor); - var insideDef = insideDefVisitor.result; - var afterDefWalker = new RestDefinitionFinderWalker(ruleGrammar, occurrence, prodType); - var afterDef = afterDefWalker.startWalking(); - var insideFlat = new gast_1.Alternative({ definition: insideDef }); - var afterFlat = new gast_1.Alternative({ definition: afterDef }); - return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k); - } - exports.getLookaheadPathsForOptionalProd = getLookaheadPathsForOptionalProd; - function containsPath(alternative, searchPath) { - compareOtherPath: for (var i = 0; i < alternative.length; i++) { - var otherPath = alternative[i]; - if (otherPath.length !== searchPath.length) { - continue; - } - for (var j = 0; j < otherPath.length; j++) { - var searchTok = searchPath[j]; - var otherTok = otherPath[j]; - var matchingTokens = searchTok === otherTok || - otherTok.categoryMatchesMap[searchTok.tokenTypeIdx] !== undefined; - if (matchingTokens === false) { - continue compareOtherPath; - } - } - return true; - } - return false; - } - exports.containsPath = containsPath; - function isStrictPrefixOfPath(prefix, other) { - return (prefix.length < other.length && - (0, every_1.default)(prefix, function (tokType, idx) { - var otherTokType = other[idx]; - return (tokType === otherTokType || - otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]); - })); - } - exports.isStrictPrefixOfPath = isStrictPrefixOfPath; - function areTokenCategoriesNotUsed(lookAheadPaths) { - return (0, every_1.default)(lookAheadPaths, function (singleAltPaths) { - return (0, every_1.default)(singleAltPaths, function (singlePath) { - return (0, every_1.default)(singlePath, function (token) { return (0, isEmpty_1.default)(token.categoryMatches); }); - }); - }); - } - exports.areTokenCategoriesNotUsed = areTokenCategoriesNotUsed; - -} (lookahead)); - -var hasRequiredChecks; - -function requireChecks () { - if (hasRequiredChecks) return checks; - hasRequiredChecks = 1; - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(checks, "__esModule", { value: true }); - checks.checkPrefixAlternativesAmbiguities = checks.validateSomeNonEmptyLookaheadPath = checks.validateTooManyAlts = checks.RepetitionCollector = checks.validateAmbiguousAlternationAlternatives = checks.validateEmptyOrAlternative = checks.getFirstNoneTerminal = checks.validateNoLeftRecursion = checks.validateRuleIsOverridden = checks.validateRuleDoesNotAlreadyExist = checks.OccurrenceValidationCollector = checks.identifyProductionForDuplicates = checks.validateGrammar = void 0; - var first_1 = __importDefault(first.exports); - var isEmpty_1 = __importDefault(isEmpty_1$1); - var drop_1 = __importDefault(drop_1$2); - var flatten_1 = __importDefault(flatten_1$3); - var filter_1$1 = __importDefault(filter_1); - var reject_1$1 = __importDefault(reject_1); - var difference_1$1 = __importDefault(difference_1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var groupBy_1 = __importDefault(groupBy_1$1); - var reduce_1 = __importDefault(reduce_1$1); - var pickBy_1 = __importDefault(pickBy_1$1); - var values_1 = __importDefault(values_1$1); - var includes_1 = __importDefault(includes_1$2); - var flatMap_1$1 = __importDefault(flatMap_1); - var clone_1 = __importDefault(clone_1$1); - var parser_1 = requireParser(); - var gast_1 = api$1; - var lookahead_1 = lookahead; - var interpreter_1 = interpreter; - var gast_2 = api$1; - var gast_3 = api$1; - var dropRight_1 = __importDefault(dropRight_1$1); - var compact_1$1 = __importDefault(compact_1); - var tokens_1 = tokens; - function validateGrammar(topLevels, globalMaxLookahead, tokenTypes, errMsgProvider, grammarName) { - var duplicateErrors = (0, flatMap_1$1.default)(topLevels, function (currTopLevel) { - return validateDuplicateProductions(currTopLevel, errMsgProvider); - }); - var leftRecursionErrors = (0, flatMap_1$1.default)(topLevels, function (currTopRule) { - return validateNoLeftRecursion(currTopRule, currTopRule, errMsgProvider); - }); - var emptyAltErrors = []; - var ambiguousAltsErrors = []; - var emptyRepetitionErrors = []; - // left recursion could cause infinite loops in the following validations. - // It is safest to first have the user fix the left recursion errors first and only then examine Further issues. - if ((0, isEmpty_1.default)(leftRecursionErrors)) { - emptyAltErrors = (0, flatMap_1$1.default)(topLevels, function (currTopRule) { - return validateEmptyOrAlternative(currTopRule, errMsgProvider); - }); - ambiguousAltsErrors = (0, flatMap_1$1.default)(topLevels, function (currTopRule) { - return validateAmbiguousAlternationAlternatives(currTopRule, globalMaxLookahead, errMsgProvider); - }); - emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(topLevels, globalMaxLookahead, errMsgProvider); - } - var termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider); - var tooManyAltsErrors = (0, flatMap_1$1.default)(topLevels, function (curRule) { - return validateTooManyAlts(curRule, errMsgProvider); - }); - var duplicateRulesError = (0, flatMap_1$1.default)(topLevels, function (curRule) { - return validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider); - }); - return duplicateErrors.concat(emptyRepetitionErrors, leftRecursionErrors, emptyAltErrors, ambiguousAltsErrors, termsNamespaceConflictErrors, tooManyAltsErrors, duplicateRulesError); - } - checks.validateGrammar = validateGrammar; - function validateDuplicateProductions(topLevelRule, errMsgProvider) { - var collectorVisitor = new OccurrenceValidationCollector(); - topLevelRule.accept(collectorVisitor); - var allRuleProductions = collectorVisitor.allProductions; - var productionGroups = (0, groupBy_1.default)(allRuleProductions, identifyProductionForDuplicates); - var duplicates = (0, pickBy_1.default)(productionGroups, function (currGroup) { - return currGroup.length > 1; - }); - var errors = (0, map_1.default)((0, values_1.default)(duplicates), function (currDuplicates) { - var firstProd = (0, first_1.default)(currDuplicates); - var msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates); - var dslName = (0, gast_1.getProductionDslName)(firstProd); - var defError = { - message: msg, - type: parser_1.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, - ruleName: topLevelRule.name, - dslName: dslName, - occurrence: firstProd.idx - }; - var param = getExtraProductionArgument(firstProd); - if (param) { - defError.parameter = param; - } - return defError; - }); - return errors; - } - function identifyProductionForDuplicates(prod) { - return "".concat((0, gast_1.getProductionDslName)(prod), "_#_").concat(prod.idx, "_#_").concat(getExtraProductionArgument(prod)); - } - checks.identifyProductionForDuplicates = identifyProductionForDuplicates; - function getExtraProductionArgument(prod) { - if (prod instanceof gast_2.Terminal) { - return prod.terminalType.name; - } - else if (prod instanceof gast_2.NonTerminal) { - return prod.nonTerminalName; - } - else { - return ""; - } - } - var OccurrenceValidationCollector = /** @class */ (function (_super) { - __extends(OccurrenceValidationCollector, _super); - function OccurrenceValidationCollector() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.allProductions = []; - return _this; - } - OccurrenceValidationCollector.prototype.visitNonTerminal = function (subrule) { - this.allProductions.push(subrule); - }; - OccurrenceValidationCollector.prototype.visitOption = function (option) { - this.allProductions.push(option); - }; - OccurrenceValidationCollector.prototype.visitRepetitionWithSeparator = function (manySep) { - this.allProductions.push(manySep); - }; - OccurrenceValidationCollector.prototype.visitRepetitionMandatory = function (atLeastOne) { - this.allProductions.push(atLeastOne); - }; - OccurrenceValidationCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { - this.allProductions.push(atLeastOneSep); - }; - OccurrenceValidationCollector.prototype.visitRepetition = function (many) { - this.allProductions.push(many); - }; - OccurrenceValidationCollector.prototype.visitAlternation = function (or) { - this.allProductions.push(or); - }; - OccurrenceValidationCollector.prototype.visitTerminal = function (terminal) { - this.allProductions.push(terminal); - }; - return OccurrenceValidationCollector; - }(gast_3.GAstVisitor)); - checks.OccurrenceValidationCollector = OccurrenceValidationCollector; - function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) { - var errors = []; - var occurrences = (0, reduce_1.default)(allRules, function (result, curRule) { - if (curRule.name === rule.name) { - return result + 1; - } - return result; - }, 0); - if (occurrences > 1) { - var errMsg = errMsgProvider.buildDuplicateRuleNameError({ - topLevelRule: rule, - grammarName: className - }); - errors.push({ - message: errMsg, - type: parser_1.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, - ruleName: rule.name - }); - } - return errors; - } - checks.validateRuleDoesNotAlreadyExist = validateRuleDoesNotAlreadyExist; - // TODO: is there anyway to get only the rule names of rules inherited from the super grammars? - // This is not part of the IGrammarErrorProvider because the validation cannot be performed on - // The grammar structure, only at runtime. - function validateRuleIsOverridden(ruleName, definedRulesNames, className) { - var errors = []; - var errMsg; - if (!(0, includes_1.default)(definedRulesNames, ruleName)) { - errMsg = - "Invalid rule override, rule: ->".concat(ruleName, "<- cannot be overridden in the grammar: ->").concat(className, "<-") + - "as it is not defined in any of the super grammars "; - errors.push({ - message: errMsg, - type: parser_1.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE, - ruleName: ruleName - }); - } - return errors; - } - checks.validateRuleIsOverridden = validateRuleIsOverridden; - function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path) { - if (path === void 0) { path = []; } - var errors = []; - var nextNonTerminals = getFirstNoneTerminal(currRule.definition); - if ((0, isEmpty_1.default)(nextNonTerminals)) { - return []; - } - else { - var ruleName = topRule.name; - var foundLeftRecursion = (0, includes_1.default)(nextNonTerminals, topRule); - if (foundLeftRecursion) { - errors.push({ - message: errMsgProvider.buildLeftRecursionError({ - topLevelRule: topRule, - leftRecursionPath: path - }), - type: parser_1.ParserDefinitionErrorType.LEFT_RECURSION, - ruleName: ruleName - }); - } - // we are only looking for cyclic paths leading back to the specific topRule - // other cyclic paths are ignored, we still need this difference to avoid infinite loops... - var validNextSteps = (0, difference_1$1.default)(nextNonTerminals, path.concat([topRule])); - var errorsFromNextSteps = (0, flatMap_1$1.default)(validNextSteps, function (currRefRule) { - var newPath = (0, clone_1.default)(path); - newPath.push(currRefRule); - return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath); - }); - return errors.concat(errorsFromNextSteps); - } - } - checks.validateNoLeftRecursion = validateNoLeftRecursion; - function getFirstNoneTerminal(definition) { - var result = []; - if ((0, isEmpty_1.default)(definition)) { - return result; - } - var firstProd = (0, first_1.default)(definition); - /* istanbul ignore else */ - if (firstProd instanceof gast_2.NonTerminal) { - result.push(firstProd.referencedRule); - } - else if (firstProd instanceof gast_2.Alternative || - firstProd instanceof gast_2.Option || - firstProd instanceof gast_2.RepetitionMandatory || - firstProd instanceof gast_2.RepetitionMandatoryWithSeparator || - firstProd instanceof gast_2.RepetitionWithSeparator || - firstProd instanceof gast_2.Repetition) { - result = result.concat(getFirstNoneTerminal(firstProd.definition)); - } - else if (firstProd instanceof gast_2.Alternation) { - // each sub definition in alternation is a FLAT - result = (0, flatten_1.default)((0, map_1.default)(firstProd.definition, function (currSubDef) { - return getFirstNoneTerminal(currSubDef.definition); - })); - } - else if (firstProd instanceof gast_2.Terminal) ; - else { - throw Error("non exhaustive match"); - } - var isFirstOptional = (0, gast_1.isOptionalProd)(firstProd); - var hasMore = definition.length > 1; - if (isFirstOptional && hasMore) { - var rest = (0, drop_1.default)(definition); - return result.concat(getFirstNoneTerminal(rest)); - } - else { - return result; - } - } - checks.getFirstNoneTerminal = getFirstNoneTerminal; - var OrCollector = /** @class */ (function (_super) { - __extends(OrCollector, _super); - function OrCollector() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.alternations = []; - return _this; - } - OrCollector.prototype.visitAlternation = function (node) { - this.alternations.push(node); - }; - return OrCollector; - }(gast_3.GAstVisitor)); - function validateEmptyOrAlternative(topLevelRule, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - var errors = (0, flatMap_1$1.default)(ors, function (currOr) { - var exceptLast = (0, dropRight_1.default)(currOr.definition); - return (0, flatMap_1$1.default)(exceptLast, function (currAlternative, currAltIdx) { - var possibleFirstInAlt = (0, interpreter_1.nextPossibleTokensAfter)([currAlternative], [], tokens_1.tokenStructuredMatcher, 1); - if ((0, isEmpty_1.default)(possibleFirstInAlt)) { - return [ - { - message: errMsgProvider.buildEmptyAlternationError({ - topLevelRule: topLevelRule, - alternation: currOr, - emptyChoiceIdx: currAltIdx - }), - type: parser_1.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, - ruleName: topLevelRule.name, - occurrence: currOr.idx, - alternative: currAltIdx + 1 - } - ]; - } - else { - return []; - } - }); - }); - return errors; - } - checks.validateEmptyOrAlternative = validateEmptyOrAlternative; - function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - // New Handling of ignoring ambiguities - // - https://github.com/chevrotain/chevrotain/issues/869 - ors = (0, reject_1$1.default)(ors, function (currOr) { return currOr.ignoreAmbiguities === true; }); - var errors = (0, flatMap_1$1.default)(ors, function (currOr) { - var currOccurrence = currOr.idx; - var actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead; - var alternatives = (0, lookahead_1.getLookaheadPathsForOr)(currOccurrence, topLevelRule, actualMaxLookahead, currOr); - var altsAmbiguityErrors = checkAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); - var altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); - return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors); - }); - return errors; - } - checks.validateAmbiguousAlternationAlternatives = validateAmbiguousAlternationAlternatives; - var RepetitionCollector = /** @class */ (function (_super) { - __extends(RepetitionCollector, _super); - function RepetitionCollector() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.allProductions = []; - return _this; - } - RepetitionCollector.prototype.visitRepetitionWithSeparator = function (manySep) { - this.allProductions.push(manySep); - }; - RepetitionCollector.prototype.visitRepetitionMandatory = function (atLeastOne) { - this.allProductions.push(atLeastOne); - }; - RepetitionCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { - this.allProductions.push(atLeastOneSep); - }; - RepetitionCollector.prototype.visitRepetition = function (many) { - this.allProductions.push(many); - }; - return RepetitionCollector; - }(gast_3.GAstVisitor)); - checks.RepetitionCollector = RepetitionCollector; - function validateTooManyAlts(topLevelRule, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - var errors = (0, flatMap_1$1.default)(ors, function (currOr) { - if (currOr.definition.length > 255) { - return [ - { - message: errMsgProvider.buildTooManyAlternativesError({ - topLevelRule: topLevelRule, - alternation: currOr - }), - type: parser_1.ParserDefinitionErrorType.TOO_MANY_ALTS, - ruleName: topLevelRule.name, - occurrence: currOr.idx - } - ]; - } - else { - return []; - } - }); - return errors; - } - checks.validateTooManyAlts = validateTooManyAlts; - function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) { - var errors = []; - (0, forEach_1.default)(topLevelRules, function (currTopRule) { - var collectorVisitor = new RepetitionCollector(); - currTopRule.accept(collectorVisitor); - var allRuleProductions = collectorVisitor.allProductions; - (0, forEach_1.default)(allRuleProductions, function (currProd) { - var prodType = (0, lookahead_1.getProdType)(currProd); - var actualMaxLookahead = currProd.maxLookahead || maxLookahead; - var currOccurrence = currProd.idx; - var paths = (0, lookahead_1.getLookaheadPathsForOptionalProd)(currOccurrence, currTopRule, prodType, actualMaxLookahead); - var pathsInsideProduction = paths[0]; - if ((0, isEmpty_1.default)((0, flatten_1.default)(pathsInsideProduction))) { - var errMsg = errMsgProvider.buildEmptyRepetitionError({ - topLevelRule: currTopRule, - repetition: currProd - }); - errors.push({ - message: errMsg, - type: parser_1.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, - ruleName: currTopRule.name - }); - } - }); - }); - return errors; - } - checks.validateSomeNonEmptyLookaheadPath = validateSomeNonEmptyLookaheadPath; - function checkAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { - var foundAmbiguousPaths = []; - var identicalAmbiguities = (0, reduce_1.default)(alternatives, function (result, currAlt, currAltIdx) { - // ignore (skip) ambiguities with this alternative - if (alternation.definition[currAltIdx].ignoreAmbiguities === true) { - return result; - } - (0, forEach_1.default)(currAlt, function (currPath) { - var altsCurrPathAppearsIn = [currAltIdx]; - (0, forEach_1.default)(alternatives, function (currOtherAlt, currOtherAltIdx) { - if (currAltIdx !== currOtherAltIdx && - (0, lookahead_1.containsPath)(currOtherAlt, currPath) && - // ignore (skip) ambiguities with this "other" alternative - alternation.definition[currOtherAltIdx].ignoreAmbiguities !== true) { - altsCurrPathAppearsIn.push(currOtherAltIdx); - } - }); - if (altsCurrPathAppearsIn.length > 1 && - !(0, lookahead_1.containsPath)(foundAmbiguousPaths, currPath)) { - foundAmbiguousPaths.push(currPath); - result.push({ - alts: altsCurrPathAppearsIn, - path: currPath - }); - } - }); - return result; - }, []); - var currErrors = (0, map_1.default)(identicalAmbiguities, function (currAmbDescriptor) { - var ambgIndices = (0, map_1.default)(currAmbDescriptor.alts, function (currAltIdx) { return currAltIdx + 1; }); - var currMessage = errMsgProvider.buildAlternationAmbiguityError({ - topLevelRule: rule, - alternation: alternation, - ambiguityIndices: ambgIndices, - prefixPath: currAmbDescriptor.path - }); - return { - message: currMessage, - type: parser_1.ParserDefinitionErrorType.AMBIGUOUS_ALTS, - ruleName: rule.name, - occurrence: alternation.idx, - alternatives: currAmbDescriptor.alts - }; - }); - return currErrors; + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress); + } // React DevTools reads this flag. + + + workInProgress.flags |= PerformedWork; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; } - function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { - // flatten - var pathsAndIndices = (0, reduce_1.default)(alternatives, function (result, currAlt, idx) { - var currPathsAndIdx = (0, map_1.default)(currAlt, function (currPath) { - return { idx: idx, path: currPath }; - }); - return result.concat(currPathsAndIdx); - }, []); - var errors = (0, compact_1$1.default)((0, flatMap_1$1.default)(pathsAndIndices, function (currPathAndIdx) { - var alternativeGast = alternation.definition[currPathAndIdx.idx]; - // ignore (skip) ambiguities with this alternative - if (alternativeGast.ignoreAmbiguities === true) { - return []; + + function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) { + { + // This is used by DevTools to force a boundary to error. + switch (shouldError(workInProgress)) { + case false: + { + var _instance = workInProgress.stateNode; + var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack. + // Is there a better way to do this? + + var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context); + var state = tempInstance.state; + + _instance.updater.enqueueSetState(_instance, state, null); + + break; } - var targetIdx = currPathAndIdx.idx; - var targetPath = currPathAndIdx.path; - var prefixAmbiguitiesPathsAndIndices = (0, filter_1$1.default)(pathsAndIndices, function (searchPathAndIdx) { - // prefix ambiguity can only be created from lower idx (higher priority) path - return ( - // ignore (skip) ambiguities with this "other" alternative - alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities !== - true && - searchPathAndIdx.idx < targetIdx && - // checking for strict prefix because identical lookaheads - // will be be detected using a different validation. - (0, lookahead_1.isStrictPrefixOfPath)(searchPathAndIdx.path, targetPath)); - }); - var currPathPrefixErrors = (0, map_1.default)(prefixAmbiguitiesPathsAndIndices, function (currAmbPathAndIdx) { - var ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1]; - var occurrence = alternation.idx === 0 ? "" : alternation.idx; - var message = errMsgProvider.buildAlternationPrefixAmbiguityError({ - topLevelRule: rule, - alternation: alternation, - ambiguityIndices: ambgIndices, - prefixPath: currAmbPathAndIdx.path - }); - return { - message: message, - type: parser_1.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, - ruleName: rule.name, - occurrence: occurrence, - alternatives: ambgIndices - }; - }); - return currPathPrefixErrors; - })); - return errors; - } - checks.checkPrefixAlternativesAmbiguities = checkPrefixAlternativesAmbiguities; - function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) { - var errors = []; - var tokenNames = (0, map_1.default)(tokenTypes, function (currToken) { return currToken.name; }); - (0, forEach_1.default)(topLevels, function (currRule) { - var currRuleName = currRule.name; - if ((0, includes_1.default)(tokenNames, currRuleName)) { - var errMsg = errMsgProvider.buildNamespaceConflictError(currRule); - errors.push({ - message: errMsg, - type: parser_1.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, - ruleName: currRuleName - }); + + case true: + { + workInProgress.flags |= DidCapture; + workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes + + var error$1 = new Error('Simulated error coming from DevTools'); + var lane = pickArbitraryLane(renderLanes); + workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state + + var update = createClassErrorUpdate(workInProgress, createCapturedValue(error$1, workInProgress), lane); + enqueueCapturedUpdate(workInProgress, update); + break; } - }); - return errors; - } - - return checks; -} + } -var hasRequiredGast_resolver_public; + if (workInProgress.type !== workInProgress.elementType) { + // Lazy component props can't be validated in createElement + // because they're only guaranteed to be resolved here. + var innerPropTypes = Component.propTypes; -function requireGast_resolver_public () { - if (hasRequiredGast_resolver_public) return gast_resolver_public; - hasRequiredGast_resolver_public = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(gast_resolver_public, "__esModule", { value: true }); - gast_resolver_public.validateGrammar = gast_resolver_public.resolveGrammar = void 0; - var forEach_1 = __importDefault(forEach_1$4); - var defaults_1$1 = __importDefault(defaults_1); - var resolver_1 = requireResolver(); - var checks_1 = requireChecks(); - var errors_public_1 = errors_public; - function resolveGrammar(options) { - var actualOptions = (0, defaults_1$1.default)(options, { - errMsgProvider: errors_public_1.defaultGrammarResolverErrorProvider - }); - var topRulesTable = {}; - (0, forEach_1.default)(options.rules, function (rule) { - topRulesTable[rule.name] = rule; - }); - return (0, resolver_1.resolveGrammar)(topRulesTable, actualOptions.errMsgProvider); - } - gast_resolver_public.resolveGrammar = resolveGrammar; - function validateGrammar(options) { - options = (0, defaults_1$1.default)(options, { - errMsgProvider: errors_public_1.defaultGrammarValidatorErrorProvider - }); - return (0, checks_1.validateGrammar)(options.rules, options.maxLookahead, options.tokenTypes, options.errMsgProvider, options.grammarName); - } - gast_resolver_public.validateGrammar = validateGrammar; - - return gast_resolver_public; -} + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, // Resolved props + 'prop', getComponentNameFromType(Component)); + } + } + } // Push context providers early to prevent context stack mismatches. + // During mounting we don't know the child context yet as the instance doesn't exist. + // We will invalidate the child context in finishClassComponent() right after rendering. -var recoverable = {}; -var exceptions_public = {}; + var hasContext; -/* istanbul ignore next */ var __extends$1 = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$3 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exceptions_public, "__esModule", { value: true }); -exceptions_public.EarlyExitException = exceptions_public.NotAllInputParsedException = exceptions_public.NoViableAltException = exceptions_public.MismatchedTokenException = exceptions_public.isRecognitionException = void 0; -var includes_1 = __importDefault$3(includes_1$2); -var MISMATCHED_TOKEN_EXCEPTION = "MismatchedTokenException"; -var NO_VIABLE_ALT_EXCEPTION = "NoViableAltException"; -var EARLY_EXIT_EXCEPTION = "EarlyExitException"; -var NOT_ALL_INPUT_PARSED_EXCEPTION = "NotAllInputParsedException"; -var RECOGNITION_EXCEPTION_NAMES = [ - MISMATCHED_TOKEN_EXCEPTION, - NO_VIABLE_ALT_EXCEPTION, - EARLY_EXIT_EXCEPTION, - NOT_ALL_INPUT_PARSED_EXCEPTION -]; -Object.freeze(RECOGNITION_EXCEPTION_NAMES); -// hacks to bypass no support for custom Errors in javascript/typescript -function isRecognitionException(error) { - // can't do instanceof on hacked custom js exceptions - return (0, includes_1.default)(RECOGNITION_EXCEPTION_NAMES, error.name); -} -exceptions_public.isRecognitionException = isRecognitionException; -var RecognitionException = /** @class */ (function (_super) { - __extends$1(RecognitionException, _super); - function RecognitionException(message, token) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) /* istanbul ignore next */ || this; - _this.token = token; - _this.resyncedTokens = []; - // fix prototype chain when typescript target is ES5 - Object.setPrototypeOf(_this, _newTarget.prototype); - /* istanbul ignore next - V8 workaround to remove constructor from stacktrace when typescript target is ES5 */ - if (Error.captureStackTrace) { - Error.captureStackTrace(_this, _this.constructor); - } - return _this; - } - return RecognitionException; -}(Error)); -var MismatchedTokenException = /** @class */ (function (_super) { - __extends$1(MismatchedTokenException, _super); - function MismatchedTokenException(message, token, previousToken) { - var _this = _super.call(this, message, token) /* istanbul ignore next */ || this; - _this.previousToken = previousToken; - _this.name = MISMATCHED_TOKEN_EXCEPTION; - return _this; - } - return MismatchedTokenException; -}(RecognitionException)); -exceptions_public.MismatchedTokenException = MismatchedTokenException; -var NoViableAltException = /** @class */ (function (_super) { - __extends$1(NoViableAltException, _super); - function NoViableAltException(message, token, previousToken) { - var _this = _super.call(this, message, token) /* istanbul ignore next */ || this; - _this.previousToken = previousToken; - _this.name = NO_VIABLE_ALT_EXCEPTION; - return _this; - } - return NoViableAltException; -}(RecognitionException)); -exceptions_public.NoViableAltException = NoViableAltException; -var NotAllInputParsedException = /** @class */ (function (_super) { - __extends$1(NotAllInputParsedException, _super); - function NotAllInputParsedException(message, token) { - var _this = _super.call(this, message, token) /* istanbul ignore next */ || this; - _this.name = NOT_ALL_INPUT_PARSED_EXCEPTION; - return _this; - } - return NotAllInputParsedException; -}(RecognitionException)); -exceptions_public.NotAllInputParsedException = NotAllInputParsedException; -var EarlyExitException = /** @class */ (function (_super) { - __extends$1(EarlyExitException, _super); - function EarlyExitException(message, token, previousToken) { - var _this = _super.call(this, message, token) /* istanbul ignore next */ || this; - _this.previousToken = previousToken; - _this.name = EARLY_EXIT_EXCEPTION; - return _this; - } - return EarlyExitException; -}(RecognitionException)); -exceptions_public.EarlyExitException = EarlyExitException; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress); + } else { + hasContext = false; + } -var hasRequiredRecoverable; + prepareToReadContext(workInProgress, renderLanes); + var instance = workInProgress.stateNode; + var shouldUpdate; -function requireRecoverable () { - if (hasRequiredRecoverable) return recoverable; - hasRequiredRecoverable = 1; - (function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.attemptInRepetitionRecovery = exports.Recoverable = exports.InRuleRecoveryException = exports.IN_RULE_RECOVERY_EXCEPTION = exports.EOF_FOLLOW_KEY = void 0; - var tokens_public_1 = tokens_public; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var dropRight_1 = __importDefault(dropRight_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var map_1 = __importDefault(map_1$4); - var find_1$1 = __importDefault(find_1); - var has_1$1 = __importDefault(has_1); - var includes_1 = __importDefault(includes_1$2); - var clone_1 = __importDefault(clone_1$1); - var exceptions_public_1 = exceptions_public; - var constants_1 = constants; - var parser_1 = requireParser(); - exports.EOF_FOLLOW_KEY = {}; - exports.IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException"; - var InRuleRecoveryException = /** @class */ (function (_super) { - __extends(InRuleRecoveryException, _super); - function InRuleRecoveryException(message) { - var _this = _super.call(this, message) || this; - _this.name = exports.IN_RULE_RECOVERY_EXCEPTION; - return _this; - } - return InRuleRecoveryException; - }(Error)); - exports.InRuleRecoveryException = InRuleRecoveryException; - /** - * This trait is responsible for the error recovery and fault tolerant logic - */ - var Recoverable = /** @class */ (function () { - function Recoverable() { - } - Recoverable.prototype.initRecoverable = function (config) { - this.firstAfterRepMap = {}; - this.resyncFollows = {}; - this.recoveryEnabled = (0, has_1$1.default)(config, "recoveryEnabled") - ? config.recoveryEnabled // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.recoveryEnabled; - // performance optimization, NOOP will be inlined which - // effectively means that this optional feature does not exist - // when not used. - if (this.recoveryEnabled) { - this.attemptInRepetitionRecovery = attemptInRepetitionRecovery; - } - }; - Recoverable.prototype.getTokenToInsert = function (tokType) { - var tokToInsert = (0, tokens_public_1.createTokenInstance)(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN); - tokToInsert.isInsertedInRecovery = true; - return tokToInsert; - }; - Recoverable.prototype.canTokenTypeBeInsertedInRecovery = function (tokType) { - return true; - }; - Recoverable.prototype.canTokenTypeBeDeletedInRecovery = function (tokType) { - return true; - }; - Recoverable.prototype.tryInRepetitionRecovery = function (grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) { - var _this = this; - // TODO: can the resyncTokenType be cached? - var reSyncTokType = this.findReSyncTokenType(); - var savedLexerState = this.exportLexerState(); - var resyncedTokens = []; - var passedResyncPoint = false; - var nextTokenWithoutResync = this.LA(1); - var currToken = this.LA(1); - var generateErrorMessage = function () { - var previousToken = _this.LA(0); - // we are preemptively re-syncing before an error has been detected, therefor we must reproduce - // the error that would have been thrown - var msg = _this.errorMessageProvider.buildMismatchTokenMessage({ - expected: expectedTokType, - actual: nextTokenWithoutResync, - previous: previousToken, - ruleName: _this.getCurrRuleFullName() - }); - var error = new exceptions_public_1.MismatchedTokenException(msg, nextTokenWithoutResync, _this.LA(0)); - // the first token here will be the original cause of the error, this is not part of the resyncedTokens property. - error.resyncedTokens = (0, dropRight_1.default)(resyncedTokens); - _this.SAVE_ERROR(error); - }; - while (!passedResyncPoint) { - // re-synced to a point where we can safely exit the repetition/ - if (this.tokenMatcher(currToken, expectedTokType)) { - generateErrorMessage(); - return; // must return here to avoid reverting the inputIdx - } - else if (lookAheadFunc.call(this)) { - // we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule - generateErrorMessage(); - // recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule - grammarRule.apply(this, grammarRuleArgs); - return; // must return here to avoid reverting the inputIdx - } - else if (this.tokenMatcher(currToken, reSyncTokType)) { - passedResyncPoint = true; - } - else { - currToken = this.SKIP_TOKEN(); - this.addToResyncTokens(currToken, resyncedTokens); - } - } - // we were unable to find a CLOSER point to resync inside the Repetition, reset the state. - // The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by - // "between rules" resync recovery later in the flow. - this.importLexerState(savedLexerState); - }; - Recoverable.prototype.shouldInRepetitionRecoveryBeTried = function (expectTokAfterLastMatch, nextTokIdx, notStuck) { - // Edge case of arriving from a MANY repetition which is stuck - // Attempting recovery in this case could cause an infinite loop - if (notStuck === false) { - return false; - } - // no need to recover, next token is what we expect... - if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) { - return false; - } - // error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path - // and prefer some backtracking path that includes recovered errors. - if (this.isBackTracking()) { - return false; - } - // if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm - // because if it works, it makes the least amount of changes to the input stream (greedy algorithm) - //noinspection RedundantIfStatementJS - if (this.canPerformInRuleRecovery(expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx))) { - return false; - } - return true; - }; - // Error Recovery functionality - Recoverable.prototype.getFollowsForInRuleRecovery = function (tokType, tokIdxInRule) { - var grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule); - var follows = this.getNextPossibleTokenTypes(grammarPath); - return follows; - }; - Recoverable.prototype.tryInRuleRecovery = function (expectedTokType, follows) { - if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) { - var tokToInsert = this.getTokenToInsert(expectedTokType); - return tokToInsert; - } - if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) { - var nextTok = this.SKIP_TOKEN(); - this.consumeToken(); - return nextTok; - } - throw new InRuleRecoveryException("sad sad panda"); - }; - Recoverable.prototype.canPerformInRuleRecovery = function (expectedToken, follows) { - return (this.canRecoverWithSingleTokenInsertion(expectedToken, follows) || - this.canRecoverWithSingleTokenDeletion(expectedToken)); - }; - Recoverable.prototype.canRecoverWithSingleTokenInsertion = function (expectedTokType, follows) { - var _this = this; - if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) { - return false; - } - // must know the possible following tokens to perform single token insertion - if ((0, isEmpty_1.default)(follows)) { - return false; - } - var mismatchedTok = this.LA(1); - var isMisMatchedTokInFollows = (0, find_1$1.default)(follows, function (possibleFollowsTokType) { - return _this.tokenMatcher(mismatchedTok, possibleFollowsTokType); - }) !== undefined; - return isMisMatchedTokInFollows; - }; - Recoverable.prototype.canRecoverWithSingleTokenDeletion = function (expectedTokType) { - if (!this.canTokenTypeBeDeletedInRecovery(expectedTokType)) { - return false; - } - var isNextTokenWhatIsExpected = this.tokenMatcher(this.LA(2), expectedTokType); - return isNextTokenWhatIsExpected; - }; - Recoverable.prototype.isInCurrentRuleReSyncSet = function (tokenTypeIdx) { - var followKey = this.getCurrFollowKey(); - var currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey); - return (0, includes_1.default)(currentRuleReSyncSet, tokenTypeIdx); - }; - Recoverable.prototype.findReSyncTokenType = function () { - var allPossibleReSyncTokTypes = this.flattenFollowSet(); - // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input - var nextToken = this.LA(1); - var k = 2; - while (true) { - var foundMatch = (0, find_1$1.default)(allPossibleReSyncTokTypes, function (resyncTokType) { - var canMatch = (0, tokens_public_1.tokenMatcher)(nextToken, resyncTokType); - return canMatch; - }); - if (foundMatch !== undefined) { - return foundMatch; - } - nextToken = this.LA(k); - k++; - } - }; - Recoverable.prototype.getCurrFollowKey = function () { - // the length is at least one as we always add the ruleName to the stack before invoking the rule. - if (this.RULE_STACK.length === 1) { - return exports.EOF_FOLLOW_KEY; - } - var currRuleShortName = this.getLastExplicitRuleShortName(); - var currRuleIdx = this.getLastExplicitRuleOccurrenceIndex(); - var prevRuleShortName = this.getPreviousExplicitRuleShortName(); - return { - ruleName: this.shortRuleNameToFullName(currRuleShortName), - idxInCallingRule: currRuleIdx, - inRule: this.shortRuleNameToFullName(prevRuleShortName) - }; - }; - Recoverable.prototype.buildFullFollowKeyStack = function () { - var _this = this; - var explicitRuleStack = this.RULE_STACK; - var explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK; - return (0, map_1.default)(explicitRuleStack, function (ruleName, idx) { - if (idx === 0) { - return exports.EOF_FOLLOW_KEY; - } - return { - ruleName: _this.shortRuleNameToFullName(ruleName), - idxInCallingRule: explicitOccurrenceStack[idx], - inRule: _this.shortRuleNameToFullName(explicitRuleStack[idx - 1]) - }; - }); - }; - Recoverable.prototype.flattenFollowSet = function () { - var _this = this; - var followStack = (0, map_1.default)(this.buildFullFollowKeyStack(), function (currKey) { - return _this.getFollowSetFromFollowKey(currKey); - }); - return (0, flatten_1.default)(followStack); - }; - Recoverable.prototype.getFollowSetFromFollowKey = function (followKey) { - if (followKey === exports.EOF_FOLLOW_KEY) { - return [tokens_public_1.EOF]; - } - var followName = followKey.ruleName + followKey.idxInCallingRule + constants_1.IN + followKey.inRule; - return this.resyncFollows[followName]; - }; - // It does not make any sense to include a virtual EOF token in the list of resynced tokens - // as EOF does not really exist and thus does not contain any useful information (line/column numbers) - Recoverable.prototype.addToResyncTokens = function (token, resyncTokens) { - if (!this.tokenMatcher(token, tokens_public_1.EOF)) { - resyncTokens.push(token); - } - return resyncTokens; - }; - Recoverable.prototype.reSyncTo = function (tokType) { - var resyncedTokens = []; - var nextTok = this.LA(1); - while (this.tokenMatcher(nextTok, tokType) === false) { - nextTok = this.SKIP_TOKEN(); - this.addToResyncTokens(nextTok, resyncedTokens); - } - // the last token is not part of the error. - return (0, dropRight_1.default)(resyncedTokens); - }; - Recoverable.prototype.attemptInRepetitionRecovery = function (prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { - // by default this is a NO-OP - // The actual implementation is with the function(not method) below - }; - Recoverable.prototype.getCurrentGrammarPath = function (tokType, tokIdxInRule) { - var pathRuleStack = this.getHumanReadableRuleStack(); - var pathOccurrenceStack = (0, clone_1.default)(this.RULE_OCCURRENCE_STACK); - var grammarPath = { - ruleStack: pathRuleStack, - occurrenceStack: pathOccurrenceStack, - lastTok: tokType, - lastTokOccurrence: tokIdxInRule - }; - return grammarPath; - }; - Recoverable.prototype.getHumanReadableRuleStack = function () { - var _this = this; - return (0, map_1.default)(this.RULE_STACK, function (currShortName) { - return _this.shortRuleNameToFullName(currShortName); - }); - }; - return Recoverable; - }()); - exports.Recoverable = Recoverable; - function attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { - var key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence); - var firstAfterRepInfo = this.firstAfterRepMap[key]; - if (firstAfterRepInfo === undefined) { - var currRuleName = this.getCurrRuleFullName(); - var ruleGrammar = this.getGAstProductions()[currRuleName]; - var walker = new nextToksWalker(ruleGrammar, prodOccurrence); - firstAfterRepInfo = walker.startWalking(); - this.firstAfterRepMap[key] = firstAfterRepInfo; - } - var expectTokAfterLastMatch = firstAfterRepInfo.token; - var nextTokIdx = firstAfterRepInfo.occurrence; - var isEndOfRule = firstAfterRepInfo.isEndOfRule; - // special edge case of a TOP most repetition after which the input should END. - // this will force an attempt for inRule recovery in that scenario. - if (this.RULE_STACK.length === 1 && - isEndOfRule && - expectTokAfterLastMatch === undefined) { - expectTokAfterLastMatch = tokens_public_1.EOF; - nextTokIdx = 1; - } - // We don't have anything to re-sync to... - // this condition was extracted from `shouldInRepetitionRecoveryBeTried` to act as a type-guard - if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) { - return; - } - if (this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck)) { - // TODO: performance optimization: instead of passing the original args here, we modify - // the args param (or create a new one) and make sure the lookahead func is explicitly provided - // to avoid searching the cache for it once more. - this.tryInRepetitionRecovery(prodFunc, args, lookaheadFunc, expectTokAfterLastMatch); - } - } - exports.attemptInRepetitionRecovery = attemptInRepetitionRecovery; - -} (recoverable)); - return recoverable; -} - -var looksahead = {}; - -var keys = {}; - -(function (exports) { - // Lookahead keys are 32Bit integers in the form - // TTTTTTTT-ZZZZZZZZZZZZ-YYYY-XXXXXXXX - // XXXX -> Occurrence Index bitmap. - // YYYY -> DSL Method Type bitmap. - // ZZZZZZZZZZZZZZZ -> Rule short Index bitmap. - // TTTTTTTTT -> alternation alternative index bitmap - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getKeyForAutomaticLookahead = exports.AT_LEAST_ONE_SEP_IDX = exports.MANY_SEP_IDX = exports.AT_LEAST_ONE_IDX = exports.MANY_IDX = exports.OPTION_IDX = exports.OR_IDX = exports.BITS_FOR_ALT_IDX = exports.BITS_FOR_RULE_IDX = exports.BITS_FOR_OCCURRENCE_IDX = exports.BITS_FOR_METHOD_TYPE = void 0; - exports.BITS_FOR_METHOD_TYPE = 4; - exports.BITS_FOR_OCCURRENCE_IDX = 8; - exports.BITS_FOR_RULE_IDX = 12; - // TODO: validation, this means that there may at most 2^8 --> 256 alternatives for an alternation. - exports.BITS_FOR_ALT_IDX = 8; - // short string used as part of mapping keys. - // being short improves the performance when composing KEYS for maps out of these - // The 5 - 8 bits (16 possible values, are reserved for the DSL method indices) - exports.OR_IDX = 1 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.OPTION_IDX = 2 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.MANY_IDX = 3 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.AT_LEAST_ONE_IDX = 4 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.MANY_SEP_IDX = 5 << exports.BITS_FOR_OCCURRENCE_IDX; - exports.AT_LEAST_ONE_SEP_IDX = 6 << exports.BITS_FOR_OCCURRENCE_IDX; - // this actually returns a number, but it is always used as a string (object prop key) - function getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) { - return occurrence | dslMethodIdx | ruleIdx; - } - exports.getKeyForAutomaticLookahead = getKeyForAutomaticLookahead; - 32 - exports.BITS_FOR_ALT_IDX; - -} (keys)); - -var hasRequiredLooksahead; - -function requireLooksahead () { - if (hasRequiredLooksahead) return looksahead; - hasRequiredLooksahead = 1; - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(looksahead, "__esModule", { value: true }); - looksahead.collectMethods = looksahead.LooksAhead = void 0; - var lookahead_1 = lookahead; - var forEach_1 = __importDefault(forEach_1$4); - var has_1$1 = __importDefault(has_1); - var parser_1 = requireParser(); - var keys_1 = keys; - var gast_1 = api$1; - var gast_2 = api$1; - /** - * Trait responsible for the lookahead related utilities and optimizations. - */ - var LooksAhead = /** @class */ (function () { - function LooksAhead() { - } - LooksAhead.prototype.initLooksAhead = function (config) { - this.dynamicTokensEnabled = (0, has_1$1.default)(config, "dynamicTokensEnabled") - ? config.dynamicTokensEnabled // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled; - this.maxLookahead = (0, has_1$1.default)(config, "maxLookahead") - ? config.maxLookahead // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.maxLookahead; - this.lookAheadFuncsCache = new Map(); - }; - LooksAhead.prototype.preComputeLookaheadFunctions = function (rules) { - var _this = this; - (0, forEach_1.default)(rules, function (currRule) { - _this.TRACE_INIT("".concat(currRule.name, " Rule Lookahead"), function () { - var _a = collectMethods(currRule), alternation = _a.alternation, repetition = _a.repetition, option = _a.option, repetitionMandatory = _a.repetitionMandatory, repetitionMandatoryWithSeparator = _a.repetitionMandatoryWithSeparator, repetitionWithSeparator = _a.repetitionWithSeparator; - (0, forEach_1.default)(alternation, function (currProd) { - var prodIdx = currProd.idx === 0 ? "" : currProd.idx; - _this.TRACE_INIT("".concat((0, gast_2.getProductionDslName)(currProd)).concat(prodIdx), function () { - var laFunc = (0, lookahead_1.buildLookaheadFuncForOr)(currProd.idx, currRule, currProd.maxLookahead || _this.maxLookahead, currProd.hasPredicates, _this.dynamicTokensEnabled, _this.lookAheadBuilderForAlternatives); - var key = (0, keys_1.getKeyForAutomaticLookahead)(_this.fullRuleNameToShort[currRule.name], keys_1.OR_IDX, currProd.idx); - _this.setLaFuncCache(key, laFunc); - }); - }); - (0, forEach_1.default)(repetition, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.MANY_IDX, lookahead_1.PROD_TYPE.REPETITION, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - (0, forEach_1.default)(option, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.OPTION_IDX, lookahead_1.PROD_TYPE.OPTION, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - (0, forEach_1.default)(repetitionMandatory, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.AT_LEAST_ONE_IDX, lookahead_1.PROD_TYPE.REPETITION_MANDATORY, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - (0, forEach_1.default)(repetitionMandatoryWithSeparator, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.AT_LEAST_ONE_SEP_IDX, lookahead_1.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - (0, forEach_1.default)(repetitionWithSeparator, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.MANY_SEP_IDX, lookahead_1.PROD_TYPE.REPETITION_WITH_SEPARATOR, currProd.maxLookahead, (0, gast_2.getProductionDslName)(currProd)); - }); - }); - }); - }; - LooksAhead.prototype.computeLookaheadFunc = function (rule, prodOccurrence, prodKey, prodType, prodMaxLookahead, dslMethodName) { - var _this = this; - this.TRACE_INIT("".concat(dslMethodName).concat(prodOccurrence === 0 ? "" : prodOccurrence), function () { - var laFunc = (0, lookahead_1.buildLookaheadFuncForOptionalProd)(prodOccurrence, rule, prodMaxLookahead || _this.maxLookahead, _this.dynamicTokensEnabled, prodType, _this.lookAheadBuilderForOptional); - var key = (0, keys_1.getKeyForAutomaticLookahead)(_this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence); - _this.setLaFuncCache(key, laFunc); - }); - }; - LooksAhead.prototype.lookAheadBuilderForOptional = function (alt, tokenMatcher, dynamicTokensEnabled) { - return (0, lookahead_1.buildSingleAlternativeLookaheadFunction)(alt, tokenMatcher, dynamicTokensEnabled); - }; - LooksAhead.prototype.lookAheadBuilderForAlternatives = function (alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { - return (0, lookahead_1.buildAlternativesLookAheadFunc)(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled); - }; - // this actually returns a number, but it is always used as a string (object prop key) - LooksAhead.prototype.getKeyForAutomaticLookahead = function (dslMethodIdx, occurrence) { - var currRuleShortName = this.getLastExplicitRuleShortName(); - return (0, keys_1.getKeyForAutomaticLookahead)(currRuleShortName, dslMethodIdx, occurrence); - }; - LooksAhead.prototype.getLaFuncFromCache = function (key) { - return this.lookAheadFuncsCache.get(key); - }; - /* istanbul ignore next */ - LooksAhead.prototype.setLaFuncCache = function (key, value) { - this.lookAheadFuncsCache.set(key, value); - }; - return LooksAhead; - }()); - looksahead.LooksAhead = LooksAhead; - var DslMethodsCollectorVisitor = /** @class */ (function (_super) { - __extends(DslMethodsCollectorVisitor, _super); - function DslMethodsCollectorVisitor() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.dslMethods = { - option: [], - alternation: [], - repetition: [], - repetitionWithSeparator: [], - repetitionMandatory: [], - repetitionMandatoryWithSeparator: [] - }; - return _this; - } - DslMethodsCollectorVisitor.prototype.reset = function () { - this.dslMethods = { - option: [], - alternation: [], - repetition: [], - repetitionWithSeparator: [], - repetitionMandatory: [], - repetitionMandatoryWithSeparator: [] - }; - }; - DslMethodsCollectorVisitor.prototype.visitOption = function (option) { - this.dslMethods.option.push(option); - }; - DslMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (manySep) { - this.dslMethods.repetitionWithSeparator.push(manySep); - }; - DslMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (atLeastOne) { - this.dslMethods.repetitionMandatory.push(atLeastOne); - }; - DslMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { - this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep); - }; - DslMethodsCollectorVisitor.prototype.visitRepetition = function (many) { - this.dslMethods.repetition.push(many); - }; - DslMethodsCollectorVisitor.prototype.visitAlternation = function (or) { - this.dslMethods.alternation.push(or); - }; - return DslMethodsCollectorVisitor; - }(gast_1.GAstVisitor)); - var collectorVisitor = new DslMethodsCollectorVisitor(); - function collectMethods(rule) { - collectorVisitor.reset(); - rule.accept(collectorVisitor); - var dslMethods = collectorVisitor.dslMethods; - // avoid uncleaned references - collectorVisitor.reset(); - return dslMethods; - } - looksahead.collectMethods = collectMethods; - - return looksahead; -} + if (instance === null) { + if (current !== null) { + // A class component without an instance only mounts if it suspended + // inside a non-concurrent tree, in an inconsistent state. We want to + // treat it like a new mount, even though an empty version of it already + // committed. Disconnect the alternate pointers. + current.alternate = null; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect -var tree_builder = {}; + workInProgress.flags |= Placement; + } // In the initial pass we might need to construct the instance. -var cst = {}; -Object.defineProperty(cst, "__esModule", { value: true }); -cst.addNoneTerminalToCst = cst.addTerminalToCst = cst.setNodeLocationFull = cst.setNodeLocationOnlyOffset = void 0; -/** - * This nodeLocation tracking is not efficient and should only be used - * when error recovery is enabled or the Token Vector contains virtual Tokens - * (e.g, Python Indent/Outdent) - * As it executes the calculation for every single terminal/nonTerminal - * and does not rely on the fact the token vector is **sorted** - */ -function setNodeLocationOnlyOffset(currNodeLocation, newLocationInfo) { - // First (valid) update for this cst node - if (isNaN(currNodeLocation.startOffset) === true) { - // assumption1: Token location information is either NaN or a valid number - // assumption2: Token location information is fully valid if it exist - // (both start/end offsets exist and are numbers). - currNodeLocation.startOffset = newLocationInfo.startOffset; - currNodeLocation.endOffset = newLocationInfo.endOffset; - } - // Once the startOffset has been updated with a valid number it should never receive - // any farther updates as the Token vector is sorted. - // We still have to check this this condition for every new possible location info - // because with error recovery enabled we may encounter invalid tokens (NaN location props) - else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { - currNodeLocation.endOffset = newLocationInfo.endOffset; - } -} -cst.setNodeLocationOnlyOffset = setNodeLocationOnlyOffset; -/** - * This nodeLocation tracking is not efficient and should only be used - * when error recovery is enabled or the Token Vector contains virtual Tokens - * (e.g, Python Indent/Outdent) - * As it executes the calculation for every single terminal/nonTerminal - * and does not rely on the fact the token vector is **sorted** - */ -function setNodeLocationFull(currNodeLocation, newLocationInfo) { - // First (valid) update for this cst node - if (isNaN(currNodeLocation.startOffset) === true) { - // assumption1: Token location information is either NaN or a valid number - // assumption2: Token location information is fully valid if it exist - // (all start/end props exist and are numbers). - currNodeLocation.startOffset = newLocationInfo.startOffset; - currNodeLocation.startColumn = newLocationInfo.startColumn; - currNodeLocation.startLine = newLocationInfo.startLine; - currNodeLocation.endOffset = newLocationInfo.endOffset; - currNodeLocation.endColumn = newLocationInfo.endColumn; - currNodeLocation.endLine = newLocationInfo.endLine; - } - // Once the start props has been updated with a valid number it should never receive - // any farther updates as the Token vector is sorted. - // We still have to check this this condition for every new possible location info - // because with error recovery enabled we may encounter invalid tokens (NaN location props) - else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { - currNodeLocation.endOffset = newLocationInfo.endOffset; - currNodeLocation.endColumn = newLocationInfo.endColumn; - currNodeLocation.endLine = newLocationInfo.endLine; - } -} -cst.setNodeLocationFull = setNodeLocationFull; -function addTerminalToCst(node, token, tokenTypeName) { - if (node.children[tokenTypeName] === undefined) { - node.children[tokenTypeName] = [token]; - } - else { - node.children[tokenTypeName].push(token); - } -} -cst.addTerminalToCst = addTerminalToCst; -function addNoneTerminalToCst(node, ruleName, ruleResult) { - if (node.children[ruleName] === undefined) { - node.children[ruleName] = [ruleResult]; - } - else { - node.children[ruleName].push(ruleResult); - } -} -cst.addNoneTerminalToCst = addNoneTerminalToCst; + constructClassInstance(workInProgress, Component, nextProps); + mountClassInstance(workInProgress, Component, nextProps, renderLanes); + shouldUpdate = true; + } else if (current === null) { + // In a resume, we'll already have an instance we can reuse. + shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes); + } else { + shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes); + } -var cst_visitor = {}; + var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes); -var lang_extensions = {}; + { + var inst = workInProgress.stateNode; -Object.defineProperty(lang_extensions, "__esModule", { value: true }); -lang_extensions.defineNameProp = void 0; -var NAME = "name"; -function defineNameProp(obj, nameValue) { - Object.defineProperty(obj, NAME, { - enumerable: false, - configurable: true, - writable: false, - value: nameValue - }); -} -lang_extensions.defineNameProp = defineNameProp; + if (shouldUpdate && inst.props !== nextProps) { + if (!didWarnAboutReassigningProps) { + error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component'); + } -(function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateRedundantMethods = exports.validateMissingCstMethods = exports.validateVisitor = exports.CstVisitorDefinitionError = exports.createBaseVisitorConstructorWithDefaults = exports.createBaseSemanticVisitorConstructor = exports.defaultVisit = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var compact_1$1 = __importDefault(compact_1); - var isArray_1 = __importDefault(isArray_1$1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var filter_1$1 = __importDefault(filter_1); - var keys_1$1 = __importDefault(keys_1); - var isFunction_1$1 = __importDefault(isFunction_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var includes_1 = __importDefault(includes_1$2); - var lang_extensions_1 = lang_extensions; - function defaultVisit(ctx, param) { - var childrenNames = (0, keys_1$1.default)(ctx); - var childrenNamesLength = childrenNames.length; - for (var i = 0; i < childrenNamesLength; i++) { - var currChildName = childrenNames[i]; - var currChildArray = ctx[currChildName]; - var currChildArrayLength = currChildArray.length; - for (var j = 0; j < currChildArrayLength; j++) { - var currChild = currChildArray[j]; - // distinction between Tokens Children and CstNode children - if (currChild.tokenTypeIdx === undefined) { - this[currChild.name](currChild.children, param); - } - } - } - // defaultVisit does not support generic out param - } - exports.defaultVisit = defaultVisit; - function createBaseSemanticVisitorConstructor(grammarName, ruleNames) { - var derivedConstructor = function () { }; - // can be overwritten according to: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/ - // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname - (0, lang_extensions_1.defineNameProp)(derivedConstructor, grammarName + "BaseSemantics"); - var semanticProto = { - visit: function (cstNode, param) { - // enables writing more concise visitor methods when CstNode has only a single child - if ((0, isArray_1.default)(cstNode)) { - // A CST Node's children dictionary can never have empty arrays as values - // If a key is defined there will be at least one element in the corresponding value array. - cstNode = cstNode[0]; - } - // enables passing optional CstNodes concisely. - if ((0, isUndefined_1.default)(cstNode)) { - return undefined; - } - return this[cstNode.name](cstNode.children, param); - }, - validateVisitor: function () { - var semanticDefinitionErrors = validateVisitor(this, ruleNames); - if (!(0, isEmpty_1.default)(semanticDefinitionErrors)) { - var errorMessages = (0, map_1.default)(semanticDefinitionErrors, function (currDefError) { return currDefError.msg; }); - throw Error("Errors Detected in CST Visitor <".concat(this.constructor.name, ">:\n\t") + - "".concat(errorMessages.join("\n\n").replace(/\n/g, "\n\t"))); - } - } - }; - derivedConstructor.prototype = semanticProto; - derivedConstructor.prototype.constructor = derivedConstructor; - derivedConstructor._RULE_NAMES = ruleNames; - return derivedConstructor; - } - exports.createBaseSemanticVisitorConstructor = createBaseSemanticVisitorConstructor; - function createBaseVisitorConstructorWithDefaults(grammarName, ruleNames, baseConstructor) { - var derivedConstructor = function () { }; - // can be overwritten according to: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/ - // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname - (0, lang_extensions_1.defineNameProp)(derivedConstructor, grammarName + "BaseSemanticsWithDefaults"); - var withDefaultsProto = Object.create(baseConstructor.prototype); - (0, forEach_1.default)(ruleNames, function (ruleName) { - withDefaultsProto[ruleName] = defaultVisit; - }); - derivedConstructor.prototype = withDefaultsProto; - derivedConstructor.prototype.constructor = derivedConstructor; - return derivedConstructor; - } - exports.createBaseVisitorConstructorWithDefaults = createBaseVisitorConstructorWithDefaults; - var CstVisitorDefinitionError; - (function (CstVisitorDefinitionError) { - CstVisitorDefinitionError[CstVisitorDefinitionError["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD"; - CstVisitorDefinitionError[CstVisitorDefinitionError["MISSING_METHOD"] = 1] = "MISSING_METHOD"; - })(CstVisitorDefinitionError = exports.CstVisitorDefinitionError || (exports.CstVisitorDefinitionError = {})); - function validateVisitor(visitorInstance, ruleNames) { - var missingErrors = validateMissingCstMethods(visitorInstance, ruleNames); - var redundantErrors = validateRedundantMethods(visitorInstance, ruleNames); - return missingErrors.concat(redundantErrors); - } - exports.validateVisitor = validateVisitor; - function validateMissingCstMethods(visitorInstance, ruleNames) { - var missingRuleNames = (0, filter_1$1.default)(ruleNames, function (currRuleName) { - return (0, isFunction_1$1.default)(visitorInstance[currRuleName]) === false; - }); - var errors = (0, map_1.default)(missingRuleNames, function (currRuleName) { - return { - msg: "Missing visitor method: <".concat(currRuleName, "> on ").concat((visitorInstance.constructor.name), " CST Visitor."), - type: CstVisitorDefinitionError.MISSING_METHOD, - methodName: currRuleName - }; - }); - return (0, compact_1$1.default)(errors); - } - exports.validateMissingCstMethods = validateMissingCstMethods; - var VALID_PROP_NAMES = ["constructor", "visit", "validateVisitor"]; - function validateRedundantMethods(visitorInstance, ruleNames) { - var errors = []; - for (var prop in visitorInstance) { - if ((0, isFunction_1$1.default)(visitorInstance[prop]) && - !(0, includes_1.default)(VALID_PROP_NAMES, prop) && - !(0, includes_1.default)(ruleNames, prop)) { - errors.push({ - msg: "Redundant visitor method: <".concat(prop, "> on ").concat((visitorInstance.constructor.name), " CST Visitor\n") + - "There is no Grammar Rule corresponding to this method's name.\n", - type: CstVisitorDefinitionError.REDUNDANT_METHOD, - methodName: prop - }); - } + didWarnAboutReassigningProps = true; } - return errors; - } - exports.validateRedundantMethods = validateRedundantMethods; - -} (cst_visitor)); + } -var hasRequiredTree_builder; + return nextUnitOfWork; + } -function requireTree_builder () { - if (hasRequiredTree_builder) return tree_builder; - hasRequiredTree_builder = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(tree_builder, "__esModule", { value: true }); - tree_builder.TreeBuilder = void 0; - var cst_1 = cst; - var noop_1$1 = __importDefault(noop_1); - var has_1$1 = __importDefault(has_1); - var keys_1$1 = __importDefault(keys_1); - var isUndefined_1 = __importDefault(isUndefined_1$1); - var cst_visitor_1 = cst_visitor; - var parser_1 = requireParser(); - /** - * This trait is responsible for the CST building logic. - */ - var TreeBuilder = /** @class */ (function () { - function TreeBuilder() { - } - TreeBuilder.prototype.initTreeBuilder = function (config) { - this.CST_STACK = []; - // outputCst is no longer exposed/defined in the pubic API - this.outputCst = config.outputCst; - this.nodeLocationTracking = (0, has_1$1.default)(config, "nodeLocationTracking") - ? config.nodeLocationTracking // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.nodeLocationTracking; - if (!this.outputCst) { - this.cstInvocationStateUpdate = noop_1$1.default; - this.cstFinallyStateUpdate = noop_1$1.default; - this.cstPostTerminal = noop_1$1.default; - this.cstPostNonTerminal = noop_1$1.default; - this.cstPostRule = noop_1$1.default; - } - else { - if (/full/i.test(this.nodeLocationTracking)) { - if (this.recoveryEnabled) { - this.setNodeLocationFromToken = cst_1.setNodeLocationFull; - this.setNodeLocationFromNode = cst_1.setNodeLocationFull; - this.cstPostRule = noop_1$1.default; - this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery; - } - else { - this.setNodeLocationFromToken = noop_1$1.default; - this.setNodeLocationFromNode = noop_1$1.default; - this.cstPostRule = this.cstPostRuleFull; - this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular; - } - } - else if (/onlyOffset/i.test(this.nodeLocationTracking)) { - if (this.recoveryEnabled) { - this.setNodeLocationFromToken = cst_1.setNodeLocationOnlyOffset; - this.setNodeLocationFromNode = cst_1.setNodeLocationOnlyOffset; - this.cstPostRule = noop_1$1.default; - this.setInitialNodeLocation = - this.setInitialNodeLocationOnlyOffsetRecovery; - } - else { - this.setNodeLocationFromToken = noop_1$1.default; - this.setNodeLocationFromNode = noop_1$1.default; - this.cstPostRule = this.cstPostRuleOnlyOffset; - this.setInitialNodeLocation = - this.setInitialNodeLocationOnlyOffsetRegular; - } - } - else if (/none/i.test(this.nodeLocationTracking)) { - this.setNodeLocationFromToken = noop_1$1.default; - this.setNodeLocationFromNode = noop_1$1.default; - this.cstPostRule = noop_1$1.default; - this.setInitialNodeLocation = noop_1$1.default; - } - else { - throw Error("Invalid config option: \"".concat(config.nodeLocationTracking, "\"")); - } - } - }; - TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRecovery = function (cstNode) { - cstNode.location = { - startOffset: NaN, - endOffset: NaN - }; - }; - TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRegular = function (cstNode) { - cstNode.location = { - // without error recovery the starting Location of a new CstNode is guaranteed - // To be the next Token's startOffset (for valid inputs). - // For invalid inputs there won't be any CSTOutput so this potential - // inaccuracy does not matter - startOffset: this.LA(1).startOffset, - endOffset: NaN - }; - }; - TreeBuilder.prototype.setInitialNodeLocationFullRecovery = function (cstNode) { - cstNode.location = { - startOffset: NaN, - startLine: NaN, - startColumn: NaN, - endOffset: NaN, - endLine: NaN, - endColumn: NaN - }; - }; - /** - * @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work - - * @param cstNode - */ - TreeBuilder.prototype.setInitialNodeLocationFullRegular = function (cstNode) { - var nextToken = this.LA(1); - cstNode.location = { - startOffset: nextToken.startOffset, - startLine: nextToken.startLine, - startColumn: nextToken.startColumn, - endOffset: NaN, - endLine: NaN, - endColumn: NaN - }; - }; - TreeBuilder.prototype.cstInvocationStateUpdate = function (fullRuleName) { - var cstNode = { - name: fullRuleName, - children: Object.create(null) - }; - this.setInitialNodeLocation(cstNode); - this.CST_STACK.push(cstNode); - }; - TreeBuilder.prototype.cstFinallyStateUpdate = function () { - this.CST_STACK.pop(); - }; - TreeBuilder.prototype.cstPostRuleFull = function (ruleCstNode) { - // casts to `required` are safe because `cstPostRuleFull` should only be invoked when full location is enabled - var prevToken = this.LA(0); - var loc = ruleCstNode.location; - // If this condition is true it means we consumed at least one Token - // In this CstNode. - if (loc.startOffset <= prevToken.startOffset === true) { - loc.endOffset = prevToken.endOffset; - loc.endLine = prevToken.endLine; - loc.endColumn = prevToken.endColumn; - } - // "empty" CstNode edge case - else { - loc.startOffset = NaN; - loc.startLine = NaN; - loc.startColumn = NaN; - } - }; - TreeBuilder.prototype.cstPostRuleOnlyOffset = function (ruleCstNode) { - var prevToken = this.LA(0); - // `location' is not null because `cstPostRuleOnlyOffset` will only be invoked when location tracking is enabled. - var loc = ruleCstNode.location; - // If this condition is true it means we consumed at least one Token - // In this CstNode. - if (loc.startOffset <= prevToken.startOffset === true) { - loc.endOffset = prevToken.endOffset; - } - // "empty" CstNode edge case - else { - loc.startOffset = NaN; - } - }; - TreeBuilder.prototype.cstPostTerminal = function (key, consumedToken) { - var rootCst = this.CST_STACK[this.CST_STACK.length - 1]; - (0, cst_1.addTerminalToCst)(rootCst, consumedToken, key); - // This is only used when **both** error recovery and CST Output are enabled. - this.setNodeLocationFromToken(rootCst.location, consumedToken); - }; - TreeBuilder.prototype.cstPostNonTerminal = function (ruleCstResult, ruleName) { - var preCstNode = this.CST_STACK[this.CST_STACK.length - 1]; - (0, cst_1.addNoneTerminalToCst)(preCstNode, ruleName, ruleCstResult); - // This is only used when **both** error recovery and CST Output are enabled. - this.setNodeLocationFromNode(preCstNode.location, ruleCstResult.location); - }; - TreeBuilder.prototype.getBaseCstVisitorConstructor = function () { - if ((0, isUndefined_1.default)(this.baseCstVisitorConstructor)) { - var newBaseCstVisitorConstructor = (0, cst_visitor_1.createBaseSemanticVisitorConstructor)(this.className, (0, keys_1$1.default)(this.gastProductionsCache)); - this.baseCstVisitorConstructor = newBaseCstVisitorConstructor; - return newBaseCstVisitorConstructor; - } - return this.baseCstVisitorConstructor; - }; - TreeBuilder.prototype.getBaseCstVisitorConstructorWithDefaults = function () { - if ((0, isUndefined_1.default)(this.baseCstVisitorWithDefaultsConstructor)) { - var newConstructor = (0, cst_visitor_1.createBaseVisitorConstructorWithDefaults)(this.className, (0, keys_1$1.default)(this.gastProductionsCache), this.getBaseCstVisitorConstructor()); - this.baseCstVisitorWithDefaultsConstructor = newConstructor; - return newConstructor; - } - return this.baseCstVisitorWithDefaultsConstructor; - }; - TreeBuilder.prototype.getLastExplicitRuleShortName = function () { - var ruleStack = this.RULE_STACK; - return ruleStack[ruleStack.length - 1]; - }; - TreeBuilder.prototype.getPreviousExplicitRuleShortName = function () { - var ruleStack = this.RULE_STACK; - return ruleStack[ruleStack.length - 2]; - }; - TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndex = function () { - var occurrenceStack = this.RULE_OCCURRENCE_STACK; - return occurrenceStack[occurrenceStack.length - 1]; - }; - return TreeBuilder; - }()); - tree_builder.TreeBuilder = TreeBuilder; - - return tree_builder; -} + function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) { + // Refs should update even if shouldComponentUpdate returns false + markRef$1(current, workInProgress); + var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags; -var lexer_adapter = {}; + if (!shouldUpdate && !didCaptureError) { + // Context providers should defer to sCU for rendering + if (hasContext) { + invalidateContextProvider(workInProgress, Component, false); + } -var hasRequiredLexer_adapter; + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } -function requireLexer_adapter () { - if (hasRequiredLexer_adapter) return lexer_adapter; - hasRequiredLexer_adapter = 1; - Object.defineProperty(lexer_adapter, "__esModule", { value: true }); - lexer_adapter.LexerAdapter = void 0; - var parser_1 = requireParser(); - /** - * Trait responsible abstracting over the interaction with Lexer output (Token vector). - * - * This could be generalized to support other kinds of lexers, e.g. - * - Just in Time Lexing / Lexer-Less parsing. - * - Streaming Lexer. - */ - var LexerAdapter = /** @class */ (function () { - function LexerAdapter() { - } - LexerAdapter.prototype.initLexerAdapter = function () { - this.tokVector = []; - this.tokVectorLength = 0; - this.currIdx = -1; - }; - Object.defineProperty(LexerAdapter.prototype, "input", { - get: function () { - return this.tokVector; - }, - set: function (newInput) { - // @ts-ignore - `this parameter` not supported in setters/getters - // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters - if (this.selfAnalysisDone !== true) { - throw Error("Missing invocation at the end of the Parser's constructor."); - } - // @ts-ignore - `this parameter` not supported in setters/getters - // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters - this.reset(); - this.tokVector = newInput; - this.tokVectorLength = newInput.length; - }, - enumerable: false, - configurable: true - }); - // skips a token and returns the next token - LexerAdapter.prototype.SKIP_TOKEN = function () { - if (this.currIdx <= this.tokVector.length - 2) { - this.consumeToken(); - return this.LA(1); - } - else { - return parser_1.END_OF_FILE; - } - }; - // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers - // or lexers dependent on parser context. - LexerAdapter.prototype.LA = function (howMuch) { - var soughtIdx = this.currIdx + howMuch; - if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) { - return parser_1.END_OF_FILE; - } - else { - return this.tokVector[soughtIdx]; - } - }; - LexerAdapter.prototype.consumeToken = function () { - this.currIdx++; - }; - LexerAdapter.prototype.exportLexerState = function () { - return this.currIdx; - }; - LexerAdapter.prototype.importLexerState = function (newState) { - this.currIdx = newState; - }; - LexerAdapter.prototype.resetLexerState = function () { - this.currIdx = -1; - }; - LexerAdapter.prototype.moveToTerminatedState = function () { - this.currIdx = this.tokVector.length - 1; - }; - LexerAdapter.prototype.getLexerPosition = function () { - return this.exportLexerState(); - }; - return LexerAdapter; - }()); - lexer_adapter.LexerAdapter = LexerAdapter; - - return lexer_adapter; -} + var instance = workInProgress.stateNode; // Rerender -var recognizer_api = {}; + ReactCurrentOwner$1.current = workInProgress; + var nextChildren; -var hasRequiredRecognizer_api; + if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') { + // If we captured an error, but getDerivedStateFromError is not defined, + // unmount all the children. componentDidCatch will schedule an update to + // re-render a fallback. This is temporary until we migrate everyone to + // the new API. + // TODO: Warn in a future release. + nextChildren = null; -function requireRecognizer_api () { - if (hasRequiredRecognizer_api) return recognizer_api; - hasRequiredRecognizer_api = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(recognizer_api, "__esModule", { value: true }); - recognizer_api.RecognizerApi = void 0; - var values_1 = __importDefault(values_1$1); - var includes_1 = __importDefault(includes_1$2); - var exceptions_public_1 = exceptions_public; - var parser_1 = requireParser(); - var errors_public_1 = errors_public; - var checks_1 = requireChecks(); - var gast_1 = api$1; - /** - * This trait is responsible for implementing the public API - * for defining Chevrotain parsers, i.e: - * - CONSUME - * - RULE - * - OPTION - * - ... - */ - var RecognizerApi = /** @class */ (function () { - function RecognizerApi() { + { + stopProfilerTimerIfRunning(); + } + } else { + { + markComponentRenderStarted(workInProgress); } - RecognizerApi.prototype.ACTION = function (impl) { - return impl.call(this); - }; - RecognizerApi.prototype.consume = function (idx, tokType, options) { - return this.consumeInternal(tokType, idx, options); - }; - RecognizerApi.prototype.subrule = function (idx, ruleToCall, options) { - return this.subruleInternal(ruleToCall, idx, options); - }; - RecognizerApi.prototype.option = function (idx, actionORMethodDef) { - return this.optionInternal(actionORMethodDef, idx); - }; - RecognizerApi.prototype.or = function (idx, altsOrOpts) { - return this.orInternal(altsOrOpts, idx); - }; - RecognizerApi.prototype.many = function (idx, actionORMethodDef) { - return this.manyInternal(idx, actionORMethodDef); - }; - RecognizerApi.prototype.atLeastOne = function (idx, actionORMethodDef) { - return this.atLeastOneInternal(idx, actionORMethodDef); - }; - RecognizerApi.prototype.CONSUME = function (tokType, options) { - return this.consumeInternal(tokType, 0, options); - }; - RecognizerApi.prototype.CONSUME1 = function (tokType, options) { - return this.consumeInternal(tokType, 1, options); - }; - RecognizerApi.prototype.CONSUME2 = function (tokType, options) { - return this.consumeInternal(tokType, 2, options); - }; - RecognizerApi.prototype.CONSUME3 = function (tokType, options) { - return this.consumeInternal(tokType, 3, options); - }; - RecognizerApi.prototype.CONSUME4 = function (tokType, options) { - return this.consumeInternal(tokType, 4, options); - }; - RecognizerApi.prototype.CONSUME5 = function (tokType, options) { - return this.consumeInternal(tokType, 5, options); - }; - RecognizerApi.prototype.CONSUME6 = function (tokType, options) { - return this.consumeInternal(tokType, 6, options); - }; - RecognizerApi.prototype.CONSUME7 = function (tokType, options) { - return this.consumeInternal(tokType, 7, options); - }; - RecognizerApi.prototype.CONSUME8 = function (tokType, options) { - return this.consumeInternal(tokType, 8, options); - }; - RecognizerApi.prototype.CONSUME9 = function (tokType, options) { - return this.consumeInternal(tokType, 9, options); - }; - RecognizerApi.prototype.SUBRULE = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 0, options); - }; - RecognizerApi.prototype.SUBRULE1 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 1, options); - }; - RecognizerApi.prototype.SUBRULE2 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 2, options); - }; - RecognizerApi.prototype.SUBRULE3 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 3, options); - }; - RecognizerApi.prototype.SUBRULE4 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 4, options); - }; - RecognizerApi.prototype.SUBRULE5 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 5, options); - }; - RecognizerApi.prototype.SUBRULE6 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 6, options); - }; - RecognizerApi.prototype.SUBRULE7 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 7, options); - }; - RecognizerApi.prototype.SUBRULE8 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 8, options); - }; - RecognizerApi.prototype.SUBRULE9 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 9, options); - }; - RecognizerApi.prototype.OPTION = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 0); - }; - RecognizerApi.prototype.OPTION1 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 1); - }; - RecognizerApi.prototype.OPTION2 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 2); - }; - RecognizerApi.prototype.OPTION3 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 3); - }; - RecognizerApi.prototype.OPTION4 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 4); - }; - RecognizerApi.prototype.OPTION5 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 5); - }; - RecognizerApi.prototype.OPTION6 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 6); - }; - RecognizerApi.prototype.OPTION7 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 7); - }; - RecognizerApi.prototype.OPTION8 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 8); - }; - RecognizerApi.prototype.OPTION9 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 9); - }; - RecognizerApi.prototype.OR = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 0); - }; - RecognizerApi.prototype.OR1 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 1); - }; - RecognizerApi.prototype.OR2 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 2); - }; - RecognizerApi.prototype.OR3 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 3); - }; - RecognizerApi.prototype.OR4 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 4); - }; - RecognizerApi.prototype.OR5 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 5); - }; - RecognizerApi.prototype.OR6 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 6); - }; - RecognizerApi.prototype.OR7 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 7); - }; - RecognizerApi.prototype.OR8 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 8); - }; - RecognizerApi.prototype.OR9 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 9); - }; - RecognizerApi.prototype.MANY = function (actionORMethodDef) { - this.manyInternal(0, actionORMethodDef); - }; - RecognizerApi.prototype.MANY1 = function (actionORMethodDef) { - this.manyInternal(1, actionORMethodDef); - }; - RecognizerApi.prototype.MANY2 = function (actionORMethodDef) { - this.manyInternal(2, actionORMethodDef); - }; - RecognizerApi.prototype.MANY3 = function (actionORMethodDef) { - this.manyInternal(3, actionORMethodDef); - }; - RecognizerApi.prototype.MANY4 = function (actionORMethodDef) { - this.manyInternal(4, actionORMethodDef); - }; - RecognizerApi.prototype.MANY5 = function (actionORMethodDef) { - this.manyInternal(5, actionORMethodDef); - }; - RecognizerApi.prototype.MANY6 = function (actionORMethodDef) { - this.manyInternal(6, actionORMethodDef); - }; - RecognizerApi.prototype.MANY7 = function (actionORMethodDef) { - this.manyInternal(7, actionORMethodDef); - }; - RecognizerApi.prototype.MANY8 = function (actionORMethodDef) { - this.manyInternal(8, actionORMethodDef); - }; - RecognizerApi.prototype.MANY9 = function (actionORMethodDef) { - this.manyInternal(9, actionORMethodDef); - }; - RecognizerApi.prototype.MANY_SEP = function (options) { - this.manySepFirstInternal(0, options); - }; - RecognizerApi.prototype.MANY_SEP1 = function (options) { - this.manySepFirstInternal(1, options); - }; - RecognizerApi.prototype.MANY_SEP2 = function (options) { - this.manySepFirstInternal(2, options); - }; - RecognizerApi.prototype.MANY_SEP3 = function (options) { - this.manySepFirstInternal(3, options); - }; - RecognizerApi.prototype.MANY_SEP4 = function (options) { - this.manySepFirstInternal(4, options); - }; - RecognizerApi.prototype.MANY_SEP5 = function (options) { - this.manySepFirstInternal(5, options); - }; - RecognizerApi.prototype.MANY_SEP6 = function (options) { - this.manySepFirstInternal(6, options); - }; - RecognizerApi.prototype.MANY_SEP7 = function (options) { - this.manySepFirstInternal(7, options); - }; - RecognizerApi.prototype.MANY_SEP8 = function (options) { - this.manySepFirstInternal(8, options); - }; - RecognizerApi.prototype.MANY_SEP9 = function (options) { - this.manySepFirstInternal(9, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE = function (actionORMethodDef) { - this.atLeastOneInternal(0, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE1 = function (actionORMethodDef) { - return this.atLeastOneInternal(1, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE2 = function (actionORMethodDef) { - this.atLeastOneInternal(2, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE3 = function (actionORMethodDef) { - this.atLeastOneInternal(3, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE4 = function (actionORMethodDef) { - this.atLeastOneInternal(4, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE5 = function (actionORMethodDef) { - this.atLeastOneInternal(5, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE6 = function (actionORMethodDef) { - this.atLeastOneInternal(6, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE7 = function (actionORMethodDef) { - this.atLeastOneInternal(7, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE8 = function (actionORMethodDef) { - this.atLeastOneInternal(8, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE9 = function (actionORMethodDef) { - this.atLeastOneInternal(9, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP = function (options) { - this.atLeastOneSepFirstInternal(0, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP1 = function (options) { - this.atLeastOneSepFirstInternal(1, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP2 = function (options) { - this.atLeastOneSepFirstInternal(2, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP3 = function (options) { - this.atLeastOneSepFirstInternal(3, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP4 = function (options) { - this.atLeastOneSepFirstInternal(4, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP5 = function (options) { - this.atLeastOneSepFirstInternal(5, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP6 = function (options) { - this.atLeastOneSepFirstInternal(6, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP7 = function (options) { - this.atLeastOneSepFirstInternal(7, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP8 = function (options) { - this.atLeastOneSepFirstInternal(8, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP9 = function (options) { - this.atLeastOneSepFirstInternal(9, options); - }; - RecognizerApi.prototype.RULE = function (name, implementation, config) { - if (config === void 0) { config = parser_1.DEFAULT_RULE_CONFIG; } - if ((0, includes_1.default)(this.definedRulesNames, name)) { - var errMsg = errors_public_1.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ - topLevelRule: name, - grammarName: this.className - }); - var error = { - message: errMsg, - type: parser_1.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, - ruleName: name - }; - this.definitionErrors.push(error); - } - this.definedRulesNames.push(name); - var ruleImplementation = this.defineRule(name, implementation, config); - this[name] = ruleImplementation; - return ruleImplementation; - }; - RecognizerApi.prototype.OVERRIDE_RULE = function (name, impl, config) { - if (config === void 0) { config = parser_1.DEFAULT_RULE_CONFIG; } - var ruleErrors = (0, checks_1.validateRuleIsOverridden)(name, this.definedRulesNames, this.className); - this.definitionErrors = this.definitionErrors.concat(ruleErrors); - var ruleImplementation = this.defineRule(name, impl, config); - this[name] = ruleImplementation; - return ruleImplementation; - }; - RecognizerApi.prototype.BACKTRACK = function (grammarRule, args) { - return function () { - // save org state - this.isBackTrackingStack.push(1); - var orgState = this.saveRecogState(); - try { - grammarRule.apply(this, args); - // if no exception was thrown we have succeed parsing the rule. - return true; - } - catch (e) { - if ((0, exceptions_public_1.isRecognitionException)(e)) { - return false; - } - else { - throw e; - } - } - finally { - this.reloadRecogState(orgState); - this.isBackTrackingStack.pop(); - } - }; - }; - // GAST export APIs - RecognizerApi.prototype.getGAstProductions = function () { - return this.gastProductionsCache; - }; - RecognizerApi.prototype.getSerializedGastProductions = function () { - return (0, gast_1.serializeGrammar)((0, values_1.default)(this.gastProductionsCache)); - }; - return RecognizerApi; - }()); - recognizer_api.RecognizerApi = RecognizerApi; - - return recognizer_api; -} -var recognizer_engine = {}; + { + setIsRendering(true); + nextChildren = instance.render(); -var hasRequiredRecognizer_engine; + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); -function requireRecognizer_engine () { - if (hasRequiredRecognizer_engine) return recognizer_engine; - hasRequiredRecognizer_engine = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(recognizer_engine, "__esModule", { value: true }); - recognizer_engine.RecognizerEngine = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var isArray_1 = __importDefault(isArray_1$1); - var flatten_1 = __importDefault(flatten_1$3); - var every_1 = __importDefault(every_1$1); - var uniq_1 = __importDefault(uniq_1$2); - var isObject_1$1 = __importDefault(isObject_1); - var has_1$1 = __importDefault(has_1); - var values_1 = __importDefault(values_1$1); - var reduce_1 = __importDefault(reduce_1$1); - var clone_1 = __importDefault(clone_1$1); - var keys_1 = keys; - var exceptions_public_1 = exceptions_public; - var lookahead_1 = lookahead; - var interpreter_1 = interpreter; - var parser_1 = requireParser(); - var recoverable_1 = requireRecoverable(); - var tokens_public_1 = tokens_public; - var tokens_1 = tokens; - /** - * This trait is responsible for the runtime parsing engine - * Used by the official API (recognizer_api.ts) - */ - var RecognizerEngine = /** @class */ (function () { - function RecognizerEngine() { - } - RecognizerEngine.prototype.initRecognizerEngine = function (tokenVocabulary, config) { - this.className = this.constructor.name; - // TODO: would using an ES6 Map or plain object be faster (CST building scenario) - this.shortRuleNameToFull = {}; - this.fullRuleNameToShort = {}; - this.ruleShortNameIdx = 256; - this.tokenMatcher = tokens_1.tokenStructuredMatcherNoCategories; - this.subruleIdx = 0; - this.definedRulesNames = []; - this.tokensMap = {}; - this.isBackTrackingStack = []; - this.RULE_STACK = []; - this.RULE_OCCURRENCE_STACK = []; - this.gastProductionsCache = {}; - if ((0, has_1$1.default)(config, "serializedGrammar")) { - throw Error("The Parser's configuration can no longer contain a property.\n" + - "\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\n" + - "\tFor Further details."); - } - if ((0, isArray_1.default)(tokenVocabulary)) { - // This only checks for Token vocabularies provided as arrays. - // That is good enough because the main objective is to detect users of pre-V4.0 APIs - // rather than all edge cases of empty Token vocabularies. - if ((0, isEmpty_1.default)(tokenVocabulary)) { - throw Error("A Token Vocabulary cannot be empty.\n" + - "\tNote that the first argument for the parser constructor\n" + - "\tis no longer a Token vector (since v4.0)."); - } - if (typeof tokenVocabulary[0].startOffset === "number") { - throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n" + - "\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0\n" + - "\tFor Further details."); - } - } - if ((0, isArray_1.default)(tokenVocabulary)) { - this.tokensMap = (0, reduce_1.default)(tokenVocabulary, function (acc, tokType) { - acc[tokType.name] = tokType; - return acc; - }, {}); - } - else if ((0, has_1$1.default)(tokenVocabulary, "modes") && - (0, every_1.default)((0, flatten_1.default)((0, values_1.default)(tokenVocabulary.modes)), tokens_1.isTokenType)) { - var allTokenTypes_1 = (0, flatten_1.default)((0, values_1.default)(tokenVocabulary.modes)); - var uniqueTokens = (0, uniq_1.default)(allTokenTypes_1); - this.tokensMap = (0, reduce_1.default)(uniqueTokens, function (acc, tokType) { - acc[tokType.name] = tokType; - return acc; - }, {}); - } - else if ((0, isObject_1$1.default)(tokenVocabulary)) { - this.tokensMap = (0, clone_1.default)(tokenVocabulary); - } - else { - throw new Error(" argument must be An Array of Token constructors," + - " A dictionary of Token constructors or an IMultiModeLexerDefinition"); - } - // always add EOF to the tokenNames -> constructors map. it is useful to assure all the input has been - // parsed with a clear error message ("expecting EOF but found ...") - this.tokensMap["EOF"] = tokens_public_1.EOF; - var allTokenTypes = (0, has_1$1.default)(tokenVocabulary, "modes") - ? (0, flatten_1.default)((0, values_1.default)(tokenVocabulary.modes)) - : (0, values_1.default)(tokenVocabulary); - var noTokenCategoriesUsed = (0, every_1.default)(allTokenTypes, function (tokenConstructor) { - return (0, isEmpty_1.default)(tokenConstructor.categoryMatches); - }); - this.tokenMatcher = noTokenCategoriesUsed - ? tokens_1.tokenStructuredMatcherNoCategories - : tokens_1.tokenStructuredMatcher; - // Because ES2015+ syntax should be supported for creating Token classes - // We cannot assume that the Token classes were created using the "extendToken" utilities - // Therefore we must augment the Token classes both on Lexer initialization and on Parser initialization - (0, tokens_1.augmentTokenTypes)((0, values_1.default)(this.tokensMap)); - }; - RecognizerEngine.prototype.defineRule = function (ruleName, impl, config) { - if (this.selfAnalysisDone) { - throw Error("Grammar rule <".concat(ruleName, "> may not be defined after the 'performSelfAnalysis' method has been called'\n") + - "Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called."); - } - var resyncEnabled = (0, has_1$1.default)(config, "resyncEnabled") - ? config.resyncEnabled // assumes end user provides the correct config value/type - : parser_1.DEFAULT_RULE_CONFIG.resyncEnabled; - var recoveryValueFunc = (0, has_1$1.default)(config, "recoveryValueFunc") - ? config.recoveryValueFunc // assumes end user provides the correct config value/type - : parser_1.DEFAULT_RULE_CONFIG.recoveryValueFunc; - // performance optimization: Use small integers as keys for the longer human readable "full" rule names. - // this greatly improves Map access time (as much as 8% for some performance benchmarks). - var shortName = this.ruleShortNameIdx << (keys_1.BITS_FOR_METHOD_TYPE + keys_1.BITS_FOR_OCCURRENCE_IDX); - this.ruleShortNameIdx++; - this.shortRuleNameToFull[shortName] = ruleName; - this.fullRuleNameToShort[ruleName] = shortName; - var invokeRuleWithTry; - // Micro optimization, only check the condition **once** on rule definition - // instead of **every single** rule invocation. - if (this.outputCst === true) { - invokeRuleWithTry = function invokeRuleWithTry() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - try { - this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx); - impl.apply(this, args); - var cst = this.CST_STACK[this.CST_STACK.length - 1]; - this.cstPostRule(cst); - return cst; - } - catch (e) { - return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc); - } - finally { - this.ruleFinallyStateUpdate(); - } - }; - } - else { - invokeRuleWithTry = function invokeRuleWithTryCst() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - try { - this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx); - return impl.apply(this, args); - } - catch (e) { - return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc); - } - finally { - this.ruleFinallyStateUpdate(); - } - }; - } - var wrappedGrammarRule = Object.assign(invokeRuleWithTry, { ruleName: ruleName, originalGrammarAction: impl }); - return wrappedGrammarRule; - }; - RecognizerEngine.prototype.invokeRuleCatch = function (e, resyncEnabledConfig, recoveryValueFunc) { - var isFirstInvokedRule = this.RULE_STACK.length === 1; - // note the reSync is always enabled for the first rule invocation, because we must always be able to - // reSync with EOF and just output some INVALID ParseTree - // during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking - // path is really the most valid one - var reSyncEnabled = resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled; - if ((0, exceptions_public_1.isRecognitionException)(e)) { - var recogError = e; - if (reSyncEnabled) { - var reSyncTokType = this.findReSyncTokenType(); - if (this.isInCurrentRuleReSyncSet(reSyncTokType)) { - recogError.resyncedTokens = this.reSyncTo(reSyncTokType); - if (this.outputCst) { - var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; - partialCstResult.recoveredNode = true; - return partialCstResult; - } - else { - return recoveryValueFunc(); - } - } - else { - if (this.outputCst) { - var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; - partialCstResult.recoveredNode = true; - recogError.partialCstResult = partialCstResult; - } - // to be handled Further up the call stack - throw recogError; - } - } - else if (isFirstInvokedRule) { - // otherwise a Redundant input error will be created as well and we cannot guarantee that this is indeed the case - this.moveToTerminatedState(); - // the parser should never throw one of its own errors outside its flow. - // even if error recovery is disabled - return recoveryValueFunc(); - } - else { - // to be recovered Further up the call stack - throw recogError; - } - } - else { - // some other Error type which we don't know how to handle (for example a built in JavaScript Error) - throw e; - } - }; - // Implementation of parsing DSL - RecognizerEngine.prototype.optionInternal = function (actionORMethodDef, occurrence) { - var key = this.getKeyForAutomaticLookahead(keys_1.OPTION_IDX, occurrence); - return this.optionInternalLogic(actionORMethodDef, occurrence, key); - }; - RecognizerEngine.prototype.optionInternalLogic = function (actionORMethodDef, occurrence, key) { - var _this = this; - var lookAheadFunc = this.getLaFuncFromCache(key); - var action; - if (typeof actionORMethodDef !== "function") { - action = actionORMethodDef.DEF; - var predicate_1 = actionORMethodDef.GATE; - // predicate present - if (predicate_1 !== undefined) { - var orgLookaheadFunction_1 = lookAheadFunc; - lookAheadFunc = function () { - return predicate_1.call(_this) && orgLookaheadFunction_1.call(_this); - }; - } - } - else { - action = actionORMethodDef; - } - if (lookAheadFunc.call(this) === true) { - return action.call(this); - } - return undefined; - }; - RecognizerEngine.prototype.atLeastOneInternal = function (prodOccurrence, actionORMethodDef) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_IDX, prodOccurrence); - return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey); - }; - RecognizerEngine.prototype.atLeastOneInternalLogic = function (prodOccurrence, actionORMethodDef, key) { - var _this = this; - var lookAheadFunc = this.getLaFuncFromCache(key); - var action; - if (typeof actionORMethodDef !== "function") { - action = actionORMethodDef.DEF; - var predicate_2 = actionORMethodDef.GATE; - // predicate present - if (predicate_2 !== undefined) { - var orgLookaheadFunction_2 = lookAheadFunc; - lookAheadFunc = function () { - return predicate_2.call(_this) && orgLookaheadFunction_2.call(_this); - }; - } - } - else { - action = actionORMethodDef; - } - if (lookAheadFunc.call(this) === true) { - var notStuck = this.doSingleRepetition(action); - while (lookAheadFunc.call(this) === true && - notStuck === true) { - notStuck = this.doSingleRepetition(action); - } - } - else { - throw this.raiseEarlyExitException(prodOccurrence, lookahead_1.PROD_TYPE.REPETITION_MANDATORY, actionORMethodDef.ERR_MSG); - } - // note that while it may seem that this can cause an error because by using a recursive call to - // AT_LEAST_ONE we change the grammar to AT_LEAST_TWO, AT_LEAST_THREE ... , the possible recursive call - // from the tryInRepetitionRecovery(...) will only happen IFF there really are TWO/THREE/.... items. - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.atLeastOneInternal, [prodOccurrence, actionORMethodDef], lookAheadFunc, keys_1.AT_LEAST_ONE_IDX, prodOccurrence, interpreter_1.NextTerminalAfterAtLeastOneWalker); - }; - RecognizerEngine.prototype.atLeastOneSepFirstInternal = function (prodOccurrence, options) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence); - this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey); - }; - RecognizerEngine.prototype.atLeastOneSepFirstInternalLogic = function (prodOccurrence, options, key) { - var _this = this; - var action = options.DEF; - var separator = options.SEP; - var firstIterationLookaheadFunc = this.getLaFuncFromCache(key); - // 1st iteration - if (firstIterationLookaheadFunc.call(this) === true) { - action.call(this); - // TODO: Optimization can move this function construction into "attemptInRepetitionRecovery" - // because it is only needed in error recovery scenarios. - var separatorLookAheadFunc = function () { - return _this.tokenMatcher(_this.LA(1), separator); - }; - // 2nd..nth iterations - while (this.tokenMatcher(this.LA(1), separator) === true) { - // note that this CONSUME will never enter recovery because - // the separatorLookAheadFunc checks that the separator really does exist. - this.CONSUME(separator); - action.call(this); - } - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ - prodOccurrence, - separator, - separatorLookAheadFunc, - action, - interpreter_1.NextTerminalAfterAtLeastOneSepWalker - ], separatorLookAheadFunc, keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence, interpreter_1.NextTerminalAfterAtLeastOneSepWalker); - } - else { - throw this.raiseEarlyExitException(prodOccurrence, lookahead_1.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG); - } - }; - RecognizerEngine.prototype.manyInternal = function (prodOccurrence, actionORMethodDef) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_IDX, prodOccurrence); - return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey); - }; - RecognizerEngine.prototype.manyInternalLogic = function (prodOccurrence, actionORMethodDef, key) { - var _this = this; - var lookaheadFunction = this.getLaFuncFromCache(key); - var action; - if (typeof actionORMethodDef !== "function") { - action = actionORMethodDef.DEF; - var predicate_3 = actionORMethodDef.GATE; - // predicate present - if (predicate_3 !== undefined) { - var orgLookaheadFunction_3 = lookaheadFunction; - lookaheadFunction = function () { - return predicate_3.call(_this) && orgLookaheadFunction_3.call(_this); - }; - } - } - else { - action = actionORMethodDef; - } - var notStuck = true; - while (lookaheadFunction.call(this) === true && notStuck === true) { - notStuck = this.doSingleRepetition(action); - } - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.manyInternal, [prodOccurrence, actionORMethodDef], lookaheadFunction, keys_1.MANY_IDX, prodOccurrence, interpreter_1.NextTerminalAfterManyWalker, - // The notStuck parameter is only relevant when "attemptInRepetitionRecovery" - // is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP] - // An infinite loop cannot occur as: - // - Either the lookahead is guaranteed to consume something (Single Token Separator) - // - AT_LEAST_ONE by definition is guaranteed to consume something (or error out). - notStuck); - }; - RecognizerEngine.prototype.manySepFirstInternal = function (prodOccurrence, options) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_SEP_IDX, prodOccurrence); - this.manySepFirstInternalLogic(prodOccurrence, options, laKey); - }; - RecognizerEngine.prototype.manySepFirstInternalLogic = function (prodOccurrence, options, key) { - var _this = this; - var action = options.DEF; - var separator = options.SEP; - var firstIterationLaFunc = this.getLaFuncFromCache(key); - // 1st iteration - if (firstIterationLaFunc.call(this) === true) { - action.call(this); - var separatorLookAheadFunc = function () { - return _this.tokenMatcher(_this.LA(1), separator); - }; - // 2nd..nth iterations - while (this.tokenMatcher(this.LA(1), separator) === true) { - // note that this CONSUME will never enter recovery because - // the separatorLookAheadFunc checks that the separator really does exist. - this.CONSUME(separator); - // No need for checking infinite loop here due to consuming the separator. - action.call(this); - } - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ - prodOccurrence, - separator, - separatorLookAheadFunc, - action, - interpreter_1.NextTerminalAfterManySepWalker - ], separatorLookAheadFunc, keys_1.MANY_SEP_IDX, prodOccurrence, interpreter_1.NextTerminalAfterManySepWalker); - } - }; - RecognizerEngine.prototype.repetitionSepSecondInternal = function (prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker) { - while (separatorLookAheadFunc()) { - // note that this CONSUME will never enter recovery because - // the separatorLookAheadFunc checks that the separator really does exist. - this.CONSUME(separator); - action.call(this); - } - // we can only arrive to this function after an error - // has occurred (hence the name 'second') so the following - // IF will always be entered, its possible to remove it... - // however it is kept to avoid confusion and be consistent. - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - /* istanbul ignore else */ - this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ - prodOccurrence, - separator, - separatorLookAheadFunc, - action, - nextTerminalAfterWalker - ], separatorLookAheadFunc, keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker); - }; - RecognizerEngine.prototype.doSingleRepetition = function (action) { - var beforeIteration = this.getLexerPosition(); - action.call(this); - var afterIteration = this.getLexerPosition(); - // This boolean will indicate if this repetition progressed - // or if we are "stuck" (potential infinite loop in the repetition). - return afterIteration > beforeIteration; - }; - RecognizerEngine.prototype.orInternal = function (altsOrOpts, occurrence) { - var laKey = this.getKeyForAutomaticLookahead(keys_1.OR_IDX, occurrence); - var alts = (0, isArray_1.default)(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF; - var laFunc = this.getLaFuncFromCache(laKey); - var altIdxToTake = laFunc.call(this, alts); - if (altIdxToTake !== undefined) { - var chosenAlternative = alts[altIdxToTake]; - return chosenAlternative.ALT.call(this); - } - this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG); - }; - RecognizerEngine.prototype.ruleFinallyStateUpdate = function () { - this.RULE_STACK.pop(); - this.RULE_OCCURRENCE_STACK.pop(); - // NOOP when cst is disabled - this.cstFinallyStateUpdate(); - if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) { - var firstRedundantTok = this.LA(1); - var errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({ - firstRedundant: firstRedundantTok, - ruleName: this.getCurrRuleFullName() - }); - this.SAVE_ERROR(new exceptions_public_1.NotAllInputParsedException(errMsg, firstRedundantTok)); - } - }; - RecognizerEngine.prototype.subruleInternal = function (ruleToCall, idx, options) { - var ruleResult; - try { - var args = options !== undefined ? options.ARGS : undefined; - this.subruleIdx = idx; - ruleResult = ruleToCall.apply(this, args); - this.cstPostNonTerminal(ruleResult, options !== undefined && options.LABEL !== undefined - ? options.LABEL - : ruleToCall.ruleName); - return ruleResult; - } - catch (e) { - throw this.subruleInternalError(e, options, ruleToCall.ruleName); - } - }; - RecognizerEngine.prototype.subruleInternalError = function (e, options, ruleName) { - if ((0, exceptions_public_1.isRecognitionException)(e) && e.partialCstResult !== undefined) { - this.cstPostNonTerminal(e.partialCstResult, options !== undefined && options.LABEL !== undefined - ? options.LABEL - : ruleName); - delete e.partialCstResult; - } - throw e; - }; - RecognizerEngine.prototype.consumeInternal = function (tokType, idx, options) { - var consumedToken; try { - var nextToken = this.LA(1); - if (this.tokenMatcher(nextToken, tokType) === true) { - this.consumeToken(); - consumedToken = nextToken; - } - else { - this.consumeInternalError(tokType, nextToken, options); - } - } - catch (eFromConsumption) { - consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption); - } - this.cstPostTerminal(options !== undefined && options.LABEL !== undefined - ? options.LABEL - : tokType.name, consumedToken); - return consumedToken; - }; - RecognizerEngine.prototype.consumeInternalError = function (tokType, nextToken, options) { - var msg; - var previousToken = this.LA(0); - if (options !== undefined && options.ERR_MSG) { - msg = options.ERR_MSG; - } - else { - msg = this.errorMessageProvider.buildMismatchTokenMessage({ - expected: tokType, - actual: nextToken, - previous: previousToken, - ruleName: this.getCurrRuleFullName() - }); - } - throw this.SAVE_ERROR(new exceptions_public_1.MismatchedTokenException(msg, nextToken, previousToken)); - }; - RecognizerEngine.prototype.consumeInternalRecovery = function (tokType, idx, eFromConsumption) { - // no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it - // but the original syntax could have been parsed successfully without any backtracking + recovery - if (this.recoveryEnabled && - // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions? - eFromConsumption.name === "MismatchedTokenException" && - !this.isBackTracking()) { - var follows = this.getFollowsForInRuleRecovery(tokType, idx); - try { - return this.tryInRuleRecovery(tokType, follows); - } - catch (eFromInRuleRecovery) { - if (eFromInRuleRecovery.name === recoverable_1.IN_RULE_RECOVERY_EXCEPTION) { - // failed in RuleRecovery. - // throw the original error in order to trigger reSync error recovery - throw eFromConsumption; - } - else { - throw eFromInRuleRecovery; - } - } - } - else { - throw eFromConsumption; + instance.render(); + } finally { + setIsStrictModeForDevtools(false); } - }; - RecognizerEngine.prototype.saveRecogState = function () { - // errors is a getter which will clone the errors array - var savedErrors = this.errors; - var savedRuleStack = (0, clone_1.default)(this.RULE_STACK); - return { - errors: savedErrors, - lexerState: this.exportLexerState(), - RULE_STACK: savedRuleStack, - CST_STACK: this.CST_STACK - }; - }; - RecognizerEngine.prototype.reloadRecogState = function (newState) { - this.errors = newState.errors; - this.importLexerState(newState.lexerState); - this.RULE_STACK = newState.RULE_STACK; - }; - RecognizerEngine.prototype.ruleInvocationStateUpdate = function (shortName, fullName, idxInCallingRule) { - this.RULE_OCCURRENCE_STACK.push(idxInCallingRule); - this.RULE_STACK.push(shortName); - // NOOP when cst is disabled - this.cstInvocationStateUpdate(fullName); - }; - RecognizerEngine.prototype.isBackTracking = function () { - return this.isBackTrackingStack.length !== 0; - }; - RecognizerEngine.prototype.getCurrRuleFullName = function () { - var shortName = this.getLastExplicitRuleShortName(); - return this.shortRuleNameToFull[shortName]; - }; - RecognizerEngine.prototype.shortRuleNameToFullName = function (shortName) { - return this.shortRuleNameToFull[shortName]; - }; - RecognizerEngine.prototype.isAtEndOfInput = function () { - return this.tokenMatcher(this.LA(1), tokens_public_1.EOF); - }; - RecognizerEngine.prototype.reset = function () { - this.resetLexerState(); - this.subruleIdx = 0; - this.isBackTrackingStack = []; - this.errors = []; - this.RULE_STACK = []; - // TODO: extract a specific reset for TreeBuilder trait - this.CST_STACK = []; - this.RULE_OCCURRENCE_STACK = []; - }; - return RecognizerEngine; - }()); - recognizer_engine.RecognizerEngine = RecognizerEngine; - - return recognizer_engine; -} + } + + setIsRendering(false); + } -var error_handler = {}; + { + markComponentRenderStopped(); + } + } // React DevTools reads this flag. -var hasRequiredError_handler; -function requireError_handler () { - if (hasRequiredError_handler) return error_handler; - hasRequiredError_handler = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(error_handler, "__esModule", { value: true }); - error_handler.ErrorHandler = void 0; - var exceptions_public_1 = exceptions_public; - var has_1$1 = __importDefault(has_1); - var clone_1 = __importDefault(clone_1$1); - var lookahead_1 = lookahead; - var parser_1 = requireParser(); - /** - * Trait responsible for runtime parsing errors. - */ - var ErrorHandler = /** @class */ (function () { - function ErrorHandler() { - } - ErrorHandler.prototype.initErrorHandler = function (config) { - this._errors = []; - this.errorMessageProvider = (0, has_1$1.default)(config, "errorMessageProvider") - ? config.errorMessageProvider // assumes end user provides the correct config value/type - : parser_1.DEFAULT_PARSER_CONFIG.errorMessageProvider; - }; - ErrorHandler.prototype.SAVE_ERROR = function (error) { - if ((0, exceptions_public_1.isRecognitionException)(error)) { - error.context = { - ruleStack: this.getHumanReadableRuleStack(), - ruleOccurrenceStack: (0, clone_1.default)(this.RULE_OCCURRENCE_STACK) - }; - this._errors.push(error); - return error; - } - else { - throw Error("Trying to save an Error which is not a RecognitionException"); - } - }; - Object.defineProperty(ErrorHandler.prototype, "errors", { - get: function () { - return (0, clone_1.default)(this._errors); - }, - set: function (newErrors) { - this._errors = newErrors; - }, - enumerable: false, - configurable: true - }); - // TODO: consider caching the error message computed information - ErrorHandler.prototype.raiseEarlyExitException = function (occurrence, prodType, userDefinedErrMsg) { - var ruleName = this.getCurrRuleFullName(); - var ruleGrammar = this.getGAstProductions()[ruleName]; - var lookAheadPathsPerAlternative = (0, lookahead_1.getLookaheadPathsForOptionalProd)(occurrence, ruleGrammar, prodType, this.maxLookahead); - var insideProdPaths = lookAheadPathsPerAlternative[0]; - var actualTokens = []; - for (var i = 1; i <= this.maxLookahead; i++) { - actualTokens.push(this.LA(i)); - } - var msg = this.errorMessageProvider.buildEarlyExitMessage({ - expectedIterationPaths: insideProdPaths, - actual: actualTokens, - previous: this.LA(0), - customUserDescription: userDefinedErrMsg, - ruleName: ruleName - }); - throw this.SAVE_ERROR(new exceptions_public_1.EarlyExitException(msg, this.LA(1), this.LA(0))); - }; - // TODO: consider caching the error message computed information - ErrorHandler.prototype.raiseNoAltException = function (occurrence, errMsgTypes) { - var ruleName = this.getCurrRuleFullName(); - var ruleGrammar = this.getGAstProductions()[ruleName]; - // TODO: getLookaheadPathsForOr can be slow for large enough maxLookahead and certain grammars, consider caching ? - var lookAheadPathsPerAlternative = (0, lookahead_1.getLookaheadPathsForOr)(occurrence, ruleGrammar, this.maxLookahead); - var actualTokens = []; - for (var i = 1; i <= this.maxLookahead; i++) { - actualTokens.push(this.LA(i)); - } - var previousToken = this.LA(0); - var errMsg = this.errorMessageProvider.buildNoViableAltMessage({ - expectedPathsPerAlt: lookAheadPathsPerAlternative, - actual: actualTokens, - previous: previousToken, - customUserDescription: errMsgTypes, - ruleName: this.getCurrRuleFullName() - }); - throw this.SAVE_ERROR(new exceptions_public_1.NoViableAltException(errMsg, this.LA(1), previousToken)); + workInProgress.flags |= PerformedWork; + + if (current !== null && didCaptureError) { + // If we're recovering from an error, reconcile without reusing any of + // the existing children. Conceptually, the normal children and the children + // that are shown on error are two different sets, so we shouldn't reuse + // normal children even if their identities match. + forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes); + } else { + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + } // Memoize state using the values we just used to render. + // TODO: Restructure so we never read values from the instance. + + + workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. + + if (hasContext) { + invalidateContextProvider(workInProgress, Component, true); + } + + return workInProgress.child; + } + + function pushHostRootContext(workInProgress) { + var root = workInProgress.stateNode; + + if (root.pendingContext) { + pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context); + } else if (root.context) { + // Should always be set + pushTopLevelContextObject(workInProgress, root.context, false); + } + + pushHostContainer(workInProgress, root.containerInfo); + } + + function updateHostRoot(current, workInProgress, renderLanes) { + pushHostRootContext(workInProgress); + + if (current === null) { + throw new Error('Should have a current fiber. This is a bug in React.'); + } + + var nextProps = workInProgress.pendingProps; + var prevState = workInProgress.memoizedState; + var prevChildren = prevState.element; + cloneUpdateQueue(current, workInProgress); + processUpdateQueue(workInProgress, nextProps, null, renderLanes); + var nextState = workInProgress.memoizedState; + workInProgress.stateNode; + // being called "element". + + + var nextChildren = nextState.element; + + if (supportsHydration && prevState.isDehydrated) { + // This is a hydration root whose shell has not yet hydrated. We should + // attempt to hydrate. + // Flip isDehydrated to false to indicate that when this render + // finishes, the root will no longer be dehydrated. + var overrideState = { + element: nextChildren, + isDehydrated: false, + cache: nextState.cache, + transitions: nextState.transitions }; - return ErrorHandler; - }()); - error_handler.ErrorHandler = ErrorHandler; - - return error_handler; -} + var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't + // have reducer functions so it doesn't need rebasing. -var context_assist = {}; + updateQueue.baseState = overrideState; + workInProgress.memoizedState = overrideState; -var __importDefault$2 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(context_assist, "__esModule", { value: true }); -context_assist.ContentAssist = void 0; -var interpreter_1 = interpreter; -var first_1 = __importDefault$2(first.exports); -var isUndefined_1 = __importDefault$2(isUndefined_1$1); -var ContentAssist = /** @class */ (function () { - function ContentAssist() { - } - ContentAssist.prototype.initContentAssist = function () { }; - ContentAssist.prototype.computeContentAssist = function (startRuleName, precedingInput) { - var startRuleGast = this.gastProductionsCache[startRuleName]; - if ((0, isUndefined_1.default)(startRuleGast)) { - throw Error("Rule ->".concat(startRuleName, "<- does not exist in this grammar.")); - } - return (0, interpreter_1.nextPossibleTokensAfter)([startRuleGast], precedingInput, this.tokenMatcher, this.maxLookahead); - }; - // TODO: should this be a member method or a utility? it does not have any state or usage of 'this'... - // TODO: should this be more explicitly part of the public API? - ContentAssist.prototype.getNextPossibleTokenTypes = function (grammarPath) { - var topRuleName = (0, first_1.default)(grammarPath.ruleStack); - var gastProductions = this.getGAstProductions(); - var topProduction = gastProductions[topRuleName]; - var nextPossibleTokenTypes = new interpreter_1.NextAfterTokenWalker(topProduction, grammarPath).startWalking(); - return nextPossibleTokenTypes; - }; - return ContentAssist; -}()); -context_assist.ContentAssist = ContentAssist; + if (workInProgress.flags & ForceClientRender) { + // Something errored during a previous attempt to hydrate the shell, so we + // forced a client render. + var recoverableError = new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'); + return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError); + } else if (nextChildren !== prevChildren) { + var _recoverableError = new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'); -var gast_recorder = {}; + return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError); + } else { + // The outermost shell has not hydrated yet. Start hydrating. + enterHydrationState(workInProgress); -var hasRequiredGast_recorder; + var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); + workInProgress.child = child; + var node = child; -function requireGast_recorder () { - if (hasRequiredGast_recorder) return gast_recorder; - hasRequiredGast_recorder = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(gast_recorder, "__esModule", { value: true }); - gast_recorder.GastRecorder = void 0; - var last_1 = __importDefault(last_1$1); - var isArray_1 = __importDefault(isArray_1$1); - var some_1 = __importDefault(some_1$2); - var forEach_1 = __importDefault(forEach_1$4); - var isFunction_1$1 = __importDefault(isFunction_1); - var has_1$1 = __importDefault(has_1); - var gast_1 = api$1; - var lexer_public_1 = requireLexer_public(); - var tokens_1 = tokens; - var tokens_public_1 = tokens_public; - var parser_1 = requireParser(); - var keys_1 = keys; - var RECORDING_NULL_OBJECT = { - description: "This Object indicates the Parser is during Recording Phase" - }; - Object.freeze(RECORDING_NULL_OBJECT); - var HANDLE_SEPARATOR = true; - var MAX_METHOD_IDX = Math.pow(2, keys_1.BITS_FOR_OCCURRENCE_IDX) - 1; - var RFT = (0, tokens_public_1.createToken)({ name: "RECORDING_PHASE_TOKEN", pattern: lexer_public_1.Lexer.NA }); - (0, tokens_1.augmentTokenTypes)([RFT]); - var RECORDING_PHASE_TOKEN = (0, tokens_public_1.createTokenInstance)(RFT, "This IToken indicates the Parser is in Recording Phase\n\t" + - "" + - "See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details", - // Using "-1" instead of NaN (as in EOF) because an actual number is less likely to - // cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase. - -1, -1, -1, -1, -1, -1); - Object.freeze(RECORDING_PHASE_TOKEN); - var RECORDING_PHASE_CSTNODE = { - name: "This CSTNode indicates the Parser is in Recording Phase\n\t" + - "See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details", - children: {} - }; - /** - * This trait handles the creation of the GAST structure for Chevrotain Grammars - */ - var GastRecorder = /** @class */ (function () { - function GastRecorder() { + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.flags = node.flags & ~Placement | Hydrating; + node = node.sibling; + } } - GastRecorder.prototype.initGastRecorder = function (config) { - this.recordingProdStack = []; - this.RECORDING_PHASE = false; - }; - GastRecorder.prototype.enableRecording = function () { - var _this = this; - this.RECORDING_PHASE = true; - this.TRACE_INIT("Enable Recording", function () { - var _loop_1 = function (i) { - var idx = i > 0 ? i : ""; - _this["CONSUME".concat(idx)] = function (arg1, arg2) { - return this.consumeInternalRecord(arg1, i, arg2); - }; - _this["SUBRULE".concat(idx)] = function (arg1, arg2) { - return this.subruleInternalRecord(arg1, i, arg2); - }; - _this["OPTION".concat(idx)] = function (arg1) { - return this.optionInternalRecord(arg1, i); - }; - _this["OR".concat(idx)] = function (arg1) { - return this.orInternalRecord(arg1, i); - }; - _this["MANY".concat(idx)] = function (arg1) { - this.manyInternalRecord(i, arg1); - }; - _this["MANY_SEP".concat(idx)] = function (arg1) { - this.manySepFirstInternalRecord(i, arg1); - }; - _this["AT_LEAST_ONE".concat(idx)] = function (arg1) { - this.atLeastOneInternalRecord(i, arg1); - }; - _this["AT_LEAST_ONE_SEP".concat(idx)] = function (arg1) { - this.atLeastOneSepFirstInternalRecord(i, arg1); - }; - }; - /** - * Warning Dark Voodoo Magic upcoming! - * We are "replacing" the public parsing DSL methods API - * With **new** alternative implementations on the Parser **instance** - * - * So far this is the only way I've found to avoid performance regressions during parsing time. - * - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the "internal" - * implementations directly instead. - */ - for (var i = 0; i < 10; i++) { - _loop_1(i); - } - // DSL methods with the idx(suffix) as an argument - _this["consume"] = function (idx, arg1, arg2) { - return this.consumeInternalRecord(arg1, idx, arg2); - }; - _this["subrule"] = function (idx, arg1, arg2) { - return this.subruleInternalRecord(arg1, idx, arg2); - }; - _this["option"] = function (idx, arg1) { - return this.optionInternalRecord(arg1, idx); - }; - _this["or"] = function (idx, arg1) { - return this.orInternalRecord(arg1, idx); - }; - _this["many"] = function (idx, arg1) { - this.manyInternalRecord(idx, arg1); - }; - _this["atLeastOne"] = function (idx, arg1) { - this.atLeastOneInternalRecord(idx, arg1); - }; - _this.ACTION = _this.ACTION_RECORD; - _this.BACKTRACK = _this.BACKTRACK_RECORD; - _this.LA = _this.LA_RECORD; - }); - }; - GastRecorder.prototype.disableRecording = function () { - var _this = this; - this.RECORDING_PHASE = false; - // By deleting these **instance** properties, any future invocation - // will be deferred to the original methods on the **prototype** object - // This seems to get rid of any incorrect optimizations that V8 may - // do during the recording phase. - this.TRACE_INIT("Deleting Recording methods", function () { - var that = _this; - for (var i = 0; i < 10; i++) { - var idx = i > 0 ? i : ""; - delete that["CONSUME".concat(idx)]; - delete that["SUBRULE".concat(idx)]; - delete that["OPTION".concat(idx)]; - delete that["OR".concat(idx)]; - delete that["MANY".concat(idx)]; - delete that["MANY_SEP".concat(idx)]; - delete that["AT_LEAST_ONE".concat(idx)]; - delete that["AT_LEAST_ONE_SEP".concat(idx)]; - } - delete that["consume"]; - delete that["subrule"]; - delete that["option"]; - delete that["or"]; - delete that["many"]; - delete that["atLeastOne"]; - delete that.ACTION; - delete that.BACKTRACK; - delete that.LA; - }); - }; - // Parser methods are called inside an ACTION? - // Maybe try/catch/finally on ACTIONS while disabling the recorders state changes? - // @ts-expect-error -- noop place holder - GastRecorder.prototype.ACTION_RECORD = function (impl) { - // NO-OP during recording - }; - // Executing backtracking logic will break our recording logic assumptions - GastRecorder.prototype.BACKTRACK_RECORD = function (grammarRule, args) { - return function () { return true; }; - }; - // LA is part of the official API and may be used for custom lookahead logic - // by end users who may forget to wrap it in ACTION or inside a GATE - GastRecorder.prototype.LA_RECORD = function (howMuch) { - // We cannot use the RECORD_PHASE_TOKEN here because someone may depend - // On LA return EOF at the end of the input so an infinite loop may occur. - return parser_1.END_OF_FILE; - }; - GastRecorder.prototype.topLevelRuleRecord = function (name, def) { - try { - var newTopLevelRule = new gast_1.Rule({ definition: [], name: name }); - newTopLevelRule.name = name; - this.recordingProdStack.push(newTopLevelRule); - def.call(this); - this.recordingProdStack.pop(); - return newTopLevelRule; - } - catch (originalError) { - if (originalError.KNOWN_RECORDER_ERROR !== true) { - try { - originalError.message = - originalError.message + - '\n\t This error was thrown during the "grammar recording phase" For more info see:\n\t' + - "https://chevrotain.io/docs/guide/internals.html#grammar-recording"; - } - catch (mutabilityError) { - // We may not be able to modify the original error object - throw originalError; - } - } - throw originalError; - } - }; - // Implementation of parsing DSL - GastRecorder.prototype.optionInternalRecord = function (actionORMethodDef, occurrence) { - return recordProd.call(this, gast_1.Option, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.atLeastOneInternalRecord = function (occurrence, actionORMethodDef) { - recordProd.call(this, gast_1.RepetitionMandatory, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.atLeastOneSepFirstInternalRecord = function (occurrence, options) { - recordProd.call(this, gast_1.RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR); - }; - GastRecorder.prototype.manyInternalRecord = function (occurrence, actionORMethodDef) { - recordProd.call(this, gast_1.Repetition, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.manySepFirstInternalRecord = function (occurrence, options) { - recordProd.call(this, gast_1.RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR); - }; - GastRecorder.prototype.orInternalRecord = function (altsOrOpts, occurrence) { - return recordOrProd.call(this, altsOrOpts, occurrence); - }; - GastRecorder.prototype.subruleInternalRecord = function (ruleToCall, occurrence, options) { - assertMethodIdxIsValid(occurrence); - if (!ruleToCall || (0, has_1$1.default)(ruleToCall, "ruleName") === false) { - var error = new Error(" argument is invalid") + - " expecting a Parser method reference but got: <".concat(JSON.stringify(ruleToCall), ">") + - "\n inside top level rule: <".concat(this.recordingProdStack[0].name, ">")); - error.KNOWN_RECORDER_ERROR = true; - throw error; - } - var prevProd = (0, last_1.default)(this.recordingProdStack); - var ruleName = ruleToCall.ruleName; - var newNoneTerminal = new gast_1.NonTerminal({ - idx: occurrence, - nonTerminalName: ruleName, - label: options === null || options === void 0 ? void 0 : options.LABEL, - // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created - referencedRule: undefined - }); - prevProd.definition.push(newNoneTerminal); - return this.outputCst ? RECORDING_PHASE_CSTNODE : RECORDING_NULL_OBJECT; - }; - GastRecorder.prototype.consumeInternalRecord = function (tokType, occurrence, options) { - assertMethodIdxIsValid(occurrence); - if (!(0, tokens_1.hasShortKeyProperty)(tokType)) { - var error = new Error(" argument is invalid") + - " expecting a TokenType reference but got: <".concat(JSON.stringify(tokType), ">") + - "\n inside top level rule: <".concat(this.recordingProdStack[0].name, ">")); - error.KNOWN_RECORDER_ERROR = true; - throw error; - } - var prevProd = (0, last_1.default)(this.recordingProdStack); - var newNoneTerminal = new gast_1.Terminal({ - idx: occurrence, - terminalType: tokType, - label: options === null || options === void 0 ? void 0 : options.LABEL - }); - prevProd.definition.push(newNoneTerminal); - return RECORDING_PHASE_TOKEN; - }; - return GastRecorder; - }()); - gast_recorder.GastRecorder = GastRecorder; - function recordProd(prodConstructor, mainProdArg, occurrence, handleSep) { - if (handleSep === void 0) { handleSep = false; } - assertMethodIdxIsValid(occurrence); - var prevProd = (0, last_1.default)(this.recordingProdStack); - var grammarAction = (0, isFunction_1$1.default)(mainProdArg) ? mainProdArg : mainProdArg.DEF; - var newProd = new prodConstructor({ definition: [], idx: occurrence }); - if (handleSep) { - newProd.separator = mainProdArg.SEP; - } - if ((0, has_1$1.default)(mainProdArg, "MAX_LOOKAHEAD")) { - newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; - } - this.recordingProdStack.push(newProd); - grammarAction.call(this); - prevProd.definition.push(newProd); - this.recordingProdStack.pop(); - return RECORDING_NULL_OBJECT; - } - function recordOrProd(mainProdArg, occurrence) { - var _this = this; - assertMethodIdxIsValid(occurrence); - var prevProd = (0, last_1.default)(this.recordingProdStack); - // Only an array of alternatives - var hasOptions = (0, isArray_1.default)(mainProdArg) === false; - var alts = hasOptions === false ? mainProdArg : mainProdArg.DEF; - var newOrProd = new gast_1.Alternation({ - definition: [], - idx: occurrence, - ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true - }); - if ((0, has_1$1.default)(mainProdArg, "MAX_LOOKAHEAD")) { - newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; - } - var hasPredicates = (0, some_1.default)(alts, function (currAlt) { return (0, isFunction_1$1.default)(currAlt.GATE); }); - newOrProd.hasPredicates = hasPredicates; - prevProd.definition.push(newOrProd); - (0, forEach_1.default)(alts, function (currAlt) { - var currAltFlat = new gast_1.Alternative({ definition: [] }); - newOrProd.definition.push(currAltFlat); - if ((0, has_1$1.default)(currAlt, "IGNORE_AMBIGUITIES")) { - currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES; // assumes end user provides the correct config value/type - } - // **implicit** ignoreAmbiguities due to usage of gate - else if ((0, has_1$1.default)(currAlt, "GATE")) { - currAltFlat.ignoreAmbiguities = true; - } - _this.recordingProdStack.push(currAltFlat); - currAlt.ALT.call(_this); - _this.recordingProdStack.pop(); - }); - return RECORDING_NULL_OBJECT; + } else { + // Root is not dehydrated. Either this is a client-only root, or it + // already hydrated. + resetHydrationState(); + + if (nextChildren === prevChildren) { + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } + + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + } + + return workInProgress.child; } - function getIdxSuffix(idx) { - return idx === 0 ? "" : "".concat(idx); + + function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) { + // Revert to client rendering. + resetHydrationState(); + queueHydrationError(recoverableError); + workInProgress.flags |= ForceClientRender; + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; } - function assertMethodIdxIsValid(idx) { - if (idx < 0 || idx > MAX_METHOD_IDX) { - var error = new Error( - // The stack trace will contain all the needed details - "Invalid DSL Method idx value: <".concat(idx, ">\n\t") + - "Idx value must be a none negative value smaller than ".concat(MAX_METHOD_IDX + 1)); - error.KNOWN_RECORDER_ERROR = true; - throw error; - } + + function updateHostComponent$1(current, workInProgress, renderLanes) { + pushHostContext(workInProgress); + + if (current === null) { + tryToClaimNextHydratableInstance(workInProgress); + } + + var type = workInProgress.type; + var nextProps = workInProgress.pendingProps; + var prevProps = current !== null ? current.memoizedProps : null; + var nextChildren = nextProps.children; + var isDirectTextChild = shouldSetTextContent(type, nextProps); + + if (isDirectTextChild) { + // We special case a direct text child of a host node. This is a common + // case. We won't handle it as a reified child. We will instead handle + // this in the host environment that also has access to this prop. That + // avoids allocating another HostText fiber and traversing it. + nextChildren = null; + } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { + // If we're switching from a direct text child to a normal child, or to + // empty, we need to schedule the text content to be reset. + workInProgress.flags |= ContentReset; + } + + markRef$1(current, workInProgress); + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + return workInProgress.child; } - - return gast_recorder; -} -var perf_tracer = {}; + function updateHostText$1(current, workInProgress) { + if (current === null) { + tryToClaimNextHydratableInstance(workInProgress); + } // Nothing to do here. This is terminal. We'll do the completion step + // immediately after. -var hasRequiredPerf_tracer; -function requirePerf_tracer () { - if (hasRequiredPerf_tracer) return perf_tracer; - hasRequiredPerf_tracer = 1; - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(perf_tracer, "__esModule", { value: true }); - perf_tracer.PerformanceTracer = void 0; - var has_1$1 = __importDefault(has_1); - var utils_1 = api$2; - var parser_1 = requireParser(); - /** - * Trait responsible for runtime parsing errors. - */ - var PerformanceTracer = /** @class */ (function () { - function PerformanceTracer() { - } - PerformanceTracer.prototype.initPerformanceTracer = function (config) { - if ((0, has_1$1.default)(config, "traceInitPerf")) { - var userTraceInitPerf = config.traceInitPerf; - var traceIsNumber = typeof userTraceInitPerf === "number"; - this.traceInitMaxIdent = traceIsNumber - ? userTraceInitPerf - : Infinity; - this.traceInitPerf = traceIsNumber - ? userTraceInitPerf > 0 - : userTraceInitPerf; // assumes end user provides the correct config value/type + return null; + } + + function mountLazyComponent(_current, workInProgress, elementType, renderLanes) { + if (_current !== null) { + // A lazy component only mounts if it suspended inside a non- + // concurrent tree, in an inconsistent state. We want to treat it like + // a new mount, even though an empty version of it already committed. + // Disconnect the alternate pointers. + _current.alternate = null; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + + workInProgress.flags |= Placement; + } + + var props = workInProgress.pendingProps; + var lazyComponent = elementType; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + var Component = init(payload); // Store the unwrapped component in the type. + + workInProgress.type = Component; + var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component); + var resolvedProps = resolveDefaultProps(Component, props); + var child; + + switch (resolvedTag) { + case FunctionComponent: + { + { + validateFunctionComponentInDev(workInProgress, Component); + workInProgress.type = Component = resolveFunctionForHotReloading(Component); } - else { - this.traceInitMaxIdent = 0; - this.traceInitPerf = parser_1.DEFAULT_PARSER_CONFIG.traceInitPerf; + + child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes); + return child; + } + + case ClassComponent: + { + { + workInProgress.type = Component = resolveClassForHotReloading(Component); } - this.traceInitIndent = -1; - }; - PerformanceTracer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) { - // No need to optimize this using NOOP pattern because - // It is not called in a hot spot... - if (this.traceInitPerf === true) { - this.traceInitIndent++; - var indent = new Array(this.traceInitIndent + 1).join("\t"); - if (this.traceInitIndent < this.traceInitMaxIdent) { - console.log("".concat(indent, "--> <").concat(phaseDesc, ">")); - } - var _a = (0, utils_1.timer)(phaseImpl), time = _a.time, value = _a.value; - /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */ - var traceMethod = time > 10 ? console.warn : console.log; - if (this.traceInitIndent < this.traceInitMaxIdent) { - traceMethod("".concat(indent, "<-- <").concat(phaseDesc, "> time: ").concat(time, "ms")); - } - this.traceInitIndent--; - return value; + + child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes); + return child; + } + + case ForwardRef: + { + { + workInProgress.type = Component = resolveForwardRefForHotReloading(Component); } - else { - return phaseImpl(); + + child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes); + return child; + } + + case MemoComponent: + { + { + if (workInProgress.type !== workInProgress.elementType) { + var outerPropTypes = Component.propTypes; + + if (outerPropTypes) { + checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only + 'prop', getComponentNameFromType(Component)); + } + } } - }; - return PerformanceTracer; - }()); - perf_tracer.PerformanceTracer = PerformanceTracer; - - return perf_tracer; -} - -var apply_mixins = {}; - -Object.defineProperty(apply_mixins, "__esModule", { value: true }); -apply_mixins.applyMixins = void 0; -function applyMixins(derivedCtor, baseCtors) { - baseCtors.forEach(function (baseCtor) { - var baseProto = baseCtor.prototype; - Object.getOwnPropertyNames(baseProto).forEach(function (propName) { - if (propName === "constructor") { - return; - } - var basePropDescriptor = Object.getOwnPropertyDescriptor(baseProto, propName); - // Handle Accessors - if (basePropDescriptor && - (basePropDescriptor.get || basePropDescriptor.set)) { - Object.defineProperty(derivedCtor.prototype, propName, basePropDescriptor); - } - else { - derivedCtor.prototype[propName] = baseCtor.prototype[propName]; - } - }); - }); -} -apply_mixins.applyMixins = applyMixins; -var hasRequiredParser; + child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too + renderLanes); + return child; + } + } -function requireParser () { - if (hasRequiredParser) return parser; - hasRequiredParser = 1; - (function (exports) { - var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EmbeddedActionsParser = exports.CstParser = exports.Parser = exports.EMPTY_ALT = exports.ParserDefinitionErrorType = exports.DEFAULT_RULE_CONFIG = exports.DEFAULT_PARSER_CONFIG = exports.END_OF_FILE = void 0; - var isEmpty_1 = __importDefault(isEmpty_1$1); - var map_1 = __importDefault(map_1$4); - var forEach_1 = __importDefault(forEach_1$4); - var values_1 = __importDefault(values_1$1); - var has_1$1 = __importDefault(has_1); - var clone_1 = __importDefault(clone_1$1); - var utils_1 = api$2; - var follow_1 = follow; - var tokens_public_1 = tokens_public; - var errors_public_1 = errors_public; - var gast_resolver_public_1 = requireGast_resolver_public(); - var recoverable_1 = requireRecoverable(); - var looksahead_1 = requireLooksahead(); - var tree_builder_1 = requireTree_builder(); - var lexer_adapter_1 = requireLexer_adapter(); - var recognizer_api_1 = requireRecognizer_api(); - var recognizer_engine_1 = requireRecognizer_engine(); - var error_handler_1 = requireError_handler(); - var context_assist_1 = context_assist; - var gast_recorder_1 = requireGast_recorder(); - var perf_tracer_1 = requirePerf_tracer(); - var apply_mixins_1 = apply_mixins; - exports.END_OF_FILE = (0, tokens_public_1.createTokenInstance)(tokens_public_1.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN); - Object.freeze(exports.END_OF_FILE); - exports.DEFAULT_PARSER_CONFIG = Object.freeze({ - recoveryEnabled: false, - maxLookahead: 3, - dynamicTokensEnabled: false, - outputCst: true, - errorMessageProvider: errors_public_1.defaultParserErrorProvider, - nodeLocationTracking: "none", - traceInitPerf: false, - skipValidations: false - }); - exports.DEFAULT_RULE_CONFIG = Object.freeze({ - recoveryValueFunc: function () { return undefined; }, - resyncEnabled: true - }); - (function (ParserDefinitionErrorType) { - ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME"; - ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME"; - ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE"; - ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF"; - ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"] = 5] = "LEFT_RECURSION"; - ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT"; - ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE"; - ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME"; - ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"] = 10] = "NO_NON_EMPTY_LOOKAHEAD"; - ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 11] = "AMBIGUOUS_PREFIX_ALTS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 12] = "TOO_MANY_ALTS"; - })(exports.ParserDefinitionErrorType || (exports.ParserDefinitionErrorType = {})); - function EMPTY_ALT(value) { - if (value === void 0) { value = undefined; } - return function () { - return value; - }; - } - exports.EMPTY_ALT = EMPTY_ALT; - var Parser = /** @class */ (function () { - function Parser(tokenVocabulary, config) { - this.definitionErrors = []; - this.selfAnalysisDone = false; - var that = this; - that.initErrorHandler(config); - that.initLexerAdapter(); - that.initLooksAhead(config); - that.initRecognizerEngine(tokenVocabulary, config); - that.initRecoverable(config); - that.initTreeBuilder(config); - that.initContentAssist(); - that.initGastRecorder(config); - that.initPerformanceTracer(config); - if ((0, has_1$1.default)(config, "ignoredIssues")) { - throw new Error("The IParserConfig property has been deprecated.\n\t" + - "Please use the flag on the relevant DSL method instead.\n\t" + - "See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n\t" + - "For further details."); - } - this.skipValidations = (0, has_1$1.default)(config, "skipValidations") - ? config.skipValidations // casting assumes the end user passing the correct type - : exports.DEFAULT_PARSER_CONFIG.skipValidations; - } - /** - * @deprecated use the **instance** method with the same name instead - */ - Parser.performSelfAnalysis = function (parserInstance) { - throw Error("The **static** `performSelfAnalysis` method has been deprecated." + - "\t\nUse the **instance** method with the same name instead."); - }; - Parser.prototype.performSelfAnalysis = function () { - var _this = this; - this.TRACE_INIT("performSelfAnalysis", function () { - var defErrorsMsgs; - _this.selfAnalysisDone = true; - var className = _this.className; - _this.TRACE_INIT("toFastProps", function () { - // Without this voodoo magic the parser would be x3-x4 slower - // It seems it is better to invoke `toFastProperties` **before** - // Any manipulations of the `this` object done during the recording phase. - (0, utils_1.toFastProperties)(_this); - }); - _this.TRACE_INIT("Grammar Recording", function () { - try { - _this.enableRecording(); - // Building the GAST - (0, forEach_1.default)(_this.definedRulesNames, function (currRuleName) { - var wrappedRule = _this[currRuleName]; - var originalGrammarAction = wrappedRule["originalGrammarAction"]; - var recordedRuleGast; - _this.TRACE_INIT("".concat(currRuleName, " Rule"), function () { - recordedRuleGast = _this.topLevelRuleRecord(currRuleName, originalGrammarAction); - }); - _this.gastProductionsCache[currRuleName] = recordedRuleGast; - }); - } - finally { - _this.disableRecording(); - } - }); - var resolverErrors = []; - _this.TRACE_INIT("Grammar Resolving", function () { - resolverErrors = (0, gast_resolver_public_1.resolveGrammar)({ - rules: (0, values_1.default)(_this.gastProductionsCache) - }); - _this.definitionErrors = _this.definitionErrors.concat(resolverErrors); - }); - _this.TRACE_INIT("Grammar Validations", function () { - // only perform additional grammar validations IFF no resolving errors have occurred. - // as unresolved grammar may lead to unhandled runtime exceptions in the follow up validations. - if ((0, isEmpty_1.default)(resolverErrors) && _this.skipValidations === false) { - var validationErrors = (0, gast_resolver_public_1.validateGrammar)({ - rules: (0, values_1.default)(_this.gastProductionsCache), - maxLookahead: _this.maxLookahead, - tokenTypes: (0, values_1.default)(_this.tokensMap), - errMsgProvider: errors_public_1.defaultGrammarValidatorErrorProvider, - grammarName: className - }); - _this.definitionErrors = _this.definitionErrors.concat(validationErrors); - } - }); - // this analysis may fail if the grammar is not perfectly valid - if ((0, isEmpty_1.default)(_this.definitionErrors)) { - // The results of these computations are not needed unless error recovery is enabled. - if (_this.recoveryEnabled) { - _this.TRACE_INIT("computeAllProdsFollows", function () { - var allFollows = (0, follow_1.computeAllProdsFollows)((0, values_1.default)(_this.gastProductionsCache)); - _this.resyncFollows = allFollows; - }); - } - _this.TRACE_INIT("ComputeLookaheadFunctions", function () { - _this.preComputeLookaheadFunctions((0, values_1.default)(_this.gastProductionsCache)); - }); - } - if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING && - !(0, isEmpty_1.default)(_this.definitionErrors)) { - defErrorsMsgs = (0, map_1.default)(_this.definitionErrors, function (defError) { return defError.message; }); - throw new Error("Parser Definition Errors detected:\n ".concat(defErrorsMsgs.join("\n-------------------------------\n"))); - } - }); - }; - // Set this flag to true if you don't want the Parser to throw error when problems in it's definition are detected. - // (normally during the parser's constructor). - // This is a design time flag, it will not affect the runtime error handling of the parser, just design time errors, - // for example: duplicate rule names, referencing an unresolved subrule, ect... - // This flag should not be enabled during normal usage, it is used in special situations, for example when - // needing to display the parser definition errors in some GUI(online playground). - Parser.DEFER_DEFINITION_ERRORS_HANDLING = false; - return Parser; - }()); - exports.Parser = Parser; - (0, apply_mixins_1.applyMixins)(Parser, [ - recoverable_1.Recoverable, - looksahead_1.LooksAhead, - tree_builder_1.TreeBuilder, - lexer_adapter_1.LexerAdapter, - recognizer_engine_1.RecognizerEngine, - recognizer_api_1.RecognizerApi, - error_handler_1.ErrorHandler, - context_assist_1.ContentAssist, - gast_recorder_1.GastRecorder, - perf_tracer_1.PerformanceTracer - ]); - var CstParser = /** @class */ (function (_super) { - __extends(CstParser, _super); - function CstParser(tokenVocabulary, config) { - if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; } - var configClone = (0, clone_1.default)(config); - configClone.outputCst = true; - return _super.call(this, tokenVocabulary, configClone) || this; - } - return CstParser; - }(Parser)); - exports.CstParser = CstParser; - var EmbeddedActionsParser = /** @class */ (function (_super) { - __extends(EmbeddedActionsParser, _super); - function EmbeddedActionsParser(tokenVocabulary, config) { - if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; } - var configClone = (0, clone_1.default)(config); - configClone.outputCst = false; - return _super.call(this, tokenVocabulary, configClone) || this; - } - return EmbeddedActionsParser; - }(Parser)); - exports.EmbeddedActionsParser = EmbeddedActionsParser; - -} (parser)); - return parser; -} + var hint = ''; + + { + if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) { + hint = ' Did you wrap a component in React.lazy() more than once?'; + } + } // This message intentionally doesn't mention ForwardRef or MemoComponent + // because the fact that it's a separate type of work is an + // implementation detail. -var api = {}; -var model = {}; + throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint)); + } -var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(model, "__esModule", { value: true }); -model.buildModel = void 0; -var gast_1 = api$1; -var map_1$1 = __importDefault$1(map_1$4); -var flatten_1$1 = __importDefault$1(flatten_1$3); -var values_1 = __importDefault$1(values_1$1); -var some_1 = __importDefault$1(some_1$2); -var groupBy_1 = __importDefault$1(groupBy_1$1); -var assign_1 = __importDefault$1(assign_1$3); -function buildModel(productions) { - var generator = new CstNodeDefinitionGenerator(); - var allRules = (0, values_1.default)(productions); - return (0, map_1$1.default)(allRules, function (rule) { return generator.visitRule(rule); }); -} -model.buildModel = buildModel; -var CstNodeDefinitionGenerator = /** @class */ (function (_super) { - __extends(CstNodeDefinitionGenerator, _super); - function CstNodeDefinitionGenerator() { - return _super !== null && _super.apply(this, arguments) || this; - } - CstNodeDefinitionGenerator.prototype.visitRule = function (node) { - var rawElements = this.visitEach(node.definition); - var grouped = (0, groupBy_1.default)(rawElements, function (el) { return el.propertyName; }); - var properties = (0, map_1$1.default)(grouped, function (group, propertyName) { - var allNullable = !(0, some_1.default)(group, function (el) { return !el.canBeNull; }); - // In an alternation with a label a property name can have - // multiple types. - var propertyType = group[0].type; - if (group.length > 1) { - propertyType = (0, map_1$1.default)(group, function (g) { return g.type; }); - } - return { - name: propertyName, - type: propertyType, - optional: allNullable - }; - }); - return { - name: node.name, - properties: properties - }; - }; - CstNodeDefinitionGenerator.prototype.visitAlternative = function (node) { - return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); - }; - CstNodeDefinitionGenerator.prototype.visitOption = function (node) { - return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); - }; - CstNodeDefinitionGenerator.prototype.visitRepetition = function (node) { - return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); - }; - CstNodeDefinitionGenerator.prototype.visitRepetitionMandatory = function (node) { - return this.visitEach(node.definition); - }; - CstNodeDefinitionGenerator.prototype.visitRepetitionMandatoryWithSeparator = function (node) { - return this.visitEach(node.definition).concat({ - propertyName: node.separator.name, - canBeNull: true, - type: getType(node.separator) - }); - }; - CstNodeDefinitionGenerator.prototype.visitRepetitionWithSeparator = function (node) { - return this.visitEachAndOverrideWith(node.definition, { - canBeNull: true - }).concat({ - propertyName: node.separator.name, - canBeNull: true, - type: getType(node.separator) - }); - }; - CstNodeDefinitionGenerator.prototype.visitAlternation = function (node) { - return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); - }; - CstNodeDefinitionGenerator.prototype.visitTerminal = function (node) { - return [ - { - propertyName: node.label || node.terminalType.name, - canBeNull: false, - type: getType(node) - } - ]; - }; - CstNodeDefinitionGenerator.prototype.visitNonTerminal = function (node) { - return [ - { - propertyName: node.label || node.nonTerminalName, - canBeNull: false, - type: getType(node) - } - ]; - }; - CstNodeDefinitionGenerator.prototype.visitEachAndOverrideWith = function (definition, override) { - return (0, map_1$1.default)(this.visitEach(definition), function (definition) { return (0, assign_1.default)({}, definition, override); }); - }; - CstNodeDefinitionGenerator.prototype.visitEach = function (definition) { - var _this = this; - return (0, flatten_1$1.default)((0, map_1$1.default)(definition, function (definition) { return _this.visit(definition); })); - }; - return CstNodeDefinitionGenerator; -}(gast_1.GAstVisitor)); -function getType(production) { - if (production instanceof gast_1.NonTerminal) { - return { - kind: "rule", - name: production.referencedRule.name - }; - } - return { kind: "token" }; -} + function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) { + if (_current !== null) { + // An incomplete component only mounts if it suspended inside a non- + // concurrent tree, in an inconsistent state. We want to treat it like + // a new mount, even though an empty version of it already committed. + // Disconnect the alternate pointers. + _current.alternate = null; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect -var generate = {}; + workInProgress.flags |= Placement; + } // Promote the fiber to a class and try rendering again. -var baseSlice = _baseSlice; -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice$1(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} + workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` + // Push context providers early to prevent context stack mismatches. + // During mounting we don't know the child context yet as the instance doesn't exist. + // We will invalidate the child context in finishClassComponent() right after rendering. -var _castSlice = castSlice$1; + var hasContext; -/** Used to compose unicode character classes. */ + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress); + } else { + hasContext = false; + } -var rsAstralRange$1 = '\\ud800-\\udfff', - rsComboMarksRange$1 = '\\u0300-\\u036f', - reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', - rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, - rsVarRange$1 = '\\ufe0e\\ufe0f'; + prepareToReadContext(workInProgress, renderLanes); + constructClassInstance(workInProgress, Component, nextProps); + mountClassInstance(workInProgress, Component, nextProps, renderLanes); + return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); + } -/** Used to compose unicode capture groups. */ -var rsZWJ$1 = '\\u200d'; + function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) { + if (_current !== null) { + // An indeterminate component only mounts if it suspended inside a non- + // concurrent tree, in an inconsistent state. We want to treat it like + // a new mount, even though an empty version of it already committed. + // Disconnect the alternate pointers. + _current.alternate = null; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ$1 + rsAstralRange$1 + rsComboRange$1 + rsVarRange$1 + ']'); + workInProgress.flags |= Placement; + } -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode$2(string) { - return reHasUnicode.test(string); -} + var props = workInProgress.pendingProps; + var context; -var _hasUnicode = hasUnicode$2; + { + var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); + context = getMaskedContext(workInProgress, unmaskedContext); + } -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ + prepareToReadContext(workInProgress, renderLanes); + var value; + var hasId; -function asciiToArray$1(string) { - return string.split(''); -} + { + markComponentRenderStarted(workInProgress); + } -var _asciiToArray = asciiToArray$1; + { + if (Component.prototype && typeof Component.prototype.render === 'function') { + var componentName = getComponentNameFromType(Component) || 'Unknown'; -/** Used to compose unicode character classes. */ + if (!didWarnAboutBadClass[componentName]) { + error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); -var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsVarRange = '\\ufe0e\\ufe0f'; + didWarnAboutBadClass[componentName] = true; + } + } -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsZWJ = '\\u200d'; + if (workInProgress.mode & StrictLegacyMode) { + ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null); + } -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + setIsRendering(true); + ReactCurrentOwner$1.current = workInProgress; + value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); + hasId = checkDidRenderIdHook(); + setIsRendering(false); + } -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + { + markComponentRenderStopped(); + } // React DevTools reads this flag. -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray$1(string) { - return string.match(reUnicode) || []; -} -var _unicodeToArray = unicodeToArray$1; + workInProgress.flags |= PerformedWork; -var asciiToArray = _asciiToArray, - hasUnicode$1 = _hasUnicode, - unicodeToArray = _unicodeToArray; + { + // Support for module components is deprecated and is removed behind a flag. + // Whether or not it would crash later, we want to show a good message in DEV first. + if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + var _componentName = getComponentNameFromType(Component) || 'Unknown'; -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray$1(string) { - return hasUnicode$1(string) - ? unicodeToArray(string) - : asciiToArray(string); -} + if (!didWarnAboutModulePatternComponent[_componentName]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); -var _stringToArray = stringToArray$1; + didWarnAboutModulePatternComponent[_componentName] = true; + } + } + } -var castSlice = _castSlice, - hasUnicode = _hasUnicode, - stringToArray = _stringToArray, - toString = toString_1; + if ( // Run these checks in production only if the flag is off. + // Eventually we'll delete this branch altogether. + typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + { + var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; -/** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ -function createCaseFirst$1(methodName) { - return function(string) { - string = toString(string); + if (!didWarnAboutModulePatternComponent[_componentName2]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; + didWarnAboutModulePatternComponent[_componentName2] = true; + } + } // Proceed under the assumption that this is a class instance - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); + workInProgress.tag = ClassComponent; // Throw out any hooks that were used. - return chr[methodName]() + trailing; - }; -} + workInProgress.memoizedState = null; + workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches. + // During mounting we don't know the child context yet as the instance doesn't exist. + // We will invalidate the child context in finishClassComponent() right after rendering. -var _createCaseFirst = createCaseFirst$1; + var hasContext = false; -var createCaseFirst = _createCaseFirst; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress); + } else { + hasContext = false; + } -/** - * Converts the first character of `string` to upper case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.upperFirst('fred'); - * // => 'Fred' - * - * _.upperFirst('FRED'); - * // => 'FRED' - */ -var upperFirst = createCaseFirst('toUpperCase'); + workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; + initializeUpdateQueue(workInProgress); + adoptClassInstance(workInProgress, value); + mountClassInstance(workInProgress, Component, props, renderLanes); + return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); + } else { + // Proceed under the assumption that this is a function component + workInProgress.tag = FunctionComponent; -var upperFirst_1$1 = upperFirst; + { -var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(generate, "__esModule", { value: true }); -generate.genDts = void 0; -var flatten_1 = __importDefault(flatten_1$3); -var isArray_1 = __importDefault(isArray_1$1); -var map_1 = __importDefault(map_1$4); -var reduce_1 = __importDefault(reduce_1$1); -var uniq_1 = __importDefault(uniq_1$2); -var upperFirst_1 = __importDefault(upperFirst_1$1); -function genDts(model, options) { - var contentParts = []; - contentParts = contentParts.concat("import type { CstNode, ICstVisitor, IToken } from \"chevrotain\";"); - contentParts = contentParts.concat((0, flatten_1.default)((0, map_1.default)(model, function (node) { return genCstNodeTypes(node); }))); - if (options.includeVisitorInterface) { - contentParts = contentParts.concat(genVisitor(options.visitorInterfaceName, model)); - } - return contentParts.join("\n\n") + "\n"; -} -generate.genDts = genDts; -function genCstNodeTypes(node) { - var nodeCstInterface = genNodeInterface(node); - var nodeChildrenInterface = genNodeChildrenType(node); - return [nodeCstInterface, nodeChildrenInterface]; -} -function genNodeInterface(node) { - var nodeInterfaceName = getNodeInterfaceName(node.name); - var childrenTypeName = getNodeChildrenTypeName(node.name); - return "export interface ".concat(nodeInterfaceName, " extends CstNode {\n name: \"").concat(node.name, "\";\n children: ").concat(childrenTypeName, ";\n}"); -} -function genNodeChildrenType(node) { - var typeName = getNodeChildrenTypeName(node.name); - return "export type ".concat(typeName, " = {\n ").concat((0, map_1.default)(node.properties, function (property) { return genChildProperty(property); }).join("\n "), "\n};"); -} -function genChildProperty(prop) { - var typeName = buildTypeString(prop.type); - return "".concat(prop.name).concat(prop.optional ? "?" : "", ": ").concat(typeName, "[];"); -} -function genVisitor(name, nodes) { - return "export interface ".concat(name, " extends ICstVisitor {\n ").concat((0, map_1.default)(nodes, function (node) { return genVisitorFunction(node); }).join("\n "), "\n}"); -} -function genVisitorFunction(node) { - var childrenTypeName = getNodeChildrenTypeName(node.name); - return "".concat(node.name, "(children: ").concat(childrenTypeName, ", param?: IN): OUT;"); -} -function buildTypeString(type) { - if ((0, isArray_1.default)(type)) { - var typeNames = (0, uniq_1.default)((0, map_1.default)(type, function (t) { return getTypeString(t); })); - var typeString = (0, reduce_1.default)(typeNames, function (sum, t) { return sum + " | " + t; }); - return "(" + typeString + ")"; - } - else { - return getTypeString(type); - } -} -function getTypeString(type) { - if (type.kind === "token") { - return "IToken"; - } - return getNodeInterfaceName(type.name); -} -function getNodeInterfaceName(ruleName) { - return (0, upperFirst_1.default)(ruleName) + "CstNode"; -} -function getNodeChildrenTypeName(ruleName) { - return (0, upperFirst_1.default)(ruleName) + "CstChildren"; -} + if ( workInProgress.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); -var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -Object.defineProperty(api, "__esModule", { value: true }); -api.generateCstDts = void 0; -var model_1 = model; -var generate_1 = generate; -var defaultOptions = { - includeVisitorInterface: true, - visitorInterfaceName: "ICstNodeVisitor" -}; -function generateCstDts(productions, options) { - var effectiveOptions = __assign(__assign({}, defaultOptions), options); - var model = (0, model_1.buildModel)(productions); - return (0, generate_1.genDts)(model, effectiveOptions); -} -api.generateCstDts = generateCstDts; - -var render_public = {}; - -Object.defineProperty(render_public, "__esModule", { value: true }); -render_public.createSyntaxDiagramsCode = void 0; -var version_1 = version; -function createSyntaxDiagramsCode(grammar, _a) { - var _b = _a === void 0 ? {} : _a, _c = _b.resourceBase, resourceBase = _c === void 0 ? "https://unpkg.com/chevrotain@".concat(version_1.VERSION, "/diagrams/") : _c, _d = _b.css, css = _d === void 0 ? "https://unpkg.com/chevrotain@".concat(version_1.VERSION, "/diagrams/diagrams.css") : _d; - var header = "\n\n\n\n\n\n"; - var cssHtml = "\n\n"); - var scripts = "\n\n\n\n\n"); - var diagramsDiv = "\n
\n"; - var serializedGrammar = "\n\n"); - var initLogic = "\n\n"; - return (header + cssHtml + scripts + diagramsDiv + serializedGrammar + initLogic); -} -render_public.createSyntaxDiagramsCode = createSyntaxDiagramsCode; - -(function (exports) { - /* istanbul ignore file - tricky to import some things from this module during testing */ - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Parser = exports.createSyntaxDiagramsCode = exports.clearCache = exports.generateCstDts = exports.GAstVisitor = exports.serializeProduction = exports.serializeGrammar = exports.Terminal = exports.Rule = exports.RepetitionWithSeparator = exports.RepetitionMandatoryWithSeparator = exports.RepetitionMandatory = exports.Repetition = exports.Option = exports.NonTerminal = exports.Alternative = exports.Alternation = exports.defaultLexerErrorProvider = exports.NoViableAltException = exports.NotAllInputParsedException = exports.MismatchedTokenException = exports.isRecognitionException = exports.EarlyExitException = exports.defaultParserErrorProvider = exports.tokenName = exports.tokenMatcher = exports.tokenLabel = exports.EOF = exports.createTokenInstance = exports.createToken = exports.LexerDefinitionErrorType = exports.Lexer = exports.EMPTY_ALT = exports.ParserDefinitionErrorType = exports.EmbeddedActionsParser = exports.CstParser = exports.VERSION = void 0; - // semantic version - var version_1 = version; - Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return version_1.VERSION; } }); - var parser_1 = requireParser(); - Object.defineProperty(exports, "CstParser", { enumerable: true, get: function () { return parser_1.CstParser; } }); - Object.defineProperty(exports, "EmbeddedActionsParser", { enumerable: true, get: function () { return parser_1.EmbeddedActionsParser; } }); - Object.defineProperty(exports, "ParserDefinitionErrorType", { enumerable: true, get: function () { return parser_1.ParserDefinitionErrorType; } }); - Object.defineProperty(exports, "EMPTY_ALT", { enumerable: true, get: function () { return parser_1.EMPTY_ALT; } }); - var lexer_public_1 = requireLexer_public(); - Object.defineProperty(exports, "Lexer", { enumerable: true, get: function () { return lexer_public_1.Lexer; } }); - Object.defineProperty(exports, "LexerDefinitionErrorType", { enumerable: true, get: function () { return lexer_public_1.LexerDefinitionErrorType; } }); - // Tokens utilities - var tokens_public_1 = tokens_public; - Object.defineProperty(exports, "createToken", { enumerable: true, get: function () { return tokens_public_1.createToken; } }); - Object.defineProperty(exports, "createTokenInstance", { enumerable: true, get: function () { return tokens_public_1.createTokenInstance; } }); - Object.defineProperty(exports, "EOF", { enumerable: true, get: function () { return tokens_public_1.EOF; } }); - Object.defineProperty(exports, "tokenLabel", { enumerable: true, get: function () { return tokens_public_1.tokenLabel; } }); - Object.defineProperty(exports, "tokenMatcher", { enumerable: true, get: function () { return tokens_public_1.tokenMatcher; } }); - Object.defineProperty(exports, "tokenName", { enumerable: true, get: function () { return tokens_public_1.tokenName; } }); - // Other Utilities - var errors_public_1 = errors_public; - Object.defineProperty(exports, "defaultParserErrorProvider", { enumerable: true, get: function () { return errors_public_1.defaultParserErrorProvider; } }); - var exceptions_public_1 = exceptions_public; - Object.defineProperty(exports, "EarlyExitException", { enumerable: true, get: function () { return exceptions_public_1.EarlyExitException; } }); - Object.defineProperty(exports, "isRecognitionException", { enumerable: true, get: function () { return exceptions_public_1.isRecognitionException; } }); - Object.defineProperty(exports, "MismatchedTokenException", { enumerable: true, get: function () { return exceptions_public_1.MismatchedTokenException; } }); - Object.defineProperty(exports, "NotAllInputParsedException", { enumerable: true, get: function () { return exceptions_public_1.NotAllInputParsedException; } }); - Object.defineProperty(exports, "NoViableAltException", { enumerable: true, get: function () { return exceptions_public_1.NoViableAltException; } }); - var lexer_errors_public_1 = lexer_errors_public; - Object.defineProperty(exports, "defaultLexerErrorProvider", { enumerable: true, get: function () { return lexer_errors_public_1.defaultLexerErrorProvider; } }); - // grammar reflection API - var gast_1 = api$1; - Object.defineProperty(exports, "Alternation", { enumerable: true, get: function () { return gast_1.Alternation; } }); - Object.defineProperty(exports, "Alternative", { enumerable: true, get: function () { return gast_1.Alternative; } }); - Object.defineProperty(exports, "NonTerminal", { enumerable: true, get: function () { return gast_1.NonTerminal; } }); - Object.defineProperty(exports, "Option", { enumerable: true, get: function () { return gast_1.Option; } }); - Object.defineProperty(exports, "Repetition", { enumerable: true, get: function () { return gast_1.Repetition; } }); - Object.defineProperty(exports, "RepetitionMandatory", { enumerable: true, get: function () { return gast_1.RepetitionMandatory; } }); - Object.defineProperty(exports, "RepetitionMandatoryWithSeparator", { enumerable: true, get: function () { return gast_1.RepetitionMandatoryWithSeparator; } }); - Object.defineProperty(exports, "RepetitionWithSeparator", { enumerable: true, get: function () { return gast_1.RepetitionWithSeparator; } }); - Object.defineProperty(exports, "Rule", { enumerable: true, get: function () { return gast_1.Rule; } }); - Object.defineProperty(exports, "Terminal", { enumerable: true, get: function () { return gast_1.Terminal; } }); - // GAST Utilities - var gast_2 = api$1; - Object.defineProperty(exports, "serializeGrammar", { enumerable: true, get: function () { return gast_2.serializeGrammar; } }); - Object.defineProperty(exports, "serializeProduction", { enumerable: true, get: function () { return gast_2.serializeProduction; } }); - Object.defineProperty(exports, "GAstVisitor", { enumerable: true, get: function () { return gast_2.GAstVisitor; } }); - var cst_dts_gen_1 = api; - Object.defineProperty(exports, "generateCstDts", { enumerable: true, get: function () { return cst_dts_gen_1.generateCstDts; } }); - /* istanbul ignore next */ - function clearCache() { - console.warn("The clearCache function was 'soft' removed from the Chevrotain API." + - "\n\t It performs no action other than printing this message." + - "\n\t Please avoid using it as it will be completely removed in the future"); - } - exports.clearCache = clearCache; - var render_public_1 = render_public; - Object.defineProperty(exports, "createSyntaxDiagramsCode", { enumerable: true, get: function () { return render_public_1.createSyntaxDiagramsCode; } }); - var Parser = /** @class */ (function () { - function Parser() { - throw new Error("The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead.\t\n" + - "See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0"); - } - return Parser; - }()); - exports.Parser = Parser; - -} (api$3)); - -var mod = /*@__PURE__*/getDefaultExportFromCjs(api$3); - -mod.Alternation; -mod.Alternative; -mod.CstParser; -mod.EMPTY_ALT; -mod.EOF; -mod.EarlyExitException; -mod.EmbeddedActionsParser; -mod.GAstVisitor; -mod.Lexer; -mod.LexerDefinitionErrorType; -mod.MismatchedTokenException; -mod.NoViableAltException; -mod.NonTerminal; -mod.NotAllInputParsedException; -mod.Option; -mod.Parser; -mod.ParserDefinitionErrorType; -mod.Repetition; -mod.RepetitionMandatory; -mod.RepetitionMandatoryWithSeparator; -mod.RepetitionWithSeparator; -mod.Rule; -mod.Terminal; -mod.VERSION; -mod.clearCache; -mod.createSyntaxDiagramsCode; -mod.createToken; -mod.createTokenInstance; -mod.defaultLexerErrorProvider; -mod.defaultParserErrorProvider; -mod.generateCstDts; -mod.isRecognitionException; -mod.serializeGrammar; -mod.serializeProduction; -mod.tokenLabel; -mod.tokenMatcher; -mod.tokenName; + try { + value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } + } -/** - * Loader for Basis Universal GPU Texture Codec. - * - * Basis Universal is a "supercompressed" GPU texture and texture video - * compression system that outputs a highly compressed intermediate file format - * (.basis) that can be quickly transcoded to a wide variety of GPU texture - * compression formats. - * - * This loader parallelizes the transcoding process across a configurable number - * of web workers, before transferring the transcoded compressed texture back - * to the main thread. - */ + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress); + } -const _taskCache = new WeakMap(); + reconcileChildren(null, workInProgress, value, renderLanes); -class BasisTextureLoader extends Loader { - constructor(manager) { - super(manager); - this.transcoderPath = ''; - this.transcoderBinary = null; - this.transcoderPending = null; - this.workerLimit = 4; - this.workerPool = []; - this.workerNextTaskID = 1; - this.workerSourceURL = ''; - this.workerConfig = null; - } + { + validateFunctionComponentInDev(workInProgress, Component); + } - setTranscoderPath(path) { - this.transcoderPath = path; - return this; - } + return workInProgress.child; + } + } - setWorkerLimit(workerLimit) { - this.workerLimit = workerLimit; - return this; - } + function validateFunctionComponentInDev(workInProgress, Component) { + { + if (Component) { + if (Component.childContextTypes) { + error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); + } + } - detectSupport(renderer) { - this.workerConfig = { - astcSupported: renderer.extensions.has('WEBGL_compressed_texture_astc'), - etc1Supported: renderer.extensions.has('WEBGL_compressed_texture_etc1'), - etc2Supported: renderer.extensions.has('WEBGL_compressed_texture_etc'), - dxtSupported: renderer.extensions.has('WEBGL_compressed_texture_s3tc'), - bptcSupported: renderer.extensions.has('EXT_texture_compression_bptc'), - pvrtcSupported: renderer.extensions.has('WEBGL_compressed_texture_pvrtc') || renderer.extensions.has('WEBKIT_WEBGL_compressed_texture_pvrtc') - }; - return this; - } + if (workInProgress.ref !== null) { + var info = ''; + var ownerName = getCurrentFiberOwnerNameInDevOrNull(); - load(url, onLoad, onProgress, onError) { - const loader = new FileLoader(this.manager); - loader.setResponseType('arraybuffer'); - loader.setWithCredentials(this.withCredentials); - const texture = new CompressedTexture(); - loader.load(url, buffer => { - // Check for an existing task using this buffer. A transferred buffer cannot be transferred - // again from this thread. - if (_taskCache.has(buffer)) { - const cachedTask = _taskCache.get(buffer); + if (ownerName) { + info += '\n\nCheck the render method of `' + ownerName + '`.'; + } - return cachedTask.promise.then(onLoad).catch(onError); - } + var warningKey = ownerName || ''; + var debugSource = workInProgress._debugSource; - this._createTexture([buffer]).then(function (_texture) { - texture.copy(_texture); - texture.needsUpdate = true; - if (onLoad) onLoad(texture); - }).catch(onError); - }, onProgress, onError); - return texture; - } - /** Low-level transcoding API, exposed for use by KTX2Loader. */ + if (debugSource) { + warningKey = debugSource.fileName + ':' + debugSource.lineNumber; + } + if (!didWarnAboutFunctionRefs[warningKey]) { + didWarnAboutFunctionRefs[warningKey] = true; - parseInternalAsync(options) { - const { - levels - } = options; - const buffers = new Set(); + error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info); + } + } - for (let i = 0; i < levels.length; i++) { - buffers.add(levels[i].data.buffer); - } + if (typeof Component.getDerivedStateFromProps === 'function') { + var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; - return this._createTexture(Array.from(buffers), { ...options, - lowLevel: true - }); - } - /** - * @param {ArrayBuffer[]} buffers - * @param {object?} config - * @return {Promise} - */ + if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { + error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); + didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; + } + } - _createTexture(buffers, config = {}) { - let worker; - let taskID; - const taskConfig = config; - let taskCost = 0; + if (typeof Component.contextType === 'object' && Component.contextType !== null) { + var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; - for (let i = 0; i < buffers.length; i++) { - taskCost += buffers[i].byteLength; - } + if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { + error('%s: Function components do not support contextType.', _componentName4); - const texturePending = this._allocateWorker(taskCost).then(_worker => { - worker = _worker; - taskID = this.workerNextTaskID++; - return new Promise((resolve, reject) => { - worker._callbacks[taskID] = { - resolve, - reject - }; - worker.postMessage({ - type: 'transcode', - id: taskID, - buffers: buffers, - taskConfig: taskConfig - }, buffers); - }); - }).then(message => { - const { - mipmaps, - width, - height, - format - } = message; - const texture = new CompressedTexture(mipmaps, width, height, format, UnsignedByteType); - texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; - texture.magFilter = LinearFilter; - texture.generateMipmaps = false; - texture.needsUpdate = true; - return texture; - }); // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416) - - - texturePending.catch(() => true).then(() => { - if (worker && taskID) { - worker._taskLoad -= taskCost; - delete worker._callbacks[taskID]; - } - }); // Cache the task result. + didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; + } + } + } + } - _taskCache.set(buffers[0], { - promise: texturePending - }); + var SUSPENDED_MARKER = { + dehydrated: null, + treeContext: null, + retryLane: NoLane + }; - return texturePending; - } - - _initTranscoder() { - if (!this.transcoderPending) { - // Load transcoder wrapper. - const jsLoader = new FileLoader(this.manager); - jsLoader.setPath(this.transcoderPath); - jsLoader.setWithCredentials(this.withCredentials); - const jsContent = new Promise((resolve, reject) => { - jsLoader.load('basis_transcoder.js', resolve, undefined, reject); - }); // Load transcoder WASM binary. - - const binaryLoader = new FileLoader(this.manager); - binaryLoader.setPath(this.transcoderPath); - binaryLoader.setResponseType('arraybuffer'); - binaryLoader.setWithCredentials(this.withCredentials); - const binaryContent = new Promise((resolve, reject) => { - binaryLoader.load('basis_transcoder.wasm', resolve, undefined, reject); - }); - this.transcoderPending = Promise.all([jsContent, binaryContent]).then(([jsContent, binaryContent]) => { - const fn = BasisTextureLoader.BasisWorker.toString(); - const body = ['/* constants */', 'let _EngineFormat = ' + JSON.stringify(BasisTextureLoader.EngineFormat), 'let _TranscoderFormat = ' + JSON.stringify(BasisTextureLoader.TranscoderFormat), 'let _BasisFormat = ' + JSON.stringify(BasisTextureLoader.BasisFormat), '/* basis_transcoder.js */', jsContent, '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n'); - this.workerSourceURL = URL.createObjectURL(new Blob([body])); - this.transcoderBinary = binaryContent; - }); - } + function mountSuspenseOffscreenState(renderLanes) { + return { + baseLanes: renderLanes, + cachePool: getSuspendedCache() + }; + } - return this.transcoderPending; - } + function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) { + var cachePool = null; - _allocateWorker(taskCost) { - return this._initTranscoder().then(() => { - if (this.workerPool.length < this.workerLimit) { - const worker = new Worker(this.workerSourceURL); - worker._callbacks = {}; - worker._taskLoad = 0; - worker.postMessage({ - type: 'init', - config: this.workerConfig, - transcoderBinary: this.transcoderBinary - }); + return { + baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes), + cachePool: cachePool + }; + } // TODO: Probably should inline this back - worker.onmessage = function (e) { - const message = e.data; - switch (message.type) { - case 'transcode': - worker._callbacks[message.id].resolve(message); + function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) { + // If we're already showing a fallback, there are cases where we need to + // remain on that fallback regardless of whether the content has resolved. + // For example, SuspenseList coordinates when nested content appears. + if (current !== null) { + var suspenseState = current.memoizedState; - break; + if (suspenseState === null) { + // Currently showing content. Don't hide it, even if ForceSuspenseFallback + // is true. More precise name might be "ForceRemainSuspenseFallback". + // Note: This is a factoring smell. Can't remain on a fallback if there's + // no fallback to remain on. + return false; + } + } // Not currently showing content. Consult the Suspense context. - case 'error': - worker._callbacks[message.id].reject(message); - break; + return hasSuspenseContext(suspenseContext, ForceSuspenseFallback); + } - default: - console.error('THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"'); - } - }; + function getRemainingWorkInPrimaryTree(current, renderLanes) { + // TODO: Should not remove render lanes that were pinged during this render + return removeLanes(current.childLanes, renderLanes); + } - this.workerPool.push(worker); - } else { - this.workerPool.sort(function (a, b) { - return a._taskLoad > b._taskLoad ? -1 : 1; - }); - } + function updateSuspenseComponent(current, workInProgress, renderLanes) { + var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. - const worker = this.workerPool[this.workerPool.length - 1]; - worker._taskLoad += taskCost; - return worker; - }); - } + { + if (shouldSuspend(workInProgress)) { + workInProgress.flags |= DidCapture; + } + } - dispose() { - for (let i = 0; i < this.workerPool.length; i++) { - this.workerPool[i].terminate(); - } + var suspenseContext = suspenseStackCursor.current; + var showFallback = false; + var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags; - this.workerPool.length = 0; - return this; - } + if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) { + // Something in this boundary's subtree already suspended. Switch to + // rendering the fallback children. + showFallback = true; + workInProgress.flags &= ~DidCapture; + } else { + // Attempting the main content + if (current === null || current.memoizedState !== null) { + // This is a new mount or this boundary is already showing a fallback state. + // Mark this subtree context as having at least one invisible parent that could + // handle the fallback state. + // Avoided boundaries are not considered since they cannot handle preferred fallback states. + { + suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext); + } + } + } -} -/* CONSTANTS */ + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense + // boundary's children. This involves some custom reconciliation logic. Two + // main reasons this is so complicated. + // + // First, Legacy Mode has different semantics for backwards compatibility. The + // primary tree will commit in an inconsistent state, so when we do the + // second pass to render the fallback, we do some exceedingly, uh, clever + // hacks to make that not totally break. Like transferring effects and + // deletions from hidden tree. In Concurrent Mode, it's much simpler, + // because we bailout on the primary tree completely and leave it in its old + // state, no effects. Same as what we do for Offscreen (except that + // Offscreen doesn't have the first render pass). + // + // Second is hydration. During hydration, the Suspense fiber has a slightly + // different layout, where the child points to a dehydrated fragment, which + // contains the DOM rendered by the server. + // + // Third, even if you set all that aside, Suspense is like error boundaries in + // that we first we try to render one tree, and if that fails, we render again + // and switch to a different tree. Like a try/catch block. So we have to track + // which branch we're currently rendering. Ideally we would model this using + // a stack. + if (current === null) { + // Initial mount + // If we're currently hydrating, try to hydrate this boundary. + tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. -BasisTextureLoader.BasisFormat = { - ETC1S: 0, - UASTC_4x4: 1 -}; -BasisTextureLoader.TranscoderFormat = { - ETC1: 0, - ETC2: 1, - BC1: 2, - BC3: 3, - BC4: 4, - BC5: 5, - BC7_M6_OPAQUE_ONLY: 6, - BC7_M5: 7, - PVRTC1_4_RGB: 8, - PVRTC1_4_RGBA: 9, - ASTC_4x4: 10, - ATC_RGB: 11, - ATC_RGBA_INTERPOLATED_ALPHA: 12, - RGBA32: 13, - RGB565: 14, - BGR565: 15, - RGBA4444: 16 -}; -BasisTextureLoader.EngineFormat = { - RGBAFormat: RGBAFormat, - RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format, - RGBA_BPTC_Format: RGBA_BPTC_Format, - RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format, - RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format, - RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format, - RGB_ETC1_Format: RGB_ETC1_Format, - RGB_ETC2_Format: RGB_ETC2_Format, - RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format, - RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format -}; -/* WEB WORKER */ + { + var suspenseState = workInProgress.memoizedState; -BasisTextureLoader.BasisWorker = function () { - let config; - let transcoderPending; - let BasisModule; - const EngineFormat = _EngineFormat; // eslint-disable-line no-undef + if (suspenseState !== null) { + var dehydrated = suspenseState.dehydrated; - const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef + if (dehydrated !== null) { + return mountDehydratedSuspenseComponent(workInProgress, dehydrated); + } + } + } - const BasisFormat = _BasisFormat; // eslint-disable-line no-undef + var nextPrimaryChildren = nextProps.children; + var nextFallbackChildren = nextProps.fallback; - onmessage = function (e) { - const message = e.data; + if (showFallback) { + var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes); + var primaryChildFragment = workInProgress.child; + primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes); + workInProgress.memoizedState = SUSPENDED_MARKER; + return fallbackFragment; + } else { + return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren); + } + } else { + // This is an update. + // If the current fiber has a SuspenseState, that means it's already showing + // a fallback. + var prevState = current.memoizedState; - switch (message.type) { - case 'init': - config = message.config; - init(message.transcoderBinary); - break; + if (prevState !== null) { + // The current tree is already showing a fallback + // Special path for hydration + { + var _dehydrated = prevState.dehydrated; - case 'transcode': - transcoderPending.then(() => { - try { - const { - width, - height, - hasAlpha, - mipmaps, - format - } = message.taskConfig.lowLevel ? transcodeLowLevel(message.taskConfig) : transcode(message.buffers[0]); - const buffers = []; - - for (let i = 0; i < mipmaps.length; ++i) { - buffers.push(mipmaps[i].data.buffer); - } + if (_dehydrated !== null) { + if (!didSuspend) { + return updateDehydratedSuspenseComponent(current, workInProgress, _dehydrated, prevState, renderLanes); + } else if (workInProgress.flags & ForceClientRender) { + // Something errored during hydration. Try again without hydrating. + workInProgress.flags &= ~ForceClientRender; + return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.')); + } else if (workInProgress.memoizedState !== null) { + // Something suspended and we should still be in dehydrated mode. + // Leave the existing child in place. + workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there + // but the normal suspense pass doesn't. - self.postMessage({ - type: 'transcode', - id: message.id, - width, - height, - hasAlpha, - mipmaps, - format - }, buffers); - } catch (error) { - console.error(error); - self.postMessage({ - type: 'error', - id: message.id, - error: error.message - }); - } - }); - break; - } - }; + workInProgress.flags |= DidCapture; + return null; + } else { + // Suspended but we should no longer be in dehydrated mode. + // Therefore we now have to render the fallback. + var _nextPrimaryChildren = nextProps.children; + var _nextFallbackChildren = nextProps.fallback; + var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes); + var _primaryChildFragment2 = workInProgress.child; + _primaryChildFragment2.memoizedState = mountSuspenseOffscreenState(renderLanes); + workInProgress.memoizedState = SUSPENDED_MARKER; + return fallbackChildFragment; + } + } + } - function init(wasmBinary) { - transcoderPending = new Promise(resolve => { - BasisModule = { - wasmBinary, - onRuntimeInitialized: resolve - }; - BASIS(BasisModule); // eslint-disable-line no-undef - }).then(() => { - BasisModule.initializeBasis(); - }); - } + if (showFallback) { + var _nextFallbackChildren2 = nextProps.fallback; + var _nextPrimaryChildren2 = nextProps.children; - function transcodeLowLevel(taskConfig) { - const { - basisFormat, - width, - height, - hasAlpha - } = taskConfig; - const { - transcoderFormat, - engineFormat - } = getTranscoderFormat(basisFormat, width, height, hasAlpha); - const blockByteLength = BasisModule.getBytesPerBlockOrPixel(transcoderFormat); - assert(BasisModule.isFormatSupported(transcoderFormat), 'THREE.BasisTextureLoader: Unsupported format.'); - const mipmaps = []; - - if (basisFormat === BasisFormat.ETC1S) { - const transcoder = new BasisModule.LowLevelETC1SImageTranscoder(); - const { - endpointCount, - endpointsData, - selectorCount, - selectorsData, - tablesData - } = taskConfig.globalData; + var _fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren2, _nextFallbackChildren2, renderLanes); - try { - let ok; - ok = transcoder.decodePalettes(endpointCount, endpointsData, selectorCount, selectorsData); - assert(ok, 'THREE.BasisTextureLoader: decodePalettes() failed.'); - ok = transcoder.decodeTables(tablesData); - assert(ok, 'THREE.BasisTextureLoader: decodeTables() failed.'); - - for (let i = 0; i < taskConfig.levels.length; i++) { - const level = taskConfig.levels[i]; - const imageDesc = taskConfig.globalData.imageDescs[i]; - const dstByteLength = getTranscodedImageByteLength(transcoderFormat, level.width, level.height); - const dst = new Uint8Array(dstByteLength); - ok = transcoder.transcodeImage(transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks(transcoderFormat, level.width), getHeightInBlocks(transcoderFormat, level.height), level.width, level.height, level.index, imageDesc.rgbSliceByteOffset, imageDesc.rgbSliceByteLength, imageDesc.alphaSliceByteOffset, imageDesc.alphaSliceByteLength, imageDesc.imageFlags, hasAlpha, false, 0, 0); - assert(ok, 'THREE.BasisTextureLoader: transcodeImage() failed for level ' + level.index + '.'); - mipmaps.push({ - data: dst, - width: level.width, - height: level.height - }); - } - } finally { - transcoder.delete(); - } - } else { - for (let i = 0; i < taskConfig.levels.length; i++) { - const level = taskConfig.levels[i]; - const dstByteLength = getTranscodedImageByteLength(transcoderFormat, level.width, level.height); - const dst = new Uint8Array(dstByteLength); - const ok = BasisModule.transcodeUASTCImage(transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks(transcoderFormat, level.width), getHeightInBlocks(transcoderFormat, level.height), level.width, level.height, level.index, 0, level.data.byteLength, 0, hasAlpha, false, 0, 0, -1, -1); - assert(ok, 'THREE.BasisTextureLoader: transcodeUASTCImage() failed for level ' + level.index + '.'); - mipmaps.push({ - data: dst, - width: level.width, - height: level.height - }); - } - } + var _primaryChildFragment3 = workInProgress.child; + var prevOffscreenState = current.child.memoizedState; + _primaryChildFragment3.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes); + _primaryChildFragment3.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); + workInProgress.memoizedState = SUSPENDED_MARKER; + return _fallbackChildFragment; + } else { + var _nextPrimaryChildren3 = nextProps.children; - return { - width, - height, - hasAlpha, - mipmaps, - format: engineFormat - }; - } + var _primaryChildFragment4 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren3, renderLanes); - function transcode(buffer) { - const basisFile = new BasisModule.BasisFile(new Uint8Array(buffer)); - const basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; - const width = basisFile.getImageWidth(0, 0); - const height = basisFile.getImageHeight(0, 0); - const levels = basisFile.getNumLevels(0); - const hasAlpha = basisFile.getHasAlpha(); + workInProgress.memoizedState = null; + return _primaryChildFragment4; + } + } else { + // The current tree is not already showing a fallback. + if (showFallback) { + // Timed out. + var _nextFallbackChildren3 = nextProps.fallback; + var _nextPrimaryChildren4 = nextProps.children; - function cleanup() { - basisFile.close(); - basisFile.delete(); - } + var _fallbackChildFragment2 = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren4, _nextFallbackChildren3, renderLanes); - const { - transcoderFormat, - engineFormat - } = getTranscoderFormat(basisFormat, width, height, hasAlpha); + var _primaryChildFragment5 = workInProgress.child; + var _prevOffscreenState = current.child.memoizedState; + _primaryChildFragment5.memoizedState = _prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(_prevOffscreenState, renderLanes); + _primaryChildFragment5.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); // Skip the primary children, and continue working on the + // fallback children. - if (!width || !height || !levels) { - cleanup(); - throw new Error('THREE.BasisTextureLoader: Invalid texture'); - } + workInProgress.memoizedState = SUSPENDED_MARKER; + return _fallbackChildFragment2; + } else { + // Still haven't timed out. Continue rendering the children, like we + // normally do. + var _nextPrimaryChildren5 = nextProps.children; - if (!basisFile.startTranscoding()) { - cleanup(); - throw new Error('THREE.BasisTextureLoader: .startTranscoding failed'); - } + var _primaryChildFragment6 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren5, renderLanes); - const mipmaps = []; + workInProgress.memoizedState = null; + return _primaryChildFragment6; + } + } + } + } - for (let mip = 0; mip < levels; mip++) { - const mipWidth = basisFile.getImageWidth(0, mip); - const mipHeight = basisFile.getImageHeight(0, mip); - const dst = new Uint8Array(basisFile.getImageTranscodedSizeInBytes(0, mip, transcoderFormat)); - const status = basisFile.transcodeImage(dst, 0, mip, transcoderFormat, 0, hasAlpha); + function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) { + var mode = workInProgress.mode; + var primaryChildProps = { + mode: 'visible', + children: primaryChildren + }; + var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); + primaryChildFragment.return = workInProgress; + workInProgress.child = primaryChildFragment; + return primaryChildFragment; + } - if (!status) { - cleanup(); - throw new Error('THREE.BasisTextureLoader: .transcodeImage failed.'); - } + function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) { + var mode = workInProgress.mode; + var progressedPrimaryFragment = workInProgress.child; + var primaryChildProps = { + mode: 'hidden', + children: primaryChildren + }; + var primaryChildFragment; + var fallbackChildFragment; - mipmaps.push({ - data: dst, - width: mipWidth, - height: mipHeight - }); - } + if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) { + // In legacy mode, we commit the primary tree as if it successfully + // completed, even though it's in an inconsistent state. + primaryChildFragment = progressedPrimaryFragment; + primaryChildFragment.childLanes = NoLanes; + primaryChildFragment.pendingProps = primaryChildProps; - cleanup(); - return { - width, - height, - hasAlpha, - mipmaps, - format: engineFormat - }; - } // - // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC), - // device capabilities, and texture dimensions. The list below ranks the formats separately - // for ETC1S and UASTC. - // - // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at - // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently - // chooses RGBA32 only as a last resort and does not expose that option to the caller. - - - const FORMAT_OPTIONS = [{ - if: 'astcSupported', - basisFormat: [BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4], - engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format], - priorityETC1S: Infinity, - priorityUASTC: 1, - needsPowerOfTwo: false - }, { - if: 'bptcSupported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5], - engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format], - priorityETC1S: 3, - priorityUASTC: 2, - needsPowerOfTwo: false - }, { - if: 'dxtSupported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3], - engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format], - priorityETC1S: 4, - priorityUASTC: 5, - needsPowerOfTwo: false - }, { - if: 'etc2Supported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2], - engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format], - priorityETC1S: 1, - priorityUASTC: 3, - needsPowerOfTwo: false - }, { - if: 'etc1Supported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC1], - engineFormat: [EngineFormat.RGB_ETC1_Format, EngineFormat.RGB_ETC1_Format], - priorityETC1S: 2, - priorityUASTC: 4, - needsPowerOfTwo: false - }, { - if: 'pvrtcSupported', - basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], - transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA], - engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format], - priorityETC1S: 5, - priorityUASTC: 6, - needsPowerOfTwo: true - }]; - const ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) { - return a.priorityETC1S - b.priorityETC1S; - }); - const UASTC_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) { - return a.priorityUASTC - b.priorityUASTC; - }); + if ( workInProgress.mode & ProfileMode) { + // Reset the durations from the first pass so they aren't included in the + // final amounts. This seems counterintuitive, since we're intentionally + // not measuring part of the render phase, but this makes it match what we + // do in Concurrent Mode. + primaryChildFragment.actualDuration = 0; + primaryChildFragment.actualStartTime = -1; + primaryChildFragment.selfBaseDuration = 0; + primaryChildFragment.treeBaseDuration = 0; + } - function getTranscoderFormat(basisFormat, width, height, hasAlpha) { - let transcoderFormat; - let engineFormat; - const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; - - for (let i = 0; i < options.length; i++) { - const opt = options[i]; - if (!config[opt.if]) continue; - if (!opt.basisFormat.includes(basisFormat)) continue; - if (opt.needsPowerOfTwo && !(isPowerOfTwo(width) && isPowerOfTwo(height))) continue; - transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0]; - engineFormat = opt.engineFormat[hasAlpha ? 1 : 0]; - return { - transcoderFormat, - engineFormat - }; - } + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); + } else { + primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); + } - console.warn('THREE.BasisTextureLoader: No suitable compressed texture format found. Decoding to RGBA32.'); - transcoderFormat = TranscoderFormat.RGBA32; - engineFormat = EngineFormat.RGBAFormat; - return { - transcoderFormat, - engineFormat - }; - } + primaryChildFragment.return = workInProgress; + fallbackChildFragment.return = workInProgress; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress.child = primaryChildFragment; + return fallbackChildFragment; + } - function assert(ok, message) { - if (!ok) throw new Error(message); - } + function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) { + // The props argument to `createFiberFromOffscreen` is `any` typed, so we use + // this wrapper function to constrain it. + return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); + } - function getWidthInBlocks(transcoderFormat, width) { - return Math.ceil(width / BasisModule.getFormatBlockWidth(transcoderFormat)); - } + function updateWorkInProgressOffscreenFiber(current, offscreenProps) { + // The props argument to `createWorkInProgress` is `any` typed, so we use this + // wrapper function to constrain it. + return createWorkInProgress(current, offscreenProps); + } - function getHeightInBlocks(transcoderFormat, height) { - return Math.ceil(height / BasisModule.getFormatBlockHeight(transcoderFormat)); - } + function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) { + var currentPrimaryChildFragment = current.child; + var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, { + mode: 'visible', + children: primaryChildren + }); - function getTranscodedImageByteLength(transcoderFormat, width, height) { - const blockByteLength = BasisModule.getBytesPerBlockOrPixel(transcoderFormat); + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + primaryChildFragment.lanes = renderLanes; + } - if (BasisModule.formatIsUncompressed(transcoderFormat)) { - return width * height * blockByteLength; - } + primaryChildFragment.return = workInProgress; + primaryChildFragment.sibling = null; - if (transcoderFormat === TranscoderFormat.PVRTC1_4_RGB || transcoderFormat === TranscoderFormat.PVRTC1_4_RGBA) { - // GL requires extra padding for very small textures: - // https://www.khronos.org/registry/OpenGL/extensions/IMG/IMG_texture_compression_pvrtc.txt - const paddedWidth = width + 3 & ~3; - const paddedHeight = height + 3 & ~3; - return (Math.max(8, paddedWidth) * Math.max(8, paddedHeight) * 4 + 7) / 8; - } + if (currentFallbackChildFragment !== null) { + // Delete the fallback child fragment + var deletions = workInProgress.deletions; - return getWidthInBlocks(transcoderFormat, width) * getHeightInBlocks(transcoderFormat, height) * blockByteLength; - } + if (deletions === null) { + workInProgress.deletions = [currentFallbackChildFragment]; + workInProgress.flags |= ChildDeletion; + } else { + deletions.push(currentFallbackChildFragment); + } + } - function isPowerOfTwo(value) { - if (value <= 2) return true; - return (value & value - 1) === 0 && value !== 0; - } -}; + workInProgress.child = primaryChildFragment; + return primaryChildFragment; + } -var n$2,i$2,s$1,a$1,r$1,o$1,l$1,f$1;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB";}(n$2||(n$2={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT";}(i$2||(i$2={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC";}(s$1||(s$1={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB";}(a$1||(a$1={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2";}(r$1||(r$1={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED";}(o$1||(o$1={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA";}(l$1||(l$1={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG";}(f$1||(f$1={})); + function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { + var mode = workInProgress.mode; + var currentPrimaryChildFragment = current.child; + var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + var primaryChildProps = { + mode: 'hidden', + children: primaryChildren + }; + var primaryChildFragment; -/** - * https://opentype.js.org v1.3.4 | (c) Frederik De Bleser and other contributors | MIT License | Uses tiny-inflate by Devon Govett and string.prototype.codepointat polyfill by Mathias Bynens - */ + if ( // In legacy mode, we commit the primary tree as if it successfully + // completed, even though it's in an inconsistent state. + (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was + // already cloned. In legacy mode, the only case where this isn't true is + // when DevTools forces us to display a fallback; we skip the first render + // pass entirely and go straight to rendering the fallback. (In Concurrent + // Mode, SuspenseList can also trigger this scenario, but this is a legacy- + // only codepath.) + workInProgress.child !== currentPrimaryChildFragment) { + var progressedPrimaryFragment = workInProgress.child; + primaryChildFragment = progressedPrimaryFragment; + primaryChildFragment.childLanes = NoLanes; + primaryChildFragment.pendingProps = primaryChildProps; -/*! https://mths.be/codepointat v0.2.0 by @mathias */ -if (!String.prototype.codePointAt) { - (function() { - var defineProperty = (function() { - // IE 8 only supports `Object.defineProperty` on DOM elements - try { - var object = {}; - var $defineProperty = Object.defineProperty; - var result = $defineProperty(object, object, object) && $defineProperty; - } catch(error) {} - return result; - }()); - var codePointAt = function(position) { - if (this == null) { - throw TypeError(); - } - var string = String(this); - var size = string.length; - // `ToInteger` - var index = position ? Number(position) : 0; - if (index != index) { // better `isNaN` - index = 0; - } - // Account for out-of-bounds indices: - if (index < 0 || index >= size) { - return undefined; - } - // Get the first code unit - var first = string.charCodeAt(index); - var second; - if ( // check if it’s the start of a surrogate pair - first >= 0xD800 && first <= 0xDBFF && // high surrogate - size > index + 1 // there is a next code unit - ) { - second = string.charCodeAt(index + 1); - if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - } - } - return first; - }; - if (defineProperty) { - defineProperty(String.prototype, 'codePointAt', { - 'value': codePointAt, - 'configurable': true, - 'writable': true - }); - } else { - String.prototype.codePointAt = codePointAt; - } - }()); -} + if ( workInProgress.mode & ProfileMode) { + // Reset the durations from the first pass so they aren't included in the + // final amounts. This seems counterintuitive, since we're intentionally + // not measuring part of the render phase, but this makes it match what we + // do in Concurrent Mode. + primaryChildFragment.actualDuration = 0; + primaryChildFragment.actualStartTime = -1; + primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; + primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; + } + // However, since we're going to remain on the fallback, we no longer want + // to delete it. -function Tree$1() { - this.table = new Uint16Array(16); /* table of code length counts */ - this.trans = new Uint16Array(288); /* code -> symbol translation table */ -} -/* --------------------------------------------------- * - * -- uninitialized global data (static structures) -- * - * --------------------------------------------------- */ + workInProgress.deletions = null; + } else { + primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); + // (We don't do this in legacy mode, because in legacy mode we don't re-use + // the current tree; see previous branch.) + -var sltree = new Tree$1(); -var sdtree = new Tree$1(); + primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; + } -/* extra bits and base tables for length codes */ -var length_bits = new Uint8Array(30); -var length_base = new Uint16Array(30); + var fallbackChildFragment; -/* extra bits and base tables for distance codes */ -var dist_bits = new Uint8Array(30); -var dist_base = new Uint16Array(30); + if (currentFallbackChildFragment !== null) { + fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren); + } else { + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already + // mounted but this is a new fiber. -/* used by tinf_decode_trees, avoids allocations every call */ -new Tree$1(); + fallbackChildFragment.flags |= Placement; + } -/* ----------------------- * - * -- utility functions -- * - * ----------------------- */ + fallbackChildFragment.return = workInProgress; + primaryChildFragment.return = workInProgress; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress.child = primaryChildFragment; + return fallbackChildFragment; + } -/* build extra bits and base tables */ -function tinf_build_bits_base(bits, base, delta, first) { - var i, sum; + function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) { + // Falling back to client rendering. Because this has performance + // implications, it's considered a recoverable error, even though the user + // likely won't observe anything wrong with the UI. + // + // The error is passed in as an argument to enforce that every caller provide + // a custom message, or explicitly opt out (currently the only path that opts + // out is legacy mode; every concurrent path provides an error). + if (recoverableError !== null) { + queueHydrationError(recoverableError); + } // This will add the old fiber to the deletion list - /* build bits table */ - for (i = 0; i < delta; ++i) { bits[i] = 0; } - for (i = 0; i < 30 - delta; ++i) { bits[i + delta] = i / delta | 0; } - /* build base table */ - for (sum = first, i = 0; i < 30; ++i) { - base[i] = sum; - sum += 1 << bits[i]; - } -} + reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated. -/* build the fixed huffman trees */ -function tinf_build_fixed_trees(lt, dt) { - var i; + var nextProps = workInProgress.pendingProps; + var primaryChildren = nextProps.children; + var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already + // mounted but this is a new fiber. - /* build fixed length tree */ - for (i = 0; i < 7; ++i) { lt.table[i] = 0; } + primaryChildFragment.flags |= Placement; + workInProgress.memoizedState = null; + return primaryChildFragment; + } - lt.table[7] = 24; - lt.table[8] = 152; - lt.table[9] = 112; + function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { + var fiberMode = workInProgress.mode; + var primaryChildProps = { + mode: 'visible', + children: primaryChildren + }; + var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode); + var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense + // boundary) already mounted but this is a new fiber. - for (i = 0; i < 24; ++i) { lt.trans[i] = 256 + i; } - for (i = 0; i < 144; ++i) { lt.trans[24 + i] = i; } - for (i = 0; i < 8; ++i) { lt.trans[24 + 144 + i] = 280 + i; } - for (i = 0; i < 112; ++i) { lt.trans[24 + 144 + 8 + i] = 144 + i; } + fallbackChildFragment.flags |= Placement; + primaryChildFragment.return = workInProgress; + fallbackChildFragment.return = workInProgress; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress.child = primaryChildFragment; - /* build fixed distance tree */ - for (i = 0; i < 5; ++i) { dt.table[i] = 0; } + if ((workInProgress.mode & ConcurrentMode) !== NoMode) { + // We will have dropped the effect list which contains the + // deletion. We need to reconcile to delete the current child. + reconcileChildFibers(workInProgress, current.child, null, renderLanes); + } - dt.table[5] = 32; + return fallbackChildFragment; + } - for (i = 0; i < 32; ++i) { dt.trans[i] = i; } -} + function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) { + // During the first pass, we'll bail out and not drill into the children. + // Instead, we'll leave the content in place and try to hydrate it later. + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + { + error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, )' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.'); + } -/* -------------------- * - * -- initialization -- * - * -------------------- */ + workInProgress.lanes = laneToLanes(SyncLane); + } else if (isSuspenseInstanceFallback(suspenseInstance)) { + // This is a client-only boundary. Since we won't get any content from the server + // for this, we need to schedule that at a higher priority based on when it would + // have timed out. In theory we could render it in this pass but it would have the + // wrong priority associated with it and will prevent hydration of parent path. + // Instead, we'll leave work left on it to render it in a separate commit. + // TODO This time should be the time at which the server rendered response that is + // a parent to this boundary was displayed. However, since we currently don't have + // a protocol to transfer that time, we'll just estimate it by using the current + // time. This will mean that Suspense timeouts are slightly shifted to later than + // they should be. + // Schedule a normal pri update to render this content. + workInProgress.lanes = laneToLanes(DefaultHydrationLane); + } else { + // We'll continue hydrating the rest at offscreen priority since we'll already + // be showing the right content coming from the server, it is no rush. + workInProgress.lanes = laneToLanes(OffscreenLane); + } -/* build fixed huffman trees */ -tinf_build_fixed_trees(sltree, sdtree); + return null; + } -/* build extra bits and base tables */ -tinf_build_bits_base(length_bits, length_base, 4, 3); -tinf_build_bits_base(dist_bits, dist_base, 2, 1); + function updateDehydratedSuspenseComponent(current, workInProgress, suspenseInstance, suspenseState, renderLanes) { + // We should never be hydrating at this point because it is the first pass, + // but after we've already committed once. + warnIfHydrating(); -/* fix a special case */ -length_bits[28] = 0; -length_base[28] = 258; + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument + // required — every concurrent mode path that causes hydration to + // de-opt to client rendering should have an error message. + null); + } -// The Bounding Box object + if (isSuspenseInstanceFallback(suspenseInstance)) { + // This boundary is in a permanent fallback state. In this case, we'll never + // get an update and we'll never be able to hydrate the final content. Let's just try the + // client side render instead. + return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: The server should serialize the error message so we can log it + // here on the client. Or, in production, a hash/id that corresponds to + // the error. + new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.')); + } + // any context has changed, we need to treat is as if the input might have changed. -function derive(v0, v1, v2, v3, t) { - return Math.pow(1 - t, 3) * v0 + - 3 * Math.pow(1 - t, 2) * t * v1 + - 3 * (1 - t) * Math.pow(t, 2) * v2 + - Math.pow(t, 3) * v3; -} -/** - * A bounding box is an enclosing box that describes the smallest measure within which all the points lie. - * It is used to calculate the bounding box of a glyph or text path. - * - * On initialization, x1/y1/x2/y2 will be NaN. Check if the bounding box is empty using `isEmpty()`. - * - * @exports opentype.BoundingBox - * @class - * @constructor - */ -function BoundingBox() { - this.x1 = Number.NaN; - this.y1 = Number.NaN; - this.x2 = Number.NaN; - this.y2 = Number.NaN; -} -/** - * Returns true if the bounding box is empty, that is, no points have been added to the box yet. - */ -BoundingBox.prototype.isEmpty = function() { - return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2); -}; + var hasContextChanged = includesSomeLane(renderLanes, current.childLanes); -/** - * Add the point to the bounding box. - * The x1/y1/x2/y2 coordinates of the bounding box will now encompass the given point. - * @param {number} x - The X coordinate of the point. - * @param {number} y - The Y coordinate of the point. - */ -BoundingBox.prototype.addPoint = function(x, y) { - if (typeof x === 'number') { - if (isNaN(this.x1) || isNaN(this.x2)) { - this.x1 = x; - this.x2 = x; - } - if (x < this.x1) { - this.x1 = x; - } - if (x > this.x2) { - this.x2 = x; - } - } - if (typeof y === 'number') { - if (isNaN(this.y1) || isNaN(this.y2)) { - this.y1 = y; - this.y2 = y; - } - if (y < this.y1) { - this.y1 = y; - } - if (y > this.y2) { - this.y2 = y; - } - } -}; + if (didReceiveUpdate || hasContextChanged) { + // This boundary has changed since the first render. This means that we are now unable to + // hydrate it. We might still be able to hydrate it using a higher priority lane. + var root = getWorkInProgressRoot(); -/** - * Add a X coordinate to the bounding box. - * This extends the bounding box to include the X coordinate. - * This function is used internally inside of addBezier. - * @param {number} x - The X coordinate of the point. - */ -BoundingBox.prototype.addX = function(x) { - this.addPoint(x, null); -}; + if (root !== null) { + var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes); -/** - * Add a Y coordinate to the bounding box. - * This extends the bounding box to include the Y coordinate. - * This function is used internally inside of addBezier. - * @param {number} y - The Y coordinate of the point. - */ -BoundingBox.prototype.addY = function(y) { - this.addPoint(null, y); -}; + if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) { + // Intentionally mutating since this render will get interrupted. This + // is one of the very rare times where we mutate the current tree + // during the render phase. + suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render -/** - * Add a Bézier curve to the bounding box. - * This extends the bounding box to include the entire Bézier. - * @param {number} x0 - The starting X coordinate. - * @param {number} y0 - The starting Y coordinate. - * @param {number} x1 - The X coordinate of the first control point. - * @param {number} y1 - The Y coordinate of the first control point. - * @param {number} x2 - The X coordinate of the second control point. - * @param {number} y2 - The Y coordinate of the second control point. - * @param {number} x - The ending X coordinate. - * @param {number} y - The ending Y coordinate. - */ -BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x, y) { - // This code is based on http://nishiohirokazu.blogspot.com/2009/06/how-to-calculate-bezier-curves-bounding.html - // and https://github.com/icons8/svg-path-bounding-box - - var p0 = [x0, y0]; - var p1 = [x1, y1]; - var p2 = [x2, y2]; - var p3 = [x, y]; - - this.addPoint(x0, y0); - this.addPoint(x, y); - - for (var i = 0; i <= 1; i++) { - var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; - var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; - var c = 3 * p1[i] - 3 * p0[i]; - - if (a === 0) { - if (b === 0) { continue; } - var t = -c / b; - if (0 < t && t < 1) { - if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t)); } - if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t)); } - } - continue; - } + var eventTime = NoTimestamp; + scheduleUpdateOnFiber(current, attemptHydrationAtLane, eventTime); + } + } // If we have scheduled higher pri work above, this will probably just abort the render + // since we now have higher priority work, but in case it doesn't, we need to prepare to + // render something, if we time out. Even if that requires us to delete everything and + // skip hydration. + // Delay having to do this as long as the suspense timeout allows us. - var b2ac = Math.pow(b, 2) - 4 * c * a; - if (b2ac < 0) { continue; } - var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); - if (0 < t1 && t1 < 1) { - if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); } - if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); } - } - var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); - if (0 < t2 && t2 < 1) { - if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); } - if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); } - } - } -}; -/** - * Add a quadratic curve to the bounding box. - * This extends the bounding box to include the entire quadratic curve. - * @param {number} x0 - The starting X coordinate. - * @param {number} y0 - The starting Y coordinate. - * @param {number} x1 - The X coordinate of the control point. - * @param {number} y1 - The Y coordinate of the control point. - * @param {number} x - The ending X coordinate. - * @param {number} y - The ending Y coordinate. - */ -BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x, y) { - var cp1x = x0 + 2 / 3 * (x1 - x0); - var cp1y = y0 + 2 / 3 * (y1 - y0); - var cp2x = cp1x + 1 / 3 * (x - x0); - var cp2y = cp1y + 1 / 3 * (y - y0); - this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y); -}; + renderDidSuspendDelayIfPossible(); + return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.')); + } else if (isSuspenseInstancePending(suspenseInstance)) { + // This component is still pending more data from the server, so we can't hydrate its + // content. We treat it as if this component suspended itself. It might seem as if + // we could just try to render it client-side instead. However, this will perform a + // lot of unnecessary work and is unlikely to complete since it often will suspend + // on missing data anyway. Additionally, the server might be able to render more + // than we can on the client yet. In that case we'd end up with more fallback states + // on the client than if we just leave it alone. If the server times out or errors + // these should update this boundary to the permanent Fallback state instead. + // Mark it as having captured (i.e. suspended). + workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. -// Geometric objects + workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result. -/** - * A bézier path containing a set of path commands similar to a SVG path. - * Paths can be drawn on a context using `draw`. - * @exports opentype.Path - * @class - * @constructor - */ -function Path() { - this.commands = []; - this.fill = 'black'; - this.stroke = null; - this.strokeWidth = 1; -} + var retry = retryDehydratedSuspenseBoundary.bind(null, current); + registerSuspenseInstanceRetry(suspenseInstance, retry); + return null; + } else { + // This is the first attempt. + reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext); + var nextProps = workInProgress.pendingProps; + var primaryChildren = nextProps.children; + var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. -/** - * @param {number} x - * @param {number} y - */ -Path.prototype.moveTo = function(x, y) { - this.commands.push({ - type: 'M', - x: x, - y: y - }); -}; + primaryChildFragment.flags |= Hydrating; + return primaryChildFragment; + } + } -/** - * @param {number} x - * @param {number} y - */ -Path.prototype.lineTo = function(x, y) { - this.commands.push({ - type: 'L', - x: x, - y: y - }); -}; + function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) { + fiber.lanes = mergeLanes(fiber.lanes, renderLanes); + var alternate = fiber.alternate; -/** - * Draws cubic curve - * @function - * curveTo - * @memberof opentype.Path.prototype - * @param {number} x1 - x of control 1 - * @param {number} y1 - y of control 1 - * @param {number} x2 - x of control 2 - * @param {number} y2 - y of control 2 - * @param {number} x - x of path point - * @param {number} y - y of path point - */ + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, renderLanes); + } -/** - * Draws cubic curve - * @function - * bezierCurveTo - * @memberof opentype.Path.prototype - * @param {number} x1 - x of control 1 - * @param {number} y1 - y of control 1 - * @param {number} x2 - x of control 2 - * @param {number} y2 - y of control 2 - * @param {number} x - x of path point - * @param {number} y - y of path point - * @see curveTo - */ -Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) { - this.commands.push({ - type: 'C', - x1: x1, - y1: y1, - x2: x2, - y2: y2, - x: x, - y: y - }); -}; + scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot); + } -/** - * Draws quadratic curve - * @function - * quadraticCurveTo - * @memberof opentype.Path.prototype - * @param {number} x1 - x of control - * @param {number} y1 - y of control - * @param {number} x - x of path point - * @param {number} y - y of path point - */ + function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) { + // Mark any Suspense boundaries with fallbacks as having work to do. + // If they were previously forced into fallbacks, they may now be able + // to unblock. + var node = firstChild; -/** - * Draws quadratic curve - * @function - * quadTo - * @memberof opentype.Path.prototype - * @param {number} x1 - x of control - * @param {number} y1 - y of control - * @param {number} x - x of path point - * @param {number} y - y of path point - */ -Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) { - this.commands.push({ - type: 'Q', - x1: x1, - y1: y1, - x: x, - y: y - }); -}; + while (node !== null) { + if (node.tag === SuspenseComponent) { + var state = node.memoizedState; -/** - * Closes the path - * @function closePath - * @memberof opentype.Path.prototype - */ + if (state !== null) { + scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); + } + } else if (node.tag === SuspenseListComponent) { + // If the tail is hidden there might not be an Suspense boundaries + // to schedule work on. In this case we have to schedule it on the + // list itself. + // We don't have to traverse to the children of the list since + // the list will propagate the change when it rerenders. + scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } -/** - * Close the path - * @function close - * @memberof opentype.Path.prototype - */ -Path.prototype.close = Path.prototype.closePath = function() { - this.commands.push({ - type: 'Z' - }); -}; + if (node === workInProgress) { + return; + } -/** - * Add the given path or list of commands to the commands of this path. - * @param {Array} pathOrCommands - another opentype.Path, an opentype.BoundingBox, or an array of commands. - */ -Path.prototype.extend = function(pathOrCommands) { - if (pathOrCommands.commands) { - pathOrCommands = pathOrCommands.commands; - } else if (pathOrCommands instanceof BoundingBox) { - var box = pathOrCommands; - this.moveTo(box.x1, box.y1); - this.lineTo(box.x2, box.y1); - this.lineTo(box.x2, box.y2); - this.lineTo(box.x1, box.y2); - this.close(); - return; - } + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress) { + return; + } - Array.prototype.push.apply(this.commands, pathOrCommands); -}; + node = node.return; + } -/** - * Calculate the bounding box of the path. - * @returns {opentype.BoundingBox} - */ -Path.prototype.getBoundingBox = function() { - var box = new BoundingBox(); - - var startX = 0; - var startY = 0; - var prevX = 0; - var prevY = 0; - for (var i = 0; i < this.commands.length; i++) { - var cmd = this.commands[i]; - switch (cmd.type) { - case 'M': - box.addPoint(cmd.x, cmd.y); - startX = prevX = cmd.x; - startY = prevY = cmd.y; - break; - case 'L': - box.addPoint(cmd.x, cmd.y); - prevX = cmd.x; - prevY = cmd.y; - break; - case 'Q': - box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y); - prevX = cmd.x; - prevY = cmd.y; - break; - case 'C': - box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); - prevX = cmd.x; - prevY = cmd.y; - break; - case 'Z': - prevX = startX; - prevY = startY; - break; - default: - throw new Error('Unexpected path command ' + cmd.type); - } - } - if (box.isEmpty()) { - box.addPoint(0, 0); - } - return box; -}; + node.sibling.return = node.return; + node = node.sibling; + } + } -/** - * Draw the path to a 2D context. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context. - */ -Path.prototype.draw = function(ctx) { - ctx.beginPath(); - for (var i = 0; i < this.commands.length; i += 1) { - var cmd = this.commands[i]; - if (cmd.type === 'M') { - ctx.moveTo(cmd.x, cmd.y); - } else if (cmd.type === 'L') { - ctx.lineTo(cmd.x, cmd.y); - } else if (cmd.type === 'C') { - ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); - } else if (cmd.type === 'Q') { - ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); - } else if (cmd.type === 'Z') { - ctx.closePath(); - } - } + function findLastContentRow(firstChild) { + // This is going to find the last row among these children that is already + // showing content on the screen, as opposed to being in fallback state or + // new. If a row has multiple Suspense boundaries, any of them being in the + // fallback state, counts as the whole row being in a fallback state. + // Note that the "rows" will be workInProgress, but any nested children + // will still be current since we haven't rendered them yet. The mounted + // order may not be the same as the new order. We use the new order. + var row = firstChild; + var lastContentRow = null; - if (this.fill) { - ctx.fillStyle = this.fill; - ctx.fill(); - } + while (row !== null) { + var currentRow = row.alternate; // New rows can't be content rows. - if (this.stroke) { - ctx.strokeStyle = this.stroke; - ctx.lineWidth = this.strokeWidth; - ctx.stroke(); - } -}; + if (currentRow !== null && findFirstSuspended(currentRow) === null) { + lastContentRow = row; + } -/** - * Convert the Path to a string of path data instructions - * See http://www.w3.org/TR/SVG/paths.html#PathData - * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values - * @return {string} - */ -Path.prototype.toPathData = function(decimalPlaces) { - decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; + row = row.sibling; + } - function floatToString(v) { - if (Math.round(v) === v) { - return '' + Math.round(v); - } else { - return v.toFixed(decimalPlaces); - } - } + return lastContentRow; + } - function packValues() { - var arguments$1 = arguments; + function validateRevealOrder(revealOrder) { + { + if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) { + didWarnAboutRevealOrder[revealOrder] = true; - var s = ''; - for (var i = 0; i < arguments.length; i += 1) { - var v = arguments$1[i]; - if (v >= 0 && i > 0) { - s += ' '; - } + if (typeof revealOrder === 'string') { + switch (revealOrder.toLowerCase()) { + case 'together': + case 'forwards': + case 'backwards': + { + error('"%s" is not a valid value for revealOrder on . ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase()); - s += floatToString(v); - } + break; + } - return s; - } + case 'forward': + case 'backward': + { + error('"%s" is not a valid value for revealOrder on . ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase()); - var d = ''; - for (var i = 0; i < this.commands.length; i += 1) { - var cmd = this.commands[i]; - if (cmd.type === 'M') { - d += 'M' + packValues(cmd.x, cmd.y); - } else if (cmd.type === 'L') { - d += 'L' + packValues(cmd.x, cmd.y); - } else if (cmd.type === 'C') { - d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); - } else if (cmd.type === 'Q') { - d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); - } else if (cmd.type === 'Z') { - d += 'Z'; - } - } + break; + } - return d; -}; + default: + error('"%s" is not a supported revealOrder on . ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); -/** - * Convert the path to an SVG element, as a string. - * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values - * @return {string} - */ -Path.prototype.toSVG = function(decimalPlaces) { - var svg = '. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); + } + } + } + } - if (this.stroke) { - svg += ' stroke="' + this.stroke + '" stroke-width="' + this.strokeWidth + '"'; - } + function validateTailOptions(tailMode, revealOrder) { + { + if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) { + if (tailMode !== 'collapsed' && tailMode !== 'hidden') { + didWarnAboutTailOptions[tailMode] = true; - svg += '/>'; - return svg; -}; + error('"%s" is not a supported value for tail on . ' + 'Did you mean "collapsed" or "hidden"?', tailMode); + } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') { + didWarnAboutTailOptions[tailMode] = true; -/** - * Convert the path to a DOM element. - * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values - * @return {SVGPathElement} - */ -Path.prototype.toDOMElement = function(decimalPlaces) { - var temporaryPath = this.toPathData(decimalPlaces); - var newPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + error(' is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode); + } + } + } + } - newPath.setAttribute('d', temporaryPath); + function validateSuspenseListNestedChild(childSlot, index) { + { + var isAnArray = isArray(childSlot); + var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function'; - return newPath; -}; + if (isAnArray || isIterable) { + var type = isAnArray ? 'array' : 'iterable'; -// Run-time checking of preconditions. + error('A nested %s was passed to row #%s in . Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + ' ... ' + '{%s} ... ' + '', type, index, type); -function fail(message) { - throw new Error(message); -} + return false; + } + } -// Precondition function that checks if the given predicate is true. -// If not, it will throw an error. -function argument(predicate, message) { - if (!predicate) { - fail(message); - } -} -var check = { fail: fail, argument: argument, assert: argument }; + return true; + } -// Data types used in the OpenType font file. + function validateSuspenseListChildren(children, revealOrder) { + { + if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) { + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + if (!validateSuspenseListNestedChild(children[i], i)) { + return; + } + } + } else { + var iteratorFn = getIteratorFn(children); -var LIMIT16 = 32768; // The limit at which a 16-bit number switches signs == 2^15 -var LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31 + if (typeof iteratorFn === 'function') { + var childrenIterator = iteratorFn.call(children); -/** - * @exports opentype.decode - * @class - */ -var decode = {}; -/** - * @exports opentype.encode - * @class - */ -var encode = {}; -/** - * @exports opentype.sizeOf - * @class - */ -var sizeOf = {}; + if (childrenIterator) { + var step = childrenIterator.next(); + var _i = 0; -// Return a function that always returns the same value. -function constant(v) { - return function() { - return v; - }; -} + for (; !step.done; step = childrenIterator.next()) { + if (!validateSuspenseListNestedChild(step.value, _i)) { + return; + } -// OpenType data types ////////////////////////////////////////////////////// + _i++; + } + } + } else { + error('A single row was passed to a . ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder); + } + } + } + } + } -/** - * Convert an 8-bit unsigned integer to a list of 1 byte. - * @param {number} - * @returns {Array} - */ -encode.BYTE = function(v) { - check.argument(v >= 0 && v <= 255, 'Byte value should be between 0 and 255.'); - return [v]; -}; -/** - * @constant - * @type {number} - */ -sizeOf.BYTE = constant(1); + function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) { + var renderState = workInProgress.memoizedState; -/** - * Convert a 8-bit signed integer to a list of 1 byte. - * @param {string} - * @returns {Array} - */ -encode.CHAR = function(v) { - return [v.charCodeAt(0)]; -}; + if (renderState === null) { + workInProgress.memoizedState = { + isBackwards: isBackwards, + rendering: null, + renderingStartTime: 0, + last: lastContentRow, + tail: tail, + tailMode: tailMode + }; + } else { + // We can reuse the existing object from previous renders. + renderState.isBackwards = isBackwards; + renderState.rendering = null; + renderState.renderingStartTime = 0; + renderState.last = lastContentRow; + renderState.tail = tail; + renderState.tailMode = tailMode; + } + } // This can end up rendering this component multiple passes. + // The first pass splits the children fibers into two sets. A head and tail. + // We first render the head. If anything is in fallback state, we do another + // pass through beginWork to rerender all children (including the tail) with + // the force suspend context. If the first render didn't have anything in + // in fallback state. Then we render each row in the tail one-by-one. + // That happens in the completeWork phase without going back to beginWork. -/** - * @constant - * @type {number} - */ -sizeOf.CHAR = constant(1); -/** - * Convert an ASCII string to a list of bytes. - * @param {string} - * @returns {Array} - */ -encode.CHARARRAY = function(v) { - if (typeof v === 'undefined') { - v = ''; - console.warn('Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name.'); - } - var b = []; - for (var i = 0; i < v.length; i += 1) { - b[i] = v.charCodeAt(i); - } + function updateSuspenseListComponent(current, workInProgress, renderLanes) { + var nextProps = workInProgress.pendingProps; + var revealOrder = nextProps.revealOrder; + var tailMode = nextProps.tail; + var newChildren = nextProps.children; + validateRevealOrder(revealOrder); + validateTailOptions(tailMode, revealOrder); + validateSuspenseListChildren(newChildren, revealOrder); + reconcileChildren(current, workInProgress, newChildren, renderLanes); + var suspenseContext = suspenseStackCursor.current; + var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback); - return b; -}; + if (shouldForceFallback) { + suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); + workInProgress.flags |= DidCapture; + } else { + var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags; -/** - * @param {Array} - * @returns {number} - */ -sizeOf.CHARARRAY = function(v) { - if (typeof v === 'undefined') { - return 0; - } - return v.length; -}; + if (didSuspendBefore) { + // If we previously forced a fallback, we need to schedule work + // on any nested boundaries to let them know to try to render + // again. This is the same as context updating. + propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes); + } -/** - * Convert a 16-bit unsigned integer to a list of 2 bytes. - * @param {number} - * @returns {Array} - */ -encode.USHORT = function(v) { - return [(v >> 8) & 0xFF, v & 0xFF]; -}; + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + } -/** - * @constant - * @type {number} - */ -sizeOf.USHORT = constant(2); + pushSuspenseContext(workInProgress, suspenseContext); -/** - * Convert a 16-bit signed integer to a list of 2 bytes. - * @param {number} - * @returns {Array} - */ -encode.SHORT = function(v) { - // Two's complement - if (v >= LIMIT16) { - v = -(2 * LIMIT16 - v); - } + if ((workInProgress.mode & ConcurrentMode) === NoMode) { + // In legacy mode, SuspenseList doesn't work so we just + // use make it a noop by treating it as the default revealOrder. + workInProgress.memoizedState = null; + } else { + switch (revealOrder) { + case 'forwards': + { + var lastContentRow = findLastContentRow(workInProgress.child); + var tail; - return [(v >> 8) & 0xFF, v & 0xFF]; -}; + if (lastContentRow === null) { + // The whole list is part of the tail. + // TODO: We could fast path by just rendering the tail now. + tail = workInProgress.child; + workInProgress.child = null; + } else { + // Disconnect the tail rows after the content row. + // We're going to render them separately later. + tail = lastContentRow.sibling; + lastContentRow.sibling = null; + } -/** - * @constant - * @type {number} - */ -sizeOf.SHORT = constant(2); + initSuspenseListRenderState(workInProgress, false, // isBackwards + tail, lastContentRow, tailMode); + break; + } -/** - * Convert a 24-bit unsigned integer to a list of 3 bytes. - * @param {number} - * @returns {Array} - */ -encode.UINT24 = function(v) { - return [(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + case 'backwards': + { + // We're going to find the first row that has existing content. + // At the same time we're going to reverse the list of everything + // we pass in the meantime. That's going to be our tail in reverse + // order. + var _tail = null; + var row = workInProgress.child; + workInProgress.child = null; -/** - * @constant - * @type {number} - */ -sizeOf.UINT24 = constant(3); + while (row !== null) { + var currentRow = row.alternate; // New rows can't be content rows. -/** - * Convert a 32-bit unsigned integer to a list of 4 bytes. - * @param {number} - * @returns {Array} - */ -encode.ULONG = function(v) { - return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + if (currentRow !== null && findFirstSuspended(currentRow) === null) { + // This is the beginning of the main content. + workInProgress.child = row; + break; + } -/** - * @constant - * @type {number} - */ -sizeOf.ULONG = constant(4); + var nextRow = row.sibling; + row.sibling = _tail; + _tail = row; + row = nextRow; + } // TODO: If workInProgress.child is null, we can continue on the tail immediately. -/** - * Convert a 32-bit unsigned integer to a list of 4 bytes. - * @param {number} - * @returns {Array} - */ -encode.LONG = function(v) { - // Two's complement - if (v >= LIMIT32) { - v = -(2 * LIMIT32 - v); - } - return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + initSuspenseListRenderState(workInProgress, true, // isBackwards + _tail, null, // last + tailMode); + break; + } -/** - * @constant - * @type {number} - */ -sizeOf.LONG = constant(4); + case 'together': + { + initSuspenseListRenderState(workInProgress, false, // isBackwards + null, // tail + null, // last + undefined); + break; + } -encode.FIXED = encode.ULONG; -sizeOf.FIXED = sizeOf.ULONG; + default: + { + // The default reveal order is the same as not having + // a boundary. + workInProgress.memoizedState = null; + } + } + } -encode.FWORD = encode.SHORT; -sizeOf.FWORD = sizeOf.SHORT; + return workInProgress.child; + } -encode.UFWORD = encode.USHORT; -sizeOf.UFWORD = sizeOf.USHORT; + function updatePortalComponent(current, workInProgress, renderLanes) { + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + var nextChildren = workInProgress.pendingProps; -/** - * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp. - * @param {number} - * @returns {Array} - */ -encode.LONGDATETIME = function(v) { - return [0, 0, 0, 0, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + if (current === null) { + // Portals are special because we don't append the children during mount + // but at commit. Therefore we need to track insertions which the normal + // flow doesn't do during mount. This doesn't happen at the root because + // the root always starts with a "current" with a null child. + // TODO: Consider unifying this with how the root works. + workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); + } else { + reconcileChildren(current, workInProgress, nextChildren, renderLanes); + } -/** - * @constant - * @type {number} - */ -sizeOf.LONGDATETIME = constant(8); + return workInProgress.child; + } -/** - * Convert a 4-char tag to a list of 4 bytes. - * @param {string} - * @returns {Array} - */ -encode.TAG = function(v) { - check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.'); - return [v.charCodeAt(0), - v.charCodeAt(1), - v.charCodeAt(2), - v.charCodeAt(3)]; -}; + var hasWarnedAboutUsingNoValuePropOnContextProvider = false; -/** - * @constant - * @type {number} - */ -sizeOf.TAG = constant(4); + function updateContextProvider(current, workInProgress, renderLanes) { + var providerType = workInProgress.type; + var context = providerType._context; + var newProps = workInProgress.pendingProps; + var oldProps = workInProgress.memoizedProps; + var newValue = newProps.value; -// CFF data types /////////////////////////////////////////////////////////// + { + if (!('value' in newProps)) { + if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { + hasWarnedAboutUsingNoValuePropOnContextProvider = true; -encode.Card8 = encode.BYTE; -sizeOf.Card8 = sizeOf.BYTE; + error('The `value` prop is required for the ``. Did you misspell it or forget to pass it?'); + } + } -encode.Card16 = encode.USHORT; -sizeOf.Card16 = sizeOf.USHORT; + var providerPropTypes = workInProgress.type.propTypes; -encode.OffSize = encode.BYTE; -sizeOf.OffSize = sizeOf.BYTE; + if (providerPropTypes) { + checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider'); + } + } -encode.SID = encode.USHORT; -sizeOf.SID = sizeOf.USHORT; + pushProvider(workInProgress, context, newValue); -// Convert a numeric operand or charstring number to a variable-size list of bytes. -/** - * Convert a numeric operand or charstring number to a variable-size list of bytes. - * @param {number} - * @returns {Array} - */ -encode.NUMBER = function(v) { - if (v >= -107 && v <= 107) { - return [v + 139]; - } else if (v >= 108 && v <= 1131) { - v = v - 108; - return [(v >> 8) + 247, v & 0xFF]; - } else if (v >= -1131 && v <= -108) { - v = -v - 108; - return [(v >> 8) + 251, v & 0xFF]; - } else if (v >= -32768 && v <= 32767) { - return encode.NUMBER16(v); - } else { - return encode.NUMBER32(v); - } -}; + { + if (oldProps !== null) { + var oldValue = oldProps.value; -/** - * @param {number} - * @returns {number} - */ -sizeOf.NUMBER = function(v) { - return encode.NUMBER(v).length; -}; + if (objectIs(oldValue, newValue)) { + // No change. Bailout early if children are the same. + if (oldProps.children === newProps.children && !hasContextChanged()) { + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } + } else { + // The context value changed. Search for matching consumers and schedule + // them to update. + propagateContextChange(workInProgress, context, renderLanes); + } + } + } -/** - * Convert a signed number between -32768 and +32767 to a three-byte value. - * This ensures we always use three bytes, but is not the most compact format. - * @param {number} - * @returns {Array} - */ -encode.NUMBER16 = function(v) { - return [28, (v >> 8) & 0xFF, v & 0xFF]; -}; + var newChildren = newProps.children; + reconcileChildren(current, workInProgress, newChildren, renderLanes); + return workInProgress.child; + } -/** - * @constant - * @type {number} - */ -sizeOf.NUMBER16 = constant(3); + var hasWarnedAboutUsingContextAsConsumer = false; -/** - * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value. - * This is useful if you want to be sure you always use four bytes, - * at the expense of wasting a few bytes for smaller numbers. - * @param {number} - * @returns {Array} - */ -encode.NUMBER32 = function(v) { - return [29, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; -}; + function updateContextConsumer(current, workInProgress, renderLanes) { + var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In + // DEV mode, we create a separate object for Context.Consumer that acts + // like a proxy to Context. This proxy object adds unnecessary code in PROD + // so we use the old behaviour (Context.Consumer references Context) to + // reduce size and overhead. The separate object references context via + // a property called "_context", which also gives us the ability to check + // in DEV mode if this property exists or not and warn if it does not. -/** - * @constant - * @type {number} - */ -sizeOf.NUMBER32 = constant(5); + { + if (context._context === undefined) { + // This may be because it's a Context (rather than a Consumer). + // Or it may be because it's older React where they're the same thing. + // We only want to warn if we're sure it's a new React. + if (context !== context.Consumer) { + if (!hasWarnedAboutUsingContextAsConsumer) { + hasWarnedAboutUsingContextAsConsumer = true; -/** - * @param {number} - * @returns {Array} - */ -encode.REAL = function(v) { - var value = v.toString(); - - // Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7) - // This code converts it back to a number without the epsilon. - var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); - if (m) { - var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length)); - value = (Math.round(v * epsilon) / epsilon).toString(); - } + error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + } + } else { + context = context._context; + } + } - var nibbles = ''; - for (var i = 0, ii = value.length; i < ii; i += 1) { - var c = value[i]; - if (c === 'e') { - nibbles += value[++i] === '-' ? 'c' : 'b'; - } else if (c === '.') { - nibbles += 'a'; - } else if (c === '-') { - nibbles += 'e'; - } else { - nibbles += c; - } - } + var newProps = workInProgress.pendingProps; + var render = newProps.children; - nibbles += (nibbles.length & 1) ? 'f' : 'ff'; - var out = [30]; - for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) { - out.push(parseInt(nibbles.substr(i$1, 2), 16)); - } + { + if (typeof render !== 'function') { + error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); + } + } - return out; -}; + prepareToReadContext(workInProgress, renderLanes); + var newValue = readContext(context); -/** - * @param {number} - * @returns {number} - */ -sizeOf.REAL = function(v) { - return encode.REAL(v).length; -}; + { + markComponentRenderStarted(workInProgress); + } -encode.NAME = encode.CHARARRAY; -sizeOf.NAME = sizeOf.CHARARRAY; + var newChildren; -encode.STRING = encode.CHARARRAY; -sizeOf.STRING = sizeOf.CHARARRAY; + { + ReactCurrentOwner$1.current = workInProgress; + setIsRendering(true); + newChildren = render(newValue); + setIsRendering(false); + } -/** - * @param {DataView} data - * @param {number} offset - * @param {number} numBytes - * @returns {string} - */ -decode.UTF8 = function(data, offset, numBytes) { - var codePoints = []; - var numChars = numBytes; - for (var j = 0; j < numChars; j++, offset += 1) { - codePoints[j] = data.getUint8(offset); - } + { + markComponentRenderStopped(); + } // React DevTools reads this flag. - return String.fromCharCode.apply(null, codePoints); -}; -/** - * @param {DataView} data - * @param {number} offset - * @param {number} numBytes - * @returns {string} - */ -decode.UTF16 = function(data, offset, numBytes) { - var codePoints = []; - var numChars = numBytes / 2; - for (var j = 0; j < numChars; j++, offset += 2) { - codePoints[j] = data.getUint16(offset); - } + workInProgress.flags |= PerformedWork; + reconcileChildren(current, workInProgress, newChildren, renderLanes); + return workInProgress.child; + } - return String.fromCharCode.apply(null, codePoints); -}; + function markWorkInProgressReceivedUpdate() { + didReceiveUpdate = true; + } -/** - * Convert a JavaScript string to UTF16-BE. - * @param {string} - * @returns {Array} - */ -encode.UTF16 = function(v) { - var b = []; - for (var i = 0; i < v.length; i += 1) { - var codepoint = v.charCodeAt(i); - b[b.length] = (codepoint >> 8) & 0xFF; - b[b.length] = codepoint & 0xFF; - } + function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) { + if (current !== null) { + // Reuse previous dependencies + workInProgress.dependencies = current.dependencies; + } - return b; -}; + { + // Don't update "base" render times for bailouts. + stopProfilerTimerIfRunning(); + } -/** - * @param {string} - * @returns {number} - */ -sizeOf.UTF16 = function(v) { - return v.length * 2; -}; + markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work. -// Data for converting old eight-bit Macintosh encodings to Unicode. -// This representation is optimized for decoding; encoding is slower -// and needs more memory. The assumption is that all opentype.js users -// want to open fonts, but saving a font will be comparatively rare -// so it can be more expensive. Keyed by IANA character set name. -// -// Python script for generating these strings: -// -// s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)]) -// print(s.encode('utf-8')) -/** - * @private - */ -var eightBitMacEncodings = { - 'x-mac-croatian': // Python: 'mac_croatian' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' + - '¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ', - 'x-mac-cyrillic': // Python: 'mac_cyrillic' - 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' + - 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю', - 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' + - 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ', - 'x-mac-greek': // Python: 'mac_greek' - 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' + - 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD', - 'x-mac-icelandic': // Python: 'mac_iceland' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + - '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', - 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT - 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' + - 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł', - 'x-mac-ce': // Python: 'mac_latin2' - 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' + - 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ', - macintosh: // Python: 'mac_roman' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + - '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', - 'x-mac-romanian': // Python: 'mac_romanian' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' + - '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', - 'x-mac-turkish': // Python: 'mac_turkish' - 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + - '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ' -}; + if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { + // The children don't have any work either. We can skip them. + // TODO: Once we add back resuming, we should check if the children are + // a work-in-progress set. If so, we need to transfer their effects. + { + return null; + } + } // This fiber doesn't have work, but its subtree does. Clone the child + // fibers and continue. -/** - * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript - * string, or 'undefined' if the encoding is unsupported. For example, we do - * not support Chinese, Japanese or Korean because these would need large - * mapping tables. - * @param {DataView} dataView - * @param {number} offset - * @param {number} dataLength - * @param {string} encoding - * @returns {string} - */ -decode.MACSTRING = function(dataView, offset, dataLength, encoding) { - var table = eightBitMacEncodings[encoding]; - if (table === undefined) { - return undefined; - } - var result = ''; - for (var i = 0; i < dataLength; i++) { - var c = dataView.getUint8(offset + i); - // In all eight-bit Mac encodings, the characters 0x00..0x7F are - // mapped to U+0000..U+007F; we only need to look up the others. - if (c <= 0x7F) { - result += String.fromCharCode(c); - } else { - result += table[c & 0x7F]; - } - } + cloneChildFibers(current, workInProgress); + return workInProgress.child; + } - return result; -}; + function remountFiber(current, oldWorkInProgress, newWorkInProgress) { + { + var returnFiber = oldWorkInProgress.return; -// Helper function for encode.MACSTRING. Returns a dictionary for mapping -// Unicode character codes to their 8-bit MacOS equivalent. This table -// is not exactly a super cheap data structure, but we do not care because -// encoding Macintosh strings is only rarely needed in typical applications. -var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap(); -var macEncodingCacheKeys; -var getMacEncodingTable = function (encoding) { - // Since we use encoding as a cache key for WeakMap, it has to be - // a String object and not a literal. And at least on NodeJS 2.10.1, - // WeakMap requires that the same String instance is passed for cache hits. - if (!macEncodingCacheKeys) { - macEncodingCacheKeys = {}; - for (var e in eightBitMacEncodings) { - /*jshint -W053 */ // Suppress "Do not use String as a constructor." - macEncodingCacheKeys[e] = new String(e); - } - } + if (returnFiber === null) { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('Cannot swap the root fiber.'); + } // Disconnect from the old current. + // It will get deleted. - var cacheKey = macEncodingCacheKeys[encoding]; - if (cacheKey === undefined) { - return undefined; - } - // We can't do "if (cache.has(key)) {return cache.get(key)}" here: - // since garbage collection may run at any time, it could also kick in - // between the calls to cache.has() and cache.get(). In that case, - // we would return 'undefined' even though we do support the encoding. - if (macEncodingTableCache) { - var cachedTable = macEncodingTableCache.get(cacheKey); - if (cachedTable !== undefined) { - return cachedTable; - } - } + current.alternate = null; + oldWorkInProgress.alternate = null; // Connect to the new tree. - var decodingTable = eightBitMacEncodings[encoding]; - if (decodingTable === undefined) { - return undefined; - } + newWorkInProgress.index = oldWorkInProgress.index; + newWorkInProgress.sibling = oldWorkInProgress.sibling; + newWorkInProgress.return = oldWorkInProgress.return; + newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. - var encodingTable = {}; - for (var i = 0; i < decodingTable.length; i++) { - encodingTable[decodingTable.charCodeAt(i)] = i + 0x80; - } + if (oldWorkInProgress === returnFiber.child) { + returnFiber.child = newWorkInProgress; + } else { + var prevSibling = returnFiber.child; - if (macEncodingTableCache) { - macEncodingTableCache.set(cacheKey, encodingTable); - } + if (prevSibling === null) { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('Expected parent to have a child.'); + } - return encodingTable; -}; + while (prevSibling.sibling !== oldWorkInProgress) { + prevSibling = prevSibling.sibling; -/** - * Encodes an old-style Macintosh string. Returns a byte array upon success. - * If the requested encoding is unsupported, or if the input string contains - * a character that cannot be expressed in the encoding, the function returns - * 'undefined'. - * @param {string} str - * @param {string} encoding - * @returns {Array} - */ -encode.MACSTRING = function(str, encoding) { - var table = getMacEncodingTable(encoding); - if (table === undefined) { - return undefined; - } + if (prevSibling === null) { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('Expected to find the previous sibling.'); + } + } - var result = []; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - - // In all eight-bit Mac encodings, the characters 0x00..0x7F are - // mapped to U+0000..U+007F; we only need to look up the others. - if (c >= 0x80) { - c = table[c]; - if (c === undefined) { - // str contains a Unicode character that cannot be encoded - // in the requested encoding. - return undefined; - } - } - result[i] = c; - // result.push(c); - } + prevSibling.sibling = newWorkInProgress; + } // Delete the old fiber and place the new one. + // Since the old fiber is disconnected, we have to schedule it manually. - return result; -}; -/** - * @param {string} str - * @param {string} encoding - * @returns {number} - */ -sizeOf.MACSTRING = function(str, encoding) { - var b = encode.MACSTRING(str, encoding); - if (b !== undefined) { - return b.length; - } else { - return 0; - } -}; + var deletions = returnFiber.deletions; -// Helper for encode.VARDELTAS -function isByteEncodable(value) { - return value >= -128 && value <= 127; -} + if (deletions === null) { + returnFiber.deletions = [current]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(current); + } -// Helper for encode.VARDELTAS -function encodeVarDeltaRunAsZeroes(deltas, pos, result) { - var runLength = 0; - var numDeltas = deltas.length; - while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) { - ++pos; - ++runLength; - } - result.push(0x80 | (runLength - 1)); - return pos; -} - -// Helper for encode.VARDELTAS -function encodeVarDeltaRunAsBytes(deltas, offset, result) { - var runLength = 0; - var numDeltas = deltas.length; - var pos = offset; - while (pos < numDeltas && runLength < 64) { - var value = deltas[pos]; - if (!isByteEncodable(value)) { - break; - } + newWorkInProgress.flags |= Placement; // Restart work from the new fiber. - // Within a byte-encoded run of deltas, a single zero is best - // stored literally as 0x00 value. However, if we have two or - // more zeroes in a sequence, it is better to start a new run. - // Fore example, the sequence of deltas [15, 15, 0, 15, 15] - // becomes 6 bytes (04 0F 0F 00 0F 0F) when storing the zero - // within the current run, but 7 bytes (01 0F 0F 80 01 0F 0F) - // when starting a new run. - if (value === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) { - break; - } + return newWorkInProgress; + } + } - ++pos; - ++runLength; - } - result.push(runLength - 1); - for (var i = offset; i < pos; ++i) { - result.push((deltas[i] + 256) & 0xff); - } - return pos; -} - -// Helper for encode.VARDELTAS -function encodeVarDeltaRunAsWords(deltas, offset, result) { - var runLength = 0; - var numDeltas = deltas.length; - var pos = offset; - while (pos < numDeltas && runLength < 64) { - var value = deltas[pos]; - - // Within a word-encoded run of deltas, it is easiest to start - // a new run (with a different encoding) whenever we encounter - // a zero value. For example, the sequence [0x6666, 0, 0x7777] - // needs 7 bytes when storing the zero inside the current run - // (42 66 66 00 00 77 77), and equally 7 bytes when starting a - // new run (40 66 66 80 40 77 77). - if (value === 0) { - break; - } + function checkScheduledUpdateOrContext(current, renderLanes) { + // Before performing an early bailout, we must check if there are pending + // updates or context. + var updateLanes = current.lanes; - // Within a word-encoded run of deltas, a single value in the - // range (-128..127) should be encoded within the current run - // because it is more compact. For example, the sequence - // [0x6666, 2, 0x7777] becomes 7 bytes when storing the value - // literally (42 66 66 00 02 77 77), but 8 bytes when starting - // a new run (40 66 66 00 02 40 77 77). - if (isByteEncodable(value) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) { - break; - } + if (includesSomeLane(updateLanes, renderLanes)) { + return true; + } // No pending update, but because context is propagated lazily, we need - ++pos; - ++runLength; - } - result.push(0x40 | (runLength - 1)); - for (var i = offset; i < pos; ++i) { - var val = deltas[i]; - result.push(((val + 0x10000) >> 8) & 0xff, (val + 0x100) & 0xff); - } - return pos; -} + return false; + } -/** - * Encode a list of variation adjustment deltas. - * - * Variation adjustment deltas are used in ‘gvar’ and ‘cvar’ tables. - * They indicate how points (in ‘gvar’) or values (in ‘cvar’) get adjusted - * when generating instances of variation fonts. - * - * @see https://www.microsoft.com/typography/otspec/gvar.htm - * @see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html - * @param {Array} - * @return {Array} - */ -encode.VARDELTAS = function(deltas) { - var pos = 0; - var result = []; - while (pos < deltas.length) { - var value = deltas[pos]; - if (value === 0) { - pos = encodeVarDeltaRunAsZeroes(deltas, pos, result); - } else if (value >= -128 && value <= 127) { - pos = encodeVarDeltaRunAsBytes(deltas, pos, result); - } else { - pos = encodeVarDeltaRunAsWords(deltas, pos, result); - } - } - return result; -}; + function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) { + // This fiber does not have any pending work. Bailout without entering + // the begin phase. There's still some bookkeeping we that needs to be done + // in this optimized path, mostly pushing stuff onto the stack. + switch (workInProgress.tag) { + case HostRoot: + pushHostRootContext(workInProgress); + workInProgress.stateNode; -// Convert a list of values to a CFF INDEX structure. -// The values should be objects containing name / type / value. -/** - * @param {Array} l - * @returns {Array} - */ -encode.INDEX = function(l) { - //var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data, - // i, v; - // Because we have to know which data type to use to encode the offsets, - // we have to go through the values twice: once to encode the data and - // calculate the offsets, then again to encode the offsets using the fitting data type. - var offset = 1; // First offset is always 1. - var offsets = [offset]; - var data = []; - for (var i = 0; i < l.length; i += 1) { - var v = encode.OBJECT(l[i]); - Array.prototype.push.apply(data, v); - offset += v.length; - offsets.push(offset); - } + resetHydrationState(); + break; - if (data.length === 0) { - return [0, 0]; - } + case HostComponent: + pushHostContext(workInProgress); + break; - var encodedOffsets = []; - var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0; - var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize]; - for (var i$1 = 0; i$1 < offsets.length; i$1 += 1) { - var encodedOffset = offsetEncoder(offsets[i$1]); - Array.prototype.push.apply(encodedOffsets, encodedOffset); - } + case ClassComponent: + { + var Component = workInProgress.type; - return Array.prototype.concat(encode.Card16(l.length), - encode.OffSize(offSize), - encodedOffsets, - data); -}; + if (isContextProvider(Component)) { + pushContextProvider(workInProgress); + } -/** - * @param {Array} - * @returns {number} - */ -sizeOf.INDEX = function(v) { - return encode.INDEX(v).length; -}; + break; + } -/** - * Convert an object to a CFF DICT structure. - * The keys should be numeric. - * The values should be objects containing name / type / value. - * @param {Object} m - * @returns {Array} - */ -encode.DICT = function(m) { - var d = []; - var keys = Object.keys(m); - var length = keys.length; - - for (var i = 0; i < length; i += 1) { - // Object.keys() return string keys, but our keys are always numeric. - var k = parseInt(keys[i], 0); - var v = m[k]; - // Value comes before the key. - d = d.concat(encode.OPERAND(v.value, v.type)); - d = d.concat(encode.OPERATOR(k)); - } + case HostPortal: + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + break; - return d; -}; + case ContextProvider: + { + var newValue = workInProgress.memoizedProps.value; + var context = workInProgress.type._context; + pushProvider(workInProgress, context, newValue); + break; + } -/** - * @param {Object} - * @returns {number} - */ -sizeOf.DICT = function(m) { - return encode.DICT(m).length; -}; + case Profiler: + { + // Profiler should only call onRender when one of its descendants actually rendered. + var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); -/** - * @param {number} - * @returns {Array} - */ -encode.OPERATOR = function(v) { - if (v < 1200) { - return [v]; - } else { - return [12, v - 1200]; - } -}; + if (hasChildWork) { + workInProgress.flags |= Update; + } -/** - * @param {Array} v - * @param {string} - * @returns {Array} - */ -encode.OPERAND = function(v, type) { - var d = []; - if (Array.isArray(type)) { - for (var i = 0; i < type.length; i += 1) { - check.argument(v.length === type.length, 'Not enough arguments given for type' + type); - d = d.concat(encode.OPERAND(v[i], type[i])); - } - } else { - if (type === 'SID') { - d = d.concat(encode.NUMBER(v)); - } else if (type === 'offset') { - // We make it easy for ourselves and always encode offsets as - // 4 bytes. This makes offset calculation for the top dict easier. - d = d.concat(encode.NUMBER32(v)); - } else if (type === 'number') { - d = d.concat(encode.NUMBER(v)); - } else if (type === 'real') { - d = d.concat(encode.REAL(v)); - } else { - throw new Error('Unknown operand type ' + type); - // FIXME Add support for booleans - } - } + { + // Reset effect durations for the next eventual effect phase. + // These are reset during render to allow the DevTools commit hook a chance to read them, + var stateNode = workInProgress.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + } - return d; -}; + break; -encode.OP = encode.BYTE; -sizeOf.OP = sizeOf.BYTE; + case SuspenseComponent: + { + var state = workInProgress.memoizedState; -// memoize charstring encoding using WeakMap if available -var wmm = typeof WeakMap === 'function' && new WeakMap(); + if (state !== null) { + { + if (state.dehydrated !== null) { + pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has + // been unsuspended it has committed as a resolved Suspense component. + // If it needs to be retried, it should have work scheduled on it. -/** - * Convert a list of CharString operations to bytes. - * @param {Array} - * @returns {Array} - */ -encode.CHARSTRING = function(ops) { - // See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))". - if (wmm) { - var cachedValue = wmm.get(ops); - if (cachedValue !== undefined) { - return cachedValue; - } - } + workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we + // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork. - var d = []; - var length = ops.length; + return null; + } + } // If this boundary is currently timed out, we need to decide + // whether to retry the primary children, or to skip over it and + // go straight to the fallback. Check the priority of the primary + // child fragment. - for (var i = 0; i < length; i += 1) { - var op = ops[i]; - d = d.concat(encode[op.type](op.value)); - } - if (wmm) { - wmm.set(ops, d); - } + var primaryChildFragment = workInProgress.child; + var primaryChildLanes = primaryChildFragment.childLanes; - return d; -}; + if (includesSomeLane(renderLanes, primaryChildLanes)) { + // The primary children have pending work. Use the normal path + // to attempt to render the primary children again. + return updateSuspenseComponent(current, workInProgress, renderLanes); + } else { + // The primary child fragment does not have pending work marked + // on it + pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient + // priority. Bailout. -/** - * @param {Array} - * @returns {number} - */ -sizeOf.CHARSTRING = function(ops) { - return encode.CHARSTRING(ops).length; -}; + var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); -// Utility functions //////////////////////////////////////////////////////// + if (child !== null) { + // The fallback children have pending work. Skip over the + // primary children and work on the fallback. + return child.sibling; + } else { + // Note: We can return `null` here because we already checked + // whether there were nested context consumers, via the call to + // `bailoutOnAlreadyFinishedWork` above. + return null; + } + } + } else { + pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); + } -/** - * Convert an object containing name / type / value to bytes. - * @param {Object} - * @returns {Array} - */ -encode.OBJECT = function(v) { - var encodingFunction = encode[v.type]; - check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type); - return encodingFunction(v.value); -}; + break; + } -/** - * @param {Object} - * @returns {number} - */ -sizeOf.OBJECT = function(v) { - var sizeOfFunction = sizeOf[v.type]; - check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type); - return sizeOfFunction(v.value); -}; + case SuspenseListComponent: + { + var didSuspendBefore = (current.flags & DidCapture) !== NoFlags; -/** - * Convert a table object to bytes. - * A table contains a list of fields containing the metadata (name, type and default value). - * The table itself has the field values set as attributes. - * @param {opentype.Table} - * @returns {Array} - */ -encode.TABLE = function(table) { - var d = []; - var length = table.fields.length; - var subtables = []; - var subtableOffsets = []; - - for (var i = 0; i < length; i += 1) { - var field = table.fields[i]; - var encodingFunction = encode[field.type]; - check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')'); - var value = table[field.name]; - if (value === undefined) { - value = field.value; - } + var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); - var bytes = encodingFunction(value); + if (didSuspendBefore) { + if (_hasChildWork) { + // If something was in fallback state last time, and we have all the + // same children then we're still in progressive loading state. + // Something might get unblocked by state updates or retries in the + // tree which will affect the tail. So we need to use the normal + // path to compute the correct tail. + return updateSuspenseListComponent(current, workInProgress, renderLanes); + } // If none of the children had any work, that means that none of + // them got retried so they'll still be blocked in the same way + // as before. We can fast bail out. - if (field.type === 'TABLE') { - subtableOffsets.push(d.length); - d = d.concat([0, 0]); - subtables.push(bytes); - } else { - d = d.concat(bytes); - } - } - for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) { - var o = subtableOffsets[i$1]; - var offset = d.length; - check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.'); - d[o] = offset >> 8; - d[o + 1] = offset & 0xff; - d = d.concat(subtables[i$1]); - } + workInProgress.flags |= DidCapture; + } // If nothing suspended before and we're rendering the same children, + // then the tail doesn't matter. Anything new that suspends will work + // in the "together" mode, so we can continue from the state we had. - return d; -}; -/** - * @param {opentype.Table} - * @returns {number} - */ -sizeOf.TABLE = function(table) { - var numBytes = 0; - var length = table.fields.length; - - for (var i = 0; i < length; i += 1) { - var field = table.fields[i]; - var sizeOfFunction = sizeOf[field.type]; - check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')'); - var value = table[field.name]; - if (value === undefined) { - value = field.value; - } + var renderState = workInProgress.memoizedState; - numBytes += sizeOfFunction(value); + if (renderState !== null) { + // Reset to the "together" mode in case we've started a different + // update in the past but didn't complete it. + renderState.rendering = null; + renderState.tail = null; + renderState.lastEffect = null; + } - // Subtables take 2 more bytes for offsets. - if (field.type === 'TABLE') { - numBytes += 2; - } - } + pushSuspenseContext(workInProgress, suspenseStackCursor.current); - return numBytes; -}; + if (_hasChildWork) { + break; + } else { + // If none of the children had any work, that means that none of + // them got retried so they'll still be blocked in the same way + // as before. We can fast bail out. + return null; + } + } -encode.RECORD = encode.TABLE; -sizeOf.RECORD = sizeOf.TABLE; + case OffscreenComponent: + case LegacyHiddenComponent: + { + // Need to check if the tree still needs to be deferred. This is + // almost identical to the logic used in the normal update path, + // so we'll just enter that. The only difference is we'll bail out + // at the next level instead of this one, because the child props + // have not changed. Which is fine. + // TODO: Probably should refactor `beginWork` to split the bailout + // path from the normal path. I'm tempted to do a labeled break here + // but I won't :) + workInProgress.lanes = NoLanes; + return updateOffscreenComponent(current, workInProgress, renderLanes); + } + } -// Merge in a list of bytes. -encode.LITERAL = function(v) { - return v; -}; + return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); + } -sizeOf.LITERAL = function(v) { - return v.length; -}; + function beginWork(current, workInProgress, renderLanes) { + { + if (workInProgress._debugNeedsRemount && current !== null) { + // This will restart the begin phase with a new fiber. + return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes)); + } + } -// Table metadata + if (current !== null) { + var oldProps = current.memoizedProps; + var newProps = workInProgress.pendingProps; -/** - * @exports opentype.Table - * @class - * @param {string} tableName - * @param {Array} fields - * @param {Object} options - * @constructor - */ -function Table(tableName, fields, options) { - // For coverage tables with coverage format 2, we do not want to add the coverage data directly to the table object, - // as this will result in wrong encoding order of the coverage data on serialization to bytes. - // The fallback of using the field values directly when not present on the table is handled in types.encode.TABLE() already. - if (fields.length && (fields[0].name !== 'coverageFormat' || fields[0].value === 1)) { - for (var i = 0; i < fields.length; i += 1) { - var field = fields[i]; - this[field.name] = field.value; - } - } + if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload: + workInProgress.type !== current.type )) { + // If props or context changed, mark the fiber as having performed work. + // This may be unset if the props are determined to be equal later (memo). + didReceiveUpdate = true; + } else { + // Neither props nor legacy context changes. Check if there's a pending + // update or context change. + var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); - this.tableName = tableName; - this.fields = fields; - if (options) { - var optionKeys = Object.keys(options); - for (var i$1 = 0; i$1 < optionKeys.length; i$1 += 1) { - var k = optionKeys[i$1]; - var v = options[k]; - if (this[k] !== undefined) { - this[k] = v; - } - } - } -} + if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there + // may not be work scheduled on `current`, so we check for this flag. + (workInProgress.flags & DidCapture) === NoFlags) { + // No pending updates or context. Bail out now. + didReceiveUpdate = false; + return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes); + } -/** - * Encodes the table and returns an array of bytes - * @return {Array} - */ -Table.prototype.encode = function() { - return encode.TABLE(this); -}; + if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { + // This is a special case that only exists for legacy mode. + // See https://github.com/facebook/react/pull/19216. + didReceiveUpdate = true; + } else { + // An update was scheduled on this fiber, but there are no new props + // nor legacy context. Set this to false. If an update queue or context + // consumer produces a changed value, it will set this to true. Otherwise, + // the component will assume the children have not changed and bail out. + didReceiveUpdate = false; + } + } + } else { + didReceiveUpdate = false; -/** - * Get the size of the table. - * @return {number} - */ -Table.prototype.sizeOf = function() { - return sizeOf.TABLE(this); -}; + if (getIsHydrating() && isForkedChild(workInProgress)) { + // Check if this child belongs to a list of muliple children in + // its parent. + // + // In a true multi-threaded implementation, we would render children on + // parallel threads. This would represent the beginning of a new render + // thread for this subtree. + // + // We only use this for id generation during hydration, which is why the + // logic is located in this special branch. + var slotIndex = workInProgress.index; + var numberOfForks = getForksAtLevel(); + pushTreeId(workInProgress, numberOfForks, slotIndex); + } + } // Before entering the begin phase, clear pending update priority. + // TODO: This assumes that we're about to evaluate the component and process + // the update queue. However, there's an exception: SimpleMemoComponent + // sometimes bails out later in the begin phase. This indicates that we should + // move this assignment out of the common path and into each branch. -/** - * @private - */ -function ushortList(itemName, list, count) { - if (count === undefined) { - count = list.length; - } - var fields = new Array(list.length + 1); - fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; - for (var i = 0; i < list.length; i++) { - fields[i + 1] = {name: itemName + i, type: 'USHORT', value: list[i]}; - } - return fields; -} -/** - * @private - */ -function tableList(itemName, records, itemCallback) { - var count = records.length; - var fields = new Array(count + 1); - fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; - for (var i = 0; i < count; i++) { - fields[i + 1] = {name: itemName + i, type: 'TABLE', value: itemCallback(records[i], i)}; - } - return fields; -} + workInProgress.lanes = NoLanes; -/** - * @private - */ -function recordList(itemName, records, itemCallback) { - var count = records.length; - var fields = []; - fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; - for (var i = 0; i < count; i++) { - fields = fields.concat(itemCallback(records[i], i)); - } - return fields; -} + switch (workInProgress.tag) { + case IndeterminateComponent: + { + return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes); + } -// Common Layout Tables + case LazyComponent: + { + var elementType = workInProgress.elementType; + return mountLazyComponent(current, workInProgress, elementType, renderLanes); + } -/** - * @exports opentype.Coverage - * @class - * @param {opentype.Table} - * @constructor - * @extends opentype.Table - */ -function Coverage(coverageTable) { - if (coverageTable.format === 1) { - Table.call(this, 'coverageTable', - [{name: 'coverageFormat', type: 'USHORT', value: 1}] - .concat(ushortList('glyph', coverageTable.glyphs)) - ); - } else if (coverageTable.format === 2) { - Table.call(this, 'coverageTable', - [{name: 'coverageFormat', type: 'USHORT', value: 2}] - .concat(recordList('rangeRecord', coverageTable.ranges, function(RangeRecord) { - return [ - {name: 'startGlyphID', type: 'USHORT', value: RangeRecord.start}, - {name: 'endGlyphID', type: 'USHORT', value: RangeRecord.end}, - {name: 'startCoverageIndex', type: 'USHORT', value: RangeRecord.index} ]; - })) - ); - } else { - check.assert(false, 'Coverage format must be 1 or 2.'); - } -} -Coverage.prototype = Object.create(Table.prototype); -Coverage.prototype.constructor = Coverage; - -function ScriptList(scriptListTable) { - Table.call(this, 'scriptListTable', - recordList('scriptRecord', scriptListTable, function(scriptRecord, i) { - var script = scriptRecord.script; - var defaultLangSys = script.defaultLangSys; - check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.'); - return [ - {name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag}, - {name: 'script' + i, type: 'TABLE', value: new Table('scriptTable', [ - {name: 'defaultLangSys', type: 'TABLE', value: new Table('defaultLangSys', [ - {name: 'lookupOrder', type: 'USHORT', value: 0}, - {name: 'reqFeatureIndex', type: 'USHORT', value: defaultLangSys.reqFeatureIndex}] - .concat(ushortList('featureIndex', defaultLangSys.featureIndexes)))} - ].concat(recordList('langSys', script.langSysRecords, function(langSysRecord, i) { - var langSys = langSysRecord.langSys; - return [ - {name: 'langSysTag' + i, type: 'TAG', value: langSysRecord.tag}, - {name: 'langSys' + i, type: 'TABLE', value: new Table('langSys', [ - {name: 'lookupOrder', type: 'USHORT', value: 0}, - {name: 'reqFeatureIndex', type: 'USHORT', value: langSys.reqFeatureIndex} - ].concat(ushortList('featureIndex', langSys.featureIndexes)))} - ]; - })))} - ]; - }) - ); -} -ScriptList.prototype = Object.create(Table.prototype); -ScriptList.prototype.constructor = ScriptList; + case FunctionComponent: + { + var Component = workInProgress.type; + var unresolvedProps = workInProgress.pendingProps; + var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); + return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes); + } -/** - * @exports opentype.FeatureList - * @class - * @param {opentype.Table} - * @constructor - * @extends opentype.Table - */ -function FeatureList(featureListTable) { - Table.call(this, 'featureListTable', - recordList('featureRecord', featureListTable, function(featureRecord, i) { - var feature = featureRecord.feature; - return [ - {name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag}, - {name: 'feature' + i, type: 'TABLE', value: new Table('featureTable', [ - {name: 'featureParams', type: 'USHORT', value: feature.featureParams} ].concat(ushortList('lookupListIndex', feature.lookupListIndexes)))} - ]; - }) - ); -} -FeatureList.prototype = Object.create(Table.prototype); -FeatureList.prototype.constructor = FeatureList; + case ClassComponent: + { + var _Component = workInProgress.type; + var _unresolvedProps = workInProgress.pendingProps; -/** - * @exports opentype.LookupList - * @class - * @param {opentype.Table} - * @param {Object} - * @constructor - * @extends opentype.Table - */ -function LookupList(lookupListTable, subtableMakers) { - Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function(lookupTable) { - var subtableCallback = subtableMakers[lookupTable.lookupType]; - check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.'); - return new Table('lookupTable', [ - {name: 'lookupType', type: 'USHORT', value: lookupTable.lookupType}, - {name: 'lookupFlag', type: 'USHORT', value: lookupTable.lookupFlag} - ].concat(tableList('subtable', lookupTable.subtables, subtableCallback))); - })); -} -LookupList.prototype = Object.create(Table.prototype); -LookupList.prototype.constructor = LookupList; - -// Record = same as Table, but inlined (a Table has an offset and its data is further in the stream) -// Don't use offsets inside Records (probable bug), only in Tables. -var table = { - Table: Table, - Record: Table, - Coverage: Coverage, - ScriptList: ScriptList, - FeatureList: FeatureList, - LookupList: LookupList, - ushortList: ushortList, - tableList: tableList, - recordList: recordList, -}; + var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps); -// Parsing utility functions + return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes); + } -// Retrieve an unsigned byte from the DataView. -function getByte(dataView, offset) { - return dataView.getUint8(offset); -} + case HostRoot: + return updateHostRoot(current, workInProgress, renderLanes); -// Retrieve an unsigned 16-bit short from the DataView. -// The value is stored in big endian. -function getUShort(dataView, offset) { - return dataView.getUint16(offset, false); -} + case HostComponent: + return updateHostComponent$1(current, workInProgress, renderLanes); -// Retrieve a signed 16-bit short from the DataView. -// The value is stored in big endian. -function getShort(dataView, offset) { - return dataView.getInt16(offset, false); -} + case HostText: + return updateHostText$1(current, workInProgress); -// Retrieve an unsigned 32-bit long from the DataView. -// The value is stored in big endian. -function getULong(dataView, offset) { - return dataView.getUint32(offset, false); -} + case SuspenseComponent: + return updateSuspenseComponent(current, workInProgress, renderLanes); -// Retrieve a 32-bit signed fixed-point number (16.16) from the DataView. -// The value is stored in big endian. -function getFixed(dataView, offset) { - var decimal = dataView.getInt16(offset, false); - var fraction = dataView.getUint16(offset + 2, false); - return decimal + fraction / 65535; -} + case HostPortal: + return updatePortalComponent(current, workInProgress, renderLanes); -// Retrieve a 4-character tag from the DataView. -// Tags are used to identify tables. -function getTag(dataView, offset) { - var tag = ''; - for (var i = offset; i < offset + 4; i += 1) { - tag += String.fromCharCode(dataView.getInt8(i)); - } + case ForwardRef: + { + var type = workInProgress.type; + var _unresolvedProps2 = workInProgress.pendingProps; - return tag; -} + var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); -// Retrieve an offset from the DataView. -// Offsets are 1 to 4 bytes in length, depending on the offSize argument. -function getOffset(dataView, offset, offSize) { - var v = 0; - for (var i = 0; i < offSize; i += 1) { - v <<= 8; - v += dataView.getUint8(offset + i); - } + return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes); + } - return v; -} + case Fragment: + return updateFragment(current, workInProgress, renderLanes); -// Retrieve a number of bytes from start offset to the end offset from the DataView. -function getBytes(dataView, startOffset, endOffset) { - var bytes = []; - for (var i = startOffset; i < endOffset; i += 1) { - bytes.push(dataView.getUint8(i)); - } + case Mode: + return updateMode(current, workInProgress, renderLanes); - return bytes; -} + case Profiler: + return updateProfiler(current, workInProgress, renderLanes); -// Convert the list of bytes to a string. -function bytesToString(bytes) { - var s = ''; - for (var i = 0; i < bytes.length; i += 1) { - s += String.fromCharCode(bytes[i]); - } + case ContextProvider: + return updateContextProvider(current, workInProgress, renderLanes); - return s; -} + case ContextConsumer: + return updateContextConsumer(current, workInProgress, renderLanes); -var typeOffsets = { - byte: 1, - uShort: 2, - short: 2, - uLong: 4, - fixed: 4, - longDateTime: 8, - tag: 4 -}; + case MemoComponent: + { + var _type2 = workInProgress.type; + var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. -// A stateful parser that changes the offset whenever a value is retrieved. -// The data is a DataView. -function Parser(data, offset) { - this.data = data; - this.offset = offset; - this.relativeOffset = 0; -} + var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); -Parser.prototype.parseByte = function() { - var v = this.data.getUint8(this.offset + this.relativeOffset); - this.relativeOffset += 1; - return v; -}; + { + if (workInProgress.type !== workInProgress.elementType) { + var outerPropTypes = _type2.propTypes; -Parser.prototype.parseChar = function() { - var v = this.data.getInt8(this.offset + this.relativeOffset); - this.relativeOffset += 1; - return v; -}; + if (outerPropTypes) { + checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only + 'prop', getComponentNameFromType(_type2)); + } + } + } -Parser.prototype.parseCard8 = Parser.prototype.parseByte; + _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes); + } -Parser.prototype.parseUShort = function() { - var v = this.data.getUint16(this.offset + this.relativeOffset); - this.relativeOffset += 2; - return v; -}; + case SimpleMemoComponent: + { + return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes); + } -Parser.prototype.parseCard16 = Parser.prototype.parseUShort; -Parser.prototype.parseSID = Parser.prototype.parseUShort; -Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; + case IncompleteClassComponent: + { + var _Component2 = workInProgress.type; + var _unresolvedProps4 = workInProgress.pendingProps; -Parser.prototype.parseShort = function() { - var v = this.data.getInt16(this.offset + this.relativeOffset); - this.relativeOffset += 2; - return v; -}; + var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4); -Parser.prototype.parseF2Dot14 = function() { - var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; - this.relativeOffset += 2; - return v; -}; + return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes); + } -Parser.prototype.parseULong = function() { - var v = getULong(this.data, this.offset + this.relativeOffset); - this.relativeOffset += 4; - return v; -}; + case SuspenseListComponent: + { + return updateSuspenseListComponent(current, workInProgress, renderLanes); + } -Parser.prototype.parseOffset32 = Parser.prototype.parseULong; + case ScopeComponent: + { -Parser.prototype.parseFixed = function() { - var v = getFixed(this.data, this.offset + this.relativeOffset); - this.relativeOffset += 4; - return v; -}; + break; + } -Parser.prototype.parseString = function(length) { - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - var string = ''; - this.relativeOffset += length; - for (var i = 0; i < length; i++) { - string += String.fromCharCode(dataView.getUint8(offset + i)); - } + case OffscreenComponent: + { + return updateOffscreenComponent(current, workInProgress, renderLanes); + } + } - return string; -}; + throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); + } -Parser.prototype.parseTag = function() { - return this.parseString(4); -}; + function unwindWork(current, workInProgress, renderLanes) { + // Note: This intentionally doesn't check if we're hydrating because comparing + // to the current tree provider fiber is just as fast and less error-prone. + // Ideally we would have a special version of the work loop only + // for hydration. + popTreeContext(workInProgress); -// LONGDATETIME is a 64-bit integer. -// JavaScript and unix timestamps traditionally use 32 bits, so we -// only take the last 32 bits. -// + Since until 2038 those bits will be filled by zeros we can ignore them. -Parser.prototype.parseLongDateTime = function() { - var v = getULong(this.data, this.offset + this.relativeOffset + 4); - // Subtract seconds between 01/01/1904 and 01/01/1970 - // to convert Apple Mac timestamp to Standard Unix timestamp - v -= 2082844800; - this.relativeOffset += 8; - return v; -}; + switch (workInProgress.tag) { + case ClassComponent: + { + var Component = workInProgress.type; -Parser.prototype.parseVersion = function(minorBase) { - var major = getUShort(this.data, this.offset + this.relativeOffset); + if (isContextProvider(Component)) { + popContext(workInProgress); + } - // How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1 - // Default returns the correct number if minor = 0xN000 where N is 0-9 - // Set minorBase to 1 for tables that use minor = N where N is 0-9 - var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); - this.relativeOffset += 4; - if (minorBase === undefined) { minorBase = 0x1000; } - return major + minor / minorBase / 10; -}; + var flags = workInProgress.flags; -Parser.prototype.skip = function(type, amount) { - if (amount === undefined) { - amount = 1; - } + if (flags & ShouldCapture) { + workInProgress.flags = flags & ~ShouldCapture | DidCapture; - this.relativeOffset += typeOffsets[type] * amount; -}; + if ( (workInProgress.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress); + } -///// Parsing lists and records /////////////////////////////// - -// Parse a list of 32 bit unsigned integers. -Parser.prototype.parseULongList = function(count) { - if (count === undefined) { count = this.parseULong(); } - var offsets = new Array(count); - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - for (var i = 0; i < count; i++) { - offsets[i] = dataView.getUint32(offset); - offset += 4; - } + return workInProgress; + } - this.relativeOffset += count * 4; - return offsets; -}; + return null; + } -// Parse a list of 16 bit unsigned integers. The length of the list can be read on the stream -// or provided as an argument. -Parser.prototype.parseOffset16List = -Parser.prototype.parseUShortList = function(count) { - if (count === undefined) { count = this.parseUShort(); } - var offsets = new Array(count); - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - for (var i = 0; i < count; i++) { - offsets[i] = dataView.getUint16(offset); - offset += 2; - } + case HostRoot: + { - this.relativeOffset += count * 2; - return offsets; -}; + popHostContainer(workInProgress); + popTopLevelContextObject(workInProgress); + resetWorkInProgressVersions(); + var _flags = workInProgress.flags; -// Parses a list of 16 bit signed integers. -Parser.prototype.parseShortList = function(count) { - var list = new Array(count); - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - for (var i = 0; i < count; i++) { - list[i] = dataView.getInt16(offset); - offset += 2; - } + if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) { + // There was an error during render that wasn't captured by a suspense + // boundary. Do a second pass on the root to unmount the children. + workInProgress.flags = _flags & ~ShouldCapture | DidCapture; + return workInProgress; + } // We unwound to the root without completing it. Exit. - this.relativeOffset += count * 2; - return list; -}; -// Parses a list of bytes. -Parser.prototype.parseByteList = function(count) { - var list = new Array(count); - var dataView = this.data; - var offset = this.offset + this.relativeOffset; - for (var i = 0; i < count; i++) { - list[i] = dataView.getUint8(offset++); - } + return null; + } - this.relativeOffset += count; - return list; -}; + case HostComponent: + { + // TODO: popHydrationState + popHostContext(workInProgress); + return null; + } -/** - * Parse a list of items. - * Record count is optional, if omitted it is read from the stream. - * itemCallback is one of the Parser methods. - */ -Parser.prototype.parseList = function(count, itemCallback) { - if (!itemCallback) { - itemCallback = count; - count = this.parseUShort(); - } - var list = new Array(count); - for (var i = 0; i < count; i++) { - list[i] = itemCallback.call(this); - } - return list; -}; + case SuspenseComponent: + { + popSuspenseContext(workInProgress); -Parser.prototype.parseList32 = function(count, itemCallback) { - if (!itemCallback) { - itemCallback = count; - count = this.parseULong(); - } - var list = new Array(count); - for (var i = 0; i < count; i++) { - list[i] = itemCallback.call(this); - } - return list; -}; + { + var suspenseState = workInProgress.memoizedState; -/** - * Parse a list of records. - * Record count is optional, if omitted it is read from the stream. - * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } - */ -Parser.prototype.parseRecordList = function(count, recordDescription) { - // If the count argument is absent, read it in the stream. - if (!recordDescription) { - recordDescription = count; - count = this.parseUShort(); - } - var records = new Array(count); - var fields = Object.keys(recordDescription); - for (var i = 0; i < count; i++) { - var rec = {}; - for (var j = 0; j < fields.length; j++) { - var fieldName = fields[j]; - var fieldType = recordDescription[fieldName]; - rec[fieldName] = fieldType.call(this); - } - records[i] = rec; - } - return records; -}; + if (suspenseState !== null && suspenseState.dehydrated !== null) { + if (workInProgress.alternate === null) { + throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.'); + } -Parser.prototype.parseRecordList32 = function(count, recordDescription) { - // If the count argument is absent, read it in the stream. - if (!recordDescription) { - recordDescription = count; - count = this.parseULong(); - } - var records = new Array(count); - var fields = Object.keys(recordDescription); - for (var i = 0; i < count; i++) { - var rec = {}; - for (var j = 0; j < fields.length; j++) { - var fieldName = fields[j]; - var fieldType = recordDescription[fieldName]; - rec[fieldName] = fieldType.call(this); - } - records[i] = rec; - } - return records; -}; + resetHydrationState(); + } + } -// Parse a data structure into an object -// Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } -Parser.prototype.parseStruct = function(description) { - if (typeof description === 'function') { - return description.call(this); - } else { - var fields = Object.keys(description); - var struct = {}; - for (var j = 0; j < fields.length; j++) { - var fieldName = fields[j]; - var fieldType = description[fieldName]; - struct[fieldName] = fieldType.call(this); - } - return struct; - } -}; + var _flags2 = workInProgress.flags; -/** - * Parse a GPOS valueRecord - * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record - * valueFormat is optional, if omitted it is read from the stream. - */ -Parser.prototype.parseValueRecord = function(valueFormat) { - if (valueFormat === undefined) { - valueFormat = this.parseUShort(); - } - if (valueFormat === 0) { - // valueFormat2 in kerning pairs is most often 0 - // in this case return undefined instead of an empty object, to save space - return; - } - var valueRecord = {}; + if (_flags2 & ShouldCapture) { + workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary. - if (valueFormat & 0x0001) { valueRecord.xPlacement = this.parseShort(); } - if (valueFormat & 0x0002) { valueRecord.yPlacement = this.parseShort(); } - if (valueFormat & 0x0004) { valueRecord.xAdvance = this.parseShort(); } - if (valueFormat & 0x0008) { valueRecord.yAdvance = this.parseShort(); } + if ( (workInProgress.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress); + } - // Device table (non-variable font) / VariationIndex table (variable font) not supported - // https://docs.microsoft.com/fr-fr/typography/opentype/spec/chapter2#devVarIdxTbls - if (valueFormat & 0x0010) { valueRecord.xPlaDevice = undefined; this.parseShort(); } - if (valueFormat & 0x0020) { valueRecord.yPlaDevice = undefined; this.parseShort(); } - if (valueFormat & 0x0040) { valueRecord.xAdvDevice = undefined; this.parseShort(); } - if (valueFormat & 0x0080) { valueRecord.yAdvDevice = undefined; this.parseShort(); } + return workInProgress; + } - return valueRecord; -}; + return null; + } -/** - * Parse a list of GPOS valueRecords - * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record - * valueFormat and valueCount are read from the stream. - */ -Parser.prototype.parseValueRecordList = function() { - var valueFormat = this.parseUShort(); - var valueCount = this.parseUShort(); - var values = new Array(valueCount); - for (var i = 0; i < valueCount; i++) { - values[i] = this.parseValueRecord(valueFormat); - } - return values; -}; + case SuspenseListComponent: + { + popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been + // caught by a nested boundary. If not, it should bubble through. -Parser.prototype.parsePointer = function(description) { - var structOffset = this.parseOffset16(); - if (structOffset > 0) { - // NULL offset => return undefined - return new Parser(this.data, this.offset + structOffset).parseStruct(description); - } - return undefined; -}; + return null; + } -Parser.prototype.parsePointer32 = function(description) { - var structOffset = this.parseOffset32(); - if (structOffset > 0) { - // NULL offset => return undefined - return new Parser(this.data, this.offset + structOffset).parseStruct(description); - } - return undefined; -}; + case HostPortal: + popHostContainer(workInProgress); + return null; -/** - * Parse a list of offsets to lists of 16-bit integers, - * or a list of offsets to lists of offsets to any kind of items. - * If itemCallback is not provided, a list of list of UShort is assumed. - * If provided, itemCallback is called on each item and must parse the item. - * See examples in tables/gsub.js - */ -Parser.prototype.parseListOfLists = function(itemCallback) { - var offsets = this.parseOffset16List(); - var count = offsets.length; - var relativeOffset = this.relativeOffset; - var list = new Array(count); - for (var i = 0; i < count; i++) { - var start = offsets[i]; - if (start === 0) { - // NULL offset - // Add i as owned property to list. Convenient with assert. - list[i] = undefined; - continue; - } - this.relativeOffset = start; - if (itemCallback) { - var subOffsets = this.parseOffset16List(); - var subList = new Array(subOffsets.length); - for (var j = 0; j < subOffsets.length; j++) { - this.relativeOffset = start + subOffsets[j]; - subList[j] = itemCallback.call(this); - } - list[i] = subList; - } else { - list[i] = this.parseUShortList(); - } - } - this.relativeOffset = relativeOffset; - return list; -}; + case ContextProvider: + var context = workInProgress.type._context; + popProvider(context, workInProgress); + return null; -///// Complex tables parsing ////////////////////////////////// + case OffscreenComponent: + case LegacyHiddenComponent: + popRenderLanes(workInProgress); -// Parse a coverage table in a GSUB, GPOS or GDEF table. -// https://www.microsoft.com/typography/OTSPEC/chapter2.htm -// parser.offset must point to the start of the table containing the coverage. -Parser.prototype.parseCoverage = function() { - var startOffset = this.offset + this.relativeOffset; - var format = this.parseUShort(); - var count = this.parseUShort(); - if (format === 1) { - return { - format: 1, - glyphs: this.parseUShortList(count) - }; - } else if (format === 2) { - var ranges = new Array(count); - for (var i = 0; i < count; i++) { - ranges[i] = { - start: this.parseUShort(), - end: this.parseUShort(), - index: this.parseUShort() - }; - } - return { - format: 2, - ranges: ranges - }; - } - throw new Error('0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.'); -}; + return null; -// Parse a Class Definition Table in a GSUB, GPOS or GDEF table. -// https://www.microsoft.com/typography/OTSPEC/chapter2.htm -Parser.prototype.parseClassDef = function() { - var startOffset = this.offset + this.relativeOffset; - var format = this.parseUShort(); - if (format === 1) { - return { - format: 1, - startGlyph: this.parseUShort(), - classes: this.parseUShortList() - }; - } else if (format === 2) { - return { - format: 2, - ranges: this.parseRecordList({ - start: Parser.uShort, - end: Parser.uShort, - classId: Parser.uShort - }) - }; - } - throw new Error('0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.'); -}; + case CacheComponent: -///// Static methods /////////////////////////////////// -// These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance. + return null; -Parser.list = function(count, itemCallback) { - return function() { - return this.parseList(count, itemCallback); - }; -}; + default: + return null; + } + } -Parser.list32 = function(count, itemCallback) { - return function() { - return this.parseList32(count, itemCallback); - }; -}; + function unwindInterruptedWork(current, interruptedWork, renderLanes) { + // Note: This intentionally doesn't check if we're hydrating because comparing + // to the current tree provider fiber is just as fast and less error-prone. + // Ideally we would have a special version of the work loop only + // for hydration. + popTreeContext(interruptedWork); -Parser.recordList = function(count, recordDescription) { - return function() { - return this.parseRecordList(count, recordDescription); - }; -}; + switch (interruptedWork.tag) { + case ClassComponent: + { + var childContextTypes = interruptedWork.type.childContextTypes; -Parser.recordList32 = function(count, recordDescription) { - return function() { - return this.parseRecordList32(count, recordDescription); - }; -}; + if (childContextTypes !== null && childContextTypes !== undefined) { + popContext(interruptedWork); + } -Parser.pointer = function(description) { - return function() { - return this.parsePointer(description); - }; -}; + break; + } -Parser.pointer32 = function(description) { - return function() { - return this.parsePointer32(description); - }; -}; + case HostRoot: + { -Parser.tag = Parser.prototype.parseTag; -Parser.byte = Parser.prototype.parseByte; -Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; -Parser.uShortList = Parser.prototype.parseUShortList; -Parser.uLong = Parser.offset32 = Parser.prototype.parseULong; -Parser.uLongList = Parser.prototype.parseULongList; -Parser.struct = Parser.prototype.parseStruct; -Parser.coverage = Parser.prototype.parseCoverage; -Parser.classDef = Parser.prototype.parseClassDef; - -///// Script, Feature, Lookup lists /////////////////////////////////////////////// -// https://www.microsoft.com/typography/OTSPEC/chapter2.htm - -var langSysTable = { - reserved: Parser.uShort, - reqFeatureIndex: Parser.uShort, - featureIndexes: Parser.uShortList -}; + popHostContainer(interruptedWork); + popTopLevelContextObject(interruptedWork); + resetWorkInProgressVersions(); + break; + } -Parser.prototype.parseScriptList = function() { - return this.parsePointer(Parser.recordList({ - tag: Parser.tag, - script: Parser.pointer({ - defaultLangSys: Parser.pointer(langSysTable), - langSysRecords: Parser.recordList({ - tag: Parser.tag, - langSys: Parser.pointer(langSysTable) - }) - }) - })) || []; -}; + case HostComponent: + { + popHostContext(interruptedWork); + break; + } -Parser.prototype.parseFeatureList = function() { - return this.parsePointer(Parser.recordList({ - tag: Parser.tag, - feature: Parser.pointer({ - featureParams: Parser.offset16, - lookupListIndexes: Parser.uShortList - }) - })) || []; -}; + case HostPortal: + popHostContainer(interruptedWork); + break; -Parser.prototype.parseLookupList = function(lookupTableParsers) { - return this.parsePointer(Parser.list(Parser.pointer(function() { - var lookupType = this.parseUShort(); - check.argument(1 <= lookupType && lookupType <= 9, 'GPOS/GSUB lookup type ' + lookupType + ' unknown.'); - var lookupFlag = this.parseUShort(); - var useMarkFilteringSet = lookupFlag & 0x10; - return { - lookupType: lookupType, - lookupFlag: lookupFlag, - subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), - markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined - }; - }))) || []; -}; + case SuspenseComponent: + popSuspenseContext(interruptedWork); + break; -Parser.prototype.parseFeatureVariationsList = function() { - return this.parsePointer32(function() { - var majorVersion = this.parseUShort(); - var minorVersion = this.parseUShort(); - check.argument(majorVersion === 1 && minorVersion < 1, 'GPOS/GSUB feature variations table unknown.'); - var featureVariations = this.parseRecordList32({ - conditionSetOffset: Parser.offset32, - featureTableSubstitutionOffset: Parser.offset32 - }); - return featureVariations; - }) || []; -}; + case SuspenseListComponent: + popSuspenseContext(interruptedWork); + break; -var parse = { - getByte: getByte, - getCard8: getByte, - getUShort: getUShort, - getCard16: getUShort, - getShort: getShort, - getULong: getULong, - getFixed: getFixed, - getTag: getTag, - getOffset: getOffset, - getBytes: getBytes, - bytesToString: bytesToString, - Parser: Parser, -}; + case ContextProvider: + var context = interruptedWork.type._context; + popProvider(context, interruptedWork); + break; -// The `cmap` table stores the mappings from characters to glyphs. + case OffscreenComponent: + case LegacyHiddenComponent: + popRenderLanes(interruptedWork); -function parseCmapTableFormat12(cmap, p) { - //Skip reserved. - p.parseUShort(); + break; + } + } - // Length in bytes of the sub-tables. - cmap.length = p.parseULong(); - cmap.language = p.parseULong(); + function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) { + var funcArgs = Array.prototype.slice.call(arguments, 3); - var groupCount; - cmap.groupCount = groupCount = p.parseULong(); - cmap.glyphIndexMap = {}; + try { + func.apply(context, funcArgs); + } catch (error) { + this.onError(error); + } + } - for (var i = 0; i < groupCount; i += 1) { - var startCharCode = p.parseULong(); - var endCharCode = p.parseULong(); - var startGlyphId = p.parseULong(); + var invokeGuardedCallbackImpl = invokeGuardedCallbackProd; - for (var c = startCharCode; c <= endCharCode; c += 1) { - cmap.glyphIndexMap[c] = startGlyphId; - startGlyphId++; - } - } -} + { + // In DEV mode, we swap out invokeGuardedCallback for a special version + // that plays more nicely with the browser's DevTools. The idea is to preserve + // "Pause on exceptions" behavior. Because React wraps all user-provided + // functions in invokeGuardedCallback, and the production version of + // invokeGuardedCallback uses a try-catch, all user exceptions are treated + // like caught exceptions, and the DevTools won't pause unless the developer + // takes the extra step of enabling pause on caught exceptions. This is + // unintuitive, though, because even though React has caught the error, from + // the developer's perspective, the error is uncaught. + // + // To preserve the expected "Pause on exceptions" behavior, we don't use a + // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake + // DOM node, and call the user-provided callback from inside an event handler + // for that fake event. If the callback throws, the error is "captured" using + // a global event handler. But because the error happens in a different + // event loop context, it does not interrupt the normal program flow. + // Effectively, this gives us try-catch behavior without actually using + // try-catch. Neat! + // Check that the browser supports the APIs we need to implement our special + // DEV version of invokeGuardedCallback + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { + var fakeNode = document.createElement('react'); -function parseCmapTableFormat4(cmap, p, data, start, offset) { - // Length in bytes of the sub-tables. - cmap.length = p.parseUShort(); - cmap.language = p.parseUShort(); - - // segCount is stored x 2. - var segCount; - cmap.segCount = segCount = p.parseUShort() >> 1; - - // Skip searchRange, entrySelector, rangeShift. - p.skip('uShort', 3); - - // The "unrolled" mapping from character codes to glyph indices. - cmap.glyphIndexMap = {}; - var endCountParser = new parse.Parser(data, start + offset + 14); - var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2); - var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4); - var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6); - var glyphIndexOffset = start + offset + 16 + segCount * 8; - for (var i = 0; i < segCount - 1; i += 1) { - var glyphIndex = (void 0); - var endCount = endCountParser.parseUShort(); - var startCount = startCountParser.parseUShort(); - var idDelta = idDeltaParser.parseShort(); - var idRangeOffset = idRangeOffsetParser.parseUShort(); - for (var c = startCount; c <= endCount; c += 1) { - if (idRangeOffset !== 0) { - // The idRangeOffset is relative to the current position in the idRangeOffset array. - // Take the current offset in the idRangeOffset array. - glyphIndexOffset = (idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2); - - // Add the value of the idRangeOffset, which will move us into the glyphIndex array. - glyphIndexOffset += idRangeOffset; - - // Then add the character index of the current segment, multiplied by 2 for USHORTs. - glyphIndexOffset += (c - startCount) * 2; - glyphIndex = parse.getUShort(data, glyphIndexOffset); - if (glyphIndex !== 0) { - glyphIndex = (glyphIndex + idDelta) & 0xFFFF; - } - } else { - glyphIndex = (c + idDelta) & 0xFFFF; - } + invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) { + // If document doesn't exist we know for sure we will crash in this method + // when we call document.createEvent(). However this can cause confusing + // errors: https://github.com/facebook/create-react-app/issues/3482 + // So we preemptively throw with a better message instead. + if (typeof document === 'undefined' || document === null) { + throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.'); + } - cmap.glyphIndexMap[c] = glyphIndex; - } - } -} + var evt = document.createEvent('Event'); + var didCall = false; // Keeps track of whether the user-provided callback threw an error. We + // set this to true at the beginning, then set it to false right after + // calling the function. If the function errors, `didError` will never be + // set to false. This strategy works even if the browser is flaky and + // fails to call our global error handler, because it doesn't rely on + // the error event at all. -// Parse the `cmap` table. This table stores the mappings from characters to glyphs. -// There are many available formats, but we only support the Windows format 4 and 12. -// This function returns a `CmapEncoding` object or null if no supported format could be found. -function parseCmapTable(data, start) { - var cmap = {}; - cmap.version = parse.getUShort(data, start); - check.argument(cmap.version === 0, 'cmap table version should be 0.'); - - // The cmap table can contain many sub-tables, each with their own format. - // We're only interested in a "platform 0" (Unicode format) and "platform 3" (Windows format) table. - cmap.numTables = parse.getUShort(data, start + 2); - var offset = -1; - for (var i = cmap.numTables - 1; i >= 0; i -= 1) { - var platformId = parse.getUShort(data, start + 4 + (i * 8)); - var encodingId = parse.getUShort(data, start + 4 + (i * 8) + 2); - if ((platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10)) || - (platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4))) { - offset = parse.getULong(data, start + 4 + (i * 8) + 4); - break; - } - } + var didError = true; // Keeps track of the value of window.event so that we can reset it + // during the callback to let user code access window.event in the + // browsers that support it. - if (offset === -1) { - // There is no cmap table in the font that we support. - throw new Error('No valid cmap sub-tables found.'); - } + var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event + // dispatching: https://github.com/facebook/react/issues/13688 - var p = new parse.Parser(data, start + offset); - cmap.format = p.parseUShort(); + var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); - if (cmap.format === 12) { - parseCmapTableFormat12(cmap, p); - } else if (cmap.format === 4) { - parseCmapTableFormat4(cmap, p, data, start, offset); - } else { - throw new Error('Only format 4 and 12 cmap tables are supported (found format ' + cmap.format + ').'); - } + function restoreAfterDispatch() { + // We immediately remove the callback from event listeners so that + // nested `invokeGuardedCallback` calls do not clash. Otherwise, a + // nested call would trigger the fake event handlers of any call higher + // in the stack. + fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the + // window.event assignment in both IE <= 10 as they throw an error + // "Member not found" in strict mode, and in Firefox which does not + // support window.event. - return cmap; -} + if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) { + window.event = windowEvent; + } + } // Create an event handler for our fake event. We will synchronously + // dispatch our fake event using `dispatchEvent`. Inside the handler, we + // call the user-provided callback. -function addSegment(t, code, glyphIndex) { - t.segments.push({ - end: code, - start: code, - delta: -(code - glyphIndex), - offset: 0, - glyphIndex: glyphIndex - }); -} -function addTerminatorSegment(t) { - t.segments.push({ - end: 0xFFFF, - start: 0xFFFF, - delta: 1, - offset: 0 - }); -} + var funcArgs = Array.prototype.slice.call(arguments, 3); -// Make cmap table, format 4 by default, 12 if needed only -function makeCmapTable(glyphs) { - // Plan 0 is the base Unicode Plan but emojis, for example are on another plan, and needs cmap 12 format (with 32bit) - var isPlan0Only = true; - var i; + function callCallback() { + didCall = true; + restoreAfterDispatch(); + func.apply(context, funcArgs); + didError = false; + } // Create a global error event handler. We use this to capture the value + // that was thrown. It's possible that this error handler will fire more + // than once; for example, if non-React code also calls `dispatchEvent` + // and a handler for that event throws. We should be resilient to most of + // those cases. Even if our error event handler fires more than once, the + // last error event is always used. If the callback actually does error, + // we know that the last error event is the correct one, because it's not + // possible for anything else to have happened in between our callback + // erroring and the code that follows the `dispatchEvent` call below. If + // the callback doesn't error, but the error event was fired, we know to + // ignore it because `didError` will be false, as described above. - // Check if we need to add cmap format 12 or if format 4 only is fine - for (i = glyphs.length - 1; i > 0; i -= 1) { - var g = glyphs.get(i); - if (g.unicode > 65535) { - console.log('Adding CMAP format 12 (needed!)'); - isPlan0Only = false; - break; - } - } - var cmapTable = [ - {name: 'version', type: 'USHORT', value: 0}, - {name: 'numTables', type: 'USHORT', value: isPlan0Only ? 1 : 2}, + var error; // Use this to track whether the error event is ever called. - // CMAP 4 header - {name: 'platformID', type: 'USHORT', value: 3}, - {name: 'encodingID', type: 'USHORT', value: 1}, - {name: 'offset', type: 'ULONG', value: isPlan0Only ? 12 : (12 + 8)} - ]; + var didSetError = false; + var isCrossOriginError = false; - if (!isPlan0Only) - { cmapTable = cmapTable.concat([ - // CMAP 12 header - {name: 'cmap12PlatformID', type: 'USHORT', value: 3}, // We encode only for PlatformID = 3 (Windows) because it is supported everywhere - {name: 'cmap12EncodingID', type: 'USHORT', value: 10}, - {name: 'cmap12Offset', type: 'ULONG', value: 0} - ]); } - - cmapTable = cmapTable.concat([ - // CMAP 4 Subtable - {name: 'format', type: 'USHORT', value: 4}, - {name: 'cmap4Length', type: 'USHORT', value: 0}, - {name: 'language', type: 'USHORT', value: 0}, - {name: 'segCountX2', type: 'USHORT', value: 0}, - {name: 'searchRange', type: 'USHORT', value: 0}, - {name: 'entrySelector', type: 'USHORT', value: 0}, - {name: 'rangeShift', type: 'USHORT', value: 0} - ]); + function handleWindowError(event) { + error = event.error; + didSetError = true; - var t = new table.Table('cmap', cmapTable); + if (error === null && event.colno === 0 && event.lineno === 0) { + isCrossOriginError = true; + } - t.segments = []; - for (i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs.get(i); - for (var j = 0; j < glyph.unicodes.length; j += 1) { - addSegment(t, glyph.unicodes[j], i); - } + if (event.defaultPrevented) { + // Some other error handler has prevented default. + // Browsers silence the error report if this happens. + // We'll remember this to later decide whether to log it or not. + if (error != null && typeof error === 'object') { + try { + error._suppressLogging = true; + } catch (inner) {// Ignore. + } + } + } + } // Create a fake event type. - t.segments = t.segments.sort(function (a, b) { - return a.start - b.start; - }); - } - addTerminatorSegment(t); - - var segCount = t.segments.length; - var segCountToRemove = 0; - - // CMAP 4 - // Set up parallel segment arrays. - var endCounts = []; - var startCounts = []; - var idDeltas = []; - var idRangeOffsets = []; - var glyphIds = []; - - // CMAP 12 - var cmap12Groups = []; - - // Reminder this loop is not following the specification at 100% - // The specification -> find suites of characters and make a group - // Here we're doing one group for each letter - // Doing as the spec can save 8 times (or more) space - for (i = 0; i < segCount; i += 1) { - var segment = t.segments[i]; - - // CMAP 4 - if (segment.end <= 65535 && segment.start <= 65535) { - endCounts = endCounts.concat({name: 'end_' + i, type: 'USHORT', value: segment.end}); - startCounts = startCounts.concat({name: 'start_' + i, type: 'USHORT', value: segment.start}); - idDeltas = idDeltas.concat({name: 'idDelta_' + i, type: 'SHORT', value: segment.delta}); - idRangeOffsets = idRangeOffsets.concat({name: 'idRangeOffset_' + i, type: 'USHORT', value: segment.offset}); - if (segment.glyphId !== undefined) { - glyphIds = glyphIds.concat({name: 'glyph_' + i, type: 'USHORT', value: segment.glyphId}); - } - } else { - // Skip Unicode > 65535 (16bit unsigned max) for CMAP 4, will be added in CMAP 12 - segCountToRemove += 1; - } + var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers - // CMAP 12 - // Skip Terminator Segment - if (!isPlan0Only && segment.glyphIndex !== undefined) { - cmap12Groups = cmap12Groups.concat({name: 'cmap12Start_' + i, type: 'ULONG', value: segment.start}); - cmap12Groups = cmap12Groups.concat({name: 'cmap12End_' + i, type: 'ULONG', value: segment.end}); - cmap12Groups = cmap12Groups.concat({name: 'cmap12Glyph_' + i, type: 'ULONG', value: segment.glyphIndex}); - } - } + window.addEventListener('error', handleWindowError); + fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function + // errors, it will trigger our global error handler. - // CMAP 4 Subtable - t.segCountX2 = (segCount - segCountToRemove) * 2; - t.searchRange = Math.pow(2, Math.floor(Math.log((segCount - segCountToRemove)) / Math.log(2))) * 2; - t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2); - t.rangeShift = t.segCountX2 - t.searchRange; - - t.fields = t.fields.concat(endCounts); - t.fields.push({name: 'reservedPad', type: 'USHORT', value: 0}); - t.fields = t.fields.concat(startCounts); - t.fields = t.fields.concat(idDeltas); - t.fields = t.fields.concat(idRangeOffsets); - t.fields = t.fields.concat(glyphIds); - - t.cmap4Length = 14 + // Subtable header - endCounts.length * 2 + - 2 + // reservedPad - startCounts.length * 2 + - idDeltas.length * 2 + - idRangeOffsets.length * 2 + - glyphIds.length * 2; - - if (!isPlan0Only) { - // CMAP 12 Subtable - var cmap12Length = 16 + // Subtable header - cmap12Groups.length * 4; - - t.cmap12Offset = 12 + (2 * 2) + 4 + t.cmap4Length; - t.fields = t.fields.concat([ - {name: 'cmap12Format', type: 'USHORT', value: 12}, - {name: 'cmap12Reserved', type: 'USHORT', value: 0}, - {name: 'cmap12Length', type: 'ULONG', value: cmap12Length}, - {name: 'cmap12Language', type: 'ULONG', value: 0}, - {name: 'cmap12nGroups', type: 'ULONG', value: cmap12Groups.length / 3} - ]); - - t.fields = t.fields.concat(cmap12Groups); - } + evt.initEvent(evtType, false, false); + fakeNode.dispatchEvent(evt); - return t; -} - -var cmap = { parse: parseCmapTable, make: makeCmapTable }; - -// Glyph encoding - -var cffStandardStrings = [ - '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', - 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', - 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', - 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', - 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', - 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', - 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', - 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', - 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', - 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', - 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', - 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', - 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', - 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', - 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', - 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', - 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', - 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', - 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', - 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', - 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', - 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', - 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff', 'onedotenleader', - 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', - 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior', - 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', - 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl', - 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', - 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', - 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', - 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', - 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', - 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', - 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', - 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', - 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', - 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', - 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', - 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', - 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', - 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', - 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000', - '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold']; - -var cffStandardEncoding = [ - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', - 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', - 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', - 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', - 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', - 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', - 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', - 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', - 'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', - 'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde', - 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron', - 'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '', - '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '', - 'lslash', 'oslash', 'oe', 'germandbls']; - -var cffExpertEncoding = [ - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior', - 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', - 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', - 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', - 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior', - 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', - 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', - 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', - 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', - 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', - 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', - 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior', - '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', - 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', - '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', - 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', - 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', - 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', - 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', - 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', - 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', - 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', - 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall']; - -var standardNames = [ - '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', - 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', - 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', - 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', - 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', - 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', - 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', - 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', - 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', - 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', - 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', - 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', - 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', - 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', - 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', - 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', - 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', - 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', - 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', - 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth', - 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior', - 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla', - 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat']; + if (windowEventDescriptor) { + Object.defineProperty(window, 'event', windowEventDescriptor); + } -/** - * This is the encoding used for fonts created from scratch. - * It loops through all glyphs and finds the appropriate unicode value. - * Since it's linear time, other encodings will be faster. - * @exports opentype.DefaultEncoding - * @class - * @constructor - * @param {opentype.Font} - */ -function DefaultEncoding(font) { - this.font = font; -} - -DefaultEncoding.prototype.charToGlyphIndex = function(c) { - var code = c.codePointAt(0); - var glyphs = this.font.glyphs; - if (glyphs) { - for (var i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs.get(i); - for (var j = 0; j < glyph.unicodes.length; j += 1) { - if (glyph.unicodes[j] === code) { - return i; - } - } - } - } - return null; -}; + if (didCall && didError) { + if (!didSetError) { + // The callback errored, but the error event never fired. + // eslint-disable-next-line react-internal/prod-error-codes + error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); + } else if (isCrossOriginError) { + // eslint-disable-next-line react-internal/prod-error-codes + error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.'); + } -/** - * @exports opentype.CffEncoding - * @class - * @constructor - * @param {string} encoding - The encoding - * @param {Array} charset - The character set. - */ -function CffEncoding(encoding, charset) { - this.encoding = encoding; - this.charset = charset; -} + this.onError(error); + } // Remove our event listeners -/** - * @param {string} s - The character - * @return {number} The index. - */ -CffEncoding.prototype.charToGlyphIndex = function(s) { - var code = s.codePointAt(0); - var charName = this.encoding[code]; - return this.charset.indexOf(charName); -}; -// Drawing utility functions. + window.removeEventListener('error', handleWindowError); -// Draw a line on the given context from point `x1,y1` to point `x2,y2`. -function line(ctx, x1, y1, x2, y2) { - ctx.beginPath(); - ctx.moveTo(x1, y1); - ctx.lineTo(x2, y2); - ctx.stroke(); -} + if (!didCall) { + // Something went really wrong, and our event was not dispatched. + // https://github.com/facebook/react/issues/16734 + // https://github.com/facebook/react/issues/16585 + // Fall back to the production implementation. + restoreAfterDispatch(); + return invokeGuardedCallbackProd.apply(this, arguments); + } + }; + } + } -var draw = { line: line }; + var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; -// The Glyph object -// import glyf from './tables/glyf' Can't be imported here, because it's a circular dependency + var hasError = false; + var caughtError = null; // Used by event system to capture/rethrow the first error. + var reporter = { + onError: function (error) { + hasError = true; + caughtError = error; + } + }; + /** + * Call a function while guarding against errors that happens within it. + * Returns an error if it throws, otherwise null. + * + * In production, this is implemented using a try-catch. The reason we don't + * use a try-catch directly is so that we can swap out a different + * implementation in DEV mode. + * + * @param {String} name of the guard to use for logging or debugging + * @param {Function} func The function to invoke + * @param {*} context The context to use when calling the function + * @param {...*} args Arguments for function + */ -function getPathDefinition(glyph, path) { - var _path = path || new Path(); - return { - configurable: true, + function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { + hasError = false; + caughtError = null; + invokeGuardedCallbackImpl$1.apply(reporter, arguments); + } + function hasCaughtError() { + return hasError; + } + function clearCaughtError() { + if (hasError) { + var error = caughtError; + hasError = false; + caughtError = null; + return error; + } else { + throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.'); + } + } - get: function() { - if (typeof _path === 'function') { - _path = _path(); - } + var didWarnAboutUndefinedSnapshotBeforeUpdate = null; - return _path; - }, + { + didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); + } // Used during the commit phase to track the state of the Offscreen component stack. + // Allows us to avoid traversing the return path to find the nearest Offscreen ancestor. + // Only used when enableSuspenseLayoutEffectSemantics is enabled. - set: function(p) { - _path = p; - } - }; -} -/** - * @typedef GlyphOptions - * @type Object - * @property {string} [name] - The glyph name - * @property {number} [unicode] - * @property {Array} [unicodes] - * @property {number} [xMin] - * @property {number} [yMin] - * @property {number} [xMax] - * @property {number} [yMax] - * @property {number} [advanceWidth] - */ -// A Glyph is an individual mark that often corresponds to a character. -// Some glyphs, such as ligatures, are a combination of many characters. -// Glyphs are the basic building blocks of a font. -// -// The `Glyph` class contains utility methods for drawing the path and its points. -/** - * @exports opentype.Glyph - * @class - * @param {GlyphOptions} - * @constructor - */ -function Glyph(options) { - // By putting all the code on a prototype function (which is only declared once) - // we reduce the memory requirements for larger fonts by some 2% - this.bindConstructorValues(options); -} + var offscreenSubtreeIsHidden = false; + var offscreenSubtreeWasHidden = false; + var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; + var nextEffect = null; // Used for Profiling builds to track updaters. -/** - * @param {GlyphOptions} - */ -Glyph.prototype.bindConstructorValues = function(options) { - this.index = options.index || 0; - - // These three values cannot be deferred for memory optimization: - this.name = options.name || null; - this.unicode = options.unicode || undefined; - this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : []; - - // But by binding these values only when necessary, we reduce can - // the memory requirements by almost 3% for larger fonts. - if ('xMin' in options) { - this.xMin = options.xMin; - } + var inProgressLanes = null; + var inProgressRoot = null; - if ('yMin' in options) { - this.yMin = options.yMin; - } + function reportUncaughtErrorInDEV(error) { + // Wrapping each small part of the commit phase into a guarded + // callback is a bit too slow (https://github.com/facebook/react/pull/21666). + // But we rely on it to surface errors to DEV tools like overlays + // (https://github.com/facebook/react/issues/21712). + // As a compromise, rethrow only caught errors in a guard. + { + invokeGuardedCallback(null, function () { + throw error; + }); + clearCaughtError(); + } + } - if ('xMax' in options) { - this.xMax = options.xMax; - } + var callComponentWillUnmountWithTimer = function (current, instance) { + instance.props = current.memoizedProps; + instance.state = current.memoizedState; - if ('yMax' in options) { - this.yMax = options.yMax; - } + if ( current.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentWillUnmount(); + } finally { + recordLayoutEffectDuration(current); + } + } else { + instance.componentWillUnmount(); + } + }; // Capture errors so they don't interrupt mounting. - if ('advanceWidth' in options) { - this.advanceWidth = options.advanceWidth; - } - // The path for a glyph is the most memory intensive, and is bound as a value - // with a getter/setter to ensure we actually do path parsing only once the - // path is actually needed by anything. - Object.defineProperty(this, 'path', getPathDefinition(this, options.path)); -}; + function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) { + try { + commitHookEffectListMount(Layout, current); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } // Capture errors so they don't interrupt unmounting. -/** - * @param {number} - */ -Glyph.prototype.addUnicode = function(unicode) { - if (this.unicodes.length === 0) { - this.unicode = unicode; - } - this.unicodes.push(unicode); -}; + function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) { + try { + callComponentWillUnmountWithTimer(current, instance); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } // Capture errors so they don't interrupt mounting. -/** - * Calculate the minimum bounding box for this glyph. - * @return {opentype.BoundingBox} - */ -Glyph.prototype.getBoundingBox = function() { - return this.path.getBoundingBox(); -}; -/** - * Convert the glyph to a Path we can draw on a drawing context. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {Object=} options - xScale, yScale to stretch the glyph. - * @param {opentype.Font} if hinting is to be used, the font - * @return {opentype.Path} - */ -Glyph.prototype.getPath = function(x, y, fontSize, options, font) { - x = x !== undefined ? x : 0; - y = y !== undefined ? y : 0; - fontSize = fontSize !== undefined ? fontSize : 72; - var commands; - var hPoints; - if (!options) { options = { }; } - var xScale = options.xScale; - var yScale = options.yScale; - - if (options.hinting && font && font.hinting) { - // in case of hinting, the hinting engine takes care - // of scaling the points (not the path) before hinting. - hPoints = this.path && font.hinting.exec(this, fontSize); - // in case the hinting engine failed hPoints is undefined - // and thus reverts to plain rending - } + function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) { + try { + instance.componentDidMount(); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } // Capture errors so they don't interrupt mounting. - if (hPoints) { - // Call font.hinting.getCommands instead of `glyf.getPath(hPoints).commands` to avoid a circular dependency - commands = font.hinting.getCommands(hPoints); - x = Math.round(x); - y = Math.round(y); - // TODO in case of hinting xyScaling is not yet supported - xScale = yScale = 1; - } else { - commands = this.path.commands; - var scale = 1 / (this.path.unitsPerEm || 1000) * fontSize; - if (xScale === undefined) { xScale = scale; } - if (yScale === undefined) { yScale = scale; } - } - var p = new Path(); - for (var i = 0; i < commands.length; i += 1) { - var cmd = commands[i]; - if (cmd.type === 'M') { - p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); - } else if (cmd.type === 'L') { - p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); - } else if (cmd.type === 'Q') { - p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), - x + (cmd.x * xScale), y + (-cmd.y * yScale)); - } else if (cmd.type === 'C') { - p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), - x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale), - x + (cmd.x * xScale), y + (-cmd.y * yScale)); - } else if (cmd.type === 'Z') { - p.closePath(); - } - } + function safelyAttachRef(current, nearestMountedAncestor) { + try { + commitAttachRef(current); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } - return p; -}; + function safelyDetachRef(current, nearestMountedAncestor) { + var ref = current.ref; -/** - * Split the glyph into contours. - * This function is here for backwards compatibility, and to - * provide raw access to the TrueType glyph outlines. - * @return {Array} - */ -Glyph.prototype.getContours = function() { - if (this.points === undefined) { - return []; - } + if (ref !== null) { + if (typeof ref === 'function') { + var retVal; - var contours = []; - var currentContour = []; - for (var i = 0; i < this.points.length; i += 1) { - var pt = this.points[i]; - currentContour.push(pt); - if (pt.lastPointOfContour) { - contours.push(currentContour); - currentContour = []; - } - } + try { + if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + retVal = ref(null); + } finally { + recordLayoutEffectDuration(current); + } + } else { + retVal = ref(null); + } + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } - check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); - return contours; -}; + { + if (typeof retVal === 'function') { + error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current)); + } + } + } else { + ref.current = null; + } + } + } -/** - * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph. - * @return {Object} - */ -Glyph.prototype.getMetrics = function() { - var commands = this.path.commands; - var xCoords = []; - var yCoords = []; - for (var i = 0; i < commands.length; i += 1) { - var cmd = commands[i]; - if (cmd.type !== 'Z') { - xCoords.push(cmd.x); - yCoords.push(cmd.y); - } + function safelyCallDestroy(current, nearestMountedAncestor, destroy) { + try { + destroy(); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(current, nearestMountedAncestor, error); + } + } + var shouldFireAfterActiveInstanceBlur = false; + function commitBeforeMutationEffects(root, firstChild) { + prepareForCommit(root.containerInfo); + nextEffect = firstChild; + commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber - if (cmd.type === 'Q' || cmd.type === 'C') { - xCoords.push(cmd.x1); - yCoords.push(cmd.y1); - } + var shouldFire = shouldFireAfterActiveInstanceBlur; + shouldFireAfterActiveInstanceBlur = false; + return shouldFire; + } - if (cmd.type === 'C') { - xCoords.push(cmd.x2); - yCoords.push(cmd.y2); - } - } + function commitBeforeMutationEffects_begin() { + while (nextEffect !== null) { + var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur. - var metrics = { - xMin: Math.min.apply(null, xCoords), - yMin: Math.min.apply(null, yCoords), - xMax: Math.max.apply(null, xCoords), - yMax: Math.max.apply(null, yCoords), - leftSideBearing: this.leftSideBearing - }; + var child = fiber.child; - if (!isFinite(metrics.xMin)) { - metrics.xMin = 0; - } + if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) { + ensureCorrectReturnPointer(child, fiber); + nextEffect = child; + } else { + commitBeforeMutationEffects_complete(); + } + } + } - if (!isFinite(metrics.xMax)) { - metrics.xMax = this.advanceWidth; - } + function commitBeforeMutationEffects_complete() { + while (nextEffect !== null) { + var fiber = nextEffect; + setCurrentFiber(fiber); - if (!isFinite(metrics.yMin)) { - metrics.yMin = 0; - } + try { + commitBeforeMutationEffectsOnFiber(fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - if (!isFinite(metrics.yMax)) { - metrics.yMax = 0; - } + resetCurrentFiber(); + var sibling = fiber.sibling; - metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); - return metrics; -}; + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } -/** - * Draw the glyph on the given context. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {Object=} options - xScale, yScale to stretch the glyph. - */ -Glyph.prototype.draw = function(ctx, x, y, fontSize, options) { - this.getPath(x, y, fontSize, options).draw(ctx); -}; + nextEffect = fiber.return; + } + } -/** - * Draw the points of the glyph. - * On-curve points will be drawn in blue, off-curve points will be drawn in red. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - */ -Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) { - function drawCircles(l, x, y, scale) { - ctx.beginPath(); - for (var j = 0; j < l.length; j += 1) { - ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale)); - ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, Math.PI * 2, false); - } + function commitBeforeMutationEffectsOnFiber(finishedWork) { + var current = finishedWork.alternate; + var flags = finishedWork.flags; - ctx.closePath(); - ctx.fill(); - } + if ((flags & Snapshot) !== NoFlags) { + setCurrentFiber(finishedWork); - x = x !== undefined ? x : 0; - y = y !== undefined ? y : 0; - fontSize = fontSize !== undefined ? fontSize : 24; - var scale = 1 / this.path.unitsPerEm * fontSize; - - var blueCircles = []; - var redCircles = []; - var path = this.path; - for (var i = 0; i < path.commands.length; i += 1) { - var cmd = path.commands[i]; - if (cmd.x !== undefined) { - blueCircles.push({x: cmd.x, y: -cmd.y}); - } + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + break; + } - if (cmd.x1 !== undefined) { - redCircles.push({x: cmd.x1, y: -cmd.y1}); - } + case ClassComponent: + { + if (current !== null) { + var prevProps = current.memoizedProps; + var prevState = current.memoizedState; + var instance = finishedWork.stateNode; // We could update instance props and state here, + // but instead we rely on them being set during last render. + // TODO: revisit this when we implement resuming. - if (cmd.x2 !== undefined) { - redCircles.push({x: cmd.x2, y: -cmd.y2}); - } - } + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + + if (instance.state !== finishedWork.memoizedState) { + error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + } + } - ctx.fillStyle = 'blue'; - drawCircles(blueCircles, x, y, scale); - ctx.fillStyle = 'red'; - drawCircles(redCircles, x, y, scale); -}; + var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState); -/** - * Draw lines indicating important font measurements. - * Black lines indicate the origin of the coordinate system (point 0,0). - * Blue lines indicate the glyph bounding box. - * Green line indicates the advance width of the glyph. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - */ -Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) { - var scale; - x = x !== undefined ? x : 0; - y = y !== undefined ? y : 0; - fontSize = fontSize !== undefined ? fontSize : 24; - scale = 1 / this.path.unitsPerEm * fontSize; - ctx.lineWidth = 1; - - // Draw the origin - ctx.strokeStyle = 'black'; - draw.line(ctx, x, -10000, x, 10000); - draw.line(ctx, -10000, y, 10000, y); - - // This code is here due to memory optimization: by not using - // defaults in the constructor, we save a notable amount of memory. - var xMin = this.xMin || 0; - var yMin = this.yMin || 0; - var xMax = this.xMax || 0; - var yMax = this.yMax || 0; - var advanceWidth = this.advanceWidth || 0; - - // Draw the glyph box - ctx.strokeStyle = 'blue'; - draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000); - draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000); - draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale)); - draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale)); - - // Draw the advance width - ctx.strokeStyle = 'green'; - draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000); -}; + { + var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; -// The GlyphSet object + if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { + didWarnSet.add(finishedWork.type); -// Define a property on the glyph that depends on the path being loaded. -function defineDependentProperty(glyph, externalName, internalName) { - Object.defineProperty(glyph, externalName, { - get: function() { - // Request the path property to make sure the path is loaded. - glyph.path; // jshint ignore:line - return glyph[internalName]; - }, - set: function(newValue) { - glyph[internalName] = newValue; - }, - enumerable: true, - configurable: true - }); -} + error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork)); + } + } -/** - * A GlyphSet represents all glyphs available in the font, but modelled using - * a deferred glyph loader, for retrieving glyphs only once they are absolutely - * necessary, to keep the memory footprint down. - * @exports opentype.GlyphSet - * @class - * @param {opentype.Font} - * @param {Array} - */ -function GlyphSet(font, glyphs) { - this.font = font; - this.glyphs = {}; - if (Array.isArray(glyphs)) { - for (var i = 0; i < glyphs.length; i++) { - var glyph = glyphs[i]; - glyph.path.unitsPerEm = font.unitsPerEm; - this.glyphs[i] = glyph; - } - } + instance.__reactInternalSnapshotBeforeUpdate = snapshot; + } - this.length = (glyphs && glyphs.length) || 0; -} + break; + } -/** - * @param {number} index - * @return {opentype.Glyph} - */ -GlyphSet.prototype.get = function(index) { - // this.glyphs[index] is 'undefined' when low memory mode is on. glyph is pushed on request only. - if (this.glyphs[index] === undefined) { - this.font._push(index); - if (typeof this.glyphs[index] === 'function') { - this.glyphs[index] = this.glyphs[index](); - } + case HostRoot: + { + if (supportsMutation) { + var root = finishedWork.stateNode; + clearContainer(root.containerInfo); + } - var glyph = this.glyphs[index]; - var unicodeObj = this.font._IndexToUnicodeMap[index]; + break; + } - if (unicodeObj) { - for (var j = 0; j < unicodeObj.unicodes.length; j++) - { glyph.addUnicode(unicodeObj.unicodes[j]); } - } + case HostComponent: + case HostText: + case HostPortal: + case IncompleteClassComponent: + // Nothing to do for these component types + break; - if (this.font.cffEncoding) { - if (this.font.isCIDFont) { - glyph.name = 'gid' + index; - } else { - glyph.name = this.font.cffEncoding.charset[index]; - } - } else if (this.font.glyphNames.names) { - glyph.name = this.font.glyphNames.glyphIndexToName(index); - } + default: + { + throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); + } + } - this.glyphs[index].advanceWidth = this.font._hmtxTableData[index].advanceWidth; - this.glyphs[index].leftSideBearing = this.font._hmtxTableData[index].leftSideBearing; - } else { - if (typeof this.glyphs[index] === 'function') { - this.glyphs[index] = this.glyphs[index](); - } - } + resetCurrentFiber(); + } + } - return this.glyphs[index]; -}; + function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) { + var updateQueue = finishedWork.updateQueue; + var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; -/** - * @param {number} index - * @param {Object} - */ -GlyphSet.prototype.push = function(index, loader) { - this.glyphs[index] = loader; - this.length++; -}; + if (lastEffect !== null) { + var firstEffect = lastEffect.next; + var effect = firstEffect; -/** - * @alias opentype.glyphLoader - * @param {opentype.Font} font - * @param {number} index - * @return {opentype.Glyph} - */ -function glyphLoader(font, index) { - return new Glyph({index: index, font: font}); -} + do { + if ((effect.tag & flags) === flags) { + // Unmount + var destroy = effect.destroy; + effect.destroy = undefined; -/** - * Generate a stub glyph that can be filled with all metadata *except* - * the "points" and "path" properties, which must be loaded only once - * the glyph's path is actually requested for text shaping. - * @alias opentype.ttfGlyphLoader - * @param {opentype.Font} font - * @param {number} index - * @param {Function} parseGlyph - * @param {Object} data - * @param {number} position - * @param {Function} buildPath - * @return {opentype.Glyph} - */ -function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) { - return function() { - var glyph = new Glyph({index: index, font: font}); + if (destroy !== undefined) { + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectUnmountStarted(finishedWork); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectUnmountStarted(finishedWork); + } + } - glyph.path = function() { - parseGlyph(glyph, data, position); - var path = buildPath(font.glyphs, glyph); - path.unitsPerEm = font.unitsPerEm; - return path; - }; + safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); - defineDependentProperty(glyph, 'xMin', '_xMin'); - defineDependentProperty(glyph, 'xMax', '_xMax'); - defineDependentProperty(glyph, 'yMin', '_yMin'); - defineDependentProperty(glyph, 'yMax', '_yMax'); + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectUnmountStopped(); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectUnmountStopped(); + } + } + } + } - return glyph; - }; -} -/** - * @alias opentype.cffGlyphLoader - * @param {opentype.Font} font - * @param {number} index - * @param {Function} parseCFFCharstring - * @param {string} charstring - * @return {opentype.Glyph} - */ -function cffGlyphLoader(font, index, parseCFFCharstring, charstring) { - return function() { - var glyph = new Glyph({index: index, font: font}); + effect = effect.next; + } while (effect !== firstEffect); + } + } - glyph.path = function() { - var path = parseCFFCharstring(font, glyph, charstring); - path.unitsPerEm = font.unitsPerEm; - return path; - }; + function commitHookEffectListMount(flags, finishedWork) { + var updateQueue = finishedWork.updateQueue; + var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - return glyph; - }; -} + if (lastEffect !== null) { + var firstEffect = lastEffect.next; + var effect = firstEffect; -var glyphset = { GlyphSet: GlyphSet, glyphLoader: glyphLoader, ttfGlyphLoader: ttfGlyphLoader, cffGlyphLoader: cffGlyphLoader }; + do { + if ((effect.tag & flags) === flags) { + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectMountStarted(finishedWork); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectMountStarted(finishedWork); + } + } // Mount -// The `CFF` table contains the glyph outlines in PostScript format. -// Custom equals function that can also check lists. -function equals(a, b) { - if (a === b) { - return true; - } else if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return false; - } + var create = effect.create; + effect.destroy = create(); - for (var i = 0; i < a.length; i += 1) { - if (!equals(a[i], b[i])) { - return false; - } - } + { + if ((flags & Passive$1) !== NoFlags$1) { + markComponentPassiveEffectMountStopped(); + } else if ((flags & Layout) !== NoFlags$1) { + markComponentLayoutEffectMountStopped(); + } + } - return true; - } else { - return false; - } -} + { + var destroy = effect.destroy; -// Subroutines are encoded using the negative half of the number space. -// See type 2 chapter 4.7 "Subroutine operators". -function calcCFFSubroutineBias(subrs) { - var bias; - if (subrs.length < 1240) { - bias = 107; - } else if (subrs.length < 33900) { - bias = 1131; - } else { - bias = 32768; - } + if (destroy !== undefined && typeof destroy !== 'function') { + var hookName = void 0; - return bias; -} - -// Parse a `CFF` INDEX array. -// An index array consists of a list of offsets, then a list of objects at those offsets. -function parseCFFIndex(data, start, conversionFn) { - var offsets = []; - var objects = []; - var count = parse.getCard16(data, start); - var objectOffset; - var endOffset; - if (count !== 0) { - var offsetSize = parse.getByte(data, start + 2); - objectOffset = start + ((count + 1) * offsetSize) + 2; - var pos = start + 3; - for (var i = 0; i < count + 1; i += 1) { - offsets.push(parse.getOffset(data, pos, offsetSize)); - pos += offsetSize; - } + if ((effect.tag & Layout) !== NoFlags) { + hookName = 'useLayoutEffect'; + } else if ((effect.tag & Insertion) !== NoFlags) { + hookName = 'useInsertionEffect'; + } else { + hookName = 'useEffect'; + } - // The total size of the index array is 4 header bytes + the value of the last offset. - endOffset = objectOffset + offsets[count]; - } else { - endOffset = start + 2; - } + var addendum = void 0; - for (var i$1 = 0; i$1 < offsets.length - 1; i$1 += 1) { - var value = parse.getBytes(data, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]); - if (conversionFn) { - value = conversionFn(value); - } + if (destroy === null) { + addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).'; + } else if (typeof destroy.then === 'function') { + addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching'; + } else { + addendum = ' You returned: ' + destroy; + } - objects.push(value); - } + error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum); + } + } + } - return {objects: objects, startOffset: start, endOffset: endOffset}; -} - -function parseCFFIndexLowMemory(data, start) { - var offsets = []; - var count = parse.getCard16(data, start); - var objectOffset; - var endOffset; - if (count !== 0) { - var offsetSize = parse.getByte(data, start + 2); - objectOffset = start + ((count + 1) * offsetSize) + 2; - var pos = start + 3; - for (var i = 0; i < count + 1; i += 1) { - offsets.push(parse.getOffset(data, pos, offsetSize)); - pos += offsetSize; - } + effect = effect.next; + } while (effect !== firstEffect); + } + } - // The total size of the index array is 4 header bytes + the value of the last offset. - endOffset = objectOffset + offsets[count]; - } else { - endOffset = start + 2; - } + function commitPassiveEffectDurations(finishedRoot, finishedWork) { + { + // Only Profilers with work in their subtree will have an Update effect scheduled. + if ((finishedWork.flags & Update) !== NoFlags) { + switch (finishedWork.tag) { + case Profiler: + { + var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration; + var _finishedWork$memoize = finishedWork.memoizedProps, + id = _finishedWork$memoize.id, + onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase. + // It does not get reset until the start of the next commit phase. - return {offsets: offsets, startOffset: start, endOffset: endOffset}; -} -function getCffIndexObject(i, offsets, data, start, conversionFn) { - var count = parse.getCard16(data, start); - var objectOffset = 0; - if (count !== 0) { - var offsetSize = parse.getByte(data, start + 2); - objectOffset = start + ((count + 1) * offsetSize) + 2; - } + var commitTime = getCommitTime(); + var phase = finishedWork.alternate === null ? 'mount' : 'update'; - var value = parse.getBytes(data, objectOffset + offsets[i], objectOffset + offsets[i + 1]); - if (conversionFn) { - value = conversionFn(value); - } - return value; -} + { + if (isCurrentUpdateNested()) { + phase = 'nested-update'; + } + } -// Parse a `CFF` DICT real value. -function parseFloatOperand(parser) { - var s = ''; - var eof = 15; - var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-']; - while (true) { - var b = parser.parseByte(); - var n1 = b >> 4; - var n2 = b & 15; + if (typeof onPostCommit === 'function') { + onPostCommit(id, phase, passiveEffectDuration, commitTime); + } // Bubble times to the next nearest ancestor Profiler. + // After we process that Profiler, we'll bubble further up. - if (n1 === eof) { - break; - } - s += lookup[n1]; + var parentFiber = finishedWork.return; - if (n2 === eof) { - break; - } + outer: while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + root.passiveEffectDuration += passiveEffectDuration; + break outer; - s += lookup[n2]; - } + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.passiveEffectDuration += passiveEffectDuration; + break outer; + } - return parseFloat(s); -} + parentFiber = parentFiber.return; + } -// Parse a `CFF` DICT operand. -function parseOperand(parser, b0) { - var b1; - var b2; - var b3; - var b4; - if (b0 === 28) { - b1 = parser.parseByte(); - b2 = parser.parseByte(); - return b1 << 8 | b2; - } + break; + } + } + } + } + } - if (b0 === 29) { - b1 = parser.parseByte(); - b2 = parser.parseByte(); - b3 = parser.parseByte(); - b4 = parser.parseByte(); - return b1 << 24 | b2 << 16 | b3 << 8 | b4; - } + function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) { + if ((finishedWork.flags & LayoutMask) !== NoFlags) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( !offscreenSubtreeWasHidden) { + // At this point layout effects have already been destroyed (during mutation phase). + // This is done to prevent sibling component effects from interfering with each other, + // e.g. a destroy function in one component should never override a ref set + // by a create function in another component during the same commit. + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListMount(Layout | HasEffect, finishedWork); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + commitHookEffectListMount(Layout | HasEffect, finishedWork); + } + } - if (b0 === 30) { - return parseFloatOperand(parser); - } + break; + } - if (b0 >= 32 && b0 <= 246) { - return b0 - 139; - } + case ClassComponent: + { + var instance = finishedWork.stateNode; - if (b0 >= 247 && b0 <= 250) { - b1 = parser.parseByte(); - return (b0 - 247) * 256 + b1 + 108; - } + if (finishedWork.flags & Update) { + if (!offscreenSubtreeWasHidden) { + if (current === null) { + // We could update instance props and state here, + // but instead we rely on them being set during last render. + // TODO: revisit this when we implement resuming. + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } - if (b0 >= 251 && b0 <= 254) { - b1 = parser.parseByte(); - return -(b0 - 251) * 256 - b1 - 108; - } + if (instance.state !== finishedWork.memoizedState) { + error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + } + } - throw new Error('Invalid b0 ' + b0); -} + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentDidMount(); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + instance.componentDidMount(); + } + } else { + var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps); + var prevState = current.memoizedState; // We could update instance props and state here, + // but instead we rely on them being set during last render. + // TODO: revisit this when we implement resuming. -// Convert the entries returned by `parseDict` to a proper dictionary. -// If a value is a list of one, it is unpacked. -function entriesToObject(entries) { - var o = {}; - for (var i = 0; i < entries.length; i += 1) { - var key = entries[i][0]; - var values = entries[i][1]; - var value = (void 0); - if (values.length === 1) { - value = values[0]; - } else { - value = values; - } + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } - if (o.hasOwnProperty(key) && !isNaN(o[key])) { - throw new Error('Object ' + o + ' already has key ' + key); - } + if (instance.state !== finishedWork.memoizedState) { + error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + } + } - o[key] = value; - } + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); + } + } + } + } // TODO: I think this is now always non-null by the time it reaches the + // commit phase. Consider removing the type check. - return o; -} -// Parse a `CFF` DICT object. -// A dictionary contains key-value pairs in a compact tokenized format. -function parseCFFDict(data, start, size) { - start = start !== undefined ? start : 0; - var parser = new parse.Parser(data, start); - var entries = []; - var operands = []; - size = size !== undefined ? size : data.length; + var updateQueue = finishedWork.updateQueue; - while (parser.relativeOffset < size) { - var op = parser.parseByte(); + if (updateQueue !== null) { + { + if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { + if (instance.props !== finishedWork.memoizedProps) { + error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } - // The first byte for each dict item distinguishes between operator (key) and operand (value). - // Values <= 21 are operators. - if (op <= 21) { - // Two-byte operators have an initial escape byte of 12. - if (op === 12) { - op = 1200 + parser.parseByte(); - } + if (instance.state !== finishedWork.memoizedState) { + error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); + } + } + } // We could update instance props and state here, + // but instead we rely on them being set during last render. + // TODO: revisit this when we implement resuming. - entries.push([op, operands]); - operands = []; - } else { - // Since the operands (values) come before the operators (keys), we store all operands in a list - // until we encounter an operator. - operands.push(parseOperand(parser, op)); - } - } - return entriesToObject(entries); -} + commitUpdateQueue(finishedWork, updateQueue, instance); + } -// Given a String Index (SID), return the value of the string. -// Strings below index 392 are standard CFF strings and are not encoded in the font. -function getCFFString(strings, index) { - if (index <= 390) { - index = cffStandardStrings[index]; - } else { - index = strings[index - 391]; - } + break; + } - return index; -} + case HostRoot: + { + // TODO: I think this is now always non-null by the time it reaches the + // commit phase. Consider removing the type check. + var _updateQueue = finishedWork.updateQueue; -// Interpret a dictionary and return a new dictionary with readable keys and values for missing entries. -// This function takes `meta` which is a list of objects containing `operand`, `name` and `default`. -function interpretDict(dict, meta, strings) { - var newDict = {}; - var value; + if (_updateQueue !== null) { + var _instance = null; - // Because we also want to include missing values, we start out from the meta list - // and lookup values in the dict. - for (var i = 0; i < meta.length; i += 1) { - var m = meta[i]; + if (finishedWork.child !== null) { + switch (finishedWork.child.tag) { + case HostComponent: + _instance = getPublicInstance(finishedWork.child.stateNode); + break; - if (Array.isArray(m.type)) { - var values = []; - values.length = m.type.length; - for (var j = 0; j < m.type.length; j++) { - value = dict[m.op] !== undefined ? dict[m.op][j] : undefined; - if (value === undefined) { - value = m.value !== undefined && m.value[j] !== undefined ? m.value[j] : null; - } - if (m.type[j] === 'SID') { - value = getCFFString(strings, value); - } - values[j] = value; - } - newDict[m.name] = values; - } else { - value = dict[m.op]; - if (value === undefined) { - value = m.value !== undefined ? m.value : null; - } + case ClassComponent: + _instance = finishedWork.child.stateNode; + break; + } + } - if (m.type === 'SID') { - value = getCFFString(strings, value); - } - newDict[m.name] = value; - } - } + commitUpdateQueue(finishedWork, _updateQueue, _instance); + } - return newDict; -} - -// Parse the CFF header. -function parseCFFHeader(data, start) { - var header = {}; - header.formatMajor = parse.getCard8(data, start); - header.formatMinor = parse.getCard8(data, start + 1); - header.size = parse.getCard8(data, start + 2); - header.offsetSize = parse.getCard8(data, start + 3); - header.startOffset = start; - header.endOffset = start + 4; - return header; -} - -var TOP_DICT_META = [ - {name: 'version', op: 0, type: 'SID'}, - {name: 'notice', op: 1, type: 'SID'}, - {name: 'copyright', op: 1200, type: 'SID'}, - {name: 'fullName', op: 2, type: 'SID'}, - {name: 'familyName', op: 3, type: 'SID'}, - {name: 'weight', op: 4, type: 'SID'}, - {name: 'isFixedPitch', op: 1201, type: 'number', value: 0}, - {name: 'italicAngle', op: 1202, type: 'number', value: 0}, - {name: 'underlinePosition', op: 1203, type: 'number', value: -100}, - {name: 'underlineThickness', op: 1204, type: 'number', value: 50}, - {name: 'paintType', op: 1205, type: 'number', value: 0}, - {name: 'charstringType', op: 1206, type: 'number', value: 2}, - { - name: 'fontMatrix', - op: 1207, - type: ['real', 'real', 'real', 'real', 'real', 'real'], - value: [0.001, 0, 0, 0.001, 0, 0] - }, - {name: 'uniqueId', op: 13, type: 'number'}, - {name: 'fontBBox', op: 5, type: ['number', 'number', 'number', 'number'], value: [0, 0, 0, 0]}, - {name: 'strokeWidth', op: 1208, type: 'number', value: 0}, - {name: 'xuid', op: 14, type: [], value: null}, - {name: 'charset', op: 15, type: 'offset', value: 0}, - {name: 'encoding', op: 16, type: 'offset', value: 0}, - {name: 'charStrings', op: 17, type: 'offset', value: 0}, - {name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0]}, - {name: 'ros', op: 1230, type: ['SID', 'SID', 'number']}, - {name: 'cidFontVersion', op: 1231, type: 'number', value: 0}, - {name: 'cidFontRevision', op: 1232, type: 'number', value: 0}, - {name: 'cidFontType', op: 1233, type: 'number', value: 0}, - {name: 'cidCount', op: 1234, type: 'number', value: 8720}, - {name: 'uidBase', op: 1235, type: 'number'}, - {name: 'fdArray', op: 1236, type: 'offset'}, - {name: 'fdSelect', op: 1237, type: 'offset'}, - {name: 'fontName', op: 1238, type: 'SID'} -]; + break; + } -var PRIVATE_DICT_META = [ - {name: 'subrs', op: 19, type: 'offset', value: 0}, - {name: 'defaultWidthX', op: 20, type: 'number', value: 0}, - {name: 'nominalWidthX', op: 21, type: 'number', value: 0} -]; + case HostComponent: + { + var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted + // (eg DOM renderer may schedule auto-focus for inputs and form controls). + // These effects should only be committed when components are first mounted, + // aka when there is no current/alternate. -// Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary. -// The top dictionary contains the essential metadata for the font, together with the private dictionary. -function parseCFFTopDict(data, strings) { - var dict = parseCFFDict(data, 0, data.byteLength); - return interpretDict(dict, TOP_DICT_META, strings); -} + if (current === null && finishedWork.flags & Update) { + var type = finishedWork.type; + var props = finishedWork.memoizedProps; + commitMount(_instance2, type, props, finishedWork); + } -// Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need. -function parseCFFPrivateDict(data, start, size, strings) { - var dict = parseCFFDict(data, start, size); - return interpretDict(dict, PRIVATE_DICT_META, strings); -} + break; + } -// Returns a list of "Top DICT"s found using an INDEX list. -// Used to read both the usual high-level Top DICTs and also the FDArray -// discovered inside CID-keyed fonts. When a Top DICT has a reference to -// a Private DICT that is read and saved into the Top DICT. -// -// In addition to the expected/optional values as outlined in TOP_DICT_META -// the following values might be saved into the Top DICT. -// -// _subrs [] array of local CFF subroutines from Private DICT -// _subrsBias bias value computed from number of subroutines -// (see calcCFFSubroutineBias() and parseCFFCharstring()) -// _defaultWidthX default widths for CFF characters -// _nominalWidthX bias added to width embedded within glyph description -// -// _privateDict saved copy of parsed Private DICT from Top DICT -function gatherCFFTopDicts(data, start, cffIndex, strings) { - var topDictArray = []; - for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) { - var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer); - var topDict = parseCFFTopDict(topDictData, strings); - topDict._subrs = []; - topDict._subrsBias = 0; - topDict._defaultWidthX = 0; - topDict._nominalWidthX = 0; - var privateSize = topDict.private[0]; - var privateOffset = topDict.private[1]; - if (privateSize !== 0 && privateOffset !== 0) { - var privateDict = parseCFFPrivateDict(data, privateOffset + start, privateSize, strings); - topDict._defaultWidthX = privateDict.defaultWidthX; - topDict._nominalWidthX = privateDict.nominalWidthX; - if (privateDict.subrs !== 0) { - var subrOffset = privateOffset + privateDict.subrs; - var subrIndex = parseCFFIndex(data, subrOffset + start); - topDict._subrs = subrIndex.objects; - topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs); - } - topDict._privateDict = privateDict; - } - topDictArray.push(topDict); - } - return topDictArray; -} - -// Parse the CFF charset table, which contains internal names for all the glyphs. -// This function will return a list of glyph names. -// See Adobe TN #5176 chapter 13, "Charsets". -function parseCFFCharset(data, start, nGlyphs, strings) { - var sid; - var count; - var parser = new parse.Parser(data, start); - - // The .notdef glyph is not included, so subtract 1. - nGlyphs -= 1; - var charset = ['.notdef']; - - var format = parser.parseCard8(); - if (format === 0) { - for (var i = 0; i < nGlyphs; i += 1) { - sid = parser.parseSID(); - charset.push(getCFFString(strings, sid)); - } - } else if (format === 1) { - while (charset.length <= nGlyphs) { - sid = parser.parseSID(); - count = parser.parseCard8(); - for (var i$1 = 0; i$1 <= count; i$1 += 1) { - charset.push(getCFFString(strings, sid)); - sid += 1; - } - } - } else if (format === 2) { - while (charset.length <= nGlyphs) { - sid = parser.parseSID(); - count = parser.parseCard16(); - for (var i$2 = 0; i$2 <= count; i$2 += 1) { - charset.push(getCFFString(strings, sid)); - sid += 1; - } - } - } else { - throw new Error('Unknown charset format ' + format); - } + case HostText: + { + // We have no life-cycles associated with text. + break; + } - return charset; -} - -// Parse the CFF encoding data. Only one encoding can be specified per font. -// See Adobe TN #5176 chapter 12, "Encodings". -function parseCFFEncoding(data, start, charset) { - var code; - var enc = {}; - var parser = new parse.Parser(data, start); - var format = parser.parseCard8(); - if (format === 0) { - var nCodes = parser.parseCard8(); - for (var i = 0; i < nCodes; i += 1) { - code = parser.parseCard8(); - enc[code] = i; - } - } else if (format === 1) { - var nRanges = parser.parseCard8(); - code = 1; - for (var i$1 = 0; i$1 < nRanges; i$1 += 1) { - var first = parser.parseCard8(); - var nLeft = parser.parseCard8(); - for (var j = first; j <= first + nLeft; j += 1) { - enc[j] = code; - code += 1; - } - } - } else { - throw new Error('Unknown encoding format ' + format); - } + case HostPortal: + { + // We have no life-cycles associated with portals. + break; + } - return new CffEncoding(enc, charset); -} - -// Take in charstring code and return a Glyph object. -// The encoding is described in the Type 2 Charstring Format -// https://www.microsoft.com/typography/OTSPEC/charstr2.htm -function parseCFFCharstring(font, glyph, code) { - var c1x; - var c1y; - var c2x; - var c2y; - var p = new Path(); - var stack = []; - var nStems = 0; - var haveWidth = false; - var open = false; - var x = 0; - var y = 0; - var subrs; - var subrsBias; - var defaultWidthX; - var nominalWidthX; - if (font.isCIDFont) { - var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index]; - var fdDict = font.tables.cff.topDict._fdArray[fdIndex]; - subrs = fdDict._subrs; - subrsBias = fdDict._subrsBias; - defaultWidthX = fdDict._defaultWidthX; - nominalWidthX = fdDict._nominalWidthX; - } else { - subrs = font.tables.cff.topDict._subrs; - subrsBias = font.tables.cff.topDict._subrsBias; - defaultWidthX = font.tables.cff.topDict._defaultWidthX; - nominalWidthX = font.tables.cff.topDict._nominalWidthX; - } - var width = defaultWidthX; + case Profiler: + { + { + var _finishedWork$memoize2 = finishedWork.memoizedProps, + onCommit = _finishedWork$memoize2.onCommit, + onRender = _finishedWork$memoize2.onRender; + var effectDuration = finishedWork.stateNode.effectDuration; + var commitTime = getCommitTime(); + var phase = current === null ? 'mount' : 'update'; - function newContour(x, y) { - if (open) { - p.closePath(); - } + { + if (isCurrentUpdateNested()) { + phase = 'nested-update'; + } + } - p.moveTo(x, y); - open = true; - } + if (typeof onRender === 'function') { + onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime); + } - function parseStems() { - var hasWidthArg; + { + if (typeof onCommit === 'function') { + onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime); + } // Schedule a passive effect for this Profiler to call onPostCommit hooks. + // This effect should be scheduled even if there is no onPostCommit callback for this Profiler, + // because the effect is also where times bubble to parent Profilers. - // The number of stem operators on the stack is always even. - // If the value is uneven, that means a width is specified. - hasWidthArg = stack.length % 2 !== 0; - if (hasWidthArg && !haveWidth) { - width = stack.shift() + nominalWidthX; - } - nStems += stack.length >> 1; - stack.length = 0; - haveWidth = true; - } + enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor. + // Do not reset these values until the next render so DevTools has a chance to read them first. - function parse(code) { - var b1; - var b2; - var b3; - var b4; - var codeIndex; - var subrCode; - var jpx; - var jpy; - var c3x; - var c3y; - var c4x; - var c4y; - - var i = 0; - while (i < code.length) { - var v = code[i]; - i += 1; - switch (v) { - case 1: // hstem - parseStems(); - break; - case 3: // vstem - parseStems(); - break; - case 4: // vmoveto - if (stack.length > 1 && !haveWidth) { - width = stack.shift() + nominalWidthX; - haveWidth = true; - } + var parentFiber = finishedWork.return; - y += stack.pop(); - newContour(x, y); - break; - case 5: // rlineto - while (stack.length > 0) { - x += stack.shift(); - y += stack.shift(); - p.lineTo(x, y); - } + outer: while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root = parentFiber.stateNode; + root.effectDuration += effectDuration; + break outer; - break; - case 6: // hlineto - while (stack.length > 0) { - x += stack.shift(); - p.lineTo(x, y); - if (stack.length === 0) { - break; - } - - y += stack.shift(); - p.lineTo(x, y); - } + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.effectDuration += effectDuration; + break outer; + } - break; - case 7: // vlineto - while (stack.length > 0) { - y += stack.shift(); - p.lineTo(x, y); - if (stack.length === 0) { - break; - } - - x += stack.shift(); - p.lineTo(x, y); - } + parentFiber = parentFiber.return; + } + } + } - break; - case 8: // rrcurveto - while (stack.length > 0) { - c1x = x + stack.shift(); - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + stack.shift(); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + break; + } - break; - case 10: // callsubr - codeIndex = stack.pop() + subrsBias; - subrCode = subrs[codeIndex]; - if (subrCode) { - parse(subrCode); - } + case SuspenseComponent: + { + commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); + break; + } - break; - case 11: // return - return; - case 12: // flex operators - v = code[i]; - i += 1; - switch (v) { - case 35: // flex - // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |- - c1x = x + stack.shift(); // dx1 - c1y = y + stack.shift(); // dy1 - c2x = c1x + stack.shift(); // dx2 - c2y = c1y + stack.shift(); // dy2 - jpx = c2x + stack.shift(); // dx3 - jpy = c2y + stack.shift(); // dy3 - c3x = jpx + stack.shift(); // dx4 - c3y = jpy + stack.shift(); // dy4 - c4x = c3x + stack.shift(); // dx5 - c4y = c3y + stack.shift(); // dy5 - x = c4x + stack.shift(); // dx6 - y = c4y + stack.shift(); // dy6 - stack.shift(); // flex depth - p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); - p.curveTo(c3x, c3y, c4x, c4y, x, y); - break; - case 34: // hflex - // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |- - c1x = x + stack.shift(); // dx1 - c1y = y; // dy1 - c2x = c1x + stack.shift(); // dx2 - c2y = c1y + stack.shift(); // dy2 - jpx = c2x + stack.shift(); // dx3 - jpy = c2y; // dy3 - c3x = jpx + stack.shift(); // dx4 - c3y = c2y; // dy4 - c4x = c3x + stack.shift(); // dx5 - c4y = y; // dy5 - x = c4x + stack.shift(); // dx6 - p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); - p.curveTo(c3x, c3y, c4x, c4y, x, y); - break; - case 36: // hflex1 - // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |- - c1x = x + stack.shift(); // dx1 - c1y = y + stack.shift(); // dy1 - c2x = c1x + stack.shift(); // dx2 - c2y = c1y + stack.shift(); // dy2 - jpx = c2x + stack.shift(); // dx3 - jpy = c2y; // dy3 - c3x = jpx + stack.shift(); // dx4 - c3y = c2y; // dy4 - c4x = c3x + stack.shift(); // dx5 - c4y = c3y + stack.shift(); // dy5 - x = c4x + stack.shift(); // dx6 - p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); - p.curveTo(c3x, c3y, c4x, c4y, x, y); - break; - case 37: // flex1 - // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |- - c1x = x + stack.shift(); // dx1 - c1y = y + stack.shift(); // dy1 - c2x = c1x + stack.shift(); // dx2 - c2y = c1y + stack.shift(); // dy2 - jpx = c2x + stack.shift(); // dx3 - jpy = c2y + stack.shift(); // dy3 - c3x = jpx + stack.shift(); // dx4 - c3y = jpy + stack.shift(); // dy4 - c4x = c3x + stack.shift(); // dx5 - c4y = c3y + stack.shift(); // dy5 - if (Math.abs(c4x - x) > Math.abs(c4y - y)) { - x = c4x + stack.shift(); - } else { - y = c4y + stack.shift(); - } - - p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); - p.curveTo(c3x, c3y, c4x, c4y, x, y); - break; - default: - console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v); - stack.length = 0; - } - break; - case 14: // endchar - if (stack.length > 0 && !haveWidth) { - width = stack.shift() + nominalWidthX; - haveWidth = true; - } + case SuspenseListComponent: + case IncompleteClassComponent: + case ScopeComponent: + case OffscreenComponent: + case LegacyHiddenComponent: + { + break; + } - if (open) { - p.closePath(); - open = false; - } + default: + throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); + } + } - break; - case 18: // hstemhm - parseStems(); - break; - case 19: // hintmask - case 20: // cntrmask - parseStems(); - i += (nStems + 7) >> 3; - break; - case 21: // rmoveto - if (stack.length > 2 && !haveWidth) { - width = stack.shift() + nominalWidthX; - haveWidth = true; - } + if ( !offscreenSubtreeWasHidden) { + { + if (finishedWork.flags & Ref) { + commitAttachRef(finishedWork); + } + } + } + } - y += stack.pop(); - x += stack.pop(); - newContour(x, y); - break; - case 22: // hmoveto - if (stack.length > 1 && !haveWidth) { - width = stack.shift() + nominalWidthX; - haveWidth = true; - } + function reappearLayoutEffectsOnFiber(node) { + // Turn on layout effects in a tree that previously disappeared. + // TODO (Offscreen) Check: flags & LayoutStatic + switch (node.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( node.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + safelyCallCommitHookLayoutEffectListMount(node, node.return); + } finally { + recordLayoutEffectDuration(node); + } + } else { + safelyCallCommitHookLayoutEffectListMount(node, node.return); + } - x += stack.pop(); - newContour(x, y); - break; - case 23: // vstemhm - parseStems(); - break; - case 24: // rcurveline - while (stack.length > 2) { - c1x = x + stack.shift(); - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + stack.shift(); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + break; + } - x += stack.shift(); - y += stack.shift(); - p.lineTo(x, y); - break; - case 25: // rlinecurve - while (stack.length > 6) { - x += stack.shift(); - y += stack.shift(); - p.lineTo(x, y); - } + case ClassComponent: + { + var instance = node.stateNode; - c1x = x + stack.shift(); - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + stack.shift(); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - break; - case 26: // vvcurveto - if (stack.length % 2) { - x += stack.shift(); - } + if (typeof instance.componentDidMount === 'function') { + safelyCallComponentDidMount(node, node.return, instance); + } - while (stack.length > 0) { - c1x = x; - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x; - y = c2y + stack.shift(); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + safelyAttachRef(node, node.return); + break; + } - break; - case 27: // hhcurveto - if (stack.length % 2) { - y += stack.shift(); - } + case HostComponent: + { + safelyAttachRef(node, node.return); + break; + } + } + } - while (stack.length > 0) { - c1x = x + stack.shift(); - c1y = y; - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y; - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + function hideOrUnhideAllChildren(finishedWork, isHidden) { + // Only hide or unhide the top-most host nodes. + var hostSubtreeRoot = null; - break; - case 28: // shortint - b1 = code[i]; - b2 = code[i + 1]; - stack.push(((b1 << 24) | (b2 << 16)) >> 16); - i += 2; - break; - case 29: // callgsubr - codeIndex = stack.pop() + font.gsubrsBias; - subrCode = font.gsubrs[codeIndex]; - if (subrCode) { - parse(subrCode); - } + if (supportsMutation) { + // We only have the top Fiber that was inserted but we need to recurse down its + // children to find all the terminal nodes. + var node = finishedWork; - break; - case 30: // vhcurveto - while (stack.length > 0) { - c1x = x; - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + (stack.length === 1 ? stack.shift() : 0); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - if (stack.length === 0) { - break; - } - - c1x = x + stack.shift(); - c1y = y; - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - y = c2y + stack.shift(); - x = c2x + (stack.length === 1 ? stack.shift() : 0); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + while (true) { + if (node.tag === HostComponent) { + if (hostSubtreeRoot === null) { + hostSubtreeRoot = node; + var instance = node.stateNode; - break; - case 31: // hvcurveto - while (stack.length > 0) { - c1x = x + stack.shift(); - c1y = y; - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - y = c2y + stack.shift(); - x = c2x + (stack.length === 1 ? stack.shift() : 0); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - if (stack.length === 0) { - break; - } - - c1x = x; - c1y = y + stack.shift(); - c2x = c1x + stack.shift(); - c2y = c1y + stack.shift(); - x = c2x + stack.shift(); - y = c2y + (stack.length === 1 ? stack.shift() : 0); - p.curveTo(c1x, c1y, c2x, c2y, x, y); - } + if (isHidden) { + hideInstance(instance); + } else { + unhideInstance(node.stateNode, node.memoizedProps); + } + } + } else if (node.tag === HostText) { + if (hostSubtreeRoot === null) { + var _instance3 = node.stateNode; - break; - default: - if (v < 32) { - console.log('Glyph ' + glyph.index + ': unknown operator ' + v); - } else if (v < 247) { - stack.push(v - 139); - } else if (v < 251) { - b1 = code[i]; - i += 1; - stack.push((v - 247) * 256 + b1 + 108); - } else if (v < 255) { - b1 = code[i]; - i += 1; - stack.push(-(v - 251) * 256 - b1 - 108); - } else { - b1 = code[i]; - b2 = code[i + 1]; - b3 = code[i + 2]; - b4 = code[i + 3]; - i += 4; - stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536); - } - } - } - } + if (isHidden) { + hideTextInstance(_instance3); + } else { + unhideTextInstance(_instance3, node.memoizedProps); + } + } + } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } - parse(code); + if (node === finishedWork) { + return; + } - glyph.advanceWidth = width; - return p; -} + while (node.sibling === null) { + if (node.return === null || node.return === finishedWork) { + return; + } -function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) { - var fdSelect = []; - var fdIndex; - var parser = new parse.Parser(data, start); - var format = parser.parseCard8(); - if (format === 0) { - // Simple list of nGlyphs elements - for (var iGid = 0; iGid < nGlyphs; iGid++) { - fdIndex = parser.parseCard8(); - if (fdIndex >= fdArrayCount) { - throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); - } - fdSelect.push(fdIndex); - } - } else if (format === 3) { - // Ranges - var nRanges = parser.parseCard16(); - var first = parser.parseCard16(); - if (first !== 0) { - throw new Error('CFF Table CID Font FDSelect format 3 range has bad initial GID ' + first); - } - var next; - for (var iRange = 0; iRange < nRanges; iRange++) { - fdIndex = parser.parseCard8(); - next = parser.parseCard16(); - if (fdIndex >= fdArrayCount) { - throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); - } - if (next > nGlyphs) { - throw new Error('CFF Table CID Font FDSelect format 3 range has bad GID ' + next); - } - for (; first < next; first++) { - fdSelect.push(fdIndex); - } - first = next; - } - if (next !== nGlyphs) { - throw new Error('CFF Table CID Font FDSelect format 3 range has bad final GID ' + next); - } - } else { - throw new Error('CFF Table CID Font FDSelect table has unsupported format ' + format); - } - return fdSelect; -} - -// Parse the `CFF` table, which contains the glyph outlines in PostScript format. -function parseCFFTable(data, start, font, opt) { - font.tables.cff = {}; - var header = parseCFFHeader(data, start); - var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString); - var topDictIndex = parseCFFIndex(data, nameIndex.endOffset); - var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString); - var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset); - font.gsubrs = globalSubrIndex.objects; - font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); - - var topDictArray = gatherCFFTopDicts(data, start, topDictIndex.objects, stringIndex.objects); - if (topDictArray.length !== 1) { - throw new Error('CFF table has too many fonts in \'FontSet\' - count of fonts NameIndex.length = ' + topDictArray.length); - } + if (hostSubtreeRoot === node) { + hostSubtreeRoot = null; + } - var topDict = topDictArray[0]; - font.tables.cff.topDict = topDict; + node = node.return; + } - if (topDict._privateDict) { - font.defaultWidthX = topDict._privateDict.defaultWidthX; - font.nominalWidthX = topDict._privateDict.nominalWidthX; - } + if (hostSubtreeRoot === node) { + hostSubtreeRoot = null; + } - if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) { - font.isCIDFont = true; - } + node.sibling.return = node.return; + node = node.sibling; + } + } + } - if (font.isCIDFont) { - var fdArrayOffset = topDict.fdArray; - var fdSelectOffset = topDict.fdSelect; - if (fdArrayOffset === 0 || fdSelectOffset === 0) { - throw new Error('Font is marked as a CID font, but FDArray and/or FDSelect information is missing'); - } - fdArrayOffset += start; - var fdArrayIndex = parseCFFIndex(data, fdArrayOffset); - var fdArray = gatherCFFTopDicts(data, start, fdArrayIndex.objects, stringIndex.objects); - topDict._fdArray = fdArray; - fdSelectOffset += start; - topDict._fdSelect = parseCFFFDSelect(data, fdSelectOffset, font.numGlyphs, fdArray.length); - } + function commitAttachRef(finishedWork) { + var ref = finishedWork.ref; - var privateDictOffset = start + topDict.private[1]; - var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict.private[0], stringIndex.objects); - font.defaultWidthX = privateDict.defaultWidthX; - font.nominalWidthX = privateDict.nominalWidthX; + if (ref !== null) { + var instance = finishedWork.stateNode; + var instanceToUse; - if (privateDict.subrs !== 0) { - var subrOffset = privateDictOffset + privateDict.subrs; - var subrIndex = parseCFFIndex(data, subrOffset); - font.subrs = subrIndex.objects; - font.subrsBias = calcCFFSubroutineBias(font.subrs); - } else { - font.subrs = []; - font.subrsBias = 0; - } + switch (finishedWork.tag) { + case HostComponent: + instanceToUse = getPublicInstance(instance); + break; - // Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset. - var charStringsIndex; - if (opt.lowMemory) { - charStringsIndex = parseCFFIndexLowMemory(data, start + topDict.charStrings); - font.nGlyphs = charStringsIndex.offsets.length; - } else { - charStringsIndex = parseCFFIndex(data, start + topDict.charStrings); - font.nGlyphs = charStringsIndex.objects.length; - } + default: + instanceToUse = instance; + } // Moved outside to ensure DCE works with this flag - var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects); - if (topDict.encoding === 0) { - // Standard encoding - font.cffEncoding = new CffEncoding(cffStandardEncoding, charset); - } else if (topDict.encoding === 1) { - // Expert encoding - font.cffEncoding = new CffEncoding(cffExpertEncoding, charset); - } else { - font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset); - } + if (typeof ref === 'function') { + var retVal; - // Prefer the CMAP encoding to the CFF encoding. - font.encoding = font.encoding || font.cffEncoding; + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + retVal = ref(instanceToUse); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + retVal = ref(instanceToUse); + } - font.glyphs = new glyphset.GlyphSet(font); - if (opt.lowMemory) { - font._push = function(i) { - var charString = getCffIndexObject(i, charStringsIndex.offsets, data, start + topDict.charStrings); - font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); - }; - } else { - for (var i = 0; i < font.nGlyphs; i += 1) { - var charString = charStringsIndex.objects[i]; - font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); - } - } -} + { + if (typeof retVal === 'function') { + error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork)); + } + } + } else { + { + if (!ref.hasOwnProperty('current')) { + error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork)); + } + } -// Convert a string to a String ID (SID). -// The list of strings is modified in place. -function encodeString(s, strings) { - var sid; + ref.current = instanceToUse; + } + } + } - // Is the string in the CFF standard strings? - var i = cffStandardStrings.indexOf(s); - if (i >= 0) { - sid = i; - } + function commitDetachRef(current) { + var currentRef = current.ref; - // Is the string already in the string index? - i = strings.indexOf(s); - if (i >= 0) { - sid = i + cffStandardStrings.length; - } else { - sid = cffStandardStrings.length + strings.length; - strings.push(s); - } + if (currentRef !== null) { + if (typeof currentRef === 'function') { + if ( current.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + currentRef(null); + } finally { + recordLayoutEffectDuration(current); + } + } else { + currentRef(null); + } + } else { + currentRef.current = null; + } + } + } // User-originating errors (lifecycles and refs) should not interrupt + // deletion, so don't let them throw. Host-originating errors should + // interrupt deletion, so it's okay - return sid; -} -function makeHeader() { - return new table.Record('Header', [ - {name: 'major', type: 'Card8', value: 1}, - {name: 'minor', type: 'Card8', value: 0}, - {name: 'hdrSize', type: 'Card8', value: 4}, - {name: 'major', type: 'Card8', value: 1} - ]); -} + function commitUnmount(finishedRoot, current, nearestMountedAncestor) { + onCommitUnmount(current); -function makeNameIndex(fontNames) { - var t = new table.Record('Name INDEX', [ - {name: 'names', type: 'INDEX', value: []} - ]); - t.names = []; - for (var i = 0; i < fontNames.length; i += 1) { - t.names.push({name: 'name_' + i, type: 'NAME', value: fontNames[i]}); - } + switch (current.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: + { + var updateQueue = current.updateQueue; - return t; -} + if (updateQueue !== null) { + var lastEffect = updateQueue.lastEffect; -// Given a dictionary's metadata, create a DICT structure. -function makeDict(meta, attrs, strings) { - var m = {}; - for (var i = 0; i < meta.length; i += 1) { - var entry = meta[i]; - var value = attrs[entry.name]; - if (value !== undefined && !equals(value, entry.value)) { - if (entry.type === 'SID') { - value = encodeString(value, strings); - } + if (lastEffect !== null) { + var firstEffect = lastEffect.next; + var effect = firstEffect; - m[entry.op] = {name: entry.name, type: entry.type, value: value}; - } - } + do { + var _effect = effect, + destroy = _effect.destroy, + tag = _effect.tag; - return m; -} + if (destroy !== undefined) { + if ((tag & Insertion) !== NoFlags$1) { + safelyCallDestroy(current, nearestMountedAncestor, destroy); + } else if ((tag & Layout) !== NoFlags$1) { + { + markComponentLayoutEffectUnmountStarted(current); + } -// The Top DICT houses the global font attributes. -function makeTopDict(attrs, strings) { - var t = new table.Record('Top DICT', [ - {name: 'dict', type: 'DICT', value: {}} - ]); - t.dict = makeDict(TOP_DICT_META, attrs, strings); - return t; -} + if ( current.mode & ProfileMode) { + startLayoutEffectTimer(); + safelyCallDestroy(current, nearestMountedAncestor, destroy); + recordLayoutEffectDuration(current); + } else { + safelyCallDestroy(current, nearestMountedAncestor, destroy); + } -function makeTopDictIndex(topDict) { - var t = new table.Record('Top DICT INDEX', [ - {name: 'topDicts', type: 'INDEX', value: []} - ]); - t.topDicts = [{name: 'topDict_0', type: 'TABLE', value: topDict}]; - return t; -} + { + markComponentLayoutEffectUnmountStopped(); + } + } + } -function makeStringIndex(strings) { - var t = new table.Record('String INDEX', [ - {name: 'strings', type: 'INDEX', value: []} - ]); - t.strings = []; - for (var i = 0; i < strings.length; i += 1) { - t.strings.push({name: 'string_' + i, type: 'STRING', value: strings[i]}); - } + effect = effect.next; + } while (effect !== firstEffect); + } + } - return t; -} + return; + } -function makeGlobalSubrIndex() { - // Currently we don't use subroutines. - return new table.Record('Global Subr INDEX', [ - {name: 'subrs', type: 'INDEX', value: []} - ]); -} + case ClassComponent: + { + safelyDetachRef(current, nearestMountedAncestor); + var instance = current.stateNode; -function makeCharsets(glyphNames, strings) { - var t = new table.Record('Charsets', [ - {name: 'format', type: 'Card8', value: 0} - ]); - for (var i = 0; i < glyphNames.length; i += 1) { - var glyphName = glyphNames[i]; - var glyphSID = encodeString(glyphName, strings); - t.fields.push({name: 'glyph_' + i, type: 'SID', value: glyphSID}); - } + if (typeof instance.componentWillUnmount === 'function') { + safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance); + } - return t; -} - -function glyphToOps(glyph) { - var ops = []; - var path = glyph.path; - ops.push({name: 'width', type: 'NUMBER', value: glyph.advanceWidth}); - var x = 0; - var y = 0; - for (var i = 0; i < path.commands.length; i += 1) { - var dx = (void 0); - var dy = (void 0); - var cmd = path.commands[i]; - if (cmd.type === 'Q') { - // CFF only supports bézier curves, so convert the quad to a bézier. - var _13 = 1 / 3; - var _23 = 2 / 3; - - // We're going to create a new command so we don't change the original path. - // Since all coordinates are relative, we round() them ASAP to avoid propagating errors. - cmd = { - type: 'C', - x: cmd.x, - y: cmd.y, - x1: Math.round(_13 * x + _23 * cmd.x1), - y1: Math.round(_13 * y + _23 * cmd.y1), - x2: Math.round(_13 * cmd.x + _23 * cmd.x1), - y2: Math.round(_13 * cmd.y + _23 * cmd.y1) - }; - } + return; + } - if (cmd.type === 'M') { - dx = Math.round(cmd.x - x); - dy = Math.round(cmd.y - y); - ops.push({name: 'dx', type: 'NUMBER', value: dx}); - ops.push({name: 'dy', type: 'NUMBER', value: dy}); - ops.push({name: 'rmoveto', type: 'OP', value: 21}); - x = Math.round(cmd.x); - y = Math.round(cmd.y); - } else if (cmd.type === 'L') { - dx = Math.round(cmd.x - x); - dy = Math.round(cmd.y - y); - ops.push({name: 'dx', type: 'NUMBER', value: dx}); - ops.push({name: 'dy', type: 'NUMBER', value: dy}); - ops.push({name: 'rlineto', type: 'OP', value: 5}); - x = Math.round(cmd.x); - y = Math.round(cmd.y); - } else if (cmd.type === 'C') { - var dx1 = Math.round(cmd.x1 - x); - var dy1 = Math.round(cmd.y1 - y); - var dx2 = Math.round(cmd.x2 - cmd.x1); - var dy2 = Math.round(cmd.y2 - cmd.y1); - dx = Math.round(cmd.x - cmd.x2); - dy = Math.round(cmd.y - cmd.y2); - ops.push({name: 'dx1', type: 'NUMBER', value: dx1}); - ops.push({name: 'dy1', type: 'NUMBER', value: dy1}); - ops.push({name: 'dx2', type: 'NUMBER', value: dx2}); - ops.push({name: 'dy2', type: 'NUMBER', value: dy2}); - ops.push({name: 'dx', type: 'NUMBER', value: dx}); - ops.push({name: 'dy', type: 'NUMBER', value: dy}); - ops.push({name: 'rrcurveto', type: 'OP', value: 8}); - x = Math.round(cmd.x); - y = Math.round(cmd.y); - } + case HostComponent: + { + safelyDetachRef(current, nearestMountedAncestor); + return; + } - // Contours are closed automatically. - } + case HostPortal: + { + // TODO: this is recursive. + // We are also not using this parent because + // the portal will get pushed immediately. + if (supportsMutation) { + unmountHostComponents(finishedRoot, current, nearestMountedAncestor); + } else if (supportsPersistence) { + emptyPortalContainer(current); + } - ops.push({name: 'endchar', type: 'OP', value: 14}); - return ops; -} + return; + } -function makeCharStringsIndex(glyphs) { - var t = new table.Record('CharStrings INDEX', [ - {name: 'charStrings', type: 'INDEX', value: []} - ]); + case DehydratedFragment: + { - for (var i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs.get(i); - var ops = glyphToOps(glyph); - t.charStrings.push({name: glyph.name, type: 'CHARSTRING', value: ops}); - } + return; + } - return t; -} + case ScopeComponent: + { -function makePrivateDict(attrs, strings) { - var t = new table.Record('Private DICT', [ - {name: 'dict', type: 'DICT', value: {}} - ]); - t.dict = makeDict(PRIVATE_DICT_META, attrs, strings); - return t; -} - -function makeCFFTable(glyphs, options) { - var t = new table.Table('CFF ', [ - {name: 'header', type: 'RECORD'}, - {name: 'nameIndex', type: 'RECORD'}, - {name: 'topDictIndex', type: 'RECORD'}, - {name: 'stringIndex', type: 'RECORD'}, - {name: 'globalSubrIndex', type: 'RECORD'}, - {name: 'charsets', type: 'RECORD'}, - {name: 'charStringsIndex', type: 'RECORD'}, - {name: 'privateDict', type: 'RECORD'} - ]); + return; + } + } + } - var fontScale = 1 / options.unitsPerEm; - // We use non-zero values for the offsets so that the DICT encodes them. - // This is important because the size of the Top DICT plays a role in offset calculation, - // and the size shouldn't change after we've written correct offsets. - var attrs = { - version: options.version, - fullName: options.fullName, - familyName: options.familyName, - weight: options.weightName, - fontBBox: options.fontBBox || [0, 0, 0, 0], - fontMatrix: [fontScale, 0, 0, fontScale, 0, 0], - charset: 999, - encoding: 0, - charStrings: 999, - private: [0, 999] - }; + function commitNestedUnmounts(finishedRoot, root, nearestMountedAncestor) { + // While we're inside a removed host node we don't want to call + // removeChild on the inner nodes because they're removed by the top + // call anyway. We also want to call componentWillUnmount on all + // composites before this host node is removed from the tree. Therefore + // we do an inner loop while we're still inside the host node. + var node = root; - var privateAttrs = {}; + while (true) { + commitUnmount(finishedRoot, node, nearestMountedAncestor); // Visit children because they may contain more composite or host nodes. + // Skip portals because commitUnmount() currently visits them recursively. - var glyphNames = []; - var glyph; + if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above. + // If we don't use mutation we drill down into portals here instead. + !supportsMutation || node.tag !== HostPortal)) { + node.child.return = node; + node = node.child; + continue; + } - // Skip first glyph (.notdef) - for (var i = 1; i < glyphs.length; i += 1) { - glyph = glyphs.get(i); - glyphNames.push(glyph.name); - } + if (node === root) { + return; + } - var strings = []; - - t.header = makeHeader(); - t.nameIndex = makeNameIndex([options.postScriptName]); - var topDict = makeTopDict(attrs, strings); - t.topDictIndex = makeTopDictIndex(topDict); - t.globalSubrIndex = makeGlobalSubrIndex(); - t.charsets = makeCharsets(glyphNames, strings); - t.charStringsIndex = makeCharStringsIndex(glyphs); - t.privateDict = makePrivateDict(privateAttrs, strings); - - // Needs to come at the end, to encode all custom strings used in the font. - t.stringIndex = makeStringIndex(strings); - - var startOffset = t.header.sizeOf() + - t.nameIndex.sizeOf() + - t.topDictIndex.sizeOf() + - t.stringIndex.sizeOf() + - t.globalSubrIndex.sizeOf(); - attrs.charset = startOffset; - - // We use the CFF standard encoding; proper encoding will be handled in cmap. - attrs.encoding = 0; - attrs.charStrings = attrs.charset + t.charsets.sizeOf(); - attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf(); - - // Recreate the Top DICT INDEX with the correct offsets. - topDict = makeTopDict(attrs, strings); - t.topDictIndex = makeTopDictIndex(topDict); - - return t; -} - -var cff = { parse: parseCFFTable, make: makeCFFTable }; - -// The `head` table contains global information about the font. - -// Parse the header `head` table -function parseHeadTable(data, start) { - var head = {}; - var p = new parse.Parser(data, start); - head.version = p.parseVersion(); - head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; - head.checkSumAdjustment = p.parseULong(); - head.magicNumber = p.parseULong(); - check.argument(head.magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.'); - head.flags = p.parseUShort(); - head.unitsPerEm = p.parseUShort(); - head.created = p.parseLongDateTime(); - head.modified = p.parseLongDateTime(); - head.xMin = p.parseShort(); - head.yMin = p.parseShort(); - head.xMax = p.parseShort(); - head.yMax = p.parseShort(); - head.macStyle = p.parseUShort(); - head.lowestRecPPEM = p.parseUShort(); - head.fontDirectionHint = p.parseShort(); - head.indexToLocFormat = p.parseShort(); - head.glyphDataFormat = p.parseShort(); - return head; -} - -function makeHeadTable(options) { - // Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970 - var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; - var createdTimestamp = timestamp; - - if (options.createdTimestamp) { - createdTimestamp = options.createdTimestamp + 2082844800; - } + while (node.sibling === null) { + if (node.return === null || node.return === root) { + return; + } - return new table.Table('head', [ - {name: 'version', type: 'FIXED', value: 0x00010000}, - {name: 'fontRevision', type: 'FIXED', value: 0x00010000}, - {name: 'checkSumAdjustment', type: 'ULONG', value: 0}, - {name: 'magicNumber', type: 'ULONG', value: 0x5F0F3CF5}, - {name: 'flags', type: 'USHORT', value: 0}, - {name: 'unitsPerEm', type: 'USHORT', value: 1000}, - {name: 'created', type: 'LONGDATETIME', value: createdTimestamp}, - {name: 'modified', type: 'LONGDATETIME', value: timestamp}, - {name: 'xMin', type: 'SHORT', value: 0}, - {name: 'yMin', type: 'SHORT', value: 0}, - {name: 'xMax', type: 'SHORT', value: 0}, - {name: 'yMax', type: 'SHORT', value: 0}, - {name: 'macStyle', type: 'USHORT', value: 0}, - {name: 'lowestRecPPEM', type: 'USHORT', value: 0}, - {name: 'fontDirectionHint', type: 'SHORT', value: 2}, - {name: 'indexToLocFormat', type: 'SHORT', value: 0}, - {name: 'glyphDataFormat', type: 'SHORT', value: 0} - ], options); -} - -var head = { parse: parseHeadTable, make: makeHeadTable }; - -// The `hhea` table contains information for horizontal layout. - -// Parse the horizontal header `hhea` table -function parseHheaTable(data, start) { - var hhea = {}; - var p = new parse.Parser(data, start); - hhea.version = p.parseVersion(); - hhea.ascender = p.parseShort(); - hhea.descender = p.parseShort(); - hhea.lineGap = p.parseShort(); - hhea.advanceWidthMax = p.parseUShort(); - hhea.minLeftSideBearing = p.parseShort(); - hhea.minRightSideBearing = p.parseShort(); - hhea.xMaxExtent = p.parseShort(); - hhea.caretSlopeRise = p.parseShort(); - hhea.caretSlopeRun = p.parseShort(); - hhea.caretOffset = p.parseShort(); - p.relativeOffset += 8; - hhea.metricDataFormat = p.parseShort(); - hhea.numberOfHMetrics = p.parseUShort(); - return hhea; -} - -function makeHheaTable(options) { - return new table.Table('hhea', [ - {name: 'version', type: 'FIXED', value: 0x00010000}, - {name: 'ascender', type: 'FWORD', value: 0}, - {name: 'descender', type: 'FWORD', value: 0}, - {name: 'lineGap', type: 'FWORD', value: 0}, - {name: 'advanceWidthMax', type: 'UFWORD', value: 0}, - {name: 'minLeftSideBearing', type: 'FWORD', value: 0}, - {name: 'minRightSideBearing', type: 'FWORD', value: 0}, - {name: 'xMaxExtent', type: 'FWORD', value: 0}, - {name: 'caretSlopeRise', type: 'SHORT', value: 1}, - {name: 'caretSlopeRun', type: 'SHORT', value: 0}, - {name: 'caretOffset', type: 'SHORT', value: 0}, - {name: 'reserved1', type: 'SHORT', value: 0}, - {name: 'reserved2', type: 'SHORT', value: 0}, - {name: 'reserved3', type: 'SHORT', value: 0}, - {name: 'reserved4', type: 'SHORT', value: 0}, - {name: 'metricDataFormat', type: 'SHORT', value: 0}, - {name: 'numberOfHMetrics', type: 'USHORT', value: 0} - ], options); -} - -var hhea = { parse: parseHheaTable, make: makeHheaTable }; - -// The `hmtx` table contains the horizontal metrics for all glyphs. - -function parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs) { - var advanceWidth; - var leftSideBearing; - var p = new parse.Parser(data, start); - for (var i = 0; i < numGlyphs; i += 1) { - // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. - if (i < numMetrics) { - advanceWidth = p.parseUShort(); - leftSideBearing = p.parseShort(); - } + node = node.return; + } - var glyph = glyphs.get(i); - glyph.advanceWidth = advanceWidth; - glyph.leftSideBearing = leftSideBearing; - } -} + node.sibling.return = node.return; + node = node.sibling; + } + } -function parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs) { - font._hmtxTableData = {}; + function detachFiberMutation(fiber) { + // Cut off the return pointer to disconnect it from the tree. + // This enables us to detect and warn against state updates on an unmounted component. + // It also prevents events from bubbling from within disconnected components. + // + // Ideally, we should also clear the child pointer of the parent alternate to let this + // get GC:ed but we don't know which for sure which parent is the current + // one so we'll settle for GC:ing the subtree of this child. + // This child itself will be GC:ed when the parent updates the next time. + // + // Note that we can't clear child or sibling pointers yet. + // They're needed for passive effects and for findDOMNode. + // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects). + // + // Don't reset the alternate yet, either. We need that so we can detach the + // alternate's fields in the passive phase. Clearing the return pointer is + // sufficient for findDOMNode semantics. + var alternate = fiber.alternate; - var advanceWidth; - var leftSideBearing; - var p = new parse.Parser(data, start); - for (var i = 0; i < numGlyphs; i += 1) { - // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. - if (i < numMetrics) { - advanceWidth = p.parseUShort(); - leftSideBearing = p.parseShort(); - } + if (alternate !== null) { + alternate.return = null; + } - font._hmtxTableData[i] = { - advanceWidth: advanceWidth, - leftSideBearing: leftSideBearing - }; - } -} + fiber.return = null; + } -// Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. -// This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. -function parseHmtxTable(font, data, start, numMetrics, numGlyphs, glyphs, opt) { - if (opt.lowMemory) - { parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs); } - else - { parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs); } -} + function detachFiberAfterEffects(fiber) { + var alternate = fiber.alternate; -function makeHmtxTable(glyphs) { - var t = new table.Table('hmtx', []); - for (var i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs.get(i); - var advanceWidth = glyph.advanceWidth || 0; - var leftSideBearing = glyph.leftSideBearing || 0; - t.fields.push({name: 'advanceWidth_' + i, type: 'USHORT', value: advanceWidth}); - t.fields.push({name: 'leftSideBearing_' + i, type: 'SHORT', value: leftSideBearing}); - } + if (alternate !== null) { + fiber.alternate = null; + detachFiberAfterEffects(alternate); + } // Note: Defensively using negation instead of < in case + // `deletedTreeCleanUpLevel` is undefined. - return t; -} -var hmtx = { parse: parseHmtxTable, make: makeHmtxTable }; + { + // Clear cyclical Fiber fields. This level alone is designed to roughly + // approximate the planned Fiber refactor. In that world, `setState` will be + // bound to a special "instance" object instead of a Fiber. The Instance + // object will not have any of these fields. It will only be connected to + // the fiber tree via a single link at the root. So if this level alone is + // sufficient to fix memory issues, that bodes well for our plans. + fiber.child = null; + fiber.deletions = null; + fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host + // tree, which has its own pointers to children, parents, and siblings. + // The other host nodes also point back to fibers, so we should detach that + // one, too. -// The `ltag` table stores IETF BCP-47 language tags. It allows supporting + if (fiber.tag === HostComponent) { + var hostInstance = fiber.stateNode; -function makeLtagTable(tags) { - var result = new table.Table('ltag', [ - {name: 'version', type: 'ULONG', value: 1}, - {name: 'flags', type: 'ULONG', value: 0}, - {name: 'numTags', type: 'ULONG', value: tags.length} - ]); + if (hostInstance !== null) { + detachDeletedInstance(hostInstance); + } + } - var stringPool = ''; - var stringPoolOffset = 12 + tags.length * 4; - for (var i = 0; i < tags.length; ++i) { - var pos = stringPool.indexOf(tags[i]); - if (pos < 0) { - pos = stringPool.length; - stringPool += tags[i]; - } + fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We + // already disconnect the `return` pointer at the root of the deleted + // subtree (in `detachFiberMutation`). Besides, `return` by itself is not + // cyclical — it's only cyclical when combined with `child`, `sibling`, and + // `alternate`. But we'll clear it in the next level anyway, just in case. - result.fields.push({name: 'offset ' + i, type: 'USHORT', value: stringPoolOffset + pos}); - result.fields.push({name: 'length ' + i, type: 'USHORT', value: tags[i].length}); - } + { + fiber._debugOwner = null; + } - result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); - return result; -} + { + // Theoretically, nothing in here should be necessary, because we already + // disconnected the fiber from the tree. So even if something leaks this + // particular fiber, it won't leak anything else + // + // The purpose of this branch is to be super aggressive so we can measure + // if there's any difference in memory impact. If there is, that could + // indicate a React leak we don't know about. + fiber.return = null; + fiber.dependencies = null; + fiber.memoizedProps = null; + fiber.memoizedState = null; + fiber.pendingProps = null; + fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead. -function parseLtagTable(data, start) { - var p = new parse.Parser(data, start); - var tableVersion = p.parseULong(); - check.argument(tableVersion === 1, 'Unsupported ltag table version.'); - // The 'ltag' specification does not define any flags; skip the field. - p.skip('uLong', 1); - var numTags = p.parseULong(); - - var tags = []; - for (var i = 0; i < numTags; i++) { - var tag = ''; - var offset = start + p.parseUShort(); - var length = p.parseUShort(); - for (var j = offset; j < offset + length; ++j) { - tag += String.fromCharCode(data.getInt8(j)); - } + fiber.updateQueue = null; + } + } + } - tags.push(tag); - } + function emptyPortalContainer(current) { + if (!supportsPersistence) { + return; + } - return tags; -} - -var ltag = { make: makeLtagTable, parse: parseLtagTable }; - -// The `maxp` table establishes the memory requirements for the font. - -// Parse the maximum profile `maxp` table. -function parseMaxpTable(data, start) { - var maxp = {}; - var p = new parse.Parser(data, start); - maxp.version = p.parseVersion(); - maxp.numGlyphs = p.parseUShort(); - if (maxp.version === 1.0) { - maxp.maxPoints = p.parseUShort(); - maxp.maxContours = p.parseUShort(); - maxp.maxCompositePoints = p.parseUShort(); - maxp.maxCompositeContours = p.parseUShort(); - maxp.maxZones = p.parseUShort(); - maxp.maxTwilightPoints = p.parseUShort(); - maxp.maxStorage = p.parseUShort(); - maxp.maxFunctionDefs = p.parseUShort(); - maxp.maxInstructionDefs = p.parseUShort(); - maxp.maxStackElements = p.parseUShort(); - maxp.maxSizeOfInstructions = p.parseUShort(); - maxp.maxComponentElements = p.parseUShort(); - maxp.maxComponentDepth = p.parseUShort(); - } + var portal = current.stateNode; + var containerInfo = portal.containerInfo; + var emptyChildSet = createContainerChildSet(containerInfo); + replaceContainerChildren(containerInfo, emptyChildSet); + } - return maxp; -} + function commitContainer(finishedWork) { + if (!supportsPersistence) { + return; + } -function makeMaxpTable(numGlyphs) { - return new table.Table('maxp', [ - {name: 'version', type: 'FIXED', value: 0x00005000}, - {name: 'numGlyphs', type: 'USHORT', value: numGlyphs} - ]); -} + switch (finishedWork.tag) { + case ClassComponent: + case HostComponent: + case HostText: + { + return; + } -var maxp = { parse: parseMaxpTable, make: makeMaxpTable }; - -// The `name` naming table. - -// NameIDs for the name table. -var nameTableNames = [ - 'copyright', // 0 - 'fontFamily', // 1 - 'fontSubfamily', // 2 - 'uniqueID', // 3 - 'fullName', // 4 - 'version', // 5 - 'postScriptName', // 6 - 'trademark', // 7 - 'manufacturer', // 8 - 'designer', // 9 - 'description', // 10 - 'manufacturerURL', // 11 - 'designerURL', // 12 - 'license', // 13 - 'licenseURL', // 14 - 'reserved', // 15 - 'preferredFamily', // 16 - 'preferredSubfamily', // 17 - 'compatibleFullName', // 18 - 'sampleText', // 19 - 'postScriptFindFontName', // 20 - 'wwsFamily', // 21 - 'wwsSubfamily' // 22 -]; + case HostRoot: + case HostPortal: + { + var portalOrRoot = finishedWork.stateNode; + var containerInfo = portalOrRoot.containerInfo, + pendingChildren = portalOrRoot.pendingChildren; + replaceContainerChildren(containerInfo, pendingChildren); + return; + } + } -var macLanguages = { - 0: 'en', - 1: 'fr', - 2: 'de', - 3: 'it', - 4: 'nl', - 5: 'sv', - 6: 'es', - 7: 'da', - 8: 'pt', - 9: 'no', - 10: 'he', - 11: 'ja', - 12: 'ar', - 13: 'fi', - 14: 'el', - 15: 'is', - 16: 'mt', - 17: 'tr', - 18: 'hr', - 19: 'zh-Hant', - 20: 'ur', - 21: 'hi', - 22: 'th', - 23: 'ko', - 24: 'lt', - 25: 'pl', - 26: 'hu', - 27: 'es', - 28: 'lv', - 29: 'se', - 30: 'fo', - 31: 'fa', - 32: 'ru', - 33: 'zh', - 34: 'nl-BE', - 35: 'ga', - 36: 'sq', - 37: 'ro', - 38: 'cz', - 39: 'sk', - 40: 'si', - 41: 'yi', - 42: 'sr', - 43: 'mk', - 44: 'bg', - 45: 'uk', - 46: 'be', - 47: 'uz', - 48: 'kk', - 49: 'az-Cyrl', - 50: 'az-Arab', - 51: 'hy', - 52: 'ka', - 53: 'mo', - 54: 'ky', - 55: 'tg', - 56: 'tk', - 57: 'mn-CN', - 58: 'mn', - 59: 'ps', - 60: 'ks', - 61: 'ku', - 62: 'sd', - 63: 'bo', - 64: 'ne', - 65: 'sa', - 66: 'mr', - 67: 'bn', - 68: 'as', - 69: 'gu', - 70: 'pa', - 71: 'or', - 72: 'ml', - 73: 'kn', - 74: 'ta', - 75: 'te', - 76: 'si', - 77: 'my', - 78: 'km', - 79: 'lo', - 80: 'vi', - 81: 'id', - 82: 'tl', - 83: 'ms', - 84: 'ms-Arab', - 85: 'am', - 86: 'ti', - 87: 'om', - 88: 'so', - 89: 'sw', - 90: 'rw', - 91: 'rn', - 92: 'ny', - 93: 'mg', - 94: 'eo', - 128: 'cy', - 129: 'eu', - 130: 'ca', - 131: 'la', - 132: 'qu', - 133: 'gn', - 134: 'ay', - 135: 'tt', - 136: 'ug', - 137: 'dz', - 138: 'jv', - 139: 'su', - 140: 'gl', - 141: 'af', - 142: 'br', - 143: 'iu', - 144: 'gd', - 145: 'gv', - 146: 'ga', - 147: 'to', - 148: 'el-polyton', - 149: 'kl', - 150: 'az', - 151: 'nn' -}; + throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); + } -// MacOS language ID → MacOS script ID -// -// Note that the script ID is not sufficient to determine what encoding -// to use in TrueType files. For some languages, MacOS used a modification -// of a mainstream script. For example, an Icelandic name would be stored -// with smRoman in the TrueType naming table, but the actual encoding -// is a special Icelandic version of the normal Macintosh Roman encoding. -// As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal -// Syllables but MacOS had run out of available script codes, so this was -// done as a (pretty radical) "modification" of Ethiopic. -// -// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt -var macLanguageToScript = { - 0: 0, // langEnglish → smRoman - 1: 0, // langFrench → smRoman - 2: 0, // langGerman → smRoman - 3: 0, // langItalian → smRoman - 4: 0, // langDutch → smRoman - 5: 0, // langSwedish → smRoman - 6: 0, // langSpanish → smRoman - 7: 0, // langDanish → smRoman - 8: 0, // langPortuguese → smRoman - 9: 0, // langNorwegian → smRoman - 10: 5, // langHebrew → smHebrew - 11: 1, // langJapanese → smJapanese - 12: 4, // langArabic → smArabic - 13: 0, // langFinnish → smRoman - 14: 6, // langGreek → smGreek - 15: 0, // langIcelandic → smRoman (modified) - 16: 0, // langMaltese → smRoman - 17: 0, // langTurkish → smRoman (modified) - 18: 0, // langCroatian → smRoman (modified) - 19: 2, // langTradChinese → smTradChinese - 20: 4, // langUrdu → smArabic - 21: 9, // langHindi → smDevanagari - 22: 21, // langThai → smThai - 23: 3, // langKorean → smKorean - 24: 29, // langLithuanian → smCentralEuroRoman - 25: 29, // langPolish → smCentralEuroRoman - 26: 29, // langHungarian → smCentralEuroRoman - 27: 29, // langEstonian → smCentralEuroRoman - 28: 29, // langLatvian → smCentralEuroRoman - 29: 0, // langSami → smRoman - 30: 0, // langFaroese → smRoman (modified) - 31: 4, // langFarsi → smArabic (modified) - 32: 7, // langRussian → smCyrillic - 33: 25, // langSimpChinese → smSimpChinese - 34: 0, // langFlemish → smRoman - 35: 0, // langIrishGaelic → smRoman (modified) - 36: 0, // langAlbanian → smRoman - 37: 0, // langRomanian → smRoman (modified) - 38: 29, // langCzech → smCentralEuroRoman - 39: 29, // langSlovak → smCentralEuroRoman - 40: 0, // langSlovenian → smRoman (modified) - 41: 5, // langYiddish → smHebrew - 42: 7, // langSerbian → smCyrillic - 43: 7, // langMacedonian → smCyrillic - 44: 7, // langBulgarian → smCyrillic - 45: 7, // langUkrainian → smCyrillic (modified) - 46: 7, // langByelorussian → smCyrillic - 47: 7, // langUzbek → smCyrillic - 48: 7, // langKazakh → smCyrillic - 49: 7, // langAzerbaijani → smCyrillic - 50: 4, // langAzerbaijanAr → smArabic - 51: 24, // langArmenian → smArmenian - 52: 23, // langGeorgian → smGeorgian - 53: 7, // langMoldavian → smCyrillic - 54: 7, // langKirghiz → smCyrillic - 55: 7, // langTajiki → smCyrillic - 56: 7, // langTurkmen → smCyrillic - 57: 27, // langMongolian → smMongolian - 58: 7, // langMongolianCyr → smCyrillic - 59: 4, // langPashto → smArabic - 60: 4, // langKurdish → smArabic - 61: 4, // langKashmiri → smArabic - 62: 4, // langSindhi → smArabic - 63: 26, // langTibetan → smTibetan - 64: 9, // langNepali → smDevanagari - 65: 9, // langSanskrit → smDevanagari - 66: 9, // langMarathi → smDevanagari - 67: 13, // langBengali → smBengali - 68: 13, // langAssamese → smBengali - 69: 11, // langGujarati → smGujarati - 70: 10, // langPunjabi → smGurmukhi - 71: 12, // langOriya → smOriya - 72: 17, // langMalayalam → smMalayalam - 73: 16, // langKannada → smKannada - 74: 14, // langTamil → smTamil - 75: 15, // langTelugu → smTelugu - 76: 18, // langSinhalese → smSinhalese - 77: 19, // langBurmese → smBurmese - 78: 20, // langKhmer → smKhmer - 79: 22, // langLao → smLao - 80: 30, // langVietnamese → smVietnamese - 81: 0, // langIndonesian → smRoman - 82: 0, // langTagalog → smRoman - 83: 0, // langMalayRoman → smRoman - 84: 4, // langMalayArabic → smArabic - 85: 28, // langAmharic → smEthiopic - 86: 28, // langTigrinya → smEthiopic - 87: 28, // langOromo → smEthiopic - 88: 0, // langSomali → smRoman - 89: 0, // langSwahili → smRoman - 90: 0, // langKinyarwanda → smRoman - 91: 0, // langRundi → smRoman - 92: 0, // langNyanja → smRoman - 93: 0, // langMalagasy → smRoman - 94: 0, // langEsperanto → smRoman - 128: 0, // langWelsh → smRoman (modified) - 129: 0, // langBasque → smRoman - 130: 0, // langCatalan → smRoman - 131: 0, // langLatin → smRoman - 132: 0, // langQuechua → smRoman - 133: 0, // langGuarani → smRoman - 134: 0, // langAymara → smRoman - 135: 7, // langTatar → smCyrillic - 136: 4, // langUighur → smArabic - 137: 26, // langDzongkha → smTibetan - 138: 0, // langJavaneseRom → smRoman - 139: 0, // langSundaneseRom → smRoman - 140: 0, // langGalician → smRoman - 141: 0, // langAfrikaans → smRoman - 142: 0, // langBreton → smRoman (modified) - 143: 28, // langInuktitut → smEthiopic (modified) - 144: 0, // langScottishGaelic → smRoman (modified) - 145: 0, // langManxGaelic → smRoman (modified) - 146: 0, // langIrishGaelicScript → smRoman (modified) - 147: 0, // langTongan → smRoman - 148: 6, // langGreekAncient → smRoman - 149: 0, // langGreenlandic → smRoman - 150: 0, // langAzerbaijanRoman → smRoman - 151: 0 // langNynorsk → smRoman -}; + function getHostParentFiber(fiber) { + var parent = fiber.return; -// While Microsoft indicates a region/country for all its language -// IDs, we omit the region code if it's equal to the "most likely -// region subtag" according to Unicode CLDR. For scripts, we omit -// the subtag if it is equal to the Suppress-Script entry in the -// IANA language subtag registry for IETF BCP 47. -// -// For example, Microsoft states that its language code 0x041A is -// Croatian in Croatia. We transform this to the BCP 47 language code 'hr' -// and not 'hr-HR' because Croatia is the default country for Croatian, -// according to Unicode CLDR. As another example, Microsoft states -// that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform -// this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script -// for the Croatian language, according to IANA. -// -// http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html -// http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry -var windowsLanguages = { - 0x0436: 'af', - 0x041C: 'sq', - 0x0484: 'gsw', - 0x045E: 'am', - 0x1401: 'ar-DZ', - 0x3C01: 'ar-BH', - 0x0C01: 'ar', - 0x0801: 'ar-IQ', - 0x2C01: 'ar-JO', - 0x3401: 'ar-KW', - 0x3001: 'ar-LB', - 0x1001: 'ar-LY', - 0x1801: 'ary', - 0x2001: 'ar-OM', - 0x4001: 'ar-QA', - 0x0401: 'ar-SA', - 0x2801: 'ar-SY', - 0x1C01: 'aeb', - 0x3801: 'ar-AE', - 0x2401: 'ar-YE', - 0x042B: 'hy', - 0x044D: 'as', - 0x082C: 'az-Cyrl', - 0x042C: 'az', - 0x046D: 'ba', - 0x042D: 'eu', - 0x0423: 'be', - 0x0845: 'bn', - 0x0445: 'bn-IN', - 0x201A: 'bs-Cyrl', - 0x141A: 'bs', - 0x047E: 'br', - 0x0402: 'bg', - 0x0403: 'ca', - 0x0C04: 'zh-HK', - 0x1404: 'zh-MO', - 0x0804: 'zh', - 0x1004: 'zh-SG', - 0x0404: 'zh-TW', - 0x0483: 'co', - 0x041A: 'hr', - 0x101A: 'hr-BA', - 0x0405: 'cs', - 0x0406: 'da', - 0x048C: 'prs', - 0x0465: 'dv', - 0x0813: 'nl-BE', - 0x0413: 'nl', - 0x0C09: 'en-AU', - 0x2809: 'en-BZ', - 0x1009: 'en-CA', - 0x2409: 'en-029', - 0x4009: 'en-IN', - 0x1809: 'en-IE', - 0x2009: 'en-JM', - 0x4409: 'en-MY', - 0x1409: 'en-NZ', - 0x3409: 'en-PH', - 0x4809: 'en-SG', - 0x1C09: 'en-ZA', - 0x2C09: 'en-TT', - 0x0809: 'en-GB', - 0x0409: 'en', - 0x3009: 'en-ZW', - 0x0425: 'et', - 0x0438: 'fo', - 0x0464: 'fil', - 0x040B: 'fi', - 0x080C: 'fr-BE', - 0x0C0C: 'fr-CA', - 0x040C: 'fr', - 0x140C: 'fr-LU', - 0x180C: 'fr-MC', - 0x100C: 'fr-CH', - 0x0462: 'fy', - 0x0456: 'gl', - 0x0437: 'ka', - 0x0C07: 'de-AT', - 0x0407: 'de', - 0x1407: 'de-LI', - 0x1007: 'de-LU', - 0x0807: 'de-CH', - 0x0408: 'el', - 0x046F: 'kl', - 0x0447: 'gu', - 0x0468: 'ha', - 0x040D: 'he', - 0x0439: 'hi', - 0x040E: 'hu', - 0x040F: 'is', - 0x0470: 'ig', - 0x0421: 'id', - 0x045D: 'iu', - 0x085D: 'iu-Latn', - 0x083C: 'ga', - 0x0434: 'xh', - 0x0435: 'zu', - 0x0410: 'it', - 0x0810: 'it-CH', - 0x0411: 'ja', - 0x044B: 'kn', - 0x043F: 'kk', - 0x0453: 'km', - 0x0486: 'quc', - 0x0487: 'rw', - 0x0441: 'sw', - 0x0457: 'kok', - 0x0412: 'ko', - 0x0440: 'ky', - 0x0454: 'lo', - 0x0426: 'lv', - 0x0427: 'lt', - 0x082E: 'dsb', - 0x046E: 'lb', - 0x042F: 'mk', - 0x083E: 'ms-BN', - 0x043E: 'ms', - 0x044C: 'ml', - 0x043A: 'mt', - 0x0481: 'mi', - 0x047A: 'arn', - 0x044E: 'mr', - 0x047C: 'moh', - 0x0450: 'mn', - 0x0850: 'mn-CN', - 0x0461: 'ne', - 0x0414: 'nb', - 0x0814: 'nn', - 0x0482: 'oc', - 0x0448: 'or', - 0x0463: 'ps', - 0x0415: 'pl', - 0x0416: 'pt', - 0x0816: 'pt-PT', - 0x0446: 'pa', - 0x046B: 'qu-BO', - 0x086B: 'qu-EC', - 0x0C6B: 'qu', - 0x0418: 'ro', - 0x0417: 'rm', - 0x0419: 'ru', - 0x243B: 'smn', - 0x103B: 'smj-NO', - 0x143B: 'smj', - 0x0C3B: 'se-FI', - 0x043B: 'se', - 0x083B: 'se-SE', - 0x203B: 'sms', - 0x183B: 'sma-NO', - 0x1C3B: 'sms', - 0x044F: 'sa', - 0x1C1A: 'sr-Cyrl-BA', - 0x0C1A: 'sr', - 0x181A: 'sr-Latn-BA', - 0x081A: 'sr-Latn', - 0x046C: 'nso', - 0x0432: 'tn', - 0x045B: 'si', - 0x041B: 'sk', - 0x0424: 'sl', - 0x2C0A: 'es-AR', - 0x400A: 'es-BO', - 0x340A: 'es-CL', - 0x240A: 'es-CO', - 0x140A: 'es-CR', - 0x1C0A: 'es-DO', - 0x300A: 'es-EC', - 0x440A: 'es-SV', - 0x100A: 'es-GT', - 0x480A: 'es-HN', - 0x080A: 'es-MX', - 0x4C0A: 'es-NI', - 0x180A: 'es-PA', - 0x3C0A: 'es-PY', - 0x280A: 'es-PE', - 0x500A: 'es-PR', - - // Microsoft has defined two different language codes for - // “Spanish with modern sorting” and “Spanish with traditional - // sorting”. This makes sense for collation APIs, and it would be - // possible to express this in BCP 47 language tags via Unicode - // extensions (eg., es-u-co-trad is Spanish with traditional - // sorting). However, for storing names in fonts, the distinction - // does not make sense, so we give “es” in both cases. - 0x0C0A: 'es', - 0x040A: 'es', - - 0x540A: 'es-US', - 0x380A: 'es-UY', - 0x200A: 'es-VE', - 0x081D: 'sv-FI', - 0x041D: 'sv', - 0x045A: 'syr', - 0x0428: 'tg', - 0x085F: 'tzm', - 0x0449: 'ta', - 0x0444: 'tt', - 0x044A: 'te', - 0x041E: 'th', - 0x0451: 'bo', - 0x041F: 'tr', - 0x0442: 'tk', - 0x0480: 'ug', - 0x0422: 'uk', - 0x042E: 'hsb', - 0x0420: 'ur', - 0x0843: 'uz-Cyrl', - 0x0443: 'uz', - 0x042A: 'vi', - 0x0452: 'cy', - 0x0488: 'wo', - 0x0485: 'sah', - 0x0478: 'ii', - 0x046A: 'yo' -}; + while (parent !== null) { + if (isHostParent(parent)) { + return parent; + } -// Returns a IETF BCP 47 language code, for example 'zh-Hant' -// for 'Chinese in the traditional script'. -function getLanguageCode(platformID, languageID, ltag) { - switch (platformID) { - case 0: // Unicode - if (languageID === 0xFFFF) { - return 'und'; - } else if (ltag) { - return ltag[languageID]; - } + parent = parent.return; + } - break; + throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.'); + } - case 1: // Macintosh - return macLanguages[languageID]; + function isHostParent(fiber) { + return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; + } - case 3: // Windows - return windowsLanguages[languageID]; - } + function getHostSibling(fiber) { + // We're going to search forward into the tree until we find a sibling host + // node. Unfortunately, if multiple insertions are done in a row we have to + // search past them. This leads to exponential search for the next sibling. + // TODO: Find a more efficient way to do this. + var node = fiber; - return undefined; -} - -var utf16 = 'utf-16'; - -// MacOS script ID → encoding. This table stores the default case, -// which can be overridden by macLanguageEncodings. -var macScriptEncodings = { - 0: 'macintosh', // smRoman - 1: 'x-mac-japanese', // smJapanese - 2: 'x-mac-chinesetrad', // smTradChinese - 3: 'x-mac-korean', // smKorean - 6: 'x-mac-greek', // smGreek - 7: 'x-mac-cyrillic', // smCyrillic - 9: 'x-mac-devanagai', // smDevanagari - 10: 'x-mac-gurmukhi', // smGurmukhi - 11: 'x-mac-gujarati', // smGujarati - 12: 'x-mac-oriya', // smOriya - 13: 'x-mac-bengali', // smBengali - 14: 'x-mac-tamil', // smTamil - 15: 'x-mac-telugu', // smTelugu - 16: 'x-mac-kannada', // smKannada - 17: 'x-mac-malayalam', // smMalayalam - 18: 'x-mac-sinhalese', // smSinhalese - 19: 'x-mac-burmese', // smBurmese - 20: 'x-mac-khmer', // smKhmer - 21: 'x-mac-thai', // smThai - 22: 'x-mac-lao', // smLao - 23: 'x-mac-georgian', // smGeorgian - 24: 'x-mac-armenian', // smArmenian - 25: 'x-mac-chinesesimp', // smSimpChinese - 26: 'x-mac-tibetan', // smTibetan - 27: 'x-mac-mongolian', // smMongolian - 28: 'x-mac-ethiopic', // smEthiopic - 29: 'x-mac-ce', // smCentralEuroRoman - 30: 'x-mac-vietnamese', // smVietnamese - 31: 'x-mac-extarabic' // smExtArabic -}; + siblings: while (true) { + // If we didn't find anything, let's try the next sibling. + while (node.sibling === null) { + if (node.return === null || isHostParent(node.return)) { + // If we pop out of the root or hit the parent the fiber we are the + // last sibling. + return null; + } -// MacOS language ID → encoding. This table stores the exceptional -// cases, which override macScriptEncodings. For writing MacOS naming -// tables, we need to emit a MacOS script ID. Therefore, we cannot -// merge macScriptEncodings into macLanguageEncodings. -// -// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt -var macLanguageEncodings = { - 15: 'x-mac-icelandic', // langIcelandic - 17: 'x-mac-turkish', // langTurkish - 18: 'x-mac-croatian', // langCroatian - 24: 'x-mac-ce', // langLithuanian - 25: 'x-mac-ce', // langPolish - 26: 'x-mac-ce', // langHungarian - 27: 'x-mac-ce', // langEstonian - 28: 'x-mac-ce', // langLatvian - 30: 'x-mac-icelandic', // langFaroese - 37: 'x-mac-romanian', // langRomanian - 38: 'x-mac-ce', // langCzech - 39: 'x-mac-ce', // langSlovak - 40: 'x-mac-ce', // langSlovenian - 143: 'x-mac-inuit', // langInuktitut - 146: 'x-mac-gaelic' // langIrishGaelicScript -}; + node = node.return; + } -function getEncoding(platformID, encodingID, languageID) { - switch (platformID) { - case 0: // Unicode - return utf16; + node.sibling.return = node.return; + node = node.sibling; - case 1: // Apple Macintosh - return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; + while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) { + // If it is not host node and, we might have a host node inside it. + // Try to search down until we find one. + if (node.flags & Placement) { + // If we don't have a child, try the siblings instead. + continue siblings; + } // If we don't have a child, try the siblings instead. + // We also skip portals because they are not part of this host tree. - case 3: // Microsoft Windows - if (encodingID === 1 || encodingID === 10) { - return utf16; - } - break; - } + if (node.child === null || node.tag === HostPortal) { + continue siblings; + } else { + node.child.return = node; + node = node.child; + } + } // Check if this host node is stable or about to be placed. - return undefined; -} - -// Parse the naming `name` table. -// FIXME: Format 1 additional fields are not supported yet. -// ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904']. -function parseNameTable(data, start, ltag) { - var name = {}; - var p = new parse.Parser(data, start); - var format = p.parseUShort(); - var count = p.parseUShort(); - var stringOffset = p.offset + p.parseUShort(); - for (var i = 0; i < count; i++) { - var platformID = p.parseUShort(); - var encodingID = p.parseUShort(); - var languageID = p.parseUShort(); - var nameID = p.parseUShort(); - var property = nameTableNames[nameID] || nameID; - var byteLength = p.parseUShort(); - var offset = p.parseUShort(); - var language = getLanguageCode(platformID, languageID, ltag); - var encoding = getEncoding(platformID, encodingID, languageID); - if (encoding !== undefined && language !== undefined) { - var text = (void 0); - if (encoding === utf16) { - text = decode.UTF16(data, stringOffset + offset, byteLength); - } else { - text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding); - } - if (text) { - var translations = name[property]; - if (translations === undefined) { - translations = name[property] = {}; - } + if (!(node.flags & Placement)) { + // Found it! + return node.stateNode; + } + } + } - translations[language] = text; - } - } - } - if (format === 1) { - // FIXME: Also handle Microsoft's 'name' table 1. - p.parseUShort(); - } + function commitPlacement(finishedWork) { + if (!supportsMutation) { + return; + } // Recursively insert all host nodes into the parent. - return name; -} -// {23: 'foo'} → {'foo': 23} -// ['bar', 'baz'] → {'bar': 0, 'baz': 1} -function reverseDict(dict) { - var result = {}; - for (var key in dict) { - result[dict[key]] = parseInt(key); - } + var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. - return result; -} + switch (parentFiber.tag) { + case HostComponent: + { + var parent = parentFiber.stateNode; -function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) { - return new table.Record('NameRecord', [ - {name: 'platformID', type: 'USHORT', value: platformID}, - {name: 'encodingID', type: 'USHORT', value: encodingID}, - {name: 'languageID', type: 'USHORT', value: languageID}, - {name: 'nameID', type: 'USHORT', value: nameID}, - {name: 'length', type: 'USHORT', value: length}, - {name: 'offset', type: 'USHORT', value: offset} - ]); -} + if (parentFiber.flags & ContentReset) { + // Reset the text content of the parent before doing any insertions + resetTextContent(parent); // Clear ContentReset from the effect tag -// Finds the position of needle in haystack, or -1 if not there. -// Like String.indexOf(), but for arrays. -function findSubArray(needle, haystack) { - var needleLength = needle.length; - var limit = haystack.length - needleLength + 1; + parentFiber.flags &= ~ContentReset; + } - loop: - for (var pos = 0; pos < limit; pos++) { - for (; pos < limit; pos++) { - for (var k = 0; k < needleLength; k++) { - if (haystack[pos + k] !== needle[k]) { - continue loop; - } - } + var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its + // children to find all the terminal nodes. - return pos; - } - } + insertOrAppendPlacementNode(finishedWork, before, parent); + break; + } - return -1; -} + case HostRoot: + case HostPortal: + { + var _parent = parentFiber.stateNode.containerInfo; -function addStringToPool(s, pool) { - var offset = findSubArray(s, pool); - if (offset < 0) { - offset = pool.length; - var i = 0; - var len = s.length; - for (; i < len; ++i) { - pool.push(s[i]); - } + var _before = getHostSibling(finishedWork); - } + insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent); + break; + } + // eslint-disable-next-line-no-fallthrough - return offset; -} + default: + throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.'); + } + } -function makeNameTable(names, ltag) { - var nameID; - var nameIDs = []; + function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { + var tag = node.tag; + var isHost = tag === HostComponent || tag === HostText; - var namesWithNumericKeys = {}; - var nameTableIds = reverseDict(nameTableNames); - for (var key in names) { - var id = nameTableIds[key]; - if (id === undefined) { - id = key; - } + if (isHost) { + var stateNode = node.stateNode; - nameID = parseInt(id); + if (before) { + insertInContainerBefore(parent, stateNode, before); + } else { + appendChildToContainer(parent, stateNode); + } + } else if (tag === HostPortal) ; else { + var child = node.child; - if (isNaN(nameID)) { - throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.'); - } + if (child !== null) { + insertOrAppendPlacementNodeIntoContainer(child, before, parent); + var sibling = child.sibling; - namesWithNumericKeys[nameID] = names[key]; - nameIDs.push(nameID); - } + while (sibling !== null) { + insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); + sibling = sibling.sibling; + } + } + } + } - var macLanguageIds = reverseDict(macLanguages); - var windowsLanguageIds = reverseDict(windowsLanguages); - - var nameRecords = []; - var stringPool = []; - - for (var i = 0; i < nameIDs.length; i++) { - nameID = nameIDs[i]; - var translations = namesWithNumericKeys[nameID]; - for (var lang in translations) { - var text = translations[lang]; - - // For MacOS, we try to emit the name in the form that was introduced - // in the initial version of the TrueType spec (in the late 1980s). - // However, this can fail for various reasons: the requested BCP 47 - // language code might not have an old-style Mac equivalent; - // we might not have a codec for the needed character encoding; - // or the name might contain characters that cannot be expressed - // in the old-style Macintosh encoding. In case of failure, we emit - // the name in a more modern fashion (Unicode encoding with BCP 47 - // language tags) that is recognized by MacOS 10.5, released in 2009. - // If fonts were only read by operating systems, we could simply - // emit all names in the modern form; this would be much easier. - // However, there are many applications and libraries that read - // 'name' tables directly, and these will usually only recognize - // the ancient form (silently skipping the unrecognized names). - var macPlatform = 1; // Macintosh - var macLanguage = macLanguageIds[lang]; - var macScript = macLanguageToScript[macLanguage]; - var macEncoding = getEncoding(macPlatform, macScript, macLanguage); - var macName = encode.MACSTRING(text, macEncoding); - if (macName === undefined) { - macPlatform = 0; // Unicode - macLanguage = ltag.indexOf(lang); - if (macLanguage < 0) { - macLanguage = ltag.length; - ltag.push(lang); - } + function insertOrAppendPlacementNode(node, before, parent) { + var tag = node.tag; + var isHost = tag === HostComponent || tag === HostText; - macScript = 4; // Unicode 2.0 and later - macName = encode.UTF16(text); - } + if (isHost) { + var stateNode = node.stateNode; - var macNameOffset = addStringToPool(macName, stringPool); - nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, - nameID, macName.length, macNameOffset)); + if (before) { + insertBefore(parent, stateNode, before); + } else { + appendChild(parent, stateNode); + } + } else if (tag === HostPortal) ; else { + var child = node.child; - var winLanguage = windowsLanguageIds[lang]; - if (winLanguage !== undefined) { - var winName = encode.UTF16(text); - var winNameOffset = addStringToPool(winName, stringPool); - nameRecords.push(makeNameRecord(3, 1, winLanguage, - nameID, winName.length, winNameOffset)); - } - } - } + if (child !== null) { + insertOrAppendPlacementNode(child, before, parent); + var sibling = child.sibling; - nameRecords.sort(function(a, b) { - return ((a.platformID - b.platformID) || - (a.encodingID - b.encodingID) || - (a.languageID - b.languageID) || - (a.nameID - b.nameID)); - }); + while (sibling !== null) { + insertOrAppendPlacementNode(sibling, before, parent); + sibling = sibling.sibling; + } + } + } + } - var t = new table.Table('name', [ - {name: 'format', type: 'USHORT', value: 0}, - {name: 'count', type: 'USHORT', value: nameRecords.length}, - {name: 'stringOffset', type: 'USHORT', value: 6 + nameRecords.length * 12} - ]); + function unmountHostComponents(finishedRoot, current, nearestMountedAncestor) { + // We only have the top Fiber that was deleted but we need to recurse down its + // children to find all the terminal nodes. + var node = current; // Each iteration, currentParent is populated with node's host parent if not + // currentParentIsValid. - for (var r = 0; r < nameRecords.length; r++) { - t.fields.push({name: 'record_' + r, type: 'RECORD', value: nameRecords[r]}); - } + var currentParentIsValid = false; // Note: these two variables *must* always be updated together. - t.fields.push({name: 'strings', type: 'LITERAL', value: stringPool}); - return t; -} - -var _name = { parse: parseNameTable, make: makeNameTable }; - -// The `OS/2` table contains metrics required in OpenType fonts. - -var unicodeRanges = [ - {begin: 0x0000, end: 0x007F}, // Basic Latin - {begin: 0x0080, end: 0x00FF}, // Latin-1 Supplement - {begin: 0x0100, end: 0x017F}, // Latin Extended-A - {begin: 0x0180, end: 0x024F}, // Latin Extended-B - {begin: 0x0250, end: 0x02AF}, // IPA Extensions - {begin: 0x02B0, end: 0x02FF}, // Spacing Modifier Letters - {begin: 0x0300, end: 0x036F}, // Combining Diacritical Marks - {begin: 0x0370, end: 0x03FF}, // Greek and Coptic - {begin: 0x2C80, end: 0x2CFF}, // Coptic - {begin: 0x0400, end: 0x04FF}, // Cyrillic - {begin: 0x0530, end: 0x058F}, // Armenian - {begin: 0x0590, end: 0x05FF}, // Hebrew - {begin: 0xA500, end: 0xA63F}, // Vai - {begin: 0x0600, end: 0x06FF}, // Arabic - {begin: 0x07C0, end: 0x07FF}, // NKo - {begin: 0x0900, end: 0x097F}, // Devanagari - {begin: 0x0980, end: 0x09FF}, // Bengali - {begin: 0x0A00, end: 0x0A7F}, // Gurmukhi - {begin: 0x0A80, end: 0x0AFF}, // Gujarati - {begin: 0x0B00, end: 0x0B7F}, // Oriya - {begin: 0x0B80, end: 0x0BFF}, // Tamil - {begin: 0x0C00, end: 0x0C7F}, // Telugu - {begin: 0x0C80, end: 0x0CFF}, // Kannada - {begin: 0x0D00, end: 0x0D7F}, // Malayalam - {begin: 0x0E00, end: 0x0E7F}, // Thai - {begin: 0x0E80, end: 0x0EFF}, // Lao - {begin: 0x10A0, end: 0x10FF}, // Georgian - {begin: 0x1B00, end: 0x1B7F}, // Balinese - {begin: 0x1100, end: 0x11FF}, // Hangul Jamo - {begin: 0x1E00, end: 0x1EFF}, // Latin Extended Additional - {begin: 0x1F00, end: 0x1FFF}, // Greek Extended - {begin: 0x2000, end: 0x206F}, // General Punctuation - {begin: 0x2070, end: 0x209F}, // Superscripts And Subscripts - {begin: 0x20A0, end: 0x20CF}, // Currency Symbol - {begin: 0x20D0, end: 0x20FF}, // Combining Diacritical Marks For Symbols - {begin: 0x2100, end: 0x214F}, // Letterlike Symbols - {begin: 0x2150, end: 0x218F}, // Number Forms - {begin: 0x2190, end: 0x21FF}, // Arrows - {begin: 0x2200, end: 0x22FF}, // Mathematical Operators - {begin: 0x2300, end: 0x23FF}, // Miscellaneous Technical - {begin: 0x2400, end: 0x243F}, // Control Pictures - {begin: 0x2440, end: 0x245F}, // Optical Character Recognition - {begin: 0x2460, end: 0x24FF}, // Enclosed Alphanumerics - {begin: 0x2500, end: 0x257F}, // Box Drawing - {begin: 0x2580, end: 0x259F}, // Block Elements - {begin: 0x25A0, end: 0x25FF}, // Geometric Shapes - {begin: 0x2600, end: 0x26FF}, // Miscellaneous Symbols - {begin: 0x2700, end: 0x27BF}, // Dingbats - {begin: 0x3000, end: 0x303F}, // CJK Symbols And Punctuation - {begin: 0x3040, end: 0x309F}, // Hiragana - {begin: 0x30A0, end: 0x30FF}, // Katakana - {begin: 0x3100, end: 0x312F}, // Bopomofo - {begin: 0x3130, end: 0x318F}, // Hangul Compatibility Jamo - {begin: 0xA840, end: 0xA87F}, // Phags-pa - {begin: 0x3200, end: 0x32FF}, // Enclosed CJK Letters And Months - {begin: 0x3300, end: 0x33FF}, // CJK Compatibility - {begin: 0xAC00, end: 0xD7AF}, // Hangul Syllables - {begin: 0xD800, end: 0xDFFF}, // Non-Plane 0 * - {begin: 0x10900, end: 0x1091F}, // Phoenicia - {begin: 0x4E00, end: 0x9FFF}, // CJK Unified Ideographs - {begin: 0xE000, end: 0xF8FF}, // Private Use Area (plane 0) - {begin: 0x31C0, end: 0x31EF}, // CJK Strokes - {begin: 0xFB00, end: 0xFB4F}, // Alphabetic Presentation Forms - {begin: 0xFB50, end: 0xFDFF}, // Arabic Presentation Forms-A - {begin: 0xFE20, end: 0xFE2F}, // Combining Half Marks - {begin: 0xFE10, end: 0xFE1F}, // Vertical Forms - {begin: 0xFE50, end: 0xFE6F}, // Small Form Variants - {begin: 0xFE70, end: 0xFEFF}, // Arabic Presentation Forms-B - {begin: 0xFF00, end: 0xFFEF}, // Halfwidth And Fullwidth Forms - {begin: 0xFFF0, end: 0xFFFF}, // Specials - {begin: 0x0F00, end: 0x0FFF}, // Tibetan - {begin: 0x0700, end: 0x074F}, // Syriac - {begin: 0x0780, end: 0x07BF}, // Thaana - {begin: 0x0D80, end: 0x0DFF}, // Sinhala - {begin: 0x1000, end: 0x109F}, // Myanmar - {begin: 0x1200, end: 0x137F}, // Ethiopic - {begin: 0x13A0, end: 0x13FF}, // Cherokee - {begin: 0x1400, end: 0x167F}, // Unified Canadian Aboriginal Syllabics - {begin: 0x1680, end: 0x169F}, // Ogham - {begin: 0x16A0, end: 0x16FF}, // Runic - {begin: 0x1780, end: 0x17FF}, // Khmer - {begin: 0x1800, end: 0x18AF}, // Mongolian - {begin: 0x2800, end: 0x28FF}, // Braille Patterns - {begin: 0xA000, end: 0xA48F}, // Yi Syllables - {begin: 0x1700, end: 0x171F}, // Tagalog - {begin: 0x10300, end: 0x1032F}, // Old Italic - {begin: 0x10330, end: 0x1034F}, // Gothic - {begin: 0x10400, end: 0x1044F}, // Deseret - {begin: 0x1D000, end: 0x1D0FF}, // Byzantine Musical Symbols - {begin: 0x1D400, end: 0x1D7FF}, // Mathematical Alphanumeric Symbols - {begin: 0xFF000, end: 0xFFFFD}, // Private Use (plane 15) - {begin: 0xFE00, end: 0xFE0F}, // Variation Selectors - {begin: 0xE0000, end: 0xE007F}, // Tags - {begin: 0x1900, end: 0x194F}, // Limbu - {begin: 0x1950, end: 0x197F}, // Tai Le - {begin: 0x1980, end: 0x19DF}, // New Tai Lue - {begin: 0x1A00, end: 0x1A1F}, // Buginese - {begin: 0x2C00, end: 0x2C5F}, // Glagolitic - {begin: 0x2D30, end: 0x2D7F}, // Tifinagh - {begin: 0x4DC0, end: 0x4DFF}, // Yijing Hexagram Symbols - {begin: 0xA800, end: 0xA82F}, // Syloti Nagri - {begin: 0x10000, end: 0x1007F}, // Linear B Syllabary - {begin: 0x10140, end: 0x1018F}, // Ancient Greek Numbers - {begin: 0x10380, end: 0x1039F}, // Ugaritic - {begin: 0x103A0, end: 0x103DF}, // Old Persian - {begin: 0x10450, end: 0x1047F}, // Shavian - {begin: 0x10480, end: 0x104AF}, // Osmanya - {begin: 0x10800, end: 0x1083F}, // Cypriot Syllabary - {begin: 0x10A00, end: 0x10A5F}, // Kharoshthi - {begin: 0x1D300, end: 0x1D35F}, // Tai Xuan Jing Symbols - {begin: 0x12000, end: 0x123FF}, // Cuneiform - {begin: 0x1D360, end: 0x1D37F}, // Counting Rod Numerals - {begin: 0x1B80, end: 0x1BBF}, // Sundanese - {begin: 0x1C00, end: 0x1C4F}, // Lepcha - {begin: 0x1C50, end: 0x1C7F}, // Ol Chiki - {begin: 0xA880, end: 0xA8DF}, // Saurashtra - {begin: 0xA900, end: 0xA92F}, // Kayah Li - {begin: 0xA930, end: 0xA95F}, // Rejang - {begin: 0xAA00, end: 0xAA5F}, // Cham - {begin: 0x10190, end: 0x101CF}, // Ancient Symbols - {begin: 0x101D0, end: 0x101FF}, // Phaistos Disc - {begin: 0x102A0, end: 0x102DF}, // Carian - {begin: 0x1F030, end: 0x1F09F} // Domino Tiles -]; + var currentParent; + var currentParentIsContainer; -function getUnicodeRange(unicode) { - for (var i = 0; i < unicodeRanges.length; i += 1) { - var range = unicodeRanges[i]; - if (unicode >= range.begin && unicode < range.end) { - return i; - } - } + while (true) { + if (!currentParentIsValid) { + var parent = node.return; - return -1; -} + findParent: while (true) { + if (parent === null) { + throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.'); + } -// Parse the OS/2 and Windows metrics `OS/2` table -function parseOS2Table(data, start) { - var os2 = {}; - var p = new parse.Parser(data, start); - os2.version = p.parseUShort(); - os2.xAvgCharWidth = p.parseShort(); - os2.usWeightClass = p.parseUShort(); - os2.usWidthClass = p.parseUShort(); - os2.fsType = p.parseUShort(); - os2.ySubscriptXSize = p.parseShort(); - os2.ySubscriptYSize = p.parseShort(); - os2.ySubscriptXOffset = p.parseShort(); - os2.ySubscriptYOffset = p.parseShort(); - os2.ySuperscriptXSize = p.parseShort(); - os2.ySuperscriptYSize = p.parseShort(); - os2.ySuperscriptXOffset = p.parseShort(); - os2.ySuperscriptYOffset = p.parseShort(); - os2.yStrikeoutSize = p.parseShort(); - os2.yStrikeoutPosition = p.parseShort(); - os2.sFamilyClass = p.parseShort(); - os2.panose = []; - for (var i = 0; i < 10; i++) { - os2.panose[i] = p.parseByte(); - } + var parentStateNode = parent.stateNode; - os2.ulUnicodeRange1 = p.parseULong(); - os2.ulUnicodeRange2 = p.parseULong(); - os2.ulUnicodeRange3 = p.parseULong(); - os2.ulUnicodeRange4 = p.parseULong(); - os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); - os2.fsSelection = p.parseUShort(); - os2.usFirstCharIndex = p.parseUShort(); - os2.usLastCharIndex = p.parseUShort(); - os2.sTypoAscender = p.parseShort(); - os2.sTypoDescender = p.parseShort(); - os2.sTypoLineGap = p.parseShort(); - os2.usWinAscent = p.parseUShort(); - os2.usWinDescent = p.parseUShort(); - if (os2.version >= 1) { - os2.ulCodePageRange1 = p.parseULong(); - os2.ulCodePageRange2 = p.parseULong(); - } + switch (parent.tag) { + case HostComponent: + currentParent = parentStateNode; + currentParentIsContainer = false; + break findParent; - if (os2.version >= 2) { - os2.sxHeight = p.parseShort(); - os2.sCapHeight = p.parseShort(); - os2.usDefaultChar = p.parseUShort(); - os2.usBreakChar = p.parseUShort(); - os2.usMaxContent = p.parseUShort(); - } + case HostRoot: + currentParent = parentStateNode.containerInfo; + currentParentIsContainer = true; + break findParent; - return os2; -} - -function makeOS2Table(options) { - return new table.Table('OS/2', [ - {name: 'version', type: 'USHORT', value: 0x0003}, - {name: 'xAvgCharWidth', type: 'SHORT', value: 0}, - {name: 'usWeightClass', type: 'USHORT', value: 0}, - {name: 'usWidthClass', type: 'USHORT', value: 0}, - {name: 'fsType', type: 'USHORT', value: 0}, - {name: 'ySubscriptXSize', type: 'SHORT', value: 650}, - {name: 'ySubscriptYSize', type: 'SHORT', value: 699}, - {name: 'ySubscriptXOffset', type: 'SHORT', value: 0}, - {name: 'ySubscriptYOffset', type: 'SHORT', value: 140}, - {name: 'ySuperscriptXSize', type: 'SHORT', value: 650}, - {name: 'ySuperscriptYSize', type: 'SHORT', value: 699}, - {name: 'ySuperscriptXOffset', type: 'SHORT', value: 0}, - {name: 'ySuperscriptYOffset', type: 'SHORT', value: 479}, - {name: 'yStrikeoutSize', type: 'SHORT', value: 49}, - {name: 'yStrikeoutPosition', type: 'SHORT', value: 258}, - {name: 'sFamilyClass', type: 'SHORT', value: 0}, - {name: 'bFamilyType', type: 'BYTE', value: 0}, - {name: 'bSerifStyle', type: 'BYTE', value: 0}, - {name: 'bWeight', type: 'BYTE', value: 0}, - {name: 'bProportion', type: 'BYTE', value: 0}, - {name: 'bContrast', type: 'BYTE', value: 0}, - {name: 'bStrokeVariation', type: 'BYTE', value: 0}, - {name: 'bArmStyle', type: 'BYTE', value: 0}, - {name: 'bLetterform', type: 'BYTE', value: 0}, - {name: 'bMidline', type: 'BYTE', value: 0}, - {name: 'bXHeight', type: 'BYTE', value: 0}, - {name: 'ulUnicodeRange1', type: 'ULONG', value: 0}, - {name: 'ulUnicodeRange2', type: 'ULONG', value: 0}, - {name: 'ulUnicodeRange3', type: 'ULONG', value: 0}, - {name: 'ulUnicodeRange4', type: 'ULONG', value: 0}, - {name: 'achVendID', type: 'CHARARRAY', value: 'XXXX'}, - {name: 'fsSelection', type: 'USHORT', value: 0}, - {name: 'usFirstCharIndex', type: 'USHORT', value: 0}, - {name: 'usLastCharIndex', type: 'USHORT', value: 0}, - {name: 'sTypoAscender', type: 'SHORT', value: 0}, - {name: 'sTypoDescender', type: 'SHORT', value: 0}, - {name: 'sTypoLineGap', type: 'SHORT', value: 0}, - {name: 'usWinAscent', type: 'USHORT', value: 0}, - {name: 'usWinDescent', type: 'USHORT', value: 0}, - {name: 'ulCodePageRange1', type: 'ULONG', value: 0}, - {name: 'ulCodePageRange2', type: 'ULONG', value: 0}, - {name: 'sxHeight', type: 'SHORT', value: 0}, - {name: 'sCapHeight', type: 'SHORT', value: 0}, - {name: 'usDefaultChar', type: 'USHORT', value: 0}, - {name: 'usBreakChar', type: 'USHORT', value: 0}, - {name: 'usMaxContext', type: 'USHORT', value: 0} - ], options); -} - -var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges: unicodeRanges, getUnicodeRange: getUnicodeRange }; - -// The `post` table stores additional PostScript information, such as glyph names. - -// Parse the PostScript `post` table -function parsePostTable(data, start) { - var post = {}; - var p = new parse.Parser(data, start); - post.version = p.parseVersion(); - post.italicAngle = p.parseFixed(); - post.underlinePosition = p.parseShort(); - post.underlineThickness = p.parseShort(); - post.isFixedPitch = p.parseULong(); - post.minMemType42 = p.parseULong(); - post.maxMemType42 = p.parseULong(); - post.minMemType1 = p.parseULong(); - post.maxMemType1 = p.parseULong(); - switch (post.version) { - case 1: - post.names = standardNames.slice(); - break; - case 2: - post.numberOfGlyphs = p.parseUShort(); - post.glyphNameIndex = new Array(post.numberOfGlyphs); - for (var i = 0; i < post.numberOfGlyphs; i++) { - post.glyphNameIndex[i] = p.parseUShort(); - } + case HostPortal: + currentParent = parentStateNode.containerInfo; + currentParentIsContainer = true; + break findParent; + } - post.names = []; - for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) { - if (post.glyphNameIndex[i$1] >= standardNames.length) { - var nameLength = p.parseChar(); - post.names.push(p.parseString(nameLength)); - } - } + parent = parent.return; + } - break; - case 2.5: - post.numberOfGlyphs = p.parseUShort(); - post.offset = new Array(post.numberOfGlyphs); - for (var i$2 = 0; i$2 < post.numberOfGlyphs; i$2++) { - post.offset[i$2] = p.parseChar(); - } + currentParentIsValid = true; + } - break; - } - return post; -} - -function makePostTable() { - return new table.Table('post', [ - {name: 'version', type: 'FIXED', value: 0x00030000}, - {name: 'italicAngle', type: 'FIXED', value: 0}, - {name: 'underlinePosition', type: 'FWORD', value: 0}, - {name: 'underlineThickness', type: 'FWORD', value: 0}, - {name: 'isFixedPitch', type: 'ULONG', value: 0}, - {name: 'minMemType42', type: 'ULONG', value: 0}, - {name: 'maxMemType42', type: 'ULONG', value: 0}, - {name: 'minMemType1', type: 'ULONG', value: 0}, - {name: 'maxMemType1', type: 'ULONG', value: 0} - ]); -} + if (node.tag === HostComponent || node.tag === HostText) { + commitNestedUnmounts(finishedRoot, node, nearestMountedAncestor); // After all the children have unmounted, it is now safe to remove the + // node from the tree. -var post = { parse: parsePostTable, make: makePostTable }; + if (currentParentIsContainer) { + removeChildFromContainer(currentParent, node.stateNode); + } else { + removeChild(currentParent, node.stateNode); + } // Don't visit children because we already visited them. -// The `GSUB` table contains ligatures, among other things. + } else if ( node.tag === DehydratedFragment) { -var subtableParsers = new Array(9); // subtableParsers[0] is unused -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS -subtableParsers[1] = function parseLookup1() { - var start = this.offset + this.relativeOffset; - var substFormat = this.parseUShort(); - if (substFormat === 1) { - return { - substFormat: 1, - coverage: this.parsePointer(Parser.coverage), - deltaGlyphId: this.parseUShort() - }; - } else if (substFormat === 2) { - return { - substFormat: 2, - coverage: this.parsePointer(Parser.coverage), - substitute: this.parseOffset16List() - }; - } - check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.'); -}; + if (currentParentIsContainer) { + clearSuspenseBoundaryFromContainer(currentParent, node.stateNode); + } else { + clearSuspenseBoundary(currentParent, node.stateNode); + } + } else if (node.tag === HostPortal) { + if (node.child !== null) { + // When we go into a portal, it becomes the parent to remove from. + // We will reassign it back when we pop the portal on the way up. + currentParent = node.stateNode.containerInfo; + currentParentIsContainer = true; // Visit children because portals might contain host components. -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS -subtableParsers[2] = function parseLookup2() { - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1'); - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - sequences: this.parseListOfLists() - }; -}; + node.child.return = node; + node = node.child; + continue; + } + } else { + commitUnmount(finishedRoot, node, nearestMountedAncestor); // Visit children because we may find more host components below. -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS -subtableParsers[3] = function parseLookup3() { - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1'); - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - alternateSets: this.parseListOfLists() - }; -}; + if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS -subtableParsers[4] = function parseLookup4() { - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1'); - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - ligatureSets: this.parseListOfLists(function() { - return { - ligGlyph: this.parseUShort(), - components: this.parseUShortList(this.parseUShort() - 1) - }; - }) - }; -}; + if (node === current) { + return; + } -var lookupRecordDesc = { - sequenceIndex: Parser.uShort, - lookupListIndex: Parser.uShort -}; + while (node.sibling === null) { + if (node.return === null || node.return === current) { + return; + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF -subtableParsers[5] = function parseLookup5() { - var start = this.offset + this.relativeOffset; - var substFormat = this.parseUShort(); + node = node.return; - if (substFormat === 1) { - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - ruleSets: this.parseListOfLists(function() { - var glyphCount = this.parseUShort(); - var substCount = this.parseUShort(); - return { - input: this.parseUShortList(glyphCount - 1), - lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) - }; - }) - }; - } else if (substFormat === 2) { - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - classDef: this.parsePointer(Parser.classDef), - classSets: this.parseListOfLists(function() { - var glyphCount = this.parseUShort(); - var substCount = this.parseUShort(); - return { - classes: this.parseUShortList(glyphCount - 1), - lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) - }; - }) - }; - } else if (substFormat === 3) { - var glyphCount = this.parseUShort(); - var substCount = this.parseUShort(); - return { - substFormat: substFormat, - coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), - lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) - }; - } - check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.'); -}; + if (node.tag === HostPortal) { + // When we go out of the portal, we need to restore the parent. + // Since we don't keep a stack of them, we will search for it. + currentParentIsValid = false; + } + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC -subtableParsers[6] = function parseLookup6() { - var start = this.offset + this.relativeOffset; - var substFormat = this.parseUShort(); - if (substFormat === 1) { - return { - substFormat: 1, - coverage: this.parsePointer(Parser.coverage), - chainRuleSets: this.parseListOfLists(function() { - return { - backtrack: this.parseUShortList(), - input: this.parseUShortList(this.parseShort() - 1), - lookahead: this.parseUShortList(), - lookupRecords: this.parseRecordList(lookupRecordDesc) - }; - }) - }; - } else if (substFormat === 2) { - return { - substFormat: 2, - coverage: this.parsePointer(Parser.coverage), - backtrackClassDef: this.parsePointer(Parser.classDef), - inputClassDef: this.parsePointer(Parser.classDef), - lookaheadClassDef: this.parsePointer(Parser.classDef), - chainClassSet: this.parseListOfLists(function() { - return { - backtrack: this.parseUShortList(), - input: this.parseUShortList(this.parseShort() - 1), - lookahead: this.parseUShortList(), - lookupRecords: this.parseRecordList(lookupRecordDesc) - }; - }) - }; - } else if (substFormat === 3) { - return { - substFormat: 3, - backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), - inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), - lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), - lookupRecords: this.parseRecordList(lookupRecordDesc) - }; - } - check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.'); -}; + node.sibling.return = node.return; + node = node.sibling; + } + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES -subtableParsers[7] = function parseLookup7() { - // Extension Substitution subtable - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1'); - var extensionLookupType = this.parseUShort(); - var extensionParser = new Parser(this.data, this.offset + this.parseULong()); - return { - substFormat: 1, - lookupType: extensionLookupType, - extension: subtableParsers[extensionLookupType].call(extensionParser) - }; -}; + function commitDeletion(finishedRoot, current, nearestMountedAncestor) { + if (supportsMutation) { + // Recursively delete all host nodes from the parent. + // Detach refs and call componentWillUnmount() on the whole subtree. + unmountHostComponents(finishedRoot, current, nearestMountedAncestor); + } else { + // Detach refs and call componentWillUnmount() on the whole subtree. + commitNestedUnmounts(finishedRoot, current, nearestMountedAncestor); + } -// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS -subtableParsers[8] = function parseLookup8() { - var substFormat = this.parseUShort(); - check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1'); - return { - substFormat: substFormat, - coverage: this.parsePointer(Parser.coverage), - backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), - lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), - substitutes: this.parseUShortList() - }; -}; + detachFiberMutation(current); + } -// https://www.microsoft.com/typography/OTSPEC/gsub.htm -function parseGsubTable(data, start) { - start = start || 0; - var p = new Parser(data, start); - var tableVersion = p.parseVersion(1); - check.argument(tableVersion === 1 || tableVersion === 1.1, 'Unsupported GSUB table version.'); - if (tableVersion === 1) { - return { - version: tableVersion, - scripts: p.parseScriptList(), - features: p.parseFeatureList(), - lookups: p.parseLookupList(subtableParsers) - }; - } else { - return { - version: tableVersion, - scripts: p.parseScriptList(), - features: p.parseFeatureList(), - lookups: p.parseLookupList(subtableParsers), - variations: p.parseFeatureVariationsList() - }; - } + function commitWork(current, finishedWork) { + if (!supportsMutation) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: + { + commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); + commitHookEffectListMount(Insertion | HasEffect, finishedWork); // Layout effects are destroyed during the mutation phase so that all + // destroy functions for all fibers are called before any create functions. + // This prevents sibling component effects from interfering with each other, + // e.g. a destroy function in one component should never override a ref set + // by a create function in another component during the same commit. + // TODO: Check if we're inside an Offscreen subtree that disappeared + // during this commit. If so, we would have already unmounted its + // layout hooks. (However, since we null out the `destroy` function + // right before calling it, the behavior is already correct, so this + // would mostly be for modeling purposes.) -} + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } -// GSUB Writing ////////////////////////////////////////////// -var subtableMakers = new Array(9); + return; + } -subtableMakers[1] = function makeLookup1(subtable) { - if (subtable.substFormat === 1) { - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 1}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}, - {name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId} - ]); - } else { - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 2}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.ushortList('substitute', subtable.substitute))); - } -}; + case Profiler: + { + return; + } -subtableMakers[2] = function makeLookup2(subtable) { - check.assert(subtable.substFormat === 1, 'Lookup type 2 substFormat must be 1.'); - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 1}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.tableList('seqSet', subtable.sequences, function(sequenceSet) { - return new table.Table('sequenceSetTable', table.ushortList('sequence', sequenceSet)); - }))); -}; + case SuspenseComponent: + { + commitSuspenseCallback(finishedWork); + attachSuspenseRetryListeners(finishedWork); + return; + } -subtableMakers[3] = function makeLookup3(subtable) { - check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.'); - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 1}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.tableList('altSet', subtable.alternateSets, function(alternateSet) { - return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet)); - }))); -}; + case SuspenseListComponent: + { + attachSuspenseRetryListeners(finishedWork); + return; + } -subtableMakers[4] = function makeLookup4(subtable) { - check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.'); - return new table.Table('substitutionTable', [ - {name: 'substFormat', type: 'USHORT', value: 1}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) { - return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function(ligature) { - return new table.Table('ligatureTable', - [{name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph}] - .concat(table.ushortList('component', ligature.components, ligature.components.length + 1)) - ); - })); - }))); -}; + case HostRoot: + { + if (supportsHydration) { + if (current !== null) { + var prevRootState = current.memoizedState; -subtableMakers[6] = function makeLookup6(subtable) { - if (subtable.substFormat === 1) { - var returnTable = new table.Table('chainContextTable', [ - {name: 'substFormat', type: 'USHORT', value: subtable.substFormat}, - {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} - ].concat(table.tableList('chainRuleSet', subtable.chainRuleSets, function(chainRuleSet) { - return new table.Table('chainRuleSetTable', table.tableList('chainRule', chainRuleSet, function(chainRule) { - var tableData = table.ushortList('backtrackGlyph', chainRule.backtrack, chainRule.backtrack.length) - .concat(table.ushortList('inputGlyph', chainRule.input, chainRule.input.length + 1)) - .concat(table.ushortList('lookaheadGlyph', chainRule.lookahead, chainRule.lookahead.length)) - .concat(table.ushortList('substitution', [], chainRule.lookupRecords.length)); - - chainRule.lookupRecords.forEach(function (record, i) { - tableData = tableData - .concat({name: 'sequenceIndex' + i, type: 'USHORT', value: record.sequenceIndex}) - .concat({name: 'lookupListIndex' + i, type: 'USHORT', value: record.lookupListIndex}); - }); - return new table.Table('chainRuleTable', tableData); - })); - }))); - return returnTable; - } else if (subtable.substFormat === 2) { - check.assert(false, 'lookup type 6 format 2 is not yet supported.'); - } else if (subtable.substFormat === 3) { - var tableData = [ - {name: 'substFormat', type: 'USHORT', value: subtable.substFormat} ]; - - tableData.push({name: 'backtrackGlyphCount', type: 'USHORT', value: subtable.backtrackCoverage.length}); - subtable.backtrackCoverage.forEach(function (coverage, i) { - tableData.push({name: 'backtrackCoverage' + i, type: 'TABLE', value: new table.Coverage(coverage)}); - }); - tableData.push({name: 'inputGlyphCount', type: 'USHORT', value: subtable.inputCoverage.length}); - subtable.inputCoverage.forEach(function (coverage, i) { - tableData.push({name: 'inputCoverage' + i, type: 'TABLE', value: new table.Coverage(coverage)}); - }); - tableData.push({name: 'lookaheadGlyphCount', type: 'USHORT', value: subtable.lookaheadCoverage.length}); - subtable.lookaheadCoverage.forEach(function (coverage, i) { - tableData.push({name: 'lookaheadCoverage' + i, type: 'TABLE', value: new table.Coverage(coverage)}); - }); + if (prevRootState.isDehydrated) { + var root = finishedWork.stateNode; + commitHydratedContainer(root.containerInfo); + } + } + } - tableData.push({name: 'substitutionCount', type: 'USHORT', value: subtable.lookupRecords.length}); - subtable.lookupRecords.forEach(function (record, i) { - tableData = tableData - .concat({name: 'sequenceIndex' + i, type: 'USHORT', value: record.sequenceIndex}) - .concat({name: 'lookupListIndex' + i, type: 'USHORT', value: record.lookupListIndex}); - }); + break; + } - var returnTable$1 = new table.Table('chainContextTable', tableData); + case OffscreenComponent: + case LegacyHiddenComponent: + { + return; + } + } - return returnTable$1; - } + commitContainer(finishedWork); + return; + } - check.assert(false, 'lookup type 6 format must be 1, 2 or 3.'); -}; + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: + { + commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); + commitHookEffectListMount(Insertion | HasEffect, finishedWork); // Layout effects are destroyed during the mutation phase so that all + // destroy functions for all fibers are called before any create functions. + // This prevents sibling component effects from interfering with each other, + // e.g. a destroy function in one component should never override a ref set + // by a create function in another component during the same commit. -function makeGsubTable(gsub) { - return new table.Table('GSUB', [ - {name: 'version', type: 'ULONG', value: 0x10000}, - {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gsub.scripts)}, - {name: 'features', type: 'TABLE', value: new table.FeatureList(gsub.features)}, - {name: 'lookups', type: 'TABLE', value: new table.LookupList(gsub.lookups, subtableMakers)} - ]); -} + if ( finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } finally { + recordLayoutEffectDuration(finishedWork); + } + } else { + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } -var gsub = { parse: parseGsubTable, make: makeGsubTable }; + return; + } -// The `GPOS` table contains kerning pairs, among other things. + case ClassComponent: + { + return; + } -// Parse the metadata `meta` table. -// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html -function parseMetaTable(data, start) { - var p = new parse.Parser(data, start); - var tableVersion = p.parseULong(); - check.argument(tableVersion === 1, 'Unsupported META table version.'); - p.parseULong(); // flags - currently unused and set to 0 - p.parseULong(); // tableOffset - var numDataMaps = p.parseULong(); + case HostComponent: + { + var instance = finishedWork.stateNode; - var tags = {}; - for (var i = 0; i < numDataMaps; i++) { - var tag = p.parseTag(); - var dataOffset = p.parseULong(); - var dataLength = p.parseULong(); - var text = decode.UTF8(data, start + dataOffset, dataLength); + if (instance != null) { + // Commit the work prepared earlier. + var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps + // as the newProps. The updatePayload will contain the real change in + // this case. - tags[tag] = text; - } - return tags; -} + var oldProps = current !== null ? current.memoizedProps : newProps; + var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. -function makeMetaTable(tags) { - var numTags = Object.keys(tags).length; - var stringPool = ''; - var stringPoolOffset = 16 + numTags * 12; + var updatePayload = finishedWork.updateQueue; + finishedWork.updateQueue = null; - var result = new table.Table('meta', [ - {name: 'version', type: 'ULONG', value: 1}, - {name: 'flags', type: 'ULONG', value: 0}, - {name: 'offset', type: 'ULONG', value: stringPoolOffset}, - {name: 'numTags', type: 'ULONG', value: numTags} - ]); + if (updatePayload !== null) { + commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork); + } + } - for (var tag in tags) { - var pos = stringPool.length; - stringPool += tags[tag]; + return; + } - result.fields.push({name: 'tag ' + tag, type: 'TAG', value: tag}); - result.fields.push({name: 'offset ' + tag, type: 'ULONG', value: stringPoolOffset + pos}); - result.fields.push({name: 'length ' + tag, type: 'ULONG', value: tags[tag].length}); - } + case HostText: + { + if (finishedWork.stateNode === null) { + throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.'); + } - result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); + var textInstance = finishedWork.stateNode; + var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps + // as the newProps. The updatePayload will contain the real change in + // this case. - return result; -} + var oldText = current !== null ? current.memoizedProps : newText; + commitTextUpdate(textInstance, oldText, newText); + return; + } -var meta = { parse: parseMetaTable, make: makeMetaTable }; + case HostRoot: + { + if (supportsHydration) { + if (current !== null) { + var _prevRootState = current.memoizedState; -// The `sfnt` wrapper provides organization for the tables in the font. + if (_prevRootState.isDehydrated) { + var _root = finishedWork.stateNode; + commitHydratedContainer(_root.containerInfo); + } + } + } -function log2(v) { - return Math.log(v) / Math.log(2) | 0; -} + return; + } -function computeCheckSum(bytes) { - while (bytes.length % 4 !== 0) { - bytes.push(0); - } + case Profiler: + { + return; + } - var sum = 0; - for (var i = 0; i < bytes.length; i += 4) { - sum += (bytes[i] << 24) + - (bytes[i + 1] << 16) + - (bytes[i + 2] << 8) + - (bytes[i + 3]); - } + case SuspenseComponent: + { + commitSuspenseCallback(finishedWork); + attachSuspenseRetryListeners(finishedWork); + return; + } - sum %= Math.pow(2, 32); - return sum; -} + case SuspenseListComponent: + { + attachSuspenseRetryListeners(finishedWork); + return; + } -function makeTableRecord(tag, checkSum, offset, length) { - return new table.Record('Table Record', [ - {name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''}, - {name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0}, - {name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0}, - {name: 'length', type: 'ULONG', value: length !== undefined ? length : 0} - ]); -} + case IncompleteClassComponent: + { + return; + } + } -function makeSfntTable(tables) { - var sfnt = new table.Table('sfnt', [ - {name: 'version', type: 'TAG', value: 'OTTO'}, - {name: 'numTables', type: 'USHORT', value: 0}, - {name: 'searchRange', type: 'USHORT', value: 0}, - {name: 'entrySelector', type: 'USHORT', value: 0}, - {name: 'rangeShift', type: 'USHORT', value: 0} - ]); - sfnt.tables = tables; - sfnt.numTables = tables.length; - var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); - sfnt.searchRange = 16 * highestPowerOf2; - sfnt.entrySelector = log2(highestPowerOf2); - sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; - - var recordFields = []; - var tableFields = []; - - var offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables); - while (offset % 4 !== 0) { - offset += 1; - tableFields.push({name: 'padding', type: 'BYTE', value: 0}); - } + throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); + } - for (var i = 0; i < tables.length; i += 1) { - var t = tables[i]; - check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.'); - var tableLength = t.sizeOf(); - var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength); - recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord}); - tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t}); - offset += tableLength; - check.argument(!isNaN(offset), 'Something went wrong calculating the offset.'); - while (offset % 4 !== 0) { - offset += 1; - tableFields.push({name: 'padding', type: 'BYTE', value: 0}); - } - } + function commitSuspenseCallback(finishedWork) { + // TODO: Move this to passive phase + finishedWork.memoizedState; + } - // Table records need to be sorted alphabetically. - recordFields.sort(function(r1, r2) { - if (r1.value.tag > r2.value.tag) { - return 1; - } else { - return -1; - } - }); + function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { + if (!supportsHydration) { + return; + } - sfnt.fields = sfnt.fields.concat(recordFields); - sfnt.fields = sfnt.fields.concat(tableFields); - return sfnt; -} + var newState = finishedWork.memoizedState; -// Get the metrics for a character. If the string has more than one character -// this function returns metrics for the first available character. -// You can provide optional fallback metrics if no characters are available. -function metricsForChar(font, chars, notFoundMetrics) { - for (var i = 0; i < chars.length; i += 1) { - var glyphIndex = font.charToGlyphIndex(chars[i]); - if (glyphIndex > 0) { - var glyph = font.glyphs.get(glyphIndex); - return glyph.getMetrics(); - } - } + if (newState === null) { + var current = finishedWork.alternate; - return notFoundMetrics; -} + if (current !== null) { + var prevState = current.memoizedState; -function average(vs) { - var sum = 0; - for (var i = 0; i < vs.length; i += 1) { - sum += vs[i]; - } + if (prevState !== null) { + var suspenseInstance = prevState.dehydrated; - return sum / vs.length; -} - -// Convert the font object to a SFNT data structure. -// This structure contains all the necessary tables and metadata to create a binary OTF file. -function fontToSfntTable(font) { - var xMins = []; - var yMins = []; - var xMaxs = []; - var yMaxs = []; - var advanceWidths = []; - var leftSideBearings = []; - var rightSideBearings = []; - var firstCharIndex; - var lastCharIndex = 0; - var ulUnicodeRange1 = 0; - var ulUnicodeRange2 = 0; - var ulUnicodeRange3 = 0; - var ulUnicodeRange4 = 0; - - for (var i = 0; i < font.glyphs.length; i += 1) { - var glyph = font.glyphs.get(i); - var unicode = glyph.unicode | 0; - - if (isNaN(glyph.advanceWidth)) { - throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.'); - } + if (suspenseInstance !== null) { + commitHydratedSuspenseInstance(suspenseInstance); + } + } + } + } + } - if (firstCharIndex > unicode || firstCharIndex === undefined) { - // ignore .notdef char - if (unicode > 0) { - firstCharIndex = unicode; - } - } + function attachSuspenseRetryListeners(finishedWork) { + // If this boundary just timed out, then it will have a set of wakeables. + // For each wakeable, attach a listener so that when it resolves, React + // attempts to re-render the boundary in the primary (pre-timeout) state. + var wakeables = finishedWork.updateQueue; - if (lastCharIndex < unicode) { - lastCharIndex = unicode; - } + if (wakeables !== null) { + finishedWork.updateQueue = null; + var retryCache = finishedWork.stateNode; - var position = os2.getUnicodeRange(unicode); - if (position < 32) { - ulUnicodeRange1 |= 1 << position; - } else if (position < 64) { - ulUnicodeRange2 |= 1 << position - 32; - } else if (position < 96) { - ulUnicodeRange3 |= 1 << position - 64; - } else if (position < 123) { - ulUnicodeRange4 |= 1 << position - 96; - } else { - throw new Error('Unicode ranges bits > 123 are reserved for internal usage'); - } - // Skip non-important characters. - if (glyph.name === '.notdef') { continue; } - var metrics = glyph.getMetrics(); - xMins.push(metrics.xMin); - yMins.push(metrics.yMin); - xMaxs.push(metrics.xMax); - yMaxs.push(metrics.yMax); - leftSideBearings.push(metrics.leftSideBearing); - rightSideBearings.push(metrics.rightSideBearing); - advanceWidths.push(glyph.advanceWidth); - } + if (retryCache === null) { + retryCache = finishedWork.stateNode = new PossiblyWeakSet(); + } - var globals = { - xMin: Math.min.apply(null, xMins), - yMin: Math.min.apply(null, yMins), - xMax: Math.max.apply(null, xMaxs), - yMax: Math.max.apply(null, yMaxs), - advanceWidthMax: Math.max.apply(null, advanceWidths), - advanceWidthAvg: average(advanceWidths), - minLeftSideBearing: Math.min.apply(null, leftSideBearings), - maxLeftSideBearing: Math.max.apply(null, leftSideBearings), - minRightSideBearing: Math.min.apply(null, rightSideBearings) - }; - globals.ascender = font.ascender; - globals.descender = font.descender; - - var headTable = head.make({ - flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0) - unitsPerEm: font.unitsPerEm, - xMin: globals.xMin, - yMin: globals.yMin, - xMax: globals.xMax, - yMax: globals.yMax, - lowestRecPPEM: 3, - createdTimestamp: font.createdTimestamp - }); + wakeables.forEach(function (wakeable) { + // Memoize using the boundary fiber to prevent redundant listeners. + var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - var hheaTable = hhea.make({ - ascender: globals.ascender, - descender: globals.descender, - advanceWidthMax: globals.advanceWidthMax, - minLeftSideBearing: globals.minLeftSideBearing, - minRightSideBearing: globals.minRightSideBearing, - xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), - numberOfHMetrics: font.glyphs.length - }); + if (!retryCache.has(wakeable)) { + retryCache.add(wakeable); - var maxpTable = maxp.make(font.glyphs.length); - - var os2Table = os2.make(Object.assign({ - xAvgCharWidth: Math.round(globals.advanceWidthAvg), - usFirstCharIndex: firstCharIndex, - usLastCharIndex: lastCharIndex, - ulUnicodeRange1: ulUnicodeRange1, - ulUnicodeRange2: ulUnicodeRange2, - ulUnicodeRange3: ulUnicodeRange3, - ulUnicodeRange4: ulUnicodeRange4, - // See http://typophile.com/node/13081 for more info on vertical metrics. - // We get metrics for typical characters (such as "x" for xHeight). - // We provide some fallback characters if characters are unavailable: their - // ordering was chosen experimentally. - sTypoAscender: globals.ascender, - sTypoDescender: globals.descender, - sTypoLineGap: 0, - usWinAscent: globals.yMax, - usWinDescent: Math.abs(globals.yMin), - ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now - sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax, - sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax, - usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available. - usBreakChar: font.hasChar(' ') ? 32 : 0, // Use space as the break character, if available. - }, font.tables.os2)); - - var hmtxTable = hmtx.make(font.glyphs); - var cmapTable = cmap.make(font.glyphs); - - var englishFamilyName = font.getEnglishName('fontFamily'); - var englishStyleName = font.getEnglishName('fontSubfamily'); - var englishFullName = englishFamilyName + ' ' + englishStyleName; - var postScriptName = font.getEnglishName('postScriptName'); - if (!postScriptName) { - postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName; - } + { + if (isDevToolsPresent) { + if (inProgressLanes !== null && inProgressRoot !== null) { + // If we have pending work still, associate the original updaters with it. + restorePendingUpdaters(inProgressRoot, inProgressLanes); + } else { + throw Error('Expected finished root and lanes to be set. This is a bug in React.'); + } + } + } - var names = {}; - for (var n in font.names) { - names[n] = font.names[n]; - } + wakeable.then(retry, retry); + } + }); + } + } // This function detects when a Suspense boundary goes from visible to hidden. - if (!names.uniqueID) { - names.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName}; - } + function commitResetTextContent(current) { + if (!supportsMutation) { + return; + } - if (!names.postScriptName) { - names.postScriptName = {en: postScriptName}; - } + resetTextContent(current.stateNode); + } - if (!names.preferredFamily) { - names.preferredFamily = font.names.fontFamily; - } + function commitMutationEffects(root, firstChild, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + nextEffect = firstChild; + commitMutationEffects_begin(root, committedLanes); + inProgressLanes = null; + inProgressRoot = null; + } - if (!names.preferredSubfamily) { - names.preferredSubfamily = font.names.fontSubfamily; - } + function commitMutationEffects_begin(root, lanes) { + while (nextEffect !== null) { + var fiber = nextEffect; // TODO: Should wrap this in flags check, too, as optimization - var languageTags = []; - var nameTable = _name.make(names, languageTags); - var ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined); - - var postTable = post.make(); - var cffTable = cff.make(font.glyphs, { - version: font.getEnglishName('version'), - fullName: englishFullName, - familyName: englishFamilyName, - weightName: englishStyleName, - postScriptName: postScriptName, - unitsPerEm: font.unitsPerEm, - fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax] - }); + var deletions = fiber.deletions; - var metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined; + if (deletions !== null) { + for (var i = 0; i < deletions.length; i++) { + var childToDelete = deletions[i]; - // The order does not matter because makeSfntTable() will sort them. - var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable]; - if (ltagTable) { - tables.push(ltagTable); - } - // Optional tables - if (font.tables.gsub) { - tables.push(gsub.make(font.tables.gsub)); - } - if (metaTable) { - tables.push(metaTable); - } + try { + commitDeletion(root, childToDelete, fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(childToDelete, fiber, error); + } + } + } - var sfntTable = makeSfntTable(tables); - - // Compute the font's checkSum and store it in head.checkSumAdjustment. - var bytes = sfntTable.encode(); - var checkSum = computeCheckSum(bytes); - var tableFields = sfntTable.fields; - var checkSumAdjusted = false; - for (var i$1 = 0; i$1 < tableFields.length; i$1 += 1) { - if (tableFields[i$1].name === 'head table') { - tableFields[i$1].value.checkSumAdjustment = 0xB1B0AFBA - checkSum; - checkSumAdjusted = true; - break; - } - } + var child = fiber.child; - if (!checkSumAdjusted) { - throw new Error('Could not find head table with checkSum to adjust.'); - } + if ((fiber.subtreeFlags & MutationMask) !== NoFlags && child !== null) { + ensureCorrectReturnPointer(child, fiber); + nextEffect = child; + } else { + commitMutationEffects_complete(root, lanes); + } + } + } - return sfntTable; -} + function commitMutationEffects_complete(root, lanes) { + while (nextEffect !== null) { + var fiber = nextEffect; + setCurrentFiber(fiber); -var sfnt = { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum: computeCheckSum }; + try { + commitMutationEffectsOnFiber(fiber, root, lanes); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } -// The Layout object is the prototype of Substitution objects, and provides + resetCurrentFiber(); + var sibling = fiber.sibling; -function searchTag(arr, tag) { - /* jshint bitwise: false */ - var imin = 0; - var imax = arr.length - 1; - while (imin <= imax) { - var imid = (imin + imax) >>> 1; - var val = arr[imid].tag; - if (val === tag) { - return imid; - } else if (val < tag) { - imin = imid + 1; - } else { imax = imid - 1; } - } - // Not found: return -1-insertion point - return -imin - 1; -} - -function binSearch(arr, value) { - /* jshint bitwise: false */ - var imin = 0; - var imax = arr.length - 1; - while (imin <= imax) { - var imid = (imin + imax) >>> 1; - var val = arr[imid]; - if (val === value) { - return imid; - } else if (val < value) { - imin = imid + 1; - } else { imax = imid - 1; } - } - // Not found: return -1-insertion point - return -imin - 1; -} - -// binary search in a list of ranges (coverage, class definition) -function searchRange(ranges, value) { - // jshint bitwise: false - var range; - var imin = 0; - var imax = ranges.length - 1; - while (imin <= imax) { - var imid = (imin + imax) >>> 1; - range = ranges[imid]; - var start = range.start; - if (start === value) { - return range; - } else if (start < value) { - imin = imid + 1; - } else { imax = imid - 1; } - } - if (imin > 0) { - range = ranges[imin - 1]; - if (value > range.end) { return 0; } - return range; - } -} + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } -/** - * @exports opentype.Layout - * @class - */ -function Layout(font, tableName) { - this.font = font; - this.tableName = tableName; -} + nextEffect = fiber.return; + } + } -Layout.prototype = { + function commitMutationEffectsOnFiber(finishedWork, root, lanes) { + // TODO: The factoring of this phase could probably be improved. Consider + // switching on the type of work before checking the flags. That's what + // we do in all the other phases. I think this one is only different + // because of the shared reconciliation logic below. + var flags = finishedWork.flags; - /** - * Binary search an object by "tag" property - * @instance - * @function searchTag - * @memberof opentype.Layout - * @param {Array} arr - * @param {string} tag - * @return {number} - */ - searchTag: searchTag, + if (flags & ContentReset) { + commitResetTextContent(finishedWork); + } - /** - * Binary search in a list of numbers - * @instance - * @function binSearch - * @memberof opentype.Layout - * @param {Array} arr - * @param {number} value - * @return {number} - */ - binSearch: binSearch, + if (flags & Ref) { + var current = finishedWork.alternate; - /** - * Get or create the Layout table (GSUB, GPOS etc). - * @param {boolean} create - Whether to create a new one. - * @return {Object} The GSUB or GPOS table. - */ - getTable: function(create) { - var layout = this.font.tables[this.tableName]; - if (!layout && create) { - layout = this.font.tables[this.tableName] = this.createDefaultTable(); - } - return layout; - }, + if (current !== null) { + commitDetachRef(current); + } + } - /** - * Returns all scripts in the substitution table. - * @instance - * @return {Array} - */ - getScriptNames: function() { - var layout = this.getTable(); - if (!layout) { return []; } - return layout.scripts.map(function(script) { - return script.tag; - }); - }, + if (flags & Visibility) { + switch (finishedWork.tag) { + case SuspenseComponent: + { + var newState = finishedWork.memoizedState; + var isHidden = newState !== null; - /** - * Returns the best bet for a script name. - * Returns 'DFLT' if it exists. - * If not, returns 'latn' if it exists. - * If neither exist, returns undefined. - */ - getDefaultScriptName: function() { - var layout = this.getTable(); - if (!layout) { return; } - var hasLatn = false; - for (var i = 0; i < layout.scripts.length; i++) { - var name = layout.scripts[i].tag; - if (name === 'DFLT') { return name; } - if (name === 'latn') { hasLatn = true; } - } - if (hasLatn) { return 'latn'; } - }, + if (isHidden) { + var _current = finishedWork.alternate; + var wasHidden = _current !== null && _current.memoizedState !== null; - /** - * Returns all LangSysRecords in the given script. - * @instance - * @param {string} [script='DFLT'] - * @param {boolean} create - forces the creation of this script table if it doesn't exist. - * @return {Object} An object with tag and script properties. - */ - getScriptTable: function(script, create) { - var layout = this.getTable(create); - if (layout) { - script = script || 'DFLT'; - var scripts = layout.scripts; - var pos = searchTag(layout.scripts, script); - if (pos >= 0) { - return scripts[pos].script; - } else if (create) { - var scr = { - tag: script, - script: { - defaultLangSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []}, - langSysRecords: [] - } - }; - scripts.splice(-1 - pos, 0, scr); - return scr.script; - } - } - }, + if (!wasHidden) { + // TODO: Move to passive phase + markCommitTimeOfFallback(); + } + } - /** - * Returns a language system table - * @instance - * @param {string} [script='DFLT'] - * @param {string} [language='dlft'] - * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist. - * @return {Object} - */ - getLangSysTable: function(script, language, create) { - var scriptTable = this.getScriptTable(script, create); - if (scriptTable) { - if (!language || language === 'dflt' || language === 'DFLT') { - return scriptTable.defaultLangSys; - } - var pos = searchTag(scriptTable.langSysRecords, language); - if (pos >= 0) { - return scriptTable.langSysRecords[pos].langSys; - } else if (create) { - var langSysRecord = { - tag: language, - langSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []} - }; - scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); - return langSysRecord.langSys; - } - } - }, + break; + } - /** - * Get a specific feature table. - * @instance - * @param {string} [script='DFLT'] - * @param {string} [language='dlft'] - * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm - * @param {boolean} create - forces the creation of the feature table if it doesn't exist. - * @return {Object} - */ - getFeatureTable: function(script, language, feature, create) { - var langSysTable = this.getLangSysTable(script, language, create); - if (langSysTable) { - var featureRecord; - var featIndexes = langSysTable.featureIndexes; - var allFeatures = this.font.tables[this.tableName].features; - // The FeatureIndex array of indices is in arbitrary order, - // even if allFeatures is sorted alphabetically by feature tag. - for (var i = 0; i < featIndexes.length; i++) { - featureRecord = allFeatures[featIndexes[i]]; - if (featureRecord.tag === feature) { - return featureRecord.feature; - } - } - if (create) { - var index = allFeatures.length; - // Automatic ordering of features would require to shift feature indexes in the script list. - check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.'); - featureRecord = { - tag: feature, - feature: { params: 0, lookupListIndexes: [] } - }; - allFeatures.push(featureRecord); - featIndexes.push(index); - return featureRecord.feature; - } - } - }, + case OffscreenComponent: + { + var _newState = finishedWork.memoizedState; - /** - * Get the lookup tables of a given type for a script/language/feature. - * @instance - * @param {string} [script='DFLT'] - * @param {string} [language='dlft'] - * @param {string} feature - 4-letter feature code - * @param {number} lookupType - 1 to 9 - * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables. - * @return {Object[]} - */ - getLookupTables: function(script, language, feature, lookupType, create) { - var featureTable = this.getFeatureTable(script, language, feature, create); - var tables = []; - if (featureTable) { - var lookupTable; - var lookupListIndexes = featureTable.lookupListIndexes; - var allLookups = this.font.tables[this.tableName].lookups; - // lookupListIndexes are in no particular order, so use naive search. - for (var i = 0; i < lookupListIndexes.length; i++) { - lookupTable = allLookups[lookupListIndexes[i]]; - if (lookupTable.lookupType === lookupType) { - tables.push(lookupTable); - } - } - if (tables.length === 0 && create) { - lookupTable = { - lookupType: lookupType, - lookupFlag: 0, - subtables: [], - markFilteringSet: undefined - }; - var index = allLookups.length; - allLookups.push(lookupTable); - lookupListIndexes.push(index); - return [lookupTable]; - } - } - return tables; - }, + var _isHidden = _newState !== null; - /** - * Find a glyph in a class definition table - * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table - * @param {object} classDefTable - an OpenType Layout class definition table - * @param {number} glyphIndex - the index of the glyph to find - * @returns {number} -1 if not found - */ - getGlyphClass: function(classDefTable, glyphIndex) { - switch (classDefTable.format) { - case 1: - if (classDefTable.startGlyph <= glyphIndex && glyphIndex < classDefTable.startGlyph + classDefTable.classes.length) { - return classDefTable.classes[glyphIndex - classDefTable.startGlyph]; - } - return 0; - case 2: - var range = searchRange(classDefTable.ranges, glyphIndex); - return range ? range.classId : 0; - } - }, + var _current2 = finishedWork.alternate; - /** - * Find a glyph in a coverage table - * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-table - * @param {object} coverageTable - an OpenType Layout coverage table - * @param {number} glyphIndex - the index of the glyph to find - * @returns {number} -1 if not found - */ - getCoverageIndex: function(coverageTable, glyphIndex) { - switch (coverageTable.format) { - case 1: - var index = binSearch(coverageTable.glyphs, glyphIndex); - return index >= 0 ? index : -1; - case 2: - var range = searchRange(coverageTable.ranges, glyphIndex); - return range ? range.index + glyphIndex - range.start : -1; - } - }, + var _wasHidden = _current2 !== null && _current2.memoizedState !== null; - /** - * Returns the list of glyph indexes of a coverage table. - * Format 1: the list is stored raw - * Format 2: compact list as range records. - * @instance - * @param {Object} coverageTable - * @return {Array} - */ - expandCoverage: function(coverageTable) { - if (coverageTable.format === 1) { - return coverageTable.glyphs; - } else { - var glyphs = []; - var ranges = coverageTable.ranges; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - var start = range.start; - var end = range.end; - for (var j = start; j <= end; j++) { - glyphs.push(j); - } - } - return glyphs; - } - } + var offscreenBoundary = finishedWork; -}; + if (supportsMutation) { + // TODO: This needs to run whenever there's an insertion or update + // inside a hidden Offscreen tree. + hideOrUnhideAllChildren(offscreenBoundary, _isHidden); + } -// The Position object provides utility methods to manipulate + { + if (_isHidden) { + if (!_wasHidden) { + if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) { + nextEffect = offscreenBoundary; + var offscreenChild = offscreenBoundary.child; -/** - * @exports opentype.Position - * @class - * @extends opentype.Layout - * @param {opentype.Font} - * @constructor - */ -function Position(font) { - Layout.call(this, font, 'gpos'); -} + while (offscreenChild !== null) { + nextEffect = offscreenChild; + disappearLayoutEffects_begin(offscreenChild); + offscreenChild = offscreenChild.sibling; + } + } + } + } -Position.prototype = Layout.prototype; + break; + } + } + } + } // The following switch statement is only concerned about placement, + // updates, and deletions. To avoid needing to add a case for every possible + // bitmap value, we remove the secondary effects from the effect tag and + // switch on that value. -/** - * Init some data for faster and easier access later. - */ -Position.prototype.init = function() { - var script = this.getDefaultScriptName(); - this.defaultKerningTables = this.getKerningTables(script); -}; -/** - * Find a glyph pair in a list of lookup tables of type 2 and retrieve the xAdvance kerning value. - * - * @param {integer} leftIndex - left glyph index - * @param {integer} rightIndex - right glyph index - * @returns {integer} - */ -Position.prototype.getKerningValue = function(kerningLookups, leftIndex, rightIndex) { - for (var i = 0; i < kerningLookups.length; i++) { - var subtables = kerningLookups[i].subtables; - for (var j = 0; j < subtables.length; j++) { - var subtable = subtables[j]; - var covIndex = this.getCoverageIndex(subtable.coverage, leftIndex); - if (covIndex < 0) { continue; } - switch (subtable.posFormat) { - case 1: - // Search Pair Adjustment Positioning Format 1 - var pairSet = subtable.pairSets[covIndex]; - for (var k = 0; k < pairSet.length; k++) { - var pair = pairSet[k]; - if (pair.secondGlyph === rightIndex) { - return pair.value1 && pair.value1.xAdvance || 0; - } - } - break; // left glyph found, not right glyph - try next subtable - case 2: - // Search Pair Adjustment Positioning Format 2 - var class1 = this.getGlyphClass(subtable.classDef1, leftIndex); - var class2 = this.getGlyphClass(subtable.classDef2, rightIndex); - var pair$1 = subtable.classRecords[class1][class2]; - return pair$1.value1 && pair$1.value1.xAdvance || 0; - } - } - } - return 0; -}; + var primaryFlags = flags & (Placement | Update | Hydrating); -/** - * List all kerning lookup tables. - * - * @param {string} [script='DFLT'] - use font.position.getDefaultScriptName() for a better default value - * @param {string} [language='dflt'] - * @return {object[]} The list of kerning lookup tables (may be empty), or undefined if there is no GPOS table (and we should use the kern table) - */ -Position.prototype.getKerningTables = function(script, language) { - if (this.font.tables.gpos) { - return this.getLookupTables(script, language, 'kern', 2); - } -}; + switch (primaryFlags) { + case Placement: + { + commitPlacement(finishedWork); // Clear the "placement" from effect tag so that we know that this is + // inserted, before any life-cycles like componentDidMount gets called. + // TODO: findDOMNode doesn't rely on this any more but isMounted does + // and isMounted is deprecated anyway so we should be able to kill this. -// The Substitution object provides utility methods to manipulate + finishedWork.flags &= ~Placement; + break; + } -/** - * @exports opentype.Substitution - * @class - * @extends opentype.Layout - * @param {opentype.Font} - * @constructor - */ -function Substitution(font) { - Layout.call(this, font, 'gsub'); -} + case PlacementAndUpdate: + { + // Placement + commitPlacement(finishedWork); // Clear the "placement" from effect tag so that we know that this is + // inserted, before any life-cycles like componentDidMount gets called. -// Check if 2 arrays of primitives are equal. -function arraysEqual(ar1, ar2) { - var n = ar1.length; - if (n !== ar2.length) { return false; } - for (var i = 0; i < n; i++) { - if (ar1[i] !== ar2[i]) { return false; } - } - return true; -} + finishedWork.flags &= ~Placement; // Update -// Find the first subtable of a lookup table in a particular format. -function getSubstFormat(lookupTable, format, defaultSubtable) { - var subtables = lookupTable.subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - if (subtable.substFormat === format) { - return subtable; - } - } - if (defaultSubtable) { - subtables.push(defaultSubtable); - return defaultSubtable; - } - return undefined; -} + var _current3 = finishedWork.alternate; + commitWork(_current3, finishedWork); + break; + } -Substitution.prototype = Layout.prototype; + case Hydrating: + { + finishedWork.flags &= ~Hydrating; + break; + } -/** - * Create a default GSUB table. - * @return {Object} gsub - The GSUB table. - */ -Substitution.prototype.createDefaultTable = function() { - // Generate a default empty GSUB table with just a DFLT script and dflt lang sys. - return { - version: 1, - scripts: [{ - tag: 'DFLT', - script: { - defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] }, - langSysRecords: [] - } - }], - features: [], - lookups: [] - }; -}; + case HydratingAndUpdate: + { + finishedWork.flags &= ~Hydrating; // Update -/** - * List all single substitutions (lookup type 1) for a given script, language, and feature. - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...) - * @return {Array} substitutions - The list of substitutions. - */ -Substitution.prototype.getSingle = function(feature, script, language) { - var substitutions = []; - var lookupTables = this.getLookupTables(script, language, feature, 1); - for (var idx = 0; idx < lookupTables.length; idx++) { - var subtables = lookupTables[idx].subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - var glyphs = this.expandCoverage(subtable.coverage); - var j = (void 0); - if (subtable.substFormat === 1) { - var delta = subtable.deltaGlyphId; - for (j = 0; j < glyphs.length; j++) { - var glyph = glyphs[j]; - substitutions.push({ sub: glyph, by: glyph + delta }); - } - } else { - var substitute = subtable.substitute; - for (j = 0; j < glyphs.length; j++) { - substitutions.push({ sub: glyphs[j], by: substitute[j] }); - } - } - } - } - return substitutions; -}; + var _current4 = finishedWork.alternate; + commitWork(_current4, finishedWork); + break; + } -/** - * List all multiple substitutions (lookup type 2) for a given script, language, and feature. - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @param {string} feature - 4-character feature name ('ccmp', 'stch') - * @return {Array} substitutions - The list of substitutions. - */ -Substitution.prototype.getMultiple = function(feature, script, language) { - var substitutions = []; - var lookupTables = this.getLookupTables(script, language, feature, 2); - for (var idx = 0; idx < lookupTables.length; idx++) { - var subtables = lookupTables[idx].subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - var glyphs = this.expandCoverage(subtable.coverage); - var j = (void 0); - - for (j = 0; j < glyphs.length; j++) { - var glyph = glyphs[j]; - var replacements = subtable.sequences[j]; - substitutions.push({ sub: glyph, by: replacements }); - } - } - } - return substitutions; -}; + case Update: + { + var _current5 = finishedWork.alternate; + commitWork(_current5, finishedWork); + break; + } + } + } -/** - * List all alternates (lookup type 3) for a given script, language, and feature. - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @param {string} feature - 4-character feature name ('aalt', 'salt'...) - * @return {Array} alternates - The list of alternates - */ -Substitution.prototype.getAlternates = function(feature, script, language) { - var alternates = []; - var lookupTables = this.getLookupTables(script, language, feature, 3); - for (var idx = 0; idx < lookupTables.length; idx++) { - var subtables = lookupTables[idx].subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - var glyphs = this.expandCoverage(subtable.coverage); - var alternateSets = subtable.alternateSets; - for (var j = 0; j < glyphs.length; j++) { - alternates.push({ sub: glyphs[j], by: alternateSets[j] }); - } - } - } - return alternates; -}; + function commitLayoutEffects(finishedWork, root, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root; + nextEffect = finishedWork; + commitLayoutEffects_begin(finishedWork, root, committedLanes); + inProgressLanes = null; + inProgressRoot = null; + } -/** - * List all ligatures (lookup type 4) for a given script, language, and feature. - * The result is an array of ligature objects like { sub: [ids], by: id } - * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @return {Array} ligatures - The list of ligatures. - */ -Substitution.prototype.getLigatures = function(feature, script, language) { - var ligatures = []; - var lookupTables = this.getLookupTables(script, language, feature, 4); - for (var idx = 0; idx < lookupTables.length; idx++) { - var subtables = lookupTables[idx].subtables; - for (var i = 0; i < subtables.length; i++) { - var subtable = subtables[i]; - var glyphs = this.expandCoverage(subtable.coverage); - var ligatureSets = subtable.ligatureSets; - for (var j = 0; j < glyphs.length; j++) { - var startGlyph = glyphs[j]; - var ligSet = ligatureSets[j]; - for (var k = 0; k < ligSet.length; k++) { - var lig = ligSet[k]; - ligatures.push({ - sub: [startGlyph].concat(lig.components), - by: lig.ligGlyph - }); - } - } - } - } - return ligatures; -}; + function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) { + // Suspense layout effects semantics don't change for legacy roots. + var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode; -/** - * Add or modify a single substitution (lookup type 1) - * Format 2, more flexible, is always used. - * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) - * @param {Object} substitution - { sub: id, by: id } (format 1 is not supported) - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.addSingle = function(feature, substitution, script, language) { - var lookupTable = this.getLookupTables(script, language, feature, 1, true)[0]; - var subtable = getSubstFormat(lookupTable, 2, { // lookup type 1 subtable, format 2, coverage format 1 - substFormat: 2, - coverage: {format: 1, glyphs: []}, - substitute: [] - }); - check.assert(subtable.coverage.format === 1, 'Single: unable to modify coverage table format ' + subtable.coverage.format); - var coverageGlyph = substitution.sub; - var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); - if (pos < 0) { - pos = -1 - pos; - subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); - subtable.substitute.splice(pos, 0, 0); - } - subtable.substitute[pos] = substitution.by; -}; + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; -/** - * Add or modify a multiple substitution (lookup type 2) - * @param {string} feature - 4-letter feature name ('ccmp', 'stch') - * @param {Object} substitution - { sub: id, by: [id] } for format 2. - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.addMultiple = function(feature, substitution, script, language) { - check.assert(substitution.by instanceof Array && substitution.by.length > 1, 'Multiple: "by" must be an array of two or more ids'); - var lookupTable = this.getLookupTables(script, language, feature, 2, true)[0]; - var subtable = getSubstFormat(lookupTable, 1, { // lookup type 2 subtable, format 1, coverage format 1 - substFormat: 1, - coverage: {format: 1, glyphs: []}, - sequences: [] - }); - check.assert(subtable.coverage.format === 1, 'Multiple: unable to modify coverage table format ' + subtable.coverage.format); - var coverageGlyph = substitution.sub; - var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); - if (pos < 0) { - pos = -1 - pos; - subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); - subtable.sequences.splice(pos, 0, 0); - } - subtable.sequences[pos] = substitution.by; -}; + if ( fiber.tag === OffscreenComponent && isModernRoot) { + // Keep track of the current Offscreen stack's state. + var isHidden = fiber.memoizedState !== null; + var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; -/** - * Add or modify an alternate substitution (lookup type 3) - * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) - * @param {Object} substitution - { sub: id, by: [ids] } - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.addAlternate = function(feature, substitution, script, language) { - var lookupTable = this.getLookupTables(script, language, feature, 3, true)[0]; - var subtable = getSubstFormat(lookupTable, 1, { // lookup type 3 subtable, format 1, coverage format 1 - substFormat: 1, - coverage: {format: 1, glyphs: []}, - alternateSets: [] - }); - check.assert(subtable.coverage.format === 1, 'Alternate: unable to modify coverage table format ' + subtable.coverage.format); - var coverageGlyph = substitution.sub; - var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); - if (pos < 0) { - pos = -1 - pos; - subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); - subtable.alternateSets.splice(pos, 0, 0); - } - subtable.alternateSets[pos] = substitution.by; -}; + if (newOffscreenSubtreeIsHidden) { + // The Offscreen tree is hidden. Skip over its layout effects. + commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); + continue; + } else { + // TODO (Offscreen) Also check: subtreeFlags & LayoutMask + var current = fiber.alternate; + var wasHidden = current !== null && current.memoizedState !== null; + var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; + var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root. -/** - * Add a ligature (lookup type 4) - * Ligatures with more components must be stored ahead of those with fewer components in order to be found - * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) - * @param {Object} ligature - { sub: [ids], by: id } - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.addLigature = function(feature, ligature, script, language) { - var lookupTable = this.getLookupTables(script, language, feature, 4, true)[0]; - var subtable = lookupTable.subtables[0]; - if (!subtable) { - subtable = { // lookup type 4 subtable, format 1, coverage format 1 - substFormat: 1, - coverage: { format: 1, glyphs: [] }, - ligatureSets: [] - }; - lookupTable.subtables[0] = subtable; - } - check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); - var coverageGlyph = ligature.sub[0]; - var ligComponents = ligature.sub.slice(1); - var ligatureTable = { - ligGlyph: ligature.by, - components: ligComponents - }; - var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); - if (pos >= 0) { - // ligatureSet already exists - var ligatureSet = subtable.ligatureSets[pos]; - for (var i = 0; i < ligatureSet.length; i++) { - // If ligature already exists, return. - if (arraysEqual(ligatureSet[i].components, ligComponents)) { - return; - } - } - // ligature does not exist: add it. - ligatureSet.push(ligatureTable); - } else { - // Create a new ligatureSet and add coverage for the first glyph. - pos = -1 - pos; - subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); - subtable.ligatureSets.splice(pos, 0, [ligatureTable]); - } -}; + offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; -/** - * List all feature data for a given script and language. - * @param {string} feature - 4-letter feature name - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - * @return {Array} substitutions - The list of substitutions. - */ -Substitution.prototype.getFeature = function(feature, script, language) { - if (/ss\d\d/.test(feature)) { - // ss01 - ss20 - return this.getSingle(feature, script, language); - } - switch (feature) { - case 'aalt': - case 'salt': - return this.getSingle(feature, script, language) - .concat(this.getAlternates(feature, script, language)); - case 'dlig': - case 'liga': - case 'rlig': - return this.getLigatures(feature, script, language); - case 'ccmp': - return this.getMultiple(feature, script, language) - .concat(this.getLigatures(feature, script, language)); - case 'stch': - return this.getMultiple(feature, script, language); - } - return undefined; -}; + if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { + // This is the root of a reappearing boundary. Turn its layout effects + // back on. + nextEffect = fiber; + reappearLayoutEffects_begin(fiber); + } -/** - * Add a substitution to a feature for a given script and language. - * @param {string} feature - 4-letter feature name - * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] }) - * @param {string} [script='DFLT'] - * @param {string} [language='dflt'] - */ -Substitution.prototype.add = function(feature, sub, script, language) { - if (/ss\d\d/.test(feature)) { - // ss01 - ss20 - return this.addSingle(feature, sub, script, language); - } - switch (feature) { - case 'aalt': - case 'salt': - if (typeof sub.by === 'number') { - return this.addSingle(feature, sub, script, language); - } - return this.addAlternate(feature, sub, script, language); - case 'dlig': - case 'liga': - case 'rlig': - return this.addLigature(feature, sub, script, language); - case 'ccmp': - if (sub.by instanceof Array) { - return this.addMultiple(feature, sub, script, language); - } - return this.addLigature(feature, sub, script, language); - } - return undefined; -}; + var child = firstChild; -function isBrowser() { - return typeof window !== 'undefined'; -} + while (child !== null) { + nextEffect = child; + commitLayoutEffects_begin(child, // New root; bubble back up to here and stop. + root, committedLanes); + child = child.sibling; + } // Restore Offscreen state and resume in our-progress traversal. -function arrayBufferToNodeBuffer(ab) { - var buffer = new Buffer(ab.byteLength); - var view = new Uint8Array(ab); - for (var i = 0; i < buffer.length; ++i) { - buffer[i] = view[i]; - } - return buffer; -} + nextEffect = fiber; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); + continue; + } + } -function checkArgument(expression, message) { - if (!expression) { - throw message; - } -} + if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) { + ensureCorrectReturnPointer(firstChild, fiber); + nextEffect = firstChild; + } else { + commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); + } + } + } -// The `glyf` table describes the glyphs in TrueType outline format. + function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) { + while (nextEffect !== null) { + var fiber = nextEffect; -// Parse the coordinate data for a glyph. -function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { - var v; - if ((flag & shortVectorBitMask) > 0) { - // The coordinate is 1 byte long. - v = p.parseByte(); - // The `same` bit is re-used for short values to signify the sign of the value. - if ((flag & sameBitMask) === 0) { - v = -v; - } + if ((fiber.flags & LayoutMask) !== NoFlags) { + var current = fiber.alternate; + setCurrentFiber(fiber); - v = previousValue + v; - } else { - // The coordinate is 2 bytes long. - // If the `same` bit is set, the coordinate is the same as the previous coordinate. - if ((flag & sameBitMask) > 0) { - v = previousValue; - } else { - // Parse the coordinate as a signed 16-bit delta value. - v = previousValue + p.parseShort(); - } - } + try { + commitLayoutEffectOnFiber(root, current, fiber, committedLanes); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - return v; -} + resetCurrentFiber(); + } -// Parse a TrueType glyph. -function parseGlyph(glyph, data, start) { - var p = new parse.Parser(data, start); - glyph.numberOfContours = p.parseShort(); - glyph._xMin = p.parseShort(); - glyph._yMin = p.parseShort(); - glyph._xMax = p.parseShort(); - glyph._yMax = p.parseShort(); - var flags; - var flag; - - if (glyph.numberOfContours > 0) { - // This glyph is not a composite. - var endPointIndices = glyph.endPointIndices = []; - for (var i = 0; i < glyph.numberOfContours; i += 1) { - endPointIndices.push(p.parseUShort()); - } + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } - glyph.instructionLength = p.parseUShort(); - glyph.instructions = []; - for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) { - glyph.instructions.push(p.parseByte()); - } + var sibling = fiber.sibling; - var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; - flags = []; - for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) { - flag = p.parseByte(); - flags.push(flag); - // If bit 3 is set, we repeat this flag n times, where n is the next byte. - if ((flag & 8) > 0) { - var repeatCount = p.parseByte(); - for (var j = 0; j < repeatCount; j += 1) { - flags.push(flag); - i$2 += 1; - } - } - } + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } - check.argument(flags.length === numberOfCoordinates, 'Bad flags.'); - - if (endPointIndices.length > 0) { - var points = []; - var point; - // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. - if (numberOfCoordinates > 0) { - for (var i$3 = 0; i$3 < numberOfCoordinates; i$3 += 1) { - flag = flags[i$3]; - point = {}; - point.onCurve = !!(flag & 1); - point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0; - points.push(point); - } + nextEffect = fiber.return; + } + } - var px = 0; - for (var i$4 = 0; i$4 < numberOfCoordinates; i$4 += 1) { - flag = flags[i$4]; - point = points[i$4]; - point.x = parseGlyphCoordinate(p, flag, px, 2, 16); - px = point.x; - } + function disappearLayoutEffects_begin(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) - var py = 0; - for (var i$5 = 0; i$5 < numberOfCoordinates; i$5 += 1) { - flag = flags[i$5]; - point = points[i$5]; - point.y = parseGlyphCoordinate(p, flag, py, 4, 32); - py = point.y; - } - } + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: + { + if ( fiber.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListUnmount(Layout, fiber, fiber.return); + } finally { + recordLayoutEffectDuration(fiber); + } + } else { + commitHookEffectListUnmount(Layout, fiber, fiber.return); + } - glyph.points = points; - } else { - glyph.points = []; - } - } else if (glyph.numberOfContours === 0) { - glyph.points = []; - } else { - glyph.isComposite = true; - glyph.points = []; - glyph.components = []; - var moreComponents = true; - while (moreComponents) { - flags = p.parseUShort(); - var component = { - glyphIndex: p.parseUShort(), - xScale: 1, - scale01: 0, - scale10: 0, - yScale: 1, - dx: 0, - dy: 0 - }; - if ((flags & 1) > 0) { - // The arguments are words - if ((flags & 2) > 0) { - // values are offset - component.dx = p.parseShort(); - component.dy = p.parseShort(); - } else { - // values are matched points - component.matchedPoints = [p.parseUShort(), p.parseUShort()]; - } + break; + } - } else { - // The arguments are bytes - if ((flags & 2) > 0) { - // values are offset - component.dx = p.parseChar(); - component.dy = p.parseChar(); - } else { - // values are matched points - component.matchedPoints = [p.parseByte(), p.parseByte()]; - } - } + case ClassComponent: + { + // TODO (Offscreen) Check: flags & RefStatic + safelyDetachRef(fiber, fiber.return); + var instance = fiber.stateNode; - if ((flags & 8) > 0) { - // We have a scale - component.xScale = component.yScale = p.parseF2Dot14(); - } else if ((flags & 64) > 0) { - // We have an X / Y scale - component.xScale = p.parseF2Dot14(); - component.yScale = p.parseF2Dot14(); - } else if ((flags & 128) > 0) { - // We have a 2x2 transformation - component.xScale = p.parseF2Dot14(); - component.scale01 = p.parseF2Dot14(); - component.scale10 = p.parseF2Dot14(); - component.yScale = p.parseF2Dot14(); - } + if (typeof instance.componentWillUnmount === 'function') { + safelyCallComponentWillUnmount(fiber, fiber.return, instance); + } - glyph.components.push(component); - moreComponents = !!(flags & 32); - } - if (flags & 0x100) { - // We have instructions - glyph.instructionLength = p.parseUShort(); - glyph.instructions = []; - for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) { - glyph.instructions.push(p.parseByte()); - } - } - } -} + break; + } -// Transform an array of points and return a new array. -function transformPoints(points, transform) { - var newPoints = []; - for (var i = 0; i < points.length; i += 1) { - var pt = points[i]; - var newPt = { - x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, - y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, - onCurve: pt.onCurve, - lastPointOfContour: pt.lastPointOfContour - }; - newPoints.push(newPt); - } + case HostComponent: + { + safelyDetachRef(fiber, fiber.return); + break; + } - return newPoints; -} + case OffscreenComponent: + { + // Check if this is a + var isHidden = fiber.memoizedState !== null; -function getContours(points) { - var contours = []; - var currentContour = []; - for (var i = 0; i < points.length; i += 1) { - var pt = points[i]; - currentContour.push(pt); - if (pt.lastPointOfContour) { - contours.push(currentContour); - currentContour = []; - } - } + if (isHidden) { + // Nested Offscreen tree is already hidden. Don't disappear + // its effects. + disappearLayoutEffects_complete(subtreeRoot); + continue; + } - check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); - return contours; -} + break; + } + } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic -// Convert the TrueType glyph outline to a Path. -function getPath(points) { - var p = new Path(); - if (!points) { - return p; - } - var contours = getContours(points); + if (firstChild !== null) { + firstChild.return = fiber; + nextEffect = firstChild; + } else { + disappearLayoutEffects_complete(subtreeRoot); + } + } + } - for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) { - var contour = contours[contourIndex]; + function disappearLayoutEffects_complete(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; - var prev = null; - var curr = contour[contour.length - 1]; - var next = contour[0]; + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } - if (curr.onCurve) { - p.moveTo(curr.x, curr.y); - } else { - if (next.onCurve) { - p.moveTo(next.x, next.y); - } else { - // If both first and last points are off-curve, start at their middle. - var start = {x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5}; - p.moveTo(start.x, start.y); - } - } + var sibling = fiber.sibling; - for (var i = 0; i < contour.length; ++i) { - prev = curr; - curr = next; - next = contour[(i + 1) % contour.length]; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } - if (curr.onCurve) { - // This is a straight line. - p.lineTo(curr.x, curr.y); - } else { - var next2 = next; + nextEffect = fiber.return; + } + } - if (!prev.onCurve) { - ({ x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 }); - } + function reappearLayoutEffects_begin(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; - if (!next.onCurve) { - next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; - } + if (fiber.tag === OffscreenComponent) { + var isHidden = fiber.memoizedState !== null; - p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); - } - } + if (isHidden) { + // Nested Offscreen tree is still hidden. Don't re-appear its effects. + reappearLayoutEffects_complete(subtreeRoot); + continue; + } + } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic - p.closePath(); - } - return p; -} - -function buildPath(glyphs, glyph) { - if (glyph.isComposite) { - for (var j = 0; j < glyph.components.length; j += 1) { - var component = glyph.components[j]; - var componentGlyph = glyphs.get(component.glyphIndex); - // Force the ttfGlyphLoader to parse the glyph. - componentGlyph.getPath(); - if (componentGlyph.points) { - var transformedPoints = (void 0); - if (component.matchedPoints === undefined) { - // component positioned by offset - transformedPoints = transformPoints(componentGlyph.points, component); - } else { - // component positioned by matched points - if ((component.matchedPoints[0] > glyph.points.length - 1) || - (component.matchedPoints[1] > componentGlyph.points.length - 1)) { - throw Error('Matched points out of range in ' + glyph.name); - } - var firstPt = glyph.points[component.matchedPoints[0]]; - var secondPt = componentGlyph.points[component.matchedPoints[1]]; - var transform = { - xScale: component.xScale, scale01: component.scale01, - scale10: component.scale10, yScale: component.yScale, - dx: 0, dy: 0 - }; - secondPt = transformPoints([secondPt], transform)[0]; - transform.dx = firstPt.x - secondPt.x; - transform.dy = firstPt.y - secondPt.y; - transformedPoints = transformPoints(componentGlyph.points, transform); - } - glyph.points = glyph.points.concat(transformedPoints); - } - } - } - return getPath(glyph.points); -} + if (firstChild !== null) { + // This node may have been reused from a previous render, so we can't + // assume its return pointer is correct. + firstChild.return = fiber; + nextEffect = firstChild; + } else { + reappearLayoutEffects_complete(subtreeRoot); + } + } + } -function parseGlyfTableAll(data, start, loca, font) { - var glyphs = new glyphset.GlyphSet(font); + function reappearLayoutEffects_complete(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic - // The last element of the loca table is invalid. - for (var i = 0; i < loca.length - 1; i += 1) { - var offset = loca[i]; - var nextOffset = loca[i + 1]; - if (offset !== nextOffset) { - glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); - } else { - glyphs.push(i, glyphset.glyphLoader(font, i)); - } - } + setCurrentFiber(fiber); - return glyphs; -} + try { + reappearLayoutEffectsOnFiber(fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } -function parseGlyfTableOnLowMemory(data, start, loca, font) { - var glyphs = new glyphset.GlyphSet(font); + resetCurrentFiber(); - font._push = function(i) { - var offset = loca[i]; - var nextOffset = loca[i + 1]; - if (offset !== nextOffset) { - glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); - } else { - glyphs.push(i, glyphset.glyphLoader(font, i)); - } - }; + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } - return glyphs; -} - -// Parse all the glyphs according to the offsets from the `loca` table. -function parseGlyfTable(data, start, loca, font, opt) { - if (opt.lowMemory) - { return parseGlyfTableOnLowMemory(data, start, loca, font); } - else - { return parseGlyfTableAll(data, start, loca, font); } -} - -var glyf = { getPath: getPath, parse: parseGlyfTable}; - -/* A TrueType font hinting interpreter. -* -* (c) 2017 Axel Kittenberger -* -* This interpreter has been implemented according to this documentation: -* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html -* -* According to the documentation F24DOT6 values are used for pixels. -* That means calculation is 1/64 pixel accurate and uses integer operations. -* However, Javascript has floating point operations by default and only -* those are available. One could make a case to simulate the 1/64 accuracy -* exactly by truncating after every division operation -* (for example with << 0) to get pixel exactly results as other TrueType -* implementations. It may make sense since some fonts are pixel optimized -* by hand using DELTAP instructions. The current implementation doesn't -* and rather uses full floating point precision. -* -* xScale, yScale and rotation is currently ignored. -* -* A few non-trivial instructions are missing as I didn't encounter yet -* a font that used them to test a possible implementation. -* -* Some fonts seem to use undocumented features regarding the twilight zone. -* Only some of them are implemented as they were encountered. -* -* The exports.DEBUG statements are removed on the minified distribution file. -*/ + var sibling = fiber.sibling; -var instructionTable; -var exec; -var execGlyph; -var execComponent; + if (sibling !== null) { + // This node may have been reused from a previous render, so we can't + // assume its return pointer is correct. + sibling.return = fiber.return; + nextEffect = sibling; + return; + } -/* -* Creates a hinting object. -* -* There ought to be exactly one -* for each truetype font that is used for hinting. -*/ -function Hinting(font) { - // the font this hinting object is for - this.font = font; + nextEffect = fiber.return; + } + } - this.getCommands = function (hPoints) { - return glyf.getPath(hPoints).commands; - }; + function commitPassiveMountEffects(root, finishedWork) { + nextEffect = finishedWork; + commitPassiveMountEffects_begin(finishedWork, root); + } - // cached states - this._fpgmState = - this._prepState = - undefined; + function commitPassiveMountEffects_begin(subtreeRoot, root) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; - // errorState - // 0 ... all okay - // 1 ... had an error in a glyf, - // continue working but stop spamming - // the console - // 2 ... error at prep, stop hinting at this ppem - // 3 ... error at fpeg, stop hinting for this font at all - this._errorState = 0; -} + if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { + ensureCorrectReturnPointer(firstChild, fiber); + nextEffect = firstChild; + } else { + commitPassiveMountEffects_complete(subtreeRoot, root); + } + } + } -/* -* Not rounding. -*/ -function roundOff(v) { - return v; -} + function commitPassiveMountEffects_complete(subtreeRoot, root) { + while (nextEffect !== null) { + var fiber = nextEffect; -/* -* Rounding to grid. -*/ -function roundToGrid(v) { - //Rounding in TT is supposed to "symmetrical around zero" - return Math.sign(v) * Math.round(Math.abs(v)); -} + if ((fiber.flags & Passive) !== NoFlags) { + setCurrentFiber(fiber); -/* -* Rounding to double grid. -*/ -function roundToDoubleGrid(v) { - return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2; -} + try { + commitPassiveMountOnFiber(root, fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } -/* -* Rounding to half grid. -*/ -function roundToHalfGrid(v) { - return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5); -} + resetCurrentFiber(); + } -/* -* Rounding to up to grid. -*/ -function roundUpToGrid(v) { - return Math.sign(v) * Math.ceil(Math.abs(v)); -} + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } -/* -* Rounding to down to grid. -*/ -function roundDownToGrid(v) { - return Math.sign(v) * Math.floor(Math.abs(v)); -} + var sibling = fiber.sibling; -/* -* Super rounding. -*/ -var roundSuper = function (v) { - var period = this.srPeriod; - var phase = this.srPhase; - var threshold = this.srThreshold; - var sign = 1; - - if (v < 0) { - v = -v; - sign = -1; - } + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } - v += threshold - phase; + nextEffect = fiber.return; + } + } - v = Math.trunc(v / period) * period; + function commitPassiveMountOnFiber(finishedRoot, finishedWork) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( finishedWork.mode & ProfileMode) { + startPassiveEffectTimer(); - v += phase; + try { + commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); + } finally { + recordPassiveEffectDuration(finishedWork); + } + } else { + commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); + } - // according to http://xgridfit.sourceforge.net/round.html - if (v < 0) { return phase * sign; } + break; + } + } + } - return v * sign; -}; + function commitPassiveUnmountEffects(firstChild) { + nextEffect = firstChild; + commitPassiveUnmountEffects_begin(); + } -/* -* Unit vector of x-axis. -*/ -var xUnitVector = { - x: 1, + function commitPassiveUnmountEffects_begin() { + while (nextEffect !== null) { + var fiber = nextEffect; + var child = fiber.child; - y: 0, + if ((nextEffect.flags & ChildDeletion) !== NoFlags) { + var deletions = fiber.deletions; - axis: 'x', + if (deletions !== null) { + for (var i = 0; i < deletions.length; i++) { + var fiberToDelete = deletions[i]; + nextEffect = fiberToDelete; + commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber); + } - // Gets the projected distance between two points. - // o1/o2 ... if true, respective original position is used. - distance: function (p1, p2, o1, o2) { - return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x); - }, + { + // A fiber was deleted from this parent fiber, but it's still part of + // the previous (alternate) parent fiber's list of children. Because + // children are a linked list, an earlier sibling that's still alive + // will be connected to the deleted fiber via its `alternate`: + // + // live fiber + // --alternate--> previous live fiber + // --sibling--> deleted fiber + // + // We can't disconnect `alternate` on nodes that haven't been deleted + // yet, but we can disconnect the `sibling` and `child` pointers. + var previousFiber = fiber.alternate; - // Moves point p so the moved position has the same relative - // position to the moved positions of rp1 and rp2 than the - // original positions had. - // - // See APPENDIX on INTERPOLATE at the bottom of this file. - interpolate: function (p, rp1, rp2, pv) { - var do1; - var do2; - var doa1; - var doa2; - var dm1; - var dm2; - var dt; - - if (!pv || pv === this) { - do1 = p.xo - rp1.xo; - do2 = p.xo - rp2.xo; - dm1 = rp1.x - rp1.xo; - dm2 = rp2.x - rp2.xo; - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; - - if (dt === 0) { - p.x = p.xo + (dm1 + dm2) / 2; - return; - } + if (previousFiber !== null) { + var detachedChild = previousFiber.child; - p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt; - return; - } + if (detachedChild !== null) { + previousFiber.child = null; - do1 = pv.distance(p, rp1, true, true); - do2 = pv.distance(p, rp2, true, true); - dm1 = pv.distance(rp1, rp1, false, true); - dm2 = pv.distance(rp2, rp2, false, true); - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; + do { + var detachedSibling = detachedChild.sibling; + detachedChild.sibling = null; + detachedChild = detachedSibling; + } while (detachedChild !== null); + } + } + } - if (dt === 0) { - xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); - return; - } + nextEffect = fiber; + } + } - xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); - }, + if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { + ensureCorrectReturnPointer(child, fiber); + nextEffect = child; + } else { + commitPassiveUnmountEffects_complete(); + } + } + } - // Slope of line normal to this - normalSlope: Number.NEGATIVE_INFINITY, - - // Sets the point 'p' relative to point 'rp' - // by the distance 'd'. - // - // See APPENDIX on SETRELATIVE at the bottom of this file. - // - // p ... point to set - // rp ... reference point - // d ... distance on projection vector - // pv ... projection vector (undefined = this) - // org ... if true, uses the original position of rp as reference. - setRelative: function (p, rp, d, pv, org) { - if (!pv || pv === this) { - p.x = (org ? rp.xo : rp.x) + d; - return; - } + function commitPassiveUnmountEffects_complete() { + while (nextEffect !== null) { + var fiber = nextEffect; - var rpx = org ? rp.xo : rp.x; - var rpy = org ? rp.yo : rp.y; - var rpdx = rpx + d * pv.x; - var rpdy = rpy + d * pv.y; + if ((fiber.flags & Passive) !== NoFlags) { + setCurrentFiber(fiber); + commitPassiveUnmountOnFiber(fiber); + resetCurrentFiber(); + } - p.x = rpdx + (p.y - rpdy) / pv.normalSlope; - }, + var sibling = fiber.sibling; - // Slope of vector line. - slope: 0, + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, fiber.return); + nextEffect = sibling; + return; + } - // Touches the point p. - touch: function (p) { - p.xTouched = true; - }, + nextEffect = fiber.return; + } + } - // Tests if a point p is touched. - touched: function (p) { - return p.xTouched; - }, + function commitPassiveUnmountOnFiber(finishedWork) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( finishedWork.mode & ProfileMode) { + startPassiveEffectTimer(); + commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); + recordPassiveEffectDuration(finishedWork); + } else { + commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); + } - // Untouches the point p. - untouch: function (p) { - p.xTouched = false; - } -}; + break; + } + } + } -/* -* Unit vector of y-axis. -*/ -var yUnitVector = { - x: 0, + function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) { + while (nextEffect !== null) { + var fiber = nextEffect; // Deletion effects fire in parent -> child order + // TODO: Check if fiber has a PassiveStatic flag - y: 1, + setCurrentFiber(fiber); + commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); + resetCurrentFiber(); + var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we + // do this, still need to handle `deletedTreeCleanUpLevel` correctly.) - axis: 'y', + if (child !== null) { + ensureCorrectReturnPointer(child, fiber); + nextEffect = child; + } else { + commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot); + } + } + } - // Gets the projected distance between two points. - // o1/o2 ... if true, respective original position is used. - distance: function (p1, p2, o1, o2) { - return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y); - }, + function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var sibling = fiber.sibling; + var returnFiber = fiber.return; - // Moves point p so the moved position has the same relative - // position to the moved positions of rp1 and rp2 than the - // original positions had. - // - // See APPENDIX on INTERPOLATE at the bottom of this file. - interpolate: function (p, rp1, rp2, pv) { - var do1; - var do2; - var doa1; - var doa2; - var dm1; - var dm2; - var dt; - - if (!pv || pv === this) { - do1 = p.yo - rp1.yo; - do2 = p.yo - rp2.yo; - dm1 = rp1.y - rp1.yo; - dm2 = rp2.y - rp2.yo; - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; - - if (dt === 0) { - p.y = p.yo + (dm1 + dm2) / 2; - return; - } + { + // Recursively traverse the entire deleted tree and clean up fiber fields. + // This is more aggressive than ideal, and the long term goal is to only + // have to detach the deleted tree at the root. + detachFiberAfterEffects(fiber); - p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt; - return; - } + if (fiber === deletedSubtreeRoot) { + nextEffect = null; + return; + } + } - do1 = pv.distance(p, rp1, true, true); - do2 = pv.distance(p, rp2, true, true); - dm1 = pv.distance(rp1, rp1, false, true); - dm2 = pv.distance(rp2, rp2, false, true); - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; + if (sibling !== null) { + ensureCorrectReturnPointer(sibling, returnFiber); + nextEffect = sibling; + return; + } - if (dt === 0) { - yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); - return; - } + nextEffect = returnFiber; + } + } - yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); - }, + function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) { + switch (current.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + if ( current.mode & ProfileMode) { + startPassiveEffectTimer(); + commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); + recordPassiveEffectDuration(current); + } else { + commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); + } - // Slope of line normal to this. - normalSlope: 0, - - // Sets the point 'p' relative to point 'rp' - // by the distance 'd' - // - // See APPENDIX on SETRELATIVE at the bottom of this file. - // - // p ... point to set - // rp ... reference point - // d ... distance on projection vector - // pv ... projection vector (undefined = this) - // org ... if true, uses the original position of rp as reference. - setRelative: function (p, rp, d, pv, org) { - if (!pv || pv === this) { - p.y = (org ? rp.yo : rp.y) + d; - return; - } + break; + } + } + } - var rpx = org ? rp.xo : rp.x; - var rpy = org ? rp.yo : rp.y; - var rpdx = rpx + d * pv.x; - var rpdy = rpy + d * pv.y; + var didWarnWrongReturnPointer = false; - p.y = rpdy + pv.normalSlope * (p.x - rpdx); - }, + function ensureCorrectReturnPointer(fiber, expectedReturnFiber) { + { + if (!didWarnWrongReturnPointer && fiber.return !== expectedReturnFiber) { + didWarnWrongReturnPointer = true; - // Slope of vector line. - slope: Number.POSITIVE_INFINITY, + error('Internal React error: Return pointer is inconsistent ' + 'with parent.'); + } + } // TODO: Remove this assignment once we're confident that it won't break + // anything, by checking the warning logs for the above invariant - // Touches the point p. - touch: function (p) { - p.yTouched = true; - }, - // Tests if a point p is touched. - touched: function (p) { - return p.yTouched; - }, + fiber.return = expectedReturnFiber; + } // TODO: Reuse reappearLayoutEffects traversal here? - // Untouches the point p. - untouch: function (p) { - p.yTouched = false; - } -}; -Object.freeze(xUnitVector); -Object.freeze(yUnitVector); + function invokeLayoutEffectMountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListMount(Layout | HasEffect, fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } -/* -* Creates a unit vector that is not x- or y-axis. -*/ -function UnitVector(x, y) { - this.x = x; - this.y = y; - this.axis = undefined; - this.slope = y / x; - this.normalSlope = -x / y; - Object.freeze(this); -} + break; + } -/* -* Gets the projected distance between two points. -* o1/o2 ... if true, respective original position is used. -*/ -UnitVector.prototype.distance = function(p1, p2, o1, o2) { - return ( - this.x * xUnitVector.distance(p1, p2, o1, o2) + - this.y * yUnitVector.distance(p1, p2, o1, o2) - ); -}; + case ClassComponent: + { + var instance = fiber.stateNode; -/* -* Moves point p so the moved position has the same relative -* position to the moved positions of rp1 and rp2 than the -* original positions had. -* -* See APPENDIX on INTERPOLATE at the bottom of this file. -*/ -UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) { - var dm1; - var dm2; - var do1; - var do2; - var doa1; - var doa2; - var dt; - - do1 = pv.distance(p, rp1, true, true); - do2 = pv.distance(p, rp2, true, true); - dm1 = pv.distance(rp1, rp1, false, true); - dm2 = pv.distance(rp2, rp2, false, true); - doa1 = Math.abs(do1); - doa2 = Math.abs(do2); - dt = doa1 + doa2; - - if (dt === 0) { - this.setRelative(p, p, (dm1 + dm2) / 2, pv, true); - return; - } + try { + instance.componentDidMount(); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); -}; + break; + } + } + } + } -/* -* Sets the point 'p' relative to point 'rp' -* by the distance 'd' -* -* See APPENDIX on SETRELATIVE at the bottom of this file. -* -* p ... point to set -* rp ... reference point -* d ... distance on projection vector -* pv ... projection vector (undefined = this) -* org ... if true, uses the original position of rp as reference. -*/ -UnitVector.prototype.setRelative = function(p, rp, d, pv, org) { - pv = pv || this; + function invokePassiveEffectMountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListMount(Passive$1 | HasEffect, fiber); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - var rpx = org ? rp.xo : rp.x; - var rpy = org ? rp.yo : rp.y; - var rpdx = rpx + d * pv.x; - var rpdy = rpy + d * pv.y; + break; + } + } + } + } - var pvns = pv.normalSlope; - var fvs = this.slope; + function invokeLayoutEffectUnmountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } - var px = p.x; - var py = p.y; + break; + } - p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns); - p.y = fvs * (p.x - px) + py; -}; + case ClassComponent: + { + var instance = fiber.stateNode; -/* -* Touches the point p. -*/ -UnitVector.prototype.touch = function(p) { - p.xTouched = true; - p.yTouched = true; -}; + if (typeof instance.componentWillUnmount === 'function') { + safelyCallComponentWillUnmount(fiber, fiber.return, instance); + } -/* -* Returns a unit vector with x/y coordinates. -*/ -function getUnitVector(x, y) { - var d = Math.sqrt(x * x + y * y); + break; + } + } + } + } - x /= d; - y /= d; + function invokePassiveEffectUnmountInDEV(fiber) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + try { + commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); + } catch (error) { + reportUncaughtErrorInDEV(error); + captureCommitPhaseError(fiber, fiber.return, error); + } + } + } + } + } - if (x === 1 && y === 0) { return xUnitVector; } - else if (x === 0 && y === 1) { return yUnitVector; } - else { return new UnitVector(x, y); } -} + var COMPONENT_TYPE = 0; + var HAS_PSEUDO_CLASS_TYPE = 1; + var ROLE_TYPE = 2; + var TEST_NAME_TYPE = 3; + var TEXT_TYPE = 4; -/* -* Creates a point in the hinting engine. -*/ -function HPoint( - x, - y, - lastPointOfContour, - onCurve -) { - this.x = this.xo = Math.round(x * 64) / 64; // hinted x value and original x-value - this.y = this.yo = Math.round(y * 64) / 64; // hinted y value and original y-value + if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + COMPONENT_TYPE = symbolFor('selector.component'); + HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class'); + ROLE_TYPE = symbolFor('selector.role'); + TEST_NAME_TYPE = symbolFor('selector.test_id'); + TEXT_TYPE = symbolFor('selector.text'); + } - this.lastPointOfContour = lastPointOfContour; - this.onCurve = onCurve; - this.prevPointOnContour = undefined; - this.nextPointOnContour = undefined; - this.xTouched = false; - this.yTouched = false; + function createComponentSelector(component) { + return { + $$typeof: COMPONENT_TYPE, + value: component + }; + } + function createHasPseudoClassSelector(selectors) { + return { + $$typeof: HAS_PSEUDO_CLASS_TYPE, + value: selectors + }; + } + function createRoleSelector(role) { + return { + $$typeof: ROLE_TYPE, + value: role + }; + } + function createTextSelector(text) { + return { + $$typeof: TEXT_TYPE, + value: text + }; + } + function createTestNameSelector(id) { + return { + $$typeof: TEST_NAME_TYPE, + value: id + }; + } - Object.preventExtensions(this); -} + function findFiberRootForHostRoot(hostRoot) { + var maybeFiber = getInstanceFromNode(hostRoot); -/* -* Returns the next touched point on the contour. -* -* v ... unit vector to test touch axis. -*/ -HPoint.prototype.nextTouched = function(v) { - var p = this.nextPointOnContour; + if (maybeFiber != null) { + if (typeof maybeFiber.memoizedProps['data-testname'] !== 'string') { + throw new Error('Invalid host root specified. Should be either a React container or a node with a testname attribute.'); + } - while (!v.touched(p) && p !== this) { p = p.nextPointOnContour; } + return maybeFiber; + } else { + var fiberRoot = findFiberRoot(hostRoot); - return p; -}; + if (fiberRoot === null) { + throw new Error('Could not find React container within specified host subtree.'); + } // The Flow type for FiberRoot is a little funky. + // createFiberRoot() cheats this by treating the root as :any and adding stateNode lazily. -/* -* Returns the previous touched point on the contour -* -* v ... unit vector to test touch axis. -*/ -HPoint.prototype.prevTouched = function(v) { - var p = this.prevPointOnContour; - while (!v.touched(p) && p !== this) { p = p.prevPointOnContour; } + return fiberRoot.stateNode.current; + } + } - return p; -}; + function matchSelector(fiber, selector) { + switch (selector.$$typeof) { + case COMPONENT_TYPE: + if (fiber.type === selector.value) { + return true; + } -/* -* The zero point. -*/ -var HPZero = Object.freeze(new HPoint(0, 0)); + break; -/* -* The default state of the interpreter. -* -* Note: Freezing the defaultState and then deriving from it -* makes the V8 Javascript engine going awkward, -* so this is avoided, albeit the defaultState shouldn't -* ever change. -*/ -var defaultState = { - cvCutIn: 17 / 16, // control value cut in - deltaBase: 9, - deltaShift: 0.125, - loop: 1, // loops some instructions - minDis: 1, // minimum distance - autoFlip: true -}; + case HAS_PSEUDO_CLASS_TYPE: + return hasMatchingPaths(fiber, selector.value); -/* -* The current state of the interpreter. -* -* env ... 'fpgm' or 'prep' or 'glyf' -* prog ... the program -*/ -function State(env, prog) { - this.env = env; - this.stack = []; - this.prog = prog; - - switch (env) { - case 'glyf' : - this.zp0 = this.zp1 = this.zp2 = 1; - this.rp0 = this.rp1 = this.rp2 = 0; - /* fall through */ - case 'prep' : - this.fv = this.pv = this.dpv = xUnitVector; - this.round = roundToGrid; - } -} + case ROLE_TYPE: + if (fiber.tag === HostComponent) { + var node = fiber.stateNode; -/* -* Executes a glyph program. -* -* This does the hinting for each glyph. -* -* Returns an array of moved points. -* -* glyph: the glyph to hint -* ppem: the size the glyph is rendered for -*/ -Hinting.prototype.exec = function(glyph, ppem) { - if (typeof ppem !== 'number') { - throw new Error('Point size is not a number!'); - } + if (matchAccessibilityRole(node, selector.value)) { + return true; + } + } - // Received a fatal error, don't do any hinting anymore. - if (this._errorState > 2) { return; } + break; - var font = this.font; - var prepState = this._prepState; + case TEXT_TYPE: + if (fiber.tag === HostComponent || fiber.tag === HostText) { + var textContent = getTextContent(fiber); - if (!prepState || prepState.ppem !== ppem) { - var fpgmState = this._fpgmState; + if (textContent !== null && textContent.indexOf(selector.value) >= 0) { + return true; + } + } - if (!fpgmState) { - // Executes the fpgm state. - // This is used by fonts to define functions. - State.prototype = defaultState; + break; - fpgmState = - this._fpgmState = - new State('fpgm', font.tables.fpgm); + case TEST_NAME_TYPE: + if (fiber.tag === HostComponent) { + var dataTestID = fiber.memoizedProps['data-testname']; - fpgmState.funcs = [ ]; - fpgmState.font = font; + if (typeof dataTestID === 'string' && dataTestID.toLowerCase() === selector.value.toLowerCase()) { + return true; + } + } - if (exports.DEBUG) { - console.log('---EXEC FPGM---'); - fpgmState.step = -1; - } + break; - try { - exec(fpgmState); - } catch (e) { - console.log('Hinting error in FPGM:' + e); - this._errorState = 3; - return; - } - } + default: + throw new Error('Invalid selector type specified.'); + } - // Executes the prep program for this ppem setting. - // This is used by fonts to set cvt values - // depending on to be rendered font size. - - State.prototype = fpgmState; - prepState = - this._prepState = - new State('prep', font.tables.prep); - - prepState.ppem = ppem; - - // Creates a copy of the cvt table - // and scales it to the current ppem setting. - var oCvt = font.tables.cvt; - if (oCvt) { - var cvt = prepState.cvt = new Array(oCvt.length); - var scale = ppem / font.unitsPerEm; - for (var c = 0; c < oCvt.length; c++) { - cvt[c] = oCvt[c] * scale; - } - } else { - prepState.cvt = []; - } + return false; + } - if (exports.DEBUG) { - console.log('---EXEC PREP---'); - prepState.step = -1; - } + function selectorToString(selector) { + switch (selector.$$typeof) { + case COMPONENT_TYPE: + var displayName = getComponentNameFromType(selector.value) || 'Unknown'; + return "<" + displayName + ">"; - try { - exec(prepState); - } catch (e) { - if (this._errorState < 2) { - console.log('Hinting error in PREP:' + e); - } - this._errorState = 2; - } - } + case HAS_PSEUDO_CLASS_TYPE: + return ":has(" + (selectorToString(selector) || '') + ")"; - if (this._errorState > 1) { return; } + case ROLE_TYPE: + return "[role=\"" + selector.value + "\"]"; - try { - return execGlyph(glyph, prepState); - } catch (e) { - if (this._errorState < 1) { - console.log('Hinting error:' + e); - console.log('Note: further hinting errors are silenced'); - } - this._errorState = 1; - return undefined; - } -}; + case TEXT_TYPE: + return "\"" + selector.value + "\""; -/* -* Executes the hinting program for a glyph. -*/ -execGlyph = function(glyph, prepState) { - // original point positions - var xScale = prepState.ppem / prepState.font.unitsPerEm; - var yScale = xScale; - var components = glyph.components; - var contours; - var gZone; - var state; - - State.prototype = prepState; - if (!components) { - state = new State('glyf', glyph.instructions); - if (exports.DEBUG) { - console.log('---EXEC GLYPH---'); - state.step = -1; - } - execComponent(glyph, state, xScale, yScale); - gZone = state.gZone; - } else { - var font = prepState.font; - gZone = []; - contours = []; - for (var i = 0; i < components.length; i++) { - var c = components[i]; - var cg = font.glyphs.get(c.glyphIndex); - - state = new State('glyf', cg.instructions); - - if (exports.DEBUG) { - console.log('---EXEC COMP ' + i + '---'); - state.step = -1; - } + case TEST_NAME_TYPE: + return "[data-testname=\"" + selector.value + "\"]"; - execComponent(cg, state, xScale, yScale); - // appends the computed points to the result array - // post processes the component points - var dx = Math.round(c.dx * xScale); - var dy = Math.round(c.dy * yScale); - var gz = state.gZone; - var cc = state.contours; - for (var pi = 0; pi < gz.length; pi++) { - var p = gz[pi]; - p.xTouched = p.yTouched = false; - p.xo = p.x = p.x + dx; - p.yo = p.y = p.y + dy; - } + default: + throw new Error('Invalid selector type specified.'); + } + } - var gLen = gZone.length; - gZone.push.apply(gZone, gz); - for (var j = 0; j < cc.length; j++) { - contours.push(cc[j] + gLen); - } - } + function findPaths(root, selectors) { + var matchingFibers = []; + var stack = [root, 0]; + var index = 0; - if (glyph.instructions && !state.inhibitGridFit) { - // the composite has instructions on its own - state = new State('glyf', glyph.instructions); + while (index < stack.length) { + var fiber = stack[index++]; + var selectorIndex = stack[index++]; + var selector = selectors[selectorIndex]; - state.gZone = state.z0 = state.z1 = state.z2 = gZone; + if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { + continue; + } else { + while (selector != null && matchSelector(fiber, selector)) { + selectorIndex++; + selector = selectors[selectorIndex]; + } + } - state.contours = contours; + if (selectorIndex === selectors.length) { + matchingFibers.push(fiber); + } else { + var child = fiber.child; - // note: HPZero cannot be used here, since - // the point might be modified - gZone.push( - new HPoint(0, 0), - new HPoint(Math.round(glyph.advanceWidth * xScale), 0) - ); + while (child !== null) { + stack.push(child, selectorIndex); + child = child.sibling; + } + } + } - if (exports.DEBUG) { - console.log('---EXEC COMPOSITE---'); - state.step = -1; - } + return matchingFibers; + } // Same as findPaths but with eager bailout on first match - exec(state); - gZone.length -= 2; - } - } + function hasMatchingPaths(root, selectors) { + var stack = [root, 0]; + var index = 0; - return gZone; -}; + while (index < stack.length) { + var fiber = stack[index++]; + var selectorIndex = stack[index++]; + var selector = selectors[selectorIndex]; -/* -* Executes the hinting program for a component of a multi-component glyph -* or of the glyph itself for a non-component glyph. -*/ -execComponent = function(glyph, state, xScale, yScale) -{ - var points = glyph.points || []; - var pLen = points.length; - var gZone = state.gZone = state.z0 = state.z1 = state.z2 = []; - var contours = state.contours = []; - - // Scales the original points and - // makes copies for the hinted points. - var cp; // current point - for (var i = 0; i < pLen; i++) { - cp = points[i]; - - gZone[i] = new HPoint( - cp.x * xScale, - cp.y * yScale, - cp.lastPointOfContour, - cp.onCurve - ); - } + if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { + continue; + } else { + while (selector != null && matchSelector(fiber, selector)) { + selectorIndex++; + selector = selectors[selectorIndex]; + } + } - // Chain links the contours. - var sp; // start point - var np; // next point + if (selectorIndex === selectors.length) { + return true; + } else { + var child = fiber.child; - for (var i$1 = 0; i$1 < pLen; i$1++) { - cp = gZone[i$1]; + while (child !== null) { + stack.push(child, selectorIndex); + child = child.sibling; + } + } + } - if (!sp) { - sp = cp; - contours.push(i$1); - } + return false; + } - if (cp.lastPointOfContour) { - cp.nextPointOnContour = sp; - sp.prevPointOnContour = cp; - sp = undefined; - } else { - np = gZone[i$1 + 1]; - cp.nextPointOnContour = np; - np.prevPointOnContour = cp; - } - } + function findAllNodes(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } - if (state.inhibitGridFit) { return; } + var root = findFiberRootForHostRoot(hostRoot); + var matchingFibers = findPaths(root, selectors); + var instanceRoots = []; + var stack = Array.from(matchingFibers); + var index = 0; - if (exports.DEBUG) { - console.log('PROCESSING GLYPH', state.stack); - for (var i$2 = 0; i$2 < pLen; i$2++) { - console.log(i$2, gZone[i$2].x, gZone[i$2].y); - } - } + while (index < stack.length) { + var node = stack[index++]; - gZone.push( - new HPoint(0, 0), - new HPoint(Math.round(glyph.advanceWidth * xScale), 0) - ); + if (node.tag === HostComponent) { + if (isHiddenSubtree(node)) { + continue; + } - exec(state); + instanceRoots.push(node.stateNode); + } else { + var child = node.child; - // Removes the extra points. - gZone.length -= 2; + while (child !== null) { + stack.push(child); + child = child.sibling; + } + } + } - if (exports.DEBUG) { - console.log('FINISHED GLYPH', state.stack); - for (var i$3 = 0; i$3 < pLen; i$3++) { - console.log(i$3, gZone[i$3].x, gZone[i$3].y); - } - } -}; + return instanceRoots; + } + function getFindAllNodesFailureDescription(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } -/* -* Executes the program loaded in state. -*/ -exec = function(state) { - var prog = state.prog; + var root = findFiberRootForHostRoot(hostRoot); + var maxSelectorIndex = 0; + var matchedNames = []; // The logic of this loop should be kept in sync with findPaths() - if (!prog) { return; } + var stack = [root, 0]; + var index = 0; - var pLen = prog.length; - var ins; + while (index < stack.length) { + var fiber = stack[index++]; + var selectorIndex = stack[index++]; + var selector = selectors[selectorIndex]; - for (state.ip = 0; state.ip < pLen; state.ip++) { - if (exports.DEBUG) { state.step++; } - ins = instructionTable[prog[state.ip]]; + if (fiber.tag === HostComponent && isHiddenSubtree(fiber)) { + continue; + } else if (matchSelector(fiber, selector)) { + matchedNames.push(selectorToString(selector)); + selectorIndex++; - if (!ins) { - throw new Error( - 'unknown instruction: 0x' + - Number(prog[state.ip]).toString(16) - ); - } + if (selectorIndex > maxSelectorIndex) { + maxSelectorIndex = selectorIndex; + } + } - ins(state); - - // very extensive debugging for each step - /* - if (exports.DEBUG) { - var da; - if (state.gZone) { - da = []; - for (let i = 0; i < state.gZone.length; i++) - { - da.push(i + ' ' + - state.gZone[i].x * 64 + ' ' + - state.gZone[i].y * 64 + ' ' + - (state.gZone[i].xTouched ? 'x' : '') + - (state.gZone[i].yTouched ? 'y' : '') - ); - } - console.log('GZ', da); - } + if (selectorIndex < selectors.length) { + var child = fiber.child; - if (state.tZone) { - da = []; - for (let i = 0; i < state.tZone.length; i++) { - da.push(i + ' ' + - state.tZone[i].x * 64 + ' ' + - state.tZone[i].y * 64 + ' ' + - (state.tZone[i].xTouched ? 'x' : '') + - (state.tZone[i].yTouched ? 'y' : '') - ); - } - console.log('TZ', da); - } + while (child !== null) { + stack.push(child, selectorIndex); + child = child.sibling; + } + } + } - if (state.stack.length > 10) { - console.log( - state.stack.length, - '...', state.stack.slice(state.stack.length - 10) - ); - } else { - console.log(state.stack.length, state.stack); - } - } - */ - } -}; + if (maxSelectorIndex < selectors.length) { + var unmatchedNames = []; -/* -* Initializes the twilight zone. -* -* This is only done if a SZPx instruction -* refers to the twilight zone. -*/ -function initTZone(state) -{ - var tZone = state.tZone = new Array(state.gZone.length); + for (var i = maxSelectorIndex; i < selectors.length; i++) { + unmatchedNames.push(selectorToString(selectors[i])); + } - // no idea if this is actually correct... - for (var i = 0; i < tZone.length; i++) - { - tZone[i] = new HPoint(0, 0); - } -} + return 'findAllNodes was able to match part of the selector:\n' + (" " + matchedNames.join(' > ') + "\n\n") + 'No matching component was found for:\n' + (" " + unmatchedNames.join(' > ')); + } -/* -* Skips the instruction pointer ahead over an IF/ELSE block. -* handleElse .. if true breaks on matching ELSE -*/ -function skip(state, handleElse) -{ - var prog = state.prog; - var ip = state.ip; - var nesting = 1; - var ins; - - do { - ins = prog[++ip]; - if (ins === 0x58) // IF - { nesting++; } - else if (ins === 0x59) // EIF - { nesting--; } - else if (ins === 0x40) // NPUSHB - { ip += prog[ip + 1] + 1; } - else if (ins === 0x41) // NPUSHW - { ip += 2 * prog[ip + 1] + 1; } - else if (ins >= 0xB0 && ins <= 0xB7) // PUSHB - { ip += ins - 0xB0 + 1; } - else if (ins >= 0xB8 && ins <= 0xBF) // PUSHW - { ip += (ins - 0xB8 + 1) * 2; } - else if (handleElse && nesting === 1 && ins === 0x1B) // ELSE - { break; } - } while (nesting > 0); - - state.ip = ip; -} - -/*----------------------------------------------------------* -* And then a lot of instructions... * -*----------------------------------------------------------*/ - -// SVTCA[a] Set freedom and projection Vectors To Coordinate Axis -// 0x00-0x01 -function SVTCA(v, state) { - if (exports.DEBUG) { console.log(state.step, 'SVTCA[' + v.axis + ']'); } - - state.fv = state.pv = state.dpv = v; -} - -// SPVTCA[a] Set Projection Vector to Coordinate Axis -// 0x02-0x03 -function SPVTCA(v, state) { - if (exports.DEBUG) { console.log(state.step, 'SPVTCA[' + v.axis + ']'); } - - state.pv = state.dpv = v; -} - -// SFVTCA[a] Set Freedom Vector to Coordinate Axis -// 0x04-0x05 -function SFVTCA(v, state) { - if (exports.DEBUG) { console.log(state.step, 'SFVTCA[' + v.axis + ']'); } - - state.fv = v; -} - -// SPVTL[a] Set Projection Vector To Line -// 0x06-0x07 -function SPVTL(a, state) { - var stack = state.stack; - var p2i = stack.pop(); - var p1i = stack.pop(); - var p2 = state.z2[p2i]; - var p1 = state.z1[p1i]; - - if (exports.DEBUG) { console.log('SPVTL[' + a + ']', p2i, p1i); } - - var dx; - var dy; - - if (!a) { - dx = p1.x - p2.x; - dy = p1.y - p2.y; - } else { - dx = p2.y - p1.y; - dy = p1.x - p2.x; - } + return null; + } + function findBoundingRects(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } - state.pv = state.dpv = getUnitVector(dx, dy); -} + var instanceRoots = findAllNodes(hostRoot, selectors); + var boundingRects = []; -// SFVTL[a] Set Freedom Vector To Line -// 0x08-0x09 -function SFVTL(a, state) { - var stack = state.stack; - var p2i = stack.pop(); - var p1i = stack.pop(); - var p2 = state.z2[p2i]; - var p1 = state.z1[p1i]; + for (var i = 0; i < instanceRoots.length; i++) { + boundingRects.push(getBoundingRect(instanceRoots[i])); + } - if (exports.DEBUG) { console.log('SFVTL[' + a + ']', p2i, p1i); } + for (var _i = boundingRects.length - 1; _i > 0; _i--) { + var targetRect = boundingRects[_i]; + var targetLeft = targetRect.x; + var targetRight = targetLeft + targetRect.width; + var targetTop = targetRect.y; + var targetBottom = targetTop + targetRect.height; - var dx; - var dy; + for (var j = _i - 1; j >= 0; j--) { + if (_i !== j) { + var otherRect = boundingRects[j]; + var otherLeft = otherRect.x; + var otherRight = otherLeft + otherRect.width; + var otherTop = otherRect.y; + var otherBottom = otherTop + otherRect.height; // Merging all rects to the minimums set would be complicated, + // but we can handle the most common cases: + // 1. completely overlapping rects + // 2. adjacent rects that are the same width or height (e.g. items in a list) + // + // Even given the above constraints, + // we still won't end up with the fewest possible rects without doing multiple passes, + // but it's good enough for this purpose. - if (!a) { - dx = p1.x - p2.x; - dy = p1.y - p2.y; - } else { - dx = p2.y - p1.y; - dy = p1.x - p2.x; - } + if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) { + // Complete overlapping rects; remove the inner one. + boundingRects.splice(_i, 1); + break; + } else if (targetLeft === otherLeft && targetRect.width === otherRect.width && !(otherBottom < targetTop) && !(otherTop > targetBottom)) { + // Adjacent vertical rects; merge them. + if (otherTop > targetTop) { + otherRect.height += otherTop - targetTop; + otherRect.y = targetTop; + } - state.fv = getUnitVector(dx, dy); -} + if (otherBottom < targetBottom) { + otherRect.height = targetBottom - otherTop; + } -// SPVFS[] Set Projection Vector From Stack -// 0x0A -function SPVFS(state) { - var stack = state.stack; - var y = stack.pop(); - var x = stack.pop(); + boundingRects.splice(_i, 1); + break; + } else if (targetTop === otherTop && targetRect.height === otherRect.height && !(otherRight < targetLeft) && !(otherLeft > targetRight)) { + // Adjacent horizontal rects; merge them. + if (otherLeft > targetLeft) { + otherRect.width += otherLeft - targetLeft; + otherRect.x = targetLeft; + } - if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); } + if (otherRight < targetRight) { + otherRect.width = targetRight - otherLeft; + } - state.pv = state.dpv = getUnitVector(x, y); -} + boundingRects.splice(_i, 1); + break; + } + } + } + } -// SFVFS[] Set Freedom Vector From Stack -// 0x0B -function SFVFS(state) { - var stack = state.stack; - var y = stack.pop(); - var x = stack.pop(); + return boundingRects; + } + function focusWithin(hostRoot, selectors) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } - if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); } + var root = findFiberRootForHostRoot(hostRoot); + var matchingFibers = findPaths(root, selectors); + var stack = Array.from(matchingFibers); + var index = 0; - state.fv = getUnitVector(x, y); -} + while (index < stack.length) { + var fiber = stack[index++]; -// GPV[] Get Projection Vector -// 0x0C -function GPV(state) { - var stack = state.stack; - var pv = state.pv; + if (isHiddenSubtree(fiber)) { + continue; + } - if (exports.DEBUG) { console.log(state.step, 'GPV[]'); } + if (fiber.tag === HostComponent) { + var node = fiber.stateNode; - stack.push(pv.x * 0x4000); - stack.push(pv.y * 0x4000); -} + if (setFocusIfFocusable(node)) { + return true; + } + } -// GFV[] Get Freedom Vector -// 0x0C -function GFV(state) { - var stack = state.stack; - var fv = state.fv; + var child = fiber.child; - if (exports.DEBUG) { console.log(state.step, 'GFV[]'); } + while (child !== null) { + stack.push(child); + child = child.sibling; + } + } - stack.push(fv.x * 0x4000); - stack.push(fv.y * 0x4000); -} + return false; + } + var commitHooks = []; + function onCommitRoot$1() { + if (supportsTestSelectors) { + commitHooks.forEach(function (commitHook) { + return commitHook(); + }); + } + } + function observeVisibleRects(hostRoot, selectors, callback, options) { + if (!supportsTestSelectors) { + throw new Error('Test selector API is not supported by this renderer.'); + } -// SFVTPV[] Set Freedom Vector To Projection Vector -// 0x0E -function SFVTPV(state) { - state.fv = state.pv; + var instanceRoots = findAllNodes(hostRoot, selectors); - if (exports.DEBUG) { console.log(state.step, 'SFVTPV[]'); } -} + var _setupIntersectionObs = setupIntersectionObserver(instanceRoots, callback, options), + disconnect = _setupIntersectionObs.disconnect, + observe = _setupIntersectionObs.observe, + unobserve = _setupIntersectionObs.unobserve; // When React mutates the host environment, we may need to change what we're listening to. -// ISECT[] moves point p to the InterSECTion of two lines -// 0x0F -function ISECT(state) -{ - var stack = state.stack; - var pa0i = stack.pop(); - var pa1i = stack.pop(); - var pb0i = stack.pop(); - var pb1i = stack.pop(); - var pi = stack.pop(); - var z0 = state.z0; - var z1 = state.z1; - var pa0 = z0[pa0i]; - var pa1 = z0[pa1i]; - var pb0 = z1[pb0i]; - var pb1 = z1[pb1i]; - var p = state.z2[pi]; - if (exports.DEBUG) { console.log('ISECT[], ', pa0i, pa1i, pb0i, pb1i, pi); } + var commitHook = function () { + var nextInstanceRoots = findAllNodes(hostRoot, selectors); + instanceRoots.forEach(function (target) { + if (nextInstanceRoots.indexOf(target) < 0) { + unobserve(target); + } + }); + nextInstanceRoots.forEach(function (target) { + if (instanceRoots.indexOf(target) < 0) { + observe(target); + } + }); + }; - // math from - // en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line + commitHooks.push(commitHook); + return { + disconnect: function () { + // Stop listening for React mutations: + var index = commitHooks.indexOf(commitHook); - var x1 = pa0.x; - var y1 = pa0.y; - var x2 = pa1.x; - var y2 = pa1.y; - var x3 = pb0.x; - var y3 = pb0.y; - var x4 = pb1.x; - var y4 = pb1.y; + if (index >= 0) { + commitHooks.splice(index, 1); + } // Disconnect the host observer: - var div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); - var f1 = x1 * y2 - y1 * x2; - var f2 = x3 * y4 - y3 * x4; - p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div; - p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div; -} + disconnect(); + } + }; + } -// SRP0[] Set Reference Point 0 -// 0x10 -function SRP0(state) { - state.rp0 = state.stack.pop(); + var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; + function isLegacyActEnvironment(fiber) { + { + // Legacy mode. We preserve the behavior of React 17's act. It assumes an + // act environment whenever `jest` is defined, but you can still turn off + // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly + // to false. + var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global + typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest - if (exports.DEBUG) { console.log(state.step, 'SRP0[]', state.rp0); } -} + var jestIsDefined = typeof jest !== 'undefined'; + return warnsIfNotActing && jestIsDefined && isReactActEnvironmentGlobal !== false; + } + } + function isConcurrentActEnvironment() { + { + var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global + typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; -// SRP1[] Set Reference Point 1 -// 0x11 -function SRP1(state) { - state.rp1 = state.stack.pop(); + if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { + // TODO: Include link to relevant documentation page. + error('The current testing environment is not configured to support ' + 'act(...)'); + } - if (exports.DEBUG) { console.log(state.step, 'SRP1[]', state.rp1); } -} + return isReactActEnvironmentGlobal; + } + } -// SRP1[] Set Reference Point 2 -// 0x12 -function SRP2(state) { - state.rp2 = state.stack.pop(); + var ceil = Math.ceil; + var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, + ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, + ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig, + ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue; + var NoContext = + /* */ + 0; + var BatchedContext = + /* */ + 1; + var RenderContext = + /* */ + 2; + var CommitContext = + /* */ + 4; + var RootInProgress = 0; + var RootFatalErrored = 1; + var RootErrored = 2; + var RootSuspended = 3; + var RootSuspendedWithDelay = 4; + var RootCompleted = 5; + var RootDidNotComplete = 6; // Describes where we are in the React execution stack - if (exports.DEBUG) { console.log(state.step, 'SRP2[]', state.rp2); } -} + var executionContext = NoContext; // The root we're working on -// SZP0[] Set Zone Pointer 0 -// 0x13 -function SZP0(state) { - var n = state.stack.pop(); + var workInProgressRoot = null; // The fiber we're working on - if (exports.DEBUG) { console.log(state.step, 'SZP0[]', n); } + var workInProgress = null; // The lanes we're rendering - state.zp0 = n; + var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree + // This is a superset of the lanes we started working on at the root. The only + // case where it's different from `workInProgressRootRenderLanes` is when we + // enter a subtree that is hidden and needs to be unhidden: Suspense and + // Offscreen component. + // + // Most things in the work loop should deal with workInProgressRootRenderLanes. + // Most things in begin/complete phases should deal with subtreeRenderLanes. - switch (n) { - case 0: - if (!state.tZone) { initTZone(state); } - state.z0 = state.tZone; - break; - case 1 : - state.z0 = state.gZone; - break; - default : - throw new Error('Invalid zone pointer'); - } -} + var subtreeRenderLanes = NoLanes; + var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc. -// SZP1[] Set Zone Pointer 1 -// 0x14 -function SZP1(state) { - var n = state.stack.pop(); + var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown - if (exports.DEBUG) { console.log(state.step, 'SZP1[]', n); } + var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's + // includes unprocessed updates, not work in bailed out children. - state.zp1 = n; + var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render. - switch (n) { - case 0: - if (!state.tZone) { initTZone(state); } - state.z1 = state.tZone; - break; - case 1 : - state.z1 = state.gZone; - break; - default : - throw new Error('Invalid zone pointer'); - } -} + var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event). -// SZP2[] Set Zone Pointer 2 -// 0x15 -function SZP2(state) { - var n = state.stack.pop(); + var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase. - if (exports.DEBUG) { console.log(state.step, 'SZP2[]', n); } + var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI. + // We will log them once the tree commits. - state.zp2 = n; + var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train + // model where we don't commit new loading states in too quick succession. - switch (n) { - case 0: - if (!state.tZone) { initTZone(state); } - state.z2 = state.tZone; - break; - case 1 : - state.z2 = state.gZone; - break; - default : - throw new Error('Invalid zone pointer'); - } -} + var globalMostRecentFallbackTime = 0; + var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering + // more and prefer CPU suspense heuristics instead. -// SZPS[] Set Zone PointerS -// 0x16 -function SZPS(state) { - var n = state.stack.pop(); + var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU + // suspense heuristics and opt out of rendering more content. - if (exports.DEBUG) { console.log(state.step, 'SZPS[]', n); } + var RENDER_TIMEOUT_MS = 500; - state.zp0 = state.zp1 = state.zp2 = n; + function resetRenderTimer() { + workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS; + } - switch (n) { - case 0: - if (!state.tZone) { initTZone(state); } - state.z0 = state.z1 = state.z2 = state.tZone; - break; - case 1 : - state.z0 = state.z1 = state.z2 = state.gZone; - break; - default : - throw new Error('Invalid zone pointer'); - } -} + function getRenderTargetTime() { + return workInProgressRootRenderTargetTime; + } + var hasUncaughtError = false; + var firstUncaughtError = null; + var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true; + var rootDoesHavePassiveEffects = false; + var rootWithPendingPassiveEffects = null; + var pendingPassiveEffectsLanes = NoLanes; + var pendingPassiveProfilerEffects = []; -// SLOOP[] Set LOOP variable -// 0x17 -function SLOOP(state) { - state.loop = state.stack.pop(); + var NESTED_UPDATE_LIMIT = 50; + var nestedUpdateCount = 0; + var rootWithNestedUpdates = null; + var NESTED_PASSIVE_UPDATE_LIMIT = 50; + var nestedPassiveUpdateCount = 0; // If two updates are scheduled within the same event, we should treat their + // event times as simultaneous, even if the actual clock time has advanced + // between the first and second call. - if (exports.DEBUG) { console.log(state.step, 'SLOOP[]', state.loop); } -} + var currentEventTime = NoTimestamp; + var currentEventTransitionLane = NoLanes; + function getWorkInProgressRoot() { + return workInProgressRoot; + } + function requestEventTime() { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + // We're inside React, so it's fine to read the actual time. + return now$1(); + } // We're not inside React, so we may be in the middle of a browser event. -// RTG[] Round To Grid -// 0x18 -function RTG(state) { - if (exports.DEBUG) { console.log(state.step, 'RTG[]'); } - state.round = roundToGrid; -} + if (currentEventTime !== NoTimestamp) { + // Use the same start time for all updates until we enter React again. + return currentEventTime; + } // This is the first update since React yielded. Compute a new start time. -// RTHG[] Round To Half Grid -// 0x19 -function RTHG(state) { - if (exports.DEBUG) { console.log(state.step, 'RTHG[]'); } - state.round = roundToHalfGrid; -} + currentEventTime = now$1(); + return currentEventTime; + } + function requestUpdateLane(fiber) { + // Special cases + var mode = fiber.mode; -// SMD[] Set Minimum Distance -// 0x1A -function SMD(state) { - var d = state.stack.pop(); + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { + // This is a render phase update. These are not officially supported. The + // old behavior is to give this the same "thread" (lanes) as + // whatever is currently rendering. So if you call `setState` on a component + // that happens later in the same render, it will flush. Ideally, we want to + // remove the special case and treat them as if they came from an + // interleaved event. Regardless, this pattern is not officially supported. + // This behavior is only a fallback. The flag only exists until we can roll + // out the setState warning, since existing code might accidentally rely on + // the current behavior. + return pickArbitraryLane(workInProgressRootRenderLanes); + } - if (exports.DEBUG) { console.log(state.step, 'SMD[]', d); } + var isTransition = requestCurrentTransition() !== NoTransition; - state.minDis = d / 0x40; -} + if (isTransition) { + if ( ReactCurrentBatchConfig$2.transition !== null) { + var transition = ReactCurrentBatchConfig$2.transition; -// ELSE[] ELSE clause -// 0x1B -function ELSE(state) { - // This instruction has been reached by executing a then branch - // so it just skips ahead until matching EIF. - // - // In case the IF was negative the IF[] instruction already - // skipped forward over the ELSE[] + if (!transition._updatedFibers) { + transition._updatedFibers = new Set(); + } - if (exports.DEBUG) { console.log(state.step, 'ELSE[]'); } + transition._updatedFibers.add(fiber); + } // The algorithm for assigning an update to a lane should be stable for all + // updates at the same priority within the same event. To do this, the + // inputs to the algorithm must be the same. + // + // The trick we use is to cache the first of each of these inputs within an + // event. Then reset the cached values once we can be sure the event is + // over. Our heuristic for that is whenever we enter a concurrent work loop. - skip(state, false); -} -// JMPR[] JuMP Relative -// 0x1C -function JMPR(state) { - var o = state.stack.pop(); + if (currentEventTransitionLane === NoLane) { + // All transitions within the same event are assigned the same lane. + currentEventTransitionLane = claimNextTransitionLane(); + } - if (exports.DEBUG) { console.log(state.step, 'JMPR[]', o); } + return currentEventTransitionLane; + } // Updates originating inside certain React methods, like flushSync, have + // their priority set by tracking it with a context variable. + // + // The opaque type returned by the host config is internally a lane, so we can + // use that directly. + // TODO: Move this type conversion to the event priority module. - // A jump by 1 would do nothing. - state.ip += o - 1; -} -// SCVTCI[] Set Control Value Table Cut-In -// 0x1D -function SCVTCI(state) { - var n = state.stack.pop(); + var updateLane = getCurrentUpdatePriority(); - if (exports.DEBUG) { console.log(state.step, 'SCVTCI[]', n); } + if (updateLane !== NoLane) { + return updateLane; + } // This update originated outside React. Ask the host environment for an + // appropriate priority, based on the type of event. + // + // The opaque type returned by the host config is internally a lane, so we can + // use that directly. + // TODO: Move this type conversion to the event priority module. - state.cvCutIn = n / 0x40; -} -// DUP[] DUPlicate top stack element -// 0x20 -function DUP(state) { - var stack = state.stack; + var eventLane = getCurrentEventPriority(); + return eventLane; + } - if (exports.DEBUG) { console.log(state.step, 'DUP[]'); } + function requestRetryLane(fiber) { + // This is a fork of `requestUpdateLane` designed specifically for Suspense + // "retries" — a special update that attempts to flip a Suspense boundary + // from its placeholder state to its primary/resolved state. + // Special cases + var mode = fiber.mode; - stack.push(stack[stack.length - 1]); -} + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } -// POP[] POP top stack element -// 0x21 -function POP(state) { - if (exports.DEBUG) { console.log(state.step, 'POP[]'); } + return claimNextRetryLane(); + } - state.stack.pop(); -} + function scheduleUpdateOnFiber(fiber, lane, eventTime) { + checkForNestedUpdates(); + var root = markUpdateLaneFromFiberToRoot(fiber, lane); -// CLEAR[] CLEAR the stack -// 0x22 -function CLEAR(state) { - if (exports.DEBUG) { console.log(state.step, 'CLEAR[]'); } + if (root === null) { + return null; + } // Mark that the root has a pending update. - state.stack.length = 0; -} -// SWAP[] SWAP the top two elements on the stack -// 0x23 -function SWAP(state) { - var stack = state.stack; + markRootUpdated(root, lane, eventTime); - var a = stack.pop(); - var b = stack.pop(); + if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) { + // This update was dispatched during the render phase. This is a mistake + // if the update originates from user space (with the exception of local + // hook updates, which are handled differently and don't reach this + // function), but there are some internal React features that use this as + // an implementation detail, like selective hydration. + warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase + } else { + // This is a normal update, scheduled from outside the render phase. For + // example, during an input event. + { + if (isDevToolsPresent) { + addFiberToLanesMap(root, fiber, lane); + } + } - if (exports.DEBUG) { console.log(state.step, 'SWAP[]'); } + warnIfUpdatesNotWrappedWithActDEV(fiber); - stack.push(a); - stack.push(b); -} + if (root === workInProgressRoot) { + // TODO: Consolidate with `isInterleavedUpdate` check + // Received an update to a tree that's in the middle of rendering. Mark + // that there was an interleaved update work on this root. Unless the + // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render + // phase update. In that case, we don't treat render phase updates as if + // they were interleaved, for backwards compat reasons. + if ( (executionContext & RenderContext) === NoContext) { + workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); + } -// DEPTH[] DEPTH of the stack -// 0x24 -function DEPTH(state) { - var stack = state.stack; + if (workInProgressRootExitStatus === RootSuspendedWithDelay) { + // The root already suspended with a delay, which means this render + // definitely won't finish. Since we have a new update, let's mark it as + // suspended now, right before marking the incoming update. This has the + // effect of interrupting the current render and switching to the update. + // TODO: Make sure this doesn't override pings that happen while we've + // already started rendering. + markRootSuspended$1(root, workInProgressRootRenderLanes); + } + } - if (exports.DEBUG) { console.log(state.step, 'DEPTH[]'); } + ensureRootIsScheduled(root, eventTime); - stack.push(stack.length); -} + if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. + !( ReactCurrentActQueue$1.isBatchingLegacy)) { + // Flush the synchronous work now, unless we're already working or inside + // a batch. This is intentionally inside scheduleUpdateOnFiber instead of + // scheduleCallbackForFiber to preserve the ability to schedule a callback + // without immediately flushing it. We only do this for user-initiated + // updates, to preserve historical behavior of legacy mode. + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } -// LOOPCALL[] LOOPCALL function -// 0x2A -function LOOPCALL(state) { - var stack = state.stack; - var fn = stack.pop(); - var c = stack.pop(); + return root; + } + function scheduleInitialHydrationOnRoot(root, lane, eventTime) { + // This is a special fork of scheduleUpdateOnFiber that is only used to + // schedule the initial hydration of a root that has just been created. Most + // of the stuff in scheduleUpdateOnFiber can be skipped. + // + // The main reason for this separate path, though, is to distinguish the + // initial children from subsequent updates. In fully client-rendered roots + // (createRoot instead of hydrateRoot), all top-level renders are modeled as + // updates, but hydration roots are special because the initial render must + // match what was rendered on the server. + var current = root.current; + current.lanes = lane; + markRootUpdated(root, lane, eventTime); + ensureRootIsScheduled(root, eventTime); + } // This is split into a separate function so we can mark a fiber with pending + // work without treating it as a typical update that originates from an event; + // e.g. retrying a Suspense boundary isn't an update, but it does schedule work + // on a fiber. - if (exports.DEBUG) { console.log(state.step, 'LOOPCALL[]', fn, c); } + function markUpdateLaneFromFiberToRoot(sourceFiber, lane) { + // Update the source fiber's lanes + sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); + var alternate = sourceFiber.alternate; - // saves callers program - var cip = state.ip; - var cprog = state.prog; + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, lane); + } - state.prog = state.funcs[fn]; + { + if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) { + warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); + } + } // Walk the parent path to the root and update the child lanes. - // executes the function - for (var i = 0; i < c; i++) { - exec(state); - if (exports.DEBUG) { console.log( - ++state.step, - i + 1 < c ? 'next loopcall' : 'done loopcall', - i - ); } - } + var node = sourceFiber; + var parent = sourceFiber.return; - // restores the callers program - state.ip = cip; - state.prog = cprog; -} + while (parent !== null) { + parent.childLanes = mergeLanes(parent.childLanes, lane); + alternate = parent.alternate; -// CALL[] CALL function -// 0x2B -function CALL(state) { - var fn = state.stack.pop(); + if (alternate !== null) { + alternate.childLanes = mergeLanes(alternate.childLanes, lane); + } else { + { + if ((parent.flags & (Placement | Hydrating)) !== NoFlags) { + warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); + } + } + } - if (exports.DEBUG) { console.log(state.step, 'CALL[]', fn); } + node = parent; + parent = parent.return; + } - // saves callers program - var cip = state.ip; - var cprog = state.prog; + if (node.tag === HostRoot) { + var root = node.stateNode; + return root; + } else { + return null; + } + } - state.prog = state.funcs[fn]; + function isInterleavedUpdate(fiber, lane) { + return (// TODO: Optimize slightly by comparing to root that fiber belongs to. + // Requires some refactoring. Not a big deal though since it's rare for + // concurrent apps to have more than a single root. + workInProgressRoot !== null && (fiber.mode & ConcurrentMode) !== NoMode && ( // If this is a render phase update (i.e. UNSAFE_componentWillReceiveProps), + // then don't treat this as an interleaved update. This pattern is + // accompanied by a warning but we haven't fully deprecated it yet. We can + // remove once the deferRenderPhaseUpdateToNextBatch flag is enabled. + (executionContext & RenderContext) === NoContext) + ); + } // Use this function to schedule a task for a root. There's only one task per + // root; if a task was already scheduled, we'll check to make sure the priority + // of the existing task is the same as the priority of the next level that the + // root has work on. This function is called on every update, and right before + // exiting a task. - // executes the function - exec(state); + function ensureRootIsScheduled(root, currentTime) { + var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as + // expired so we know to work on those next. - // restores the callers program - state.ip = cip; - state.prog = cprog; + markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority. - if (exports.DEBUG) { console.log(++state.step, 'returning from', fn); } -} + var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); -// CINDEX[] Copy the INDEXed element to the top of the stack -// 0x25 -function CINDEX(state) { - var stack = state.stack; - var k = stack.pop(); + if (nextLanes === NoLanes) { + // Special case: There's nothing to work on. + if (existingCallbackNode !== null) { + cancelCallback$1(existingCallbackNode); + } - if (exports.DEBUG) { console.log(state.step, 'CINDEX[]', k); } + root.callbackNode = null; + root.callbackPriority = NoLane; + return; + } // We use the highest priority lane to represent the priority of the callback. - // In case of k == 1, it copies the last element after popping - // thus stack.length - k. - stack.push(stack[stack.length - k]); -} -// MINDEX[] Move the INDEXed element to the top of the stack -// 0x26 -function MINDEX(state) { - var stack = state.stack; - var k = stack.pop(); + var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it. - if (exports.DEBUG) { console.log(state.step, 'MINDEX[]', k); } + var existingCallbackPriority = root.callbackPriority; - stack.push(stack.splice(stack.length - k, 1)[0]); -} + if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a + // Scheduler task, rather than an `act` task, cancel it and re-scheduled + // on the `act` queue. + !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { + { + // If we're going to re-use an existing task, it needs to exist. + // Assume that discrete update microtasks are non-cancellable and null. + // TODO: Temporary until we confirm this warning is not fired. + if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) { + error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.'); + } + } // The priority hasn't changed. We can reuse the existing task. Exit. -// FDEF[] Function DEFinition -// 0x2C -function FDEF(state) { - if (state.env !== 'fpgm') { throw new Error('FDEF not allowed here'); } - var stack = state.stack; - var prog = state.prog; - var ip = state.ip; - var fn = stack.pop(); - var ipBegin = ip; + return; + } - if (exports.DEBUG) { console.log(state.step, 'FDEF[]', fn); } + if (existingCallbackNode != null) { + // Cancel the existing callback. We'll schedule a new one below. + cancelCallback$1(existingCallbackNode); + } // Schedule a new callback. - while (prog[++ip] !== 0x2D){ } - state.ip = ip; - state.funcs[fn] = prog.slice(ipBegin + 1, ip); -} + var newCallbackNode; -// MDAP[a] Move Direct Absolute Point -// 0x2E-0x2F -function MDAP(round, state) { - var pi = state.stack.pop(); - var p = state.z0[pi]; - var fv = state.fv; - var pv = state.pv; + if (newCallbackPriority === SyncLane) { + // Special case: Sync React callbacks are scheduled on a special + // internal queue + if (root.tag === LegacyRoot) { + if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) { + ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; + } - if (exports.DEBUG) { console.log(state.step, 'MDAP[' + round + ']', pi); } + scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); + } else { + scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); + } - var d = pv.distance(p, HPZero); + if (supportsMicrotasks) { + // Flush the queue in a microtask. + if ( ReactCurrentActQueue$1.current !== null) { + // Inside `act`, use our internal `act` queue so that these get flushed + // at the end of the current scope even when using the sync version + // of `act`. + ReactCurrentActQueue$1.current.push(flushSyncCallbacks); + } else { + scheduleMicrotask(function () { + // In Safari, appending an iframe forces microtasks to run. + // https://github.com/facebook/react/issues/22459 + // We don't support running callbacks in the middle of render + // or commit so we need to check against that. + if (executionContext === NoContext) { + // It's only safe to do this conditionally because we always + // check for pending work before we exit the task. + flushSyncCallbacks(); + } + }); + } + } else { + // Flush the queue in an Immediate task. + scheduleCallback$1(ImmediatePriority, flushSyncCallbacks); + } - if (round) { d = state.round(d); } + newCallbackNode = null; + } else { + var schedulerPriorityLevel; - fv.setRelative(p, HPZero, d, pv); - fv.touch(p); + switch (lanesToEventPriority(nextLanes)) { + case DiscreteEventPriority: + schedulerPriorityLevel = ImmediatePriority; + break; - state.rp0 = state.rp1 = pi; -} + case ContinuousEventPriority: + schedulerPriorityLevel = UserBlockingPriority; + break; -// IUP[a] Interpolate Untouched Points through the outline -// 0x30 -function IUP(v, state) { - var z2 = state.z2; - var pLen = z2.length - 2; - var cp; - var pp; - var np; + case DefaultEventPriority: + schedulerPriorityLevel = NormalPriority; + break; - if (exports.DEBUG) { console.log(state.step, 'IUP[' + v.axis + ']'); } + case IdleEventPriority: + schedulerPriorityLevel = IdlePriority; + break; - for (var i = 0; i < pLen; i++) { - cp = z2[i]; // current point + default: + schedulerPriorityLevel = NormalPriority; + break; + } - // if this point has been touched go on - if (v.touched(cp)) { continue; } + newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root)); + } - pp = cp.prevTouched(v); + root.callbackPriority = newCallbackPriority; + root.callbackNode = newCallbackNode; + } // This is the entry point for every concurrent task, i.e. anything that + // goes through Scheduler. - // no point on the contour has been touched? - if (pp === cp) { continue; } - np = cp.nextTouched(v); + function performConcurrentWorkOnRoot(root, didTimeout) { + { + resetNestedUpdateFlag(); + } // Since we know we're in a React event, we can clear the current + // event time. The next update will compute a new event time. - if (pp === np) { - // only one point on the contour has been touched - // so simply moves the point like that - v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true); - } + currentEventTime = NoTimestamp; + currentEventTransitionLane = NoLanes; - v.interpolate(cp, pp, np, v); - } -} + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Should not already be working.'); + } // Flush any pending passive effects before deciding which lanes to work on, + // in case they schedule additional work. -// SHP[] SHift Point using reference point -// 0x32-0x33 -function SHP(a, state) { - var stack = state.stack; - var rpi = a ? state.rp1 : state.rp2; - var rp = (a ? state.z0 : state.z1)[rpi]; - var fv = state.fv; - var pv = state.pv; - var loop = state.loop; - var z2 = state.z2; - while (loop--) - { - var pi = stack.pop(); - var p = z2[pi]; - - var d = pv.distance(rp, rp, false, true); - fv.setRelative(p, p, d, pv); - fv.touch(p); - - if (exports.DEBUG) { - console.log( - state.step, - (state.loop > 1 ? - 'loop ' + (state.loop - loop) + ': ' : - '' - ) + - 'SHP[' + (a ? 'rp1' : 'rp2') + ']', pi - ); - } - } + var originalCallbackNode = root.callbackNode; + var didFlushPassiveEffects = flushPassiveEffects(); - state.loop = 1; -} + if (didFlushPassiveEffects) { + // Something in the passive effect phase may have canceled the current task. + // Check if the task node for this root was changed. + if (root.callbackNode !== originalCallbackNode) { + // The current task was canceled. Exit. We don't need to call + // `ensureRootIsScheduled` because the check above implies either that + // there's a new task, or that there's no remaining work on this root. + return null; + } + } // Determine the next lanes to work on, using the fields stored + // on the root. -// SHC[] SHift Contour using reference point -// 0x36-0x37 -function SHC(a, state) { - var stack = state.stack; - var rpi = a ? state.rp1 : state.rp2; - var rp = (a ? state.z0 : state.z1)[rpi]; - var fv = state.fv; - var pv = state.pv; - var ci = stack.pop(); - var sp = state.z2[state.contours[ci]]; - var p = sp; - if (exports.DEBUG) { console.log(state.step, 'SHC[' + a + ']', ci); } + var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); - var d = pv.distance(rp, rp, false, true); + if (lanes === NoLanes) { + // Defensive coding. This is never expected to happen. + return null; + } // We disable time-slicing in some cases: if the work has been CPU-bound + // for too long ("expired" work, to prevent starvation), or we're in + // sync-updates-by-default mode. + // TODO: We only check `didTimeout` defensively, to account for a Scheduler + // bug we're still investigating. Once the bug in Scheduler is fixed, + // we can remove this, since we track expiration ourselves. - do { - if (p !== rp) { fv.setRelative(p, p, d, pv); } - p = p.nextPointOnContour; - } while (p !== sp); -} -// SHZ[] SHift Zone using reference point -// 0x36-0x37 -function SHZ(a, state) { - var stack = state.stack; - var rpi = a ? state.rp1 : state.rp2; - var rp = (a ? state.z0 : state.z1)[rpi]; - var fv = state.fv; - var pv = state.pv; + var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout); + var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes); - var e = stack.pop(); + if (exitStatus !== RootInProgress) { + if (exitStatus === RootErrored) { + // If something threw an error, try rendering one more time. We'll + // render synchronously to block concurrent data mutations, and we'll + // includes all pending updates are included. If it still fails after + // the second attempt, we'll give up and commit the resulting tree. + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - if (exports.DEBUG) { console.log(state.step, 'SHZ[' + a + ']', e); } + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, errorRetryLanes); + } + } - var z; - switch (e) { - case 0 : z = state.tZone; break; - case 1 : z = state.gZone; break; - default : throw new Error('Invalid zone'); - } + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now$1()); + throw fatalError; + } - var p; - var d = pv.distance(rp, rp, false, true); - var pLen = z.length - 2; - for (var i = 0; i < pLen; i++) - { - p = z[i]; - fv.setRelative(p, p, d, pv); - //if (p !== rp) fv.setRelative(p, p, d, pv); - } -} + if (exitStatus === RootDidNotComplete) { + // The render unwound without completing the tree. This happens in special + // cases where need to exit the current render without producing a + // consistent tree or committing. + // + // This should only happen during a concurrent render, not a discrete or + // synchronous update. We should have already checked for this when we + // unwound the stack. + markRootSuspended$1(root, lanes); + } else { + // The render completed. + // Check if this render may have yielded to a concurrent event, and if so, + // confirm that any newly rendered stores are consistent. + // TODO: It's possible that even a concurrent render may never have yielded + // to the main thread, if it was fast enough, or if it expired. We could + // skip the consistency check in that case, too. + var renderWasConcurrent = !includesBlockingLane(root, lanes); + var finishedWork = root.current.alternate; -// SHPIX[] SHift point by a PIXel amount -// 0x38 -function SHPIX(state) { - var stack = state.stack; - var loop = state.loop; - var fv = state.fv; - var d = stack.pop() / 0x40; - var z2 = state.z2; - - while (loop--) { - var pi = stack.pop(); - var p = z2[pi]; - - if (exports.DEBUG) { - console.log( - state.step, - (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + - 'SHPIX[]', pi, d - ); - } + if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { + // A store was mutated in an interleaved event. Render again, + // synchronously, to block further mutations. + exitStatus = renderRootSync(root, lanes); // We need to check again if something threw - fv.setRelative(p, p, d); - fv.touch(p); - } + if (exitStatus === RootErrored) { + var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - state.loop = 1; -} - -// IP[] Interpolate Point -// 0x39 -function IP(state) { - var stack = state.stack; - var rp1i = state.rp1; - var rp2i = state.rp2; - var loop = state.loop; - var rp1 = state.z0[rp1i]; - var rp2 = state.z1[rp2i]; - var fv = state.fv; - var pv = state.dpv; - var z2 = state.z2; - - while (loop--) { - var pi = stack.pop(); - var p = z2[pi]; - - if (exports.DEBUG) { - console.log( - state.step, - (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + - 'IP[]', pi, rp1i, '<->', rp2i - ); - } + if (_errorRetryLanes !== NoLanes) { + lanes = _errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any + // concurrent events. + } + } - fv.interpolate(p, rp1, rp2, pv); + if (exitStatus === RootFatalErrored) { + var _fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now$1()); + throw _fatalError; + } + } // We now have a consistent tree. The next step is either to commit it, + // or, if something suspended, wait to commit it after a timeout. - fv.touch(p); - } - state.loop = 1; -} - -// MSIRP[a] Move Stack Indirect Relative Point -// 0x3A-0x3B -function MSIRP(a, state) { - var stack = state.stack; - var d = stack.pop() / 64; - var pi = stack.pop(); - var p = state.z1[pi]; - var rp0 = state.z0[state.rp0]; - var fv = state.fv; - var pv = state.pv; - - fv.setRelative(p, rp0, d, pv); - fv.touch(p); - - if (exports.DEBUG) { console.log(state.step, 'MSIRP[' + a + ']', d, pi); } - - state.rp1 = state.rp0; - state.rp2 = pi; - if (a) { state.rp0 = pi; } -} - -// ALIGNRP[] Align to reference point. -// 0x3C -function ALIGNRP(state) { - var stack = state.stack; - var rp0i = state.rp0; - var rp0 = state.z0[rp0i]; - var loop = state.loop; - var fv = state.fv; - var pv = state.pv; - var z1 = state.z1; - - while (loop--) { - var pi = stack.pop(); - var p = z1[pi]; - - if (exports.DEBUG) { - console.log( - state.step, - (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + - 'ALIGNRP[]', pi - ); - } + root.finishedWork = finishedWork; + root.finishedLanes = lanes; + finishConcurrentRender(root, exitStatus, lanes); + } + } - fv.setRelative(p, rp0, 0, pv); - fv.touch(p); - } + ensureRootIsScheduled(root, now$1()); - state.loop = 1; -} + if (root.callbackNode === originalCallbackNode) { + // The task node scheduled for this root is the same one that's + // currently executed. Need to return a continuation. + return performConcurrentWorkOnRoot.bind(null, root); + } -// RTG[] Round To Double Grid -// 0x3D -function RTDG(state) { - if (exports.DEBUG) { console.log(state.step, 'RTDG[]'); } + return null; + } - state.round = roundToDoubleGrid; -} + function recoverFromConcurrentError(root, errorRetryLanes) { + // If an error occurred during hydration, discard server response and fall + // back to client side render. + // Before rendering again, save the errors from the previous attempt. + var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; -// MIAP[a] Move Indirect Absolute Point -// 0x3E-0x3F -function MIAP(round, state) { - var stack = state.stack; - var n = stack.pop(); - var pi = stack.pop(); - var p = state.z0[pi]; - var fv = state.fv; - var pv = state.pv; - var cv = state.cvt[n]; + if (isRootDehydrated(root)) { + // The shell failed to hydrate. Set a flag to force a client rendering + // during the next attempt. To do this, we call prepareFreshStack now + // to create the root work-in-progress fiber. This is a bit weird in terms + // of factoring, because it relies on renderRootSync not calling + // prepareFreshStack again in the call below, which happens because the + // root and lanes haven't changed. + // + // TODO: I think what we should do is set ForceClientRender inside + // throwException, like we do for nested Suspense boundaries. The reason + // it's here instead is so we can switch to the synchronous work loop, too. + // Something to consider for a future refactor. + var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); + rootWorkInProgress.flags |= ForceClientRender; - if (exports.DEBUG) { - console.log( - state.step, - 'MIAP[' + round + ']', - n, '(', cv, ')', pi - ); - } + { + errorHydratingContainer(root.containerInfo); + } + } - var d = pv.distance(p, HPZero); + var exitStatus = renderRootSync(root, errorRetryLanes); - if (round) { - if (Math.abs(d - cv) < state.cvCutIn) { d = cv; } + if (exitStatus !== RootErrored) { + // Successfully finished rendering on retry + // The errors from the failed first attempt have been recovered. Add + // them to the collection of recoverable errors. We'll log them in the + // commit phase. + var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; + workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors + // from the first attempt, to preserve the causal sequence. - d = state.round(d); - } + if (errorsFromSecondAttempt !== null) { + queueRecoverableErrors(errorsFromSecondAttempt); + } + } - fv.setRelative(p, HPZero, d, pv); + return exitStatus; + } - if (state.zp0 === 0) { - p.xo = p.x; - p.yo = p.y; - } + function queueRecoverableErrors(errors) { + if (workInProgressRootRecoverableErrors === null) { + workInProgressRootRecoverableErrors = errors; + } else { + workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); + } + } - fv.touch(p); + function finishConcurrentRender(root, exitStatus, lanes) { + switch (exitStatus) { + case RootInProgress: + case RootFatalErrored: + { + throw new Error('Root did not complete. This is a bug in React.'); + } + // Flow knows about invariant, so it complains if I add a break + // statement, but eslint doesn't know about invariant, so it complains + // if I do. eslint-disable-next-line no-fallthrough - state.rp0 = state.rp1 = pi; -} + case RootErrored: + { + // We should have already attempted to retry this tree. If we reached + // this point, it errored again. Commit it. + commitRoot(root, workInProgressRootRecoverableErrors); + break; + } -// NPUSB[] PUSH N Bytes -// 0x40 -function NPUSHB(state) { - var prog = state.prog; - var ip = state.ip; - var stack = state.stack; + case RootSuspended: + { + markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we + // should immediately commit it or wait a bit. - var n = prog[++ip]; + if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope + !shouldForceFlushFallbacksInDEV()) { + // This render only included retries, no updates. Throttle committing + // retries so that we don't show too many loading states too quickly. + var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now$1(); // Don't bother with a very short suspense time. - if (exports.DEBUG) { console.log(state.step, 'NPUSHB[]', n); } + if (msUntilTimeout > 10) { + var nextLanes = getNextLanes(root, NoLanes); - for (var i = 0; i < n; i++) { stack.push(prog[++ip]); } + if (nextLanes !== NoLanes) { + // There's additional work on this root. + break; + } - state.ip = ip; -} + var suspendedLanes = root.suspendedLanes; -// NPUSHW[] PUSH N Words -// 0x41 -function NPUSHW(state) { - var ip = state.ip; - var prog = state.prog; - var stack = state.stack; - var n = prog[++ip]; + if (!isSubsetOfLanes(suspendedLanes, lanes)) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + // FIXME: What if the suspended lanes are Idle? Should not restart. + requestEventTime(); + markRootPinged(root, suspendedLanes); + break; + } // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback + // immediately, wait for more data to arrive. - if (exports.DEBUG) { console.log(state.step, 'NPUSHW[]', n); } - for (var i = 0; i < n; i++) { - var w = (prog[++ip] << 8) | prog[++ip]; - if (w & 0x8000) { w = -((w ^ 0xffff) + 1); } - stack.push(w); - } + root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors), msUntilTimeout); + break; + } + } // The work expired. Commit immediately. - state.ip = ip; -} -// WS[] Write Store -// 0x42 -function WS(state) { - var stack = state.stack; - var store = state.store; + commitRoot(root, workInProgressRootRecoverableErrors); + break; + } - if (!store) { store = state.store = []; } + case RootSuspendedWithDelay: + { + markRootSuspended$1(root, lanes); - var v = stack.pop(); - var l = stack.pop(); + if (includesOnlyTransitions(lanes)) { + // This is a transition, so we should exit without committing a + // placeholder and without scheduling a timeout. Delay indefinitely + // until we receive more data. + break; + } - if (exports.DEBUG) { console.log(state.step, 'WS', v, l); } + if (!shouldForceFlushFallbacksInDEV()) { + // This is not a transition, but we did trigger an avoided state. + // Schedule a placeholder to display after a short delay, using the Just + // Noticeable Difference. + // TODO: Is the JND optimization worth the added complexity? If this is + // the only reason we track the event time, then probably not. + // Consider removing. + var mostRecentEventTime = getMostRecentEventTime(root, lanes); + var eventTimeMs = mostRecentEventTime; + var timeElapsedMs = now$1() - eventTimeMs; - store[l] = v; -} + var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time. -// RS[] Read Store -// 0x43 -function RS(state) { - var stack = state.stack; - var store = state.store; - var l = stack.pop(); + if (_msUntilTimeout > 10) { + // Instead of committing the fallback immediately, wait for more data + // to arrive. + root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors), _msUntilTimeout); + break; + } + } // Commit the placeholder. - if (exports.DEBUG) { console.log(state.step, 'RS', l); } - var v = (store && store[l]) || 0; + commitRoot(root, workInProgressRootRecoverableErrors); + break; + } - stack.push(v); -} + case RootCompleted: + { + // The work completed. Ready to commit. + commitRoot(root, workInProgressRootRecoverableErrors); + break; + } -// WCVTP[] Write Control Value Table in Pixel units -// 0x44 -function WCVTP(state) { - var stack = state.stack; + default: + { + throw new Error('Unknown root exit status.'); + } + } + } - var v = stack.pop(); - var l = stack.pop(); + function isRenderConsistentWithExternalStores(finishedWork) { + // Search the rendered tree for external store reads, and check whether the + // stores were mutated in a concurrent event. Intentionally using an iterative + // loop instead of recursion so we can exit early. + var node = finishedWork; - if (exports.DEBUG) { console.log(state.step, 'WCVTP', v, l); } + while (true) { + if (node.flags & StoreConsistency) { + var updateQueue = node.updateQueue; - state.cvt[l] = v / 0x40; -} + if (updateQueue !== null) { + var checks = updateQueue.stores; -// RCVT[] Read Control Value Table entry -// 0x45 -function RCVT(state) { - var stack = state.stack; - var cvte = stack.pop(); + if (checks !== null) { + for (var i = 0; i < checks.length; i++) { + var check = checks[i]; + var getSnapshot = check.getSnapshot; + var renderedValue = check.value; - if (exports.DEBUG) { console.log(state.step, 'RCVT', cvte); } + try { + if (!objectIs(getSnapshot(), renderedValue)) { + // Found an inconsistent store. + return false; + } + } catch (error) { + // If `getSnapshot` throws, return `false`. This will schedule + // a re-render, and the error will be rethrown during render. + return false; + } + } + } + } + } - stack.push(state.cvt[cvte] * 0x40); -} + var child = node.child; -// GC[] Get Coordinate projected onto the projection vector -// 0x46-0x47 -function GC(a, state) { - var stack = state.stack; - var pi = stack.pop(); - var p = state.z2[pi]; + if (node.subtreeFlags & StoreConsistency && child !== null) { + child.return = node; + node = child; + continue; + } - if (exports.DEBUG) { console.log(state.step, 'GC[' + a + ']', pi); } + if (node === finishedWork) { + return true; + } - stack.push(state.dpv.distance(p, HPZero, a, false) * 0x40); -} + while (node.sibling === null) { + if (node.return === null || node.return === finishedWork) { + return true; + } -// MD[a] Measure Distance -// 0x49-0x4A -function MD(a, state) { - var stack = state.stack; - var pi2 = stack.pop(); - var pi1 = stack.pop(); - var p2 = state.z1[pi2]; - var p1 = state.z0[pi1]; - var d = state.dpv.distance(p1, p2, a, a); + node = node.return; + } - if (exports.DEBUG) { console.log(state.step, 'MD[' + a + ']', pi2, pi1, '->', d); } + node.sibling.return = node.return; + node = node.sibling; + } // Flow doesn't know this is unreachable, but eslint does + // eslint-disable-next-line no-unreachable - state.stack.push(Math.round(d * 64)); -} -// MPPEM[] Measure Pixels Per EM -// 0x4B -function MPPEM(state) { - if (exports.DEBUG) { console.log(state.step, 'MPPEM[]'); } - state.stack.push(state.ppem); -} + return true; + } -// FLIPON[] set the auto FLIP Boolean to ON -// 0x4D -function FLIPON(state) { - if (exports.DEBUG) { console.log(state.step, 'FLIPON[]'); } - state.autoFlip = true; -} + function markRootSuspended$1(root, suspendedLanes) { + // When suspending, we should always exclude lanes that were pinged or (more + // rarely, since we try to avoid it) updated during the render phase. + // TODO: Lol maybe there's a better way to factor this besides this + // obnoxiously named function :) + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); + markRootSuspended(root, suspendedLanes); + } // This is the entry point for synchronous tasks that don't go + // through Scheduler -// LT[] Less Than -// 0x50 -function LT(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'LT[]', e2, e1); } + function performSyncWorkOnRoot(root) { + { + syncNestedUpdateFlag(); + } - stack.push(e1 < e2 ? 1 : 0); -} + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Should not already be working.'); + } -// LTEQ[] Less Than or EQual -// 0x53 -function LTEQ(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + flushPassiveEffects(); + var lanes = getNextLanes(root, NoLanes); - if (exports.DEBUG) { console.log(state.step, 'LTEQ[]', e2, e1); } + if (!includesSomeLane(lanes, SyncLane)) { + // There's no remaining sync work left. + ensureRootIsScheduled(root, now$1()); + return null; + } - stack.push(e1 <= e2 ? 1 : 0); -} + var exitStatus = renderRootSync(root, lanes); -// GTEQ[] Greater Than -// 0x52 -function GT(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + if (root.tag !== LegacyRoot && exitStatus === RootErrored) { + // If something threw an error, try rendering one more time. We'll render + // synchronously to block concurrent data mutations, and we'll includes + // all pending updates are included. If it still fails after the second + // attempt, we'll give up and commit the resulting tree. + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); - if (exports.DEBUG) { console.log(state.step, 'GT[]', e2, e1); } + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root, errorRetryLanes); + } + } - stack.push(e1 > e2 ? 1 : 0); -} + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root, NoLanes); + markRootSuspended$1(root, lanes); + ensureRootIsScheduled(root, now$1()); + throw fatalError; + } -// GTEQ[] Greater Than or EQual -// 0x53 -function GTEQ(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + if (exitStatus === RootDidNotComplete) { + throw new Error('Root did not complete. This is a bug in React.'); + } // We now have a consistent tree. Because this is a sync render, we + // will commit it even if something suspended. - if (exports.DEBUG) { console.log(state.step, 'GTEQ[]', e2, e1); } - stack.push(e1 >= e2 ? 1 : 0); -} + var finishedWork = root.current.alternate; + root.finishedWork = finishedWork; + root.finishedLanes = lanes; + commitRoot(root, workInProgressRootRecoverableErrors); // Before exiting, make sure there's a callback scheduled for the next + // pending level. -// EQ[] EQual -// 0x54 -function EQ(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + ensureRootIsScheduled(root, now$1()); + return null; + } - if (exports.DEBUG) { console.log(state.step, 'EQ[]', e2, e1); } + function flushRoot(root, lanes) { + if (lanes !== NoLanes) { + markRootEntangled(root, mergeLanes(lanes, SyncLane)); + ensureRootIsScheduled(root, now$1()); - stack.push(e2 === e1 ? 1 : 0); -} + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + resetRenderTimer(); + flushSyncCallbacks(); + } + } + } + function deferredUpdates(fn) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$2.transition; -// NEQ[] Not EQual -// 0x55 -function NEQ(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DefaultEventPriority); + return fn(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + } + } + function batchedUpdates(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; - if (exports.DEBUG) { console.log(state.step, 'NEQ[]', e2, e1); } + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer + // most batchedUpdates-like method. - stack.push(e2 !== e1 ? 1 : 0); -} + if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. + !( ReactCurrentActQueue$1.isBatchingLegacy)) { + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } + } + function discreteUpdates(fn, a, b, c, d) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$2.transition; -// ODD[] ODD -// 0x56 -function ODD(state) { - var stack = state.stack; - var n = stack.pop(); + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + return fn(a, b, c, d); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; - if (exports.DEBUG) { console.log(state.step, 'ODD[]', n); } + if (executionContext === NoContext) { + resetRenderTimer(); + } + } + } // Overload the definition to the two valid signatures. + // Warning, this opts-out of checking the function body. - stack.push(Math.trunc(n) % 2 ? 1 : 0); -} + // eslint-disable-next-line no-redeclare + function flushSync(fn) { + // In legacy mode, we flush pending passive effects at the beginning of the + // next event, not at the end of the previous one. + if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { + flushPassiveEffects(); + } -// EVEN[] EVEN -// 0x57 -function EVEN(state) { - var stack = state.stack; - var n = stack.pop(); + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + var prevTransition = ReactCurrentBatchConfig$2.transition; + var previousPriority = getCurrentUpdatePriority(); - if (exports.DEBUG) { console.log(state.step, 'EVEN[]', n); } + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); - stack.push(Math.trunc(n) % 2 ? 0 : 1); -} + if (fn) { + return fn(); + } else { + return undefined; + } + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. + // Note that this will happen even if batchedUpdates is higher up + // the stack. -// IF[] IF test -// 0x58 -function IF(state) { - var test = state.stack.pop(); + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + flushSyncCallbacks(); + } + } + } + function isAlreadyRendering() { + // Used by the renderer to print a warning if certain APIs are called from + // the wrong context. + return (executionContext & (RenderContext | CommitContext)) !== NoContext; + } + function flushControlled(fn) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + var prevTransition = ReactCurrentBatchConfig$2.transition; + var previousPriority = getCurrentUpdatePriority(); - if (exports.DEBUG) { console.log(state.step, 'IF[]', test); } + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + fn(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + executionContext = prevExecutionContext; - // if test is true it just continues - // if not the ip is skipped until matching ELSE or EIF - if (!test) { - skip(state, true); + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + resetRenderTimer(); + flushSyncCallbacks(); + } + } + } + function pushRenderLanes(fiber, lanes) { + push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); + subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); + } + function popRenderLanes(fiber) { + subtreeRenderLanes = subtreeRenderLanesCursor.current; + pop(subtreeRenderLanesCursor, fiber); + } - if (exports.DEBUG) { console.log(state.step, 'EIF[]'); } - } -} + function prepareFreshStack(root, lanes) { + root.finishedWork = null; + root.finishedLanes = NoLanes; + var timeoutHandle = root.timeoutHandle; -// EIF[] End IF -// 0x59 -function EIF(state) { - // this can be reached normally when - // executing an else branch. - // -> just ignore it + if (timeoutHandle !== noTimeout) { + // The root previous suspended and scheduled a timeout to commit a fallback + // state. Now that we have additional work, cancel the timeout. + root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above - if (exports.DEBUG) { console.log(state.step, 'EIF[]'); } -} + cancelTimeout(timeoutHandle); + } -// AND[] logical AND -// 0x5A -function AND(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + if (workInProgress !== null) { + var interruptedWork = workInProgress.return; - if (exports.DEBUG) { console.log(state.step, 'AND[]', e2, e1); } + while (interruptedWork !== null) { + var current = interruptedWork.alternate; + unwindInterruptedWork(current, interruptedWork); + interruptedWork = interruptedWork.return; + } + } - stack.push(e2 && e1 ? 1 : 0); -} + workInProgressRoot = root; + var rootWorkInProgress = createWorkInProgress(root.current, null); + workInProgress = rootWorkInProgress; + workInProgressRootRenderLanes = subtreeRenderLanes = lanes; + workInProgressRootExitStatus = RootInProgress; + workInProgressRootFatalError = null; + workInProgressRootSkippedLanes = NoLanes; + workInProgressRootInterleavedUpdatedLanes = NoLanes; + workInProgressRootPingedLanes = NoLanes; + workInProgressRootConcurrentErrors = null; + workInProgressRootRecoverableErrors = null; + enqueueInterleavedUpdates(); -// OR[] logical OR -// 0x5B -function OR(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + { + ReactStrictModeWarnings.discardPendingWarnings(); + } - if (exports.DEBUG) { console.log(state.step, 'OR[]', e2, e1); } + return rootWorkInProgress; + } - stack.push(e2 || e1 ? 1 : 0); -} + function handleError(root, thrownValue) { + do { + var erroredWork = workInProgress; -// NOT[] logical NOT -// 0x5C -function NOT(state) { - var stack = state.stack; - var e = stack.pop(); + try { + // Reset module-level state that was set during the render phase. + resetContextDependencies(); + resetHooksAfterThrow(); + resetCurrentFiber(); // TODO: I found and added this missing line while investigating a + // separate issue. Write a regression test using string refs. - if (exports.DEBUG) { console.log(state.step, 'NOT[]', e); } + ReactCurrentOwner$2.current = null; - stack.push(e ? 0 : 1); -} + if (erroredWork === null || erroredWork.return === null) { + // Expected to be working on a non-root fiber. This is a fatal error + // because there's no ancestor that can handle it; the root is + // supposed to capture all errors that weren't caught by an error + // boundary. + workInProgressRootExitStatus = RootFatalErrored; + workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next + // sibling, or the parent if there are no siblings. But since the root + // has no siblings nor a parent, we set it to null. Usually this is + // handled by `completeUnitOfWork` or `unwindWork`, but since we're + // intentionally not calling those, we need set it here. + // TODO: Consider calling `unwindWork` to pop the contexts. -// DELTAP1[] DELTA exception P1 -// DELTAP2[] DELTA exception P2 -// DELTAP3[] DELTA exception P3 -// 0x5D, 0x71, 0x72 -function DELTAP123(b, state) { - var stack = state.stack; - var n = stack.pop(); - var fv = state.fv; - var pv = state.pv; - var ppem = state.ppem; - var base = state.deltaBase + (b - 1) * 16; - var ds = state.deltaShift; - var z0 = state.z0; + workInProgress = null; + return; + } - if (exports.DEBUG) { console.log(state.step, 'DELTAP[' + b + ']', n, stack); } + if (enableProfilerTimer && erroredWork.mode & ProfileMode) { + // Record the time spent rendering before an error was thrown. This + // avoids inaccurate Profiler durations in the case of a + // suspended render. + stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); + } - for (var i = 0; i < n; i++) { - var pi = stack.pop(); - var arg = stack.pop(); - var appem = base + ((arg & 0xF0) >> 4); - if (appem !== ppem) { continue; } + if (enableSchedulingProfiler) { + markComponentRenderStopped(); - var mag = (arg & 0x0F) - 8; - if (mag >= 0) { mag++; } - if (exports.DEBUG) { console.log(state.step, 'DELTAPFIX', pi, 'by', mag * ds); } + if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') { + var wakeable = thrownValue; + markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes); + } else { + markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes); + } + } - var p = z0[pi]; - fv.setRelative(p, p, mag * ds, pv); - } -} + throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); + completeUnitOfWork(erroredWork); + } catch (yetAnotherThrownValue) { + // Something in the return path also threw. + thrownValue = yetAnotherThrownValue; -// SDB[] Set Delta Base in the graphics state -// 0x5E -function SDB(state) { - var stack = state.stack; - var n = stack.pop(); + if (workInProgress === erroredWork && erroredWork !== null) { + // If this boundary has already errored, then we had trouble processing + // the error. Bubble it to the next boundary. + erroredWork = erroredWork.return; + workInProgress = erroredWork; + } else { + erroredWork = workInProgress; + } - if (exports.DEBUG) { console.log(state.step, 'SDB[]', n); } + continue; + } // Return to the normal work loop. - state.deltaBase = n; -} -// SDS[] Set Delta Shift in the graphics state -// 0x5F -function SDS(state) { - var stack = state.stack; - var n = stack.pop(); + return; + } while (true); + } - if (exports.DEBUG) { console.log(state.step, 'SDS[]', n); } + function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher$2.current; + ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; - state.deltaShift = Math.pow(0.5, n); -} + if (prevDispatcher === null) { + // The React isomorphic package does not include a default dispatcher. + // Instead the first renderer will lazily attach one, in order to give + // nicer error messages. + return ContextOnlyDispatcher; + } else { + return prevDispatcher; + } + } -// ADD[] ADD -// 0x60 -function ADD(state) { - var stack = state.stack; - var n2 = stack.pop(); - var n1 = stack.pop(); + function popDispatcher(prevDispatcher) { + ReactCurrentDispatcher$2.current = prevDispatcher; + } - if (exports.DEBUG) { console.log(state.step, 'ADD[]', n2, n1); } + function markCommitTimeOfFallback() { + globalMostRecentFallbackTime = now$1(); + } + function markSkippedUpdateLanes(lane) { + workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes); + } + function renderDidSuspend() { + if (workInProgressRootExitStatus === RootInProgress) { + workInProgressRootExitStatus = RootSuspended; + } + } + function renderDidSuspendDelayIfPossible() { + if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) { + workInProgressRootExitStatus = RootSuspendedWithDelay; + } // Check if there are updates that we skipped tree that might have unblocked + // this render. - stack.push(n1 + n2); -} -// SUB[] SUB -// 0x61 -function SUB(state) { - var stack = state.stack; - var n2 = stack.pop(); - var n1 = stack.pop(); + if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { + // Mark the current render as suspended so that we switch to working on + // the updates that were skipped. Usually we only suspend at the end of + // the render phase. + // TODO: We should probably always mark the root as suspended immediately + // (inside this function), since by suspending at the end of the render + // phase introduces a potential mistake where we suspend lanes that were + // pinged or updated while we were rendering. + markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); + } + } + function renderDidError(error) { + if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { + workInProgressRootExitStatus = RootErrored; + } - if (exports.DEBUG) { console.log(state.step, 'SUB[]', n2, n1); } + if (workInProgressRootConcurrentErrors === null) { + workInProgressRootConcurrentErrors = [error]; + } else { + workInProgressRootConcurrentErrors.push(error); + } + } // Called during render to determine if anything has suspended. + // Returns false if we're not sure. - stack.push(n1 - n2); -} + function renderHasNotSuspendedYet() { + // If something errored or completed, we can't really be sure, + // so those are false. + return workInProgressRootExitStatus === RootInProgress; + } -// DIV[] DIV -// 0x62 -function DIV(state) { - var stack = state.stack; - var n2 = stack.pop(); - var n1 = stack.pop(); + function renderRootSync(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. - if (exports.DEBUG) { console.log(state.step, 'DIV[]', n2, n1); } + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; - stack.push(n1 * 64 / n2); -} + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. + // If we bailout on this work, we'll move them back (like above). + // It's important to move them now in case the work spawns more work at the same priority with different updaters. + // That way we can keep the current update and future updates separate. -// MUL[] MUL -// 0x63 -function MUL(state) { - var stack = state.stack; - var n2 = stack.pop(); - var n1 = stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'MUL[]', n2, n1); } + movePendingFibersToMemoized(root, lanes); + } + } + prepareFreshStack(root, lanes); + } - stack.push(n1 * n2 / 64); -} + { + markRenderStarted(lanes); + } -// ABS[] ABSolute value -// 0x64 -function ABS(state) { - var stack = state.stack; - var n = stack.pop(); + do { + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); - if (exports.DEBUG) { console.log(state.step, 'ABS[]', n); } + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); - stack.push(Math.abs(n)); -} + if (workInProgress !== null) { + // This is a sync render, so we should have finished the whole tree. + throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.'); + } -// NEG[] NEGate -// 0x65 -function NEG(state) { - var stack = state.stack; - var n = stack.pop(); + { + markRenderStopped(); + } // Set this to null to indicate there's no in-progress render. - if (exports.DEBUG) { console.log(state.step, 'NEG[]', n); } - stack.push(-n); -} + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; + return workInProgressRootExitStatus; + } // The work loop is an extremely hot path. Tell Closure not to inline it. -// FLOOR[] FLOOR -// 0x66 -function FLOOR(state) { - var stack = state.stack; - var n = stack.pop(); + /** @noinline */ - if (exports.DEBUG) { console.log(state.step, 'FLOOR[]', n); } - stack.push(Math.floor(n / 0x40) * 0x40); -} + function workLoopSync() { + // Already timed out, so perform work without checking if we need to yield. + while (workInProgress !== null) { + performUnitOfWork(workInProgress); + } + } -// CEILING[] CEILING -// 0x67 -function CEILING(state) { - var stack = state.stack; - var n = stack.pop(); + function renderRootConcurrent(root, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. - if (exports.DEBUG) { console.log(state.step, 'CEILING[]', n); } + if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; - stack.push(Math.ceil(n / 0x40) * 0x40); -} + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. + // If we bailout on this work, we'll move them back (like above). + // It's important to move them now in case the work spawns more work at the same priority with different updaters. + // That way we can keep the current update and future updates separate. -// ROUND[ab] ROUND value -// 0x68-0x6B -function ROUND(dt, state) { - var stack = state.stack; - var n = stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'ROUND[]'); } + movePendingFibersToMemoized(root, lanes); + } + } + resetRenderTimer(); + prepareFreshStack(root, lanes); + } - stack.push(state.round(n / 0x40) * 0x40); -} + { + markRenderStarted(lanes); + } -// WCVTF[] Write Control Value Table in Funits -// 0x70 -function WCVTF(state) { - var stack = state.stack; - var v = stack.pop(); - var l = stack.pop(); + do { + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); - if (exports.DEBUG) { console.log(state.step, 'WCVTF[]', v, l); } + resetContextDependencies(); + popDispatcher(prevDispatcher); + executionContext = prevExecutionContext; - state.cvt[l] = v * state.ppem / state.font.unitsPerEm; -} -// DELTAC1[] DELTA exception C1 -// DELTAC2[] DELTA exception C2 -// DELTAC3[] DELTA exception C3 -// 0x73, 0x74, 0x75 -function DELTAC123(b, state) { - var stack = state.stack; - var n = stack.pop(); - var ppem = state.ppem; - var base = state.deltaBase + (b - 1) * 16; - var ds = state.deltaShift; + if (workInProgress !== null) { + // Still work remaining. + { + markRenderYielded(); + } - if (exports.DEBUG) { console.log(state.step, 'DELTAC[' + b + ']', n, stack); } + return RootInProgress; + } else { + // Completed the tree. + { + markRenderStopped(); + } // Set this to null to indicate there's no in-progress render. - for (var i = 0; i < n; i++) { - var c = stack.pop(); - var arg = stack.pop(); - var appem = base + ((arg & 0xF0) >> 4); - if (appem !== ppem) { continue; } - var mag = (arg & 0x0F) - 8; - if (mag >= 0) { mag++; } + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; // Return the final exit status. - var delta = mag * ds; + return workInProgressRootExitStatus; + } + } + /** @noinline */ - if (exports.DEBUG) { console.log(state.step, 'DELTACFIX', c, 'by', delta); } - state.cvt[c] += delta; - } -} + function workLoopConcurrent() { + // Perform work until Scheduler asks us to yield + while (workInProgress !== null && !shouldYield()) { + performUnitOfWork(workInProgress); + } + } -// SROUND[] Super ROUND -// 0x76 -function SROUND(state) { - var n = state.stack.pop(); + function performUnitOfWork(unitOfWork) { + // The current, flushed, state of this fiber is the alternate. Ideally + // nothing should rely on this, but relying on it here means that we don't + // need an additional field on the work in progress. + var current = unitOfWork.alternate; + setCurrentFiber(unitOfWork); + var next; - if (exports.DEBUG) { console.log(state.step, 'SROUND[]', n); } + if ( (unitOfWork.mode & ProfileMode) !== NoMode) { + startProfilerTimer(unitOfWork); + next = beginWork$1(current, unitOfWork, subtreeRenderLanes); + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); + } else { + next = beginWork$1(current, unitOfWork, subtreeRenderLanes); + } - state.round = roundSuper; + resetCurrentFiber(); + unitOfWork.memoizedProps = unitOfWork.pendingProps; - var period; + if (next === null) { + // If this doesn't spawn new work, complete the current work. + completeUnitOfWork(unitOfWork); + } else { + workInProgress = next; + } - switch (n & 0xC0) { - case 0x00: - period = 0.5; - break; - case 0x40: - period = 1; - break; - case 0x80: - period = 2; - break; - default: - throw new Error('invalid SROUND value'); - } + ReactCurrentOwner$2.current = null; + } - state.srPeriod = period; - - switch (n & 0x30) { - case 0x00: - state.srPhase = 0; - break; - case 0x10: - state.srPhase = 0.25 * period; - break; - case 0x20: - state.srPhase = 0.5 * period; - break; - case 0x30: - state.srPhase = 0.75 * period; - break; - default: throw new Error('invalid SROUND value'); - } + function completeUnitOfWork(unitOfWork) { + // Attempt to complete the current unit of work, then move to the next + // sibling. If there are no more siblings, return to the parent fiber. + var completedWork = unitOfWork; - n &= 0x0F; + do { + // The current, flushed, state of this fiber is the alternate. Ideally + // nothing should rely on this, but relying on it here means that we don't + // need an additional field on the work in progress. + var current = completedWork.alternate; + var returnFiber = completedWork.return; // Check if the work completed or if something threw. - if (n === 0) { state.srThreshold = 0; } - else { state.srThreshold = (n / 8 - 0.5) * period; } -} + if ((completedWork.flags & Incomplete) === NoFlags) { + setCurrentFiber(completedWork); + var next = void 0; -// S45ROUND[] Super ROUND 45 degrees -// 0x77 -function S45ROUND(state) { - var n = state.stack.pop(); + if ( (completedWork.mode & ProfileMode) === NoMode) { + next = completeWork(current, completedWork, subtreeRenderLanes); + } else { + startProfilerTimer(completedWork); + next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error. - if (exports.DEBUG) { console.log(state.step, 'S45ROUND[]', n); } + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); + } - state.round = roundSuper; + resetCurrentFiber(); - var period; + if (next !== null) { + // Completing this fiber spawned new work. Work on that next. + workInProgress = next; + return; + } + } else { + // This fiber did not complete because something threw. Pop values off + // the stack without entering the complete phase. If this is a boundary, + // capture values if possible. + var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes. - switch (n & 0xC0) { - case 0x00: - period = Math.sqrt(2) / 2; - break; - case 0x40: - period = Math.sqrt(2); - break; - case 0x80: - period = 2 * Math.sqrt(2); - break; - default: - throw new Error('invalid S45ROUND value'); - } - state.srPeriod = period; - - switch (n & 0x30) { - case 0x00: - state.srPhase = 0; - break; - case 0x10: - state.srPhase = 0.25 * period; - break; - case 0x20: - state.srPhase = 0.5 * period; - break; - case 0x30: - state.srPhase = 0.75 * period; - break; - default: - throw new Error('invalid S45ROUND value'); - } + if (_next !== null) { + // If completing this work spawned new work, do that next. We'll come + // back here again. + // Since we're restarting, remove anything that is not a host effect + // from the effect tag. + _next.flags &= HostEffectMask; + workInProgress = _next; + return; + } - n &= 0x0F; + if ( (completedWork.mode & ProfileMode) !== NoMode) { + // Record the render duration for the fiber that errored. + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing. - if (n === 0) { state.srThreshold = 0; } - else { state.srThreshold = (n / 8 - 0.5) * period; } -} + var actualDuration = completedWork.actualDuration; + var child = completedWork.child; -// ROFF[] Round Off -// 0x7A -function ROFF(state) { - if (exports.DEBUG) { console.log(state.step, 'ROFF[]'); } + while (child !== null) { + actualDuration += child.actualDuration; + child = child.sibling; + } - state.round = roundOff; -} + completedWork.actualDuration = actualDuration; + } -// RUTG[] Round Up To Grid -// 0x7C -function RUTG(state) { - if (exports.DEBUG) { console.log(state.step, 'RUTG[]'); } + if (returnFiber !== null) { + // Mark the parent fiber as incomplete and clear its subtree flags. + returnFiber.flags |= Incomplete; + returnFiber.subtreeFlags = NoFlags; + returnFiber.deletions = null; + } else { + // We've unwound all the way to the root. + workInProgressRootExitStatus = RootDidNotComplete; + workInProgress = null; + return; + } + } - state.round = roundUpToGrid; -} + var siblingFiber = completedWork.sibling; -// RDTG[] Round Down To Grid -// 0x7D -function RDTG(state) { - if (exports.DEBUG) { console.log(state.step, 'RDTG[]'); } + if (siblingFiber !== null) { + // If there is more work to do in this returnFiber, do that next. + workInProgress = siblingFiber; + return; + } // Otherwise, return to the parent - state.round = roundDownToGrid; -} -// SCANCTRL[] SCAN conversion ConTRoL -// 0x85 -function SCANCTRL(state) { - var n = state.stack.pop(); + completedWork = returnFiber; // Update the next thing we're working on in case something throws. - // ignored by opentype.js + workInProgress = completedWork; + } while (completedWork !== null); // We've reached the root. - if (exports.DEBUG) { console.log(state.step, 'SCANCTRL[]', n); } -} -// SDPVTL[a] Set Dual Projection Vector To Line -// 0x86-0x87 -function SDPVTL(a, state) { - var stack = state.stack; - var p2i = stack.pop(); - var p1i = stack.pop(); - var p2 = state.z2[p2i]; - var p1 = state.z1[p1i]; + if (workInProgressRootExitStatus === RootInProgress) { + workInProgressRootExitStatus = RootCompleted; + } + } - if (exports.DEBUG) { console.log(state.step, 'SDPVTL[' + a + ']', p2i, p1i); } + function commitRoot(root, recoverableErrors) { + // TODO: This no longer makes any sense. We already wrap the mutation and + // layout phases. Should be able to remove. + var previousUpdateLanePriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$2.transition; - var dx; - var dy; + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + commitRootImpl(root, recoverableErrors, previousUpdateLanePriority); + } finally { + ReactCurrentBatchConfig$2.transition = prevTransition; + setCurrentUpdatePriority(previousUpdateLanePriority); + } - if (!a) { - dx = p1.x - p2.x; - dy = p1.y - p2.y; - } else { - dx = p2.y - p1.y; - dy = p1.x - p2.x; - } + return null; + } - state.dpv = getUnitVector(dx, dy); -} + function commitRootImpl(root, recoverableErrors, renderPriorityLevel) { + do { + // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which + // means `flushPassiveEffects` will sometimes result in additional + // passive effects. So we need to keep flushing in a loop until there are + // no more pending effects. + // TODO: Might be better if `flushPassiveEffects` did not automatically + // flush synchronous work at the end, to avoid factoring hazards like this. + flushPassiveEffects(); + } while (rootWithPendingPassiveEffects !== null); -// GETINFO[] GET INFOrmation -// 0x88 -function GETINFO(state) { - var stack = state.stack; - var sel = stack.pop(); - var r = 0; + flushRenderPhaseStrictModeWarningsInDEV(); - if (exports.DEBUG) { console.log(state.step, 'GETINFO[]', sel); } + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Should not already be working.'); + } - // v35 as in no subpixel hinting - if (sel & 0x01) { r = 35; } + var finishedWork = root.finishedWork; + var lanes = root.finishedLanes; - // TODO rotation and stretch currently not supported - // and thus those GETINFO are always 0. + { + markCommitStarted(lanes); + } - // opentype.js is always gray scaling - if (sel & 0x20) { r |= 0x1000; } + if (finishedWork === null) { - stack.push(r); -} + { + markCommitStopped(); + } -// ROLL[] ROLL the top three stack elements -// 0x8A -function ROLL(state) { - var stack = state.stack; - var a = stack.pop(); - var b = stack.pop(); - var c = stack.pop(); + return null; + } else { + { + if (lanes === NoLanes) { + error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.'); + } + } + } - if (exports.DEBUG) { console.log(state.step, 'ROLL[]'); } + root.finishedWork = null; + root.finishedLanes = NoLanes; - stack.push(b); - stack.push(a); - stack.push(c); -} + if (finishedWork === root.current) { + throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.'); + } // commitRoot never returns a continuation; it always finishes synchronously. + // So we can clear these now to allow a new callback to be scheduled. -// MAX[] MAXimum of top two stack elements -// 0x8B -function MAX(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'MAX[]', e2, e1); } + root.callbackNode = null; + root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first + // pending time is whatever is left on the root fiber. - stack.push(Math.max(e1, e2)); -} + var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); + markRootFinished(root, remainingLanes); -// MIN[] MINimum of top two stack elements -// 0x8C -function MIN(state) { - var stack = state.stack; - var e2 = stack.pop(); - var e1 = stack.pop(); + if (root === workInProgressRoot) { + // We can reset these now that they are finished. + workInProgressRoot = null; + workInProgress = null; + workInProgressRootRenderLanes = NoLanes; + } // If there are pending passive effects, schedule a callback to process them. + // Do this as early as possible, so it is queued before anything else that + // might get scheduled in the commit phase. (See #16714.) + // TODO: Delete all other places that schedule the passive effect callback + // They're redundant. - if (exports.DEBUG) { console.log(state.step, 'MIN[]', e2, e1); } - stack.push(Math.min(e1, e2)); -} + if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback$1(NormalPriority, function () { + flushPassiveEffects(); // This render triggered passive effects: release the root cache pool + // *after* passive effects fire to avoid freeing a cache pool that may + // be referenced by a node in the tree (HostRoot, Cache boundary etc) -// SCANTYPE[] SCANTYPE -// 0x8D -function SCANTYPE(state) { - var n = state.stack.pop(); - // ignored by opentype.js - if (exports.DEBUG) { console.log(state.step, 'SCANTYPE[]', n); } -} + return null; + }); + } + } // Check if there are any effects in the whole tree. + // TODO: This is left over from the effect list implementation, where we had + // to check for the existence of `firstEffect` to satisfy Flow. I think the + // only other reason this optimization exists is because it affects profiling. + // Reconsider whether this is necessary. -// INSTCTRL[] INSTCTRL -// 0x8D -function INSTCTRL(state) { - var s = state.stack.pop(); - var v = state.stack.pop(); - if (exports.DEBUG) { console.log(state.step, 'INSTCTRL[]', s, v); } + var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; + var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; - switch (s) { - case 1 : state.inhibitGridFit = !!v; return; - case 2 : state.ignoreCvt = !!v; return; - default: throw new Error('invalid INSTCTRL[] selector'); - } -} + if (subtreeHasEffects || rootHasEffect) { + var prevTransition = ReactCurrentBatchConfig$2.transition; + ReactCurrentBatchConfig$2.transition = null; + var previousPriority = getCurrentUpdatePriority(); + setCurrentUpdatePriority(DiscreteEventPriority); + var prevExecutionContext = executionContext; + executionContext |= CommitContext; // Reset this to null before calling lifecycles -// PUSHB[abc] PUSH Bytes -// 0xB0-0xB7 -function PUSHB(n, state) { - var stack = state.stack; - var prog = state.prog; - var ip = state.ip; + ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass + // of the effect list for each phase: all mutation effects come before all + // layout effects, and so on. + // The first phase a "before mutation" phase. We use this phase to read the + // state of the host tree right before we mutate it. This is where + // getSnapshotBeforeUpdate is called. - if (exports.DEBUG) { console.log(state.step, 'PUSHB[' + n + ']'); } + commitBeforeMutationEffects(root, finishedWork); - for (var i = 0; i < n; i++) { stack.push(prog[++ip]); } + { + // Mark the current commit time to be shared by all Profilers in this + // batch. This enables them to be grouped later. + recordCommitTime(); + } - state.ip = ip; -} -// PUSHW[abc] PUSH Words -// 0xB8-0xBF -function PUSHW(n, state) { - var ip = state.ip; - var prog = state.prog; - var stack = state.stack; + commitMutationEffects(root, finishedWork, lanes); - if (exports.DEBUG) { console.log(state.ip, 'PUSHW[' + n + ']'); } + resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after + // the mutation phase, so that the previous tree is still current during + // componentWillUnmount, but before the layout phase, so that the finished + // work is current during componentDidMount/Update. - for (var i = 0; i < n; i++) { - var w = (prog[++ip] << 8) | prog[++ip]; - if (w & 0x8000) { w = -((w ^ 0xffff) + 1); } - stack.push(w); - } + root.current = finishedWork; // The next phase is the layout phase, where we call effects that read - state.ip = ip; -} + { + markLayoutEffectsStarted(lanes); + } -// MDRP[abcde] Move Direct Relative Point -// 0xD0-0xEF -// (if indirect is 0) -// -// and -// -// MIRP[abcde] Move Indirect Relative Point -// 0xE0-0xFF -// (if indirect is 1) - -function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) { - var stack = state.stack; - var cvte = indirect && stack.pop(); - var pi = stack.pop(); - var rp0i = state.rp0; - var rp = state.z0[rp0i]; - var p = state.z1[pi]; - - var md = state.minDis; - var fv = state.fv; - var pv = state.dpv; - var od; // original distance - var d; // moving distance - var sign; // sign of distance - var cv; - - d = od = pv.distance(p, rp, true, true); - sign = d >= 0 ? 1 : -1; // Math.sign would be 0 in case of 0 - - // TODO consider autoFlip - d = Math.abs(d); - - if (indirect) { - cv = state.cvt[cvte]; - - if (ro && Math.abs(d - cv) < state.cvCutIn) { d = cv; } - } + commitLayoutEffects(finishedWork, root, lanes); - if (keepD && d < md) { d = md; } + { + markLayoutEffectsStopped(); + } + // opportunity to paint. - if (ro) { d = state.round(d); } - fv.setRelative(p, rp, sign * d, pv); - fv.touch(p); + requestPaint(); + executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value. - if (exports.DEBUG) { - console.log( - state.step, - (indirect ? 'MIRP[' : 'MDRP[') + - (setRp0 ? 'M' : 'm') + - (keepD ? '>' : '_') + - (ro ? 'R' : '_') + - (dt === 0 ? 'Gr' : (dt === 1 ? 'Bl' : (dt === 2 ? 'Wh' : ''))) + - ']', - indirect ? - cvte + '(' + state.cvt[cvte] + ',' + cv + ')' : - '', - pi, - '(d =', od, '->', sign * d, ')' - ); - } + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; + } else { + // No effects. + root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were + // no effects. + // TODO: Maybe there's a better way to report this. - state.rp1 = state.rp0; - state.rp2 = pi; - if (setRp0) { state.rp0 = pi; } -} + { + recordCommitTime(); + } + } -/* -* The instruction table. -*/ -instructionTable = [ - /* 0x00 */ SVTCA.bind(undefined, yUnitVector), - /* 0x01 */ SVTCA.bind(undefined, xUnitVector), - /* 0x02 */ SPVTCA.bind(undefined, yUnitVector), - /* 0x03 */ SPVTCA.bind(undefined, xUnitVector), - /* 0x04 */ SFVTCA.bind(undefined, yUnitVector), - /* 0x05 */ SFVTCA.bind(undefined, xUnitVector), - /* 0x06 */ SPVTL.bind(undefined, 0), - /* 0x07 */ SPVTL.bind(undefined, 1), - /* 0x08 */ SFVTL.bind(undefined, 0), - /* 0x09 */ SFVTL.bind(undefined, 1), - /* 0x0A */ SPVFS, - /* 0x0B */ SFVFS, - /* 0x0C */ GPV, - /* 0x0D */ GFV, - /* 0x0E */ SFVTPV, - /* 0x0F */ ISECT, - /* 0x10 */ SRP0, - /* 0x11 */ SRP1, - /* 0x12 */ SRP2, - /* 0x13 */ SZP0, - /* 0x14 */ SZP1, - /* 0x15 */ SZP2, - /* 0x16 */ SZPS, - /* 0x17 */ SLOOP, - /* 0x18 */ RTG, - /* 0x19 */ RTHG, - /* 0x1A */ SMD, - /* 0x1B */ ELSE, - /* 0x1C */ JMPR, - /* 0x1D */ SCVTCI, - /* 0x1E */ undefined, // TODO SSWCI - /* 0x1F */ undefined, // TODO SSW - /* 0x20 */ DUP, - /* 0x21 */ POP, - /* 0x22 */ CLEAR, - /* 0x23 */ SWAP, - /* 0x24 */ DEPTH, - /* 0x25 */ CINDEX, - /* 0x26 */ MINDEX, - /* 0x27 */ undefined, // TODO ALIGNPTS - /* 0x28 */ undefined, - /* 0x29 */ undefined, // TODO UTP - /* 0x2A */ LOOPCALL, - /* 0x2B */ CALL, - /* 0x2C */ FDEF, - /* 0x2D */ undefined, // ENDF (eaten by FDEF) - /* 0x2E */ MDAP.bind(undefined, 0), - /* 0x2F */ MDAP.bind(undefined, 1), - /* 0x30 */ IUP.bind(undefined, yUnitVector), - /* 0x31 */ IUP.bind(undefined, xUnitVector), - /* 0x32 */ SHP.bind(undefined, 0), - /* 0x33 */ SHP.bind(undefined, 1), - /* 0x34 */ SHC.bind(undefined, 0), - /* 0x35 */ SHC.bind(undefined, 1), - /* 0x36 */ SHZ.bind(undefined, 0), - /* 0x37 */ SHZ.bind(undefined, 1), - /* 0x38 */ SHPIX, - /* 0x39 */ IP, - /* 0x3A */ MSIRP.bind(undefined, 0), - /* 0x3B */ MSIRP.bind(undefined, 1), - /* 0x3C */ ALIGNRP, - /* 0x3D */ RTDG, - /* 0x3E */ MIAP.bind(undefined, 0), - /* 0x3F */ MIAP.bind(undefined, 1), - /* 0x40 */ NPUSHB, - /* 0x41 */ NPUSHW, - /* 0x42 */ WS, - /* 0x43 */ RS, - /* 0x44 */ WCVTP, - /* 0x45 */ RCVT, - /* 0x46 */ GC.bind(undefined, 0), - /* 0x47 */ GC.bind(undefined, 1), - /* 0x48 */ undefined, // TODO SCFS - /* 0x49 */ MD.bind(undefined, 0), - /* 0x4A */ MD.bind(undefined, 1), - /* 0x4B */ MPPEM, - /* 0x4C */ undefined, // TODO MPS - /* 0x4D */ FLIPON, - /* 0x4E */ undefined, // TODO FLIPOFF - /* 0x4F */ undefined, // TODO DEBUG - /* 0x50 */ LT, - /* 0x51 */ LTEQ, - /* 0x52 */ GT, - /* 0x53 */ GTEQ, - /* 0x54 */ EQ, - /* 0x55 */ NEQ, - /* 0x56 */ ODD, - /* 0x57 */ EVEN, - /* 0x58 */ IF, - /* 0x59 */ EIF, - /* 0x5A */ AND, - /* 0x5B */ OR, - /* 0x5C */ NOT, - /* 0x5D */ DELTAP123.bind(undefined, 1), - /* 0x5E */ SDB, - /* 0x5F */ SDS, - /* 0x60 */ ADD, - /* 0x61 */ SUB, - /* 0x62 */ DIV, - /* 0x63 */ MUL, - /* 0x64 */ ABS, - /* 0x65 */ NEG, - /* 0x66 */ FLOOR, - /* 0x67 */ CEILING, - /* 0x68 */ ROUND.bind(undefined, 0), - /* 0x69 */ ROUND.bind(undefined, 1), - /* 0x6A */ ROUND.bind(undefined, 2), - /* 0x6B */ ROUND.bind(undefined, 3), - /* 0x6C */ undefined, // TODO NROUND[ab] - /* 0x6D */ undefined, // TODO NROUND[ab] - /* 0x6E */ undefined, // TODO NROUND[ab] - /* 0x6F */ undefined, // TODO NROUND[ab] - /* 0x70 */ WCVTF, - /* 0x71 */ DELTAP123.bind(undefined, 2), - /* 0x72 */ DELTAP123.bind(undefined, 3), - /* 0x73 */ DELTAC123.bind(undefined, 1), - /* 0x74 */ DELTAC123.bind(undefined, 2), - /* 0x75 */ DELTAC123.bind(undefined, 3), - /* 0x76 */ SROUND, - /* 0x77 */ S45ROUND, - /* 0x78 */ undefined, // TODO JROT[] - /* 0x79 */ undefined, // TODO JROF[] - /* 0x7A */ ROFF, - /* 0x7B */ undefined, - /* 0x7C */ RUTG, - /* 0x7D */ RDTG, - /* 0x7E */ POP, // actually SANGW, supposed to do only a pop though - /* 0x7F */ POP, // actually AA, supposed to do only a pop though - /* 0x80 */ undefined, // TODO FLIPPT - /* 0x81 */ undefined, // TODO FLIPRGON - /* 0x82 */ undefined, // TODO FLIPRGOFF - /* 0x83 */ undefined, - /* 0x84 */ undefined, - /* 0x85 */ SCANCTRL, - /* 0x86 */ SDPVTL.bind(undefined, 0), - /* 0x87 */ SDPVTL.bind(undefined, 1), - /* 0x88 */ GETINFO, - /* 0x89 */ undefined, // TODO IDEF - /* 0x8A */ ROLL, - /* 0x8B */ MAX, - /* 0x8C */ MIN, - /* 0x8D */ SCANTYPE, - /* 0x8E */ INSTCTRL, - /* 0x8F */ undefined, - /* 0x90 */ undefined, - /* 0x91 */ undefined, - /* 0x92 */ undefined, - /* 0x93 */ undefined, - /* 0x94 */ undefined, - /* 0x95 */ undefined, - /* 0x96 */ undefined, - /* 0x97 */ undefined, - /* 0x98 */ undefined, - /* 0x99 */ undefined, - /* 0x9A */ undefined, - /* 0x9B */ undefined, - /* 0x9C */ undefined, - /* 0x9D */ undefined, - /* 0x9E */ undefined, - /* 0x9F */ undefined, - /* 0xA0 */ undefined, - /* 0xA1 */ undefined, - /* 0xA2 */ undefined, - /* 0xA3 */ undefined, - /* 0xA4 */ undefined, - /* 0xA5 */ undefined, - /* 0xA6 */ undefined, - /* 0xA7 */ undefined, - /* 0xA8 */ undefined, - /* 0xA9 */ undefined, - /* 0xAA */ undefined, - /* 0xAB */ undefined, - /* 0xAC */ undefined, - /* 0xAD */ undefined, - /* 0xAE */ undefined, - /* 0xAF */ undefined, - /* 0xB0 */ PUSHB.bind(undefined, 1), - /* 0xB1 */ PUSHB.bind(undefined, 2), - /* 0xB2 */ PUSHB.bind(undefined, 3), - /* 0xB3 */ PUSHB.bind(undefined, 4), - /* 0xB4 */ PUSHB.bind(undefined, 5), - /* 0xB5 */ PUSHB.bind(undefined, 6), - /* 0xB6 */ PUSHB.bind(undefined, 7), - /* 0xB7 */ PUSHB.bind(undefined, 8), - /* 0xB8 */ PUSHW.bind(undefined, 1), - /* 0xB9 */ PUSHW.bind(undefined, 2), - /* 0xBA */ PUSHW.bind(undefined, 3), - /* 0xBB */ PUSHW.bind(undefined, 4), - /* 0xBC */ PUSHW.bind(undefined, 5), - /* 0xBD */ PUSHW.bind(undefined, 6), - /* 0xBE */ PUSHW.bind(undefined, 7), - /* 0xBF */ PUSHW.bind(undefined, 8), - /* 0xC0 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0), - /* 0xC1 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1), - /* 0xC2 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2), - /* 0xC3 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3), - /* 0xC4 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0), - /* 0xC5 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1), - /* 0xC6 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2), - /* 0xC7 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3), - /* 0xC8 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0), - /* 0xC9 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1), - /* 0xCA */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2), - /* 0xCB */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3), - /* 0xCC */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0), - /* 0xCD */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1), - /* 0xCE */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2), - /* 0xCF */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3), - /* 0xD0 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0), - /* 0xD1 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1), - /* 0xD2 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2), - /* 0xD3 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3), - /* 0xD4 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0), - /* 0xD5 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1), - /* 0xD6 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2), - /* 0xD7 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3), - /* 0xD8 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0), - /* 0xD9 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1), - /* 0xDA */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2), - /* 0xDB */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3), - /* 0xDC */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0), - /* 0xDD */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1), - /* 0xDE */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2), - /* 0xDF */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3), - /* 0xE0 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0), - /* 0xE1 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1), - /* 0xE2 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2), - /* 0xE3 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3), - /* 0xE4 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0), - /* 0xE5 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1), - /* 0xE6 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2), - /* 0xE7 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3), - /* 0xE8 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0), - /* 0xE9 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1), - /* 0xEA */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2), - /* 0xEB */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3), - /* 0xEC */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0), - /* 0xED */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1), - /* 0xEE */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2), - /* 0xEF */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3), - /* 0xF0 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0), - /* 0xF1 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1), - /* 0xF2 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2), - /* 0xF3 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3), - /* 0xF4 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0), - /* 0xF5 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1), - /* 0xF6 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2), - /* 0xF7 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3), - /* 0xF8 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0), - /* 0xF9 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1), - /* 0xFA */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2), - /* 0xFB */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3), - /* 0xFC */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0), - /* 0xFD */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1), - /* 0xFE */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2), - /* 0xFF */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3) -]; + var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; -/***************************** - Mathematical Considerations -****************************** - -fv ... refers to freedom vector -pv ... refers to projection vector -rp ... refers to reference point -p ... refers to to point being operated on -d ... refers to distance + if (rootDoesHavePassiveEffects) { + // This commit has passive effects. Stash a reference to them. But don't + // schedule a callback until after flushing layout work. + rootDoesHavePassiveEffects = false; + rootWithPendingPassiveEffects = root; + pendingPassiveEffectsLanes = lanes; + } // Read this again, since an effect might have updated it -SETRELATIVE: -============ -case freedom vector == x-axis: ------------------------------- + remainingLanes = root.pendingLanes; // Check if there's remaining work on this root + // TODO: This is part of the `componentDidCatch` implementation. Its purpose + // is to detect whether something might have called setState inside + // `componentDidCatch`. The mechanism is known to be flawed because `setState` + // inside `componentDidCatch` is itself flawed — that's why we recommend + // `getDerivedStateFromError` instead. However, it could be improved by + // checking if remainingLanes includes Sync work, instead of whether there's + // any work remaining at all (which would also include stuff like Suspense + // retries or transitions). It's been like this for a while, though, so fixing + // it probably isn't that urgent. - (pv) - .-' - rpd .-' - .-* - d .-'90°' - .-' ' - .-' ' - *-' ' b - rp ' - ' - ' - p *----------*-------------- (fv) - pm + if (remainingLanes === NoLanes) { + // If there's no remaining work, we can clear the set of already failed + // error boundaries. + legacyErrorBoundariesThatAlreadyFailed = null; + } - rpdx = rpx + d * pv.x - rpdy = rpy + d * pv.y + { + if (!rootDidHavePassiveEffects) { + commitDoubleInvokeEffectsInDEV(root.current, false); + } + } - equation of line b + onCommitRoot(finishedWork.stateNode, renderPriorityLevel); - y - rpdy = pvns * (x- rpdx) + { + if (isDevToolsPresent) { + root.memoizedUpdaters.clear(); + } + } - y = p.y + { + onCommitRoot$1(); + } // Always call this before exiting `commitRoot`, to ensure that any + // additional work on this root is scheduled. - x = rpdx + ( p.y - rpdy ) / pvns + ensureRootIsScheduled(root, now$1()); -case freedom vector == y-axis: ------------------------------- + if (recoverableErrors !== null) { + // There were errors during this render, but recovered from them without + // needing to surface it to the UI. We log them here. + var onRecoverableError = root.onRecoverableError; - * pm - |\ - | \ - | \ - | \ - | \ - | \ - | \ - | \ - | \ - | \ b - | \ - | \ - | \ .-' (pv) - | 90° \.-' - | .-'* rpd - | .-' - * *-' d - p rp + for (var i = 0; i < recoverableErrors.length; i++) { + var recoverableError = recoverableErrors[i]; + onRecoverableError(recoverableError); + } + } - rpdx = rpx + d * pv.x - rpdy = rpy + d * pv.y + if (hasUncaughtError) { + hasUncaughtError = false; + var error$1 = firstUncaughtError; + firstUncaughtError = null; + throw error$1; + } // If the passive effects are the result of a discrete render, flush them + // synchronously at the end of the current task so that the result is + // immediately observable. Otherwise, we assume that they are not + // order-dependent and do not need to be observed by external systems, so we + // can wait until after paint. + // TODO: We can optimize this by not scheduling the callback earlier. Since we + // currently schedule the callback in multiple places, will wait until those + // are consolidated. - equation of line b: - pvns ... normal slope to pv - y - rpdy = pvns * (x - rpdx) + if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) { + flushPassiveEffects(); + } // Read this again, since a passive effect might have updated it - x = p.x - y = rpdy + pvns * (p.x - rpdx) + remainingLanes = root.pendingLanes; + if (includesSomeLane(remainingLanes, SyncLane)) { + { + markNestedUpdateScheduled(); + } // Count the number of times the root synchronously re-renders without + // finishing. If there are too many, it indicates an infinite update loop. -generic case: -------------- + if (root === rootWithNestedUpdates) { + nestedUpdateCount++; + } else { + nestedUpdateCount = 0; + rootWithNestedUpdates = root; + } + } else { + nestedUpdateCount = 0; + } // If layout work was scheduled, flush it now. - .'(fv) - .' - .* pm - .' ! - .' . - .' ! - .' . b - .' ! - * . - p ! - 90° . ... (pv) - ...-*-''' - ...---''' rpd - ...---''' d - *--''' - rp + flushSyncCallbacks(); - rpdx = rpx + d * pv.x - rpdy = rpy + d * pv.y + { + markCommitStopped(); + } - equation of line b: - pvns... normal slope to pv + return null; + } - y - rpdy = pvns * (x - rpdx) + function flushPassiveEffects() { + // Returns whether passive effects were flushed. + // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should + // probably just combine the two functions. I believe they were only separate + // in the first place because we used to wrap it with + // `Scheduler.runWithPriority`, which accepts a function. But now we track the + // priority within React itself, so we can mutate the variable directly. + if (rootWithPendingPassiveEffects !== null) { + var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); + var priority = lowerEventPriority(DefaultEventPriority, renderPriority); + var prevTransition = ReactCurrentBatchConfig$2.transition; + var previousPriority = getCurrentUpdatePriority(); - equation of freedom vector line: - fvs ... slope of freedom vector (=fy/fx) + try { + ReactCurrentBatchConfig$2.transition = null; + setCurrentUpdatePriority(priority); + return flushPassiveEffectsImpl(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.transition = prevTransition; // Once passive effects have run for the tree - giving components a + } + } - y - py = fvs * (x - px) + return false; + } + function enqueuePendingPassiveProfilerEffect(fiber) { + { + pendingPassiveProfilerEffects.push(fiber); + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback$1(NormalPriority, function () { + flushPassiveEffects(); + return null; + }); + } + } + } - on pm both equations are true for same x/y + function flushPassiveEffectsImpl() { + if (rootWithPendingPassiveEffects === null) { + return false; + } - y - rpdy = pvns * (x - rpdx) + var root = rootWithPendingPassiveEffects; + var lanes = pendingPassiveEffectsLanes; + rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects. + // Figure out why and fix it. It's not causing any known issues (probably + // because it's only used for profiling), but it's a refactor hazard. - y - py = fvs * (x - px) + pendingPassiveEffectsLanes = NoLanes; - form to y and set equal: + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error('Cannot flush passive effects while already rendering.'); + } - pvns * (x - rpdx) + rpdy = fvs * (x - px) + py + { + markPassiveEffectsStarted(lanes); + } - expand: + var prevExecutionContext = executionContext; + executionContext |= CommitContext; + commitPassiveUnmountEffects(root.current); + commitPassiveMountEffects(root, root.current); // TODO: Move to commitPassiveMountEffects - pvns * x - pvns * rpdx + rpdy = fvs * x - fvs * px + py + { + var profilerEffects = pendingPassiveProfilerEffects; + pendingPassiveProfilerEffects = []; - switch: + for (var i = 0; i < profilerEffects.length; i++) { + var _fiber = profilerEffects[i]; + commitPassiveEffectDurations(root, _fiber); + } + } - fvs * x - fvs * px + py = pvns * x - pvns * rpdx + rpdy + { + markPassiveEffectsStopped(); + } - solve for x: + { + commitDoubleInvokeEffectsInDEV(root.current, true); + } - fvs * x - pvns * x = fvs * px - pvns * rpdx - py + rpdy + executionContext = prevExecutionContext; + flushSyncCallbacks(); // If additional passive effects were scheduled, increment a counter. If this + // exceeds the limit, we'll fire a warning. + nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1; // TODO: Move to commitPassiveMountEffects + onPostCommitRoot(root); - fvs * px - pvns * rpdx + rpdy - py - x = ----------------------------------- - fvs - pvns + { + var stateNode = root.current.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } - and: + return true; + } - y = fvs * (x - px) + py + function isAlreadyFailedLegacyErrorBoundary(instance) { + return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); + } + function markLegacyErrorBoundaryAsFailed(instance) { + if (legacyErrorBoundariesThatAlreadyFailed === null) { + legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); + } else { + legacyErrorBoundariesThatAlreadyFailed.add(instance); + } + } + function prepareToThrowUncaughtError(error) { + if (!hasUncaughtError) { + hasUncaughtError = true; + firstUncaughtError = error; + } + } + var onUncaughtError = prepareToThrowUncaughtError; -INTERPOLATE: -============ + function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { + var errorInfo = createCapturedValue(error, sourceFiber); + var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); + enqueueUpdate(rootFiber, update); + var eventTime = requestEventTime(); + var root = markUpdateLaneFromFiberToRoot(rootFiber, SyncLane); -Examples of point interpolation. + if (root !== null) { + markRootUpdated(root, SyncLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + } -The weight of the movement of the reference point gets bigger -the further the other reference point is away, thus the safest -option (that is avoiding 0/0 divisions) is to weight the -original distance of the other point by the sum of both distances. + function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { + if (sourceFiber.tag === HostRoot) { + // Error was thrown at the root. There is no parent, so the root + // itself should capture it. + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1); + return; + } -If the sum of both distances is 0, then move the point by the -arithmetic average of the movement of both reference points. + var fiber = null; + { + fiber = nearestMountedAncestor; + } + while (fiber !== null) { + if (fiber.tag === HostRoot) { + captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1); + return; + } else if (fiber.tag === ClassComponent) { + var ctor = fiber.type; + var instance = fiber.stateNode; + if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) { + var errorInfo = createCapturedValue(error$1, sourceFiber); + var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); + enqueueUpdate(fiber, update); + var eventTime = requestEventTime(); + var root = markUpdateLaneFromFiberToRoot(fiber, SyncLane); - (+6) - rp1o *---->*rp1 - . . (+12) - . . rp2o *---------->* rp2 - . . . . - . . . . - . 10 20 . . - |.........|...................| . - . . . - . . (+8) . - po *------>*p . - . . . - . 12 . 24 . - |...........|.......................| - 36 + if (root !== null) { + markRootUpdated(root, SyncLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + return; + } + } -------- + fiber = fiber.return; + } + { + // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning + // will fire for errors that are thrown by destroy functions inside deleted + // trees. What it should instead do is propagate the error to the parent of + // the deleted tree. In the meantime, do not add this warning to the + // allowlist; this is only for our internal use. + error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1); + } + } + function pingSuspendedRoot(root, wakeable, pingedLanes) { + var pingCache = root.pingCache; + if (pingCache !== null) { + // The wakeable resolved, so we no longer need to memoize, because it will + // never be thrown again. + pingCache.delete(wakeable); + } - (+10) - rp1o *-------->*rp1 - . . (-10) - . . rp2 *<---------* rpo2 - . . . . - . . . . - . 10 . 30 . . - |.........|.............................| - . . - . (+5) . - po *--->* p . - . . . - . . 20 . - |....|..............| - 5 15 + var eventTime = requestEventTime(); + markRootPinged(root, pingedLanes); + warnIfSuspenseResolutionNotWrappedWithActDEV(root); + if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { + // Received a ping at the same priority level at which we're currently + // rendering. We might want to restart this render. This should mirror + // the logic of whether or not a root suspends once it completes. + // TODO: If we're rendering sync either due to Sync, Batched or expired, + // we should probably never restart. + // If we're suspended with delay, or if it's a retry, we'll always suspend + // so we can always restart. + if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now$1() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { + // Restart from the root. + prepareFreshStack(root, NoLanes); + } else { + // Even though we can't restart right now, we might get an + // opportunity later. So we mark this render as having a ping. + workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); + } + } -------- + ensureRootIsScheduled(root, eventTime); + } + function retryTimedOutBoundary(boundaryFiber, retryLane) { + // The boundary fiber (a Suspense component or SuspenseList component) + // previously was rendered in its fallback state. One of the promises that + // suspended it has resolved, which means at least part of the tree was + // likely unblocked. Try rendering again, at a new lanes. + if (retryLane === NoLane) { + // TODO: Assign this to `suspenseState.retryLane`? to avoid + // unnecessary entanglement? + retryLane = requestRetryLane(boundaryFiber); + } // TODO: Special case idle priority? - (+10) - rp1o *-------->*rp1 - . . - . . - rp2o *-------->*rp2 + var eventTime = requestEventTime(); + var root = markUpdateLaneFromFiberToRoot(boundaryFiber, retryLane); - (+10) - po *-------->* p + if (root !== null) { + markRootUpdated(root, retryLane, eventTime); + ensureRootIsScheduled(root, eventTime); + } + } -------- + function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState; + var retryLane = NoLane; + if (suspenseState !== null) { + retryLane = suspenseState.retryLane; + } - (+10) - rp1o *-------->*rp1 - . . - . .(+30) - rp2o *---------------------------->*rp2 + retryTimedOutBoundary(boundaryFiber, retryLane); + } + function resolveRetryWakeable(boundaryFiber, wakeable) { + var retryLane = NoLane; // Default + var retryCache; - (+25) - po *----------------------->* p + { + switch (boundaryFiber.tag) { + case SuspenseComponent: + retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + if (suspenseState !== null) { + retryLane = suspenseState.retryLane; + } + break; -vim: set ts=4 sw=4 expandtab: -*****/ + case SuspenseListComponent: + retryCache = boundaryFiber.stateNode; + break; -/** - * Converts a string into a list of tokens. - */ + default: + throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.'); + } + } -/** - * Create a new token - * @param {string} char a single char - */ -function Token(char) { - this.char = char; - this.state = {}; - this.activeState = null; -} + if (retryCache !== null) { + // The wakeable resolved, so we no longer need to memoize, because it will + // never be thrown again. + retryCache.delete(wakeable); + } -/** - * Create a new context range - * @param {number} startIndex range start index - * @param {number} endOffset range end index offset - * @param {string} contextName owner context name - */ -function ContextRange(startIndex, endOffset, contextName) { - this.contextName = contextName; - this.startIndex = startIndex; - this.endOffset = endOffset; -} + retryTimedOutBoundary(boundaryFiber, retryLane); + } // Computes the next Just Noticeable Difference (JND) boundary. + // The theory is that a person can't tell the difference between small differences in time. + // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable + // difference in the experience. However, waiting for longer might mean that we can avoid + // showing an intermediate loading state. The longer we have already waited, the harder it + // is to tell small differences in time. Therefore, the longer we've already waited, + // the longer we can wait additionally. At some point we have to give up though. + // We pick a train model where the next boundary commits at a consistent schedule. + // These particular numbers are vague estimates. We expect to adjust them based on research. -/** - * Check context start and end - * @param {string} contextName a unique context name - * @param {function} checkStart a predicate function the indicates a context's start - * @param {function} checkEnd a predicate function the indicates a context's end - */ -function ContextChecker(contextName, checkStart, checkEnd) { - this.contextName = contextName; - this.openRange = null; - this.ranges = []; - this.checkStart = checkStart; - this.checkEnd = checkEnd; -} + function jnd(timeElapsed) { + return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960; + } -/** - * @typedef ContextParams - * @type Object - * @property {array} context context items - * @property {number} currentIndex current item index - */ + function checkForNestedUpdates() { + if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { + nestedUpdateCount = 0; + rootWithNestedUpdates = null; + throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.'); + } -/** - * Create a context params - * @param {array} context a list of items - * @param {number} currentIndex current item index - */ -function ContextParams(context, currentIndex) { - this.context = context; - this.index = currentIndex; - this.length = context.length; - this.current = context[currentIndex]; - this.backtrack = context.slice(0, currentIndex); - this.lookahead = context.slice(currentIndex + 1); -} + { + if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { + nestedPassiveUpdateCount = 0; -/** - * Create an event instance - * @param {string} eventId event unique id - */ -function Event(eventId) { - this.eventId = eventId; - this.subscribers = []; -} + error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.'); + } + } + } -/** - * Initialize a core events and auto subscribe required event handlers - * @param {any} events an object that enlists core events handlers - */ -function initializeCoreEvents(events) { - var this$1$1 = this; + function flushRenderPhaseStrictModeWarningsInDEV() { + { + ReactStrictModeWarnings.flushLegacyContextWarning(); - var coreEvents = [ - 'start', 'end', 'next', 'newToken', 'contextStart', - 'contextEnd', 'insertToken', 'removeToken', 'removeRange', - 'replaceToken', 'replaceRange', 'composeRUD', 'updateContextsRanges' - ]; + { + ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); + } + } + } - coreEvents.forEach(function (eventId) { - Object.defineProperty(this$1$1.events, eventId, { - value: new Event(eventId) - }); - }); + function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) { + { + // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects + // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level. + // Maybe not a big deal since this is DEV only behavior. + setCurrentFiber(fiber); + invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); - if (!!events) { - coreEvents.forEach(function (eventId) { - var event = events[eventId]; - if (typeof event === 'function') { - this$1$1.events[eventId].subscribe(event); - } - }); - } - var requiresContextUpdate = [ - 'insertToken', 'removeToken', 'removeRange', - 'replaceToken', 'replaceRange', 'composeRUD' - ]; - requiresContextUpdate.forEach(function (eventId) { - this$1$1.events[eventId].subscribe( - this$1$1.updateContextsRanges - ); - }); -} + if (hasPassiveEffects) { + invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); + } -/** - * Converts a string into a list of tokens - * @param {any} events tokenizer core events - */ -function Tokenizer(events) { - this.tokens = []; - this.registeredContexts = {}; - this.contextCheckers = []; - this.events = {}; - this.registeredModifiers = []; + invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); - initializeCoreEvents.call(this, events); -} + if (hasPassiveEffects) { + invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); + } -/** - * Sets the state of a token, usually called by a state modifier. - * @param {string} key state item key - * @param {any} value state item value - */ -Token.prototype.setState = function(key, value) { - this.state[key] = value; - this.activeState = { key: key, value: this.state[key] }; - return this.activeState; -}; + resetCurrentFiber(); + } + } -Token.prototype.getState = function (stateId) { - return this.state[stateId] || null; -}; + function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) { + { + // We don't need to re-check StrictEffectsMode here. + // This function is only called if that check has already passed. + var current = firstChild; + var subtreeRoot = null; -/** - * Checks if an index exists in the tokens list. - * @param {number} index token index - */ -Tokenizer.prototype.inboundIndex = function(index) { - return index >= 0 && index < this.tokens.length; -}; + while (current !== null) { + var primarySubtreeFlag = current.subtreeFlags & fiberFlags; -/** - * Compose and apply a list of operations (replace, update, delete) - * @param {array} RUDs replace, update and delete operations - * TODO: Perf. Optimization (lengthBefore === lengthAfter ? dispatch once) - */ -Tokenizer.prototype.composeRUD = function (RUDs) { - var this$1$1 = this; - - var silent = true; - var state = RUDs.map(function (RUD) { return ( - this$1$1[RUD[0]].apply(this$1$1, RUD.slice(1).concat(silent)) - ); }); - var hasFAILObject = function (obj) { return ( - typeof obj === 'object' && - obj.hasOwnProperty('FAIL') - ); }; - if (state.every(hasFAILObject)) { - return { - FAIL: "composeRUD: one or more operations hasn't completed successfully", - report: state.filter(hasFAILObject) - }; - } - this.dispatch('composeRUD', [state.filter(function (op) { return !hasFAILObject(op); })]); -}; + if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) { + current = current.child; + } else { + if ((current.flags & fiberFlags) !== NoFlags) { + invokeEffectFn(current); + } -/** - * Replace a range of tokens with a list of tokens - * @param {number} startIndex range start index - * @param {number} offset range offset - * @param {token} tokens a list of tokens to replace - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.replaceRange = function (startIndex, offset, tokens, silent) { - offset = offset !== null ? offset : this.tokens.length; - var isTokenType = tokens.every(function (token) { return token instanceof Token; }); - if (!isNaN(startIndex) && this.inboundIndex(startIndex) && isTokenType) { - var replaced = this.tokens.splice.apply( - this.tokens, [startIndex, offset].concat(tokens) - ); - if (!silent) { this.dispatch('replaceToken', [startIndex, offset, tokens]); } - return [replaced, tokens]; - } else { - return { FAIL: 'replaceRange: invalid tokens or startIndex.' }; - } -}; + if (current.sibling !== null) { + current = current.sibling; + } else { + current = subtreeRoot = current.return; + } + } + } + } + } -/** - * Replace a token with another token - * @param {number} index token index - * @param {token} token a token to replace - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.replaceToken = function (index, token, silent) { - if (!isNaN(index) && this.inboundIndex(index) && token instanceof Token) { - var replaced = this.tokens.splice(index, 1, token); - if (!silent) { this.dispatch('replaceToken', [index, token]); } - return [replaced[0], token]; - } else { - return { FAIL: 'replaceToken: invalid token or index.' }; - } -}; + var didWarnStateUpdateForNotYetMountedComponent = null; -/** - * Removes a range of tokens - * @param {number} startIndex range start index - * @param {number} offset range offset - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.removeRange = function(startIndex, offset, silent) { - offset = !isNaN(offset) ? offset : this.tokens.length; - var tokens = this.tokens.splice(startIndex, offset); - if (!silent) { this.dispatch('removeRange', [tokens, startIndex, offset]); } - return tokens; -}; + function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { + { + if ((executionContext & RenderContext) !== NoContext) { + // We let the other warning about render phase updates deal with this one. + return; + } -/** - * Remove a token at a certain index - * @param {number} index token index - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.removeToken = function(index, silent) { - if (!isNaN(index) && this.inboundIndex(index)) { - var token = this.tokens.splice(index, 1); - if (!silent) { this.dispatch('removeToken', [token, index]); } - return token; - } else { - return { FAIL: 'removeToken: invalid token index.' }; - } -}; + if (!(fiber.mode & ConcurrentMode)) { + return; + } -/** - * Insert a list of tokens at a certain index - * @param {array} tokens a list of tokens to insert - * @param {number} index insert the list of tokens at index - * @param {boolean} silent dispatch events and update context ranges - */ -Tokenizer.prototype.insertToken = function (tokens, index, silent) { - var tokenType = tokens.every( - function (token) { return token instanceof Token; } - ); - if (tokenType) { - this.tokens.splice.apply( - this.tokens, [index, 0].concat(tokens) - ); - if (!silent) { this.dispatch('insertToken', [tokens, index]); } - return tokens; - } else { - return { FAIL: 'insertToken: invalid token(s).' }; - } -}; + var tag = fiber.tag; -/** - * A state modifier that is called on 'newToken' event - * @param {string} modifierId state modifier id - * @param {function} condition a predicate function that returns true or false - * @param {function} modifier a function to update token state - */ -Tokenizer.prototype.registerModifier = function(modifierId, condition, modifier) { - this.events.newToken.subscribe(function(token, contextParams) { - var conditionParams = [token, contextParams]; - var canApplyModifier = ( - condition === null || - condition.apply(this, conditionParams) === true - ); - var modifierParams = [token, contextParams]; - if (canApplyModifier) { - var newStateValue = modifier.apply(this, modifierParams); - token.setState(modifierId, newStateValue); - } - }); - this.registeredModifiers.push(modifierId); -}; + if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) { + // Only warn for user-defined components, not internal ones like Suspense. + return; + } // We show the whole stack but dedupe on the top component's name because + // the problematic code almost always lies inside that component. -/** - * Subscribe a handler to an event - * @param {function} eventHandler an event handler function - */ -Event.prototype.subscribe = function (eventHandler) { - if (typeof eventHandler === 'function') { - return ((this.subscribers.push(eventHandler)) - 1); - } else { - return { FAIL: ("invalid '" + (this.eventId) + "' event handler")}; - } -}; -/** - * Unsubscribe an event handler - * @param {string} subsId subscription id - */ -Event.prototype.unsubscribe = function (subsId) { - this.subscribers.splice(subsId, 1); -}; + var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent'; -/** - * Sets context params current value index - * @param {number} index context params current value index - */ -ContextParams.prototype.setCurrentIndex = function(index) { - this.index = index; - this.current = this.context[index]; - this.backtrack = this.context.slice(0, index); - this.lookahead = this.context.slice(index + 1); -}; + if (didWarnStateUpdateForNotYetMountedComponent !== null) { + if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { + return; + } -/** - * Get an item at an offset from the current value - * example (current value is 3): - * 1 2 [3] 4 5 | items values - * -2 -1 0 1 2 | offset values - * @param {number} offset an offset from current value index - */ -ContextParams.prototype.get = function (offset) { - switch (true) { - case (offset === 0): - return this.current; - case (offset < 0 && Math.abs(offset) <= this.backtrack.length): - return this.backtrack.slice(offset)[0]; - case (offset > 0 && offset <= this.lookahead.length): - return this.lookahead[offset - 1]; - default: - return null; - } -}; + didWarnStateUpdateForNotYetMountedComponent.add(componentName); + } else { + didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]); + } -/** - * Converts a context range into a string value - * @param {contextRange} range a context range - */ -Tokenizer.prototype.rangeToText = function (range) { - if (range instanceof ContextRange) { - return ( - this.getRangeTokens(range) - .map(function (token) { return token.char; }).join('') - ); - } -}; + var previousFiber = current; -/** - * Converts all tokens into a string - */ -Tokenizer.prototype.getText = function () { - return this.tokens.map(function (token) { return token.char; }).join(''); -}; + try { + setCurrentFiber(fiber); -/** - * Get a context by name - * @param {string} contextName context name to get - */ -Tokenizer.prototype.getContext = function (contextName) { - var context = this.registeredContexts[contextName]; - return !!context ? context : null; -}; + error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.'); + } finally { + if (previousFiber) { + setCurrentFiber(fiber); + } else { + resetCurrentFiber(); + } + } + } + } -/** - * Subscribes a new event handler to an event - * @param {string} eventName event name to subscribe to - * @param {function} eventHandler a function to be invoked on event - */ -Tokenizer.prototype.on = function(eventName, eventHandler) { - var event = this.events[eventName]; - if (!!event) { - return event.subscribe(eventHandler); - } else { - return null; - } -}; + var beginWork$1; -/** - * Dispatches an event - * @param {string} eventName event name - * @param {any} args event handler arguments - */ -Tokenizer.prototype.dispatch = function(eventName, args) { - var this$1$1 = this; + { + var dummyFiber = null; - var event = this.events[eventName]; - if (event instanceof Event) { - event.subscribers.forEach(function (subscriber) { - subscriber.apply(this$1$1, args || []); - }); - } -}; + beginWork$1 = function (current, unitOfWork, lanes) { + // If a component throws an error, we replay it again in a synchronously + // dispatched event, so that the debugger will treat it as an uncaught + // error See ReactErrorUtils for more information. + // Before entering the begin phase, copy the work-in-progress onto a dummy + // fiber. If beginWork throws, we'll use this to reset the state. + var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); -/** - * Register a new context checker - * @param {string} contextName a unique context name - * @param {function} contextStartCheck a predicate function that returns true on context start - * @param {function} contextEndCheck a predicate function that returns true on context end - * TODO: call tokenize on registration to update context ranges with the new context. - */ -Tokenizer.prototype.registerContextChecker = function(contextName, contextStartCheck, contextEndCheck) { - if (!!this.getContext(contextName)) { return { - FAIL: - ("context name '" + contextName + "' is already registered.") - }; } - if (typeof contextStartCheck !== 'function') { return { - FAIL: - "missing context start check." - }; } - if (typeof contextEndCheck !== 'function') { return { - FAIL: - "missing context end check." - }; } - var contextCheckers = new ContextChecker( - contextName, contextStartCheck, contextEndCheck - ); - this.registeredContexts[contextName] = contextCheckers; - this.contextCheckers.push(contextCheckers); - return contextCheckers; -}; + try { + return beginWork(current, unitOfWork, lanes); + } catch (originalError) { + if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') { + // Don't replay promises. Treat everything else like an error. + throw originalError; + } // Keep this code in sync with handleError; any changes here must have + // corresponding changes there. -/** - * Gets a context range tokens - * @param {contextRange} range a context range - */ -Tokenizer.prototype.getRangeTokens = function(range) { - var endIndex = range.startIndex + range.endOffset; - return [].concat( - this.tokens - .slice(range.startIndex, endIndex) - ); -}; -/** - * Gets the ranges of a context - * @param {string} contextName context name - */ -Tokenizer.prototype.getContextRanges = function(contextName) { - var context = this.getContext(contextName); - if (!!context) { - return context.ranges; - } else { - return { FAIL: ("context checker '" + contextName + "' is not registered.") }; - } -}; + resetContextDependencies(); + resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the + // same fiber again. + // Unwind the failed stack frame -/** - * Resets context ranges to run context update - */ -Tokenizer.prototype.resetContextsRanges = function () { - var registeredContexts = this.registeredContexts; - for (var contextName in registeredContexts) { - if (registeredContexts.hasOwnProperty(contextName)) { - var context = registeredContexts[contextName]; - context.ranges = []; - } - } -}; + unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber. -/** - * Updates context ranges - */ -Tokenizer.prototype.updateContextsRanges = function () { - this.resetContextsRanges(); - var chars = this.tokens.map(function (token) { return token.char; }); - for (var i = 0; i < chars.length; i++) { - var contextParams = new ContextParams(chars, i); - this.runContextCheck(contextParams); - } - this.dispatch('updateContextsRanges', [this.registeredContexts]); -}; + assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); -/** - * Sets the end offset of an open range - * @param {number} offset range end offset - * @param {string} contextName context name - */ -Tokenizer.prototype.setEndOffset = function (offset, contextName) { - var startIndex = this.getContext(contextName).openRange.startIndex; - var range = new ContextRange(startIndex, offset, contextName); - var ranges = this.getContext(contextName).ranges; - range.rangeId = contextName + "." + (ranges.length); - ranges.push(range); - this.getContext(contextName).openRange = null; - return range; -}; + if ( unitOfWork.mode & ProfileMode) { + // Reset the profiler timer. + startProfilerTimer(unitOfWork); + } // Run beginWork again. -/** - * Runs a context check on the current context - * @param {contextParams} contextParams current context params - */ -Tokenizer.prototype.runContextCheck = function(contextParams) { - var this$1$1 = this; - - var index = contextParams.index; - this.contextCheckers.forEach(function (contextChecker) { - var contextName = contextChecker.contextName; - var openRange = this$1$1.getContext(contextName).openRange; - if (!openRange && contextChecker.checkStart(contextParams)) { - openRange = new ContextRange(index, null, contextName); - this$1$1.getContext(contextName).openRange = openRange; - this$1$1.dispatch('contextStart', [contextName, index]); - } - if (!!openRange && contextChecker.checkEnd(contextParams)) { - var offset = (index - openRange.startIndex) + 1; - var range = this$1$1.setEndOffset(offset, contextName); - this$1$1.dispatch('contextEnd', [contextName, range]); - } - }); -}; -/** - * Converts a text into a list of tokens - * @param {string} text a text to tokenize - */ -Tokenizer.prototype.tokenize = function (text) { - this.tokens = []; - this.resetContextsRanges(); - var chars = Array.from(text); - this.dispatch('start'); - for (var i = 0; i < chars.length; i++) { - var char = chars[i]; - var contextParams = new ContextParams(chars, i); - this.dispatch('next', [contextParams]); - this.runContextCheck(contextParams); - var token = new Token(char); - this.tokens.push(token); - this.dispatch('newToken', [token, contextParams]); - } - this.dispatch('end', [this.tokens]); - return this.tokens; -}; + invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes); -// ╭─┄┄┄────────────────────────┄─────────────────────────────────────────────╮ -// ┊ Character Class Assertions ┊ Checks if a char belongs to a certain class ┊ -// ╰─╾──────────────────────────┄─────────────────────────────────────────────╯ -// jscs:disable maximumLineLength -/** - * Check if a char is Arabic - * @param {string} c a single char - */ -function isArabicChar(c) { - return /[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c); -} + if (hasCaughtError()) { + var replayError = clearCaughtError(); -/** - * Check if a char is an isolated arabic char - * @param {string} c a single char - */ -function isIsolatedArabicChar(char) { - return /[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(char); -} + if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) { + // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. + originalError._suppressLogging = true; + } + } // We always throw the original error in case the second render pass is not idempotent. + // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. -/** - * Check if a char is an Arabic Tashkeel char - * @param {string} c a single char - */ -function isTashkeelArabicChar(char) { - return /[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(char); -} -/** - * Check if a char is Latin - * @param {string} c a single char - */ -function isLatinChar(c) { - return /[A-z]/.test(c); -} + throw originalError; + } + }; + } -/** - * Check if a char is whitespace char - * @param {string} c a single char - */ -function isWhiteSpace(c) { - return /\s/.test(c); -} + var didWarnAboutUpdateInRender = false; + var didWarnAboutUpdateInRenderForAnotherComponent; -/** - * Query a feature by some of it's properties to lookup a glyph substitution. - */ + { + didWarnAboutUpdateInRenderForAnotherComponent = new Set(); + } -/** - * Create feature query instance - * @param {Font} font opentype font instance - */ -function FeatureQuery(font) { - this.font = font; - this.features = {}; -} + function warnAboutRenderPhaseUpdatesInDEV(fiber) { + { + if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: + { + var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed. -/** - * @typedef SubstitutionAction - * @type Object - * @property {number} id substitution type - * @property {string} tag feature tag - * @property {any} substitution substitution value(s) - */ + var dedupeKey = renderingComponentName; -/** - * Create a substitution action instance - * @param {SubstitutionAction} action - */ -function SubstitutionAction(action) { - this.id = action.id; - this.tag = action.tag; - this.substitution = action.substitution; -} + if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { + didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); + var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown'; -/** - * Lookup a coverage table - * @param {number} glyphIndex glyph index - * @param {CoverageTable} coverage coverage table - */ -function lookupCoverage(glyphIndex, coverage) { - if (!glyphIndex) { return -1; } - switch (coverage.format) { - case 1: - return coverage.glyphs.indexOf(glyphIndex); - - case 2: - var ranges = coverage.ranges; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (glyphIndex >= range.start && glyphIndex <= range.end) { - var offset = glyphIndex - range.start; - return range.index + offset; - } - } - break; - default: - return -1; // not found - } - return -1; -} + error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName); + } -/** - * Handle a single substitution - format 1 - * @param {ContextParams} contextParams context params to lookup - */ -function singleSubstitutionFormat1(glyphIndex, subtable) { - var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); - if (substituteIndex === -1) { return null; } - return glyphIndex + subtable.deltaGlyphId; -} + break; + } -/** - * Handle a single substitution - format 2 - * @param {ContextParams} contextParams context params to lookup - */ -function singleSubstitutionFormat2(glyphIndex, subtable) { - var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); - if (substituteIndex === -1) { return null; } - return subtable.substitute[substituteIndex]; -} + case ClassComponent: + { + if (!didWarnAboutUpdateInRender) { + error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.'); -/** - * Lookup a list of coverage tables - * @param {any} coverageList a list of coverage tables - * @param {ContextParams} contextParams context params to lookup - */ -function lookupCoverageList(coverageList, contextParams) { - var lookupList = []; - for (var i = 0; i < coverageList.length; i++) { - var coverage = coverageList[i]; - var glyphIndex = contextParams.current; - glyphIndex = Array.isArray(glyphIndex) ? glyphIndex[0] : glyphIndex; - var lookupIndex = lookupCoverage(glyphIndex, coverage); - if (lookupIndex !== -1) { - lookupList.push(lookupIndex); - } - } - if (lookupList.length !== coverageList.length) { return -1; } - return lookupList; -} + didWarnAboutUpdateInRender = true; + } -/** - * Handle chaining context substitution - format 3 - * @param {ContextParams} contextParams context params to lookup - */ -function chainingSubstitutionFormat3(contextParams, subtable) { - var lookupsCount = ( - subtable.inputCoverage.length + - subtable.lookaheadCoverage.length + - subtable.backtrackCoverage.length - ); - if (contextParams.context.length < lookupsCount) { return []; } - // INPUT LOOKUP // - var inputLookups = lookupCoverageList( - subtable.inputCoverage, contextParams - ); - if (inputLookups === -1) { return []; } - // LOOKAHEAD LOOKUP // - var lookaheadOffset = subtable.inputCoverage.length - 1; - if (contextParams.lookahead.length < subtable.lookaheadCoverage.length) { return []; } - var lookaheadContext = contextParams.lookahead.slice(lookaheadOffset); - while (lookaheadContext.length && isTashkeelArabicChar(lookaheadContext[0].char)) { - lookaheadContext.shift(); - } - var lookaheadParams = new ContextParams(lookaheadContext, 0); - var lookaheadLookups = lookupCoverageList( - subtable.lookaheadCoverage, lookaheadParams - ); - // BACKTRACK LOOKUP // - var backtrackContext = [].concat(contextParams.backtrack); - backtrackContext.reverse(); - while (backtrackContext.length && isTashkeelArabicChar(backtrackContext[0].char)) { - backtrackContext.shift(); - } - if (backtrackContext.length < subtable.backtrackCoverage.length) { return []; } - var backtrackParams = new ContextParams(backtrackContext, 0); - var backtrackLookups = lookupCoverageList( - subtable.backtrackCoverage, backtrackParams - ); - var contextRulesMatch = ( - inputLookups.length === subtable.inputCoverage.length && - lookaheadLookups.length === subtable.lookaheadCoverage.length && - backtrackLookups.length === subtable.backtrackCoverage.length - ); - var substitutions = []; - if (contextRulesMatch) { - for (var i = 0; i < subtable.lookupRecords.length; i++) { - var lookupRecord = subtable.lookupRecords[i]; - var lookupListIndex = lookupRecord.lookupListIndex; - var lookupTable = this.getLookupByIndex(lookupListIndex); - for (var s = 0; s < lookupTable.subtables.length; s++) { - var subtable$1 = lookupTable.subtables[s]; - var lookup = this.getLookupMethod(lookupTable, subtable$1); - var substitutionType = this.getSubstitutionType(lookupTable, subtable$1); - if (substitutionType === '12') { - for (var n = 0; n < inputLookups.length; n++) { - var glyphIndex = contextParams.get(n); - var substitution = lookup(glyphIndex); - if (substitution) { substitutions.push(substitution); } - } - } - } - } - } - return substitutions; -} + break; + } + } + } + } + } -/** - * Handle ligature substitution - format 1 - * @param {ContextParams} contextParams context params to lookup - */ -function ligatureSubstitutionFormat1(contextParams, subtable) { - // COVERAGE LOOKUP // - var glyphIndex = contextParams.current; - var ligSetIndex = lookupCoverage(glyphIndex, subtable.coverage); - if (ligSetIndex === -1) { return null; } - // COMPONENTS LOOKUP - // (!) note, components are ordered in the written direction. - var ligature; - var ligatureSet = subtable.ligatureSets[ligSetIndex]; - for (var s = 0; s < ligatureSet.length; s++) { - ligature = ligatureSet[s]; - for (var l = 0; l < ligature.components.length; l++) { - var lookaheadItem = contextParams.lookahead[l]; - var component = ligature.components[l]; - if (lookaheadItem !== component) { break; } - if (l === ligature.components.length - 1) { return ligature; } - } - } - return null; -} + function restorePendingUpdaters(root, lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root.memoizedUpdaters; + memoizedUpdaters.forEach(function (schedulingFiber) { + addFiberToLanesMap(root, schedulingFiber, lanes); + }); // This function intentionally does not clear memoized updaters. + // Those may still be relevant to the current commit + // and a future one (e.g. Suspense). + } + } + } + var fakeActCallbackNode = {}; -/** - * Handle decomposition substitution - format 1 - * @param {number} glyphIndex glyph index - * @param {any} subtable subtable - */ -function decompositionSubstitutionFormat1(glyphIndex, subtable) { - var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); - if (substituteIndex === -1) { return null; } - return subtable.sequences[substituteIndex]; -} + function scheduleCallback$1(priorityLevel, callback) { + { + // If we're currently inside an `act` scope, bypass Scheduler and push to + // the `act` queue instead. + var actQueue = ReactCurrentActQueue$1.current; -/** - * Get default script features indexes - */ -FeatureQuery.prototype.getDefaultScriptFeaturesIndexes = function () { - var scripts = this.font.tables.gsub.scripts; - for (var s = 0; s < scripts.length; s++) { - var script = scripts[s]; - if (script.tag === 'DFLT') { return ( - script.script.defaultLangSys.featureIndexes - ); } - } - return []; -}; + if (actQueue !== null) { + actQueue.push(callback); + return fakeActCallbackNode; + } else { + return scheduleCallback(priorityLevel, callback); + } + } + } -/** - * Get feature indexes of a specific script - * @param {string} scriptTag script tag - */ -FeatureQuery.prototype.getScriptFeaturesIndexes = function(scriptTag) { - var tables = this.font.tables; - if (!tables.gsub) { return []; } - if (!scriptTag) { return this.getDefaultScriptFeaturesIndexes(); } - var scripts = this.font.tables.gsub.scripts; - for (var i = 0; i < scripts.length; i++) { - var script = scripts[i]; - if (script.tag === scriptTag && script.script.defaultLangSys) { - return script.script.defaultLangSys.featureIndexes; - } else { - var langSysRecords = script.langSysRecords; - if (!!langSysRecords) { - for (var j = 0; j < langSysRecords.length; j++) { - var langSysRecord = langSysRecords[j]; - if (langSysRecord.tag === scriptTag) { - var langSys = langSysRecord.langSys; - return langSys.featureIndexes; - } - } - } - } - } - return this.getDefaultScriptFeaturesIndexes(); -}; + function cancelCallback$1(callbackNode) { + if ( callbackNode === fakeActCallbackNode) { + return; + } // In production, always call Scheduler. This function will be stripped out. -/** - * Map a feature tag to a gsub feature - * @param {any} features gsub features - * @param {string} scriptTag script tag - */ -FeatureQuery.prototype.mapTagsToFeatures = function (features, scriptTag) { - var tags = {}; - for (var i = 0; i < features.length; i++) { - var tag = features[i].tag; - var feature = features[i].feature; - tags[tag] = feature; - } - this.features[scriptTag].tags = tags; -}; -/** - * Get features of a specific script - * @param {string} scriptTag script tag - */ -FeatureQuery.prototype.getScriptFeatures = function (scriptTag) { - var features = this.features[scriptTag]; - if (this.features.hasOwnProperty(scriptTag)) { return features; } - var featuresIndexes = this.getScriptFeaturesIndexes(scriptTag); - if (!featuresIndexes) { return null; } - var gsub = this.font.tables.gsub; - features = featuresIndexes.map(function (index) { return gsub.features[index]; }); - this.features[scriptTag] = features; - this.mapTagsToFeatures(features, scriptTag); - return features; -}; + return cancelCallback(callbackNode); + } -/** - * Get substitution type - * @param {any} lookupTable lookup table - * @param {any} subtable subtable - */ -FeatureQuery.prototype.getSubstitutionType = function(lookupTable, subtable) { - var lookupType = lookupTable.lookupType.toString(); - var substFormat = subtable.substFormat.toString(); - return lookupType + substFormat; -}; + function shouldForceFlushFallbacksInDEV() { + // Never force flush in production. This function should get stripped out. + return ReactCurrentActQueue$1.current !== null; + } -/** - * Get lookup method - * @param {any} lookupTable lookup table - * @param {any} subtable subtable - */ -FeatureQuery.prototype.getLookupMethod = function(lookupTable, subtable) { - var this$1$1 = this; - - var substitutionType = this.getSubstitutionType(lookupTable, subtable); - switch (substitutionType) { - case '11': - return function (glyphIndex) { return singleSubstitutionFormat1.apply( - this$1$1, [glyphIndex, subtable] - ); }; - case '12': - return function (glyphIndex) { return singleSubstitutionFormat2.apply( - this$1$1, [glyphIndex, subtable] - ); }; - case '63': - return function (contextParams) { return chainingSubstitutionFormat3.apply( - this$1$1, [contextParams, subtable] - ); }; - case '41': - return function (contextParams) { return ligatureSubstitutionFormat1.apply( - this$1$1, [contextParams, subtable] - ); }; - case '21': - return function (glyphIndex) { return decompositionSubstitutionFormat1.apply( - this$1$1, [glyphIndex, subtable] - ); }; - default: - throw new Error( - "lookupType: " + (lookupTable.lookupType) + " - " + - "substFormat: " + (subtable.substFormat) + " " + - "is not yet supported" - ); - } -}; + function warnIfUpdatesNotWrappedWithActDEV(fiber) { + { + if (fiber.mode & ConcurrentMode) { + if (!isConcurrentActEnvironment()) { + // Not in an act environment. No need to warn. + return; + } + } else { + // Legacy mode has additional cases where we suppress a warning. + if (!isLegacyActEnvironment()) { + // Not in an act environment. No need to warn. + return; + } -/** - * [ LOOKUP TYPES ] - * ------------------------------- - * Single 1; - * Multiple 2; - * Alternate 3; - * Ligature 4; - * Context 5; - * ChainingContext 6; - * ExtensionSubstitution 7; - * ReverseChainingContext 8; - * ------------------------------- - * - */ + if (executionContext !== NoContext) { + // Legacy mode doesn't warn if the update is batched, i.e. + // batchedUpdates or flushSync. + return; + } -/** - * @typedef FQuery - * @type Object - * @param {string} tag feature tag - * @param {string} script feature script - * @param {ContextParams} contextParams context params - */ + if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { + // For backwards compatibility with pre-hooks code, legacy mode only + // warns for updates that originate from a hook. + return; + } + } -/** - * Lookup a feature using a query parameters - * @param {FQuery} query feature query - */ -FeatureQuery.prototype.lookupFeature = function (query) { - var contextParams = query.contextParams; - var currentIndex = contextParams.index; - var feature = this.getFeature({ - tag: query.tag, script: query.script - }); - if (!feature) { return new Error( - "font '" + (this.font.names.fullName.en) + "' " + - "doesn't support feature '" + (query.tag) + "' " + - "for script '" + (query.script) + "'." - ); } - var lookups = this.getFeatureLookups(feature); - var substitutions = [].concat(contextParams.context); - for (var l = 0; l < lookups.length; l++) { - var lookupTable = lookups[l]; - var subtables = this.getLookupSubtables(lookupTable); - for (var s = 0; s < subtables.length; s++) { - var subtable = subtables[s]; - var substType = this.getSubstitutionType(lookupTable, subtable); - var lookup = this.getLookupMethod(lookupTable, subtable); - var substitution = (void 0); - switch (substType) { - case '11': - substitution = lookup(contextParams.current); - if (substitution) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 11, tag: query.tag, substitution: substitution - })); - } - break; - case '12': - substitution = lookup(contextParams.current); - if (substitution) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 12, tag: query.tag, substitution: substitution - })); - } - break; - case '63': - substitution = lookup(contextParams); - if (Array.isArray(substitution) && substitution.length) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 63, tag: query.tag, substitution: substitution - })); - } - break; - case '41': - substitution = lookup(contextParams); - if (substitution) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 41, tag: query.tag, substitution: substitution - })); - } - break; - case '21': - substitution = lookup(contextParams.current); - if (substitution) { - substitutions.splice(currentIndex, 1, new SubstitutionAction({ - id: 21, tag: query.tag, substitution: substitution - })); - } - break; - } - contextParams = new ContextParams(substitutions, currentIndex); - if (Array.isArray(substitution) && !substitution.length) { continue; } - substitution = null; - } - } - return substitutions.length ? substitutions : null; -}; + if (ReactCurrentActQueue$1.current === null) { + var previousFiber = current; -/** - * Checks if a font supports a specific features - * @param {FQuery} query feature query object - */ -FeatureQuery.prototype.supports = function (query) { - if (!query.script) { return false; } - this.getScriptFeatures(query.script); - var supportedScript = this.features.hasOwnProperty(query.script); - if (!query.tag) { return supportedScript; } - var supportedFeature = ( - this.features[query.script].some(function (feature) { return feature.tag === query.tag; }) - ); - return supportedScript && supportedFeature; -}; + try { + setCurrentFiber(fiber); -/** - * Get lookup table subtables - * @param {any} lookupTable lookup table - */ -FeatureQuery.prototype.getLookupSubtables = function (lookupTable) { - return lookupTable.subtables || null; -}; + error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber)); + } finally { + if (previousFiber) { + setCurrentFiber(fiber); + } else { + resetCurrentFiber(); + } + } + } + } + } -/** - * Get lookup table by index - * @param {number} index lookup table index - */ -FeatureQuery.prototype.getLookupByIndex = function (index) { - var lookups = this.font.tables.gsub.lookups; - return lookups[index] || null; -}; + function warnIfSuspenseResolutionNotWrappedWithActDEV(root) { + { + if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) { + error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + ' /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act'); + } + } + } -/** - * Get lookup tables for a feature - * @param {string} feature - */ -FeatureQuery.prototype.getFeatureLookups = function (feature) { - // TODO: memoize - return feature.lookupListIndexes.map(this.getLookupByIndex.bind(this)); -}; + /* eslint-disable react-internal/prod-error-codes */ + var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. -/** - * Query a feature by it's properties - * @param {any} query an object that describes the properties of a query - */ -FeatureQuery.prototype.getFeature = function getFeature(query) { - if (!this.font) { return { FAIL: "No font was found"}; } - if (!this.features.hasOwnProperty(query.script)) { - this.getScriptFeatures(query.script); - } - var scriptFeatures = this.features[query.script]; - if (!scriptFeatures) { return ( - { FAIL: ("No feature for script " + (query.script))} - ); } - if (!scriptFeatures.tags[query.tag]) { return null; } - return this.features[query.script].tags[query.tag]; -}; + var failedBoundaries = null; + var setRefreshHandler = function (handler) { + { + resolveFamily = handler; + } + }; + function resolveFunctionForHotReloading(type) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return type; + } -/** - * Arabic word context checkers - */ + var family = resolveFamily(type); -function arabicWordStartCheck(contextParams) { - var char = contextParams.current; - var prevChar = contextParams.get(-1); - return ( - // ? arabic first char - (prevChar === null && isArabicChar(char)) || - // ? arabic char preceded with a non arabic char - (!isArabicChar(prevChar) && isArabicChar(char)) - ); -} + if (family === undefined) { + return type; + } // Use the latest known implementation. -function arabicWordEndCheck(contextParams) { - var nextChar = contextParams.get(1); - return ( - // ? last arabic char - (nextChar === null) || - // ? next char is not arabic - (!isArabicChar(nextChar)) - ); -} -var arabicWordCheck = { - startCheck: arabicWordStartCheck, - endCheck: arabicWordEndCheck -}; + return family.current; + } + } + function resolveClassForHotReloading(type) { + // No implementation differences. + return resolveFunctionForHotReloading(type); + } + function resolveForwardRefForHotReloading(type) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return type; + } -/** - * Arabic sentence context checkers - */ + var family = resolveFamily(type); -function arabicSentenceStartCheck(contextParams) { - var char = contextParams.current; - var prevChar = contextParams.get(-1); - return ( - // ? an arabic char preceded with a non arabic char - (isArabicChar(char) || isTashkeelArabicChar(char)) && - !isArabicChar(prevChar) - ); -} + if (family === undefined) { + // Check if we're dealing with a real forwardRef. Don't want to crash early. + if (type !== null && type !== undefined && typeof type.render === 'function') { + // ForwardRef is special because its resolved .type is an object, + // but it's possible that we only have its inner render function in the map. + // If that inner render function is different, we'll build a new forwardRef type. + var currentRender = resolveFunctionForHotReloading(type.render); -function arabicSentenceEndCheck(contextParams) { - var nextChar = contextParams.get(1); - switch (true) { - case nextChar === null: - return true; - case (!isArabicChar(nextChar) && !isTashkeelArabicChar(nextChar)): - var nextIsWhitespace = isWhiteSpace(nextChar); - if (!nextIsWhitespace) { return true; } - if (nextIsWhitespace) { - var arabicCharAhead = false; - arabicCharAhead = ( - contextParams.lookahead.some( - function (c) { return isArabicChar(c) || isTashkeelArabicChar(c); } - ) - ); - if (!arabicCharAhead) { return true; } - } - break; - default: - return false; - } -} + if (type.render !== currentRender) { + var syntheticType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render: currentRender + }; -var arabicSentenceCheck = { - startCheck: arabicSentenceStartCheck, - endCheck: arabicSentenceEndCheck -}; + if (type.displayName !== undefined) { + syntheticType.displayName = type.displayName; + } -/** - * Apply single substitution format 1 - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function singleSubstitutionFormat1$1(action, tokens, index) { - tokens[index].setState(action.tag, action.substitution); -} + return syntheticType; + } + } -/** - * Apply single substitution format 2 - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function singleSubstitutionFormat2$1(action, tokens, index) { - tokens[index].setState(action.tag, action.substitution); -} + return type; + } // Use the latest known implementation. -/** - * Apply chaining context substitution format 3 - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function chainingSubstitutionFormat3$1(action, tokens, index) { - action.substitution.forEach(function (subst, offset) { - var token = tokens[index + offset]; - token.setState(action.tag, subst); - }); -} -/** - * Apply ligature substitution format 1 - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function ligatureSubstitutionFormat1$1(action, tokens, index) { - var token = tokens[index]; - token.setState(action.tag, action.substitution.ligGlyph); - var compsCount = action.substitution.components.length; - for (var i = 0; i < compsCount; i++) { - token = tokens[index + i + 1]; - token.setState('deleted', true); - } -} + return family.current; + } + } + function isCompatibleFamilyForHotReloading(fiber, element) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return false; + } -/** - * Supported substitutions - */ -var SUBSTITUTIONS = { - 11: singleSubstitutionFormat1$1, - 12: singleSubstitutionFormat2$1, - 63: chainingSubstitutionFormat3$1, - 41: ligatureSubstitutionFormat1$1 -}; + var prevType = fiber.elementType; + var nextType = element.type; // If we got here, we know types aren't === equal. -/** - * Apply substitutions to a list of tokens - * @param {Array} substitutions substitutions - * @param {any} tokens a list of tokens - * @param {number} index token index - */ -function applySubstitution(action, tokens, index) { - if (action instanceof SubstitutionAction && SUBSTITUTIONS[action.id]) { - SUBSTITUTIONS[action.id](action, tokens, index); - } -} + var needsCompareFamilies = false; + var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null; -/** - * Apply Arabic presentation forms to a range of tokens - */ + switch (fiber.tag) { + case ClassComponent: + { + if (typeof nextType === 'function') { + needsCompareFamilies = true; + } -/** - * Check if a char can be connected to it's preceding char - * @param {ContextParams} charContextParams context params of a char - */ -function willConnectPrev(charContextParams) { - var backtrack = [].concat(charContextParams.backtrack); - for (var i = backtrack.length - 1; i >= 0; i--) { - var prevChar = backtrack[i]; - var isolated = isIsolatedArabicChar(prevChar); - var tashkeel = isTashkeelArabicChar(prevChar); - if (!isolated && !tashkeel) { return true; } - if (isolated) { return false; } - } - return false; -} + break; + } -/** - * Check if a char can be connected to it's proceeding char - * @param {ContextParams} charContextParams context params of a char - */ -function willConnectNext(charContextParams) { - if (isIsolatedArabicChar(charContextParams.current)) { return false; } - for (var i = 0; i < charContextParams.lookahead.length; i++) { - var nextChar = charContextParams.lookahead[i]; - var tashkeel = isTashkeelArabicChar(nextChar); - if (!tashkeel) { return true; } - } - return false; -} + case FunctionComponent: + { + if (typeof nextType === 'function') { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + // We don't know the inner type yet. + // We're going to assume that the lazy inner type is stable, + // and so it is sufficient to avoid reconciling it away. + // We're not going to unwrap or actually use the new lazy type. + needsCompareFamilies = true; + } -/** - * Apply arabic presentation forms to a list of tokens - * @param {ContextRange} range a range of tokens - */ -function arabicPresentationForms(range) { - var this$1$1 = this; - - var script = 'arab'; - var tags = this.featuresTags[script]; - var tokens = this.tokenizer.getRangeTokens(range); - if (tokens.length === 1) { return; } - var contextParams = new ContextParams( - tokens.map(function (token) { return token.getState('glyphIndex'); } - ), 0); - var charContextParams = new ContextParams( - tokens.map(function (token) { return token.char; } - ), 0); - tokens.forEach(function (token, index) { - if (isTashkeelArabicChar(token.char)) { return; } - contextParams.setCurrentIndex(index); - charContextParams.setCurrentIndex(index); - var CONNECT = 0; // 2 bits 00 (10: can connect next) (01: can connect prev) - if (willConnectPrev(charContextParams)) { CONNECT |= 1; } - if (willConnectNext(charContextParams)) { CONNECT |= 2; } - var tag; - switch (CONNECT) { - case 1: (tag = 'fina'); break; - case 2: (tag = 'init'); break; - case 3: (tag = 'medi'); break; - } - if (tags.indexOf(tag) === -1) { return; } - var substitutions = this$1$1.query.lookupFeature({ - tag: tag, script: script, contextParams: contextParams - }); - if (substitutions instanceof Error) { return console.info(substitutions.message); } - substitutions.forEach(function (action, index) { - if (action instanceof SubstitutionAction) { - applySubstitution(action, tokens, index); - contextParams.context[index] = action.substitution; - } - }); - }); -} + break; + } -/** - * Apply Arabic required ligatures feature to a range of tokens - */ + case ForwardRef: + { + if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } -/** - * Update context params - * @param {any} tokens a list of tokens - * @param {number} index current item index - */ -function getContextParams(tokens, index) { - var context = tokens.map(function (token) { return token.activeState.value; }); - return new ContextParams(context, index || 0); -} + break; + } -/** - * Apply Arabic required ligatures to a context range - * @param {ContextRange} range a range of tokens - */ -function arabicRequiredLigatures(range) { - var this$1$1 = this; - - var script = 'arab'; - var tokens = this.tokenizer.getRangeTokens(range); - var contextParams = getContextParams(tokens); - contextParams.context.forEach(function (glyphIndex, index) { - contextParams.setCurrentIndex(index); - var substitutions = this$1$1.query.lookupFeature({ - tag: 'rlig', script: script, contextParams: contextParams - }); - if (substitutions.length) { - substitutions.forEach( - function (action) { return applySubstitution(action, tokens, index); } - ); - contextParams = getContextParams(tokens); - } - }); -} + case MemoComponent: + case SimpleMemoComponent: + { + if ($$typeofNextType === REACT_MEMO_TYPE) { + // TODO: if it was but can no longer be simple, + // we shouldn't set this. + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } -/** - * Latin word context checkers - */ + break; + } -function latinWordStartCheck(contextParams) { - var char = contextParams.current; - var prevChar = contextParams.get(-1); - return ( - // ? latin first char - (prevChar === null && isLatinChar(char)) || - // ? latin char preceded with a non latin char - (!isLatinChar(prevChar) && isLatinChar(char)) - ); -} + default: + return false; + } // Check if both types have a family and it's the same one. -function latinWordEndCheck(contextParams) { - var nextChar = contextParams.get(1); - return ( - // ? last latin char - (nextChar === null) || - // ? next char is not latin - (!isLatinChar(nextChar)) - ); -} -var latinWordCheck = { - startCheck: latinWordStartCheck, - endCheck: latinWordEndCheck -}; + if (needsCompareFamilies) { + // Note: memo() and forwardRef() we'll compare outer rather than inner type. + // This means both of them need to be registered to preserve state. + // If we unwrapped and compared the inner types for wrappers instead, + // then we would risk falsely saying two separate memo(Foo) + // calls are equivalent because they wrap the same Foo function. + var prevFamily = resolveFamily(prevType); -/** - * Apply Latin ligature feature to a range of tokens - */ + if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { + return true; + } + } -/** - * Update context params - * @param {any} tokens a list of tokens - * @param {number} index current item index - */ -function getContextParams$1(tokens, index) { - var context = tokens.map(function (token) { return token.activeState.value; }); - return new ContextParams(context, index || 0); -} + return false; + } + } + function markFailedErrorBoundaryForHotReloading(fiber) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return; + } -/** - * Apply Arabic required ligatures to a context range - * @param {ContextRange} range a range of tokens - */ -function latinLigature(range) { - var this$1$1 = this; - - var script = 'latn'; - var tokens = this.tokenizer.getRangeTokens(range); - var contextParams = getContextParams$1(tokens); - contextParams.context.forEach(function (glyphIndex, index) { - contextParams.setCurrentIndex(index); - var substitutions = this$1$1.query.lookupFeature({ - tag: 'liga', script: script, contextParams: contextParams - }); - if (substitutions.length) { - substitutions.forEach( - function (action) { return applySubstitution(action, tokens, index); } - ); - contextParams = getContextParams$1(tokens); - } - }); -} + if (typeof WeakSet !== 'function') { + return; + } -/** - * Infer bidirectional properties for a given text and apply - * the corresponding layout rules. - */ + if (failedBoundaries === null) { + failedBoundaries = new WeakSet(); + } -/** - * Create Bidi. features - * @param {string} baseDir text base direction. value either 'ltr' or 'rtl' - */ -function Bidi(baseDir) { - this.baseDir = baseDir || 'ltr'; - this.tokenizer = new Tokenizer(); - this.featuresTags = {}; -} + failedBoundaries.add(fiber); + } + } + var scheduleRefresh = function (root, update) { + { + if (resolveFamily === null) { + // Hot reloading is disabled. + return; + } -/** - * Sets Bidi text - * @param {string} text a text input - */ -Bidi.prototype.setText = function (text) { - this.text = text; -}; + var staleFamilies = update.staleFamilies, + updatedFamilies = update.updatedFamilies; + flushPassiveEffects(); + flushSync(function () { + scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies); + }); + } + }; + var scheduleRoot = function (root, element) { + { + if (root.context !== emptyContextObject) { + // Super edge case: root has a legacy _renderSubtree context + // but we don't know the parentComponent so we can't pass it. + // Just ignore. We'll delete this with _renderSubtree code path later. + return; + } -/** - * Store essential context checks: - * arabic word check for applying gsub features - * arabic sentence check for adjusting arabic layout - */ -Bidi.prototype.contextChecks = ({ - latinWordCheck: latinWordCheck, - arabicWordCheck: arabicWordCheck, - arabicSentenceCheck: arabicSentenceCheck -}); + flushPassiveEffects(); + flushSync(function () { + updateContainer(element, root, null, null); + }); + } + }; -/** - * Register arabic word check - */ -function registerContextChecker(checkId) { - var check = this.contextChecks[(checkId + "Check")]; - return this.tokenizer.registerContextChecker( - checkId, check.startCheck, check.endCheck - ); -} + function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { + { + var alternate = fiber.alternate, + child = fiber.child, + sibling = fiber.sibling, + tag = fiber.tag, + type = fiber.type; + var candidateType = null; -/** - * Perform pre tokenization procedure then - * tokenize text input - */ -function tokenizeText() { - registerContextChecker.call(this, 'latinWord'); - registerContextChecker.call(this, 'arabicWord'); - registerContextChecker.call(this, 'arabicSentence'); - return this.tokenizer.tokenize(this.text); -} + switch (tag) { + case FunctionComponent: + case SimpleMemoComponent: + case ClassComponent: + candidateType = type; + break; -/** - * Reverse arabic sentence layout - * TODO: check base dir before applying adjustments - priority low - */ -function reverseArabicSentences() { - var this$1$1 = this; - - var ranges = this.tokenizer.getContextRanges('arabicSentence'); - ranges.forEach(function (range) { - var rangeTokens = this$1$1.tokenizer.getRangeTokens(range); - this$1$1.tokenizer.replaceRange( - range.startIndex, - range.endOffset, - rangeTokens.reverse() - ); - }); -} + case ForwardRef: + candidateType = type.render; + break; + } -/** - * Register supported features tags - * @param {script} script script tag - * @param {Array} tags features tags list - */ -Bidi.prototype.registerFeatures = function (script, tags) { - var this$1$1 = this; + if (resolveFamily === null) { + throw new Error('Expected resolveFamily to be set during hot reload.'); + } - var supportedTags = tags.filter( - function (tag) { return this$1$1.query.supports({script: script, tag: tag}); } - ); - if (!this.featuresTags.hasOwnProperty(script)) { - this.featuresTags[script] = supportedTags; - } else { - this.featuresTags[script] = - this.featuresTags[script].concat(supportedTags); - } -}; + var needsRender = false; + var needsRemount = false; -/** - * Apply GSUB features - * @param {Array} tagsList a list of features tags - * @param {string} script a script tag - * @param {Font} font opentype font instance - */ -Bidi.prototype.applyFeatures = function (font, features) { - if (!font) { throw new Error( - 'No valid font was provided to apply features' - ); } - if (!this.query) { this.query = new FeatureQuery(font); } - for (var f = 0; f < features.length; f++) { - var feature = features[f]; - if (!this.query.supports({script: feature.script})) { continue; } - this.registerFeatures(feature.script, feature.tags); - } -}; + if (candidateType !== null) { + var family = resolveFamily(candidateType); -/** - * Register a state modifier - * @param {string} modifierId state modifier id - * @param {function} condition a predicate function that returns true or false - * @param {function} modifier a modifier function to set token state - */ -Bidi.prototype.registerModifier = function (modifierId, condition, modifier) { - this.tokenizer.registerModifier(modifierId, condition, modifier); -}; + if (family !== undefined) { + if (staleFamilies.has(family)) { + needsRemount = true; + } else if (updatedFamilies.has(family)) { + if (tag === ClassComponent) { + needsRemount = true; + } else { + needsRender = true; + } + } + } + } -/** - * Check if 'glyphIndex' is registered - */ -function checkGlyphIndexStatus() { - if (this.tokenizer.registeredModifiers.indexOf('glyphIndex') === -1) { - throw new Error( - 'glyphIndex modifier is required to apply ' + - 'arabic presentation features.' - ); - } -} + if (failedBoundaries !== null) { + if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) { + needsRemount = true; + } + } -/** - * Apply arabic presentation forms features - */ -function applyArabicPresentationForms() { - var this$1$1 = this; - - var script = 'arab'; - if (!this.featuresTags.hasOwnProperty(script)) { return; } - checkGlyphIndexStatus.call(this); - var ranges = this.tokenizer.getContextRanges('arabicWord'); - ranges.forEach(function (range) { - arabicPresentationForms.call(this$1$1, range); - }); -} + if (needsRemount) { + fiber._debugNeedsRemount = true; + } -/** - * Apply required arabic ligatures - */ -function applyArabicRequireLigatures() { - var this$1$1 = this; - - var script = 'arab'; - if (!this.featuresTags.hasOwnProperty(script)) { return; } - var tags = this.featuresTags[script]; - if (tags.indexOf('rlig') === -1) { return; } - checkGlyphIndexStatus.call(this); - var ranges = this.tokenizer.getContextRanges('arabicWord'); - ranges.forEach(function (range) { - arabicRequiredLigatures.call(this$1$1, range); - }); -} + if (needsRemount || needsRender) { + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } -/** - * Apply required arabic ligatures - */ -function applyLatinLigatures() { - var this$1$1 = this; - - var script = 'latn'; - if (!this.featuresTags.hasOwnProperty(script)) { return; } - var tags = this.featuresTags[script]; - if (tags.indexOf('liga') === -1) { return; } - checkGlyphIndexStatus.call(this); - var ranges = this.tokenizer.getContextRanges('latinWord'); - ranges.forEach(function (range) { - latinLigature.call(this$1$1, range); - }); -} + if (child !== null && !needsRemount) { + scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); + } -/** - * Check if a context is registered - * @param {string} contextId context id - */ -Bidi.prototype.checkContextReady = function (contextId) { - return !!this.tokenizer.getContext(contextId); -}; + if (sibling !== null) { + scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); + } + } + } -/** - * Apply features to registered contexts - */ -Bidi.prototype.applyFeaturesToContexts = function () { - if (this.checkContextReady('arabicWord')) { - applyArabicPresentationForms.call(this); - applyArabicRequireLigatures.call(this); - } - if (this.checkContextReady('latinWord')) { - applyLatinLigatures.call(this); - } - if (this.checkContextReady('arabicSentence')) { - reverseArabicSentences.call(this); - } -}; + var findHostInstancesForRefresh = function (root, families) { + { + var hostInstances = new Set(); + var types = new Set(families.map(function (family) { + return family.current; + })); + findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances); + return hostInstances; + } + }; -/** - * process text input - * @param {string} text an input text - */ -Bidi.prototype.processText = function(text) { - if (!this.text || this.text !== text) { - this.setText(text); - tokenizeText.call(this); - this.applyFeaturesToContexts(); - } -}; + function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { + { + var child = fiber.child, + sibling = fiber.sibling, + tag = fiber.tag, + type = fiber.type; + var candidateType = null; -/** - * Process a string of text to identify and adjust - * bidirectional text entities. - * @param {string} text input text - */ -Bidi.prototype.getBidiText = function (text) { - this.processText(text); - return this.tokenizer.getText(); -}; + switch (tag) { + case FunctionComponent: + case SimpleMemoComponent: + case ClassComponent: + candidateType = type; + break; -/** - * Get the current state index of each token - * @param {text} text an input text - */ -Bidi.prototype.getTextGlyphs = function (text) { - this.processText(text); - var indexes = []; - for (var i = 0; i < this.tokenizer.tokens.length; i++) { - var token = this.tokenizer.tokens[i]; - if (token.state.deleted) { continue; } - var index = token.activeState.value; - indexes.push(Array.isArray(index) ? index[0] : index); - } - return indexes; -}; + case ForwardRef: + candidateType = type.render; + break; + } -// The Font object + var didMatch = false; -/** - * @typedef FontOptions - * @type Object - * @property {Boolean} empty - whether to create a new empty font - * @property {string} familyName - * @property {string} styleName - * @property {string=} fullName - * @property {string=} postScriptName - * @property {string=} designer - * @property {string=} designerURL - * @property {string=} manufacturer - * @property {string=} manufacturerURL - * @property {string=} license - * @property {string=} licenseURL - * @property {string=} version - * @property {string=} description - * @property {string=} copyright - * @property {string=} trademark - * @property {Number} unitsPerEm - * @property {Number} ascender - * @property {Number} descender - * @property {Number} createdTimestamp - * @property {string=} weightClass - * @property {string=} widthClass - * @property {string=} fsSelection - */ + if (candidateType !== null) { + if (types.has(candidateType)) { + didMatch = true; + } + } -/** - * A Font represents a loaded OpenType font file. - * It contains a set of glyphs and methods to draw text on a drawing context, - * or to get a path representing the text. - * @exports opentype.Font - * @class - * @param {FontOptions} - * @constructor - */ -function Font(options) { - options = options || {}; - options.tables = options.tables || {}; - - if (!options.empty) { - // Check that we've provided the minimum set of names. - checkArgument(options.familyName, 'When creating a new Font object, familyName is required.'); - checkArgument(options.styleName, 'When creating a new Font object, styleName is required.'); - checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.'); - checkArgument(options.ascender, 'When creating a new Font object, ascender is required.'); - checkArgument(options.descender <= 0, 'When creating a new Font object, negative descender value is required.'); - - // OS X will complain if the names are empty, so we put a single space everywhere by default. - this.names = { - fontFamily: {en: options.familyName || ' '}, - fontSubfamily: {en: options.styleName || ' '}, - fullName: {en: options.fullName || options.familyName + ' ' + options.styleName}, - // postScriptName may not contain any whitespace - postScriptName: {en: options.postScriptName || (options.familyName + options.styleName).replace(/\s/g, '')}, - designer: {en: options.designer || ' '}, - designerURL: {en: options.designerURL || ' '}, - manufacturer: {en: options.manufacturer || ' '}, - manufacturerURL: {en: options.manufacturerURL || ' '}, - license: {en: options.license || ' '}, - licenseURL: {en: options.licenseURL || ' '}, - version: {en: options.version || 'Version 0.1'}, - description: {en: options.description || ' '}, - copyright: {en: options.copyright || ' '}, - trademark: {en: options.trademark || ' '} - }; - this.unitsPerEm = options.unitsPerEm || 1000; - this.ascender = options.ascender; - this.descender = options.descender; - this.createdTimestamp = options.createdTimestamp; - this.tables = Object.assign(options.tables, { - os2: Object.assign({ - usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, - usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, - fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR, - }, options.tables.os2) - }); - } + if (didMatch) { + // We have a match. This only drills down to the closest host components. + // There's no need to search deeper because for the purpose of giving + // visual feedback, "flashing" outermost parent rectangles is sufficient. + findHostInstancesForFiberShallowly(fiber, hostInstances); + } else { + // If there's no match, maybe there will be one further down in the child tree. + if (child !== null) { + findHostInstancesForMatchingFibersRecursively(child, types, hostInstances); + } + } - this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported. - this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); - this.encoding = new DefaultEncoding(this); - this.position = new Position(this); - this.substitution = new Substitution(this); - this.tables = this.tables || {}; - - // needed for low memory mode only. - this._push = null; - this._hmtxTableData = {}; - - Object.defineProperty(this, 'hinting', { - get: function() { - if (this._hinting) { return this._hinting; } - if (this.outlinesFormat === 'truetype') { - return (this._hinting = new Hinting(this)); - } - } - }); -} + if (sibling !== null) { + findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); + } + } + } -/** - * Check if the font has a glyph for the given character. - * @param {string} - * @return {Boolean} - */ -Font.prototype.hasChar = function(c) { - return this.encoding.charToGlyphIndex(c) !== null; -}; + function findHostInstancesForFiberShallowly(fiber, hostInstances) { + { + var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances); -/** - * Convert the given character to a single glyph index. - * Note that this function assumes that there is a one-to-one mapping between - * the given character and a glyph; for complex scripts this might not be the case. - * @param {string} - * @return {Number} - */ -Font.prototype.charToGlyphIndex = function(s) { - return this.encoding.charToGlyphIndex(s); -}; + if (foundHostInstances) { + return; + } // If we didn't find any host children, fallback to closest host parent. -/** - * Convert the given character to a single Glyph object. - * Note that this function assumes that there is a one-to-one mapping between - * the given character and a glyph; for complex scripts this might not be the case. - * @param {string} - * @return {opentype.Glyph} - */ -Font.prototype.charToGlyph = function(c) { - var glyphIndex = this.charToGlyphIndex(c); - var glyph = this.glyphs.get(glyphIndex); - if (!glyph) { - // .notdef - glyph = this.glyphs.get(0); - } - return glyph; -}; + var node = fiber; -/** - * Update features - * @param {any} options features options - */ -Font.prototype.updateFeatures = function (options) { - // TODO: update all features options not only 'latn'. - return this.defaultRenderOptions.features.map(function (feature) { - if (feature.script === 'latn') { - return { - script: 'latn', - tags: feature.tags.filter(function (tag) { return options[tag]; }) - }; - } else { - return feature; - } - }); -}; + while (true) { + switch (node.tag) { + case HostComponent: + hostInstances.add(node.stateNode); + return; -/** - * Convert the given text to a list of Glyph objects. - * Note that there is no strict one-to-one mapping between characters and - * glyphs, so the list of returned glyphs can be larger or smaller than the - * length of the given string. - * @param {string} - * @param {GlyphRenderOptions} [options] - * @return {opentype.Glyph[]} - */ -Font.prototype.stringToGlyphs = function(s, options) { - var this$1$1 = this; + case HostPortal: + hostInstances.add(node.stateNode.containerInfo); + return; + case HostRoot: + hostInstances.add(node.stateNode.containerInfo); + return; + } - var bidi = new Bidi(); + if (node.return === null) { + throw new Error('Expected to reach root first.'); + } - // Create and register 'glyphIndex' state modifier - var charToGlyphIndexMod = function (token) { return this$1$1.charToGlyphIndex(token.char); }; - bidi.registerModifier('glyphIndex', null, charToGlyphIndexMod); + node = node.return; + } + } + } - // roll-back to default features - var features = options ? - this.updateFeatures(options.features) : - this.defaultRenderOptions.features; + function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { + { + var node = fiber; + var foundHostInstances = false; - bidi.applyFeatures(this, features); + while (true) { + if (node.tag === HostComponent) { + // We got a match. + foundHostInstances = true; + hostInstances.add(node.stateNode); // There may still be more, so keep searching. + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } - var indexes = bidi.getTextGlyphs(s); + if (node === fiber) { + return foundHostInstances; + } - var length = indexes.length; + while (node.sibling === null) { + if (node.return === null || node.return === fiber) { + return foundHostInstances; + } - // convert glyph indexes to glyph objects - var glyphs = new Array(length); - var notdef = this.glyphs.get(0); - for (var i = 0; i < length; i += 1) { - glyphs[i] = this.glyphs.get(indexes[i]) || notdef; - } - return glyphs; -}; + node = node.return; + } -/** - * @param {string} - * @return {Number} - */ -Font.prototype.nameToGlyphIndex = function(name) { - return this.glyphNames.nameToGlyphIndex(name); -}; + node.sibling.return = node.return; + node = node.sibling; + } + } -/** - * @param {string} - * @return {opentype.Glyph} - */ -Font.prototype.nameToGlyph = function(name) { - var glyphIndex = this.nameToGlyphIndex(name); - var glyph = this.glyphs.get(glyphIndex); - if (!glyph) { - // .notdef - glyph = this.glyphs.get(0); - } + return false; + } - return glyph; -}; + var hasBadMapPolyfill; -/** - * @param {Number} - * @return {String} - */ -Font.prototype.glyphIndexToName = function(gid) { - if (!this.glyphNames.glyphIndexToName) { - return ''; - } + { + hasBadMapPolyfill = false; - return this.glyphNames.glyphIndexToName(gid); -}; + try { + var nonExtensibleObject = Object.preventExtensions({}); + /* eslint-disable no-new */ -/** - * Retrieve the value of the kerning pair between the left glyph (or its index) - * and the right glyph (or its index). If no kerning pair is found, return 0. - * The kerning value gets added to the advance width when calculating the spacing - * between glyphs. - * For GPOS kerning, this method uses the default script and language, which covers - * most use cases. To have greater control, use font.position.getKerningValue . - * @param {opentype.Glyph} leftGlyph - * @param {opentype.Glyph} rightGlyph - * @return {Number} - */ -Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { - leftGlyph = leftGlyph.index || leftGlyph; - rightGlyph = rightGlyph.index || rightGlyph; - var gposKerning = this.position.defaultKerningTables; - if (gposKerning) { - return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph); - } - // "kern" table - return this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0; -}; + new Map([[nonExtensibleObject, null]]); + new Set([nonExtensibleObject]); + /* eslint-enable no-new */ + } catch (e) { + // TODO: Consider warning about bad polyfills + hasBadMapPolyfill = true; + } + } -/** - * @typedef GlyphRenderOptions - * @type Object - * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used. - * See https://www.microsoft.com/typography/otspec/scripttags.htm - * @property {string} [language='dflt'] - language system used to determine which features to apply. - * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx - * @property {boolean} [kerning=true] - whether to include kerning values - * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system. - * See https://www.microsoft.com/typography/otspec/featuretags.htm - */ -Font.prototype.defaultRenderOptions = { - kerning: true, - features: [ - /** - * these 4 features are required to render Arabic text properly - * and shouldn't be turned off when rendering arabic text. - */ - { script: 'arab', tags: ['init', 'medi', 'fina', 'rlig'] }, - { script: 'latn', tags: ['liga', 'rlig'] } - ] -}; + function FiberNode(tag, pendingProps, key, mode) { + // Instance + this.tag = tag; + this.key = key; + this.elementType = null; + this.type = null; + this.stateNode = null; // Fiber -/** - * Helper function that invokes the given callback for each glyph in the given text. - * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text - * @param {string} text - The text to apply. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - * @param {Function} callback - */ -Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) { - x = x !== undefined ? x : 0; - y = y !== undefined ? y : 0; - fontSize = fontSize !== undefined ? fontSize : 72; - options = Object.assign({}, this.defaultRenderOptions, options); - var fontScale = 1 / this.unitsPerEm * fontSize; - var glyphs = this.stringToGlyphs(text, options); - var kerningLookups; - if (options.kerning) { - var script = options.script || this.position.getDefaultScriptName(); - kerningLookups = this.position.getKerningTables(script, options.language); - } - for (var i = 0; i < glyphs.length; i += 1) { - var glyph = glyphs[i]; - callback.call(this, glyph, x, y, fontSize, options); - if (glyph.advanceWidth) { - x += glyph.advanceWidth * fontScale; - } + this.return = null; + this.child = null; + this.sibling = null; + this.index = 0; + this.ref = null; + this.pendingProps = pendingProps; + this.memoizedProps = null; + this.updateQueue = null; + this.memoizedState = null; + this.dependencies = null; + this.mode = mode; // Effects - if (options.kerning && i < glyphs.length - 1) { - // We should apply position adjustment lookups in a more generic way. - // Here we only use the xAdvance value. - var kerningValue = kerningLookups ? - this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) : - this.getKerningValue(glyph, glyphs[i + 1]); - x += kerningValue * fontScale; - } + this.flags = NoFlags; + this.subtreeFlags = NoFlags; + this.deletions = null; + this.lanes = NoLanes; + this.childLanes = NoLanes; + this.alternate = null; - if (options.letterSpacing) { - x += options.letterSpacing * fontSize; - } else if (options.tracking) { - x += (options.tracking / 1000) * fontSize; - } - } - return x; -}; + { + // Note: The following is done to avoid a v8 performance cliff. + // + // Initializing the fields below to smis and later updating them with + // double values will cause Fibers to end up having separate shapes. + // This behavior/bug has something to do with Object.preventExtension(). + // Fortunately this only impacts DEV builds. + // Unfortunately it makes React unusably slow for some applications. + // To work around this, initialize the fields below with doubles. + // + // Learn more about this here: + // https://github.com/facebook/react/issues/14365 + // https://bugs.chromium.org/p/v8/issues/detail?id=8538 + this.actualDuration = Number.NaN; + this.actualStartTime = Number.NaN; + this.selfBaseDuration = Number.NaN; + this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. + // This won't trigger the performance cliff mentioned above, + // and it simplifies other profiler code (including DevTools). -/** - * Create a Path object that represents the given text. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - * @return {opentype.Path} - */ -Font.prototype.getPath = function(text, x, y, fontSize, options) { - var fullPath = new Path(); - this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { - var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); - fullPath.extend(glyphPath); - }); - return fullPath; -}; + this.actualDuration = 0; + this.actualStartTime = -1; + this.selfBaseDuration = 0; + this.treeBaseDuration = 0; + } -/** - * Create an array of Path objects that represent the glyphs of a given text. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - * @return {opentype.Path[]} - */ -Font.prototype.getPaths = function(text, x, y, fontSize, options) { - var glyphPaths = []; - this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { - var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); - glyphPaths.push(glyphPath); - }); + { + // This isn't directly used but is handy for debugging internals: + this._debugSource = null; + this._debugOwner = null; + this._debugNeedsRemount = false; + this._debugHookTypes = null; - return glyphPaths; -}; + if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { + Object.preventExtensions(this); + } + } + } // This is a constructor function, rather than a POJO constructor, still + // please ensure we do the following: + // 1) Nobody should add any instance methods on this. Instance methods can be + // more difficult to predict when they get optimized and they are almost + // never inlined properly in static compilers. + // 2) Nobody should rely on `instanceof Fiber` for type testing. We should + // always know when it is a fiber. + // 3) We might want to experiment with using numeric keys since they are easier + // to optimize in a non-JIT environment. + // 4) We can easily go from a constructor to a createFiber object literal if that + // is faster. + // 5) It should be easy to port this to a C struct and keep a C implementation + // compatible. -/** - * Returns the advance width of a text. - * - * This is something different than Path.getBoundingBox() as for example a - * suffixed whitespace increases the advanceWidth but not the bounding box - * or an overhanging letter like a calligraphic 'f' might have a quite larger - * bounding box than its advance width. - * - * This corresponds to canvas2dContext.measureText(text).width - * - * @param {string} text - The text to create. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - * @return advance width - */ -Font.prototype.getAdvanceWidth = function(text, fontSize, options) { - return this.forEachGlyph(text, 0, 0, fontSize, options, function() {}); -}; -/** - * Draw the text on the given drawing context. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - */ -Font.prototype.draw = function(ctx, text, x, y, fontSize, options) { - this.getPath(text, x, y, fontSize, options).draw(ctx); -}; + var createFiber = function (tag, pendingProps, key, mode) { + // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors + return new FiberNode(tag, pendingProps, key, mode); + }; -/** - * Draw the points of all glyphs in the text. - * On-curve points will be drawn in blue, off-curve points will be drawn in red. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - */ -Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) { - this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { - glyph.drawPoints(ctx, gX, gY, gFontSize); - }); -}; + function shouldConstruct$1(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } -/** - * Draw lines indicating important font measurements for all glyphs in the text. - * Black lines indicate the origin of the coordinate system (point 0,0). - * Blue lines indicate the glyph bounding box. - * Green line indicates the advance width of the glyph. - * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. - * @param {string} text - The text to create. - * @param {number} [x=0] - Horizontal position of the beginning of the text. - * @param {number} [y=0] - Vertical position of the *baseline* of the text. - * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. - * @param {GlyphRenderOptions=} options - */ -Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) { - this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { - glyph.drawMetrics(ctx, gX, gY, gFontSize); - }); -}; + function isSimpleFunctionComponent(type) { + return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined; + } + function resolveLazyComponentTag(Component) { + if (typeof Component === 'function') { + return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent; + } else if (Component !== undefined && Component !== null) { + var $$typeof = Component.$$typeof; -/** - * @param {string} - * @return {string} - */ -Font.prototype.getEnglishName = function(name) { - var translations = this.names[name]; - if (translations) { - return translations.en; - } -}; + if ($$typeof === REACT_FORWARD_REF_TYPE) { + return ForwardRef; + } -/** - * Validate - */ -Font.prototype.validate = function() { - var _this = this; + if ($$typeof === REACT_MEMO_TYPE) { + return MemoComponent; + } + } - function assert(predicate, message) { - } + return IndeterminateComponent; + } // This is used to create an alternate fiber to do work on. - function assertNamePresent(name) { - var englishName = _this.getEnglishName(name); - assert(englishName && englishName.trim().length > 0); - } + function createWorkInProgress(current, pendingProps) { + var workInProgress = current.alternate; - // Identification information - assertNamePresent('fontFamily'); - assertNamePresent('weightName'); - assertNamePresent('manufacturer'); - assertNamePresent('copyright'); - assertNamePresent('version'); + if (workInProgress === null) { + // We use a double buffering pooling technique because we know that we'll + // only ever need at most two versions of a tree. We pool the "other" unused + // node that we're free to reuse. This is lazily created to avoid allocating + // extra objects for things that are never updated. It also allow us to + // reclaim the extra memory if needed. + workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode); + workInProgress.elementType = current.elementType; + workInProgress.type = current.type; + workInProgress.stateNode = current.stateNode; - // Dimension information - assert(this.unitsPerEm > 0); -}; + { + // DEV-only fields + workInProgress._debugSource = current._debugSource; + workInProgress._debugOwner = current._debugOwner; + workInProgress._debugHookTypes = current._debugHookTypes; + } -/** - * Convert the font object to a SFNT data structure. - * This structure contains all the necessary tables and metadata to create a binary OTF file. - * @return {opentype.Table} - */ -Font.prototype.toTables = function() { - return sfnt.fontToTable(this); -}; -/** - * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. - */ -Font.prototype.toBuffer = function() { - console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'); - return this.toArrayBuffer(); -}; -/** - * Converts a `opentype.Font` into an `ArrayBuffer` - * @return {ArrayBuffer} - */ -Font.prototype.toArrayBuffer = function() { - var sfntTable = this.toTables(); - var bytes = sfntTable.encode(); - var buffer = new ArrayBuffer(bytes.length); - var intArray = new Uint8Array(buffer); - for (var i = 0; i < bytes.length; i++) { - intArray[i] = bytes[i]; - } + workInProgress.alternate = current; + current.alternate = workInProgress; + } else { + workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type. - return buffer; -}; + workInProgress.type = current.type; // We already have an alternate. + // Reset the effect tag. -/** - * Initiate a download of the OpenType font. - */ -Font.prototype.download = function(fileName) { - var familyName = this.getEnglishName('fontFamily'); - var styleName = this.getEnglishName('fontSubfamily'); - fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf'; - var arrayBuffer = this.toArrayBuffer(); - - if (isBrowser()) { - window.URL = window.URL || window.webkitURL; - - if (window.URL) { - var dataView = new DataView(arrayBuffer); - var blob = new Blob([dataView], {type: 'font/opentype'}); - - var link = document.createElement('a'); - link.href = window.URL.createObjectURL(blob); - link.download = fileName; - - var event = document.createEvent('MouseEvents'); - event.initEvent('click', true, false); - link.dispatchEvent(event); - } else { - console.warn('Font file could not be downloaded. Try using a different browser.'); - } - } else { - var fs = require('fs'); - var buffer = arrayBufferToNodeBuffer(arrayBuffer); - fs.writeFileSync(fileName, buffer); - } -}; -/** - * @private - */ -Font.prototype.fsSelectionValues = { - ITALIC: 0x001, //1 - UNDERSCORE: 0x002, //2 - NEGATIVE: 0x004, //4 - OUTLINED: 0x008, //8 - STRIKEOUT: 0x010, //16 - BOLD: 0x020, //32 - REGULAR: 0x040, //64 - USER_TYPO_METRICS: 0x080, //128 - WWS: 0x100, //256 - OBLIQUE: 0x200 //512 -}; + workInProgress.flags = NoFlags; // The effects are no longer valid. -/** - * @private - */ -Font.prototype.usWidthClasses = { - ULTRA_CONDENSED: 1, - EXTRA_CONDENSED: 2, - CONDENSED: 3, - SEMI_CONDENSED: 4, - MEDIUM: 5, - SEMI_EXPANDED: 6, - EXPANDED: 7, - EXTRA_EXPANDED: 8, - ULTRA_EXPANDED: 9 -}; + workInProgress.subtreeFlags = NoFlags; + workInProgress.deletions = null; -/** - * @private - */ -Font.prototype.usWeightClasses = { - THIN: 100, - EXTRA_LIGHT: 200, - LIGHT: 300, - NORMAL: 400, - MEDIUM: 500, - SEMI_BOLD: 600, - BOLD: 700, - EXTRA_BOLD: 800, - BLACK: 900 -}; + { + // We intentionally reset, rather than copy, actualDuration & actualStartTime. + // This prevents time from endlessly accumulating in new commits. + // This has the downside of resetting values for different priority renders, + // But works for yielding (the common case) and should support resuming. + workInProgress.actualDuration = 0; + workInProgress.actualStartTime = -1; + } + } // Reset all effects except static ones. + // Static effects are not specific to a render. -// The `GPOS` table contains kerning pairs, among other things. -var subtableParsers$1 = new Array(10); // subtableParsers[0] is unused + workInProgress.flags = current.flags & StaticMask; + workInProgress.childLanes = current.childLanes; + workInProgress.lanes = current.lanes; + workInProgress.child = current.child; + workInProgress.memoizedProps = current.memoizedProps; + workInProgress.memoizedState = current.memoizedState; + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so + // it cannot be shared with the current fiber. -// https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-1-single-adjustment-positioning-subtable -// this = Parser instance -subtableParsers$1[1] = function parseLookup1() { - var start = this.offset + this.relativeOffset; - var posformat = this.parseUShort(); - if (posformat === 1) { - return { - posFormat: 1, - coverage: this.parsePointer(Parser.coverage), - value: this.parseValueRecord() - }; - } else if (posformat === 2) { - return { - posFormat: 2, - coverage: this.parsePointer(Parser.coverage), - values: this.parseValueRecordList() - }; - } - check.assert(false, '0x' + start.toString(16) + ': GPOS lookup type 1 format must be 1 or 2.'); -}; + var currentDependencies = current.dependencies; + workInProgress.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; // These will be overridden during the parent's reconciliation -// https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable -subtableParsers$1[2] = function parseLookup2() { - var start = this.offset + this.relativeOffset; - var posFormat = this.parseUShort(); - check.assert(posFormat === 1 || posFormat === 2, '0x' + start.toString(16) + ': GPOS lookup type 2 format must be 1 or 2.'); - var coverage = this.parsePointer(Parser.coverage); - var valueFormat1 = this.parseUShort(); - var valueFormat2 = this.parseUShort(); - if (posFormat === 1) { - // Adjustments for Glyph Pairs - return { - posFormat: posFormat, - coverage: coverage, - valueFormat1: valueFormat1, - valueFormat2: valueFormat2, - pairSets: this.parseList(Parser.pointer(Parser.list(function() { - return { // pairValueRecord - secondGlyph: this.parseUShort(), - value1: this.parseValueRecord(valueFormat1), - value2: this.parseValueRecord(valueFormat2) - }; - }))) - }; - } else if (posFormat === 2) { - var classDef1 = this.parsePointer(Parser.classDef); - var classDef2 = this.parsePointer(Parser.classDef); - var class1Count = this.parseUShort(); - var class2Count = this.parseUShort(); - return { - // Class Pair Adjustment - posFormat: posFormat, - coverage: coverage, - valueFormat1: valueFormat1, - valueFormat2: valueFormat2, - classDef1: classDef1, - classDef2: classDef2, - class1Count: class1Count, - class2Count: class2Count, - classRecords: this.parseList(class1Count, Parser.list(class2Count, function() { - return { - value1: this.parseValueRecord(valueFormat1), - value2: this.parseValueRecord(valueFormat2) - }; - })) - }; - } -}; + workInProgress.sibling = current.sibling; + workInProgress.index = current.index; + workInProgress.ref = current.ref; -subtableParsers$1[3] = function parseLookup3() { return { error: 'GPOS Lookup 3 not supported' }; }; -subtableParsers$1[4] = function parseLookup4() { return { error: 'GPOS Lookup 4 not supported' }; }; -subtableParsers$1[5] = function parseLookup5() { return { error: 'GPOS Lookup 5 not supported' }; }; -subtableParsers$1[6] = function parseLookup6() { return { error: 'GPOS Lookup 6 not supported' }; }; -subtableParsers$1[7] = function parseLookup7() { return { error: 'GPOS Lookup 7 not supported' }; }; -subtableParsers$1[8] = function parseLookup8() { return { error: 'GPOS Lookup 8 not supported' }; }; -subtableParsers$1[9] = function parseLookup9() { return { error: 'GPOS Lookup 9 not supported' }; }; + { + workInProgress.selfBaseDuration = current.selfBaseDuration; + workInProgress.treeBaseDuration = current.treeBaseDuration; + } -// GPOS Writing ////////////////////////////////////////////// -// NOT SUPPORTED -new Array(10); + { + workInProgress._debugNeedsRemount = current._debugNeedsRemount; -var AssimpLoader = function (manager) { - Loader.call(this, manager); -}; + switch (workInProgress.tag) { + case IndeterminateComponent: + case FunctionComponent: + case SimpleMemoComponent: + workInProgress.type = resolveFunctionForHotReloading(current.type); + break; -AssimpLoader.prototype = Object.assign(Object.create(Loader.prototype), { - constructor: AssimpLoader, - load: function (url, onLoad, onProgress, onError) { - var scope = this; - var path = scope.path === '' ? LoaderUtils.extractUrlBase(url) : scope.path; - var loader = new FileLoader(scope.manager); - loader.setPath(scope.path); - loader.setResponseType('arraybuffer'); - loader.setRequestHeader(scope.requestHeader); - loader.setWithCredentials(scope.withCredentials); - loader.load(url, function (buffer) { - try { - onLoad(scope.parse(buffer, path)); - } catch (e) { - if (onError) { - onError(e); - } else { - console.error(e); - } + case ClassComponent: + workInProgress.type = resolveClassForHotReloading(current.type); + break; - scope.manager.itemError(url); - } - }, onProgress, onError); - }, - parse: function (buffer, path) { - var textureLoader = new TextureLoader(this.manager); - textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin); - var Virtulous = {}; - - Virtulous.KeyFrame = function (time, matrix) { - this.time = time; - this.matrix = matrix.clone(); - this.position = new Vector3(); - this.quaternion = new Quaternion(); - this.scale = new Vector3(1, 1, 1); - this.matrix.decompose(this.position, this.quaternion, this.scale); - - this.clone = function () { - var n = new Virtulous.KeyFrame(this.time, this.matrix); - return n; - }; + case ForwardRef: + workInProgress.type = resolveForwardRefForHotReloading(current.type); + break; + } + } - this.lerp = function (nextKey, time) { - time -= this.time; - var dist = nextKey.time - this.time; - var l = time / dist; - var l2 = 1 - l; - var keypos = this.position; - var keyrot = this.quaternion; // var keyscl = key.parentspaceScl || key.scl; - - var key2pos = nextKey.position; - var key2rot = nextKey.quaternion; // var key2scl = key2.parentspaceScl || key2.scl; - - Virtulous.KeyFrame.tempAniPos.x = keypos.x * l2 + key2pos.x * l; - Virtulous.KeyFrame.tempAniPos.y = keypos.y * l2 + key2pos.y * l; - Virtulous.KeyFrame.tempAniPos.z = keypos.z * l2 + key2pos.z * l; // tempAniScale.x = keyscl[0] * l2 + key2scl[0] * l; - // tempAniScale.y = keyscl[1] * l2 + key2scl[1] * l; - // tempAniScale.z = keyscl[2] * l2 + key2scl[2] * l; - - Virtulous.KeyFrame.tempAniQuat.set(keyrot.x, keyrot.y, keyrot.z, keyrot.w); - Virtulous.KeyFrame.tempAniQuat.slerp(key2rot, l); - return Virtulous.KeyFrame.tempAniMatrix.compose(Virtulous.KeyFrame.tempAniPos, Virtulous.KeyFrame.tempAniQuat, Virtulous.KeyFrame.tempAniScale); - }; - }; + return workInProgress; + } // Used to reuse a Fiber for a second pass. - Virtulous.KeyFrame.tempAniPos = new Vector3(); - Virtulous.KeyFrame.tempAniQuat = new Quaternion(); - Virtulous.KeyFrame.tempAniScale = new Vector3(1, 1, 1); - Virtulous.KeyFrame.tempAniMatrix = new Matrix4(); + function resetWorkInProgress(workInProgress, renderLanes) { + // This resets the Fiber to what createFiber or createWorkInProgress would + // have set the values to before during the first pass. Ideally this wouldn't + // be necessary but unfortunately many code paths reads from the workInProgress + // when they should be reading from current and writing to workInProgress. + // We assume pendingProps, index, key, ref, return are still untouched to + // avoid doing another reconciliation. + // Reset the effect flags but keep any Placement tags, since that's something + // that child fiber is setting, not the reconciliation. + workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid. - Virtulous.KeyFrameTrack = function () { - this.keys = []; - this.target = null; - this.time = 0; - this.length = 0; - this._accelTable = {}; - this.fps = 20; + var current = workInProgress.alternate; - this.addKey = function (key) { - this.keys.push(key); - }; + if (current === null) { + // Reset to createFiber's initial values. + workInProgress.childLanes = NoLanes; + workInProgress.lanes = renderLanes; + workInProgress.child = null; + workInProgress.subtreeFlags = NoFlags; + workInProgress.memoizedProps = null; + workInProgress.memoizedState = null; + workInProgress.updateQueue = null; + workInProgress.dependencies = null; + workInProgress.stateNode = null; - this.init = function () { - this.sortKeys(); - if (this.keys.length > 0) this.length = this.keys[this.keys.length - 1].time;else this.length = 0; - if (!this.fps) return; + { + // Note: We don't reset the actualTime counts. It's useful to accumulate + // actual time across multiple render passes. + workInProgress.selfBaseDuration = 0; + workInProgress.treeBaseDuration = 0; + } + } else { + // Reset to the cloned values that createWorkInProgress would've. + workInProgress.childLanes = current.childLanes; + workInProgress.lanes = current.lanes; + workInProgress.child = current.child; + workInProgress.subtreeFlags = NoFlags; + workInProgress.deletions = null; + workInProgress.memoizedProps = current.memoizedProps; + workInProgress.memoizedState = current.memoizedState; + workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type. - for (let j = 0; j < this.length * this.fps; j++) { - for (let i = 0; i < this.keys.length; i++) { - if (this.keys[i].time == j) { - this._accelTable[j] = i; - break; - } else if (this.keys[i].time < j / this.fps && this.keys[i + 1] && this.keys[i + 1].time >= j / this.fps) { - this._accelTable[j] = i; - break; - } - } - } - }; + workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so + // it cannot be shared with the current fiber. - this.parseFromThree = function (data) { - var fps = data.fps; - this.target = data.node; - var track = data.hierarchy[0].keys; + var currentDependencies = current.dependencies; + workInProgress.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; - for (let i = 0; i < track.length; i++) { - this.addKey(new Virtulous.KeyFrame(i / fps || track[i].time, track[i].targets[0].data)); - } + { + // Note: We don't reset the actualTime counts. It's useful to accumulate + // actual time across multiple render passes. + workInProgress.selfBaseDuration = current.selfBaseDuration; + workInProgress.treeBaseDuration = current.treeBaseDuration; + } + } - this.init(); - }; + return workInProgress; + } + function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { + var mode; - this.parseFromCollada = function (data) { - var track = data.keys; - var fps = this.fps; + if (tag === ConcurrentRoot) { + mode = ConcurrentMode; - for (let i = 0; i < track.length; i++) { - this.addKey(new Virtulous.KeyFrame(i / fps || track[i].time, track[i].matrix)); - } + if (isStrictMode === true) { + mode |= StrictLegacyMode; - this.init(); - }; + { + mode |= StrictEffectsMode; + } + } + } else { + mode = NoMode; + } - this.sortKeys = function () { - this.keys.sort(this.keySortFunc); - }; + if ( isDevToolsPresent) { + // Always collect profile timings when DevTools are present. + // This enables DevTools to start capturing timing at any point– + // Without some nodes in the tree having empty base times. + mode |= ProfileMode; + } - this.keySortFunc = function (a, b) { - return a.time - b.time; - }; + return createFiber(HostRoot, null, null, mode); + } + function createFiberFromTypeAndProps(type, // React$ElementType + key, pendingProps, owner, mode, lanes) { + var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. - this.clone = function () { - var t = new Virtulous.KeyFrameTrack(); - t.target = this.target; - t.time = this.time; - t.length = this.length; + var resolvedType = type; - for (let i = 0; i < this.keys.length; i++) { - t.addKey(this.keys[i].clone()); - } + if (typeof type === 'function') { + if (shouldConstruct$1(type)) { + fiberTag = ClassComponent; - t.init(); - return t; - }; + { + resolvedType = resolveClassForHotReloading(resolvedType); + } + } else { + { + resolvedType = resolveFunctionForHotReloading(resolvedType); + } + } + } else if (typeof type === 'string') { + fiberTag = HostComponent; + } else { + getTag: switch (type) { + case REACT_FRAGMENT_TYPE: + return createFiberFromFragment(pendingProps.children, mode, lanes, key); - this.reTarget = function (root, compareitor) { - if (!compareitor) compareitor = Virtulous.TrackTargetNodeNameCompare; - this.target = compareitor(root, this.target); - }; + case REACT_STRICT_MODE_TYPE: + fiberTag = Mode; + mode |= StrictLegacyMode; - this.keySearchAccel = function (time) { - time *= this.fps; - time = Math.floor(time); - return this._accelTable[time] || 0; - }; + if ( (mode & ConcurrentMode) !== NoMode) { + // Strict effects should never run on legacy roots + mode |= StrictEffectsMode; + } - this.setTime = function (time) { - time = Math.abs(time); - if (this.length) time = time % this.length + 0.05; - var key0 = null; - var key1 = null; - - for (let i = this.keySearchAccel(time); i < this.keys.length; i++) { - if (this.keys[i].time == time) { - key0 = this.keys[i]; - key1 = this.keys[i]; - break; - } else if (this.keys[i].time < time && this.keys[i + 1] && this.keys[i + 1].time > time) { - key0 = this.keys[i]; - key1 = this.keys[i + 1]; - break; - } else if (this.keys[i].time < time && i == this.keys.length - 1) { - key0 = this.keys[i]; - key1 = this.keys[0].clone(); - key1.time += this.length + 0.05; - break; - } - } + break; - if (key0 && key1 && key0 !== key1) { - this.target.matrixAutoUpdate = false; - this.target.matrix.copy(key0.lerp(key1, time)); - this.target.matrixWorldNeedsUpdate = true; - return; - } + case REACT_PROFILER_TYPE: + return createFiberFromProfiler(pendingProps, mode, lanes, key); - if (key0 && key1 && key0 == key1) { - this.target.matrixAutoUpdate = false; - this.target.matrix.copy(key0.matrix); - this.target.matrixWorldNeedsUpdate = true; - return; - } - }; - }; + case REACT_SUSPENSE_TYPE: + return createFiberFromSuspense(pendingProps, mode, lanes, key); - Virtulous.TrackTargetNodeNameCompare = function (root, target) { - function find(node, name) { - if (node.name == name) return node; + case REACT_SUSPENSE_LIST_TYPE: + return createFiberFromSuspenseList(pendingProps, mode, lanes, key); - for (let i = 0; i < node.children.length; i++) { - var r = find(node.children[i], name); - if (r) return r; - } + case REACT_OFFSCREEN_TYPE: + return createFiberFromOffscreen(pendingProps, mode, lanes, key); - return null; - } + case REACT_LEGACY_HIDDEN_TYPE: - return find(root, target.name); - }; + // eslint-disable-next-line no-fallthrough - Virtulous.Animation = function () { - this.tracks = []; - this.length = 0; + case REACT_SCOPE_TYPE: - this.addTrack = function (track) { - this.tracks.push(track); - this.length = Math.max(track.length, this.length); - }; + // eslint-disable-next-line no-fallthrough - this.setTime = function (time) { - this.time = time; + case REACT_CACHE_TYPE: - for (let i = 0; i < this.tracks.length; i++) this.tracks[i].setTime(time); - }; + // eslint-disable-next-line no-fallthrough - this.clone = function (target, compareitor) { - if (!compareitor) compareitor = Virtulous.TrackTargetNodeNameCompare; - var n = new Virtulous.Animation(); - n.target = target; + case REACT_TRACING_MARKER_TYPE: - for (let i = 0; i < this.tracks.length; i++) { - var track = this.tracks[i].clone(); - track.reTarget(target, compareitor); - n.addTrack(track); - } + // eslint-disable-next-line no-fallthrough - return n; - }; - }; + case REACT_DEBUG_TRACING_MODE_TYPE: - var ASSBIN_CHUNK_AICAMERA = 0x1234; - var ASSBIN_CHUNK_AILIGHT = 0x1235; - var ASSBIN_CHUNK_AITEXTURE = 0x1236; - var ASSBIN_CHUNK_AIMESH = 0x1237; - var ASSBIN_CHUNK_AINODEANIM = 0x1238; - var ASSBIN_CHUNK_AISCENE = 0x1239; - var ASSBIN_CHUNK_AIBONE = 0x123a; - var ASSBIN_CHUNK_AIANIMATION = 0x123b; - var ASSBIN_CHUNK_AINODE = 0x123c; - var ASSBIN_CHUNK_AIMATERIAL = 0x123d; - var ASSBIN_CHUNK_AIMATERIALPROPERTY = 0x123e; - var ASSBIN_MESH_HAS_POSITIONS = 0x1; - var ASSBIN_MESH_HAS_NORMALS = 0x2; - var ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS = 0x4; - var ASSBIN_MESH_HAS_TEXCOORD_BASE = 0x100; - var ASSBIN_MESH_HAS_COLOR_BASE = 0x10000; - var AI_MAX_NUMBER_OF_COLOR_SETS = 1; - var AI_MAX_NUMBER_OF_TEXTURECOORDS = 4; //var aiLightSource_UNDEFINED = 0x0; - //! A directional light source has a well-defined direction - //! but is infinitely far away. That's quite a good - //! approximation for sun light. - - var aiLightSource_DIRECTIONAL = 0x1; //! A point light source has a well-defined position - //! in space but no direction - it emits light in all - //! directions. A normal bulb is a point light. - //var aiLightSource_POINT = 0x2; - //! A spot light source emits light in a specific - //! angle. It has a position and a direction it is pointing to. - //! A good example for a spot light is a light spot in - //! sport arenas. - - var aiLightSource_SPOT = 0x3; //! The generic light level of the world, including the bounces - //! of all other lightsources. - //! Typically, there's at most one ambient light in a scene. - //! This light type doesn't have a valid position, direction, or - //! other properties, just a color. - //var aiLightSource_AMBIENT = 0x4; - - /** Flat shading. Shading is done on per-face base, - * diffuse only. Also known as 'faceted shading'. - */ - //var aiShadingMode_Flat = 0x1; + // eslint-disable-next-line no-fallthrough - /** Simple Gouraud shading. - */ - //var aiShadingMode_Gouraud = 0x2; + default: + { + if (typeof type === 'object' && type !== null) { + switch (type.$$typeof) { + case REACT_PROVIDER_TYPE: + fiberTag = ContextProvider; + break getTag; - /** Phong-Shading - - */ - //var aiShadingMode_Phong = 0x3; + case REACT_CONTEXT_TYPE: + // This is a consumer + fiberTag = ContextConsumer; + break getTag; - /** Phong-Blinn-Shading - */ - //var aiShadingMode_Blinn = 0x4; + case REACT_FORWARD_REF_TYPE: + fiberTag = ForwardRef; - /** Toon-Shading per pixel - * - * Also known as 'comic' shader. - */ - //var aiShadingMode_Toon = 0x5; + { + resolvedType = resolveForwardRefForHotReloading(resolvedType); + } - /** OrenNayar-Shading per pixel - * - * Extension to standard Lambertian shading, taking the - * roughness of the material into account - */ - //var aiShadingMode_OrenNayar = 0x6; + break getTag; - /** Minnaert-Shading per pixel - * - * Extension to standard Lambertian shading, taking the - * "darkness" of the material into account - */ - //var aiShadingMode_Minnaert = 0x7; + case REACT_MEMO_TYPE: + fiberTag = MemoComponent; + break getTag; - /** CookTorrance-Shading per pixel - * - * Special shader for metallic surfaces. - */ - //var aiShadingMode_CookTorrance = 0x8; + case REACT_LAZY_TYPE: + fiberTag = LazyComponent; + resolvedType = null; + break getTag; + } + } - /** No shading at all. Constant light influence of 1.0. - */ - //var aiShadingMode_NoShading = 0x9; + var info = ''; - /** Fresnel shading - */ - //var aiShadingMode_Fresnel = 0xa; - //var aiTextureType_NONE = 0x0; + { + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; + } - /** The texture is combined with the result of the diffuse - * lighting equation. - */ + var ownerName = owner ? getComponentNameFromFiber(owner) : null; - var aiTextureType_DIFFUSE = 0x1; - /** The texture is combined with the result of the specular - * lighting equation. - */ - //var aiTextureType_SPECULAR = 0x2; + if (ownerName) { + info += '\n\nCheck the render method of `' + ownerName + '`.'; + } + } - /** The texture is combined with the result of the ambient - * lighting equation. - */ - //var aiTextureType_AMBIENT = 0x3; + throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); + } + } + } - /** The texture is added to the result of the lighting - * calculation. It isn't influenced by incoming light. - */ - //var aiTextureType_EMISSIVE = 0x4; + var fiber = createFiber(fiberTag, pendingProps, key, mode); + fiber.elementType = type; + fiber.type = resolvedType; + fiber.lanes = lanes; - /** The texture is a height map. - * - * By convention, higher gray-scale values stand for - * higher elevations from the base height. - */ - //var aiTextureType_HEIGHT = 0x5; + { + fiber._debugOwner = owner; + } - /** The texture is a (tangent space) normal-map. - * - * Again, there are several conventions for tangent-space - * normal maps. Assimp does (intentionally) not - * distinguish here. - */ + return fiber; + } + function createFiberFromElement(element, mode, lanes) { + var owner = null; - var aiTextureType_NORMALS = 0x6; - /** The texture defines the glossiness of the material. - * - * The glossiness is in fact the exponent of the specular - * (phong) lighting equation. Usually there is a conversion - * function defined to map the linear color values in the - * texture to a suitable exponent. Have fun. - */ - //var aiTextureType_SHININESS = 0x7; + { + owner = element._owner; + } - /** The texture defines per-pixel opacity. - * - * Usually 'white' means opaque and 'black' means - * 'transparency'. Or quite the opposite. Have fun. - */ + var type = element.type; + var key = element.key; + var pendingProps = element.props; + var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes); - var aiTextureType_OPACITY = 0x8; - /** Displacement texture - * - * The exact purpose and format is application-dependent. - * Higher color values stand for higher vertex displacements. - */ - //var aiTextureType_DISPLACEMENT = 0x9; + { + fiber._debugSource = element._source; + fiber._debugOwner = element._owner; + } - /** Lightmap texture (aka Ambient Occlusion) - * - * Both 'Lightmaps' and dedicated 'ambient occlusion maps' are - * covered by this material property. The texture contains a - * scaling value for the final color value of a pixel. Its - * intensity is not affected by incoming light. - */ + return fiber; + } + function createFiberFromFragment(elements, mode, lanes, key) { + var fiber = createFiber(Fragment, elements, key, mode); + fiber.lanes = lanes; + return fiber; + } - var aiTextureType_LIGHTMAP = 0xa; - /** Reflection texture - * - * Contains the color of a perfect mirror reflection. - * Rarely used, almost never for real-time applications. - */ - //var aiTextureType_REFLECTION = 0xB; + function createFiberFromProfiler(pendingProps, mode, lanes, key) { + { + if (typeof pendingProps.id !== 'string') { + error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id); + } + } - /** Unknown texture - * - * A texture reference that does not match any of the definitions - * above is considered to be 'unknown'. It is still imported, - * but is excluded from any further postprocessing. - */ - //var aiTextureType_UNKNOWN = 0xC; + var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); + fiber.elementType = REACT_PROFILER_TYPE; + fiber.lanes = lanes; - var BONESPERVERT = 4; + { + fiber.stateNode = { + effectDuration: 0, + passiveEffectDuration: 0 + }; + } - function ASSBIN_MESH_HAS_TEXCOORD(n) { - return ASSBIN_MESH_HAS_TEXCOORD_BASE << n; - } + return fiber; + } - function ASSBIN_MESH_HAS_COLOR(n) { - return ASSBIN_MESH_HAS_COLOR_BASE << n; - } + function createFiberFromSuspense(pendingProps, mode, lanes, key) { + var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); + fiber.elementType = REACT_SUSPENSE_TYPE; + fiber.lanes = lanes; + return fiber; + } + function createFiberFromSuspenseList(pendingProps, mode, lanes, key) { + var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); + fiber.elementType = REACT_SUSPENSE_LIST_TYPE; + fiber.lanes = lanes; + return fiber; + } + function createFiberFromOffscreen(pendingProps, mode, lanes, key) { + var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); + fiber.elementType = REACT_OFFSCREEN_TYPE; + fiber.lanes = lanes; + var primaryChildInstance = {}; + fiber.stateNode = primaryChildInstance; + return fiber; + } + function createFiberFromText(content, mode, lanes) { + var fiber = createFiber(HostText, content, null, mode); + fiber.lanes = lanes; + return fiber; + } + function createFiberFromHostInstanceForDeletion() { + var fiber = createFiber(HostComponent, null, null, NoMode); + fiber.elementType = 'DELETED'; + return fiber; + } + function createFiberFromDehydratedFragment(dehydratedNode) { + var fiber = createFiber(DehydratedFragment, null, null, NoMode); + fiber.stateNode = dehydratedNode; + return fiber; + } + function createFiberFromPortal(portal, mode, lanes) { + var pendingProps = portal.children !== null ? portal.children : []; + var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); + fiber.lanes = lanes; + fiber.stateNode = { + containerInfo: portal.containerInfo, + pendingChildren: null, + // Used by persistent updates + implementation: portal.implementation + }; + return fiber; + } // Used for stashing WIP properties to replay failed work in DEV. - function markBones(scene) { - for (let i in scene.mMeshes) { - var mesh = scene.mMeshes[i]; + function assignFiberPropertiesInDEV(target, source) { + if (target === null) { + // This Fiber's initial properties will always be overwritten. + // We only use a Fiber to ensure the same hidden class so DEV isn't slow. + target = createFiber(IndeterminateComponent, null, null, NoMode); + } // This is intentionally written as a list of all properties. + // We tried to use Object.assign() instead but this is called in + // the hottest path, and Object.assign() was too slow: + // https://github.com/facebook/react/issues/12502 + // This code is DEV-only so size is not a concern. - for (let k in mesh.mBones) { - var boneNode = scene.findNode(mesh.mBones[k].mName); - if (boneNode) boneNode.isBone = true; - } - } - } - function cloneTreeToBones(root, scene) { - var rootBone = new Bone(); - rootBone.matrix.copy(root.matrix); - rootBone.matrixWorld.copy(root.matrixWorld); - rootBone.position.copy(root.position); - rootBone.quaternion.copy(root.quaternion); - rootBone.scale.copy(root.scale); - scene.nodeCount++; - rootBone.name = 'bone_' + root.name + scene.nodeCount.toString(); - if (!scene.nodeToBoneMap[root.name]) scene.nodeToBoneMap[root.name] = []; - scene.nodeToBoneMap[root.name].push(rootBone); - - for (let i in root.children) { - var child = cloneTreeToBones(root.children[i], scene); - rootBone.add(child); - } + target.tag = source.tag; + target.key = source.key; + target.elementType = source.elementType; + target.type = source.type; + target.stateNode = source.stateNode; + target.return = source.return; + target.child = source.child; + target.sibling = source.sibling; + target.index = source.index; + target.ref = source.ref; + target.pendingProps = source.pendingProps; + target.memoizedProps = source.memoizedProps; + target.updateQueue = source.updateQueue; + target.memoizedState = source.memoizedState; + target.dependencies = source.dependencies; + target.mode = source.mode; + target.flags = source.flags; + target.subtreeFlags = source.subtreeFlags; + target.deletions = source.deletions; + target.lanes = source.lanes; + target.childLanes = source.childLanes; + target.alternate = source.alternate; - return rootBone; - } + { + target.actualDuration = source.actualDuration; + target.actualStartTime = source.actualStartTime; + target.selfBaseDuration = source.selfBaseDuration; + target.treeBaseDuration = source.treeBaseDuration; + } - function sortWeights(indexes, weights) { - var pairs = []; + target._debugSource = source._debugSource; + target._debugOwner = source._debugOwner; + target._debugNeedsRemount = source._debugNeedsRemount; + target._debugHookTypes = source._debugHookTypes; + return target; + } - for (let i = 0; i < indexes.length; i++) { - pairs.push({ - i: indexes[i], - w: weights[i] - }); - } + function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) { + this.tag = tag; + this.containerInfo = containerInfo; + this.pendingChildren = null; + this.current = null; + this.pingCache = null; + this.finishedWork = null; + this.timeoutHandle = noTimeout; + this.context = null; + this.pendingContext = null; + this.callbackNode = null; + this.callbackPriority = NoLane; + this.eventTimes = createLaneMap(NoLanes); + this.expirationTimes = createLaneMap(NoTimestamp); + this.pendingLanes = NoLanes; + this.suspendedLanes = NoLanes; + this.pingedLanes = NoLanes; + this.expiredLanes = NoLanes; + this.mutableReadLanes = NoLanes; + this.finishedLanes = NoLanes; + this.entangledLanes = NoLanes; + this.entanglements = createLaneMap(NoLanes); + this.identifierPrefix = identifierPrefix; + this.onRecoverableError = onRecoverableError; - pairs.sort(function (a, b) { - return b.w - a.w; - }); + if (supportsHydration) { + this.mutableSourceEagerHydrationData = null; + } - while (pairs.length < 4) { - pairs.push({ - i: 0, - w: 0 - }); - } + { + this.effectDuration = 0; + this.passiveEffectDuration = 0; + } + + { + this.memoizedUpdaters = new Set(); + var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = []; + + for (var _i = 0; _i < TotalLanes; _i++) { + pendingUpdatersLaneMap.push(new Set()); + } + } - if (pairs.length > 4) pairs.length = 4; - var sum = 0; + { + switch (tag) { + case ConcurrentRoot: + this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()'; + break; - for (let i = 0; i < 4; i++) { - sum += pairs[i].w * pairs[i].w; - } + case LegacyRoot: + this._debugRootType = hydrate ? 'hydrate()' : 'render()'; + break; + } + } + } - sum = Math.sqrt(sum); + function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the + // host config, but because they are passed in at runtime, we have to thread + // them through the root constructor. Perhaps we should put them all into a + // single type, like a DynamicHostConfig that is defined by the renderer. + identifierPrefix, onRecoverableError, transitionCallbacks) { + var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); + // stateNode is any. - for (let i = 0; i < 4; i++) { - pairs[i].w = pairs[i].w / sum; - indexes[i] = pairs[i].i; - weights[i] = pairs[i].w; - } - } - function findMatchingBone(root, name) { - if (root.name.indexOf('bone_' + name) == 0) return root; + var uninitializedFiber = createHostRootFiber(tag, isStrictMode); + root.current = uninitializedFiber; + uninitializedFiber.stateNode = root; - for (let i in root.children) { - var ret = findMatchingBone(root.children[i], name); - if (ret) return ret; - } + { + var _initialState = { + element: initialChildren, + isDehydrated: hydrate, + cache: null, + // not enabled yet + transitions: null + }; + uninitializedFiber.memoizedState = _initialState; + } - return undefined; - } + initializeUpdateQueue(uninitializedFiber); + return root; + } - function aiMesh() { - this.mPrimitiveTypes = 0; - this.mNumVertices = 0; - this.mNumFaces = 0; - this.mNumBones = 0; - this.mMaterialIndex = 0; - this.mVertices = []; - this.mNormals = []; - this.mTangents = []; - this.mBitangents = []; - this.mColors = [[]]; - this.mTextureCoords = [[]]; - this.mFaces = []; - this.mBones = []; - - this.hookupSkeletons = function (scene) { - if (this.mBones.length == 0) return; - var allBones = []; - var offsetMatrix = []; - var skeletonRoot = scene.findNode(this.mBones[0].mName); - - while (skeletonRoot.mParent && skeletonRoot.mParent.isBone) { - skeletonRoot = skeletonRoot.mParent; - } + var ReactVersion = '18.0.0-fc46dba67-20220329'; - var threeSkeletonRoot = skeletonRoot.toTHREE(scene); - var threeSkeletonRootBone = cloneTreeToBones(threeSkeletonRoot, scene); - this.threeNode.add(threeSkeletonRootBone); + function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation. + implementation) { + var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - for (let i = 0; i < this.mBones.length; i++) { - var bone = findMatchingBone(threeSkeletonRootBone, this.mBones[i].mName); + { + checkKeyStringCoercion(key); + } - if (bone) { - var tbone = bone; - allBones.push(tbone); //tbone.matrixAutoUpdate = false; + return { + // This tag allow us to uniquely identify this as a React Portal + $$typeof: REACT_PORTAL_TYPE, + key: key == null ? null : '' + key, + children: children, + containerInfo: containerInfo, + implementation: implementation + }; + } - offsetMatrix.push(this.mBones[i].mOffsetMatrix.toTHREE()); - } else { - var skeletonRoot = scene.findNode(this.mBones[i].mName); - if (!skeletonRoot) return; - var threeSkeletonRoot = skeletonRoot.toTHREE(scene); - var threeSkeletonRootBone = cloneTreeToBones(threeSkeletonRoot, scene); - this.threeNode.add(threeSkeletonRootBone); - var bone = findMatchingBone(threeSkeletonRootBone, this.mBones[i].mName); - var tbone = bone; - allBones.push(tbone); //tbone.matrixAutoUpdate = false; - - offsetMatrix.push(this.mBones[i].mOffsetMatrix.toTHREE()); - } - } + var didWarnAboutNestedUpdates; + var didWarnAboutFindNodeInStrictMode; - var skeleton = new Skeleton(allBones, offsetMatrix); - this.threeNode.bind(skeleton, new Matrix4()); - this.threeNode.material.skinning = true; - }; + { + didWarnAboutNestedUpdates = false; + didWarnAboutFindNodeInStrictMode = {}; + } - this.toTHREE = function (scene) { - if (this.threeNode) return this.threeNode; - var geometry = new BufferGeometry(); - var mat; - if (scene.mMaterials[this.mMaterialIndex]) mat = scene.mMaterials[this.mMaterialIndex].toTHREE(scene);else mat = new MeshLambertMaterial(); - geometry.setIndex(new BufferAttribute(new Uint32Array(this.mIndexArray), 1)); - geometry.setAttribute('position', new BufferAttribute(this.mVertexBuffer, 3)); + function getContextForSubtree(parentComponent) { + if (!parentComponent) { + return emptyContextObject; + } - if (this.mNormalBuffer && this.mNormalBuffer.length > 0) { - geometry.setAttribute('normal', new BufferAttribute(this.mNormalBuffer, 3)); - } + var fiber = get(parentComponent); + var parentContext = findCurrentUnmaskedContext(fiber); - if (this.mColorBuffer && this.mColorBuffer.length > 0) { - geometry.setAttribute('color', new BufferAttribute(this.mColorBuffer, 4)); - } + if (fiber.tag === ClassComponent) { + var Component = fiber.type; - if (this.mTexCoordsBuffers[0] && this.mTexCoordsBuffers[0].length > 0) { - geometry.setAttribute('uv', new BufferAttribute(new Float32Array(this.mTexCoordsBuffers[0]), 2)); - } + if (isContextProvider(Component)) { + return processChildContext(fiber, Component, parentContext); + } + } - if (this.mTexCoordsBuffers[1] && this.mTexCoordsBuffers[1].length > 0) { - geometry.setAttribute('uv1', new BufferAttribute(new Float32Array(this.mTexCoordsBuffers[1]), 2)); - } + return parentContext; + } - if (this.mTangentBuffer && this.mTangentBuffer.length > 0) { - geometry.setAttribute('tangents', new BufferAttribute(this.mTangentBuffer, 3)); - } + function findHostInstance(component) { + var fiber = get(component); - if (this.mBitangentBuffer && this.mBitangentBuffer.length > 0) { - geometry.setAttribute('bitangents', new BufferAttribute(this.mBitangentBuffer, 3)); - } + if (fiber === undefined) { + if (typeof component.render === 'function') { + throw new Error('Unable to find node on an unmounted component.'); + } else { + var keys = Object.keys(component).join(','); + throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); + } + } - if (this.mBones.length > 0) { - var weights = []; - var bones = []; + var hostFiber = findCurrentHostFiber(fiber); - for (let i = 0; i < this.mBones.length; i++) { - for (let j = 0; j < this.mBones[i].mWeights.length; j++) { - var weight = this.mBones[i].mWeights[j]; + if (hostFiber === null) { + return null; + } - if (weight) { - if (!weights[weight.mVertexId]) weights[weight.mVertexId] = []; - if (!bones[weight.mVertexId]) bones[weight.mVertexId] = []; - weights[weight.mVertexId].push(weight.mWeight); - bones[weight.mVertexId].push(parseInt(i)); - } - } - } + return hostFiber.stateNode; + } - for (let i in bones) { - sortWeights(bones[i], weights[i]); - } + function findHostInstanceWithWarning(component, methodName) { + { + var fiber = get(component); - var _weights = []; - var _bones = []; + if (fiber === undefined) { + if (typeof component.render === 'function') { + throw new Error('Unable to find node on an unmounted component.'); + } else { + var keys = Object.keys(component).join(','); + throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); + } + } - for (let i = 0; i < weights.length; i++) { - for (let j = 0; j < 4; j++) { - if (weights[i] && bones[i]) { - _weights.push(weights[i][j]); + var hostFiber = findCurrentHostFiber(fiber); - _bones.push(bones[i][j]); - } else { - _weights.push(0); + if (hostFiber === null) { + return null; + } - _bones.push(0); - } - } - } + if (hostFiber.mode & StrictLegacyMode) { + var componentName = getComponentNameFromFiber(fiber) || 'Component'; - geometry.setAttribute('skinWeight', new BufferAttribute(new Float32Array(_weights), BONESPERVERT)); - geometry.setAttribute('skinIndex', new BufferAttribute(new Float32Array(_bones), BONESPERVERT)); - } + if (!didWarnAboutFindNodeInStrictMode[componentName]) { + didWarnAboutFindNodeInStrictMode[componentName] = true; + var previousFiber = current; - var mesh; - if (this.mBones.length == 0) mesh = new Mesh(geometry, mat); + try { + setCurrentFiber(hostFiber); - if (this.mBones.length > 0) { - mesh = new SkinnedMesh(geometry, mat); - mesh.normalizeSkinWeights(); - } + if (fiber.mode & StrictLegacyMode) { + error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); + } else { + error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); + } + } finally { + // Ideally this should reset to previous but this shouldn't be called in + // render and there's another warning for that anyway. + if (previousFiber) { + setCurrentFiber(previousFiber); + } else { + resetCurrentFiber(); + } + } + } + } - this.threeNode = mesh; //mesh.matrixAutoUpdate = false; + return hostFiber.stateNode; + } + } - return mesh; - }; - } + function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate = false; + var initialChildren = null; + return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + } + function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode. + callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate = true; + var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor - function aiFace() { - this.mNumIndices = 0; - this.mIndices = []; - } + root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from + // a regular update because the initial render must match was was rendered + // on the server. + // NOTE: This update intentionally doesn't have a payload. We're only using + // the update to schedule work on the root fiber (and, for legacy roots, to + // enqueue the callback if one is provided). - function aiVector3D() { - this.x = 0; - this.y = 0; - this.z = 0; + var current = root.current; + var eventTime = requestEventTime(); + var lane = requestUpdateLane(current); + var update = createUpdate(eventTime, lane); + update.callback = callback !== undefined && callback !== null ? callback : null; + enqueueUpdate(current, update); + scheduleInitialHydrationOnRoot(root, lane, eventTime); + return root; + } + function updateContainer(element, container, parentComponent, callback) { + { + onScheduleRoot(container, element); + } - this.toTHREE = function () { - return new Vector3(this.x, this.y, this.z); - }; - } + var current$1 = container.current; + var eventTime = requestEventTime(); + var lane = requestUpdateLane(current$1); - function aiColor3D() { - this.r = 0; - this.g = 0; - this.b = 0; - this.a = 0; + { + markRenderScheduled(lane); + } - this.toTHREE = function () { - return new Color(this.r, this.g, this.b); - }; - } + var context = getContextForSubtree(parentComponent); - function aiQuaternion() { - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 0; + if (container.context === null) { + container.context = context; + } else { + container.pendingContext = context; + } - this.toTHREE = function () { - return new Quaternion(this.x, this.y, this.z, this.w); - }; - } + { + if (isRendering && current !== null && !didWarnAboutNestedUpdates) { + didWarnAboutNestedUpdates = true; - function aiVertexWeight() { - this.mVertexId = 0; - this.mWeight = 0; - } + error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown'); + } + } - function aiString() { - this.data = []; + var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property + // being called "element". - this.toString = function () { - var str = ''; - this.data.forEach(function (i) { - str += String.fromCharCode(i); - }); - return str.replace(/[^\x20-\x7E]+/g, ''); - }; - } + update.payload = { + element: element + }; + callback = callback === undefined ? null : callback; - function aiVectorKey() { - this.mTime = 0; - this.mValue = null; - } + if (callback !== null) { + { + if (typeof callback !== 'function') { + error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback); + } + } - function aiQuatKey() { - this.mTime = 0; - this.mValue = null; - } + update.callback = callback; + } - function aiNode() { - this.mName = ''; - this.mTransformation = []; - this.mNumChildren = 0; - this.mNumMeshes = 0; - this.mMeshes = []; - this.mChildren = []; - - this.toTHREE = function (scene) { - if (this.threeNode) return this.threeNode; - var o = new Object3D(); - o.name = this.mName; - o.matrix = this.mTransformation.toTHREE(); - - for (let i = 0; i < this.mChildren.length; i++) { - o.add(this.mChildren[i].toTHREE(scene)); - } + enqueueUpdate(current$1, update); + var root = scheduleUpdateOnFiber(current$1, lane, eventTime); - for (let i = 0; i < this.mMeshes.length; i++) { - o.add(scene.mMeshes[this.mMeshes[i]].toTHREE(scene)); - } + if (root !== null) { + entangleTransitions(root, current$1, lane); + } - this.threeNode = o; //o.matrixAutoUpdate = false; + return lane; + } + function getPublicRootInstance(container) { + var containerFiber = container.current; - o.matrix.decompose(o.position, o.quaternion, o.scale); - return o; - }; - } + if (!containerFiber.child) { + return null; + } - function aiBone() { - this.mName = ''; - this.mNumWeights = 0; - this.mOffsetMatrix = 0; - } + switch (containerFiber.child.tag) { + case HostComponent: + return getPublicInstance(containerFiber.child.stateNode); - function aiMaterialProperty() { - this.mKey = ''; - this.mSemantic = 0; - this.mIndex = 0; - this.mData = []; - this.mDataLength = 0; - this.mType = 0; - - this.dataAsColor = function () { - var array = new Uint8Array(this.mData).buffer; - var reader = new DataView(array); - var r = reader.getFloat32(0, true); - var g = reader.getFloat32(4, true); - var b = reader.getFloat32(8, true); //var a = reader.getFloat32(12, true); - - return new Color(r, g, b); - }; + default: + return containerFiber.child.stateNode; + } + } + function attemptSynchronousHydration(fiber) { + switch (fiber.tag) { + case HostRoot: + var root = fiber.stateNode; - this.dataAsFloat = function () { - var array = new Uint8Array(this.mData).buffer; - var reader = new DataView(array); - var r = reader.getFloat32(0, true); - return r; - }; + if (isRootDehydrated(root)) { + // Flush the first scheduled "update". + var lanes = getHighestPriorityPendingLanes(root); + flushRoot(root, lanes); + } - this.dataAsBool = function () { - var array = new Uint8Array(this.mData).buffer; - var reader = new DataView(array); - var r = reader.getFloat32(0, true); - return !!r; - }; + break; - this.dataAsString = function () { - var s = new aiString(); - s.data = this.mData; - return s.toString(); - }; + case SuspenseComponent: + var eventTime = requestEventTime(); + flushSync(function () { + return scheduleUpdateOnFiber(fiber, SyncLane, eventTime); + }); // If we're still blocked after this, we need to increase + // the priority of any promises resolving within this + // boundary so that they next attempt also has higher pri. - this.dataAsMap = function () { - var s = new aiString(); - s.data = this.mData; - var path = s.toString(); - path = path.replace(/\\/g, '/'); + var retryLane = SyncLane; + markRetryLaneIfNotHydrated(fiber, retryLane); + break; + } + } - if (path.indexOf('/') != -1) { - path = path.substr(path.lastIndexOf('/') + 1); - } + function markRetryLaneImpl(fiber, retryLane) { + var suspenseState = fiber.memoizedState; - return textureLoader.load(path); - }; - } + if (suspenseState !== null && suspenseState.dehydrated !== null) { + suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane); + } + } // Increases the priority of thenables when they resolve within this boundary. - var namePropMapping = { - '?mat.name': 'name', - '$mat.shadingm': 'shading', - '$mat.twosided': 'twoSided', - '$mat.wireframe': 'wireframe', - '$clr.ambient': 'ambient', - '$clr.diffuse': 'color', - '$clr.specular': 'specular', - '$clr.emissive': 'emissive', - '$clr.transparent': 'transparent', - '$clr.reflective': 'reflect', - '$mat.shininess': 'shininess', - '$mat.reflectivity': 'reflectivity', - '$mat.refracti': 'refraction', - '$tex.file': 'map' - }; - var nameTypeMapping = { - '?mat.name': 'string', - '$mat.shadingm': 'bool', - '$mat.twosided': 'bool', - '$mat.wireframe': 'bool', - '$clr.ambient': 'color', - '$clr.diffuse': 'color', - '$clr.specular': 'color', - '$clr.emissive': 'color', - '$clr.transparent': 'color', - '$clr.reflective': 'color', - '$mat.shininess': 'float', - '$mat.reflectivity': 'float', - '$mat.refracti': 'float', - '$tex.file': 'map' - }; - function aiMaterial() { - this.mNumAllocated = 0; - this.mNumProperties = 0; - this.mProperties = []; + function markRetryLaneIfNotHydrated(fiber, retryLane) { + markRetryLaneImpl(fiber, retryLane); + var alternate = fiber.alternate; - this.toTHREE = function () { - var mat = new MeshPhongMaterial(); + if (alternate) { + markRetryLaneImpl(alternate, retryLane); + } + } - for (let i = 0; i < this.mProperties.length; i++) { - if (nameTypeMapping[this.mProperties[i].mKey] == 'float') { - mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsFloat(); - } + function attemptContinuousHydration(fiber) { + if (fiber.tag !== SuspenseComponent) { + // We ignore HostRoots here because we can't increase + // their priority and they should not suspend on I/O, + // since you have to wrap anything that might suspend in + // Suspense. + return; + } - if (nameTypeMapping[this.mProperties[i].mKey] == 'color') { - mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsColor(); - } + var eventTime = requestEventTime(); + var lane = SelectiveHydrationLane; + scheduleUpdateOnFiber(fiber, lane, eventTime); + markRetryLaneIfNotHydrated(fiber, lane); + } + function attemptHydrationAtCurrentPriority(fiber) { + if (fiber.tag !== SuspenseComponent) { + // We ignore HostRoots here because we can't increase + // their priority other than synchronously flush it. + return; + } - if (nameTypeMapping[this.mProperties[i].mKey] == 'bool') { - mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsBool(); - } + var eventTime = requestEventTime(); + var lane = requestUpdateLane(fiber); + scheduleUpdateOnFiber(fiber, lane, eventTime); + markRetryLaneIfNotHydrated(fiber, lane); + } + function findHostInstanceWithNoPortals(fiber) { + var hostFiber = findCurrentHostFiberWithNoPortals(fiber); - if (nameTypeMapping[this.mProperties[i].mKey] == 'string') { - mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsString(); - } + if (hostFiber === null) { + return null; + } - if (nameTypeMapping[this.mProperties[i].mKey] == 'map') { - var prop = this.mProperties[i]; - if (prop.mSemantic == aiTextureType_DIFFUSE) mat.map = this.mProperties[i].dataAsMap(); - if (prop.mSemantic == aiTextureType_NORMALS) mat.normalMap = this.mProperties[i].dataAsMap(); - if (prop.mSemantic == aiTextureType_LIGHTMAP) mat.lightMap = this.mProperties[i].dataAsMap(); - if (prop.mSemantic == aiTextureType_OPACITY) mat.alphaMap = this.mProperties[i].dataAsMap(); - } - } + return hostFiber.stateNode; + } - mat.ambient.r = 0.53; - mat.ambient.g = 0.53; - mat.ambient.b = 0.53; - mat.color.r = 1; - mat.color.g = 1; - mat.color.b = 1; - return mat; - }; - } + var shouldErrorImpl = function (fiber) { + return null; + }; - function veclerp(v1, v2, l) { - var v = new Vector3(); - var lm1 = 1 - l; - v.x = v1.x * l + v2.x * lm1; - v.y = v1.y * l + v2.y * lm1; - v.z = v1.z * l + v2.z * lm1; - return v; - } + function shouldError(fiber) { + return shouldErrorImpl(fiber); + } - function quatlerp(q1, q2, l) { - return q1.clone().slerp(q2, 1 - l); - } + var shouldSuspendImpl = function (fiber) { + return false; + }; - function sampleTrack(keys, time, lne, lerp) { - if (keys.length == 1) return keys[0].mValue.toTHREE(); - var dist = Infinity; - var key = null; - var nextKey = null; + function shouldSuspend(fiber) { + return shouldSuspendImpl(fiber); + } + var overrideHookState = null; + var overrideHookStateDeletePath = null; + var overrideHookStateRenamePath = null; + var overrideProps = null; + var overridePropsDeletePath = null; + var overridePropsRenamePath = null; + var scheduleUpdate = null; + var setErrorHandler = null; + var setSuspenseHandler = null; - for (let i = 0; i < keys.length; i++) { - var timeDist = Math.abs(keys[i].mTime - time); + { + var copyWithDeleteImpl = function (obj, path, index) { + var key = path[index]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); - if (timeDist < dist && keys[i].mTime <= time) { - dist = timeDist; - key = keys[i]; - nextKey = keys[i + 1]; - } - } + if (index + 1 === path.length) { + if (isArray(updated)) { + updated.splice(key, 1); + } else { + delete updated[key]; + } - if (!key) { - return null; - } else if (nextKey) { - var dT = nextKey.mTime - key.mTime; - var T = key.mTime - time; - var l = T / dT; - return lerp(key.mValue.toTHREE(), nextKey.mValue.toTHREE(), l); - } else { - nextKey = keys[0].clone(); - nextKey.mTime += lne; - var dT = nextKey.mTime - key.mTime; - var T = key.mTime - time; - var l = T / dT; - return lerp(key.mValue.toTHREE(), nextKey.mValue.toTHREE(), l); - } - } + return updated; + } // $FlowFixMe number or string is fine here - function aiNodeAnim() { - this.mNodeName = ''; - this.mNumPositionKeys = 0; - this.mNumRotationKeys = 0; - this.mNumScalingKeys = 0; - this.mPositionKeys = []; - this.mRotationKeys = []; - this.mScalingKeys = []; - this.mPreState = ''; - this.mPostState = ''; - - this.init = function (tps) { - if (!tps) tps = 1; - - function t(t) { - t.mTime /= tps; - } - this.mPositionKeys.forEach(t); - this.mRotationKeys.forEach(t); - this.mScalingKeys.forEach(t); - }; + updated[key] = copyWithDeleteImpl(obj[key], path, index + 1); + return updated; + }; - this.sortKeys = function () { - function comp(a, b) { - return a.mTime - b.mTime; - } + var copyWithDelete = function (obj, path) { + return copyWithDeleteImpl(obj, path, 0); + }; - this.mPositionKeys.sort(comp); - this.mRotationKeys.sort(comp); - this.mScalingKeys.sort(comp); - }; + var copyWithRenameImpl = function (obj, oldPath, newPath, index) { + var oldKey = oldPath[index]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); - this.getLength = function () { - return Math.max(Math.max.apply(null, this.mPositionKeys.map(function (a) { - return a.mTime; - })), Math.max.apply(null, this.mRotationKeys.map(function (a) { - return a.mTime; - })), Math.max.apply(null, this.mScalingKeys.map(function (a) { - return a.mTime; - }))); - }; + if (index + 1 === oldPath.length) { + var newKey = newPath[index]; // $FlowFixMe number or string is fine here - this.toTHREE = function (o) { - this.sortKeys(); - var length = this.getLength(); - var track = new Virtulous.KeyFrameTrack(); - - for (let i = 0; i < length; i += 0.05) { - var matrix = new Matrix4(); - var time = i; - var pos = sampleTrack(this.mPositionKeys, time, length, veclerp); - var scale = sampleTrack(this.mScalingKeys, time, length, veclerp); - var rotation = sampleTrack(this.mRotationKeys, time, length, quatlerp); - matrix.compose(pos, rotation, scale); - var key = new Virtulous.KeyFrame(time, matrix); - track.addKey(key); - } + updated[newKey] = updated[oldKey]; - track.target = o.findNode(this.mNodeName).toTHREE(); - var tracks = [track]; + if (isArray(updated)) { + updated.splice(oldKey, 1); + } else { + delete updated[oldKey]; + } + } else { + // $FlowFixMe number or string is fine here + updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here + obj[oldKey], oldPath, newPath, index + 1); + } - if (o.nodeToBoneMap[this.mNodeName]) { - for (let i = 0; i < o.nodeToBoneMap[this.mNodeName].length; i++) { - var t2 = track.clone(); - t2.target = o.nodeToBoneMap[this.mNodeName][i]; - tracks.push(t2); - } - } + return updated; + }; - return tracks; - }; - } + var copyWithRename = function (obj, oldPath, newPath) { + if (oldPath.length !== newPath.length) { + warn('copyWithRename() expects paths of the same length'); - function aiAnimation() { - this.mName = ''; - this.mDuration = 0; - this.mTicksPerSecond = 0; - this.mNumChannels = 0; - this.mChannels = []; + return; + } else { + for (var i = 0; i < newPath.length - 1; i++) { + if (oldPath[i] !== newPath[i]) { + warn('copyWithRename() expects paths to be the same except for the deepest key'); - this.toTHREE = function (root) { - var animationHandle = new Virtulous.Animation(); + return; + } + } + } - for (let i in this.mChannels) { - this.mChannels[i].init(this.mTicksPerSecond); - var tracks = this.mChannels[i].toTHREE(root); + return copyWithRenameImpl(obj, oldPath, newPath, 0); + }; - for (let j in tracks) { - tracks[j].init(); - animationHandle.addTrack(tracks[j]); - } - } + var copyWithSetImpl = function (obj, path, index, value) { + if (index >= path.length) { + return value; + } - animationHandle.length = Math.max.apply(null, animationHandle.tracks.map(function (e) { - return e.length; - })); - return animationHandle; - }; - } + var key = path[index]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here - function aiTexture() { - this.mWidth = 0; - this.mHeight = 0; - this.texAchFormatHint = []; - this.pcData = []; - } + updated[key] = copyWithSetImpl(obj[key], path, index + 1, value); + return updated; + }; - function aiLight() { - this.mName = ''; - this.mType = 0; - this.mAttenuationConstant = 0; - this.mAttenuationLinear = 0; - this.mAttenuationQuadratic = 0; - this.mAngleInnerCone = 0; - this.mAngleOuterCone = 0; - this.mColorDiffuse = null; - this.mColorSpecular = null; - this.mColorAmbient = null; - } + var copyWithSet = function (obj, path, value) { + return copyWithSetImpl(obj, path, 0, value); + }; - function aiCamera() { - this.mName = ''; - this.mPosition = null; - this.mLookAt = null; - this.mUp = null; - this.mHorizontalFOV = 0; - this.mClipPlaneNear = 0; - this.mClipPlaneFar = 0; - this.mAspect = 0; - } + var findHook = function (fiber, id) { + // For now, the "id" of stateful hooks is just the stateful hook index. + // This may change in the future with e.g. nested hooks. + var currentHook = fiber.memoizedState; - function aiScene() { - this.versionMajor = 0; - this.versionMinor = 0; - this.versionRevision = 0; - this.compileFlags = 0; - this.mFlags = 0; - this.mNumMeshes = 0; - this.mNumMaterials = 0; - this.mNumAnimations = 0; - this.mNumTextures = 0; - this.mNumLights = 0; - this.mNumCameras = 0; - this.mRootNode = null; - this.mMeshes = []; - this.mMaterials = []; - this.mAnimations = []; - this.mLights = []; - this.mCameras = []; - this.nodeToBoneMap = {}; - - this.findNode = function (name, root) { - if (!root) { - root = this.mRootNode; - } + while (currentHook !== null && id > 0) { + currentHook = currentHook.next; + id--; + } - if (root.mName == name) { - return root; - } + return currentHook; + }; // Support DevTools editable values for useState and useReducer. - for (let i = 0; i < root.mChildren.length; i++) { - var ret = this.findNode(name, root.mChildren[i]); - if (ret) return ret; - } - return null; - }; + overrideHookState = function (fiber, id, path, value) { + var hook = findHook(fiber, id); - this.toTHREE = function () { - this.nodeCount = 0; - markBones(this); - var o = this.mRootNode.toTHREE(this); + if (hook !== null) { + var newState = copyWithSet(hook.memoizedState, path, value); + hook.memoizedState = newState; + hook.baseState = newState; // We aren't actually adding an update to the queue, + // because there is no update we can add for useReducer hooks that won't trigger an error. + // (There's no appropriate action type for DevTools overrides.) + // As a result though, React will see the scheduled update as a noop and bailout. + // Shallow cloning props works as a workaround for now to bypass the bailout check. - for (let i in this.mMeshes) this.mMeshes[i].hookupSkeletons(this); + fiber.memoizedProps = assign({}, fiber.memoizedProps); + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } + }; - if (this.mAnimations.length > 0) { - var a = this.mAnimations[0].toTHREE(this); - } + overrideHookStateDeletePath = function (fiber, id, path) { + var hook = findHook(fiber, id); - return { - object: o, - animation: a - }; - }; - } + if (hook !== null) { + var newState = copyWithDelete(hook.memoizedState, path); + hook.memoizedState = newState; + hook.baseState = newState; // We aren't actually adding an update to the queue, + // because there is no update we can add for useReducer hooks that won't trigger an error. + // (There's no appropriate action type for DevTools overrides.) + // As a result though, React will see the scheduled update as a noop and bailout. + // Shallow cloning props works as a workaround for now to bypass the bailout check. - function aiMatrix4() { - this.elements = [[], [], [], []]; + fiber.memoizedProps = assign({}, fiber.memoizedProps); + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } + }; - this.toTHREE = function () { - var m = new Matrix4(); + overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) { + var hook = findHook(fiber, id); - for (let i = 0; i < 4; ++i) { - for (let i2 = 0; i2 < 4; ++i2) { - m.elements[i * 4 + i2] = this.elements[i2][i]; - } - } + if (hook !== null) { + var newState = copyWithRename(hook.memoizedState, oldPath, newPath); + hook.memoizedState = newState; + hook.baseState = newState; // We aren't actually adding an update to the queue, + // because there is no update we can add for useReducer hooks that won't trigger an error. + // (There's no appropriate action type for DevTools overrides.) + // As a result though, React will see the scheduled update as a noop and bailout. + // Shallow cloning props works as a workaround for now to bypass the bailout check. - return m; - }; - } + fiber.memoizedProps = assign({}, fiber.memoizedProps); + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + } + }; // Support DevTools props for function components, forwardRef, memo, host components, etc. - var littleEndian = true; - function readFloat(dataview) { - var val = dataview.getFloat32(dataview.readOffset, littleEndian); - dataview.readOffset += 4; - return val; - } + overrideProps = function (fiber, path, value) { + fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); - function Read_double(dataview) { - var val = dataview.getFloat64(dataview.readOffset, littleEndian); - dataview.readOffset += 8; - return val; - } + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } - function Read_uint8_t(dataview) { - var val = dataview.getUint8(dataview.readOffset); - dataview.readOffset += 1; - return val; - } + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + }; - function Read_uint16_t(dataview) { - var val = dataview.getUint16(dataview.readOffset, littleEndian); - dataview.readOffset += 2; - return val; - } + overridePropsDeletePath = function (fiber, path) { + fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); - function Read_unsigned_int(dataview) { - var val = dataview.getUint32(dataview.readOffset, littleEndian); - dataview.readOffset += 4; - return val; - } + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } - function Read_uint32_t(dataview) { - var val = dataview.getUint32(dataview.readOffset, littleEndian); - dataview.readOffset += 4; - return val; - } + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + }; - function Read_aiVector3D(stream) { - var v = new aiVector3D(); - v.x = readFloat(stream); - v.y = readFloat(stream); - v.z = readFloat(stream); - return v; - } + overridePropsRenamePath = function (fiber, oldPath, newPath) { + fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); - function Read_aiColor3D(stream) { - var c = new aiColor3D(); - c.r = readFloat(stream); - c.g = readFloat(stream); - c.b = readFloat(stream); - return c; - } + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } - function Read_aiQuaternion(stream) { - var v = new aiQuaternion(); - v.w = readFloat(stream); - v.x = readFloat(stream); - v.y = readFloat(stream); - v.z = readFloat(stream); - return v; - } + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + }; - function Read_aiString(stream) { - var s = new aiString(); - var stringlengthbytes = Read_unsigned_int(stream); - stream.ReadBytes(s.data, 1, stringlengthbytes); - return s.toString(); - } + scheduleUpdate = function (fiber) { + scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); + }; - function Read_aiVertexWeight(stream) { - var w = new aiVertexWeight(); - w.mVertexId = Read_unsigned_int(stream); - w.mWeight = readFloat(stream); - return w; - } + setErrorHandler = function (newShouldErrorImpl) { + shouldErrorImpl = newShouldErrorImpl; + }; - function Read_aiMatrix4x4(stream) { - var m = new aiMatrix4(); + setSuspenseHandler = function (newShouldSuspendImpl) { + shouldSuspendImpl = newShouldSuspendImpl; + }; + } - for (let i = 0; i < 4; ++i) { - for (let i2 = 0; i2 < 4; ++i2) { - m.elements[i][i2] = readFloat(stream); - } - } + function findHostInstanceByFiber(fiber) { + var hostFiber = findCurrentHostFiber(fiber); - return m; - } + if (hostFiber === null) { + return null; + } - function Read_aiVectorKey(stream) { - var v = new aiVectorKey(); - v.mTime = Read_double(stream); - v.mValue = Read_aiVector3D(stream); - return v; - } + return hostFiber.stateNode; + } - function Read_aiQuatKey(stream) { - var v = new aiQuatKey(); - v.mTime = Read_double(stream); - v.mValue = Read_aiQuaternion(stream); - return v; - } + function emptyFindFiberByHostInstance(instance) { + return null; + } - function ReadArray_aiVertexWeight(stream, data, size) { - for (let i = 0; i < size; i++) data[i] = Read_aiVertexWeight(stream); - } + function getCurrentFiberForDevTools() { + return current; + } - function ReadArray_aiVectorKey(stream, data, size) { - for (let i = 0; i < size; i++) data[i] = Read_aiVectorKey(stream); - } + function injectIntoDevTools(devToolsConfig) { + var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + return injectInternals({ + bundleType: devToolsConfig.bundleType, + version: devToolsConfig.version, + rendererPackageName: devToolsConfig.rendererPackageName, + rendererConfig: devToolsConfig.rendererConfig, + overrideHookState: overrideHookState, + overrideHookStateDeletePath: overrideHookStateDeletePath, + overrideHookStateRenamePath: overrideHookStateRenamePath, + overrideProps: overrideProps, + overridePropsDeletePath: overridePropsDeletePath, + overridePropsRenamePath: overridePropsRenamePath, + setErrorHandler: setErrorHandler, + setSuspenseHandler: setSuspenseHandler, + scheduleUpdate: scheduleUpdate, + currentDispatcherRef: ReactCurrentDispatcher, + findHostInstanceByFiber: findHostInstanceByFiber, + findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, + // React Refresh + findHostInstancesForRefresh: findHostInstancesForRefresh , + scheduleRefresh: scheduleRefresh , + scheduleRoot: scheduleRoot , + setRefreshHandler: setRefreshHandler , + // Enables DevTools to append owner stacks to error messages in DEV mode. + getCurrentFiber: getCurrentFiberForDevTools , + // Enables DevTools to detect reconciler version rather than renderer version + // which may not match for third party renderers. + reconcilerVersion: ReactVersion + }); + } - function ReadArray_aiQuatKey(stream, data, size) { - for (let i = 0; i < size; i++) data[i] = Read_aiQuatKey(stream); - } + exports.attemptContinuousHydration = attemptContinuousHydration; + exports.attemptHydrationAtCurrentPriority = attemptHydrationAtCurrentPriority; + exports.attemptSynchronousHydration = attemptSynchronousHydration; + exports.batchedUpdates = batchedUpdates; + exports.createComponentSelector = createComponentSelector; + exports.createContainer = createContainer; + exports.createHasPseudoClassSelector = createHasPseudoClassSelector; + exports.createHydrationContainer = createHydrationContainer; + exports.createPortal = createPortal; + exports.createRoleSelector = createRoleSelector; + exports.createTestNameSelector = createTestNameSelector; + exports.createTextSelector = createTextSelector; + exports.deferredUpdates = deferredUpdates; + exports.discreteUpdates = discreteUpdates; + exports.findAllNodes = findAllNodes; + exports.findBoundingRects = findBoundingRects; + exports.findHostInstance = findHostInstance; + exports.findHostInstanceWithNoPortals = findHostInstanceWithNoPortals; + exports.findHostInstanceWithWarning = findHostInstanceWithWarning; + exports.flushControlled = flushControlled; + exports.flushPassiveEffects = flushPassiveEffects; + exports.flushSync = flushSync; + exports.focusWithin = focusWithin; + exports.getCurrentUpdatePriority = getCurrentUpdatePriority; + exports.getFindAllNodesFailureDescription = getFindAllNodesFailureDescription; + exports.getPublicRootInstance = getPublicRootInstance; + exports.injectIntoDevTools = injectIntoDevTools; + exports.isAlreadyRendering = isAlreadyRendering; + exports.observeVisibleRects = observeVisibleRects; + exports.registerMutableSourceForHydration = registerMutableSourceForHydration; + exports.runWithPriority = runWithPriority; + exports.shouldError = shouldError; + exports.shouldSuspend = shouldSuspend; + exports.updateContainer = updateContainer; + return exports; + }; + } + return reactReconciler_development.exports; +} - function ReadBounds(stream, T - /*p*/ - , n) { - // not sure what to do here, the data isn't really useful. - return stream.Seek(sizeof(T) * n, aiOrigin_CUR); // eslint-disable-line no-undef - } +(function (module) { - function ai_assert(bool) { - if (!bool) throw 'asset failed'; - } + if (process.env.NODE_ENV === 'production') { + module.exports = requireReactReconciler_production_min(); + } else { + module.exports = requireReactReconciler_development(); + } +} (reactReconciler)); - function ReadBinaryNode(stream, parent, depth) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AINODE); - /*uint32_t size =*/ - - Read_uint32_t(stream); - var node = new aiNode(); - node.mParent = parent; - node.mDepth = depth; - node.mName = Read_aiString(stream); - node.mTransformation = Read_aiMatrix4x4(stream); - node.mNumChildren = Read_unsigned_int(stream); - node.mNumMeshes = Read_unsigned_int(stream); - - if (node.mNumMeshes) { - node.mMeshes = []; - - for (let i = 0; i < node.mNumMeshes; ++i) { - node.mMeshes[i] = Read_unsigned_int(stream); - } - } +var Reconciler = /*@__PURE__*/getDefaultExportFromCjs(reactReconciler.exports); - if (node.mNumChildren) { - node.mChildren = []; +function shallowEqualArrays(arrA, arrB, equal = (a, b) => a === b) { + if (arrA === arrB) return true; + if (!arrA || !arrB) return false; + const len = arrA.length; + if (arrB.length !== len) return false; - for (let i = 0; i < node.mNumChildren; ++i) { - var node2 = ReadBinaryNode(stream, node, depth++); - node.mChildren[i] = node2; - } - } + for (let i = 0; i < len; i++) if (!equal(arrA[i], arrB[i])) return false; - return node; - } // ----------------------------------------------------------------------------------- + return true; +} +const globalCache = []; - function ReadBinaryBone(stream, b) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIBONE); - /*uint32_t size =*/ +function query(fn, keys, preload = false, config = {}) { + for (const entry of globalCache) { + // Find a match + if (shallowEqualArrays(keys, entry.keys, entry.equal)) { + // If we're pre-loading and the element is present, just return + if (preload) return undefined; // If an error occurred, throw - Read_uint32_t(stream); - b.mName = Read_aiString(stream); - b.mNumWeights = Read_unsigned_int(stream); - b.mOffsetMatrix = Read_aiMatrix4x4(stream); // for the moment we write dumb min/max values for the bones, too. - // maybe I'll add a better, hash-like solution later + if (Object.prototype.hasOwnProperty.call(entry, 'error')) throw entry.error; // If a response was successful, return - if (shortened) { - ReadBounds(stream, b.mWeights, b.mNumWeights); - } else { - // else write as usual - b.mWeights = []; - ReadArray_aiVertexWeight(stream, b.mWeights, b.mNumWeights); - } + if (Object.prototype.hasOwnProperty.call(entry, 'response')) return entry.response; // If the promise is still unresolved, throw - return b; + if (!preload) throw entry.promise; } + } // The request is new or has changed. - function ReadBinaryMesh(stream, mesh) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIMESH); - /*uint32_t size =*/ - - Read_uint32_t(stream); - mesh.mPrimitiveTypes = Read_unsigned_int(stream); - mesh.mNumVertices = Read_unsigned_int(stream); - mesh.mNumFaces = Read_unsigned_int(stream); - mesh.mNumBones = Read_unsigned_int(stream); - mesh.mMaterialIndex = Read_unsigned_int(stream); - mesh.mNumUVComponents = []; // first of all, write bits for all existent vertex components - - var c = Read_unsigned_int(stream); - if (c & ASSBIN_MESH_HAS_POSITIONS) { - if (shortened) { - ReadBounds(stream, mesh.mVertices, mesh.mNumVertices); - } else { - // else write as usual - mesh.mVertices = []; - mesh.mVertexBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); - stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); - } + const entry = { + keys, + equal: config.equal, + promise: // Execute the promise + fn(...keys) // When it resolves, store its value + .then(response => entry.response = response) // Remove the entry if a lifespan was given + .then(() => { + if (config.lifespan && config.lifespan > 0) { + setTimeout(() => { + const index = globalCache.indexOf(entry); + if (index !== -1) globalCache.splice(index, 1); + }, config.lifespan); } + }) // Store caught errors, they will be thrown in the render-phase to bubble into an error-bound + .catch(error => entry.error = error) + }; // Register the entry - if (c & ASSBIN_MESH_HAS_NORMALS) { - if (shortened) { - ReadBounds(stream, mesh.mNormals, mesh.mNumVertices); - } else { - // else write as usual - mesh.mNormals = []; - mesh.mNormalBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); - stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); - } - } + globalCache.push(entry); // And throw the promise, this yields control back to React - if (c & ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS) { - if (shortened) { - ReadBounds(stream, mesh.mTangents, mesh.mNumVertices); - ReadBounds(stream, mesh.mBitangents, mesh.mNumVertices); - } else { - // else write as usual - mesh.mTangents = []; - mesh.mTangentBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); - stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); - mesh.mBitangents = []; - mesh.mBitangentBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); - stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); - } - } + if (!preload) throw entry.promise; + return undefined; +} - for (let n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) { - if (!(c & ASSBIN_MESH_HAS_COLOR(n))) break; +const suspend = (fn, keys, config) => query(fn, keys, false, config); - if (shortened) { - ReadBounds(stream, mesh.mColors[n], mesh.mNumVertices); - } else { - // else write as usual - mesh.mColors[n] = []; - mesh.mColorBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 4 * 4); - stream.Seek(mesh.mNumVertices * 4 * 4, aiOrigin_CUR); - } - } +const isOrthographicCamera = def => def && def.isOrthographicCamera; // React currently throws a warning when using useLayoutEffect on the server. +// To get around it, we can conditionally useEffect on the server (no-op) and +// useLayoutEffect on the client. - mesh.mTexCoordsBuffers = []; +const isSSR$2 = typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); +const useIsomorphicLayoutEffect$1 = isSSR$2 ? React__namespace.useEffect : React__namespace.useLayoutEffect; +function useMutableCallback(fn) { + const ref = React__namespace.useRef(fn); + useIsomorphicLayoutEffect$1(() => void (ref.current = fn), [fn]); + return ref; +} +function Block({ + set +}) { + useIsomorphicLayoutEffect$1(() => { + set(new Promise(() => null)); + return () => set(false); + }, [set]); + return null; +} +class ErrorBoundary extends React__namespace.Component { + constructor(...args) { + super(...args); + this.state = { + error: false + }; + } - for (let n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) { - if (!(c & ASSBIN_MESH_HAS_TEXCOORD(n))) break; // write number of UV components + componentDidCatch(error) { + this.props.set(error); + } - mesh.mNumUVComponents[n] = Read_unsigned_int(stream); + render() { + return this.state.error ? null : this.props.children; + } - if (shortened) { - ReadBounds(stream, mesh.mTextureCoords[n], mesh.mNumVertices); - } else { - // else write as usual - mesh.mTextureCoords[n] = []; //note that assbin always writes 3d texcoords +} - mesh.mTexCoordsBuffers[n] = []; +ErrorBoundary.getDerivedStateFromError = () => ({ + error: true +}); - for (let uv = 0; uv < mesh.mNumVertices; uv++) { - mesh.mTexCoordsBuffers[n].push(readFloat(stream)); - mesh.mTexCoordsBuffers[n].push(readFloat(stream)); - readFloat(stream); - } - } - } // write faces. There are no floating-point calculations involved - // in these, so we can write a simple hash over the face data - // to the dump file. We generate a single 32 Bit hash for 512 faces - // using Assimp's standard hashing function. +const DEFAULT = '__default'; +const isDiffSet = def => def && !!def.memoized && !!def.changes; +function calculateDpr(dpr) { + return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], window.devicePixelRatio), dpr[1]) : dpr; +} +/** + * Returns instance root state + */ +const getRootState = obj => { + var _r3f; - if (shortened) { - Read_unsigned_int(stream); - } else { - // else write as usual - // if there are less than 2^16 vertices, we can simply use 16 bit integers ... - mesh.mFaces = []; - mesh.mIndexArray = []; + return (_r3f = obj.__r3f) == null ? void 0 : _r3f.root.getState(); +}; +// A collection of compare functions +const is$1 = { + obj: a => a === Object(a) && !is$1.arr(a) && typeof a !== 'function', + fun: a => typeof a === 'function', + str: a => typeof a === 'string', + num: a => typeof a === 'number', + boo: a => typeof a === 'boolean', + und: a => a === void 0, + arr: a => Array.isArray(a), - for (let i = 0; i < mesh.mNumFaces; ++i) { - var f = mesh.mFaces[i] = new aiFace(); // BOOST_STATIC_ASSERT(AI_MAX_FACE_INDICES <= 0xffff); + equ(a, b, { + arrays = 'shallow', + objects = 'reference', + strict = true + } = {}) { + // Wrong type or one of the two undefined, doesn't match + if (typeof a !== typeof b || !!a !== !!b) return false; // Atomic, just compare a against b - f.mNumIndices = Read_uint16_t(stream); - f.mIndices = []; + if (is$1.str(a) || is$1.num(a)) return a === b; + const isObj = is$1.obj(a); + if (isObj && objects === 'reference') return a === b; + const isArr = is$1.arr(a); + if (isArr && arrays === 'reference') return a === b; // Array or Object, shallow compare first to see if it's a match - for (let a = 0; a < f.mNumIndices; ++a) { - if (mesh.mNumVertices < 1 << 16) { - f.mIndices[a] = Read_uint16_t(stream); - } else { - f.mIndices[a] = Read_unsigned_int(stream); - } - } + if ((isArr || isObj) && a === b) return true; // Last resort, go through keys - if (f.mNumIndices === 3) { - mesh.mIndexArray.push(f.mIndices[0]); - mesh.mIndexArray.push(f.mIndices[1]); - mesh.mIndexArray.push(f.mIndices[2]); - } else if (f.mNumIndices === 4) { - mesh.mIndexArray.push(f.mIndices[0]); - mesh.mIndexArray.push(f.mIndices[1]); - mesh.mIndexArray.push(f.mIndices[2]); - mesh.mIndexArray.push(f.mIndices[2]); - mesh.mIndexArray.push(f.mIndices[3]); - mesh.mIndexArray.push(f.mIndices[0]); - } else { - throw new Error("Sorry, can't currently triangulate polys. Use the triangulate preprocessor in Assimp."); - } - } - } // write bones + let i; + for (i in a) if (!(i in b)) return false; - if (mesh.mNumBones) { - mesh.mBones = []; + for (i in strict ? b : a) if (a[i] !== b[i]) return false; - for (let a = 0; a < mesh.mNumBones; ++a) { - mesh.mBones[a] = new aiBone(); - ReadBinaryBone(stream, mesh.mBones[a]); - } - } + if (is$1.und(i)) { + if (isArr && a.length === 0 && b.length === 0) return true; + if (isObj && Object.keys(a).length === 0 && Object.keys(b).length === 0) return true; + if (a !== b) return false; } - function ReadBinaryMaterialProperty(stream, prop) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIMATERIALPROPERTY); - /*uint32_t size =*/ - - Read_uint32_t(stream); - prop.mKey = Read_aiString(stream); - prop.mSemantic = Read_unsigned_int(stream); - prop.mIndex = Read_unsigned_int(stream); - prop.mDataLength = Read_unsigned_int(stream); - prop.mType = Read_unsigned_int(stream); - prop.mData = []; - stream.ReadBytes(prop.mData, 1, prop.mDataLength); - } // ----------------------------------------------------------------------------------- - - - function ReadBinaryMaterial(stream, mat) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIMATERIAL); - /*uint32_t size =*/ - - Read_uint32_t(stream); - mat.mNumAllocated = mat.mNumProperties = Read_unsigned_int(stream); - - if (mat.mNumProperties) { - if (mat.mProperties) { - delete mat.mProperties; - } + return true; + } - mat.mProperties = []; +}; // Collects nodes and materials from a THREE.Object3D - for (let i = 0; i < mat.mNumProperties; ++i) { - mat.mProperties[i] = new aiMaterialProperty(); - ReadBinaryMaterialProperty(stream, mat.mProperties[i]); - } - } - } +function dispose(obj) { + if (obj.dispose && obj.type !== 'Scene') obj.dispose(); - function ReadBinaryNodeAnim(stream, nd) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AINODEANIM); - /*uint32_t size =*/ - - Read_uint32_t(stream); - nd.mNodeName = Read_aiString(stream); - nd.mNumPositionKeys = Read_unsigned_int(stream); - nd.mNumRotationKeys = Read_unsigned_int(stream); - nd.mNumScalingKeys = Read_unsigned_int(stream); - nd.mPreState = Read_unsigned_int(stream); - nd.mPostState = Read_unsigned_int(stream); - - if (nd.mNumPositionKeys) { - if (shortened) { - ReadBounds(stream, nd.mPositionKeys, nd.mNumPositionKeys); - } else { - // else write as usual - nd.mPositionKeys = []; - ReadArray_aiVectorKey(stream, nd.mPositionKeys, nd.mNumPositionKeys); - } - } + for (const p in obj) { + p.dispose == null ? void 0 : p.dispose(); + delete obj[p]; + } +} // Each object in the scene carries a small LocalState descriptor - if (nd.mNumRotationKeys) { - if (shortened) { - ReadBounds(stream, nd.mRotationKeys, nd.mNumRotationKeys); - } else { - // else write as usual - nd.mRotationKeys = []; - ReadArray_aiQuatKey(stream, nd.mRotationKeys, nd.mNumRotationKeys); - } - } +function prepare(object, state) { + const instance = object; - if (nd.mNumScalingKeys) { - if (shortened) { - ReadBounds(stream, nd.mScalingKeys, nd.mNumScalingKeys); - } else { - // else write as usual - nd.mScalingKeys = []; - ReadArray_aiVectorKey(stream, nd.mScalingKeys, nd.mNumScalingKeys); - } - } - } + if (state != null && state.primitive || !instance.__r3f) { + instance.__r3f = { + type: '', + root: null, + previousAttach: null, + memoizedProps: {}, + eventCount: 0, + handlers: {}, + objects: [], + parent: null, + ...state + }; + } - function ReadBinaryAnim(stream, anim) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AIANIMATION); - /*uint32_t size =*/ + return object; +} + +function resolve(instance, key) { + let target = instance; - Read_uint32_t(stream); - anim.mName = Read_aiString(stream); - anim.mDuration = Read_double(stream); - anim.mTicksPerSecond = Read_double(stream); - anim.mNumChannels = Read_unsigned_int(stream); + if (key.includes('-')) { + const entries = key.split('-'); + const last = entries.pop(); + target = entries.reduce((acc, key) => acc[key], instance); + return { + target, + key: last + }; + } else return { + target, + key + }; +} // Checks if a dash-cased string ends with an integer - if (anim.mNumChannels) { - anim.mChannels = []; - for (let a = 0; a < anim.mNumChannels; ++a) { - anim.mChannels[a] = new aiNodeAnim(); - ReadBinaryNodeAnim(stream, anim.mChannels[a]); - } - } +const INDEX_REGEX = /-\d+$/; +function attach(parent, child, type) { + if (is$1.str(type)) { + // If attaching into an array (foo-0), create one + if (INDEX_REGEX.test(type)) { + const root = type.replace(INDEX_REGEX, ''); + const { + target, + key + } = resolve(parent, root); + if (!Array.isArray(target[key])) target[key] = []; } - function ReadBinaryTexture(stream, tex) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AITEXTURE); - /*uint32_t size =*/ + const { + target, + key + } = resolve(parent, type); + child.__r3f.previousAttach = target[key]; + target[key] = child; + } else child.__r3f.previousAttach = type(parent, child); +} +function detach(parent, child, type) { + var _child$__r3f, _child$__r3f2; - Read_uint32_t(stream); - tex.mWidth = Read_unsigned_int(stream); - tex.mHeight = Read_unsigned_int(stream); - stream.ReadBytes(tex.achFormatHint, 1, 4); + if (is$1.str(type)) { + const { + target, + key + } = resolve(parent, type); + const previous = child.__r3f.previousAttach; // When the previous value was undefined, it means the value was never set to begin with - if (!shortened) { - if (!tex.mHeight) { - tex.pcData = []; - stream.ReadBytes(tex.pcData, 1, tex.mWidth); - } else { - tex.pcData = []; - stream.ReadBytes(tex.pcData, 1, tex.mWidth * tex.mHeight * 4); - } - } - } + if (previous === undefined) delete target[key]; // Otherwise set the previous value + else target[key] = previous; + } else (_child$__r3f = child.__r3f) == null ? void 0 : _child$__r3f.previousAttach == null ? void 0 : _child$__r3f.previousAttach(parent, child); - function ReadBinaryLight(stream, l) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AILIGHT); - /*uint32_t size =*/ + (_child$__r3f2 = child.__r3f) == null ? true : delete _child$__r3f2.previousAttach; +} // This function prepares a set of changes to be applied to the instance - Read_uint32_t(stream); - l.mName = Read_aiString(stream); - l.mType = Read_unsigned_int(stream); +function diffProps(instance, { + children: cN, + key: kN, + ref: rN, + ...props +}, { + children: cP, + key: kP, + ref: rP, + ...previous +} = {}, remove = false) { + var _instance$__r3f; - if (l.mType != aiLightSource_DIRECTIONAL) { - l.mAttenuationConstant = readFloat(stream); - l.mAttenuationLinear = readFloat(stream); - l.mAttenuationQuadratic = readFloat(stream); - } + const localState = (_instance$__r3f = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f : {}; + const entries = Object.entries(props); + const changes = []; // Catch removed props, prepend them so they can be reset or removed - l.mColorDiffuse = Read_aiColor3D(stream); - l.mColorSpecular = Read_aiColor3D(stream); - l.mColorAmbient = Read_aiColor3D(stream); + if (remove) { + const previousKeys = Object.keys(previous); - if (l.mType == aiLightSource_SPOT) { - l.mAngleInnerCone = readFloat(stream); - l.mAngleOuterCone = readFloat(stream); - } + for (let i = 0; i < previousKeys.length; i++) { + if (!props.hasOwnProperty(previousKeys[i])) entries.unshift([previousKeys[i], DEFAULT + 'remove']); } + } - function ReadBinaryCamera(stream, cam) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AICAMERA); - /*uint32_t size =*/ - - Read_uint32_t(stream); - cam.mName = Read_aiString(stream); - cam.mPosition = Read_aiVector3D(stream); - cam.mLookAt = Read_aiVector3D(stream); - cam.mUp = Read_aiVector3D(stream); - cam.mHorizontalFOV = readFloat(stream); - cam.mClipPlaneNear = readFloat(stream); - cam.mClipPlaneFar = readFloat(stream); - cam.mAspect = readFloat(stream); - } + entries.forEach(([key, value]) => { + var _instance$__r3f2; - function ReadBinaryScene(stream, scene) { - var chunkID = Read_uint32_t(stream); - ai_assert(chunkID == ASSBIN_CHUNK_AISCENE); - /*uint32_t size =*/ - - Read_uint32_t(stream); - scene.mFlags = Read_unsigned_int(stream); - scene.mNumMeshes = Read_unsigned_int(stream); - scene.mNumMaterials = Read_unsigned_int(stream); - scene.mNumAnimations = Read_unsigned_int(stream); - scene.mNumTextures = Read_unsigned_int(stream); - scene.mNumLights = Read_unsigned_int(stream); - scene.mNumCameras = Read_unsigned_int(stream); // Read node graph - - scene.mRootNode = new aiNode(); - scene.mRootNode = ReadBinaryNode(stream, null, 0); // Read all meshes - - if (scene.mNumMeshes) { - scene.mMeshes = []; - - for (let i = 0; i < scene.mNumMeshes; ++i) { - scene.mMeshes[i] = new aiMesh(); - ReadBinaryMesh(stream, scene.mMeshes[i]); - } - } // Read materials + // Bail out on primitive object + if ((_instance$__r3f2 = instance.__r3f) != null && _instance$__r3f2.primitive && key === 'object') return; // When props match bail out + if (is$1.equ(value, previous[key])) return; // Collect handlers and bail out - if (scene.mNumMaterials) { - scene.mMaterials = []; + if (/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key)) return changes.push([key, value, true, []]); // Split dashed props - for (let i = 0; i < scene.mNumMaterials; ++i) { - scene.mMaterials[i] = new aiMaterial(); - ReadBinaryMaterial(stream, scene.mMaterials[i]); - } - } // Read all animations + let entries = []; + if (key.includes('-')) entries = key.split('-'); + changes.push([key, value, false, entries]); + }); + const memoized = { ...props + }; + if (localState.memoizedProps && localState.memoizedProps.args) memoized.args = localState.memoizedProps.args; + if (localState.memoizedProps && localState.memoizedProps.attach) memoized.attach = localState.memoizedProps.attach; + return { + memoized, + changes + }; +} // This function applies a set of changes to the instance +function applyProps$1(instance, data) { + var _instance$__r3f3, _root$getState; - if (scene.mNumAnimations) { - scene.mAnimations = []; + // Filter equals, events and reserved props + const localState = (_instance$__r3f3 = instance.__r3f) != null ? _instance$__r3f3 : {}; + const root = localState.root; + const rootState = (_root$getState = root == null ? void 0 : root.getState == null ? void 0 : root.getState()) != null ? _root$getState : {}; + const { + memoized, + changes + } = isDiffSet(data) ? data : diffProps(instance, data); + const prevHandlers = localState.eventCount; // Prepare memoized props - for (let i = 0; i < scene.mNumAnimations; ++i) { - scene.mAnimations[i] = new aiAnimation(); - ReadBinaryAnim(stream, scene.mAnimations[i]); - } - } // Read all textures + if (instance.__r3f) instance.__r3f.memoizedProps = memoized; + changes.forEach(([key, value, isEvent, keys]) => { + let currentInstance = instance; + let targetProp = currentInstance[key]; // Revolve dashed props + if (keys.length) { + targetProp = keys.reduce((acc, key) => acc[key], instance); // If the target is atomic, it forces us to switch the root - if (scene.mNumTextures) { - scene.mTextures = []; + if (!(targetProp && targetProp.set)) { + const [name, ...reverseEntries] = keys.reverse(); + currentInstance = reverseEntries.reverse().reduce((acc, key) => acc[key], instance); + key = name; + } + } // https://github.com/mrdoob/three.js/issues/21209 + // HMR/fast-refresh relies on the ability to cancel out props, but threejs + // has no means to do this. Hence we curate a small collection of value-classes + // with their respective constructor/set arguments + // For removed props, try to set default values, if possible - for (let i = 0; i < scene.mNumTextures; ++i) { - scene.mTextures[i] = new aiTexture(); - ReadBinaryTexture(stream, scene.mTextures[i]); - } - } // Read lights + if (value === DEFAULT + 'remove') { + if (targetProp && targetProp.constructor) { + var _memoized$args; - if (scene.mNumLights) { - scene.mLights = []; + // use the prop constructor to find the default it should be + value = new targetProp.constructor(...((_memoized$args = memoized.args) != null ? _memoized$args : [])); + } else if (currentInstance.constructor) { + var _currentInstance$__r; - for (let i = 0; i < scene.mNumLights; ++i) { - scene.mLights[i] = new aiLight(); - ReadBinaryLight(stream, scene.mLights[i]); - } - } // Read cameras + // create a blank slate of the instance and copy the particular parameter. + // @ts-ignore + const defaultClassCall = new currentInstance.constructor(...((_currentInstance$__r = currentInstance.__r3f.memoizedProps.args) != null ? _currentInstance$__r : [])); + value = defaultClassCall[targetProp]; // destory the instance + if (defaultClassCall.dispose) defaultClassCall.dispose(); // instance does not have constructor, just set it to 0 + } else { + value = 0; + } + } // Deal with pointer events ... - if (scene.mNumCameras) { - scene.mCameras = []; - for (let i = 0; i < scene.mNumCameras; ++i) { - scene.mCameras[i] = new aiCamera(); - ReadBinaryCamera(stream, scene.mCameras[i]); - } + if (isEvent) { + if (value) localState.handlers[key] = value;else delete localState.handlers[key]; + localState.eventCount = Object.keys(localState.handlers).length; + } // Special treatment for objects with support for set/copy, and layers + else if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof Layers)) { + // If value is an array + if (Array.isArray(value)) { + if (targetProp.fromArray) targetProp.fromArray(value);else targetProp.set(...value); + } // Test again target.copy(class) next ... + else if (targetProp.copy && value && value.constructor && targetProp.constructor.name === value.constructor.name) { + targetProp.copy(value); + } // If nothing else fits, just set the single value, ignore undefined + // https://github.com/pmndrs/react-three-fiber/issues/274 + else if (value !== undefined) { + const isColor = targetProp instanceof Color; // Allow setting array scalars + + if (!isColor && targetProp.setScalar) targetProp.setScalar(value); // Layers have no copy function, we must therefore copy the mask property + else if (targetProp instanceof Layers && value instanceof Layers) targetProp.mask = value.mask; // Otherwise just set ... + else targetProp.set(value); // For versions of three which don't support THREE.ColorManagement, + // Auto-convert sRGB colors + // https://github.com/pmndrs/react-three-fiber/issues/344 + + const supportsColorManagement = ('ColorManagement' in THREE); + if (!supportsColorManagement && !rootState.linear && isColor) targetProp.convertSRGBToLinear(); + } // Else, just overwrite the value + + } else { + currentInstance[key] = value; // Auto-convert sRGB textures, for now ... + // https://github.com/pmndrs/react-three-fiber/issues/344 + + if (!rootState.linear && currentInstance[key] instanceof Texture) { + currentInstance[key].encoding = sRGBEncoding; } } - var aiOrigin_CUR = 0; - var aiOrigin_BEG = 1; - - function extendStream(stream) { - stream.readOffset = 0; + invalidateInstance(instance); + }); - stream.Seek = function (off, ori) { - if (ori == aiOrigin_CUR) { - stream.readOffset += off; - } + if (localState.parent && rootState.internal && instance.raycast && prevHandlers !== localState.eventCount) { + // Pre-emptively remove the instance from the interaction manager + const index = rootState.internal.interaction.indexOf(instance); + if (index > -1) rootState.internal.interaction.splice(index, 1); // Add the instance to the interaction manager only when it has handlers - if (ori == aiOrigin_BEG) { - stream.readOffset = off; - } - }; + if (localState.eventCount) rootState.internal.interaction.push(instance); + } // Call the update lifecycle when it is being updated, but only when it is part of the scene - stream.ReadBytes = function (buff, size, n) { - var bytes = size * n; - for (let i = 0; i < bytes; i++) buff[i] = Read_uint8_t(this); - }; + if (changes.length && instance.parent) updateInstance(instance); + return instance; +} +function invalidateInstance(instance) { + var _instance$__r3f4, _instance$__r3f4$root; - stream.subArray32 = function (start, end) { - var buff = this.buffer; - var newbuff = buff.slice(start, end); - return new Float32Array(newbuff); - }; + const state = (_instance$__r3f4 = instance.__r3f) == null ? void 0 : (_instance$__r3f4$root = _instance$__r3f4.root) == null ? void 0 : _instance$__r3f4$root.getState == null ? void 0 : _instance$__r3f4$root.getState(); + if (state && state.internal.frames === 0) state.invalidate(); +} +function updateInstance(instance) { + instance.onUpdate == null ? void 0 : instance.onUpdate(instance); +} +function updateCamera(camera, size) { + // https://github.com/pmndrs/react-three-fiber/issues/92 + // Do not mess with the camera if it belongs to the user + if (!camera.manual) { + if (isOrthographicCamera(camera)) { + camera.left = size.width / -2; + camera.right = size.width / 2; + camera.top = size.height / 2; + camera.bottom = size.height / -2; + } else { + camera.aspect = size.width / size.height; + } - stream.subArrayUint16 = function (start, end) { - var buff = this.buffer; - var newbuff = buff.slice(start, end); - return new Uint16Array(newbuff); - }; + camera.updateProjectionMatrix(); // https://github.com/pmndrs/react-three-fiber/issues/178 + // Update matrix world since the renderer is a frame late - stream.subArrayUint8 = function (start, end) { - var buff = this.buffer; - var newbuff = buff.slice(start, end); - return new Uint8Array(newbuff); - }; + camera.updateMatrixWorld(); + } +} +/** + * Safely sets a deeply-nested value on an object. + */ - stream.subArrayUint32 = function (start, end) { - var buff = this.buffer; - var newbuff = buff.slice(start, end); - return new Uint32Array(newbuff); - }; - } +function setDeep(obj, value, keys) { + const key = keys.pop(); + const target = keys.reduce((acc, key) => acc[key], obj); + return target[key] = value; +} - var shortened, compressed; +function makeId(event) { + return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId; +} // https://github.com/facebook/react/tree/main/packages/react-reconciler#getcurrenteventpriority +// Gives React a clue as to how import the current interaction is - function InternReadFile(pFiledata) { - var pScene = new aiScene(); - var stream = new DataView(pFiledata); - extendStream(stream); - stream.Seek(44, aiOrigin_CUR); // signature - /*unsigned int versionMajor =*/ +function getEventPriority() { + var _window, _window$event; - pScene.versionMajor = Read_unsigned_int(stream); - /*unsigned int versionMinor =*/ + let name = (_window = window) == null ? void 0 : (_window$event = _window.event) == null ? void 0 : _window$event.type; - pScene.versionMinor = Read_unsigned_int(stream); - /*unsigned int versionRevision =*/ + switch (name) { + case 'click': + case 'contextmenu': + case 'dblclick': + case 'pointercancel': + case 'pointerdown': + case 'pointerup': + return constants.exports.DiscreteEventPriority; - pScene.versionRevision = Read_unsigned_int(stream); - /*unsigned int compileFlags =*/ + case 'pointermove': + case 'pointerout': + case 'pointerover': + case 'pointerenter': + case 'pointerleave': + case 'wheel': + return constants.exports.ContinuousEventPriority; - pScene.compileFlags = Read_unsigned_int(stream); - shortened = Read_uint16_t(stream) > 0; - compressed = Read_uint16_t(stream) > 0; - if (shortened) throw 'Shortened binaries are not supported!'; - stream.Seek(256, aiOrigin_CUR); // original filename + default: + return constants.exports.DefaultEventPriority; + } +} +/** + * Release pointer captures. + * This is called by releasePointerCapture in the API, and when an object is removed. + */ - stream.Seek(128, aiOrigin_CUR); // options +function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) { + const captureData = captures.get(obj); - stream.Seek(64, aiOrigin_CUR); // padding + if (captureData) { + captures.delete(obj); // If this was the last capturing object for this pointer - if (compressed) { - var uncompressedSize = Read_uint32_t(stream); - var compressedSize = stream.FileSize() - stream.Tell(); - var compressedData = []; - stream.Read(compressedData, 1, compressedSize); - var uncompressedData = []; - uncompress(uncompressedData, uncompressedSize, compressedData, compressedSize); // eslint-disable-line no-undef + if (captures.size === 0) { + capturedMap.delete(pointerId); + captureData.target.releasePointerCapture(pointerId); + } + } +} - var buff = new ArrayBuffer(uncompressedData); - ReadBinaryScene(buff, pScene); - } else { - ReadBinaryScene(stream, pScene); - } +function removeInteractivity(store, object) { + const { + internal + } = store.getState(); // Removes every trace of an object from the data store - return pScene.toTHREE(); + internal.interaction = internal.interaction.filter(o => o !== object); + internal.initialHits = internal.initialHits.filter(o => o !== object); + internal.hovered.forEach((value, key) => { + if (value.eventObject === object || value.object === object) { + // Clear out intersects, they are outdated by now + internal.hovered.delete(key); } + }); + internal.capturedMap.forEach((captures, pointerId) => { + releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId); + }); +} +function createEvents(store) { + const temp = new Vector3(); + /** Calculates delta */ - return InternReadFile(buffer); + function calculateDistance(event) { + const { + internal + } = store.getState(); + const dx = event.offsetX - internal.initialClick[0]; + const dy = event.offsetY - internal.initialClick[1]; + return Math.round(Math.sqrt(dx * dx + dy * dy)); } -}); - -new Vector3(); + /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */ -new Vector3(); -new Ray(); + function filterPointerEvents(objects) { + return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => { + var _r3f; -function LWO3Parser(IFFParser) { - this.IFF = IFFParser; -} + return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers['onPointer' + name]; + })); + } -LWO3Parser.prototype = { - constructor: LWO3Parser, - parseBlock: function () { - this.IFF.debugger.offset = this.IFF.reader.offset; - this.IFF.debugger.closeForms(); - var blockID = this.IFF.reader.getIDTag(); - var length = this.IFF.reader.getUint32(); // size of data in bytes + function intersect(event, filter) { + const state = store.getState(); + const duplicates = new Set(); + const intersections = []; // Allow callers to eliminate event objects - this.IFF.debugger.dataOffset = this.IFF.reader.offset; - this.IFF.debugger.length = length; // Data types may be found in either LWO2 OR LWO3 spec + const eventsObjects = filter ? filter(state.internal.interaction) : state.internal.interaction; // Reset all raycaster cameras to undefined - switch (blockID) { - case 'FORM': - // form blocks may consist of sub -chunks or sub-forms - this.IFF.parseForm(length); - break; - // SKIPPED CHUNKS - // MISC skipped - - case 'ICON': // Thumbnail Icon Image - - case 'VMPA': // Vertex Map Parameter - - case 'BBOX': // bounding box - // case 'VMMD': - // case 'VTYP': - // normal maps can be specified, normally on models imported from other applications. Currently ignored - - case 'NORM': // ENVL FORM skipped - - case 'PRE ': - case 'POST': - case 'KEY ': - case 'SPAN': // CLIP FORM skipped - - case 'TIME': - case 'CLRS': - case 'CLRA': - case 'FILT': - case 'DITH': - case 'CONT': - case 'BRIT': - case 'SATR': - case 'HUE ': - case 'GAMM': - case 'NEGA': - case 'IFLT': - case 'PFLT': // Image Map Layer skipped - - case 'PROJ': - case 'AXIS': - case 'AAST': - case 'PIXB': - case 'STCK': // Procedural Textures skipped - - case 'VALU': // Gradient Textures skipped - - case 'PNAM': - case 'INAM': - case 'GRST': - case 'GREN': - case 'GRPT': - case 'FKEY': - case 'IKEY': // Texture Mapping Form skipped - - case 'CSYS': // Surface CHUNKs skipped - - case 'OPAQ': // top level 'opacity' checkbox - - case 'CMAP': // clip map - // Surface node CHUNKS skipped - // These mainly specify the node editor setup in LW - - case 'NLOC': - case 'NZOM': - case 'NVER': - case 'NSRV': - case 'NCRD': - case 'NMOD': - case 'NSEL': - case 'NPRW': - case 'NPLA': - case 'VERS': - case 'ENUM': - case 'TAG ': // Car Material CHUNKS - - case 'CGMD': - case 'CGTY': - case 'CGST': - case 'CGEN': - case 'CGTS': - case 'CGTE': - case 'OSMP': - case 'OMDE': - case 'OUTR': - case 'FLAG': - case 'TRNL': - case 'SHRP': - case 'RFOP': - case 'RSAN': - case 'TROP': - case 'RBLR': - case 'TBLR': - case 'CLRH': - case 'CLRF': - case 'ADTR': - case 'GLOW': - case 'LINE': - case 'ALPH': - case 'VCOL': - case 'ENAB': - this.IFF.debugger.skipped = true; - this.IFF.reader.skip(length); - break; - // Texture node chunks (not in spec) + eventsObjects.forEach(obj => { + const state = getRootState(obj); - case 'IPIX': // usePixelBlending + if (state) { + state.raycaster.camera = undefined; + } + }); - case 'IMIP': // useMipMaps + if (!state.previousRoot) { + // Make sure root-level pointer and ray are set up + state.events.compute == null ? void 0 : state.events.compute(event, state); + } // Collect events - case 'IMOD': // imageBlendingMode - case 'AMOD': // unknown + let hits = eventsObjects // Intersect objects + .flatMap(obj => { + const state = getRootState(obj); // Skip event handling when noEvents is set, or when the raycasters camera is null - case 'IINV': // imageInvertAlpha + if (!state || !state.events.enabled || state.raycaster.camera === null) return []; // When the camera is undefined we have to call the event layers update function - case 'INCR': // imageInvertColor + if (state.raycaster.camera === undefined) { + var _state$previousRoot; - case 'IAXS': // imageAxis ( for non-UV maps) + state.events.compute == null ? void 0 : state.events.compute(event, state, (_state$previousRoot = state.previousRoot) == null ? void 0 : _state$previousRoot.getState()); // If the camera is still undefined we have to skip this layer entirely - case 'IFOT': // imageFallofType + if (state.raycaster.camera === undefined) state.raycaster.camera = null; + } // Intersect object by object - case 'ITIM': // timing for animated textures - case 'IWRL': - case 'IUTI': - case 'IINX': - case 'IINY': - case 'IINZ': - case 'IREF': - // possibly a VX for reused texture nodes - if (length === 4) this.IFF.currentNode[blockID] = this.IFF.reader.getInt32();else this.IFF.reader.skip(length); - break; + return state.raycaster.camera ? state.raycaster.intersectObject(obj, true) : []; + }) // Sort by event priority and distance + .sort((a, b) => { + const aState = getRootState(a.object); + const bState = getRootState(b.object); + if (!aState || !bState) return 0; + return bState.events.priority - aState.events.priority || a.distance - b.distance; + }) // Filter out duplicates + .filter(item => { + const id = makeId(item); + if (duplicates.has(id)) return false; + duplicates.add(id); + return true; + }); // https://github.com/mrdoob/three.js/issues/16031 + // Allow custom userland intersect sort order, this likely only makes sense on the root filter - case 'OTAG': - this.IFF.parseObjectTag(); - break; + if (state.events.filter) hits = state.events.filter(hits, state); // Bubble up the events, find the event source (eventObject) - case 'LAYR': - this.IFF.parseLayer(length); - break; + for (const hit of hits) { + let eventObject = hit.object; // Bubble event up - case 'PNTS': - this.IFF.parsePoints(length); - break; + while (eventObject) { + var _r3f2; - case 'VMAP': - this.IFF.parseVertexMapping(length); - break; + if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({ ...hit, + eventObject + }); + eventObject = eventObject.parent; + } + } // If the interaction is captured, make all capturing targets part of the intersect. - case 'POLS': - this.IFF.parsePolygonList(length); - break; - case 'TAGS': - this.IFF.parseTagStrings(length); - break; + if ('pointerId' in event && state.internal.capturedMap.has(event.pointerId)) { + for (let captureData of state.internal.capturedMap.get(event.pointerId).values()) { + intersections.push(captureData.intersection); + } + } - case 'PTAG': - this.IFF.parsePolygonTagMapping(length); - break; + return intersections; + } + /** Handles intersections by forwarding them to handlers */ - case 'VMAD': - this.IFF.parseVertexMapping(length, true); - break; - // Misc CHUNKS - case 'DESC': - // Description Line - this.IFF.currentForm.description = this.IFF.reader.getString(); - break; + function handleIntersects(intersections, event, delta, callback) { + const { + raycaster, + pointer, + camera, + internal + } = store.getState(); // If anything has been found, forward it to the event listeners - case 'TEXT': - case 'CMNT': - case 'NCOM': - this.IFF.currentForm.comment = this.IFF.reader.getString(); - break; - // Envelope Form + if (intersections.length) { + const unprojectedPoint = temp.set(pointer.x, pointer.y, 0).unproject(camera); + const localState = { + stopped: false + }; - case 'NAME': - this.IFF.currentForm.channelName = this.IFF.reader.getString(); - break; - // Image Map Layer + for (const hit of intersections) { + const hasPointerCapture = id => { + var _internal$capturedMap, _internal$capturedMap2; - case 'WRAP': - this.IFF.currentForm.wrap = { - w: this.IFF.reader.getUint16(), - h: this.IFF.reader.getUint16() + return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false; }; - break; - - case 'IMAG': - var index = this.IFF.reader.getVariableLengthIndex(); - this.IFF.currentForm.imageIndex = index; - break; - // Texture Mapping Form - - case 'OREF': - this.IFF.currentForm.referenceObject = this.IFF.reader.getString(); - break; - - case 'ROID': - this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32(); - break; - // Surface Blocks - case 'SSHN': - this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString(); - break; + const setPointerCapture = id => { + const captureData = { + intersection: hit, + target: event.target + }; - case 'AOVN': - this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString(); - break; - // Nodal Blocks + if (internal.capturedMap.has(id)) { + // if the pointerId was previously captured, we add the hit to the + // event capturedMap. + internal.capturedMap.get(id).set(hit.eventObject, captureData); + } else { + // if the pointerId was not previously captured, we create a map + // containing the hitObject, and the hit. hitObject is used for + // faster access. + internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]])); + } // Call the original event now + event.target.setPointerCapture(id); + }; - case 'NSTA': - this.IFF.currentForm.disabled = this.IFF.reader.getUint16(); - break; + const releasePointerCapture = id => { + const captures = internal.capturedMap.get(id); - case 'NRNM': - this.IFF.currentForm.realName = this.IFF.reader.getString(); - break; + if (captures) { + releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id); + } + }; // Add native event props - case 'NNME': - this.IFF.currentForm.refName = this.IFF.reader.getString(); - this.IFF.currentSurface.nodes[this.IFF.currentForm.refName] = this.IFF.currentForm; - break; - // Nodal Blocks : connections - case 'INME': - if (!this.IFF.currentForm.nodeName) this.IFF.currentForm.nodeName = []; - this.IFF.currentForm.nodeName.push(this.IFF.reader.getString()); - break; + let extractEventProps = {}; // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones. - case 'IINN': - if (!this.IFF.currentForm.inputNodeName) this.IFF.currentForm.inputNodeName = []; - this.IFF.currentForm.inputNodeName.push(this.IFF.reader.getString()); - break; + for (let prop in event) { + let property = event[prop]; // Only copy over atomics, leave functions alone as these should be + // called as event.nativeEvent.fn() - case 'IINM': - if (!this.IFF.currentForm.inputName) this.IFF.currentForm.inputName = []; - this.IFF.currentForm.inputName.push(this.IFF.reader.getString()); - break; + if (typeof property !== 'function') extractEventProps[prop] = property; + } - case 'IONM': - if (!this.IFF.currentForm.inputOutputName) this.IFF.currentForm.inputOutputName = []; - this.IFF.currentForm.inputOutputName.push(this.IFF.reader.getString()); - break; + let raycastEvent = { ...hit, + ...extractEventProps, + pointer, + intersections, + stopped: localState.stopped, + delta, + unprojectedPoint, + ray: raycaster.ray, + camera: camera, + // Hijack stopPropagation, which just sets a flag + stopPropagation: () => { + // https://github.com/pmndrs/react-three-fiber/issues/596 + // Events are not allowed to stop propagation if the pointer has been captured + const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId); // We only authorize stopPropagation... - case 'FNAM': - this.IFF.currentForm.fileName = this.IFF.reader.getString(); - break; + if ( // ...if this pointer hasn't been captured + !capturesForPointer || // ... or if the hit object is capturing the pointer + capturesForPointer.has(hit.eventObject)) { + raycastEvent.stopped = localState.stopped = true; // Propagation is stopped, remove all other hover records + // An event handler is only allowed to flush other handlers if it is hovered itself - case 'CHAN': - // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored - if (length === 4) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();else this.IFF.reader.skip(length); - break; - // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format + if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) { + // Objects cannot flush out higher up objects that have already caught the event + const higher = intersections.slice(0, intersections.indexOf(hit)); + cancelPointer([...higher, hit]); + } + } + }, + // there should be a distinction between target and currentTarget + target: { + hasPointerCapture, + setPointerCapture, + releasePointerCapture + }, + currentTarget: { + hasPointerCapture, + setPointerCapture, + releasePointerCapture + }, + nativeEvent: event + }; // Call subscribers - case 'SMAN': - var maxSmoothingAngle = this.IFF.reader.getFloat32(); - this.IFF.currentSurface.attributes.smooth = maxSmoothingAngle < 0 ? false : true; - break; - // LWO2: Basic Surface Parameters + callback(raycastEvent); // Event bubbling may be interrupted by stopPropagation - case 'COLR': - this.IFF.currentSurface.attributes.Color = { - value: this.IFF.reader.getFloat32Array(3) - }; - this.IFF.reader.skip(2); // VX: envelope + if (localState.stopped === true) break; + } + } - break; + return intersections; + } - case 'LUMI': - this.IFF.currentSurface.attributes.Luminosity = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + function cancelPointer(intersections) { + const { + internal + } = store.getState(); + Array.from(internal.hovered.values()).forEach(hoveredObj => { + // When no objects were hit or the the hovered object wasn't found underneath the cursor + // we call onPointerOut and delete the object from the hovered-elements map + if (!intersections.length || !intersections.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) { + const eventObject = hoveredObj.eventObject; + const instance = eventObject.__r3f; + const handlers = instance == null ? void 0 : instance.handlers; + internal.hovered.delete(makeId(hoveredObj)); - case 'SPEC': - this.IFF.currentSurface.attributes.Specular = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + if (instance != null && instance.eventCount) { + // Clear out intersects, they are outdated by now + const data = { ...hoveredObj, + intersections + }; + handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data); + handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data); + } + } + }); + } - case 'DIFF': - this.IFF.currentSurface.attributes.Diffuse = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + const handlePointer = name => { + // Deal with cancelation + switch (name) { + case 'onPointerLeave': + case 'onPointerCancel': + return () => cancelPointer([]); - case 'REFL': - this.IFF.currentSurface.attributes.Reflection = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + case 'onLostPointerCapture': + return event => { + const { + internal + } = store.getState(); - case 'GLOS': - this.IFF.currentSurface.attributes.Glossiness = { - value: this.IFF.reader.getFloat32() + if ('pointerId' in event && !internal.capturedMap.has(event.pointerId)) { + // If the object event interface had onLostPointerCapture, we'd call it here on every + // object that's getting removed. + internal.capturedMap.delete(event.pointerId); + cancelPointer([]); + } }; - this.IFF.reader.skip(2); - break; - - case 'TRAN': - this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; - - case 'BUMP': - this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; - - case 'SIDE': - this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16(); - break; - - case 'RIMG': - this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex(); - break; - - case 'RIND': - this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; + } // Any other pointer goes here ... - case 'TIMG': - this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex(); - break; - case 'IMAP': - this.IFF.currentSurface.attributes.imageMapIndex = this.IFF.reader.getUint32(); - break; + return event => { + const { + onPointerMissed, + internal + } = store.getState(); //prepareRay(event) - case 'IUVI': - // uv channel name - this.IFF.currentNode.UVChannel = this.IFF.reader.getString(length); - break; + internal.lastEvent.current = event; // Get fresh intersects - case 'IUTL': - // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge - this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32(); - break; + const isPointerMove = name === 'onPointerMove'; + const isClickEvent = name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick'; + const filter = isPointerMove ? filterPointerEvents : undefined; //const hits = patchIntersects(intersect(filter), event) - case 'IVTL': - // heightWrappingMode - this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32(); - break; + const hits = intersect(event, filter); + const delta = isClickEvent ? calculateDistance(event) : 0; // Save initial coordinates on pointer-down - default: - this.IFF.parseUnknownCHUNK(blockID, length); - } + if (name === 'onPointerDown') { + internal.initialClick = [event.offsetX, event.offsetY]; + internal.initialHits = hits.map(hit => hit.eventObject); + } // If a click yields no results, pass it back to the user as a miss + // Missed events have to come first in order to establish user-land side-effect clean up - if (blockID != 'FORM') { - this.IFF.debugger.node = 1; - this.IFF.debugger.nodeID = blockID; - this.IFF.debugger.log(); - } - if (this.IFF.reader.offset >= this.IFF.currentFormEnd) { - this.IFF.currentForm = this.IFF.parentForm; - } - } -}; + if (isClickEvent && !hits.length) { + if (delta <= 2) { + pointerMissed(event, internal.interaction); + if (onPointerMissed) onPointerMissed(event); + } + } // Take care of unhover -function LWO2Parser(IFFParser) { - this.IFF = IFFParser; -} -LWO2Parser.prototype = { - constructor: LWO2Parser, - parseBlock: function () { - this.IFF.debugger.offset = this.IFF.reader.offset; - this.IFF.debugger.closeForms(); - var blockID = this.IFF.reader.getIDTag(); - var length = this.IFF.reader.getUint32(); // size of data in bytes + if (isPointerMove) cancelPointer(hits); + handleIntersects(hits, event, delta, data => { + const eventObject = data.eventObject; + const instance = eventObject.__r3f; + const handlers = instance == null ? void 0 : instance.handlers; // Check presence of handlers - if (length > this.IFF.reader.dv.byteLength - this.IFF.reader.offset) { - this.IFF.reader.offset -= 4; - length = this.IFF.reader.getUint16(); - } + if (!(instance != null && instance.eventCount)) return; - this.IFF.debugger.dataOffset = this.IFF.reader.offset; - this.IFF.debugger.length = length; // Data types may be found in either LWO2 OR LWO3 spec + if (isPointerMove) { + // Move event ... + if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) { + // When enter or out is present take care of hover-state + const id = makeId(data); + const hoveredItem = internal.hovered.get(id); - switch (blockID) { - case 'FORM': - // form blocks may consist of sub -chunks or sub-forms - this.IFF.parseForm(length); - break; - // SKIPPED CHUNKS - // if break; is called directly, the position in the lwoTree is not created - // any sub chunks and forms are added to the parent form instead - // MISC skipped - - case 'ICON': // Thumbnail Icon Image - - case 'VMPA': // Vertex Map Parameter - - case 'BBOX': // bounding box - // case 'VMMD': - // case 'VTYP': - // normal maps can be specified, normally on models imported from other applications. Currently ignored - - case 'NORM': // ENVL FORM skipped - - case 'PRE ': - case 'POST': - case 'KEY ': - case 'SPAN': // CLIP FORM skipped - - case 'TIME': - case 'CLRS': - case 'CLRA': - case 'FILT': - case 'DITH': - case 'CONT': - case 'BRIT': - case 'SATR': - case 'HUE ': - case 'GAMM': - case 'NEGA': - case 'IFLT': - case 'PFLT': // Image Map Layer skipped - - case 'PROJ': - case 'AXIS': - case 'AAST': - case 'PIXB': - case 'AUVO': - case 'STCK': // Procedural Textures skipped - - case 'PROC': - case 'VALU': - case 'FUNC': // Gradient Textures skipped - - case 'PNAM': - case 'INAM': - case 'GRST': - case 'GREN': - case 'GRPT': - case 'FKEY': - case 'IKEY': // Texture Mapping Form skipped - - case 'CSYS': // Surface CHUNKs skipped - - case 'OPAQ': // top level 'opacity' checkbox - - case 'CMAP': // clip map - // Surface node CHUNKS skipped - // These mainly specify the node editor setup in LW - - case 'NLOC': - case 'NZOM': - case 'NVER': - case 'NSRV': - case 'NVSK': // unknown - - case 'NCRD': - case 'WRPW': // image wrap w ( for cylindrical and spherical projections) - - case 'WRPH': // image wrap h - - case 'NMOD': - case 'NPRW': - case 'NPLA': - case 'NODS': - case 'VERS': - case 'ENUM': - case 'TAG ': - case 'OPAC': // Car Material CHUNKS - - case 'CGMD': - case 'CGTY': - case 'CGST': - case 'CGEN': - case 'CGTS': - case 'CGTE': - case 'OSMP': - case 'OMDE': - case 'OUTR': - case 'FLAG': - case 'TRNL': - case 'GLOW': - case 'GVAL': // glow intensity - - case 'SHRP': - case 'RFOP': - case 'RSAN': - case 'TROP': - case 'RBLR': - case 'TBLR': - case 'CLRH': - case 'CLRF': - case 'ADTR': - case 'LINE': - case 'ALPH': - case 'VCOL': - case 'ENAB': - this.IFF.debugger.skipped = true; - this.IFF.reader.skip(length); - break; + if (!hoveredItem) { + // If the object wasn't previously hovered, book it and call its handler + internal.hovered.set(id, data); + handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data); + handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data); + } else if (hoveredItem.stopped) { + // If the object was previously hovered and stopped, we shouldn't allow other items to proceed + data.stopPropagation(); + } + } // Call mouse move - case 'SURF': - this.IFF.parseSurfaceLwo2(length); - break; - case 'CLIP': - this.IFF.parseClipLwo2(length); - break; - // Texture node chunks (not in spec) + handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data); + } else { + // All other events ... + const handler = handlers[name]; - case 'IPIX': // usePixelBlending + if (handler) { + // Forward all events back to their respective handlers with the exception of click events, + // which must use the initial target + if (!isClickEvent || internal.initialHits.includes(eventObject)) { + // Missed events have to come first + pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); // Now call the handler - case 'IMIP': // useMipMaps + handler(data); + } + } else { + // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit + if (isClickEvent && internal.initialHits.includes(eventObject)) { + pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); + } + } + } + }); + }; + }; - case 'IMOD': // imageBlendingMode + function pointerMissed(event, objects) { + objects.forEach(object => { + var _r3f3; - case 'AMOD': // unknown + return (_r3f3 = object.__r3f) == null ? void 0 : _r3f3.handlers.onPointerMissed == null ? void 0 : _r3f3.handlers.onPointerMissed(event); + }); + } - case 'IINV': // imageInvertAlpha + return { + handlePointer + }; +} - case 'INCR': // imageInvertColor +let catalogue = {}; - case 'IAXS': // imageAxis ( for non-UV maps) +let extend = objects => void (catalogue = { ...catalogue, + ...objects +}); - case 'IFOT': // imageFallofType +function createRenderer(roots, getEventPriority) { + function createInstance(type, { + args = [], + attach, + ...props + }, root) { + let name = `${type[0].toUpperCase()}${type.slice(1)}`; + let instance; // Auto-attach geometries and materials - case 'ITIM': // timing for animated textures + if (attach === undefined) { + if (name.endsWith('Geometry')) attach = 'geometry';else if (name.endsWith('Material')) attach = 'material'; + } - case 'IWRL': - case 'IUTI': - case 'IINX': - case 'IINY': - case 'IINZ': - case 'IREF': - // possibly a VX for reused texture nodes - if (length === 4) this.IFF.currentNode[blockID] = this.IFF.reader.getInt32();else this.IFF.reader.skip(length); - break; + if (type === 'primitive') { + if (props.object === undefined) throw `Primitives without 'object' are invalid!`; + const object = props.object; + instance = prepare(object, { + type, + root, + attach, + primitive: true + }); + } else { + const target = catalogue[name]; - case 'OTAG': - this.IFF.parseObjectTag(); - break; + if (!target) { + throw `${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`; + } // Throw if an object or literal was passed for args - case 'LAYR': - this.IFF.parseLayer(length); - break; - case 'PNTS': - this.IFF.parsePoints(length); - break; + if (!Array.isArray(args)) throw 'The args prop must be an array!'; // Instanciate new object, link it to the root + // Append memoized props with args so it's not forgotten - case 'VMAP': - this.IFF.parseVertexMapping(length); - break; + instance = prepare(new target(...args), { + type, + root, + attach, + // Save args in case we need to reconstruct later for HMR + memoizedProps: { + args + } + }); + } // It should NOT call onUpdate on object instanciation, because it hasn't been added to the + // view yet. If the callback relies on references for instance, they won't be ready yet, this is + // why it passes "true" here + // There is no reason to apply props to injects - case 'AUVU': - case 'AUVN': - this.IFF.reader.skip(length - 1); - this.IFF.reader.getVariableLengthIndex(); // VX - break; + if (name !== 'inject') applyProps$1(instance, props); + return instance; + } - case 'POLS': - this.IFF.parsePolygonList(length); - break; + function appendChild(parentInstance, child) { + let added = false; - case 'TAGS': - this.IFF.parseTagStrings(length); - break; + if (child) { + var _child$__r3f, _parentInstance$__r3f; - case 'PTAG': - this.IFF.parsePolygonTagMapping(length); - break; + // The attach attribute implies that the object attaches itself on the parent + if ((_child$__r3f = child.__r3f) != null && _child$__r3f.attach) { + attach(parentInstance, child, child.__r3f.attach); + } else if (child.isObject3D && parentInstance.isObject3D) { + // add in the usual parent-child way + parentInstance.add(child); + added = true; + } // This is for anything that used attach, and for non-Object3Ds that don't get attached to props; + // that is, anything that's a child in React but not a child in the scenegraph. - case 'VMAD': - this.IFF.parseVertexMapping(length, true); - break; - // Misc CHUNKS - case 'DESC': - // Description Line - this.IFF.currentForm.description = this.IFF.reader.getString(); - break; + if (!added) (_parentInstance$__r3f = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f.objects.push(child); + if (!child.__r3f) prepare(child, {}); + child.__r3f.parent = parentInstance; + updateInstance(child); + invalidateInstance(child); + } + } - case 'TEXT': - case 'CMNT': - case 'NCOM': - this.IFF.currentForm.comment = this.IFF.reader.getString(); - break; - // Envelope Form + function insertBefore(parentInstance, child, beforeChild) { + let added = false; - case 'NAME': - this.IFF.currentForm.channelName = this.IFF.reader.getString(); - break; - // Image Map Layer + if (child) { + var _child$__r3f2, _parentInstance$__r3f2; - case 'WRAP': - this.IFF.currentForm.wrap = { - w: this.IFF.reader.getUint16(), - h: this.IFF.reader.getUint16() - }; - break; + if ((_child$__r3f2 = child.__r3f) != null && _child$__r3f2.attach) { + attach(parentInstance, child, child.__r3f.attach); + } else if (child.isObject3D && parentInstance.isObject3D) { + child.parent = parentInstance; + child.dispatchEvent({ + type: 'added' + }); + const restSiblings = parentInstance.children.filter(sibling => sibling !== child); + const index = restSiblings.indexOf(beforeChild); + parentInstance.children = [...restSiblings.slice(0, index), child, ...restSiblings.slice(index)]; + added = true; + } - case 'IMAG': - var index = this.IFF.reader.getVariableLengthIndex(); - this.IFF.currentForm.imageIndex = index; - break; - // Texture Mapping Form + if (!added) (_parentInstance$__r3f2 = parentInstance.__r3f) == null ? void 0 : _parentInstance$__r3f2.objects.push(child); + if (!child.__r3f) prepare(child, {}); + child.__r3f.parent = parentInstance; + updateInstance(child); + invalidateInstance(child); + } + } - case 'OREF': - this.IFF.currentForm.referenceObject = this.IFF.reader.getString(); - break; + function removeRecursive(array, parent, dispose = false) { + if (array) [...array].forEach(child => removeChild(parent, child, dispose)); + } - case 'ROID': - this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32(); - break; - // Surface Blocks + function removeChild(parentInstance, child, dispose) { + if (child) { + var _parentInstance$__r3f3, _child$__r3f3, _child$__r3f5; - case 'SSHN': - this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString(); - break; + // Clear the parent reference + if (child.__r3f) child.__r3f.parent = null; // Remove child from the parents objects - case 'AOVN': - this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString(); - break; - // Nodal Blocks + if ((_parentInstance$__r3f3 = parentInstance.__r3f) != null && _parentInstance$__r3f3.objects) parentInstance.__r3f.objects = parentInstance.__r3f.objects.filter(x => x !== child); // Remove attachment - case 'NSTA': - this.IFF.currentForm.disabled = this.IFF.reader.getUint16(); - break; + if ((_child$__r3f3 = child.__r3f) != null && _child$__r3f3.attach) { + detach(parentInstance, child, child.__r3f.attach); + } else if (child.isObject3D && parentInstance.isObject3D) { + var _child$__r3f4; - case 'NRNM': - this.IFF.currentForm.realName = this.IFF.reader.getString(); - break; + parentInstance.remove(child); // Remove interactivity - case 'NNME': - this.IFF.currentForm.refName = this.IFF.reader.getString(); - this.IFF.currentSurface.nodes[this.IFF.currentForm.refName] = this.IFF.currentForm; - break; - // Nodal Blocks : connections + if ((_child$__r3f4 = child.__r3f) != null && _child$__r3f4.root) { + removeInteractivity(child.__r3f.root, child); + } + } // Allow objects to bail out of recursive dispose altogether by passing dispose={null} + // Never dispose of primitives because their state may be kept outside of React! + // In order for an object to be able to dispose it has to have + // - a dispose method, + // - it cannot be a + // - it cannot be a THREE.Scene, because three has broken it's own api + // + // Since disposal is recursive, we can check the optional dispose arg, which will be undefined + // when the reconciler calls it, but then carry our own check recursively - case 'INME': - if (!this.IFF.currentForm.nodeName) this.IFF.currentForm.nodeName = []; - this.IFF.currentForm.nodeName.push(this.IFF.reader.getString()); - break; - case 'IINN': - if (!this.IFF.currentForm.inputNodeName) this.IFF.currentForm.inputNodeName = []; - this.IFF.currentForm.inputNodeName.push(this.IFF.reader.getString()); - break; + const isPrimitive = (_child$__r3f5 = child.__r3f) == null ? void 0 : _child$__r3f5.primitive; + const shouldDispose = dispose === undefined ? child.dispose !== null && !isPrimitive : dispose; // Remove nested child objects. Primitives should not have objects and children that are + // attached to them declaratively ... - case 'IINM': - if (!this.IFF.currentForm.inputName) this.IFF.currentForm.inputName = []; - this.IFF.currentForm.inputName.push(this.IFF.reader.getString()); - break; + if (!isPrimitive) { + var _child$__r3f6; - case 'IONM': - if (!this.IFF.currentForm.inputOutputName) this.IFF.currentForm.inputOutputName = []; - this.IFF.currentForm.inputOutputName.push(this.IFF.reader.getString()); - break; + removeRecursive((_child$__r3f6 = child.__r3f) == null ? void 0 : _child$__r3f6.objects, child, shouldDispose); + removeRecursive(child.children, child, shouldDispose); + } // Remove references - case 'FNAM': - this.IFF.currentForm.fileName = this.IFF.reader.getString(); - break; - case 'CHAN': - // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored - if (length === 4) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();else this.IFF.reader.skip(length); - break; - // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format + if (child.__r3f) { + delete child.__r3f.root; + delete child.__r3f.objects; + delete child.__r3f.handlers; + delete child.__r3f.memoizedProps; + if (!isPrimitive) delete child.__r3f; + } // Dispose item whenever the reconciler feels like it - case 'SMAN': - var maxSmoothingAngle = this.IFF.reader.getFloat32(); - this.IFF.currentSurface.attributes.smooth = maxSmoothingAngle < 0 ? false : true; - break; - // LWO2: Basic Surface Parameters - case 'COLR': - this.IFF.currentSurface.attributes.Color = { - value: this.IFF.reader.getFloat32Array(3) - }; - this.IFF.reader.skip(2); // VX: envelope + if (shouldDispose && child.dispose && child.type !== 'Scene') { + scheduler$1.exports.unstable_scheduleCallback(scheduler$1.exports.unstable_IdlePriority, () => { + try { + child.dispose(); + } catch (e) { + /* ... */ + } + }); + } - break; + invalidateInstance(parentInstance); + } + } - case 'LUMI': - this.IFF.currentSurface.attributes.Luminosity = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + function switchInstance(instance, type, newProps, fiber) { + var _instance$__r3f; - case 'SPEC': - this.IFF.currentSurface.attributes.Specular = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + const parent = (_instance$__r3f = instance.__r3f) == null ? void 0 : _instance$__r3f.parent; + if (!parent) return; + const newInstance = createInstance(type, newProps, instance.__r3f.root); // https://github.com/pmndrs/react-three-fiber/issues/1348 + // When args change the instance has to be re-constructed, which then + // forces r3f to re-parent the children and non-scene objects + // This can not include primitives, which should not have declarative children - case 'DIFF': - this.IFF.currentSurface.attributes.Diffuse = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + if (type !== 'primitive' && instance.children) { + instance.children.forEach(child => appendChild(newInstance, child)); + instance.children = []; + } - case 'REFL': - this.IFF.currentSurface.attributes.Reflection = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + instance.__r3f.objects.forEach(child => appendChild(newInstance, child)); - case 'GLOS': - this.IFF.currentSurface.attributes.Glossiness = { - value: this.IFF.reader.getFloat32() - }; - this.IFF.reader.skip(2); - break; + instance.__r3f.objects = []; + removeChild(parent, instance); + appendChild(parent, newInstance); // Re-bind event handlers - case 'TRAN': - this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; + if (newInstance.raycast && newInstance.__r3f.eventCount) { + const rootState = newInstance.__r3f.root.getState(); - case 'BUMP': - this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; + rootState.internal.interaction.push(newInstance); + } // This evil hack switches the react-internal fiber node + [fiber, fiber.alternate].forEach(fiber => { + if (fiber !== null) { + fiber.stateNode = newInstance; - case 'SIDE': - this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16(); - break; + if (fiber.ref) { + if (typeof fiber.ref === 'function') fiber.ref(newInstance);else fiber.ref.current = newInstance; + } + } + }); + } - case 'RIMG': - this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex(); - break; + const reconciler = Reconciler({ + createInstance, + removeChild, + appendChild, + appendInitialChild: appendChild, + insertBefore, + supportsMicrotask: true, + warnsIfNotActing: true, + supportsMutation: true, + isPrimaryRenderer: false, + noTimeout: -1, + appendChildToContainer: (container, child) => { + const scene = container.getState().scene; // Link current root to the default scene - case 'RIND': - this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32(); - this.IFF.reader.skip(2); - break; + scene.__r3f.root = container; + appendChild(scene, child); + }, + removeChildFromContainer: (container, child) => removeChild(container.getState().scene, child), + insertInContainerBefore: (container, child, beforeChild) => insertBefore(container.getState().scene, child, beforeChild), + getRootHostContext: () => null, + getChildHostContext: parentHostContext => parentHostContext, - case 'TIMG': - this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex(); - break; + finalizeInitialChildren(instance) { + var _instance$__r3f2; - case 'IMAP': - this.IFF.reader.skip(2); - break; + const localState = (_instance$__r3f2 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f2 : {}; // https://github.com/facebook/react/issues/20271 + // Returning true will trigger commitMount - case 'TMAP': - this.IFF.debugger.skipped = true; - this.IFF.reader.skip(length); // needs implementing + return !!localState.handlers; + }, - break; + prepareUpdate(instance, type, oldProps, newProps) { + // Create diff-sets + if (instance.__r3f.primitive && newProps.object && newProps.object !== instance) { + return [true]; + } else { + // This is a data object, let's extract critical information about it + const { + args: argsNew = [], + children: cN, + ...restNew + } = newProps; + const { + args: argsOld = [], + children: cO, + ...restOld + } = oldProps; // Throw if an object or literal was passed for args - case 'IUVI': - // uv channel name - this.IFF.currentNode.UVChannel = this.IFF.reader.getString(length); - break; + if (!Array.isArray(argsNew)) throw 'The args prop must be an array!'; // If it has new props or arguments, then it needs to be re-instanciated - case 'IUTL': - // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge - this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32(); - break; + if (argsNew.some((value, index) => value !== argsOld[index])) return [true]; // Create a diff-set, flag if there are any changes - case 'IVTL': - // heightWrappingMode - this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32(); - break; - // LWO2 USE + const diff = diffProps(instance, restNew, restOld, true); + if (diff.changes.length) return [false, diff]; // Otherwise do not touch the instance - case 'BLOK': - // skip - break; + return null; + } + }, - default: - this.IFF.parseUnknownCHUNK(blockID, length); - } + commitUpdate(instance, [reconstruct, diff], type, oldProps, newProps, fiber) { + // Reconstruct when args or = this.IFF.currentFormEnd) { - this.IFF.currentForm = this.IFF.parentForm; - } - } -}; + // https://github.com/facebook/react/issues/20271 + // This will make sure events are only added once to the central container + const localState = (_instance$__r3f3 = instance.__r3f) != null ? _instance$__r3f3 : {}; -/** - * === IFFParser === - * - Parses data from the IFF buffer. - * - LWO3 files are in IFF format and can contain the following data types, referred to by shorthand codes - * - * ATOMIC DATA TYPES - * ID Tag - 4x 7 bit uppercase ASCII chars: ID4 - * signed integer, 1, 2, or 4 byte length: I1, I2, I4 - * unsigned integer, 1, 2, or 4 byte length: U1, U2, U4 - * float, 4 byte length: F4 - * string, series of ASCII chars followed by null byte (If the length of the string including the null terminating byte is odd, an extra null is added so that the data that follows will begin on an even byte boundary): S0 - * - * COMPOUND DATA TYPES - * Variable-length Index (index into an array or collection): U2 or U4 : VX - * Color (RGB): F4 + F4 + F4: COL12 - * Coordinate (x, y, z): F4 + F4 + F4: VEC12 - * Percentage F4 data type from 0->1 with 1 = 100%: FP4 - * Angle in radian F4: ANG4 - * Filename (string) S0: FNAM0 - * XValue F4 + index (VX) + optional envelope( ENVL ): XVAL - * XValue vector VEC12 + index (VX) + optional envelope( ENVL ): XVAL3 - * - * The IFF file is arranged in chunks: - * CHUNK = ID4 + length (U4) + length X bytes of data + optional 0 pad byte - * optional 0 pad byte is there to ensure chunk ends on even boundary, not counted in size - * - * COMPOUND DATA TYPES - * - Chunks are combined in Forms (collections of chunks) - * - FORM = string 'FORM' (ID4) + length (U4) + type (ID4) + optional ( CHUNK | FORM ) - * - CHUNKS and FORMS are collectively referred to as blocks - * - The entire file is contained in one top level FORM - * - **/ + if (instance.raycast && localState.handlers && localState.eventCount) { + instance.__r3f.root.getState().internal.interaction.push(instance); + } + }, -function IFFParser() { - this.debugger = new Debugger(); // this.debugger.enable(); // un-comment to log IFF hierarchy. -} + getPublicInstance: instance => instance, + shouldDeprioritizeSubtree: () => false, + prepareForCommit: () => null, + preparePortalMount: container => prepare(container.getState().scene), + resetAfterCommit: () => {}, + shouldSetTextContent: () => false, + clearContainer: () => false, + detachDeletedInstance: () => {}, -IFFParser.prototype = { - constructor: IFFParser, - parse: function (buffer) { - this.reader = new DataViewReader(buffer); - this.tree = { - materials: {}, - layers: [], - tags: [], - textures: [] - }; // start out at the top level to add any data before first layer is encountered + hideInstance(instance) { + var _instance$__r3f4; - this.currentLayer = this.tree; - this.currentForm = this.tree; - this.parseTopForm(); - if (this.tree.format === undefined) return; + // Deatch while the instance is hidden + const { + attach: type, + parent + } = (_instance$__r3f4 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f4 : {}; + if (type && parent) detach(parent, instance, type); + if (instance.isObject3D) instance.visible = false; + invalidateInstance(instance); + }, - if (this.tree.format === 'LWO2') { - this.parser = new LWO2Parser(this); + unhideInstance(instance, props) { + var _instance$__r3f5; - while (!this.reader.endOfFile()) this.parser.parseBlock(); - } else if (this.tree.format === 'LWO3') { - this.parser = new LWO3Parser(this); + // Re-attach when the instance is unhidden + const { + attach: type, + parent + } = (_instance$__r3f5 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f5 : {}; + if (type && parent) attach(parent, instance, type); + if (instance.isObject3D && props.visible == null || props.visible) instance.visible = true; + invalidateInstance(instance); + }, - while (!this.reader.endOfFile()) this.parser.parseBlock(); - } + createTextInstance: () => {}, + hideTextInstance: () => { + throw new Error('Text is not allowed in the R3F tree.'); + }, + unhideTextInstance: () => {}, + getCurrentEventPriority: () => getEventPriority ? getEventPriority() : constants.exports.DefaultEventPriority, + // @ts-ignore + now: typeof performance !== 'undefined' && is$1.fun(performance.now) ? performance.now : is$1.fun(Date.now) ? Date.now : undefined, + // @ts-ignore + scheduleTimeout: is$1.fun(setTimeout) ? setTimeout : undefined, + // @ts-ignore + cancelTimeout: is$1.fun(clearTimeout) ? clearTimeout : undefined, + setTimeout: is$1.fun(setTimeout) ? setTimeout : undefined, + clearTimeout: is$1.fun(clearTimeout) ? clearTimeout : undefined + }); + return { + reconciler, + applyProps: applyProps$1 + }; +} +const isRenderer = def => !!(def != null && def.render); +const context = /*#__PURE__*/React__namespace.createContext(null); - this.debugger.offset = this.reader.offset; - this.debugger.closeForms(); - return this.tree; - }, +const createStore$2 = (invalidate, advance) => { + const rootState = create$4((set, get) => { + const position = new Vector3(); + const defaultTarget = new Vector3(); + const tempTarget = new Vector3(); - parseTopForm() { - this.debugger.offset = this.reader.offset; - var topForm = this.reader.getIDTag(); + function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) { + const { + width, + height + } = size; + const aspect = width / height; + if (target instanceof Vector3) tempTarget.copy(target);else tempTarget.set(...target); + const distance = camera.getWorldPosition(position).distanceTo(tempTarget); - if (topForm !== 'FORM') { - console.warn('LWOLoader: Top-level FORM missing.'); - return; - } + if (isOrthographicCamera(camera)) { + return { + width: width / camera.zoom, + height: height / camera.zoom, + factor: 1, + distance, + aspect + }; + } else { + const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians - var length = this.reader.getUint32(); - this.debugger.dataOffset = this.reader.offset; - this.debugger.length = length; - var type = this.reader.getIDTag(); + const h = 2 * Math.tan(fov / 2) * distance; // visible height - if (type === 'LWO2') { - this.tree.format = type; - } else if (type === 'LWO3') { - this.tree.format = type; + const w = h * (width / height); + return { + width: w, + height: h, + factor: width / w, + distance, + aspect + }; + } } - this.debugger.node = 0; - this.debugger.nodeID = type; - this.debugger.log(); - return; - }, - - /// - // FORM PARSING METHODS - /// - // Forms are organisational and can contain any number of sub chunks and sub forms - // FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * } - parseForm(length) { - var type = this.reader.getIDTag(); - - switch (type) { - // SKIPPED FORMS - // if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped - case 'ISEQ': // Image sequence - - case 'ANIM': // plug in animation - - case 'STCC': // Color-cycling Still - - case 'VPVL': - case 'VPRM': - case 'NROT': - case 'WRPW': // image wrap w ( for cylindrical and spherical projections) + let performanceTimeout = undefined; - case 'WRPH': // image wrap h + const setPerformanceCurrent = current => set(state => ({ + performance: { ...state.performance, + current + } + })); - case 'FUNC': - case 'FALL': - case 'OPAC': - case 'GRAD': // gradient texture + const pointer = new Vector2(); + return { + set, + get, + // Mock objects that have to be configured + gl: null, + camera: null, + raycaster: null, + events: { + priority: 1, + enabled: true, + connected: false + }, + xr: null, + invalidate: (frames = 1) => invalidate(get(), frames), + advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()), + legacy: false, + linear: false, + flat: false, + scene: prepare(new Scene$1()), + controls: null, + clock: new Clock(), + pointer, + mouse: pointer, + frameloop: 'always', + onPointerMissed: undefined, + performance: { + current: 1, + min: 0.5, + max: 1, + debounce: 200, + regress: () => { + const state = get(); // Clear timeout - case 'ENVS': - case 'VMOP': - case 'VMBG': // Car Material FORMS + if (performanceTimeout) clearTimeout(performanceTimeout); // Set lower bound performance - case 'OMAX': - case 'STEX': - case 'CKBG': - case 'CKEY': - case 'VMLA': - case 'VMLB': - this.debugger.skipped = true; - this.skipForm(length); // not currently supported + if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min); // Go back to upper bound performance after a while unless something regresses meanwhile - break; - // if break; is called directly, the position in the lwoTree is not created - // any sub chunks and forms are added to the parent form instead + performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce); + } + }, + size: { + width: 0, + height: 0, + updateStyle: false + }, + viewport: { + initialDpr: 0, + dpr: 0, + width: 0, + height: 0, + aspect: 0, + distance: 0, + factor: 0, + getCurrentViewport + }, + setEvents: events => set(state => ({ ...state, + events: { ...state.events, + ...events + } + })), + setSize: (width, height, updateStyle) => { + const camera = get().camera; + const size = { + width, + height, + updateStyle + }; + set(state => ({ + size, + viewport: { ...state.viewport, + ...getCurrentViewport(camera, defaultTarget, size) + } + })); + }, + setDpr: dpr => set(state => { + const resolved = calculateDpr(dpr); + return { + viewport: { ...state.viewport, + dpr: resolved, + initialDpr: state.viewport.initialDpr || resolved + } + }; + }), + setFrameloop: (frameloop = 'always') => { + const clock = get().clock; // if frameloop === "never" clock.elapsedTime is updated using advance(timestamp) - case 'META': - case 'NNDS': - case 'NODS': - case 'NDTA': - case 'ADAT': - case 'AOVS': - case 'BLOK': // used by texture nodes + clock.stop(); + clock.elapsedTime = 0; - case 'IBGC': // imageBackgroundColor + if (frameloop !== 'never') { + clock.start(); + clock.elapsedTime = 0; + } - case 'IOPC': // imageOpacity + set(() => ({ + frameloop + })); + }, + previousRoot: undefined, + internal: { + active: false, + priority: 0, + frames: 0, + lastEvent: /*#__PURE__*/React__namespace.createRef(), + interaction: [], + hovered: new Map(), + subscribers: [], + initialClick: [0, 0], + initialHits: [], + capturedMap: new Map(), + subscribe: (ref, priority, store) => { + const internal = get().internal; // If this subscription was given a priority, it takes rendering into its own hands + // For that reason we switch off automatic rendering and increase the manual flag + // As long as this flag is positive there can be no internal rendering at all + // because there could be multiple render subscriptions - case 'IIMG': // hold reference to image path + internal.priority = internal.priority + (priority > 0 ? 1 : 0); + internal.subscribers.push({ + ref, + priority, + store + }); // Register subscriber and sort layers from lowest to highest, meaning, + // highest priority renders last (on top of the other frames) - case 'TXTR': - // this.setupForm( type, length ); - this.debugger.length = 4; - this.debugger.skipped = true; - break; + internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority); + return () => { + const internal = get().internal; - case 'IFAL': // imageFallof + if (internal != null && internal.subscribers) { + // Decrease manual flag if this subscription had a priority + internal.priority = internal.priority - (priority > 0 ? 1 : 0); // Remove subscriber from list - case 'ISCL': // imageScale + internal.subscribers = internal.subscribers.filter(s => s.ref !== ref); + } + }; + } + } + }; + }); + const state = rootState.getState(); + let oldSize = state.size; + let oldDpr = state.viewport.dpr; + let oldCamera = state.camera; + rootState.subscribe(() => { + const { + camera, + size, + viewport, + gl, + set + } = rootState.getState(); // Resize camera and renderer on changes to size and pixelratio - case 'IPOS': // imagePosition + if (size !== oldSize || viewport.dpr !== oldDpr) { + oldSize = size; + oldDpr = viewport.dpr; // Update camera & renderer - case 'IROT': // imageRotation + updateCamera(camera, size); + gl.setPixelRatio(viewport.dpr); + gl.setSize(size.width, size.height, size.updateStyle); + } // Update viewport once the camera changes - case 'IBMP': - case 'IUTD': - case 'IVTD': - this.parseTextureNodeAttribute(type); - break; - case 'ENVL': - this.parseEnvelope(length); - break; - // CLIP FORM AND SUB FORMS + if (camera !== oldCamera) { + oldCamera = camera; // Update viewport - case 'CLIP': - if (this.tree.format === 'LWO2') { - this.parseForm(length); - } else { - this.parseClip(length); + set(state => ({ + viewport: { ...state.viewport, + ...state.viewport.getCurrentViewport(camera) } + })); + } + }); // Invalidate on any change - break; - - case 'STIL': - this.parseImage(); - break; + rootState.subscribe(state => invalidate(state)); // Return root state - case 'XREF': - // clone of another STIL - this.reader.skip(8); // unknown + return rootState; +}; - this.currentForm.referenceTexture = { - index: this.reader.getUint32(), - refName: this.reader.getString() // internal unique ref +function createSubs(callback, subs) { + const index = subs.length; + subs.push(callback); + return () => void subs.splice(index, 1); +} - }; - break; - // Not in spec, used by texture nodes +let i$1; +let globalEffects = []; +let globalAfterEffects = []; +let globalTailEffects = []; +/** + * Adds a global render callback which is called each frame. + * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect + */ - case 'IMST': - this.parseImageStateForm(length); - break; - // SURF FORM AND SUB FORMS +const addEffect = callback => createSubs(callback, globalEffects); - case 'SURF': - this.parseSurfaceForm(length); - break; +function run(effects, timestamp) { + for (i$1 = 0; i$1 < effects.length; i$1++) effects[i$1](timestamp); +} - case 'VALU': - // Not in spec - this.parseValueForm(length); - break; +let subscribers; +let subscription; - case 'NTAG': - this.parseSubNode(length); - break; +function render$1(timestamp, state, frame) { + // Run local effects + let delta = state.clock.getDelta(); // In frameloop='never' mode, clock times are updated using the provided timestamp - case 'ATTR': // BSDF Node Attributes + if (state.frameloop === 'never' && typeof timestamp === 'number') { + delta = timestamp - state.clock.elapsedTime; + state.clock.oldTime = state.clock.elapsedTime; + state.clock.elapsedTime = timestamp; + } // Call subscribers (useFrame) - case 'SATR': - // Standard Node Attributes - this.setupForm('attributes', length); - break; - case 'NCON': - this.parseConnections(length); - break; + subscribers = state.internal.subscribers; - case 'SSHA': - this.parentForm = this.currentForm; - this.currentForm = this.currentSurface; - this.setupForm('surfaceShader', length); - break; + for (i$1 = 0; i$1 < subscribers.length; i$1++) { + subscription = subscribers[i$1]; + subscription.ref.current(subscription.store.getState(), delta, frame); + } // Render content - case 'SSHD': - this.setupForm('surfaceShaderData', length); - break; - case 'ENTR': - // Not in spec - this.parseEntryForm(length); - break; - // Image Map Layer + if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera); // Decrease frame count - case 'IMAP': - this.parseImageMap(length); - break; + state.internal.frames = Math.max(0, state.internal.frames - 1); + return state.frameloop === 'always' ? 1 : state.internal.frames; +} - case 'TAMP': - this.parseXVAL('amplitude', length); - break; - //Texture Mapping Form +function createLoop(roots) { + let running = false; + let repeat; + let frame; + let state; - case 'TMAP': - this.setupForm('textureMap', length); - break; + function loop(timestamp) { + frame = requestAnimationFrame(loop); + running = true; + repeat = 0; // Run effects - case 'CNTR': - this.parseXVAL3('center', length); - break; + if (globalEffects.length) run(globalEffects, timestamp); // Render all roots - case 'SIZE': - this.parseXVAL3('scale', length); - break; + roots.forEach(root => { + var _state$gl$xr; - case 'ROTA': - this.parseXVAL3('rotation', length); - break; + state = root.store.getState(); // If the frameloop is invalidated, do not run another frame - default: - this.parseUnknownForm(type, length); - } + if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) { + repeat += render$1(timestamp, state); + } + }); // Run after-effects - this.debugger.node = 0; - this.debugger.nodeID = type; - this.debugger.log(); - }, + if (globalAfterEffects.length) run(globalAfterEffects, timestamp); // Stop the loop if nothing invalidates it - setupForm(type, length) { - if (!this.currentForm) this.currentForm = this.currentNode; - this.currentFormEnd = this.reader.offset + length; - this.parentForm = this.currentForm; + if (repeat === 0) { + // Tail call effects, they are called when rendering stops + if (globalTailEffects.length) run(globalTailEffects, timestamp); // Flag end of operation - if (!this.currentForm[type]) { - this.currentForm[type] = {}; - this.currentForm = this.currentForm[type]; - } else { - // should never see this unless there's a bug in the reader - console.warn('LWOLoader: form already exists on parent: ', type, this.currentForm); - this.currentForm = this.currentForm[type]; + running = false; + return cancelAnimationFrame(frame); } - }, - - skipForm(length) { - this.reader.skip(length - 4); - }, + } - parseUnknownForm(type, length) { - console.warn('LWOLoader: unknown FORM encountered: ' + type, length); - printBuffer(this.reader.dv.buffer, this.reader.offset, length - 4); - this.reader.skip(length - 4); - }, + function invalidate(state, frames = 1) { + var _state$gl$xr2; - parseSurfaceForm(length) { - this.reader.skip(8); // unknown Uint32 x2 - - var name = this.reader.getString(); - var surface = { - attributes: {}, - // LWO2 style non-node attributes will go here - connections: {}, - name: name, - inputName: name, - nodes: {}, - source: this.reader.getString() - }; - this.tree.materials[name] = surface; - this.currentSurface = surface; - this.parentForm = this.tree.materials; - this.currentForm = surface; - this.currentFormEnd = this.reader.offset + length; - }, + if (!state) return roots.forEach(root => invalidate(root.store.getState()), frames); + if ((_state$gl$xr2 = state.gl.xr) != null && _state$gl$xr2.isPresenting || !state.internal.active || state.frameloop === 'never') return; // Increase frames, do not go higher than 60 - parseSurfaceLwo2(length) { - var name = this.reader.getString(); - var surface = { - attributes: {}, - // LWO2 style non-node attributes will go here - connections: {}, - name: name, - nodes: {}, - source: this.reader.getString() - }; - this.tree.materials[name] = surface; - this.currentSurface = surface; - this.parentForm = this.tree.materials; - this.currentForm = surface; - this.currentFormEnd = this.reader.offset + length; - }, + state.internal.frames = Math.min(60, state.internal.frames + frames); // If the render-loop isn't active, start it - parseSubNode(length) { - // parse the NRNM CHUNK of the subnode FORM to get - // a meaningful name for the subNode - // some subnodes can be renamed, but Input and Surface cannot - this.reader.skip(8); // NRNM + length + if (!running) { + running = true; + requestAnimationFrame(loop); + } + } - var name = this.reader.getString(); - var node = { - name: name - }; - this.currentForm = node; - this.currentNode = node; - this.currentFormEnd = this.reader.offset + length; - }, + function advance(timestamp, runGlobalEffects = true, state, frame) { + if (runGlobalEffects) run(globalEffects, timestamp); + if (!state) roots.forEach(root => render$1(timestamp, root.store.getState()));else render$1(timestamp, state, frame); + if (runGlobalEffects) run(globalAfterEffects, timestamp); + } - // collect attributes from all nodes at the top level of a surface - parseConnections(length) { - this.currentFormEnd = this.reader.offset + length; - this.parentForm = this.currentForm; - this.currentForm = this.currentSurface.connections; - }, + return { + loop, - // surface node attribute data, e.g. specular, roughness etc - parseEntryForm(length) { - this.reader.skip(8); // NAME + length + /** + * Invalidates the view, requesting a frame to be rendered. Will globally invalidate unless passed a root's state. + * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate + */ + invalidate, - var name = this.reader.getString(); - this.currentForm = this.currentNode.attributes; - this.setupForm(name, length); - }, + /** + * Advances the frameloop and runs render effects, useful for when manually rendering via `frameloop="never"`. + * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance + */ + advance + }; +} - // parse values from material - doesn't match up to other LWO3 data types - // sub form of entry form - parseValueForm() { - this.reader.skip(8); // unknown + length - - var valueType = this.reader.getString(); - - if (valueType === 'double') { - this.currentForm.value = this.reader.getUint64(); - } else if (valueType === 'int') { - this.currentForm.value = this.reader.getUint32(); - } else if (valueType === 'vparam') { - this.reader.skip(24); - this.currentForm.value = this.reader.getFloat64(); - } else if (valueType === 'vparam3') { - this.reader.skip(24); - this.currentForm.value = this.reader.getFloat64Array(3); - } - }, +function useStore$1() { + const store = React__namespace.useContext(context); + if (!store) throw `R3F hooks can only be used within the Canvas component!`; + return store; +} +/** + * Accesses R3F's internal state, containing renderer, canvas, scene, etc. + * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usethree + */ - // holds various data about texture node image state - // Data other thanmipMapLevel unknown - parseImageStateForm() { - this.reader.skip(8); // unknown +function useThree(selector = state => state, equalityFn) { + return useStore$1()(selector, equalityFn); +} +/** + * Executes a callback before render in a shared frame loop. + * Can order effects with render priority or manually render with a positive priority. + * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe + */ - this.currentForm.mipMapLevel = this.reader.getFloat32(); - }, +function useFrame(callback, renderPriority = 0) { + const store = useStore$1(); + const subscribe = store.getState().internal.subscribe; // Memoize ref - // LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node) - parseImageMap(length) { - this.currentFormEnd = this.reader.offset + length; - this.parentForm = this.currentForm; - if (!this.currentForm.maps) this.currentForm.maps = []; - var map = {}; - this.currentForm.maps.push(map); - this.currentForm = map; - this.reader.skip(10); // unknown, could be an issue if it contains a VX - }, + const ref = useMutableCallback(callback); // Subscribe on mount, unsubscribe on unmount - parseTextureNodeAttribute(type) { - this.reader.skip(28); // FORM + length + VPRM + unknown + Uint32 x2 + float32 + useIsomorphicLayoutEffect$1(() => subscribe(ref, renderPriority, store), [renderPriority, subscribe, store]); + return null; +} - this.reader.skip(20); // FORM + length + VPVL + float32 + Uint32 +const roots = new Map(); +const { + invalidate, + advance: advance$1 +} = createLoop(roots); +const { + reconciler, + applyProps +} = createRenderer(roots, getEventPriority); +const shallowLoose = { + objects: 'shallow', + strict: false +}; - switch (type) { - case 'ISCL': - this.currentNode.scale = this.reader.getFloat32Array(3); - break; +const createRendererInstance = (gl, canvas) => { + const customRenderer = typeof gl === 'function' ? gl(canvas) : gl; + if (isRenderer(customRenderer)) return customRenderer;else return new WebGLRenderer({ + powerPreference: 'high-performance', + canvas: canvas, + antialias: true, + alpha: true, + ...gl + }); +}; - case 'IPOS': - this.currentNode.position = this.reader.getFloat32Array(3); - break; +function createRoot(canvas) { + // Check against mistaken use of createRoot + let prevRoot = roots.get(canvas); + let prevFiber = prevRoot == null ? void 0 : prevRoot.fiber; + let prevStore = prevRoot == null ? void 0 : prevRoot.store; + if (prevRoot) console.warn('R3F.createRoot should only be called once!'); // Report when an error was detected in a previous render + // https://github.com/pmndrs/react-three-fiber/pull/2261 - case 'IROT': - this.currentNode.rotation = this.reader.getFloat32Array(3); - break; + const logRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event, + // emulating an uncaught JavaScript error. + reportError : // In older browsers and test environments, fallback to console.error. + console.error; // Create store - case 'IFAL': - this.currentNode.falloff = this.reader.getFloat32Array(3); - break; + const store = prevStore || createStore$2(invalidate, advance$1); // Create renderer - case 'IBMP': - this.currentNode.amplitude = this.reader.getFloat32(); - break; + const fiber = prevFiber || reconciler.createContainer(store, constants.exports.ConcurrentRoot, null, false, null, '', logRecoverableError, null); // Map it - case 'IUTD': - this.currentNode.uTiles = this.reader.getFloat32(); - break; + if (!prevRoot) roots.set(canvas, { + fiber, + store + }); // Locals - case 'IVTD': - this.currentNode.vTiles = this.reader.getFloat32(); - break; - } + let onCreated; + let configured = false; + return { + configure(props = {}) { + var _canvas$parentElement, _canvas$parentElement2, _canvas$parentElement3, _canvas$parentElement4; - this.reader.skip(2); // unknown - }, + let { + gl: glConfig, + size, + events, + onCreated: onCreatedCallback, + shadows = false, + linear = false, + flat = false, + legacy = false, + orthographic = false, + frameloop = 'always', + dpr = [1, 2], + performance, + raycaster: raycastOptions, + camera: cameraOptions, + onPointerMissed + } = props; + let state = store.getState(); // Set up renderer (one time only!) - // ENVL forms are currently ignored - parseEnvelope(length) { - this.reader.skip(length - 4); // skipping entirely for now - }, + let gl = state.gl; + if (!state.gl) state.set({ + gl: gl = createRendererInstance(glConfig, canvas) + }); // Set up raycaster (one time only!) - /// - // CHUNK PARSING METHODS - /// - // clips can either be defined inside a surface node, or at the top - // level and they have a different format in each case - parseClip(length) { - var tag = this.reader.getIDTag(); // inside surface node + let raycaster = state.raycaster; + if (!raycaster) state.set({ + raycaster: raycaster = new Raycaster() + }); // Set raycaster options - if (tag === 'FORM') { - this.reader.skip(16); - this.currentNode.fileName = this.reader.getString(); - return; - } // otherwise top level + const { + params, + ...options + } = raycastOptions || {}; + if (!is$1.equ(options, raycaster, shallowLoose)) applyProps(raycaster, { ...options + }); + if (!is$1.equ(params, raycaster.params, shallowLoose)) applyProps(raycaster, { + params: { ...raycaster.params, + ...params + } + }); // Create default camera (one time only!) + if (!state.camera) { + const isCamera = cameraOptions instanceof Camera; + const camera = isCamera ? cameraOptions : orthographic ? new OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new PerspectiveCamera(75, 0, 0.1, 1000); - this.reader.setOffset(this.reader.offset - 4); - this.currentFormEnd = this.reader.offset + length; - this.parentForm = this.currentForm; - this.reader.skip(8); // unknown + if (!isCamera) { + camera.position.z = 5; + if (cameraOptions) applyProps(camera, cameraOptions); // Always look at center by default - var texture = { - index: this.reader.getUint32() - }; - this.tree.textures.push(texture); - this.currentForm = texture; - }, + if (!(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0); + } - parseClipLwo2(length) { - var texture = { - index: this.reader.getUint32(), - fileName: '' - }; // seach STIL block + state.set({ + camera + }); + } // Set up XR (one time only!) - while (true) { - var tag = this.reader.getIDTag(); - var n_length = this.reader.getUint16(); - if (tag === 'STIL') { - texture.fileName = this.reader.getString(); - break; - } + if (!state.xr) { + // Handle frame behavior in WebXR + const handleXRFrame = (timestamp, frame) => { + const state = store.getState(); + if (state.frameloop === 'never') return; + advance$1(timestamp, true, state, frame); + }; // Toggle render switching on session - if (n_length >= length) { - break; - } - } - this.tree.textures.push(texture); - this.currentForm = texture; - }, + const handleSessionChange = () => { + const state = store.getState(); + state.gl.xr.enabled = state.gl.xr.isPresenting; + state.gl.xr.setAnimationLoop(state.gl.xr.isPresenting ? handleXRFrame : null); + if (!state.gl.xr.isPresenting) invalidate(state); + }; // WebXR session manager - parseImage() { - this.reader.skip(8); // unknown - this.currentForm.fileName = this.reader.getString(); - }, + const xr = { + connect() { + const gl = store.getState().gl; + gl.xr.addEventListener('sessionstart', handleSessionChange); + gl.xr.addEventListener('sessionend', handleSessionChange); + }, - parseXVAL(type, length) { - var endOffset = this.reader.offset + length - 4; - this.reader.skip(8); - this.currentForm[type] = this.reader.getFloat32(); - this.reader.setOffset(endOffset); // set end offset directly to skip optional envelope - }, + disconnect() { + const gl = store.getState().gl; + gl.xr.removeEventListener('sessionstart', handleSessionChange); + gl.xr.removeEventListener('sessionend', handleSessionChange); + } - parseXVAL3(type, length) { - var endOffset = this.reader.offset + length - 4; - this.reader.skip(8); - this.currentForm[type] = { - x: this.reader.getFloat32(), - y: this.reader.getFloat32(), - z: this.reader.getFloat32() - }; - this.reader.setOffset(endOffset); - }, + }; // Subscribe to WebXR session events - // Tags associated with an object - // OTAG { type[ID4], tag-string[S0] } - parseObjectTag() { - if (!this.tree.objectTags) this.tree.objectTags = {}; - this.tree.objectTags[this.reader.getIDTag()] = { - tagString: this.reader.getString() - }; - }, + if (gl.xr) xr.connect(); + state.set({ + xr + }); + } // Set shadowmap - // Signals the start of a new layer. All the data chunks which follow will be included in this layer until another layer chunk is encountered. - // LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2] - parseLayer(length) { - var layer = { - number: this.reader.getUint16(), - flags: this.reader.getUint16(), - // If the least significant bit of flags is set, the layer is hidden. - pivot: this.reader.getFloat32Array(3), - // Note: this seems to be superflous, as the geometry is translated when pivot is present - name: this.reader.getString() - }; - this.tree.layers.push(layer); - this.currentLayer = layer; - var parsedLength = 16 + stringOffset(this.currentLayer.name); // index ( 2 ) + flags( 2 ) + pivot( 12 ) + stringlength - // if we have not reached then end of the layer block, there must be a parent defined - this.currentLayer.parent = parsedLength < length ? this.reader.getUint16() : -1; // omitted or -1 for no parent - }, + if (gl.shadowMap) { + const isBoolean = is$1.boo(shadows); - // VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors - // Converting from left to right handed coordinate system: - // x -> -x and switch material FrontSide -> BackSide - parsePoints(length) { - this.currentPoints = []; + if (isBoolean && gl.shadowMap.enabled !== shadows || !is$1.equ(shadows, gl.shadowMap, shallowLoose)) { + const old = gl.shadowMap.enabled; + gl.shadowMap.enabled = !!shadows; + if (!isBoolean) Object.assign(gl.shadowMap, shadows);else gl.shadowMap.type = PCFSoftShadowMap; + if (old !== gl.shadowMap.enabled) gl.shadowMap.needsUpdate = true; + } + } // Safely set color management if available. + // Avoid accessing THREE.ColorManagement to play nice with older versions - for (let i = 0; i < length / 4; i += 3) { - // z -> -z to match three.js right handed coords - this.currentPoints.push(this.reader.getFloat32(), this.reader.getFloat32(), -this.reader.getFloat32()); - } - }, - // parse VMAP or VMAD - // Associates a set of floating-point vectors with a set of points. - // VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * } - // VMAD Associates a set of floating-point vectors with the vertices of specific polygons. - // Similar to VMAP UVs, but associates with polygon vertices rather than points - // to solve to problem of UV seams: VMAD chunks are paired with VMAPs of the same name, - // if they exist. The vector values in the VMAD will then replace those in the - // corresponding VMAP, but only for calculations involving the specified polygons. - // VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * } - parseVertexMapping(length, discontinuous) { - var finalOffset = this.reader.offset + length; - var channelName = this.reader.getString(); - - if (this.reader.offset === finalOffset) { - // then we are in a texture node and the VMAP chunk is just a reference to a UV channel name - this.currentForm.UVChannel = channelName; - return; - } // otherwise reset to initial length and parse normal VMAP CHUNK - - - this.reader.setOffset(this.reader.offset - stringOffset(channelName)); - var type = this.reader.getIDTag(); - this.reader.getUint16(); // dimension - - var name = this.reader.getString(); - var remainingLength = length - 6 - stringOffset(name); - - switch (type) { - case 'TXUV': - this.parseUVMapping(name, finalOffset, discontinuous); - break; + if ('ColorManagement' in THREE) { + setDeep(THREE, legacy, ['ColorManagement', 'legacyMode']); + } - case 'MORF': - case 'SPOT': - this.parseMorphTargets(name, finalOffset, type); // can't be discontinuous + const outputEncoding = linear ? LinearEncoding : sRGBEncoding; + const toneMapping = flat ? NoToneMapping : ACESFilmicToneMapping; + if (gl.outputEncoding !== outputEncoding) gl.outputEncoding = outputEncoding; + if (gl.toneMapping !== toneMapping) gl.toneMapping = toneMapping; // Update color management state - break; - // unsupported VMAPs - - case 'APSL': - case 'NORM': - case 'WGHT': - case 'MNVW': - case 'PICK': - case 'RGB ': - case 'RGBA': - this.reader.skip(remainingLength); - break; + if (state.legacy !== legacy) state.set(() => ({ + legacy + })); + if (state.linear !== linear) state.set(() => ({ + linear + })); + if (state.flat !== flat) state.set(() => ({ + flat + })); // Set gl props - default: - console.warn('LWOLoader: unknown vertex map type: ' + type); - this.reader.skip(remainingLength); - } - }, + if (glConfig && !is$1.fun(glConfig) && !isRenderer(glConfig) && !is$1.equ(glConfig, gl, shallowLoose)) applyProps(gl, glConfig); // Store events internally - parseUVMapping(name, finalOffset, discontinuous) { - var uvIndices = []; - var polyIndices = []; - var uvs = []; + if (events && !state.events.handlers) state.set({ + events: events(store) + }); // Check pixelratio - while (this.reader.offset < finalOffset) { - uvIndices.push(this.reader.getVariableLengthIndex()); - if (discontinuous) polyIndices.push(this.reader.getVariableLengthIndex()); - uvs.push(this.reader.getFloat32(), this.reader.getFloat32()); - } + if (dpr && state.viewport.dpr !== calculateDpr(dpr)) state.setDpr(dpr); // Check size, allow it to take on container bounds initially - if (discontinuous) { - if (!this.currentLayer.discontinuousUVs) this.currentLayer.discontinuousUVs = {}; - this.currentLayer.discontinuousUVs[name] = { - uvIndices: uvIndices, - polyIndices: polyIndices, - uvs: uvs - }; - } else { - if (!this.currentLayer.uvs) this.currentLayer.uvs = {}; - this.currentLayer.uvs[name] = { - uvIndices: uvIndices, - uvs: uvs + size = size || { + width: (_canvas$parentElement = (_canvas$parentElement2 = canvas.parentElement) == null ? void 0 : _canvas$parentElement2.clientWidth) != null ? _canvas$parentElement : 0, + height: (_canvas$parentElement3 = (_canvas$parentElement4 = canvas.parentElement) == null ? void 0 : _canvas$parentElement4.clientHeight) != null ? _canvas$parentElement3 : 0 }; - } - }, + if (!is$1.equ(size, state.size, shallowLoose)) state.setSize(size.width, size.height, size.updateStyle); // Check frameloop - parseMorphTargets(name, finalOffset, type) { - var indices = []; - var points = []; - type = type === 'MORF' ? 'relative' : 'absolute'; + if (state.frameloop !== frameloop) state.setFrameloop(frameloop); // Check pointer missed - while (this.reader.offset < finalOffset) { - indices.push(this.reader.getVariableLengthIndex()); // z -> -z to match three.js right handed coords + if (!state.onPointerMissed) state.set({ + onPointerMissed + }); // Check performance - points.push(this.reader.getFloat32(), this.reader.getFloat32(), -this.reader.getFloat32()); - } + if (performance && !is$1.equ(performance, state.performance, shallowLoose)) state.set(state => ({ + performance: { ...state.performance, + ...performance + } + })); // Set locals - if (!this.currentLayer.morphTargets) this.currentLayer.morphTargets = {}; - this.currentLayer.morphTargets[name] = { - indices: indices, - points: points, - type: type - }; - }, + onCreated = onCreatedCallback; + configured = true; + return this; + }, - // A list of polygons for the current layer. - // POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * } - parsePolygonList(length) { - var finalOffset = this.reader.offset + length; - var type = this.reader.getIDTag(); - var indices = []; // hold a list of polygon sizes, to be split up later + render(children) { + // The root has to be configured before it can be rendered + if (!configured) this.configure(); + reconciler.updateContainer( /*#__PURE__*/React__namespace.createElement(Provider, { + store: store, + children: children, + onCreated: onCreated, + rootElement: canvas + }), fiber, null, () => undefined); + return store; + }, - var polygonDimensions = []; + unmount() { + unmountComponentAtNode(canvas); + } - while (this.reader.offset < finalOffset) { - var numverts = this.reader.getUint16(); //var flags = numverts & 64512; // 6 high order bits are flags - ignoring for now + }; +} - numverts = numverts & 1023; // remaining ten low order bits are vertex num +function Provider({ + store, + children, + onCreated, + rootElement +}) { + useIsomorphicLayoutEffect$1(() => { + const state = store.getState(); // Flag the canvas active, rendering will now begin - polygonDimensions.push(numverts); + state.set(state => ({ + internal: { ...state.internal, + active: true + } + })); // Notifiy that init is completed, the scene graph exists, but nothing has yet rendered - for (let j = 0; j < numverts; j++) indices.push(this.reader.getVariableLengthIndex()); - } + if (onCreated) onCreated(state); // Connect events to the targets parent, this is done to ensure events are registered on + // a shared target, and not on the canvas itself - var geometryData = { - type: type, - vertexIndices: indices, - polygonDimensions: polygonDimensions, - points: this.currentPoints - }; // Note: assuming that all polys will be lines or points if the first is + if (!store.getState().events.connected) state.events.connect == null ? void 0 : state.events.connect(rootElement); // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + return /*#__PURE__*/React__namespace.createElement(context.Provider, { + value: store + }, children); +} - if (polygonDimensions[0] === 1) geometryData.type = 'points';else if (polygonDimensions[0] === 2) geometryData.type = 'lines'; - this.currentLayer.geometry = geometryData; - }, +function unmountComponentAtNode(canvas, callback) { + const root = roots.get(canvas); + const fiber = root == null ? void 0 : root.fiber; - // Lists the tag strings that can be associated with polygons by the PTAG chunk. - // TAGS { tag-string[S0] * } - parseTagStrings(length) { - this.tree.tags = this.reader.getStringArray(length); - }, + if (fiber) { + const state = root == null ? void 0 : root.store.getState(); + if (state) state.internal.active = false; + reconciler.updateContainer(null, fiber, null, () => { + if (state) { + setTimeout(() => { + try { + var _state$gl, _state$gl$renderLists, _state$gl2, _state$gl3; - // Associates tags of a given type with polygons in the most recent POLS chunk. - // PTAG { type[ID4], ( poly[VX], tag[U2] ) * } - parsePolygonTagMapping(length) { - var finalOffset = this.reader.offset + length; - var type = this.reader.getIDTag(); + state.events.disconnect == null ? void 0 : state.events.disconnect(); + (_state$gl = state.gl) == null ? void 0 : (_state$gl$renderLists = _state$gl.renderLists) == null ? void 0 : _state$gl$renderLists.dispose == null ? void 0 : _state$gl$renderLists.dispose(); + (_state$gl2 = state.gl) == null ? void 0 : _state$gl2.forceContextLoss == null ? void 0 : _state$gl2.forceContextLoss(); + if ((_state$gl3 = state.gl) != null && _state$gl3.xr) state.xr.disconnect(); + dispose(state); + roots.delete(canvas); + if (callback) callback(canvas); + } catch (e) { + /* ... */ + } + }, 500); + } + }); + } +} - if (type === 'SURF') { - this.parseMaterialIndices(finalOffset); - } else { - //PART, SMGP, COLR not supported - this.reader.skip(length - 4); - } - }, +reconciler.injectIntoDevTools({ + bundleType: process.env.NODE_ENV === 'production' ? 0 : 1, + rendererPackageName: '@react-three/fiber', + version: React__namespace.version +}); - parseMaterialIndices(finalOffset) { - // array holds polygon index followed by material index - this.currentLayer.geometry.materialIndices = []; +function _extends$3() { + _extends$3 = Object.assign ? Object.assign.bind() : function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - while (this.reader.offset < finalOffset) { - var polygonIndex = this.reader.getVariableLengthIndex(); - var materialIndex = this.reader.getUint16(); - this.currentLayer.geometry.materialIndices.push(polygonIndex, materialIndex); + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } } - }, - - parseUnknownCHUNK(blockID, length) { - console.warn('LWOLoader: unknown chunk type: ' + blockID + ' length: ' + length); // print the chunk plus some bytes padding either side - // printBuffer( this.reader.dv.buffer, this.reader.offset - 20, length + 40 ); - var data = this.reader.getString(length); - this.currentForm[blockID] = data; - } + return target; + }; + return _extends$3.apply(this, arguments); +} -}; +/** + * Returns a function, that, as long as it continues to be invoked, will not + * be triggered. The function will be called after it stops being called for + * N milliseconds. If `immediate` is passed, trigger the function on the + * leading edge, instead of the trailing. The function also has a property 'clear' + * that is a function which will clear the timer to prevent previously scheduled executions. + * + * @source underscore.js + * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ + * @param {Function} function to wrap + * @param {Number} timeout in ms (`100`) + * @param {Boolean} whether to execute at the beginning (`false`) + * @api public + */ -function DataViewReader(buffer) { - this.dv = new DataView(buffer); - this.offset = 0; -} +function debounce(func, wait, immediate){ + var timeout, args, context, timestamp, result; + if (null == wait) wait = 100; -DataViewReader.prototype = { - constructor: DataViewReader, - size: function () { - return this.dv.buffer.byteLength; - }, + function later() { + var last = Date.now() - timestamp; - setOffset(offset) { - if (offset > 0 && offset < this.dv.buffer.byteLength) { - this.offset = offset; + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); } else { - console.error('LWOLoader: invalid buffer offset'); + timeout = null; + if (!immediate) { + result = func.apply(context, args); + context = args = null; + } } - }, - - endOfFile: function () { - if (this.offset >= this.size()) return true; - return false; - }, - skip: function (length) { - this.offset += length; - }, - getUint8: function () { - var value = this.dv.getUint8(this.offset); - this.offset += 1; - return value; - }, - getUint16: function () { - var value = this.dv.getUint16(this.offset); - this.offset += 2; - return value; - }, - getInt32: function () { - var value = this.dv.getInt32(this.offset, false); - this.offset += 4; - return value; - }, - getUint32: function () { - var value = this.dv.getUint32(this.offset, false); - this.offset += 4; - return value; - }, - getUint64: function () { - var low, high; - high = this.getUint32(); - low = this.getUint32(); - return high * 0x100000000 + low; - }, - getFloat32: function () { - var value = this.dv.getFloat32(this.offset, false); - this.offset += 4; - return value; - }, - getFloat32Array: function (size) { - var a = []; - - for (let i = 0; i < size; i++) { - a.push(this.getFloat32()); + } + var debounced = function(){ + context = this; + args = arguments; + timestamp = Date.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; } - return a; - }, - getFloat64: function () { - var value = this.dv.getFloat64(this.offset, this.littleEndian); - this.offset += 8; - return value; - }, - getFloat64Array: function (size) { - var a = []; + return result; + }; - for (let i = 0; i < size; i++) { - a.push(this.getFloat64()); + debounced.clear = function() { + if (timeout) { + clearTimeout(timeout); + timeout = null; } - - return a; - }, - - // get variable-length index data type - // VX ::= index[U2] | (index + 0xFF000000)[U4] - // If the index value is less than 65,280 (0xFF00),then VX === U2 - // otherwise VX === U4 with bits 24-31 set - // When reading an index, if the first byte encountered is 255 (0xFF), then - // the four-byte form is being used and the first byte should be discarded or masked out. - getVariableLengthIndex() { - var firstByte = this.getUint8(); - - if (firstByte === 255) { - return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8(); + }; + + debounced.flush = function() { + if (timeout) { + result = func.apply(context, args); + context = args = null; + + clearTimeout(timeout); + timeout = null; } + }; - return firstByte * 256 + this.getUint8(); - }, - - // An ID tag is a sequence of 4 bytes containing 7-bit ASCII values - getIDTag() { - return this.getString(4); - }, - - getString: function (size) { - if (size === 0) return; // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead + return debounced; +} +// Adds compatibility for ES modules +debounce.debounce = debounce; - var a = []; +var debounce_1 = debounce; - if (size) { - for (let i = 0; i < size; i++) { - a[i] = this.getUint8(); - } - } else { - var currentChar; - var len = 0; +function useMeasure(_temp) { + let { + debounce, + scroll, + polyfill, + offsetSize + } = _temp === void 0 ? { + debounce: 0, + scroll: false, + offsetSize: false + } : _temp; + const ResizeObserver = polyfill || (typeof window === 'undefined' ? class ResizeObserver {} : window.ResizeObserver); - while (currentChar !== 0) { - currentChar = this.getUint8(); - if (currentChar !== 0) a.push(currentChar); - len++; - } + if (!ResizeObserver) { + throw new Error('This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills'); + } - if (!isEven(len + 1)) this.getUint8(); // if string with terminating nullbyte is uneven, extra nullbyte is added - } + const [bounds, set] = React.useState({ + left: 0, + top: 0, + width: 0, + height: 0, + bottom: 0, + right: 0, + x: 0, + y: 0 + }); // keep all state in a ref - return LoaderUtils.decodeText(new Uint8Array(a)); - }, - getStringArray: function (size) { - var a = this.getString(size); - a = a.split('\0'); - return a.filter(Boolean); // return array with any empty strings removed - } -}; // ************** DEBUGGER ************** + const state = React.useRef({ + element: null, + scrollContainers: null, + resizeObserver: null, + lastBounds: bounds + }); // set actual debounce values early, so effects know if they should react accordingly -function Debugger() { - this.active = false; - this.depth = 0; - this.formList = []; -} + const scrollDebounce = debounce ? typeof debounce === 'number' ? debounce : debounce.scroll : null; + const resizeDebounce = debounce ? typeof debounce === 'number' ? debounce : debounce.resize : null; // make sure to update state only as long as the component is truly mounted -Debugger.prototype = { - constructor: Debugger, - enable: function () { - this.active = true; - }, - log: function () { - if (!this.active) return; - var nodeType; + const mounted = React.useRef(false); + React.useEffect(() => { + mounted.current = true; + return () => void (mounted.current = false); + }); // memoize handlers, so event-listeners know when they should update - switch (this.node) { - case 0: - nodeType = 'FORM'; - break; + const [forceRefresh, resizeChange, scrollChange] = React.useMemo(() => { + const callback = () => { + if (!state.current.element) return; + const { + left, + top, + width, + height, + bottom, + right, + x, + y + } = state.current.element.getBoundingClientRect(); + const size = { + left, + top, + width, + height, + bottom, + right, + x, + y + }; - case 1: - nodeType = 'CHK'; - break; + if (state.current.element instanceof HTMLElement && offsetSize) { + size.height = state.current.element.offsetHeight; + size.width = state.current.element.offsetWidth; + } - case 2: - nodeType = 'S-CHK'; - break; - } + Object.freeze(size); + if (mounted.current && !areBoundsEqual(state.current.lastBounds, size)) set(state.current.lastBounds = size); + }; - console.log('| '.repeat(this.depth) + nodeType, this.nodeID, `( ${this.offset} ) -> ( ${this.dataOffset + this.length} )`, this.node == 0 ? ' {' : '', this.skipped ? 'SKIPPED' : '', this.node == 0 && this.skipped ? '}' : ''); + return [callback, resizeDebounce ? debounce_1(callback, resizeDebounce) : callback, scrollDebounce ? debounce_1(callback, scrollDebounce) : callback]; + }, [set, offsetSize, scrollDebounce, resizeDebounce]); // cleanup current scroll-listeners / observers - if (this.node == 0 && !this.skipped) { - this.depth += 1; - this.formList.push(this.dataOffset + this.length); + function removeListeners() { + if (state.current.scrollContainers) { + state.current.scrollContainers.forEach(element => element.removeEventListener('scroll', scrollChange, true)); + state.current.scrollContainers = null; } - this.skipped = false; - }, - closeForms: function () { - if (!this.active) return; - - for (let i = this.formList.length - 1; i >= 0; i--) { - if (this.offset >= this.formList[i]) { - this.depth -= 1; - console.log('| '.repeat(this.depth) + '}'); - this.formList.splice(-1, 1); - } + if (state.current.resizeObserver) { + state.current.resizeObserver.disconnect(); + state.current.resizeObserver = null; } - } -}; // ************** UTILITY FUNCTIONS ************** + } // add scroll-listeners / observers -function isEven(num) { - return num % 2; -} // calculate the length of the string in the buffer -// this will be string.length + nullbyte + optional padbyte to make the length even + function addListeners() { + if (!state.current.element) return; + state.current.resizeObserver = new ResizeObserver(scrollChange); + state.current.resizeObserver.observe(state.current.element); -function stringOffset(string) { - return string.length + 1 + (isEven(string.length + 1) ? 1 : 0); -} // for testing purposes, dump buffer to console -// printBuffer( this.reader.dv.buffer, this.reader.offset, length ); + if (scroll && state.current.scrollContainers) { + state.current.scrollContainers.forEach(scrollContainer => scrollContainer.addEventListener('scroll', scrollChange, { + capture: true, + passive: true + })); + } + } // the ref we expose to the user -function printBuffer(buffer, from, to) { - console.log(LoaderUtils.decodeText(new Uint8Array(buffer, from, to))); -} + const ref = node => { + if (!node || node === state.current.element) return; + removeListeners(); + state.current.element = node; + state.current.scrollContainers = findScrollContainers(node); + addListeners(); + }; // add general event listeners -new Vector3(); -new Vector3(); + useOnWindowScroll(scrollChange, Boolean(scroll)); + useOnWindowResize(resizeChange); // respond to changes that are relevant for the listeners -new Vector3(); + React.useEffect(() => { + removeListeners(); + addListeners(); + }, [scroll, scrollChange, resizeChange]); // remove all listeners when the components unmounts -new Vector3(); + React.useEffect(() => removeListeners, []); + return [ref, bounds, forceRefresh]; +} // Adds native resize listener to window -new Vector3(); -var UPNG = {}; - -UPNG.toRGBA8 = function (out) { - var w = out.width, - h = out.height; - if (out.tabs.acTL == null) return [UPNG.toRGBA8.decodeImage(out.data, w, h, out).buffer]; - var frms = []; - if (out.frames[0].data == null) out.frames[0].data = out.data; - var len = w * h * 4, - img = new Uint8Array(len), - empty = new Uint8Array(len), - prev = new Uint8Array(len); - - for (var i = 0; i < out.frames.length; i++) { - var frm = out.frames[i]; - var fx = frm.rect.x, - fy = frm.rect.y, - fw = frm.rect.width, - fh = frm.rect.height; - var fdata = UPNG.toRGBA8.decodeImage(frm.data, fw, fh, out); - if (i != 0) for (var j = 0; j < len; j++) prev[j] = img[j]; - if (frm.blend == 0) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 0);else if (frm.blend == 1) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 1); - frms.push(img.buffer.slice(0)); - if (frm.dispose == 1) UPNG._copyTile(empty, fw, fh, img, w, h, fx, fy, 0);else if (frm.dispose == 2) for (var j = 0; j < len; j++) img[j] = prev[j]; - } - - return frms; -}; +function useOnWindowResize(onWindowResize) { + React.useEffect(() => { + const cb = onWindowResize; + window.addEventListener('resize', cb); + return () => void window.removeEventListener('resize', cb); + }, [onWindowResize]); +} -UPNG.toRGBA8.decodeImage = function (data, w, h, out) { - var area = w * h, - bpp = UPNG.decode._getBPP(out); - - var bpl = Math.ceil(w * bpp / 8); // bytes per line - - var bf = new Uint8Array(area * 4), - bf32 = new Uint32Array(bf.buffer); - var ctype = out.ctype, - depth = out.depth; - var rs = UPNG._bin.readUshort; - - if (ctype == 6) { - // RGB + alpha - var qarea = area << 2; - if (depth == 8) for (var i = 0; i < qarea; i += 4) { - bf[i] = data[i]; - bf[i + 1] = data[i + 1]; - bf[i + 2] = data[i + 2]; - bf[i + 3] = data[i + 3]; - } - if (depth == 16) for (var i = 0; i < qarea; i++) { - bf[i] = data[i << 1]; - } - } else if (ctype == 2) { - // RGB - var ts = out.tabs['tRNS']; - - if (ts == null) { - if (depth == 8) for (var i = 0; i < area; i++) { - var ti = i * 3; - bf32[i] = 255 << 24 | data[ti + 2] << 16 | data[ti + 1] << 8 | data[ti]; - } - if (depth == 16) for (var i = 0; i < area; i++) { - var ti = i * 6; - bf32[i] = 255 << 24 | data[ti + 4] << 16 | data[ti + 2] << 8 | data[ti]; - } - } else { - var tr = ts[0], - tg = ts[1], - tb = ts[2]; - if (depth == 8) for (var i = 0; i < area; i++) { - var qi = i << 2, - ti = i * 3; - bf32[i] = 255 << 24 | data[ti + 2] << 16 | data[ti + 1] << 8 | data[ti]; - if (data[ti] == tr && data[ti + 1] == tg && data[ti + 2] == tb) bf[qi + 3] = 0; - } - if (depth == 16) for (var i = 0; i < area; i++) { - var qi = i << 2, - ti = i * 6; - bf32[i] = 255 << 24 | data[ti + 4] << 16 | data[ti + 2] << 8 | data[ti]; - if (rs(data, ti) == tr && rs(data, ti + 2) == tg && rs(data, ti + 4) == tb) bf[qi + 3] = 0; - } - } - } else if (ctype == 3) { - // palette - var p = out.tabs['PLTE'], - ap = out.tabs['tRNS'], - tl = ap ? ap.length : 0; //console.log(p, ap); - - if (depth == 1) for (var y = 0; y < h; y++) { - var s0 = y * bpl, - t0 = y * w; - - for (var i = 0; i < w; i++) { - var qi = t0 + i << 2, - j = data[s0 + (i >> 3)] >> 7 - ((i & 7) << 0) & 1, - cj = 3 * j; - bf[qi] = p[cj]; - bf[qi + 1] = p[cj + 1]; - bf[qi + 2] = p[cj + 2]; - bf[qi + 3] = j < tl ? ap[j] : 255; - } - } - if (depth == 2) for (var y = 0; y < h; y++) { - var s0 = y * bpl, - t0 = y * w; - - for (var i = 0; i < w; i++) { - var qi = t0 + i << 2, - j = data[s0 + (i >> 2)] >> 6 - ((i & 3) << 1) & 3, - cj = 3 * j; - bf[qi] = p[cj]; - bf[qi + 1] = p[cj + 1]; - bf[qi + 2] = p[cj + 2]; - bf[qi + 3] = j < tl ? ap[j] : 255; - } - } - if (depth == 4) for (var y = 0; y < h; y++) { - var s0 = y * bpl, - t0 = y * w; - - for (var i = 0; i < w; i++) { - var qi = t0 + i << 2, - j = data[s0 + (i >> 1)] >> 4 - ((i & 1) << 2) & 15, - cj = 3 * j; - bf[qi] = p[cj]; - bf[qi + 1] = p[cj + 1]; - bf[qi + 2] = p[cj + 2]; - bf[qi + 3] = j < tl ? ap[j] : 255; - } - } - if (depth == 8) for (var i = 0; i < area; i++) { - var qi = i << 2, - j = data[i], - cj = 3 * j; - bf[qi] = p[cj]; - bf[qi + 1] = p[cj + 1]; - bf[qi + 2] = p[cj + 2]; - bf[qi + 3] = j < tl ? ap[j] : 255; - } - } else if (ctype == 4) { - // gray + alpha - if (depth == 8) for (var i = 0; i < area; i++) { - var qi = i << 2, - di = i << 1, - gr = data[di]; - bf[qi] = gr; - bf[qi + 1] = gr; - bf[qi + 2] = gr; - bf[qi + 3] = data[di + 1]; - } - if (depth == 16) for (var i = 0; i < area; i++) { - var qi = i << 2, - di = i << 2, - gr = data[di]; - bf[qi] = gr; - bf[qi + 1] = gr; - bf[qi + 2] = gr; - bf[qi + 3] = data[di + 2]; - } - } else if (ctype == 0) { - // gray - var tr = out.tabs['tRNS'] ? out.tabs['tRNS'] : -1; - - for (var y = 0; y < h; y++) { - var off = y * bpl, - to = y * w; - if (depth == 1) for (var x = 0; x < w; x++) { - var gr = 255 * (data[off + (x >>> 3)] >>> 7 - (x & 7) & 1), - al = gr == tr * 255 ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } else if (depth == 2) for (var x = 0; x < w; x++) { - var gr = 85 * (data[off + (x >>> 2)] >>> 6 - ((x & 3) << 1) & 3), - al = gr == tr * 85 ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } else if (depth == 4) for (var x = 0; x < w; x++) { - var gr = 17 * (data[off + (x >>> 1)] >>> 4 - ((x & 1) << 2) & 15), - al = gr == tr * 17 ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } else if (depth == 8) for (var x = 0; x < w; x++) { - var gr = data[off + x], - al = gr == tr ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } else if (depth == 16) for (var x = 0; x < w; x++) { - var gr = data[off + (x << 1)], - al = rs(data, off + (x << 1)) == tr ? 0 : 255; - bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; - } +function useOnWindowScroll(onScroll, enabled) { + React.useEffect(() => { + if (enabled) { + const cb = onScroll; + window.addEventListener('scroll', cb, { + capture: true, + passive: true + }); + return () => void window.removeEventListener('scroll', cb, true); } - } //console.log(Date.now()-time); - + }, [onScroll, enabled]); +} // Returns a list of scroll offsets - return bf; -}; -UPNG.decode = function (buff) { - var data = new Uint8Array(buff), - offset = 8, - bin = UPNG._bin, - rUs = bin.readUshort, - rUi = bin.readUint; - var out = { - tabs: {}, - frames: [] - }; - var dd = new Uint8Array(data.length), - doff = 0; // put all IDAT data into it - - var fd, - foff = 0; // frames - - var text, keyw, bfr; - var mgck = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; - - for (var i = 0; i < 8; i++) if (data[i] != mgck[i]) throw new Error('The input is not a PNG file!'); - - while (offset < data.length) { - var len = bin.readUint(data, offset); - offset += 4; - var type = bin.readASCII(data, offset, 4); - offset += 4; //console.log(type,len); - - if (type == 'IHDR') { - UPNG.decode._IHDR(data, offset, out); - } else if (type == 'CgBI') { - out.tabs[type] = data.slice(offset, offset + 4); - } else if (type == 'IDAT') { - for (var i = 0; i < len; i++) dd[doff + i] = data[offset + i]; - - doff += len; - } else if (type == 'acTL') { - out.tabs[type] = { - num_frames: rUi(data, offset), - num_plays: rUi(data, offset + 4) - }; - fd = new Uint8Array(data.length); - } else if (type == 'fcTL') { - if (foff != 0) { - var fr = out.frames[out.frames.length - 1]; - fr.data = UPNG.decode._decompress(out, fd.slice(0, foff), fr.rect.width, fr.rect.height); - foff = 0; - } +function findScrollContainers(element) { + const result = []; + if (!element || element === document.body) return result; + const { + overflow, + overflowX, + overflowY + } = window.getComputedStyle(element); + if ([overflow, overflowX, overflowY].some(prop => prop === 'auto' || prop === 'scroll')) result.push(element); + return [...result, ...findScrollContainers(element.parentElement)]; +} // Checks if element boundaries are equal - var rct = { - x: rUi(data, offset + 12), - y: rUi(data, offset + 16), - width: rUi(data, offset + 4), - height: rUi(data, offset + 8) - }; - var del = rUs(data, offset + 22); - del = rUs(data, offset + 20) / (del == 0 ? 100 : del); - var frm = { - rect: rct, - delay: Math.round(del * 1000), - dispose: data[offset + 24], - blend: data[offset + 25] - }; //console.log(frm); - - out.frames.push(frm); - } else if (type == 'fdAT') { - for (var i = 0; i < len - 4; i++) fd[foff + i] = data[offset + i + 4]; - - foff += len - 4; - } else if (type == 'pHYs') { - out.tabs[type] = [bin.readUint(data, offset), bin.readUint(data, offset + 4), data[offset + 8]]; - } else if (type == 'cHRM') { - out.tabs[type] = []; - - for (var i = 0; i < 8; i++) out.tabs[type].push(bin.readUint(data, offset + i * 4)); - } else if (type == 'tEXt' || type == 'zTXt') { - if (out.tabs[type] == null) out.tabs[type] = {}; - var nz = bin.nextZero(data, offset); - keyw = bin.readASCII(data, offset, nz - offset); - var tl = offset + len - nz - 1; - if (type == 'tEXt') text = bin.readASCII(data, nz + 1, tl);else { - bfr = UPNG.decode._inflate(data.slice(nz + 2, nz + 2 + tl)); - text = bin.readUTF8(bfr, 0, bfr.length); - } - out.tabs[type][keyw] = text; - } else if (type == 'iTXt') { - if (out.tabs[type] == null) out.tabs[type] = {}; - var nz = 0, - off = offset; - nz = bin.nextZero(data, off); - keyw = bin.readASCII(data, off, nz - off); - off = nz + 1; - var cflag = data[off]; - off += 2; - nz = bin.nextZero(data, off); - bin.readASCII(data, off, nz - off); - off = nz + 1; - nz = bin.nextZero(data, off); - bin.readUTF8(data, off, nz - off); - off = nz + 1; - var tl = len - (off - offset); - if (cflag == 0) text = bin.readUTF8(data, off, tl);else { - bfr = UPNG.decode._inflate(data.slice(off, off + tl)); - text = bin.readUTF8(bfr, 0, bfr.length); - } - out.tabs[type][keyw] = text; - } else if (type == 'PLTE') { - out.tabs[type] = bin.readBytes(data, offset, len); - } else if (type == 'hIST') { - var pl = out.tabs['PLTE'].length / 3; - out.tabs[type] = []; - - for (var i = 0; i < pl; i++) out.tabs[type].push(rUs(data, offset + i * 2)); - } else if (type == 'tRNS') { - if (out.ctype == 3) out.tabs[type] = bin.readBytes(data, offset, len);else if (out.ctype == 0) out.tabs[type] = rUs(data, offset);else if (out.ctype == 2) out.tabs[type] = [rUs(data, offset), rUs(data, offset + 2), rUs(data, offset + 4)]; //else console.log("tRNS for unsupported color type",out.ctype, len); - } else if (type == 'gAMA') out.tabs[type] = bin.readUint(data, offset) / 100000;else if (type == 'sRGB') out.tabs[type] = data[offset];else if (type == 'bKGD') { - if (out.ctype == 0 || out.ctype == 4) out.tabs[type] = [rUs(data, offset)];else if (out.ctype == 2 || out.ctype == 6) out.tabs[type] = [rUs(data, offset), rUs(data, offset + 2), rUs(data, offset + 4)];else if (out.ctype == 3) out.tabs[type] = data[offset]; - } else if (type == 'IEND') { - break; - } //else { console.log("unknown chunk type", type, len); out.tabs[type]=data.slice(offset,offset+len); } - - - offset += len; - bin.readUint(data, offset); - offset += 4; - } - - if (foff != 0) { - var fr = out.frames[out.frames.length - 1]; - fr.data = UPNG.decode._decompress(out, fd.slice(0, foff), fr.rect.width, fr.rect.height); - } - - out.data = UPNG.decode._decompress(out, dd, out.width, out.height); - delete out.compress; - delete out.interlace; - delete out.filter; - return out; -}; -UPNG.decode._decompress = function (out, dd, w, h) { - var bpp = UPNG.decode._getBPP(out), - bpl = Math.ceil(w * bpp / 8), - buff = new Uint8Array((bpl + 1 + out.interlace) * h); +const keys = ['x', 'y', 'top', 'bottom', 'left', 'right', 'width', 'height']; - if (out.tabs['CgBI']) dd = UPNG.inflateRaw(dd, buff);else dd = UPNG.decode._inflate(dd, buff); - if (out.interlace == 0) dd = UPNG.decode._filterZero(dd, out, 0, w, h);else if (out.interlace == 1) dd = UPNG.decode._readInterlace(dd, out); - return dd; -}; +const areBoundsEqual = (a, b) => keys.every(key => a[key] === b[key]); -UPNG.decode._inflate = function (data, buff) { - var out = UPNG['inflateRaw'](new Uint8Array(data.buffer, 2, data.length - 6), buff); - return out; +const DOM_EVENTS = { + onClick: ['click', false], + onContextMenu: ['contextmenu', false], + onDoubleClick: ['dblclick', false], + onWheel: ['wheel', true], + onPointerDown: ['pointerdown', true], + onPointerUp: ['pointerup', true], + onPointerLeave: ['pointerleave', true], + onPointerMove: ['pointermove', true], + onPointerCancel: ['pointercancel', true], + onLostPointerCapture: ['lostpointercapture', true] }; +/** Default R3F event manager for web */ -UPNG.inflateRaw = function () { - var H = {}; - H.H = {}; - - H.H.N = function (N, W) { - var R = Uint8Array, - i = 0, - m = 0, - J = 0, - h = 0, - Q = 0, - X = 0, - u = 0, - w = 0, - d = 0, - v, - C; - if (N[0] == 3 && N[1] == 0) return W ? W : new R(0); - var V = H.H, - n = V.b, - A = V.e, - l = V.R, - M = V.n, - I = V.A, - e = V.Z, - b = V.m, - Z = W == null; - if (Z) W = new R(N.length >>> 2 << 5); - - while (i == 0) { - i = n(N, d, 1); - m = n(N, d + 1, 2); - d += 3; - - if (m == 0) { - if ((d & 7) != 0) d += 8 - (d & 7); - var D = (d >>> 3) + 4, - q = N[D - 4] | N[D - 3] << 8; - if (Z) W = H.H.W(W, w + q); - W.set(new R(N.buffer, N.byteOffset + D, q), w); - d = D + q << 3; - w += q; - continue; - } - - if (Z) W = H.H.W(W, w + (1 << 17)); - - if (m == 1) { - v = b.J; - C = b.h; - X = (1 << 9) - 1; - u = (1 << 5) - 1; - } +function createPointerEvents(store) { + const { + handlePointer + } = createEvents(store); + return { + priority: 1, + enabled: true, - if (m == 2) { - J = A(N, d, 5) + 257; - h = A(N, d + 5, 5) + 1; - Q = A(N, d + 10, 4) + 4; - d += 14; - var j = 1; + compute(event, state, previous) { + // https://github.com/pmndrs/react-three-fiber/pull/782 + // Events trigger outside of canvas when moved, use offsetX/Y by default and allow overrides + state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1); + state.raycaster.setFromCamera(state.pointer, state.camera); + }, - for (var c = 0; c < 38; c += 2) { - b.Q[c] = 0; - b.Q[c + 1] = 0; - } + connected: undefined, + handlers: Object.keys(DOM_EVENTS).reduce((acc, key) => ({ ...acc, + [key]: handlePointer(key) + }), {}), + connect: target => { + var _events$handlers; - for (var c = 0; c < Q; c++) { - var K = A(N, d + c * 3, 3); - b.Q[(b.X[c] << 1) + 1] = K; - if (K > j) j = K; + const { + set, + events + } = store.getState(); + events.disconnect == null ? void 0 : events.disconnect(); + set(state => ({ + events: { ...state.events, + connected: target } + })); + Object.entries((_events$handlers = events.handlers) != null ? _events$handlers : []).forEach(([name, event]) => { + const [eventName, passive] = DOM_EVENTS[name]; + target.addEventListener(eventName, event, { + passive + }); + }); + }, + disconnect: () => { + const { + set, + events + } = store.getState(); - d += 3 * Q; - M(b.Q, j); - I(b.Q, j, b.u); - v = b.w; - C = b.d; - d = l(b.u, (1 << j) - 1, J + h, N, d, b.v); - var r = V.V(b.v, 0, J, b.C); - X = (1 << r) - 1; - var S = V.V(b.v, J, h, b.D); - u = (1 << S) - 1; - M(b.C, r); - I(b.C, r, v); - M(b.D, S); - I(b.D, S, C); - } - - while (!0) { - var T = v[e(N, d) & X]; - d += T & 15; - var p = T >>> 4; - - if (p >>> 8 == 0) { - W[w++] = p; - } else if (p == 256) { - break; - } else { - var z = w + p - 254; + if (events.connected) { + var _events$handlers2; - if (p > 264) { - var _ = b.q[p - 257]; - z = w + (_ >>> 3) + A(N, d, _ & 7); - d += _ & 7; + Object.entries((_events$handlers2 = events.handlers) != null ? _events$handlers2 : []).forEach(([name, event]) => { + if (events && events.connected instanceof HTMLElement) { + const [eventName] = DOM_EVENTS[name]; + events.connected.removeEventListener(eventName, event); } - - var $ = C[e(N, d) & u]; - d += $ & 15; - var s = $ >>> 4, - Y = b.c[s], - a = (Y >>> 4) + n(N, d, Y & 15); - d += Y & 15; - - while (w < z) { - W[w] = W[w++ - a]; - W[w] = W[w++ - a]; - W[w] = W[w++ - a]; - W[w] = W[w++ - a]; + }); + set(state => ({ + events: { ...state.events, + connected: undefined } - - w = z; - } + })); } } - - return W.length == w ? W : W.slice(0, w); - }; - - H.H.W = function (N, W) { - var R = N.length; - if (W <= R) return N; - var V = new Uint8Array(R << 1); - V.set(N, 0); - return V; }; +} - H.H.R = function (N, W, R, V, n, A) { - var l = H.H.e, - M = H.H.Z, - I = 0; - - while (I < R) { - var e = N[M(V, n) & W]; - n += e & 15; - var b = e >>> 4; +/** + * A DOM canvas which accepts threejs elements as children. + * @see https://docs.pmnd.rs/react-three-fiber/api/canvas + */ +const Canvas = /*#__PURE__*/React__namespace.forwardRef(function Canvas({ + children, + fallback, + resize, + style, + gl, + events = createPointerEvents, + shadows, + linear, + flat, + legacy, + orthographic, + frameloop, + dpr, + performance, + raycaster, + camera, + onPointerMissed, + onCreated, + ...props +}, forwardedRef) { + // Create a known catalogue of Threejs-native elements + // This will include the entire THREE namespace by default, users can extend + // their own elements by using the createRoot API instead + React__namespace.useMemo(() => extend(THREE), []); + const [containerRef, { + width, + height + }] = useMeasure({ + scroll: true, + debounce: { + scroll: 50, + resize: 0 + }, + ...resize + }); + const canvasRef = React__namespace.useRef(null); + const divRef = React__namespace.useRef(null); + const [canvas, setCanvas] = React__namespace.useState(null); + React__namespace.useImperativeHandle(forwardedRef, () => canvasRef.current); + const handlePointerMissed = useMutableCallback(onPointerMissed); + const [block, setBlock] = React__namespace.useState(false); + const [error, setError] = React__namespace.useState(false); // Suspend this component if block is a promise (2nd run) - if (b <= 15) { - A[I] = b; - I++; - } else { - var Z = 0, - m = 0; - - if (b == 16) { - m = 3 + l(V, n, 2); - n += 2; - Z = A[I - 1]; - } else if (b == 17) { - m = 3 + l(V, n, 3); - n += 3; - } else if (b == 18) { - m = 11 + l(V, n, 7); - n += 7; - } + if (block) throw block; // Throw exception outwards if anything within canvas throws - var J = I + m; + if (error) throw error; + const root = React__namespace.useRef(null); - while (I < J) { - A[I] = Z; - I++; - } + if (width > 0 && height > 0 && canvas) { + if (!root.current) root.current = createRoot(canvas); + root.current.configure({ + gl, + events, + shadows, + linear, + flat, + legacy, + orthographic, + frameloop, + dpr, + performance, + raycaster, + camera, + size: { + width, + height + }, + // Pass mutable reference to onPointerMissed so it's free to update + onPointerMissed: (...args) => handlePointerMissed.current == null ? void 0 : handlePointerMissed.current(...args), + onCreated: state => { + state.events.connect == null ? void 0 : state.events.connect(divRef.current); + onCreated == null ? void 0 : onCreated(state); } - } - - return n; - }; + }); + root.current.render( /*#__PURE__*/React__namespace.createElement(ErrorBoundary, { + set: setError + }, /*#__PURE__*/React__namespace.createElement(React__namespace.Suspense, { + fallback: /*#__PURE__*/React__namespace.createElement(Block, { + set: setBlock + }) + }, children))); + } - H.H.V = function (N, W, R, V) { - var n = 0, - A = 0, - l = V.length >>> 1; - - while (A < R) { - var M = N[A + W]; - V[A << 1] = 0; - V[(A << 1) + 1] = M; - if (M > n) n = M; - A++; + useIsomorphicLayoutEffect$1(() => { + setCanvas(canvasRef.current); + }, []); + React__namespace.useEffect(() => { + if (canvas) return () => unmountComponentAtNode(canvas); + }, [canvas]); + return /*#__PURE__*/React__namespace.createElement("div", _extends$3({ + ref: divRef, + style: { + position: 'relative', + width: '100%', + height: '100%', + overflow: 'hidden', + ...style } - - while (A < l) { - V[A << 1] = 0; - V[(A << 1) + 1] = 0; - A++; + }, props), /*#__PURE__*/React__namespace.createElement("div", { + ref: containerRef, + style: { + width: '100%', + height: '100%' + } + }, /*#__PURE__*/React__namespace.createElement("canvas", { + ref: canvasRef, + style: { + display: 'block' } + }, fallback))); +}); - return n; - }; +var resizeObservers = []; + +var hasActiveObservations = function () { + return resizeObservers.some(function (ro) { return ro.activeTargets.length > 0; }); +}; - H.H.n = function (N, W) { - var R = H.H.m, - V = N.length, - n, - A, - l, - M, - I, - e = R.j; +var hasSkippedObservations = function () { + return resizeObservers.some(function (ro) { return ro.skippedTargets.length > 0; }); +}; - for (var M = 0; M <= W; M++) e[M] = 0; +var msg = 'ResizeObserver loop completed with undelivered notifications.'; +var deliverResizeLoopError = function () { + var event; + if (typeof ErrorEvent === 'function') { + event = new ErrorEvent('error', { + message: msg + }); + } + else { + event = document.createEvent('Event'); + event.initEvent('error', false, false); + event.message = msg; + } + window.dispatchEvent(event); +}; - for (M = 1; M < V; M += 2) e[N[M]]++; +var ResizeObserverBoxOptions; +(function (ResizeObserverBoxOptions) { + ResizeObserverBoxOptions["BORDER_BOX"] = "border-box"; + ResizeObserverBoxOptions["CONTENT_BOX"] = "content-box"; + ResizeObserverBoxOptions["DEVICE_PIXEL_CONTENT_BOX"] = "device-pixel-content-box"; +})(ResizeObserverBoxOptions || (ResizeObserverBoxOptions = {})); - var b = R.K; - n = 0; - e[0] = 0; +var freeze = function (obj) { return Object.freeze(obj); }; - for (A = 1; A <= W; A++) { - n = n + e[A - 1] << 1; - b[A] = n; +var ResizeObserverSize = (function () { + function ResizeObserverSize(inlineSize, blockSize) { + this.inlineSize = inlineSize; + this.blockSize = blockSize; + freeze(this); } + return ResizeObserverSize; +}()); - for (l = 0; l < V; l += 2) { - I = N[l + 1]; - - if (I != 0) { - N[l] = b[I]; - b[I]++; - } +var DOMRectReadOnly = (function () { + function DOMRectReadOnly(x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.top = this.y; + this.left = this.x; + this.bottom = this.top + this.height; + this.right = this.left + this.width; + return freeze(this); } - }; + DOMRectReadOnly.prototype.toJSON = function () { + var _a = this, x = _a.x, y = _a.y, top = _a.top, right = _a.right, bottom = _a.bottom, left = _a.left, width = _a.width, height = _a.height; + return { x: x, y: y, top: top, right: right, bottom: bottom, left: left, width: width, height: height }; + }; + DOMRectReadOnly.fromRect = function (rectangle) { + return new DOMRectReadOnly(rectangle.x, rectangle.y, rectangle.width, rectangle.height); + }; + return DOMRectReadOnly; +}()); - H.H.A = function (N, W, R) { - var V = N.length, - n = H.H.m, - A = n.r; - - for (var l = 0; l < V; l += 2) if (N[l + 1] != 0) { - var M = l >> 1, - I = N[l + 1], - e = M << 4 | I, - b = W - I, - Z = N[l] << b, - m = Z + (1 << b); - - while (Z != m) { - var J = A[Z] >>> 15 - W; - R[J] = e; - Z++; - } +var isSVG = function (target) { return target instanceof SVGElement && 'getBBox' in target; }; +var isHidden = function (target) { + if (isSVG(target)) { + var _a = target.getBBox(), width = _a.width, height = _a.height; + return !width && !height; + } + var _b = target, offsetWidth = _b.offsetWidth, offsetHeight = _b.offsetHeight; + return !(offsetWidth || offsetHeight || target.getClientRects().length); +}; +var isElement = function (obj) { + var _a, _b; + if (obj instanceof Element) { + return true; + } + var scope = (_b = (_a = obj) === null || _a === void 0 ? void 0 : _a.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView; + return !!(scope && obj instanceof scope.Element); +}; +var isReplacedElement = function (target) { + switch (target.tagName) { + case 'INPUT': + if (target.type !== 'image') { + break; + } + case 'VIDEO': + case 'AUDIO': + case 'EMBED': + case 'OBJECT': + case 'CANVAS': + case 'IFRAME': + case 'IMG': + return true; } - }; + return false; +}; - H.H.l = function (N, W) { - var R = H.H.m.r, - V = 15 - W; +var global$1 = typeof window !== 'undefined' ? window : {}; - for (var n = 0; n < N.length; n += 2) { - var A = N[n] << W - N[n + 1]; - N[n] = R[A] >>> V; +var cache = new WeakMap(); +var scrollRegexp = /auto|scroll/; +var verticalRegexp = /^tb|vertical/; +var IE = (/msie|trident/i).test(global$1.navigator && global$1.navigator.userAgent); +var parseDimension = function (pixel) { return parseFloat(pixel || '0'); }; +var size = function (inlineSize, blockSize, switchSizes) { + if (inlineSize === void 0) { inlineSize = 0; } + if (blockSize === void 0) { blockSize = 0; } + if (switchSizes === void 0) { switchSizes = false; } + return new ResizeObserverSize((switchSizes ? blockSize : inlineSize) || 0, (switchSizes ? inlineSize : blockSize) || 0); +}; +var zeroBoxes = freeze({ + devicePixelContentBoxSize: size(), + borderBoxSize: size(), + contentBoxSize: size(), + contentRect: new DOMRectReadOnly(0, 0, 0, 0) +}); +var calculateBoxSizes = function (target, forceRecalculation) { + if (forceRecalculation === void 0) { forceRecalculation = false; } + if (cache.has(target) && !forceRecalculation) { + return cache.get(target); } - }; - - H.H.M = function (N, W, R) { - R = R << (W & 7); - var V = W >>> 3; - N[V] |= R; - N[V + 1] |= R >>> 8; - }; - - H.H.I = function (N, W, R) { - R = R << (W & 7); - var V = W >>> 3; - N[V] |= R; - N[V + 1] |= R >>> 8; - N[V + 2] |= R >>> 16; - }; - - H.H.e = function (N, W, R) { - return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R) - 1; - }; - - H.H.b = function (N, W, R) { - return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R) - 1; - }; - - H.H.Z = function (N, W) { - return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7); - }; - - H.H.i = function (N, W) { - return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7); - }; - - H.H.m = function () { - var N = Uint16Array, - W = Uint32Array; - return { - K: new N(16), - j: new N(16), - X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], - S: [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 999, 999, 999], - T: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0], - q: new N(32), - p: [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 65535, 65535], - z: [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0], - c: new W(32), - J: new N(512), - _: [], - h: new N(32), - $: [], - w: new N(32768), - C: [], - v: [], - d: new N(32768), - D: [], - u: new N(512), - Q: [], - r: new N(1 << 15), - s: new W(286), - Y: new W(30), - a: new W(19), - t: new W(15e3), - k: new N(1 << 16), - g: new N(1 << 15) - }; - }(); - - (function () { - var N = H.H.m, - W = 1 << 15; - - for (var R = 0; R < W; R++) { - var V = R; - V = (V & 2863311530) >>> 1 | (V & 1431655765) << 1; - V = (V & 3435973836) >>> 2 | (V & 858993459) << 2; - V = (V & 4042322160) >>> 4 | (V & 252645135) << 4; - V = (V & 4278255360) >>> 8 | (V & 16711935) << 8; - N.r[R] = (V >>> 16 | V << 16) >>> 17; + if (isHidden(target)) { + cache.set(target, zeroBoxes); + return zeroBoxes; } - - function n(A, l, M) { - while (l-- != 0) A.push(0, M); + var cs = getComputedStyle(target); + var svg = isSVG(target) && target.ownerSVGElement && target.getBBox(); + var removePadding = !IE && cs.boxSizing === 'border-box'; + var switchSizes = verticalRegexp.test(cs.writingMode || ''); + var canScrollVertically = !svg && scrollRegexp.test(cs.overflowY || ''); + var canScrollHorizontally = !svg && scrollRegexp.test(cs.overflowX || ''); + var paddingTop = svg ? 0 : parseDimension(cs.paddingTop); + var paddingRight = svg ? 0 : parseDimension(cs.paddingRight); + var paddingBottom = svg ? 0 : parseDimension(cs.paddingBottom); + var paddingLeft = svg ? 0 : parseDimension(cs.paddingLeft); + var borderTop = svg ? 0 : parseDimension(cs.borderTopWidth); + var borderRight = svg ? 0 : parseDimension(cs.borderRightWidth); + var borderBottom = svg ? 0 : parseDimension(cs.borderBottomWidth); + var borderLeft = svg ? 0 : parseDimension(cs.borderLeftWidth); + var horizontalPadding = paddingLeft + paddingRight; + var verticalPadding = paddingTop + paddingBottom; + var horizontalBorderArea = borderLeft + borderRight; + var verticalBorderArea = borderTop + borderBottom; + var horizontalScrollbarThickness = !canScrollHorizontally ? 0 : target.offsetHeight - verticalBorderArea - target.clientHeight; + var verticalScrollbarThickness = !canScrollVertically ? 0 : target.offsetWidth - horizontalBorderArea - target.clientWidth; + var widthReduction = removePadding ? horizontalPadding + horizontalBorderArea : 0; + var heightReduction = removePadding ? verticalPadding + verticalBorderArea : 0; + var contentWidth = svg ? svg.width : parseDimension(cs.width) - widthReduction - verticalScrollbarThickness; + var contentHeight = svg ? svg.height : parseDimension(cs.height) - heightReduction - horizontalScrollbarThickness; + var borderBoxWidth = contentWidth + horizontalPadding + verticalScrollbarThickness + horizontalBorderArea; + var borderBoxHeight = contentHeight + verticalPadding + horizontalScrollbarThickness + verticalBorderArea; + var boxes = freeze({ + devicePixelContentBoxSize: size(Math.round(contentWidth * devicePixelRatio), Math.round(contentHeight * devicePixelRatio), switchSizes), + borderBoxSize: size(borderBoxWidth, borderBoxHeight, switchSizes), + contentBoxSize: size(contentWidth, contentHeight, switchSizes), + contentRect: new DOMRectReadOnly(paddingLeft, paddingTop, contentWidth, contentHeight) + }); + cache.set(target, boxes); + return boxes; +}; +var calculateBoxSize = function (target, observedBox, forceRecalculation) { + var _a = calculateBoxSizes(target, forceRecalculation), borderBoxSize = _a.borderBoxSize, contentBoxSize = _a.contentBoxSize, devicePixelContentBoxSize = _a.devicePixelContentBoxSize; + switch (observedBox) { + case ResizeObserverBoxOptions.DEVICE_PIXEL_CONTENT_BOX: + return devicePixelContentBoxSize; + case ResizeObserverBoxOptions.BORDER_BOX: + return borderBoxSize; + default: + return contentBoxSize; } +}; - for (var R = 0; R < 32; R++) { - N.q[R] = N.S[R] << 3 | N.T[R]; - N.c[R] = N.p[R] << 4 | N.z[R]; +var ResizeObserverEntry = (function () { + function ResizeObserverEntry(target) { + var boxes = calculateBoxSizes(target); + this.target = target; + this.contentRect = boxes.contentRect; + this.borderBoxSize = freeze([boxes.borderBoxSize]); + this.contentBoxSize = freeze([boxes.contentBoxSize]); + this.devicePixelContentBoxSize = freeze([boxes.devicePixelContentBoxSize]); } + return ResizeObserverEntry; +}()); - n(N._, 144, 8); - n(N._, 255 - 143, 9); - n(N._, 279 - 255, 7); - n(N._, 287 - 279, 8); - H.H.n(N._, 9); - H.H.A(N._, 9, N.J); - H.H.l(N._, 9); - n(N.$, 32, 5); - H.H.n(N.$, 5); - H.H.A(N.$, 5, N.h); - H.H.l(N.$, 5); - n(N.Q, 19, 0); - n(N.C, 286, 0); - n(N.D, 30, 0); - n(N.v, 320, 0); - })(); - - return H.H.N; -}(); - -UPNG.decode._readInterlace = function (data, out) { - var w = out.width, - h = out.height; - - var bpp = UPNG.decode._getBPP(out), - cbpp = bpp >> 3, - bpl = Math.ceil(w * bpp / 8); - - var img = new Uint8Array(h * bpl); - var di = 0; - var starting_row = [0, 0, 4, 0, 2, 0, 1]; - var starting_col = [0, 4, 0, 2, 0, 1, 0]; - var row_increment = [8, 8, 8, 4, 4, 2, 2]; - var col_increment = [8, 8, 4, 4, 2, 2, 1]; - var pass = 0; - - while (pass < 7) { - var ri = row_increment[pass], - ci = col_increment[pass]; - var sw = 0, - sh = 0; - var cr = starting_row[pass]; - - while (cr < h) { - cr += ri; - sh++; +var calculateDepthForNode = function (node) { + if (isHidden(node)) { + return Infinity; } - - var cc = starting_col[pass]; - - while (cc < w) { - cc += ci; - sw++; + var depth = 0; + var parent = node.parentNode; + while (parent) { + depth += 1; + parent = parent.parentNode; } + return depth; +}; - var bpll = Math.ceil(sw * bpp / 8); - - UPNG.decode._filterZero(data, out, di, sw, sh); - - var y = 0, - row = starting_row[pass]; - var val; - - while (row < h) { - var col = starting_col[pass]; - var cdi = di + y * bpll << 3; - - while (col < w) { - if (bpp == 1) { - val = data[cdi >> 3]; - val = val >> 7 - (cdi & 7) & 1; - img[row * bpl + (col >> 3)] |= val << 7 - ((col & 7) << 0); - } - - if (bpp == 2) { - val = data[cdi >> 3]; - val = val >> 6 - (cdi & 7) & 3; - img[row * bpl + (col >> 2)] |= val << 6 - ((col & 3) << 1); - } - - if (bpp == 4) { - val = data[cdi >> 3]; - val = val >> 4 - (cdi & 7) & 15; - img[row * bpl + (col >> 1)] |= val << 4 - ((col & 1) << 2); - } - - if (bpp >= 8) { - var ii = row * bpl + col * cbpp; - - for (var j = 0; j < cbpp; j++) img[ii + j] = data[(cdi >> 3) + j]; +var broadcastActiveObservations = function () { + var shallowestDepth = Infinity; + var callbacks = []; + resizeObservers.forEach(function processObserver(ro) { + if (ro.activeTargets.length === 0) { + return; } - - cdi += bpp; - col += ci; - } - - y++; - row += ri; + var entries = []; + ro.activeTargets.forEach(function processTarget(ot) { + var entry = new ResizeObserverEntry(ot.target); + var targetDepth = calculateDepthForNode(ot.target); + entries.push(entry); + ot.lastReportedSize = calculateBoxSize(ot.target, ot.observedBox); + if (targetDepth < shallowestDepth) { + shallowestDepth = targetDepth; + } + }); + callbacks.push(function resizeObserverCallback() { + ro.callback.call(ro.observer, entries, ro.observer); + }); + ro.activeTargets.splice(0, ro.activeTargets.length); + }); + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var callback = callbacks_1[_i]; + callback(); } - - if (sw * sh != 0) di += sh * (1 + bpll); - pass = pass + 1; - } - - return img; + return shallowestDepth; }; -UPNG.decode._getBPP = function (out) { - var noc = [1, null, 3, 1, 2, null, 4][out.ctype]; - return noc * out.depth; +var gatherActiveObservationsAtDepth = function (depth) { + resizeObservers.forEach(function processObserver(ro) { + ro.activeTargets.splice(0, ro.activeTargets.length); + ro.skippedTargets.splice(0, ro.skippedTargets.length); + ro.observationTargets.forEach(function processTarget(ot) { + if (ot.isActive()) { + if (calculateDepthForNode(ot.target) > depth) { + ro.activeTargets.push(ot); + } + else { + ro.skippedTargets.push(ot); + } + } + }); + }); }; -UPNG.decode._filterZero = function (data, out, off, w, h) { - var bpp = UPNG.decode._getBPP(out), - bpl = Math.ceil(w * bpp / 8), - paeth = UPNG.decode._paeth; - - bpp = Math.ceil(bpp / 8); - var i, - di, - type = data[off], - x = 0; - if (type > 1) data[off] = [0, 0, 1][type - 2]; - if (type == 3) for (x = bpp; x < bpl; x++) data[x + 1] = data[x + 1] + (data[x + 1 - bpp] >>> 1) & 255; - - for (var y = 0; y < h; y++) { - i = off + y * bpl; - di = i + y + 1; - type = data[di - 1]; - x = 0; - if (type == 0) for (; x < bpl; x++) data[i + x] = data[di + x];else if (type == 1) { - for (; x < bpp; x++) data[i + x] = data[di + x]; - - for (; x < bpl; x++) data[i + x] = data[di + x] + data[i + x - bpp]; - } else if (type == 2) { - for (; x < bpl; x++) data[i + x] = data[di + x] + data[i + x - bpl]; - } else if (type == 3) { - for (; x < bpp; x++) data[i + x] = data[di + x] + (data[i + x - bpl] >>> 1); - - for (; x < bpl; x++) data[i + x] = data[di + x] + (data[i + x - bpl] + data[i + x - bpp] >>> 1); - } else { - for (; x < bpp; x++) data[i + x] = data[di + x] + paeth(0, data[i + x - bpl], 0); - - for (; x < bpl; x++) data[i + x] = data[di + x] + paeth(data[i + x - bpp], data[i + x - bpl], data[i + x - bpp - bpl]); +var process$1 = function () { + var depth = 0; + gatherActiveObservationsAtDepth(depth); + while (hasActiveObservations()) { + depth = broadcastActiveObservations(); + gatherActiveObservationsAtDepth(depth); } - } - - return data; + if (hasSkippedObservations()) { + deliverResizeLoopError(); + } + return depth > 0; }; -UPNG.decode._paeth = function (a, b, c) { - var p = a + b - c, - pa = p - a, - pb = p - b, - pc = p - c; - if (pa * pa <= pb * pb && pa * pa <= pc * pc) return a;else if (pb * pb <= pc * pc) return b; - return c; +var trigger; +var callbacks = []; +var notify = function () { return callbacks.splice(0).forEach(function (cb) { return cb(); }); }; +var queueMicroTask = function (callback) { + if (!trigger) { + var toggle_1 = 0; + var el_1 = document.createTextNode(''); + var config = { characterData: true }; + new MutationObserver(function () { return notify(); }).observe(el_1, config); + trigger = function () { el_1.textContent = "" + (toggle_1 ? toggle_1-- : toggle_1++); }; + } + callbacks.push(callback); + trigger(); }; -UPNG.decode._IHDR = function (data, offset, out) { - var bin = UPNG._bin; - out.width = bin.readUint(data, offset); - offset += 4; - out.height = bin.readUint(data, offset); - offset += 4; - out.depth = data[offset]; - offset++; - out.ctype = data[offset]; - offset++; - out.compress = data[offset]; - offset++; - out.filter = data[offset]; - offset++; - out.interlace = data[offset]; - offset++; +var queueResizeObserver = function (cb) { + queueMicroTask(function ResizeObserver() { + requestAnimationFrame(cb); + }); }; -UPNG._bin = { - nextZero: function (data, p) { - while (data[p] != 0) p++; - - return p; - }, - readUshort: function (buff, p) { - return buff[p] << 8 | buff[p + 1]; - }, - writeUshort: function (buff, p, n) { - buff[p] = n >> 8 & 255; - buff[p + 1] = n & 255; - }, - readUint: function (buff, p) { - return buff[p] * (256 * 256 * 256) + (buff[p + 1] << 16 | buff[p + 2] << 8 | buff[p + 3]); - }, - writeUint: function (buff, p, n) { - buff[p] = n >> 24 & 255; - buff[p + 1] = n >> 16 & 255; - buff[p + 2] = n >> 8 & 255; - buff[p + 3] = n & 255; - }, - readASCII: function (buff, p, l) { - var s = ''; - - for (var i = 0; i < l; i++) s += String.fromCharCode(buff[p + i]); - - return s; - }, - writeASCII: function (data, p, s) { - for (var i = 0; i < s.length; i++) data[p + i] = s.charCodeAt(i); - }, - readBytes: function (buff, p, l) { - var arr = []; - - for (var i = 0; i < l; i++) arr.push(buff[p + i]); - - return arr; - }, - pad: function (n) { - return n.length < 2 ? '0' + n : n; - }, - readUTF8: function (buff, p, l) { - var s = '', - ns; - - for (var i = 0; i < l; i++) s += '%' + UPNG._bin.pad(buff[p + i].toString(16)); - - try { - ns = decodeURIComponent(s); - } catch (e) { - return UPNG._bin.readASCII(buff, p, l); - } - - return ns; - } +var watching = 0; +var isWatching = function () { return !!watching; }; +var CATCH_PERIOD = 250; +var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true }; +var events = [ + 'resize', + 'load', + 'transitionend', + 'animationend', + 'animationstart', + 'animationiteration', + 'keyup', + 'keydown', + 'mouseup', + 'mousedown', + 'mouseover', + 'mouseout', + 'blur', + 'focus' +]; +var time = function (timeout) { + if (timeout === void 0) { timeout = 0; } + return Date.now() + timeout; }; - -UPNG._copyTile = function (sb, sw, sh, tb, tw, th, xoff, yoff, mode) { - var w = Math.min(sw, tw), - h = Math.min(sh, th); - var si = 0, - ti = 0; - - for (var y = 0; y < h; y++) for (var x = 0; x < w; x++) { - if (xoff >= 0 && yoff >= 0) { - si = y * sw + x << 2; - ti = (yoff + y) * tw + xoff + x << 2; - } else { - si = (-yoff + y) * sw - xoff + x << 2; - ti = y * tw + x << 2; - } - - if (mode == 0) { - tb[ti] = sb[si]; - tb[ti + 1] = sb[si + 1]; - tb[ti + 2] = sb[si + 2]; - tb[ti + 3] = sb[si + 3]; - } else if (mode == 1) { - var fa = sb[si + 3] * (1 / 255), - fr = sb[si] * fa, - fg = sb[si + 1] * fa, - fb = sb[si + 2] * fa; - var ba = tb[ti + 3] * (1 / 255), - br = tb[ti] * ba, - bg = tb[ti + 1] * ba, - bb = tb[ti + 2] * ba; - var ifa = 1 - fa, - oa = fa + ba * ifa, - ioa = oa == 0 ? 0 : 1 / oa; - tb[ti + 3] = 255 * oa; - tb[ti + 0] = (fr + br * ifa) * ioa; - tb[ti + 1] = (fg + bg * ifa) * ioa; - tb[ti + 2] = (fb + bb * ifa) * ioa; - } else if (mode == 2) { - // copy only differences, otherwise zero - var fa = sb[si + 3], - fr = sb[si], - fg = sb[si + 1], - fb = sb[si + 2]; - var ba = tb[ti + 3], - br = tb[ti], - bg = tb[ti + 1], - bb = tb[ti + 2]; - - if (fa == ba && fr == br && fg == bg && fb == bb) { - tb[ti] = 0; - tb[ti + 1] = 0; - tb[ti + 2] = 0; - tb[ti + 3] = 0; - } else { - tb[ti] = fr; - tb[ti + 1] = fg; - tb[ti + 2] = fb; - tb[ti + 3] = fa; - } - } else if (mode == 3) { - // check if can be blended - var fa = sb[si + 3], - fr = sb[si], - fg = sb[si + 1], - fb = sb[si + 2]; - var ba = tb[ti + 3], - br = tb[ti], - bg = tb[ti + 1], - bb = tb[ti + 2]; - if (fa == ba && fr == br && fg == bg && fb == bb) continue; //if(fa!=255 && ba!=0) return false; - - if (fa < 220 && ba > 20) return false; +var scheduled = false; +var Scheduler = (function () { + function Scheduler() { + var _this = this; + this.stopped = true; + this.listener = function () { return _this.schedule(); }; } - } - - return true; + Scheduler.prototype.run = function (timeout) { + var _this = this; + if (timeout === void 0) { timeout = CATCH_PERIOD; } + if (scheduled) { + return; + } + scheduled = true; + var until = time(timeout); + queueResizeObserver(function () { + var elementsHaveResized = false; + try { + elementsHaveResized = process$1(); + } + finally { + scheduled = false; + timeout = until - time(); + if (!isWatching()) { + return; + } + if (elementsHaveResized) { + _this.run(1000); + } + else if (timeout > 0) { + _this.run(timeout); + } + else { + _this.start(); + } + } + }); + }; + Scheduler.prototype.schedule = function () { + this.stop(); + this.run(); + }; + Scheduler.prototype.observe = function () { + var _this = this; + var cb = function () { return _this.observer && _this.observer.observe(document.body, observerConfig); }; + document.body ? cb() : global$1.addEventListener('DOMContentLoaded', cb); + }; + Scheduler.prototype.start = function () { + var _this = this; + if (this.stopped) { + this.stopped = false; + this.observer = new MutationObserver(this.listener); + this.observe(); + events.forEach(function (name) { return global$1.addEventListener(name, _this.listener, true); }); + } + }; + Scheduler.prototype.stop = function () { + var _this = this; + if (!this.stopped) { + this.observer && this.observer.disconnect(); + events.forEach(function (name) { return global$1.removeEventListener(name, _this.listener, true); }); + this.stopped = true; + } + }; + return Scheduler; +}()); +var scheduler = new Scheduler(); +var updateCount = function (n) { + !watching && n > 0 && scheduler.start(); + watching += n; + !watching && scheduler.stop(); }; -class LineSegmentsGeometry extends InstancedBufferGeometry { - constructor() { - super(); - - _defineProperty$1(this, "isLineSegmentsGeometry", true); - - _defineProperty$1(this, "type", 'LineSegmentsGeometry'); - - _defineProperty$1(this, "boundingBox", null); - - _defineProperty$1(this, "boundingSphere", null); - - _defineProperty$1(this, "box", new Box3()); - - _defineProperty$1(this, "vector", new Vector3()); - - const positions = [-1, 2, 0, 1, 2, 0, -1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0, -1, -1, 0, 1, -1, 0]; - const uvs = [-1, 2, 1, 2, -1, 1, 1, 1, -1, -1, 1, -1, -1, -2, 1, -2]; - const index = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5]; - this.setIndex(index); - this.setAttribute('position', new Float32BufferAttribute(positions, 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); - } - - applyMatrix4(matrix) { - const start = this.attributes.instanceStart; - const end = this.attributes.instanceEnd; - - if (start !== undefined) { - start.applyMatrix4(matrix); - end.applyMatrix4(matrix); - start.needsUpdate = true; - } - - if (this.boundingBox !== null) { - this.computeBoundingBox(); - } - - if (this.boundingSphere !== null) { - this.computeBoundingSphere(); - } - - return this; - } - - setPositions(array) { - let lineSegments; - - if (array instanceof Float32Array) { - lineSegments = array; - } else if (Array.isArray(array)) { - lineSegments = new Float32Array(array); - } else { - console.error('LineSegmentsGeometry.setPosition requires either a Float32Array or regular array of numbers'); - return this; - } - - const instanceBuffer = new InstancedInterleavedBuffer(lineSegments, 6, 1); // xyz, xyz - - this.setAttribute('instanceStart', new InterleavedBufferAttribute(instanceBuffer, 3, 0)); // xyz - - this.setAttribute('instanceEnd', new InterleavedBufferAttribute(instanceBuffer, 3, 3)); // xyz - // - - this.computeBoundingBox(); - this.computeBoundingSphere(); - return this; - } - - setColors(array) { - let colors; - - if (array instanceof Float32Array) { - colors = array; - } else if (Array.isArray(array)) { - colors = new Float32Array(array); - } else { - console.error('LineSegmentsGeometry.setColors requires either a Float32Array or regular array of numbers'); - return this; - } - - const instanceColorBuffer = new InstancedInterleavedBuffer(colors, 6, 1); // rgb, rgb - - this.setAttribute('instanceColorStart', new InterleavedBufferAttribute(instanceColorBuffer, 3, 0)); // rgb - - this.setAttribute('instanceColorEnd', new InterleavedBufferAttribute(instanceColorBuffer, 3, 3)); // rgb - - return this; - } - - fromWireframeGeometry(geometry) { - this.setPositions(Array.from(geometry.attributes.position.array)); - return this; - } - - fromEdgesGeometry(geometry) { - this.setPositions(Array.from(geometry.attributes.position.array)); - return this; - } - - fromMesh(mesh) { - this.fromWireframeGeometry(new WireframeGeometry(mesh.geometry)); - return this; - } - - fromLineSegments(lineSegments) { - const geometry = lineSegments.geometry; - - if (geometry.isBufferGeometry) { - this.setPositions(Array.from(geometry.attributes.position.array)); // assumes non-indexed - } // set colors, maybe - - - return this; - } - - computeBoundingBox() { - if (this.boundingBox === null) { - this.boundingBox = new Box3(); +var skipNotifyOnElement = function (target) { + return !isSVG(target) + && !isReplacedElement(target) + && getComputedStyle(target).display === 'inline'; +}; +var ResizeObservation = (function () { + function ResizeObservation(target, observedBox) { + this.target = target; + this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX; + this.lastReportedSize = { + inlineSize: 0, + blockSize: 0 + }; } + ResizeObservation.prototype.isActive = function () { + var size = calculateBoxSize(this.target, this.observedBox, true); + if (skipNotifyOnElement(this.target)) { + this.lastReportedSize = size; + } + if (this.lastReportedSize.inlineSize !== size.inlineSize + || this.lastReportedSize.blockSize !== size.blockSize) { + return true; + } + return false; + }; + return ResizeObservation; +}()); - const start = this.attributes.instanceStart; - const end = this.attributes.instanceEnd; - - if (start !== undefined && end !== undefined) { - this.boundingBox.setFromBufferAttribute(start); - this.box.setFromBufferAttribute(end); - this.boundingBox.union(this.box); +var ResizeObserverDetail = (function () { + function ResizeObserverDetail(resizeObserver, callback) { + this.activeTargets = []; + this.skippedTargets = []; + this.observationTargets = []; + this.observer = resizeObserver; + this.callback = callback; } - } + return ResizeObserverDetail; +}()); - computeBoundingSphere() { - if (this.boundingSphere === null) { - this.boundingSphere = new Sphere(); +var observerMap = new WeakMap(); +var getObservationIndex = function (observationTargets, target) { + for (var i = 0; i < observationTargets.length; i += 1) { + if (observationTargets[i].target === target) { + return i; + } } - - if (this.boundingBox === null) { - this.computeBoundingBox(); + return -1; +}; +var ResizeObserverController = (function () { + function ResizeObserverController() { } + ResizeObserverController.connect = function (resizeObserver, callback) { + var detail = new ResizeObserverDetail(resizeObserver, callback); + observerMap.set(resizeObserver, detail); + }; + ResizeObserverController.observe = function (resizeObserver, target, options) { + var detail = observerMap.get(resizeObserver); + var firstObservation = detail.observationTargets.length === 0; + if (getObservationIndex(detail.observationTargets, target) < 0) { + firstObservation && resizeObservers.push(detail); + detail.observationTargets.push(new ResizeObservation(target, options && options.box)); + updateCount(1); + scheduler.schedule(); + } + }; + ResizeObserverController.unobserve = function (resizeObserver, target) { + var detail = observerMap.get(resizeObserver); + var index = getObservationIndex(detail.observationTargets, target); + var lastObservation = detail.observationTargets.length === 1; + if (index >= 0) { + lastObservation && resizeObservers.splice(resizeObservers.indexOf(detail), 1); + detail.observationTargets.splice(index, 1); + updateCount(-1); + } + }; + ResizeObserverController.disconnect = function (resizeObserver) { + var _this = this; + var detail = observerMap.get(resizeObserver); + detail.observationTargets.slice().forEach(function (ot) { return _this.unobserve(resizeObserver, ot.target); }); + detail.activeTargets.splice(0, detail.activeTargets.length); + }; + return ResizeObserverController; +}()); - const start = this.attributes.instanceStart; - const end = this.attributes.instanceEnd; - - if (start !== undefined && end !== undefined) { - const center = this.boundingSphere.center; - - if (this.boundingBox) { - this.boundingBox.getCenter(center); - } - - let maxRadiusSq = 0; - - for (let i = 0, il = start.count; i < il; i++) { - this.vector.fromBufferAttribute(start, i); - maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(this.vector)); - this.vector.fromBufferAttribute(end, i); - maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(this.vector)); - } - - this.boundingSphere.radius = Math.sqrt(maxRadiusSq); - - if (isNaN(this.boundingSphere.radius)) { - console.error('THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this); - } +var ResizeObserver = (function () { + function ResizeObserver(callback) { + if (arguments.length === 0) { + throw new TypeError("Failed to construct 'ResizeObserver': 1 argument required, but only 0 present."); + } + if (typeof callback !== 'function') { + throw new TypeError("Failed to construct 'ResizeObserver': The callback provided as parameter 1 is not a function."); + } + ResizeObserverController.connect(this, callback); } - } - - toJSON() {// todo - } - -} - -class LineGeometry extends LineSegmentsGeometry { - constructor() { - super(); - - _defineProperty$1(this, "type", 'LineGeometry'); - - _defineProperty$1(this, "isLineGeometry", true); - - _defineProperty$1(this, "setColors", array => { - // converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format - const length = array.length - 3; - const colors = new Float32Array(2 * length); - - for (let i = 0; i < length; i += 3) { - colors[2 * i] = array[i]; - colors[2 * i + 1] = array[i + 1]; - colors[2 * i + 2] = array[i + 2]; - colors[2 * i + 3] = array[i + 3]; - colors[2 * i + 4] = array[i + 4]; - colors[2 * i + 5] = array[i + 5]; - } - - super.setColors(colors); - return this; - }); + ResizeObserver.prototype.observe = function (target, options) { + if (arguments.length === 0) { + throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': 1 argument required, but only 0 present."); + } + if (!isElement(target)) { + throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element"); + } + ResizeObserverController.observe(this, target, options); + }; + ResizeObserver.prototype.unobserve = function (target) { + if (arguments.length === 0) { + throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': 1 argument required, but only 0 present."); + } + if (!isElement(target)) { + throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': parameter 1 is not of type 'Element"); + } + ResizeObserverController.unobserve(this, target); + }; + ResizeObserver.prototype.disconnect = function () { + ResizeObserverController.disconnect(this); + }; + ResizeObserver.toString = function () { + return 'function ResizeObserver () { [polyfill code] }'; + }; + return ResizeObserver; +}()); - _defineProperty$1(this, "fromLine", line => { - const geometry = line.geometry; +const v1 = new Vector3(); +const v2 = new Vector3(); +const v3 = new Vector3(); - if (geometry.isBufferGeometry) { - this.setPositions(Array.from(geometry.attributes.position.array)); // assumes non-indexed - } // set colors, maybe +function defaultCalculatePosition(el, camera, size) { + const objectPos = v1.setFromMatrixPosition(el.matrixWorld); + objectPos.project(camera); + const widthHalf = size.width / 2; + const heightHalf = size.height / 2; + return [objectPos.x * widthHalf + widthHalf, -(objectPos.y * heightHalf) + heightHalf]; +} +function isObjectBehindCamera(el, camera) { + const objectPos = v1.setFromMatrixPosition(el.matrixWorld); + const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); + const deltaCamObj = objectPos.sub(cameraPos); + const camDir = camera.getWorldDirection(v3); + return deltaCamObj.angleTo(camDir) > Math.PI / 2; +} - return this; - }); +function isObjectVisible(el, camera, raycaster, occlude) { + const elPos = v1.setFromMatrixPosition(el.matrixWorld); + const screenPos = elPos.clone(); + screenPos.project(camera); + raycaster.setFromCamera(screenPos, camera); + const intersects = raycaster.intersectObjects(occlude, true); - _defineProperty$1(this, "copy", () => { - // todo - return this; - }); + if (intersects.length) { + const intersectionDistance = intersects[0].distance; + const pointDistance = elPos.distanceTo(raycaster.ray.origin); + return pointDistance < intersectionDistance; } - setPositions(array) { - // converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format - const length = array.length - 3; - const points = new Float32Array(2 * length); - - for (let i = 0; i < length; i += 3) { - points[2 * i] = array[i]; - points[2 * i + 1] = array[i + 1]; - points[2 * i + 2] = array[i + 2]; - points[2 * i + 3] = array[i + 3]; - points[2 * i + 4] = array[i + 4]; - points[2 * i + 5] = array[i + 5]; - } + return true; +} - super.setPositions(points); - return this; +function objectScale(el, camera) { + if (camera instanceof OrthographicCamera) { + return camera.zoom; + } else if (camera instanceof PerspectiveCamera) { + const objectPos = v1.setFromMatrixPosition(el.matrixWorld); + const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); + const vFOV = camera.fov * Math.PI / 180; + const dist = objectPos.distanceTo(cameraPos); + const scaleFOV = 2 * Math.tan(vFOV / 2) * dist; + return 1 / scaleFOV; + } else { + return 1; } - } -/** - * parameters = { - * color: , - * linewidth: , - * dashed: , - * dashScale: , - * dashSize: , - * dashOffset: , - * gapSize: , - * resolution: , // to be set by renderer - * } - */ -const LineUniforms = { - linewidth: { - value: 1 - }, - resolution: { - value: new Vector2(1, 1) - }, - dashScale: { - value: 1 - }, - dashSize: { - value: 1 - }, - dashOffset: { - value: 0 - }, - gapSize: { - value: 1 - }, - // todo FIX - maybe change to totalSize - opacity: { - value: 1 +function objectZIndex(el, camera, zIndexRange) { + if (camera instanceof PerspectiveCamera || camera instanceof OrthographicCamera) { + const objectPos = v1.setFromMatrixPosition(el.matrixWorld); + const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); + const dist = objectPos.distanceTo(cameraPos); + const A = (zIndexRange[1] - zIndexRange[0]) / (camera.far - camera.near); + const B = zIndexRange[1] - A * camera.far; + return Math.round(A * dist + B); } -}; -ShaderLib['line'] = { - uniforms: UniformsUtils.merge([UniformsLib.common, UniformsLib.fog, LineUniforms]), - vertexShader: - /* glsl */ - ` - #include - #include - #include - #include - #include - uniform float linewidth; - uniform vec2 resolution; + return undefined; +} + +const epsilon = value => Math.abs(value) < 1e-10 ? 0 : value; - attribute vec3 instanceStart; - attribute vec3 instanceEnd; +function getCSSMatrix(matrix, multipliers, prepend = '') { + let matrix3d = 'matrix3d('; - attribute vec3 instanceColorStart; - attribute vec3 instanceColorEnd; + for (let i = 0; i !== 16; i++) { + matrix3d += epsilon(multipliers[i] * matrix.elements[i]) + (i !== 15 ? ',' : ')'); + } - varying vec2 vUv; + return prepend + matrix3d; +} - #ifdef USE_DASH +const getCameraCSSMatrix = (multipliers => { + return matrix => getCSSMatrix(matrix, multipliers); +})([1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1]); - uniform float dashScale; - attribute float instanceDistanceStart; - attribute float instanceDistanceEnd; - varying float vLineDistance; +const getObjectCSSMatrix = (scaleMultipliers => { + return (matrix, factor) => getCSSMatrix(matrix, scaleMultipliers(factor), 'translate(-50%,-50%)'); +})(f => [1 / f, 1 / f, 1 / f, 1, -1 / f, -1 / f, -1 / f, -1, 1 / f, 1 / f, 1 / f, 1, 1, 1, 1, 1]); - #endif +const Html = /*#__PURE__*/React__namespace.forwardRef(({ + children, + eps = 0.001, + style, + className, + prepend, + center, + fullscreen, + portal, + distanceFactor, + sprite = false, + transform = false, + occlude, + onOcclude, + zIndexRange = [16777271, 0], + calculatePosition = defaultCalculatePosition, + as = 'div', + wrapperClass, + pointerEvents = 'auto', + ...props +}, ref) => { + var _portal$current; - void trimSegment( const in vec4 start, inout vec4 end ) { + const gl = useThree(({ + gl + }) => gl); + const camera = useThree(({ + camera + }) => camera); + const scene = useThree(({ + scene + }) => scene); + const size = useThree(({ + size + }) => size); + const raycaster = useThree(({ + raycaster + }) => raycaster); + const [el] = React__namespace.useState(() => document.createElement(as)); + const root = React__namespace.useRef(); + const group = React__namespace.useRef(null); + const oldZoom = React__namespace.useRef(0); + const oldPosition = React__namespace.useRef([0, 0]); + const transformOuterRef = React__namespace.useRef(null); + const transformInnerRef = React__namespace.useRef(null); + const target = (_portal$current = portal == null ? void 0 : portal.current) !== null && _portal$current !== void 0 ? _portal$current : gl.domElement.parentNode; + React__namespace.useLayoutEffect(() => { + if (group.current) { + const currentRoot = root.current = ReactDOM__namespace.createRoot(el); + scene.updateMatrixWorld(); - // trim end segment so it terminates between the camera plane and the near plane + if (transform) { + el.style.cssText = `position:absolute;top:0;left:0;pointer-events:none;overflow:hidden;`; + } else { + const vec = calculatePosition(group.current, camera, size); + el.style.cssText = `position:absolute;top:0;left:0;transform:translate3d(${vec[0]}px,${vec[1]}px,0);transform-origin:0 0;`; + } - // conservative estimate of the near plane - float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column - float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column - float nearEstimate = - 0.5 * b / a; + if (target) { + if (prepend) target.prepend(el);else target.appendChild(el); + } - float alpha = ( nearEstimate - start.z ) / ( end.z - start.z ); + return () => { + if (target) target.removeChild(el); + currentRoot.unmount(); + }; + } + }, [target, transform]); + React__namespace.useLayoutEffect(() => { + if (wrapperClass) el.className = wrapperClass; + }, [wrapperClass]); + const styles = React__namespace.useMemo(() => { + if (transform) { + return { + position: 'absolute', + top: 0, + left: 0, + width: size.width, + height: size.height, + transformStyle: 'preserve-3d', + pointerEvents: 'none' + }; + } else { + return { + position: 'absolute', + transform: center ? 'translate3d(-50%,-50%,0)' : 'none', + ...(fullscreen && { + top: -size.height / 2, + left: -size.width / 2, + width: size.width, + height: size.height + }), + ...style + }; + } + }, [style, center, fullscreen, size, transform]); + const transformInnerStyles = React__namespace.useMemo(() => ({ + position: 'absolute', + pointerEvents + }), [pointerEvents]); + React__namespace.useLayoutEffect(() => { + if (transform) { + var _root$current; - end.xyz = mix( start.xyz, end.xyz, alpha ); + (_root$current = root.current) == null ? void 0 : _root$current.render( /*#__PURE__*/React__namespace.createElement("div", { + ref: transformOuterRef, + style: styles + }, /*#__PURE__*/React__namespace.createElement("div", { + ref: transformInnerRef, + style: transformInnerStyles + }, /*#__PURE__*/React__namespace.createElement("div", { + ref: ref, + className: className, + style: style, + children: children + })))); + } else { + var _root$current2; - } + (_root$current2 = root.current) == null ? void 0 : _root$current2.render( /*#__PURE__*/React__namespace.createElement("div", { + ref: ref, + style: styles, + className: className, + children: children + })); + } + }); + const visible = React__namespace.useRef(true); + useFrame(() => { + if (group.current) { + camera.updateMatrixWorld(); + group.current.updateWorldMatrix(true, false); + const vec = transform ? oldPosition.current : calculatePosition(group.current, camera, size); - void main() { + if (transform || Math.abs(oldZoom.current - camera.zoom) > eps || Math.abs(oldPosition.current[0] - vec[0]) > eps || Math.abs(oldPosition.current[1] - vec[1]) > eps) { + const isBehindCamera = isObjectBehindCamera(group.current, camera); + let raytraceTarget = false; - #ifdef USE_COLOR + if (typeof occlude === 'boolean') { + if (occlude === true) { + raytraceTarget = [scene]; + } + } else if (Array.isArray(occlude)) { + raytraceTarget = occlude.map(item => item.current); + } - vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd; + const previouslyVisible = visible.current; - #endif + if (raytraceTarget) { + const isvisible = isObjectVisible(group.current, camera, raycaster, raytraceTarget); + visible.current = isvisible && !isBehindCamera; + } else { + visible.current = !isBehindCamera; + } - #ifdef USE_DASH + if (previouslyVisible !== visible.current) { + if (onOcclude) onOcclude(!visible.current);else el.style.display = visible.current ? 'block' : 'none'; + } - vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd; + el.style.zIndex = `${objectZIndex(group.current, camera, zIndexRange)}`; - #endif + if (transform) { + const [widthHalf, heightHalf] = [size.width / 2, size.height / 2]; + const fov = camera.projectionMatrix.elements[5] * heightHalf; + const { + isOrthographicCamera, + top, + left, + bottom, + right + } = camera; + const cameraMatrix = getCameraCSSMatrix(camera.matrixWorldInverse); + const cameraTransform = isOrthographicCamera ? `scale(${fov})translate(${epsilon(-(right + left) / 2)}px,${epsilon((top + bottom) / 2)}px)` : `translateZ(${fov}px)`; + let matrix = group.current.matrixWorld; - float aspect = resolution.x / resolution.y; + if (sprite) { + matrix = camera.matrixWorldInverse.clone().transpose().copyPosition(matrix).scale(group.current.scale); + matrix.elements[3] = matrix.elements[7] = matrix.elements[11] = 0; + matrix.elements[15] = 1; + } - vUv = uv; + el.style.width = size.width + 'px'; + el.style.height = size.height + 'px'; + el.style.perspective = isOrthographicCamera ? '' : `${fov}px`; - // camera space - vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 ); - vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 ); + if (transformOuterRef.current && transformInnerRef.current) { + transformOuterRef.current.style.transform = `${cameraTransform}${cameraMatrix}translate(${widthHalf}px,${heightHalf}px)`; + transformInnerRef.current.style.transform = getObjectCSSMatrix(matrix, 1 / ((distanceFactor || 10) / 400)); + } + } else { + const scale = distanceFactor === undefined ? 1 : objectScale(group.current, camera) * distanceFactor; + el.style.transform = `translate3d(${vec[0]}px,${vec[1]}px,0) scale(${scale})`; + } - // special case for perspective projection, and segments that terminate either in, or behind, the camera plane - // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space - // but we need to perform ndc-space calculations in the shader, so we must address this issue directly - // perhaps there is a more elegant solution -- WestLangley + oldPosition.current = vec; + oldZoom.current = camera.zoom; + } + } + }); + return /*#__PURE__*/React__namespace.createElement("group", _extends$3({}, props, { + ref: group + })); +}); - bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column +function createStore$1(createState) { + let state; + const listeners = /* @__PURE__ */ new Set(); + const setState = (partial, replace) => { + const nextState = typeof partial === "function" ? partial(state) : partial; + if (nextState !== state) { + const previousState = state; + state = replace ? nextState : Object.assign({}, state, nextState); + listeners.forEach((listener) => listener(state, previousState)); + } + }; + const getState = () => state; + const subscribeWithSelector = (listener, selector = getState, equalityFn = Object.is) => { + console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware"); + let currentSlice = selector(state); + function listenerToAdd() { + const nextSlice = selector(state); + if (!equalityFn(currentSlice, nextSlice)) { + const previousSlice = currentSlice; + listener(currentSlice = nextSlice, previousSlice); + } + } + listeners.add(listenerToAdd); + return () => listeners.delete(listenerToAdd); + }; + const subscribe = (listener, selector, equalityFn) => { + if (selector || equalityFn) { + return subscribeWithSelector(listener, selector, equalityFn); + } + listeners.add(listener); + return () => listeners.delete(listener); + }; + const destroy = () => listeners.clear(); + const api = { setState, getState, subscribe, destroy }; + state = createState(setState, getState, api); + return api; +} - if ( perspective ) { +const isSSR$1 = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); +const useIsomorphicLayoutEffect = isSSR$1 ? React.useEffect : React.useLayoutEffect; +function create$3(createState) { + const api = typeof createState === "function" ? createStore$1(createState) : createState; + const useStore = (selector = api.getState, equalityFn = Object.is) => { + const [, forceUpdate] = React.useReducer((c) => c + 1, 0); + const state = api.getState(); + const stateRef = React.useRef(state); + const selectorRef = React.useRef(selector); + const equalityFnRef = React.useRef(equalityFn); + const erroredRef = React.useRef(false); + const currentSliceRef = React.useRef(); + if (currentSliceRef.current === void 0) { + currentSliceRef.current = selector(state); + } + let newStateSlice; + let hasNewStateSlice = false; + if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) { + newStateSlice = selector(state); + hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice); + } + useIsomorphicLayoutEffect(() => { + if (hasNewStateSlice) { + currentSliceRef.current = newStateSlice; + } + stateRef.current = state; + selectorRef.current = selector; + equalityFnRef.current = equalityFn; + erroredRef.current = false; + }); + const stateBeforeSubscriptionRef = React.useRef(state); + useIsomorphicLayoutEffect(() => { + const listener = () => { + try { + const nextState = api.getState(); + const nextStateSlice = selectorRef.current(nextState); + if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) { + stateRef.current = nextState; + currentSliceRef.current = nextStateSlice; + forceUpdate(); + } + } catch (error) { + erroredRef.current = true; + forceUpdate(); + } + }; + const unsubscribe = api.subscribe(listener); + if (api.getState() !== stateBeforeSubscriptionRef.current) { + listener(); + } + return unsubscribe; + }, []); + const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current; + React.useDebugValue(sliceToReturn); + return sliceToReturn; + }; + Object.assign(useStore, api); + useStore[Symbol.iterator] = function() { + console.warn("[useStore, api] = create() is deprecated and will be removed in v4"); + const items = [useStore, api]; + return { + next() { + const done = items.length <= 0; + return { value: items.shift(), done }; + } + }; + }; + return useStore; +} - if ( start.z < 0.0 && end.z >= 0.0 ) { +let saveLastTotalLoaded = 0; +create$3(set => { + DefaultLoadingManager.onStart = (item, loaded, total) => { + set({ + active: true, + item, + loaded, + total, + progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 + }); + }; - trimSegment( start, end ); + DefaultLoadingManager.onLoad = () => { + set({ + active: false + }); + }; - } else if ( end.z < 0.0 && start.z >= 0.0 ) { + DefaultLoadingManager.onError = item => set(state => ({ + errors: [...state.errors, item] + })); - trimSegment( end, start ); + DefaultLoadingManager.onProgress = (item, loaded, total) => { + if (loaded === total) { + saveLastTotalLoaded = total; + } - } + set({ + active: true, + item, + loaded, + total, + progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 || 100 + }); + }; - } + return { + errors: [], + active: false, + progress: 0, + item: '', + loaded: 0, + total: 0 + }; +}); - // clip space - vec4 clipStart = projectionMatrix * start; - vec4 clipEnd = projectionMatrix * end; +function mergeRefs(refs) { + return function (value) { + refs.forEach(function (ref) { + if (typeof ref === "function") { + ref(value); + } else if (ref != null) { + ref.current = value; + } + }); + }; +} - // ndc space - vec2 ndcStart = clipStart.xy / clipStart.w; - vec2 ndcEnd = clipEnd.xy / clipEnd.w; +let updateQueue = makeQueue(); +const raf = fn => schedule(fn, updateQueue); +let writeQueue = makeQueue(); - // direction - vec2 dir = ndcEnd - ndcStart; +raf.write = fn => schedule(fn, writeQueue); - // account for clip-space aspect ratio - dir.x *= aspect; - dir = normalize( dir ); +let onStartQueue = makeQueue(); - // perpendicular to dir - vec2 offset = vec2( dir.y, - dir.x ); +raf.onStart = fn => schedule(fn, onStartQueue); - // undo aspect ratio adjustment - dir.x /= aspect; - offset.x /= aspect; +let onFrameQueue = makeQueue(); - // sign flip - if ( position.x < 0.0 ) offset *= - 1.0; +raf.onFrame = fn => schedule(fn, onFrameQueue); - // endcaps - if ( position.y < 0.0 ) { +let onFinishQueue = makeQueue(); - offset += - dir; +raf.onFinish = fn => schedule(fn, onFinishQueue); - } else if ( position.y > 1.0 ) { +let timeouts = []; - offset += dir; +raf.setTimeout = (handler, ms) => { + let time = raf.now() + ms; - } + let cancel = () => { + let i = timeouts.findIndex(t => t.cancel == cancel); + if (~i) timeouts.splice(i, 1); + pendingCount -= ~i ? 1 : 0; + }; - // adjust for linewidth - offset *= linewidth; + let timeout = { + time, + handler, + cancel + }; + timeouts.splice(findTimeout(time), 0, timeout); + pendingCount += 1; + start(); + return timeout; +}; - // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ... - offset /= resolution.y; +let findTimeout = time => ~(~timeouts.findIndex(t => t.time > time) || ~timeouts.length); - // select end - vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd; +raf.cancel = fn => { + onStartQueue.delete(fn); + onFrameQueue.delete(fn); + updateQueue.delete(fn); + writeQueue.delete(fn); + onFinishQueue.delete(fn); +}; - // back to clip space - offset *= clip.w; +raf.sync = fn => { + sync = true; + raf.batchedUpdates(fn); + sync = false; +}; - clip.xy += offset; +raf.throttle = fn => { + let lastArgs; - gl_Position = clip; + function queuedFn() { + try { + fn(...lastArgs); + } finally { + lastArgs = null; + } + } - vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation + function throttled(...args) { + lastArgs = args; + raf.onStart(queuedFn); + } - #include - #include - #include + throttled.handler = fn; - } - `, - fragmentShader: - /* glsl */ - ` - uniform vec3 diffuse; - uniform float opacity; + throttled.cancel = () => { + onStartQueue.delete(queuedFn); + lastArgs = null; + }; - #ifdef USE_DASH + return throttled; +}; - uniform float dashSize; - uniform float dashOffset; - uniform float gapSize; +let nativeRaf = typeof window != 'undefined' ? window.requestAnimationFrame : () => {}; - #endif +raf.use = impl => nativeRaf = impl; - varying float vLineDistance; +raf.now = typeof performance != 'undefined' ? () => performance.now() : Date.now; - #include - #include - #include - #include - #include +raf.batchedUpdates = fn => fn(); - varying vec2 vUv; +raf.catch = console.error; +raf.frameLoop = 'always'; - void main() { +raf.advance = () => { + if (raf.frameLoop !== 'demand') { + console.warn('Cannot call the manual advancement of rafz whilst frameLoop is not set as demand'); + } else { + update(); + } +}; - #include +let ts = -1; +let pendingCount = 0; +let sync = false; - #ifdef USE_DASH +function schedule(fn, queue) { + if (sync) { + queue.delete(fn); + fn(0); + } else { + queue.add(fn); + start(); + } +} - if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps +function start() { + if (ts < 0) { + ts = 0; - if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX + if (raf.frameLoop !== 'demand') { + nativeRaf(loop); + } + } +} - #endif +function stop() { + ts = -1; +} - float alpha = opacity; +function loop() { + if (~ts) { + nativeRaf(loop); + raf.batchedUpdates(update); + } +} - #ifdef ALPHA_TO_COVERAGE +function update() { + let prevTs = ts; + ts = raf.now(); + let count = findTimeout(ts); - // artifacts appear on some hardware if a derivative is taken within a conditional - float a = vUv.x; - float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; - float len2 = a * a + b * b; - float dlen = fwidth( len2 ); + if (count) { + eachSafely(timeouts.splice(0, count), t => t.handler()); + pendingCount -= count; + } - if ( abs( vUv.y ) > 1.0 ) { + onStartQueue.flush(); + updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667); + onFrameQueue.flush(); + writeQueue.flush(); + onFinishQueue.flush(); - alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 ); + if (!pendingCount) { + stop(); + } +} - } +function makeQueue() { + let next = new Set(); + let current = next; + return { + add(fn) { + pendingCount += current == next && !next.has(fn) ? 1 : 0; + next.add(fn); + }, - #else + delete(fn) { + pendingCount -= current == next && next.has(fn) ? 1 : 0; + return next.delete(fn); + }, - if ( abs( vUv.y ) > 1.0 ) { + flush(arg) { + if (current.size) { + next = new Set(); + pendingCount -= current.size; + eachSafely(current, fn => fn(arg) && next.add(fn)); + pendingCount += next.size; + current = next; + } + } - float a = vUv.x; - float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; - float len2 = a * a + b * b; + }; +} - if ( len2 > 1.0 ) discard; +function eachSafely(values, each) { + values.forEach(value => { + try { + each(value); + } catch (e) { + raf.catch(e); + } + }); +} - } +function noop() {} +const defineHidden = (obj, key, value) => Object.defineProperty(obj, key, { + value, + writable: true, + configurable: true +}); +const is = { + arr: Array.isArray, + obj: a => !!a && a.constructor.name === 'Object', + fun: a => typeof a === 'function', + str: a => typeof a === 'string', + num: a => typeof a === 'number', + und: a => a === undefined +}; +function isEqual(a, b) { + if (is.arr(a)) { + if (!is.arr(b) || a.length !== b.length) return false; - #endif + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } - vec4 diffuseColor = vec4( diffuse, alpha ); + return true; + } - #include - #include + return a === b; +} +const each = (obj, fn) => obj.forEach(fn); +function eachProp(obj, fn, ctx) { + if (is.arr(obj)) { + for (let i = 0; i < obj.length; i++) { + fn.call(ctx, obj[i], `${i}`); + } - gl_FragColor = vec4( diffuseColor.rgb, alpha ); + return; + } - #include - #include - #include - #include + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + fn.call(ctx, obj[key], key); + } + } +} +const toArray = a => is.und(a) ? [] : is.arr(a) ? a : [a]; +const isSSR = () => typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent); - } - ` +let createStringInterpolator$1; +let to; +let colors$1 = null; +let skipAnimation = false; +let willAdvance = noop; +const assign$2 = globals => { + if (globals.to) to = globals.to; + if (globals.now) raf.now = globals.now; + if (globals.colors !== undefined) colors$1 = globals.colors; + if (globals.skipAnimation != null) skipAnimation = globals.skipAnimation; + if (globals.createStringInterpolator) createStringInterpolator$1 = globals.createStringInterpolator; + if (globals.requestAnimationFrame) raf.use(globals.requestAnimationFrame); + if (globals.batchedUpdates) raf.batchedUpdates = globals.batchedUpdates; + if (globals.willAdvance) willAdvance = globals.willAdvance; + if (globals.frameLoop) raf.frameLoop = globals.frameLoop; }; -class LineMaterial extends ShaderMaterial { - constructor(parameters = {}) { - super({ - uniforms: UniformsUtils.clone(ShaderLib['line'].uniforms), - vertexShader: ShaderLib['line'].vertexShader, - fragmentShader: ShaderLib['line'].fragmentShader, - clipping: true // required for clipping support +var globals = /*#__PURE__*/Object.freeze({ + __proto__: null, + get createStringInterpolator () { return createStringInterpolator$1; }, + get to () { return to; }, + get colors () { return colors$1; }, + get skipAnimation () { return skipAnimation; }, + get willAdvance () { return willAdvance; }, + assign: assign$2 +}); - }); - /** - * Everytime I remove this, everything just breaks, - * so I'm just gonna leave it here. - */ +const startQueue = new Set(); +let currentFrame = []; +let prevFrame = []; +let priority = 0; +const frameLoop = { + get idle() { + return !startQueue.size && !currentFrame.length; + }, - _defineProperty$1(this, "isLineMaterial", true); + start(animation) { + if (priority > animation.priority) { + startQueue.add(animation); + raf.onStart(flushStartQueue); + } else { + startSafely(animation); + raf(advance); + } + }, - _defineProperty$1(this, "dashed", false); + advance, - _defineProperty$1(this, "color", new Color(0x000000)); + sort(animation) { + if (priority) { + raf.onFrame(() => frameLoop.sort(animation)); + } else { + const prevIndex = currentFrame.indexOf(animation); - _defineProperty$1(this, "lineWidth", 0); + if (~prevIndex) { + currentFrame.splice(prevIndex, 1); + startUnsafely(animation); + } + } + }, - _defineProperty$1(this, "dashScale", 0); + clear() { + currentFrame = []; + startQueue.clear(); + } - _defineProperty$1(this, "dashOffset", 0); +}; - _defineProperty$1(this, "dashSize", 0); +function flushStartQueue() { + startQueue.forEach(startSafely); + startQueue.clear(); + raf(advance); +} - _defineProperty$1(this, "opacity", 0); +function startSafely(animation) { + if (!currentFrame.includes(animation)) startUnsafely(animation); +} - _defineProperty$1(this, "resolution", new Vector2()); +function startUnsafely(animation) { + currentFrame.splice(findIndex(currentFrame, other => other.priority > animation.priority), 0, animation); +} - _defineProperty$1(this, "alphaToCoverage", false); +function advance(dt) { + const nextFrame = prevFrame; - Object.defineProperties(this, { - color: { - enumerable: true, - get: function () { - return this.uniforms.diffuse.value; - }, - set: function (value) { - const colorObj = new Color(value); - this.uniforms.diffuse.value = colorObj.getHex(); - } - }, - linewidth: { - enumerable: true, - get: function () { - return this.uniforms.linewidth.value; - }, - set: function (value) { - this.uniforms.linewidth.value = value; - } - }, - dashScale: { - enumerable: true, - get: function () { - return this.uniforms.dashScale.value; - }, - set: function (value) { - this.uniforms.dashScale.value = value; - } - }, - dashSize: { - enumerable: true, - get: function () { - return this.uniforms.dashSize.value; - }, - set: function (value) { - this.uniforms.dashSize.value = value; - } - }, - dashOffset: { - enumerable: true, - get: function () { - return this.uniforms.dashOffset.value; - }, - set: function (value) { - this.uniforms.dashOffset.value = value; - } - }, - gapSize: { - enumerable: true, - get: function () { - return this.uniforms.gapSize.value; - }, - set: function (value) { - this.uniforms.gapSize.value = value; - } - }, - opacity: { - enumerable: true, - get: function () { - return this.uniforms.opacity.value; - }, - set: function (value) { - this.uniforms.opacity.value = value; - } - }, - resolution: { - enumerable: true, - get: function () { - return this.uniforms.resolution.value; - }, - set: function (value) { - this.uniforms.resolution.value.copy(value); - } - }, - alphaToCoverage: { - enumerable: true, - get: function () { - return Boolean('ALPHA_TO_COVERAGE' in this.defines); - }, - set: function (value) { - if (Boolean(value) !== Boolean('ALPHA_TO_COVERAGE' in this.defines)) { - this.needsUpdate = true; - } + for (let i = 0; i < currentFrame.length; i++) { + const animation = currentFrame[i]; + priority = animation.priority; - if (value) { - this.defines.ALPHA_TO_COVERAGE = ''; - this.extensions.derivatives = true; - } else { - delete this.defines.ALPHA_TO_COVERAGE; - this.extensions.derivatives = false; - } - } - }, - dashed: { - enumerable: true, - get: function () { - return Boolean('USE_DASH' in this.defines); - }, - set: function (value) { - if (Boolean(value) !== Boolean('USE_DASH' in this.defines)) { - this.needsUpdate = true; - } + if (!animation.idle) { + willAdvance(animation); + animation.advance(dt); - if (value) { - this.defines.USE_DASH = ''; - } else { - delete this.defines.USE_DASH; - } - } + if (!animation.idle) { + nextFrame.push(animation); } - }); - this.setValues(parameters); + } } + priority = 0; + prevFrame = currentFrame; + prevFrame.length = 0; + currentFrame = nextFrame; + return currentFrame.length > 0; } -var Wireframe = function (geometry, material) { - Mesh.call(this); - this.type = 'Wireframe'; - this.geometry = geometry !== undefined ? geometry : new LineSegmentsGeometry(); - this.material = material !== undefined ? material : new LineMaterial({ - color: Math.random() * 0xffffff - }); -}; - -Wireframe.prototype = Object.assign(Object.create(Mesh.prototype), { - constructor: Wireframe, - isWireframe: true, - computeLineDistances: function () { - // for backwards-compatability, but could be a method of LineSegmentsGeometry... - var start = new Vector3(); - var end = new Vector3(); - return function computeLineDistances() { - var geometry = this.geometry; - var instanceStart = geometry.attributes.instanceStart; - var instanceEnd = geometry.attributes.instanceEnd; - var lineDistances = new Float32Array(2 * instanceStart.data.count); - - for (let i = 0, j = 0, l = instanceStart.data.count; i < l; i++, j += 2) { - start.fromBufferAttribute(instanceStart, i); - end.fromBufferAttribute(instanceEnd, i); - lineDistances[j] = j === 0 ? 0 : lineDistances[j - 1]; - lineDistances[j + 1] = lineDistances[j] + start.distanceTo(end); - } - - var instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1); // d0, d1 +function findIndex(arr, test) { + const index = arr.findIndex(test); + return index < 0 ? arr.length : index; +} - geometry.setAttribute('instanceDistanceStart', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0)); // d0 +const colors = { + transparent: 0x00000000, + aliceblue: 0xf0f8ffff, + antiquewhite: 0xfaebd7ff, + aqua: 0x00ffffff, + aquamarine: 0x7fffd4ff, + azure: 0xf0ffffff, + beige: 0xf5f5dcff, + bisque: 0xffe4c4ff, + black: 0x000000ff, + blanchedalmond: 0xffebcdff, + blue: 0x0000ffff, + blueviolet: 0x8a2be2ff, + brown: 0xa52a2aff, + burlywood: 0xdeb887ff, + burntsienna: 0xea7e5dff, + cadetblue: 0x5f9ea0ff, + chartreuse: 0x7fff00ff, + chocolate: 0xd2691eff, + coral: 0xff7f50ff, + cornflowerblue: 0x6495edff, + cornsilk: 0xfff8dcff, + crimson: 0xdc143cff, + cyan: 0x00ffffff, + darkblue: 0x00008bff, + darkcyan: 0x008b8bff, + darkgoldenrod: 0xb8860bff, + darkgray: 0xa9a9a9ff, + darkgreen: 0x006400ff, + darkgrey: 0xa9a9a9ff, + darkkhaki: 0xbdb76bff, + darkmagenta: 0x8b008bff, + darkolivegreen: 0x556b2fff, + darkorange: 0xff8c00ff, + darkorchid: 0x9932ccff, + darkred: 0x8b0000ff, + darksalmon: 0xe9967aff, + darkseagreen: 0x8fbc8fff, + darkslateblue: 0x483d8bff, + darkslategray: 0x2f4f4fff, + darkslategrey: 0x2f4f4fff, + darkturquoise: 0x00ced1ff, + darkviolet: 0x9400d3ff, + deeppink: 0xff1493ff, + deepskyblue: 0x00bfffff, + dimgray: 0x696969ff, + dimgrey: 0x696969ff, + dodgerblue: 0x1e90ffff, + firebrick: 0xb22222ff, + floralwhite: 0xfffaf0ff, + forestgreen: 0x228b22ff, + fuchsia: 0xff00ffff, + gainsboro: 0xdcdcdcff, + ghostwhite: 0xf8f8ffff, + gold: 0xffd700ff, + goldenrod: 0xdaa520ff, + gray: 0x808080ff, + green: 0x008000ff, + greenyellow: 0xadff2fff, + grey: 0x808080ff, + honeydew: 0xf0fff0ff, + hotpink: 0xff69b4ff, + indianred: 0xcd5c5cff, + indigo: 0x4b0082ff, + ivory: 0xfffff0ff, + khaki: 0xf0e68cff, + lavender: 0xe6e6faff, + lavenderblush: 0xfff0f5ff, + lawngreen: 0x7cfc00ff, + lemonchiffon: 0xfffacdff, + lightblue: 0xadd8e6ff, + lightcoral: 0xf08080ff, + lightcyan: 0xe0ffffff, + lightgoldenrodyellow: 0xfafad2ff, + lightgray: 0xd3d3d3ff, + lightgreen: 0x90ee90ff, + lightgrey: 0xd3d3d3ff, + lightpink: 0xffb6c1ff, + lightsalmon: 0xffa07aff, + lightseagreen: 0x20b2aaff, + lightskyblue: 0x87cefaff, + lightslategray: 0x778899ff, + lightslategrey: 0x778899ff, + lightsteelblue: 0xb0c4deff, + lightyellow: 0xffffe0ff, + lime: 0x00ff00ff, + limegreen: 0x32cd32ff, + linen: 0xfaf0e6ff, + magenta: 0xff00ffff, + maroon: 0x800000ff, + mediumaquamarine: 0x66cdaaff, + mediumblue: 0x0000cdff, + mediumorchid: 0xba55d3ff, + mediumpurple: 0x9370dbff, + mediumseagreen: 0x3cb371ff, + mediumslateblue: 0x7b68eeff, + mediumspringgreen: 0x00fa9aff, + mediumturquoise: 0x48d1ccff, + mediumvioletred: 0xc71585ff, + midnightblue: 0x191970ff, + mintcream: 0xf5fffaff, + mistyrose: 0xffe4e1ff, + moccasin: 0xffe4b5ff, + navajowhite: 0xffdeadff, + navy: 0x000080ff, + oldlace: 0xfdf5e6ff, + olive: 0x808000ff, + olivedrab: 0x6b8e23ff, + orange: 0xffa500ff, + orangered: 0xff4500ff, + orchid: 0xda70d6ff, + palegoldenrod: 0xeee8aaff, + palegreen: 0x98fb98ff, + paleturquoise: 0xafeeeeff, + palevioletred: 0xdb7093ff, + papayawhip: 0xffefd5ff, + peachpuff: 0xffdab9ff, + peru: 0xcd853fff, + pink: 0xffc0cbff, + plum: 0xdda0ddff, + powderblue: 0xb0e0e6ff, + purple: 0x800080ff, + rebeccapurple: 0x663399ff, + red: 0xff0000ff, + rosybrown: 0xbc8f8fff, + royalblue: 0x4169e1ff, + saddlebrown: 0x8b4513ff, + salmon: 0xfa8072ff, + sandybrown: 0xf4a460ff, + seagreen: 0x2e8b57ff, + seashell: 0xfff5eeff, + sienna: 0xa0522dff, + silver: 0xc0c0c0ff, + skyblue: 0x87ceebff, + slateblue: 0x6a5acdff, + slategray: 0x708090ff, + slategrey: 0x708090ff, + snow: 0xfffafaff, + springgreen: 0x00ff7fff, + steelblue: 0x4682b4ff, + tan: 0xd2b48cff, + teal: 0x008080ff, + thistle: 0xd8bfd8ff, + tomato: 0xff6347ff, + turquoise: 0x40e0d0ff, + violet: 0xee82eeff, + wheat: 0xf5deb3ff, + white: 0xffffffff, + whitesmoke: 0xf5f5f5ff, + yellow: 0xffff00ff, + yellowgreen: 0x9acd32ff +}; - geometry.setAttribute('instanceDistanceEnd', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1)); // d1 +const NUMBER = '[-+]?\\d*\\.?\\d+'; +const PERCENTAGE = NUMBER + '%'; - return this; - }; - }() -}); +function call$1(...parts) { + return '\\(\\s*(' + parts.join(')\\s*,\\s*(') + ')\\s*\\)'; +} -var WireframeGeometry2 = function (geometry) { - LineSegmentsGeometry.call(this); - this.type = 'WireframeGeometry2'; - this.fromWireframeGeometry(new WireframeGeometry(geometry)); // set colors, maybe -}; +const rgb = new RegExp('rgb' + call$1(NUMBER, NUMBER, NUMBER)); +const rgba = new RegExp('rgba' + call$1(NUMBER, NUMBER, NUMBER, NUMBER)); +const hsl = new RegExp('hsl' + call$1(NUMBER, PERCENTAGE, PERCENTAGE)); +const hsla = new RegExp('hsla' + call$1(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)); +const hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; +const hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; +const hex6 = /^#([0-9a-fA-F]{6})$/; +const hex8 = /^#([0-9a-fA-F]{8})$/; -WireframeGeometry2.prototype = Object.assign(Object.create(LineSegmentsGeometry.prototype), { - constructor: WireframeGeometry2, - isWireframeGeometry2: true -}); +function normalizeColor(color) { + let match; -class LineSegments2 extends Mesh { - constructor(_geometry = new LineSegmentsGeometry(), _material = new LineMaterial({ - color: Math.random() * 0xffffff - })) { - super(_geometry, _material); + if (typeof color === 'number') { + return color >>> 0 === color && color >= 0 && color <= 0xffffffff ? color : null; + } - _defineProperty$1(this, "type", 'LineSegments2'); + if (match = hex6.exec(color)) return parseInt(match[1] + 'ff', 16) >>> 0; - _defineProperty$1(this, "isLineSegments2", true); + if (colors$1 && colors$1[color] !== undefined) { + return colors$1[color]; + } - _defineProperty$1(this, "distStart", new Vector3()); + if (match = rgb.exec(color)) { + return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | 0x000000ff) >>> 0; + } - _defineProperty$1(this, "distEnd", new Vector3()); + if (match = rgba.exec(color)) { + return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | parse1(match[4])) >>> 0; + } - _defineProperty$1(this, "computeLineDistances", () => { - const geometry = this.geometry; - const instanceStart = geometry.attributes.instanceStart; - const instanceEnd = geometry.attributes.instanceEnd; - const lineDistances = new Float32Array(2 * instanceStart.data.count); + if (match = hex3.exec(color)) { + return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + 'ff', 16) >>> 0; + } - for (let i = 0, j = 0, l = instanceStart.data.count; i < l; i++, j += 2) { - this.distStart.fromBufferAttribute(instanceStart, i); - this.distEnd.fromBufferAttribute(instanceEnd, i); - lineDistances[j] = j === 0 ? 0 : lineDistances[j - 1]; - lineDistances[j + 1] = lineDistances[j] + this.distStart.distanceTo(this.distEnd); - } + if (match = hex8.exec(color)) return parseInt(match[1], 16) >>> 0; - const instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1); // d0, d1 + if (match = hex4.exec(color)) { + return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + match[4] + match[4], 16) >>> 0; + } - geometry.setAttribute('instanceDistanceStart', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0)); // d0 + if (match = hsl.exec(color)) { + return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | 0x000000ff) >>> 0; + } - geometry.setAttribute('instanceDistanceEnd', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1)); // d1 + if (match = hsla.exec(color)) { + return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | parse1(match[4])) >>> 0; + } - return this; - }); + return null; +} - _defineProperty$1(this, "rayStart", new Vector4()); +function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; +} - _defineProperty$1(this, "rayEnd", new Vector4()); +function hslToRgb(h, s, l) { + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + const r = hue2rgb(p, q, h + 1 / 3); + const g = hue2rgb(p, q, h); + const b = hue2rgb(p, q, h - 1 / 3); + return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8; +} - _defineProperty$1(this, "ssOrigin", new Vector4()); +function parse255(str) { + const int = parseInt(str, 10); + if (int < 0) return 0; + if (int > 255) return 255; + return int; +} - _defineProperty$1(this, "ssOrigin3", new Vector3()); +function parse360(str) { + const int = parseFloat(str); + return (int % 360 + 360) % 360 / 360; +} - _defineProperty$1(this, "mvMatrix", new Matrix4()); +function parse1(str) { + const num = parseFloat(str); + if (num < 0) return 0; + if (num > 1) return 255; + return Math.round(num * 255); +} - _defineProperty$1(this, "line", new Line3()); +function parsePercentage(str) { + const int = parseFloat(str); + if (int < 0) return 0; + if (int > 100) return 1; + return int / 100; +} - _defineProperty$1(this, "closestPoint", new Vector3()); +function colorToRgba(input) { + let int32Color = normalizeColor(input); + if (int32Color === null) return input; + int32Color = int32Color || 0; + let r = (int32Color & 0xff000000) >>> 24; + let g = (int32Color & 0x00ff0000) >>> 16; + let b = (int32Color & 0x0000ff00) >>> 8; + let a = (int32Color & 0x000000ff) / 255; + return `rgba(${r}, ${g}, ${b}, ${a})`; +} - _defineProperty$1(this, "raycast", (raycaster, intersects) => { - if (raycaster.camera === null) { - console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2.'); - } +const createInterpolator = (range, output, extrapolate) => { + if (is.fun(range)) { + return range; + } - const threshold = 0; - const ray = raycaster.ray; - const camera = raycaster.camera; - const projectionMatrix = camera.projectionMatrix; - const geometry = this.geometry; - const material = this.material; - const resolution = material.resolution; - const lineWidth = material.linewidth + threshold; - const instanceStart = geometry.attributes.instanceStart; - const instanceEnd = geometry.attributes.instanceEnd; // camera forward is negative - - const near = -camera.near; // pick a point 1 unit out along the ray to avoid the ray origin - // sitting at the camera origin which will cause "w" to be 0 when - // applying the projection matrix. - - ray.at(1, this.ssOrigin); // ndc space [ - 1.0, 1.0 ] - - this.ssOrigin.w = 1; - this.ssOrigin.applyMatrix4(camera.matrixWorldInverse); - this.ssOrigin.applyMatrix4(projectionMatrix); - this.ssOrigin.multiplyScalar(1 / this.ssOrigin.w); // screen space - - this.ssOrigin.x *= resolution.x / 2; - this.ssOrigin.y *= resolution.y / 2; - this.ssOrigin.z = 0; - this.ssOrigin3.set(this.ssOrigin.x, this.ssOrigin.y, this.ssOrigin.z); - const matrixWorld = this.matrixWorld; - this.mvMatrix.multiplyMatrices(camera.matrixWorldInverse, matrixWorld); - - for (let i = 0, l = instanceStart.count; i < l; i++) { - this.rayStart.fromBufferAttribute(instanceStart, i); - this.rayEnd.fromBufferAttribute(instanceEnd, i); - this.rayStart.w = 1; - this.rayEnd.w = 1; // camera space - - this.rayStart.applyMatrix4(this.mvMatrix); - this.rayEnd.applyMatrix4(this.mvMatrix); // skip the segment if it's entirely behind the camera - - const isBehindCameraNear = this.rayStart.z > near && this.rayEnd.z > near; - - if (isBehindCameraNear) { - continue; - } // trim the segment if it extends behind camera near - - - if (this.rayStart.z > near) { - const deltaDist = this.rayStart.z - this.rayEnd.z; - const t = (this.rayStart.z - near) / deltaDist; - this.rayStart.lerp(this.rayEnd, t); - } else if (this.rayEnd.z > near) { - const deltaDist = this.rayEnd.z - this.rayStart.z; - const t = (this.rayEnd.z - near) / deltaDist; - this.rayEnd.lerp(this.rayStart, t); - } // clip space - - - this.rayStart.applyMatrix4(projectionMatrix); - this.rayEnd.applyMatrix4(projectionMatrix); // ndc space [ - 1.0, 1.0 ] - - this.rayStart.multiplyScalar(1 / this.rayStart.w); - this.rayEnd.multiplyScalar(1 / this.rayEnd.w); // screen space - - this.rayStart.x *= resolution.x / 2; - this.rayStart.y *= resolution.y / 2; - this.rayEnd.x *= resolution.x / 2; - this.rayEnd.y *= resolution.y / 2; // create 2d segment - - this.line.start.set(this.rayStart.x, this.rayStart.y, this.rayStart.z); - this.line.start.z = 0; - this.line.end.set(this.rayEnd.x, this.rayEnd.y, this.rayEnd.z); - this.line.end.z = 0; // get closest point on ray to segment - - const param = this.line.closestPointToPointParameter(this.ssOrigin3, true); - this.line.at(param, this.closestPoint); // check if the intersection point is within clip space - - const zPos = MathUtils.lerp(this.rayStart.z, this.rayEnd.z, param); - const isInClipSpace = zPos >= -1 && zPos <= 1; - const isInside = this.ssOrigin3.distanceTo(this.closestPoint) < lineWidth * 0.5; - - if (isInClipSpace && isInside) { - this.line.start.fromBufferAttribute(instanceStart, i); - this.line.end.fromBufferAttribute(instanceEnd, i); - this.line.start.applyMatrix4(matrixWorld); - this.line.end.applyMatrix4(matrixWorld); - const pointOnLine = new Vector3(); - const point = new Vector3(); - ray.distanceSqToSegment(this.line.start, this.line.end, point, pointOnLine); - intersects.push({ - distance: ray.origin.distanceTo(point), - point: point, - face: null, - faceIndex: i, - object: this, - uv: undefined, - pointOnLine - }); - } - } + if (is.arr(range)) { + return createInterpolator({ + range, + output: output, + extrapolate }); } -} - -class Line2 extends LineSegments2 { - constructor(geometry = new LineGeometry(), material = new LineMaterial({ - color: Math.random() * 0xffffff - })) { - super(geometry, material); - - _defineProperty$1(this, "type", 'Line2'); - - _defineProperty$1(this, "isLine2", true); + if (is.str(range.output[0])) { + return createStringInterpolator$1(range); } -} - -new Vector3(); + const config = range; + const outputRange = config.output; + const inputRange = config.range || [0, 1]; + const extrapolateLeft = config.extrapolateLeft || config.extrapolate || 'extend'; + const extrapolateRight = config.extrapolateRight || config.extrapolate || 'extend'; -new Vector3(); + const easing = config.easing || (t => t); -new Vector3(); + return input => { + const range = findRange(input, inputRange); + return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight, config.map); + }; +}; -new Vector3(); +function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) { + let result = map ? map(input) : input; -new Matrix3(); + if (result < inputMin) { + if (extrapolateLeft === 'identity') return result;else if (extrapolateLeft === 'clamp') result = inputMin; + } -const _m1 = new Matrix4(); + if (result > inputMax) { + if (extrapolateRight === 'identity') return result;else if (extrapolateRight === 'clamp') result = inputMax; + } -const _obj = new Object3D(); + if (outputMin === outputMax) return outputMin; + if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax; + if (inputMin === -Infinity) result = -result;else if (inputMax === Infinity) result = result - inputMin;else result = (result - inputMin) / (inputMax - inputMin); + result = easing(result); + if (outputMin === -Infinity) result = -result;else if (outputMax === Infinity) result = result + outputMin;else result = result * (outputMax - outputMin) + outputMin; + return result; +} -const _offset = new Vector3(); +function findRange(input, inputRange) { + for (var i = 1; i < inputRange.length - 1; ++i) if (inputRange[i] >= input) break; -class Geometry extends EventDispatcher { - constructor() { - super(); - this.isGeometry = true; - this.uuid = MathUtils.generateUUID(); - this.name = ''; - this.type = 'Geometry'; - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [[]]; - this.morphTargets = []; - this.morphNormals = []; - this.skinWeights = []; - this.skinIndices = []; - this.lineDistances = []; - this.boundingBox = null; - this.boundingSphere = null; // update flags - - this.elementsNeedUpdate = false; - this.verticesNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; - this.groupsNeedUpdate = false; - } - - applyMatrix4(matrix) { - const normalMatrix = new Matrix3().getNormalMatrix(matrix); - - for (let i = 0, il = this.vertices.length; i < il; i++) { - const vertex = this.vertices[i]; - vertex.applyMatrix4(matrix); - } + return i - 1; +} - for (let i = 0, il = this.faces.length; i < il; i++) { - const face = this.faces[i]; - face.normal.applyMatrix3(normalMatrix).normalize(); +function _extends$2() { + _extends$2 = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - for (let j = 0, jl = face.vertexNormals.length; j < jl; j++) { - face.vertexNormals[j].applyMatrix3(normalMatrix).normalize(); + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } } } - if (this.boundingBox !== null) { - this.computeBoundingBox(); - } - - if (this.boundingSphere !== null) { - this.computeBoundingSphere(); - } + return target; + }; - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; - return this; - } + return _extends$2.apply(this, arguments); +} - rotateX(angle) { - // rotate geometry around world x-axis - _m1.makeRotationX(angle); +const $get = Symbol.for('FluidValue.get'); +const $observers = Symbol.for('FluidValue.observers'); - this.applyMatrix4(_m1); - return this; - } +const hasFluidValue = arg => Boolean(arg && arg[$get]); - rotateY(angle) { - // rotate geometry around world y-axis - _m1.makeRotationY(angle); +const getFluidValue = arg => arg && arg[$get] ? arg[$get]() : arg; - this.applyMatrix4(_m1); - return this; +function callFluidObserver(observer, event) { + if (observer.eventObserved) { + observer.eventObserved(event); + } else { + observer(event); } +} - rotateZ(angle) { - // rotate geometry around world z-axis - _m1.makeRotationZ(angle); +function callFluidObservers(target, event) { + let observers = target[$observers]; - this.applyMatrix4(_m1); - return this; + if (observers) { + observers.forEach(observer => { + callFluidObserver(observer, event); + }); } +} - translate(x, y, z) { - // translate geometry - _m1.makeTranslation(x, y, z); - - this.applyMatrix4(_m1); - return this; - } +class FluidValue { + constructor(get) { + this[$get] = void 0; + this[$observers] = void 0; - scale(x, y, z) { - // scale geometry - _m1.makeScale(x, y, z); + if (!get && !(get = this.get)) { + throw Error('Unknown getter'); + } - this.applyMatrix4(_m1); - return this; + setFluidGetter(this, get); } - lookAt(vector) { - _obj.lookAt(vector); - - _obj.updateMatrix(); +} - this.applyMatrix4(_obj.matrix); - return this; - } +const setFluidGetter = (target, get) => setHidden(target, $get, get); - fromBufferGeometry(geometry) { - const scope = this; - const index = geometry.index !== null ? geometry.index : undefined; - const attributes = geometry.attributes; +function addFluidObserver(target, observer) { + if (target[$get]) { + let observers = target[$observers]; - if (attributes.position === undefined) { - console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.'); - return this; + if (!observers) { + setHidden(target, $observers, observers = new Set()); } - const position = attributes.position; - const normal = attributes.normal; - const color = attributes.color; - const uv = attributes.uv; - const uv2 = attributes.uv2; - if (uv2 !== undefined) this.faceVertexUvs[1] = []; - - for (let i = 0; i < position.count; i++) { - scope.vertices.push(new Vector3().fromBufferAttribute(position, i)); + if (!observers.has(observer)) { + observers.add(observer); - if (color !== undefined) { - scope.colors.push(new Color().fromBufferAttribute(color, i)); + if (target.observerAdded) { + target.observerAdded(observers.size, observer); } } + } - function addFace(a, b, c, materialIndex) { - const vertexColors = color === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()]; - const vertexNormals = normal === undefined ? [] : [new Vector3().fromBufferAttribute(normal, a), new Vector3().fromBufferAttribute(normal, b), new Vector3().fromBufferAttribute(normal, c)]; - const face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex); - scope.faces.push(face); - - if (uv !== undefined) { - scope.faceVertexUvs[0].push([new Vector2().fromBufferAttribute(uv, a), new Vector2().fromBufferAttribute(uv, b), new Vector2().fromBufferAttribute(uv, c)]); - } - - if (uv2 !== undefined) { - scope.faceVertexUvs[1].push([new Vector2().fromBufferAttribute(uv2, a), new Vector2().fromBufferAttribute(uv2, b), new Vector2().fromBufferAttribute(uv2, c)]); - } - } + return observer; +} - const groups = geometry.groups; +function removeFluidObserver(target, observer) { + let observers = target[$observers]; - if (groups.length > 0) { - for (let i = 0; i < groups.length; i++) { - const group = groups[i]; - const start = group.start; - const count = group.count; + if (observers && observers.has(observer)) { + const count = observers.size - 1; - for (let j = start, jl = start + count; j < jl; j += 3) { - if (index !== undefined) { - addFace(index.getX(j), index.getX(j + 1), index.getX(j + 2), group.materialIndex); - } else { - addFace(j, j + 1, j + 2, group.materialIndex); - } - } - } + if (count) { + observers.delete(observer); } else { - if (index !== undefined) { - for (let i = 0; i < index.count; i += 3) { - addFace(index.getX(i), index.getX(i + 1), index.getX(i + 2)); - } - } else { - for (let i = 0; i < position.count; i += 3) { - addFace(i, i + 1, i + 2); - } - } + target[$observers] = null; } - this.computeFaceNormals(); - - if (geometry.boundingBox !== null) { - this.boundingBox = geometry.boundingBox.clone(); + if (target.observerRemoved) { + target.observerRemoved(count, observer); } + } +} - if (geometry.boundingSphere !== null) { - this.boundingSphere = geometry.boundingSphere.clone(); - } +const setHidden = (target, key, value) => Object.defineProperty(target, key, { + value, + writable: true, + configurable: true +}); - return this; - } +const numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; +const colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi; +const unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, 'i'); +const rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi; +const cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/; - center() { - this.computeBoundingBox(); - this.boundingBox.getCenter(_offset).negate(); - this.translate(_offset.x, _offset.y, _offset.z); - return this; - } +const variableToRgba = input => { + const [token, fallback] = parseCSSVariable(input); - normalize() { - this.computeBoundingSphere(); - const center = this.boundingSphere.center; - const radius = this.boundingSphere.radius; - const s = radius === 0 ? 1 : 1.0 / radius; - const matrix = new Matrix4(); - matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1); - this.applyMatrix4(matrix); - return this; + if (!token || isSSR()) { + return input; } - computeFaceNormals() { - const cb = new Vector3(), - ab = new Vector3(); - - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const vA = this.vertices[face.a]; - const vB = this.vertices[face.b]; - const vC = this.vertices[face.c]; - cb.subVectors(vC, vB); - ab.subVectors(vA, vB); - cb.cross(ab); - cb.normalize(); - face.normal.copy(cb); - } - } + const value = window.getComputedStyle(document.documentElement).getPropertyValue(token); - computeVertexNormals(areaWeighted = true) { - const vertices = new Array(this.vertices.length); + if (value) { + return value.trim(); + } else if (fallback && fallback.startsWith('--')) { + const _value = window.getComputedStyle(document.documentElement).getPropertyValue(fallback); - for (let v = 0, vl = this.vertices.length; v < vl; v++) { - vertices[v] = new Vector3(); + if (_value) { + return _value; + } else { + return input; } + } else if (fallback && cssVariableRegex.test(fallback)) { + return variableToRgba(fallback); + } else if (fallback) { + return fallback; + } - if (areaWeighted) { - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm - const cb = new Vector3(), - ab = new Vector3(); - - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const vA = this.vertices[face.a]; - const vB = this.vertices[face.b]; - const vC = this.vertices[face.c]; - cb.subVectors(vC, vB); - ab.subVectors(vA, vB); - cb.cross(ab); - vertices[face.a].add(cb); - vertices[face.b].add(cb); - vertices[face.c].add(cb); - } - } else { - this.computeFaceNormals(); + return input; +}; - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - vertices[face.a].add(face.normal); - vertices[face.b].add(face.normal); - vertices[face.c].add(face.normal); - } - } +const parseCSSVariable = current => { + const match = cssVariableRegex.exec(current); + if (!match) return [,]; + const [, token, fallback] = match; + return [token, fallback]; +}; - for (let v = 0, vl = this.vertices.length; v < vl; v++) { - vertices[v].normalize(); - } +let namedColorRegex; - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const vertexNormals = face.vertexNormals; +const rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`; - if (vertexNormals.length === 3) { - vertexNormals[0].copy(vertices[face.a]); - vertexNormals[1].copy(vertices[face.b]); - vertexNormals[2].copy(vertices[face.c]); - } else { - vertexNormals[0] = vertices[face.a].clone(); - vertexNormals[1] = vertices[face.b].clone(); - vertexNormals[2] = vertices[face.c].clone(); - } +const createStringInterpolator = config => { + if (!namedColorRegex) namedColorRegex = colors$1 ? new RegExp(`(${Object.keys(colors$1).join('|')})(?!\\w)`, 'g') : /^\b$/; + const output = config.output.map(value => { + return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba); + }); + const keyframes = output.map(value => value.match(numberRegex).map(Number)); + const outputRanges = keyframes[0].map((_, i) => keyframes.map(values => { + if (!(i in values)) { + throw Error('The arity of each "output" value must be equal'); } - if (this.faces.length > 0) { - this.normalsNeedUpdate = true; - } - } + return values[i]; + })); + const interpolators = outputRanges.map(output => createInterpolator(_extends$2({}, config, { + output + }))); + return input => { + var _output$find; - computeFlatVertexNormals() { - this.computeFaceNormals(); + const missingUnit = !unitRegex.test(output[0]) && ((_output$find = output.find(value => unitRegex.test(value))) == null ? void 0 : _output$find.replace(numberRegex, '')); + let i = 0; + return output[0].replace(numberRegex, () => `${interpolators[i++](input)}${missingUnit || ''}`).replace(rgbaRegex, rgbaRound); + }; +}; - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const vertexNormals = face.vertexNormals; +const prefix = 'react-spring: '; - if (vertexNormals.length === 3) { - vertexNormals[0].copy(face.normal); - vertexNormals[1].copy(face.normal); - vertexNormals[2].copy(face.normal); - } else { - vertexNormals[0] = face.normal.clone(); - vertexNormals[1] = face.normal.clone(); - vertexNormals[2] = face.normal.clone(); - } - } +const once = fn => { + const func = fn; + let called = false; - if (this.faces.length > 0) { - this.normalsNeedUpdate = true; - } + if (typeof func != 'function') { + throw new TypeError(`${prefix}once requires a function parameter`); } - computeMorphNormals() { - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - - if (!face.__originalFaceNormal) { - face.__originalFaceNormal = face.normal.clone(); - } else { - face.__originalFaceNormal.copy(face.normal); - } + return (...args) => { + if (!called) { + func(...args); + called = true; + } + }; +}; - if (!face.__originalVertexNormals) face.__originalVertexNormals = []; +const warnInterpolate = once(console.warn); +function deprecateInterpolate() { + warnInterpolate(`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`); +} +once(console.warn); - for (let i = 0, il = face.vertexNormals.length; i < il; i++) { - if (!face.__originalVertexNormals[i]) { - face.__originalVertexNormals[i] = face.vertexNormals[i].clone(); - } else { - face.__originalVertexNormals[i].copy(face.vertexNormals[i]); - } - } - } // use temp geometry to compute face and vertex normals for each morph - - - const tmpGeo = new Geometry(); - tmpGeo.faces = this.faces; - - for (let i = 0, il = this.morphTargets.length; i < il; i++) { - // create on first access - if (!this.morphNormals[i]) { - this.morphNormals[i] = {}; - this.morphNormals[i].faceNormals = []; - this.morphNormals[i].vertexNormals = []; - const dstNormalsFace = this.morphNormals[i].faceNormals; - const dstNormalsVertex = this.morphNormals[i].vertexNormals; - - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const faceNormal = new Vector3(); - const vertexNormals = { - a: new Vector3(), - b: new Vector3(), - c: new Vector3() - }; - dstNormalsFace.push(faceNormal); - dstNormalsVertex.push(vertexNormals); - } - } +function isAnimatedString(value) { + return is.str(value) && (value[0] == '#' || /\d/.test(value) || !isSSR() && cssVariableRegex.test(value) || value in (colors$1 || {})); +} - const morphNormals = this.morphNormals[i]; // set vertices to morph target +const useLayoutEffect = typeof window !== 'undefined' && window.document && window.document.createElement ? React__namespace.useLayoutEffect : React__namespace.useEffect; - tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals +const useIsMounted = () => { + const isMounted = React.useRef(false); + useLayoutEffect(() => { + isMounted.current = true; + return () => { + isMounted.current = false; + }; + }, []); + return isMounted; +}; - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); // store morph normals +function useForceUpdate() { + const update = React.useState()[1]; + const isMounted = useIsMounted(); + return () => { + if (isMounted.current) { + update(Math.random()); + } + }; +} - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - const faceNormal = morphNormals.faceNormals[f]; - const vertexNormals = morphNormals.vertexNormals[f]; - faceNormal.copy(face.normal); - vertexNormals.a.copy(face.vertexNormals[0]); - vertexNormals.b.copy(face.vertexNormals[1]); - vertexNormals.c.copy(face.vertexNormals[2]); - } - } // restore original normals +function useMemoOne(getResult, inputs) { + const [initial] = React.useState(() => ({ + inputs, + result: getResult() + })); + const committed = React.useRef(); + const prevCache = committed.current; + let cache = prevCache; + if (cache) { + const useCache = Boolean(inputs && cache.inputs && areInputsEqual(inputs, cache.inputs)); - for (let f = 0, fl = this.faces.length; f < fl; f++) { - const face = this.faces[f]; - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + if (!useCache) { + cache = { + inputs, + result: getResult() + }; } + } else { + cache = initial; } - computeBoundingBox() { - if (this.boundingBox === null) { - this.boundingBox = new Box3(); - } - - this.boundingBox.setFromPoints(this.vertices); - } + React.useEffect(() => { + committed.current = cache; - computeBoundingSphere() { - if (this.boundingSphere === null) { - this.boundingSphere = new Sphere(); + if (prevCache == initial) { + initial.inputs = initial.result = undefined; } + }, [cache]); + return cache.result; +} - this.boundingSphere.setFromPoints(this.vertices); +function areInputsEqual(next, prev) { + if (next.length !== prev.length) { + return false; } - merge(geometry, matrix, materialIndexOffset = 0) { - if (!(geometry && geometry.isGeometry)) { - console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry); - return; + for (let i = 0; i < next.length; i++) { + if (next[i] !== prev[i]) { + return false; } + } - let normalMatrix; - const vertexOffset = this.vertices.length, - vertices1 = this.vertices, - vertices2 = geometry.vertices, - faces1 = this.faces, - faces2 = geometry.faces, - colors1 = this.colors, - colors2 = geometry.colors; - - if (matrix !== undefined) { - normalMatrix = new Matrix3().getNormalMatrix(matrix); - } // vertices - - - for (let i = 0, il = vertices2.length; i < il; i++) { - const vertex = vertices2[i]; - const vertexCopy = vertex.clone(); - if (matrix !== undefined) vertexCopy.applyMatrix4(matrix); - vertices1.push(vertexCopy); - } // colors - - - for (let i = 0, il = colors2.length; i < il; i++) { - colors1.push(colors2[i].clone()); - } // faces - - - for (let i = 0, il = faces2.length; i < il; i++) { - const face = faces2[i]; - let normal, color; - const faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; - const faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset); - faceCopy.normal.copy(face.normal); - - if (normalMatrix !== undefined) { - faceCopy.normal.applyMatrix3(normalMatrix).normalize(); - } - - for (let j = 0, jl = faceVertexNormals.length; j < jl; j++) { - normal = faceVertexNormals[j].clone(); - - if (normalMatrix !== undefined) { - normal.applyMatrix3(normalMatrix).normalize(); - } - - faceCopy.vertexNormals.push(normal); - } - - faceCopy.color.copy(face.color); - - for (let j = 0, jl = faceVertexColors.length; j < jl; j++) { - color = faceVertexColors[j]; - faceCopy.vertexColors.push(color.clone()); - } + return true; +} - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - faces1.push(faceCopy); - } // uvs +const useOnce = effect => React.useEffect(effect, emptyDeps); +const emptyDeps = []; +const $node = Symbol.for('Animated:node'); +const isAnimated = value => !!value && value[$node] === value; +const getAnimated = owner => owner && owner[$node]; +const setAnimated = (owner, node) => defineHidden(owner, $node, node); +const getPayload = owner => owner && owner[$node] && owner[$node].getPayload(); +class Animated { + constructor() { + this.payload = void 0; + setAnimated(this, this); + } - for (let i = 0, il = geometry.faceVertexUvs.length; i < il; i++) { - const faceVertexUvs2 = geometry.faceVertexUvs[i]; - if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = []; + getPayload() { + return this.payload || []; + } - for (let j = 0, jl = faceVertexUvs2.length; j < jl; j++) { - const uvs2 = faceVertexUvs2[j], - uvsCopy = []; +} - for (let k = 0, kl = uvs2.length; k < kl; k++) { - uvsCopy.push(uvs2[k].clone()); - } +class AnimatedValue extends Animated { + constructor(_value) { + super(); + this.done = true; + this.elapsedTime = void 0; + this.lastPosition = void 0; + this.lastVelocity = void 0; + this.v0 = void 0; + this.durationProgress = 0; + this._value = _value; - this.faceVertexUvs[i].push(uvsCopy); - } + if (is.num(this._value)) { + this.lastPosition = this._value; } } - mergeMesh(mesh) { - if (!(mesh && mesh.isMesh)) { - console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh); - return; - } - - if (mesh.matrixAutoUpdate) mesh.updateMatrix(); - this.merge(mesh.geometry, mesh.matrix); + static create(value) { + return new AnimatedValue(value); } - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ - - - mergeVertices(precisionPoints = 4) { - const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) - - const unique = [], - changes = []; - const precision = Math.pow(10, precisionPoints); - - for (let i = 0, il = this.vertices.length; i < il; i++) { - const v = this.vertices[i]; - const key = `${Math.round(v.x * precision)}_${Math.round(v.y * precision)}_${Math.round(v.z * precision)}`; - if (verticesMap[key] === undefined) { - verticesMap[key] = i; - unique.push(this.vertices[i]); - changes[i] = unique.length - 1; - } else { - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[i] = changes[verticesMap[key]]; - } - } // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. + getPayload() { + return [this]; + } + getValue() { + return this._value; + } - const faceIndicesToRemove = []; + setValue(value, step) { + if (is.num(value)) { + this.lastPosition = value; - for (let i = 0, il = this.faces.length; i < il; i++) { - const face = this.faces[i]; - face.a = changes[face.a]; - face.b = changes[face.b]; - face.c = changes[face.c]; - const indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3 - // we have to remove the face as nothing can be saved + if (step) { + value = Math.round(value / step) * step; - for (let n = 0; n < 3; n++) { - if (indices[n] === indices[(n + 1) % 3]) { - faceIndicesToRemove.push(i); - break; + if (this.done) { + this.lastPosition = value; } } } - for (let i = faceIndicesToRemove.length - 1; i >= 0; i--) { - const idx = faceIndicesToRemove[i]; - this.faces.splice(idx, 1); - - for (let j = 0, jl = this.faceVertexUvs.length; j < jl; j++) { - this.faceVertexUvs[j].splice(idx, 1); - } - } // Use unique set of vertices - - - const diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; - } - - setFromPoints(points) { - this.vertices = []; - - for (let i = 0, l = points.length; i < l; i++) { - const point = points[i]; - this.vertices.push(new Vector3(point.x, point.y, point.z || 0)); + if (this._value === value) { + return false; } - return this; + this._value = value; + return true; } - sortFacesByMaterialIndex() { - const faces = this.faces; - const length = faces.length; // tag faces - - for (let i = 0; i < length; i++) { - faces[i]._id = i; - } // sort faces - + reset() { + const { + done + } = this; + this.done = false; - function materialIndexSort(a, b) { - return a.materialIndex - b.materialIndex; + if (is.num(this._value)) { + this.elapsedTime = 0; + this.durationProgress = 0; + this.lastPosition = this._value; + if (done) this.lastVelocity = null; + this.v0 = null; } + } - faces.sort(materialIndexSort); // sort uvs - - const uvs1 = this.faceVertexUvs[0]; - const uvs2 = this.faceVertexUvs[1]; - let newUvs1, newUvs2; - if (uvs1 && uvs1.length === length) newUvs1 = []; - if (uvs2 && uvs2.length === length) newUvs2 = []; - - for (let i = 0; i < length; i++) { - const id = faces[i]._id; - if (newUvs1) newUvs1.push(uvs1[id]); - if (newUvs2) newUvs2.push(uvs2[id]); - } +} - if (newUvs1) this.faceVertexUvs[0] = newUvs1; - if (newUvs2) this.faceVertexUvs[1] = newUvs2; +class AnimatedString extends AnimatedValue { + constructor(value) { + super(0); + this._string = null; + this._toString = void 0; + this._toString = createInterpolator({ + output: [value, value] + }); } - toJSON() { - const data = { - metadata: { - version: 4.5, - type: 'Geometry', - generator: 'Geometry.toJSON' - } - }; // standard Geometry serialization - - data.uuid = this.uuid; - data.type = this.type; - if (this.name !== '') data.name = this.name; + static create(value) { + return new AnimatedString(value); + } - if (this.parameters !== undefined) { - const parameters = this.parameters; + getValue() { + let value = this._string; + return value == null ? this._string = this._toString(this._value) : value; + } - for (let key in parameters) { - if (parameters[key] !== undefined) data[key] = parameters[key]; + setValue(value) { + if (is.str(value)) { + if (value == this._string) { + return false; } - return data; - } - - const vertices = []; - - for (let i = 0; i < this.vertices.length; i++) { - const vertex = this.vertices[i]; - vertices.push(vertex.x, vertex.y, vertex.z); + this._string = value; + this._value = 1; + } else if (super.setValue(value)) { + this._string = null; + } else { + return false; } - const faces = []; - const normals = []; - const normalsHash = {}; - const colors = []; - const colorsHash = {}; - const uvs = []; - const uvsHash = {}; - - for (let i = 0; i < this.faces.length; i++) { - const face = this.faces[i]; - const hasMaterial = true; - const hasFaceUv = false; // deprecated - - const hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined; - const hasFaceNormal = face.normal.length() > 0; - const hasFaceVertexNormal = face.vertexNormals.length > 0; - const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; - const hasFaceVertexColor = face.vertexColors.length > 0; - let faceType = 0; - faceType = setBit(faceType, 0, 0); // isQuad - - faceType = setBit(faceType, 1, hasMaterial); - faceType = setBit(faceType, 2, hasFaceUv); - faceType = setBit(faceType, 3, hasFaceVertexUv); - faceType = setBit(faceType, 4, hasFaceNormal); - faceType = setBit(faceType, 5, hasFaceVertexNormal); - faceType = setBit(faceType, 6, hasFaceColor); - faceType = setBit(faceType, 7, hasFaceVertexColor); - faces.push(faceType); - faces.push(face.a, face.b, face.c); - faces.push(face.materialIndex); - - if (hasFaceVertexUv) { - const faceVertexUvs = this.faceVertexUvs[0][i]; - faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2])); - } - - if (hasFaceNormal) { - faces.push(getNormalIndex(face.normal)); - } - - if (hasFaceVertexNormal) { - const vertexNormals = face.vertexNormals; - faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2])); - } - - if (hasFaceColor) { - faces.push(getColorIndex(face.color)); - } - - if (hasFaceVertexColor) { - const vertexColors = face.vertexColors; - faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2])); - } - } + return true; + } - function setBit(value, position, enabled) { - return enabled ? value | 1 << position : value & ~(1 << position); + reset(goal) { + if (goal) { + this._toString = createInterpolator({ + output: [this.getValue(), goal] + }); } - function getNormalIndex(normal) { - const hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); + this._value = 0; + super.reset(); + } - if (normalsHash[hash] !== undefined) { - return normalsHash[hash]; - } +} - normalsHash[hash] = normals.length / 3; - normals.push(normal.x, normal.y, normal.z); - return normalsHash[hash]; - } +const TreeContext = { + dependencies: null +}; - function getColorIndex(color) { - const hash = color.r.toString() + color.g.toString() + color.b.toString(); +class AnimatedObject extends Animated { + constructor(source) { + super(); + this.source = source; + this.setValue(source); + } - if (colorsHash[hash] !== undefined) { - return colorsHash[hash]; + getValue(animated) { + const values = {}; + eachProp(this.source, (source, key) => { + if (isAnimated(source)) { + values[key] = source.getValue(animated); + } else if (hasFluidValue(source)) { + values[key] = getFluidValue(source); + } else if (!animated) { + values[key] = source; } + }); + return values; + } - colorsHash[hash] = colors.length; - colors.push(color.getHex()); - return colorsHash[hash]; - } - - function getUvIndex(uv) { - const hash = uv.x.toString() + uv.y.toString(); - - if (uvsHash[hash] !== undefined) { - return uvsHash[hash]; - } + setValue(source) { + this.source = source; + this.payload = this._makePayload(source); + } - uvsHash[hash] = uvs.length / 2; - uvs.push(uv.x, uv.y); - return uvsHash[hash]; + reset() { + if (this.payload) { + each(this.payload, node => node.reset()); } - - data.data = {}; - data.data.vertices = vertices; - data.data.normals = normals; - if (colors.length > 0) data.data.colors = colors; - if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility - - data.data.faces = faces; - return data; } - clone() { - /* - // Handle primitives - const parameters = this.parameters; - if ( parameters !== undefined ) { - const values = []; - for ( const key in parameters ) { - values.push( parameters[ key ] ); - } - const geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + _makePayload(source) { + if (source) { + const payload = new Set(); + eachProp(source, this._addToPayload, payload); + return Array.from(payload); } - return new this.constructor().copy( this ); - */ - return new Geometry().copy(this); } - copy(source) { - // reset - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [[]]; - this.morphTargets = []; - this.morphNormals = []; - this.skinWeights = []; - this.skinIndices = []; - this.lineDistances = []; - this.boundingBox = null; - this.boundingSphere = null; // name + _addToPayload(source) { + if (TreeContext.dependencies && hasFluidValue(source)) { + TreeContext.dependencies.add(source); + } - this.name = source.name; // vertices + const payload = getPayload(source); - const vertices = source.vertices; + if (payload) { + each(payload, node => this.add(node)); + } + } - for (let i = 0, il = vertices.length; i < il; i++) { - this.vertices.push(vertices[i].clone()); - } // colors +} +class AnimatedArray extends AnimatedObject { + constructor(source) { + super(source); + } - const colors = source.colors; + static create(source) { + return new AnimatedArray(source); + } - for (let i = 0, il = colors.length; i < il; i++) { - this.colors.push(colors[i].clone()); - } // faces + getValue() { + return this.source.map(node => node.getValue()); + } + setValue(source) { + const payload = this.getPayload(); - const faces = source.faces; + if (source.length == payload.length) { + return payload.map((node, i) => node.setValue(source[i])).some(Boolean); + } - for (let i = 0, il = faces.length; i < il; i++) { - this.faces.push(faces[i].clone()); - } // face vertex uvs + super.setValue(source.map(makeAnimated)); + return true; + } +} - for (let i = 0, il = source.faceVertexUvs.length; i < il; i++) { - const faceVertexUvs = source.faceVertexUvs[i]; +function makeAnimated(value) { + const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue; + return nodeType.create(value); +} - if (this.faceVertexUvs[i] === undefined) { - this.faceVertexUvs[i] = []; - } +function getAnimatedType(value) { + const parentNode = getAnimated(value); + return parentNode ? parentNode.constructor : is.arr(value) ? AnimatedArray : isAnimatedString(value) ? AnimatedString : AnimatedValue; +} - for (let j = 0, jl = faceVertexUvs.length; j < jl; j++) { - const uvs = faceVertexUvs[j], - uvsCopy = []; +function _extends$1() { + _extends$1 = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - for (let k = 0, kl = uvs.length; k < kl; k++) { - const uv = uvs[k]; - uvsCopy.push(uv.clone()); + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; } - - this.faceVertexUvs[i].push(uvsCopy); } - } // morph targets - - - const morphTargets = source.morphTargets; - - for (let i = 0, il = morphTargets.length; i < il; i++) { - const morphTarget = {}; - morphTarget.name = morphTargets[i].name; // vertices + } - if (morphTargets[i].vertices !== undefined) { - morphTarget.vertices = []; + return target; + }; - for (let j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) { - morphTarget.vertices.push(morphTargets[i].vertices[j].clone()); - } - } // normals + return _extends$1.apply(this, arguments); +} +const withAnimated = (Component, host) => { + const hasInstance = !is.fun(Component) || Component.prototype && Component.prototype.isReactComponent; + return React.forwardRef((givenProps, givenRef) => { + const instanceRef = React.useRef(null); + const ref = hasInstance && React.useCallback(value => { + instanceRef.current = updateRef(givenRef, value); + }, [givenRef]); + const [props, deps] = getAnimatedState(givenProps, host); + const forceUpdate = useForceUpdate(); - if (morphTargets[i].normals !== undefined) { - morphTarget.normals = []; + const callback = () => { + const instance = instanceRef.current; - for (let j = 0, jl = morphTargets[i].normals.length; j < jl; j++) { - morphTarget.normals.push(morphTargets[i].normals[j].clone()); - } + if (hasInstance && !instance) { + return; } - this.morphTargets.push(morphTarget); - } // morph normals + const didUpdate = instance ? host.applyAnimatedValues(instance, props.getValue(true)) : false; + if (didUpdate === false) { + forceUpdate(); + } + }; - const morphNormals = source.morphNormals; + const observer = new PropsObserver(callback, deps); + const observerRef = React.useRef(); + useLayoutEffect(() => { + observerRef.current = observer; + each(deps, dep => addFluidObserver(dep, observer)); + return () => { + if (observerRef.current) { + each(observerRef.current.deps, dep => removeFluidObserver(dep, observerRef.current)); + raf.cancel(observerRef.current.update); + } + }; + }); + React.useEffect(callback, []); + useOnce(() => () => { + const observer = observerRef.current; + each(observer.deps, dep => removeFluidObserver(dep, observer)); + }); + const usedProps = host.getComponentProps(props.getValue()); + return React__namespace.createElement(Component, _extends$1({}, usedProps, { + ref: ref + })); + }); +}; - for (let i = 0, il = morphNormals.length; i < il; i++) { - const morphNormal = {}; // vertex normals +class PropsObserver { + constructor(update, deps) { + this.update = update; + this.deps = deps; + } - if (morphNormals[i].vertexNormals !== undefined) { - morphNormal.vertexNormals = []; + eventObserved(event) { + if (event.type == 'change') { + raf.write(this.update); + } + } - for (let j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) { - const srcVertexNormal = morphNormals[i].vertexNormals[j]; - const destVertexNormal = {}; - destVertexNormal.a = srcVertexNormal.a.clone(); - destVertexNormal.b = srcVertexNormal.b.clone(); - destVertexNormal.c = srcVertexNormal.c.clone(); - morphNormal.vertexNormals.push(destVertexNormal); - } - } // face normals +} +function getAnimatedState(props, host) { + const dependencies = new Set(); + TreeContext.dependencies = dependencies; + if (props.style) props = _extends$1({}, props, { + style: host.createAnimatedStyle(props.style) + }); + props = new AnimatedObject(props); + TreeContext.dependencies = null; + return [props, dependencies]; +} - if (morphNormals[i].faceNormals !== undefined) { - morphNormal.faceNormals = []; +function updateRef(ref, value) { + if (ref) { + if (is.fun(ref)) ref(value);else ref.current = value; + } - for (let j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) { - morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone()); - } - } + return value; +} - this.morphNormals.push(morphNormal); - } // skin weights +const cacheKey = Symbol.for('AnimatedComponent'); +const createHost = (components, { + applyAnimatedValues: _applyAnimatedValues = () => false, + createAnimatedStyle: _createAnimatedStyle = style => new AnimatedObject(style), + getComponentProps: _getComponentProps = props => props +} = {}) => { + const hostConfig = { + applyAnimatedValues: _applyAnimatedValues, + createAnimatedStyle: _createAnimatedStyle, + getComponentProps: _getComponentProps + }; + const animated = Component => { + const displayName = getDisplayName(Component) || 'Anonymous'; - const skinWeights = source.skinWeights; + if (is.str(Component)) { + Component = animated[Component] || (animated[Component] = withAnimated(Component, hostConfig)); + } else { + Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig)); + } - for (let i = 0, il = skinWeights.length; i < il; i++) { - this.skinWeights.push(skinWeights[i].clone()); - } // skin indices + Component.displayName = `Animated(${displayName})`; + return Component; + }; + eachProp(components, (Component, key) => { + if (is.arr(components)) { + key = getDisplayName(Component); + } - const skinIndices = source.skinIndices; + animated[key] = animated(Component); + }); + return { + animated + }; +}; - for (let i = 0, il = skinIndices.length; i < il; i++) { - this.skinIndices.push(skinIndices[i].clone()); - } // line distances +const getDisplayName = arg => is.str(arg) ? arg : arg && is.str(arg.displayName) ? arg.displayName : is.fun(arg) && arg.name || null; +function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - const lineDistances = source.lineDistances; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } - for (let i = 0, il = lineDistances.length; i < il; i++) { - this.lineDistances.push(lineDistances[i]); - } // bounding box + return target; + }; + return _extends.apply(this, arguments); +} - const boundingBox = source.boundingBox; +const config = { + default: { + tension: 170, + friction: 26 + }, + gentle: { + tension: 120, + friction: 14 + }, + wobbly: { + tension: 180, + friction: 12 + }, + stiff: { + tension: 210, + friction: 20 + }, + slow: { + tension: 280, + friction: 60 + }, + molasses: { + tension: 280, + friction: 120 + } +}; +const c1 = 1.70158; +const c2 = c1 * 1.525; +const c3 = c1 + 1; +const c4 = 2 * Math.PI / 3; +const c5 = 2 * Math.PI / 4.5; - if (boundingBox !== null) { - this.boundingBox = boundingBox.clone(); - } // bounding sphere +const bounceOut = x => { + const n1 = 7.5625; + const d1 = 2.75; + if (x < 1 / d1) { + return n1 * x * x; + } else if (x < 2 / d1) { + return n1 * (x -= 1.5 / d1) * x + 0.75; + } else if (x < 2.5 / d1) { + return n1 * (x -= 2.25 / d1) * x + 0.9375; + } else { + return n1 * (x -= 2.625 / d1) * x + 0.984375; + } +}; - const boundingSphere = source.boundingSphere; +const easings = { + linear: x => x, + easeInQuad: x => x * x, + easeOutQuad: x => 1 - (1 - x) * (1 - x), + easeInOutQuad: x => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2, + easeInCubic: x => x * x * x, + easeOutCubic: x => 1 - Math.pow(1 - x, 3), + easeInOutCubic: x => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2, + easeInQuart: x => x * x * x * x, + easeOutQuart: x => 1 - Math.pow(1 - x, 4), + easeInOutQuart: x => x < 0.5 ? 8 * x * x * x * x : 1 - Math.pow(-2 * x + 2, 4) / 2, + easeInQuint: x => x * x * x * x * x, + easeOutQuint: x => 1 - Math.pow(1 - x, 5), + easeInOutQuint: x => x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2, + easeInSine: x => 1 - Math.cos(x * Math.PI / 2), + easeOutSine: x => Math.sin(x * Math.PI / 2), + easeInOutSine: x => -(Math.cos(Math.PI * x) - 1) / 2, + easeInExpo: x => x === 0 ? 0 : Math.pow(2, 10 * x - 10), + easeOutExpo: x => x === 1 ? 1 : 1 - Math.pow(2, -10 * x), + easeInOutExpo: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2, + easeInCirc: x => 1 - Math.sqrt(1 - Math.pow(x, 2)), + easeOutCirc: x => Math.sqrt(1 - Math.pow(x - 1, 2)), + easeInOutCirc: x => x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2, + easeInBack: x => c3 * x * x * x - c1 * x * x, + easeOutBack: x => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2), + easeInOutBack: x => x < 0.5 ? Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2, + easeInElastic: x => x === 0 ? 0 : x === 1 ? 1 : -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4), + easeOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1, + easeInOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2 : Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5) / 2 + 1, + easeInBounce: x => 1 - bounceOut(1 - x), + easeOutBounce: bounceOut, + easeInOutBounce: x => x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2 +}; - if (boundingSphere !== null) { - this.boundingSphere = boundingSphere.clone(); - } // update flags +_extends({}, config.default, { + mass: 1, + damping: 1, + easing: easings.linear, + clamp: false +}); +const isFrameValue = value => value instanceof FrameValue; +let nextId$1 = 1; +class FrameValue extends FluidValue { + constructor(...args) { + super(...args); + this.id = nextId$1++; + this.key = void 0; + this._priority = 0; + } - this.elementsNeedUpdate = source.elementsNeedUpdate; - this.verticesNeedUpdate = source.verticesNeedUpdate; - this.uvsNeedUpdate = source.uvsNeedUpdate; - this.normalsNeedUpdate = source.normalsNeedUpdate; - this.colorsNeedUpdate = source.colorsNeedUpdate; - this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate; - this.groupsNeedUpdate = source.groupsNeedUpdate; - return this; + get priority() { + return this._priority; } - toBufferGeometry() { - const geometry = new DirectGeometry().fromGeometry(this); - const buffergeometry = new BufferGeometry(); - const positions = new Float32Array(geometry.vertices.length * 3); - buffergeometry.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices)); + set priority(priority) { + if (this._priority != priority) { + this._priority = priority; - if (geometry.normals.length > 0) { - const normals = new Float32Array(geometry.normals.length * 3); - buffergeometry.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals)); + this._onPriorityChange(priority); } + } - if (geometry.colors.length > 0) { - const colors = new Float32Array(geometry.colors.length * 3); - buffergeometry.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors)); - } + get() { + const node = getAnimated(this); + return node && node.getValue(); + } - if (geometry.uvs.length > 0) { - const uvs = new Float32Array(geometry.uvs.length * 2); - buffergeometry.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs)); - } + to(...args) { + return globals.to(this, args); + } - if (geometry.uvs2.length > 0) { - const uvs2 = new Float32Array(geometry.uvs2.length * 2); - buffergeometry.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2)); - } // groups + interpolate(...args) { + deprecateInterpolate(); + return globals.to(this, args); + } + toJSON() { + return this.get(); + } - buffergeometry.groups = geometry.groups; // morphs + observerAdded(count) { + if (count == 1) this._attach(); + } - for (let name in geometry.morphTargets) { - const array = []; - const morphTargets = geometry.morphTargets[name]; + observerRemoved(count) { + if (count == 0) this._detach(); + } - for (let i = 0, l = morphTargets.length; i < l; i++) { - const morphTarget = morphTargets[i]; - const attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3); - attribute.name = morphTarget.name; - array.push(attribute.copyVector3sArray(morphTarget.data)); - } + _attach() {} - buffergeometry.morphAttributes[name] = array; - } // skinning + _detach() {} + _onChange(value, idle = false) { + callFluidObservers(this, { + type: 'change', + parent: this, + value, + idle + }); + } - if (geometry.skinIndices.length > 0) { - const skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4); - buffergeometry.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices)); + _onPriorityChange(priority) { + if (!this.idle) { + frameLoop.sort(this); } - if (geometry.skinWeights.length > 0) { - const skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4); - buffergeometry.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights)); - } // - - - if (geometry.boundingSphere !== null) { - buffergeometry.boundingSphere = geometry.boundingSphere.clone(); - } + callFluidObservers(this, { + type: 'priority', + parent: this, + priority + }); + } - if (geometry.boundingBox !== null) { - buffergeometry.boundingBox = geometry.boundingBox.clone(); - } +} - return buffergeometry; - } +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - computeTangents() { - console.error('THREE.Geometry: .computeTangents() has been removed.'); + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; } - computeLineDistances() { - console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.'); - } + return target; +} - applyMatrix(matrix) { - console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().'); - return this.applyMatrix4(matrix); - } +const _excluded$3 = ["children"]; +const SpringContext = _ref => { + let { + children + } = _ref, + props = _objectWithoutPropertiesLoose(_ref, _excluded$3); - dispose() { - this.dispatchEvent({ - type: 'dispose' - }); - } + const inherited = React.useContext(ctx); + const pause = props.pause || !!inherited.pause, + immediate = props.immediate || !!inherited.immediate; + props = useMemoOne(() => ({ + pause, + immediate + }), [pause, immediate]); + const { + Provider + } = ctx; + return React__namespace.createElement(Provider, { + value: props + }, children); +}; +const ctx = makeContext(SpringContext, {}); +SpringContext.Provider = ctx.Provider; +SpringContext.Consumer = ctx.Consumer; +function makeContext(target, init) { + Object.assign(target, React__namespace.createContext(init)); + target.Provider._context = target; + target.Consumer._context = target; + return target; } -Geometry.createBufferGeometryFromObject = object => { - let buffergeometry = new BufferGeometry(); - const geometry = object.geometry; +let TransitionPhase; - if (object.isPoints || object.isLine) { - const positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3); - const colors = new Float32BufferAttribute(geometry.colors.length * 3, 3); - buffergeometry.setAttribute('position', positions.copyVector3sArray(geometry.vertices)); - buffergeometry.setAttribute('color', colors.copyColorsArray(geometry.colors)); +(function (TransitionPhase) { + TransitionPhase["MOUNT"] = "mount"; + TransitionPhase["ENTER"] = "enter"; + TransitionPhase["UPDATE"] = "update"; + TransitionPhase["LEAVE"] = "leave"; +})(TransitionPhase || (TransitionPhase = {})); - if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) { - const lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1); - buffergeometry.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances)); - } +class Interpolation extends FrameValue { + constructor(source, args) { + super(); + this.key = void 0; + this.idle = true; + this.calc = void 0; + this._active = new Set(); + this.source = source; + this.calc = createInterpolator(...args); - if (geometry.boundingSphere !== null) { - buffergeometry.boundingSphere = geometry.boundingSphere.clone(); - } + const value = this._get(); - if (geometry.boundingBox !== null) { - buffergeometry.boundingBox = geometry.boundingBox.clone(); - } - } else if (object.isMesh) { - buffergeometry = geometry.toBufferGeometry(); + const nodeType = getAnimatedType(value); + setAnimated(this, nodeType.create(value)); } - return buffergeometry; -}; + advance(_dt) { + const value = this._get(); -class DirectGeometry { - constructor() { - this.vertices = []; - this.normals = []; - this.colors = []; - this.uvs = []; - this.uvs2 = []; - this.groups = []; - this.morphTargets = {}; - this.skinWeights = []; - this.skinIndices = []; // this.lineDistances = []; - - this.boundingBox = null; - this.boundingSphere = null; // update flags - - this.verticesNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.groupsNeedUpdate = false; - } - - computeGroups(geometry) { - const groups = []; - let group, i; - let materialIndex = undefined; - const faces = geometry.faces; - - for (i = 0; i < faces.length; i++) { - const face = faces[i]; // materials - - if (face.materialIndex !== materialIndex) { - materialIndex = face.materialIndex; - - if (group !== undefined) { - group.count = i * 3 - group.start; - groups.push(group); - } + const oldValue = this.get(); - group = { - start: i * 3, - materialIndex - }; - } - } + if (!isEqual(value, oldValue)) { + getAnimated(this).setValue(value); - if (group !== undefined) { - group.count = i * 3 - group.start; - groups.push(group); + this._onChange(value, this.idle); } - this.groups = groups; + if (!this.idle && checkIdle(this._active)) { + becomeIdle(this); + } } - fromGeometry(geometry) { - const faces = geometry.faces; - const vertices = geometry.vertices; - const faceVertexUvs = geometry.faceVertexUvs; - const hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0; - const hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs - - const morphTargets = geometry.morphTargets; - const morphTargetsLength = morphTargets.length; - let morphTargetsPosition; + _get() { + const inputs = is.arr(this.source) ? this.source.map(getFluidValue) : toArray(getFluidValue(this.source)); + return this.calc(...inputs); + } - if (morphTargetsLength > 0) { - morphTargetsPosition = []; + _start() { + if (this.idle && !checkIdle(this._active)) { + this.idle = false; + each(getPayload(this), node => { + node.done = false; + }); - for (let i = 0; i < morphTargetsLength; i++) { - morphTargetsPosition[i] = { - name: morphTargets[i].name, - data: [] - }; + if (globals.skipAnimation) { + raf.batchedUpdates(() => this.advance()); + becomeIdle(this); + } else { + frameLoop.start(this); } - - this.morphTargets.position = morphTargetsPosition; } + } - const morphNormals = geometry.morphNormals; - const morphNormalsLength = morphNormals.length; - let morphTargetsNormal; + _attach() { + let priority = 1; + each(toArray(this.source), source => { + if (hasFluidValue(source)) { + addFluidObserver(source, this); + } - if (morphNormalsLength > 0) { - morphTargetsNormal = []; + if (isFrameValue(source)) { + if (!source.idle) { + this._active.add(source); + } - for (let i = 0; i < morphNormalsLength; i++) { - morphTargetsNormal[i] = { - name: morphNormals[i].name, - data: [] - }; + priority = Math.max(priority, source.priority + 1); } + }); + this.priority = priority; - this.morphTargets.normal = morphTargetsNormal; - } // skins - + this._start(); + } - const skinIndices = geometry.skinIndices; - const skinWeights = geometry.skinWeights; - const hasSkinIndices = skinIndices.length === vertices.length; - const hasSkinWeights = skinWeights.length === vertices.length; // + _detach() { + each(toArray(this.source), source => { + if (hasFluidValue(source)) { + removeFluidObserver(source, this); + } + }); - if (vertices.length > 0 && faces.length === 0) { - console.error('THREE.DirectGeometry: Faceless geometries are not supported.'); - } + this._active.clear(); - for (let i = 0; i < faces.length; i++) { - const face = faces[i]; - this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]); - const vertexNormals = face.vertexNormals; + becomeIdle(this); + } - if (vertexNormals.length === 3) { - this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]); + eventObserved(event) { + if (event.type == 'change') { + if (event.idle) { + this.advance(); } else { - const normal = face.normal; - this.normals.push(normal, normal, normal); + this._active.add(event.parent); + + this._start(); } + } else if (event.type == 'idle') { + this._active.delete(event.parent); + } else if (event.type == 'priority') { + this.priority = toArray(this.source).reduce((highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1), 0); + } + } - const vertexColors = face.vertexColors; +} - if (vertexColors.length === 3) { - this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]); - } else { - const color = face.color; - this.colors.push(color, color, color); - } +function isIdle(source) { + return source.idle !== false; +} - if (hasFaceVertexUv === true) { - const vertexUvs = faceVertexUvs[0][i]; +function checkIdle(active) { + return !active.size || Array.from(active).every(isIdle); +} - if (vertexUvs !== undefined) { - this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]); - } else { - console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i); - this.uvs.push(new Vector2(), new Vector2(), new Vector2()); - } - } +function becomeIdle(self) { + if (!self.idle) { + self.idle = true; + each(getPayload(self), node => { + node.done = true; + }); + callFluidObservers(self, { + type: 'idle', + parent: self + }); + } +} - if (hasFaceVertexUv2 === true) { - const vertexUvs = faceVertexUvs[1][i]; +globals.assign({ + createStringInterpolator, + to: (source, args) => new Interpolation(source, args) +}); - if (vertexUvs !== undefined) { - this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]); - } else { - console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i); - this.uvs2.push(new Vector2(), new Vector2(), new Vector2()); - } - } // morphs +const primitives = ['primitive'].concat(Object.keys(THREE).filter(key => /^[A-Z]/.test(key)).map(key => key[0].toLowerCase() + key.slice(1))); + +globals.assign({ + createStringInterpolator, + colors, + frameLoop: 'demand' +}); +addEffect(() => { + raf.advance(); +}); +createHost(primitives, { + applyAnimatedValues: applyProps +}); +const V = { + toVector(v, fallback) { + if (v === undefined) v = fallback; + return Array.isArray(v) ? v : [v, v]; + }, - for (let j = 0; j < morphTargetsLength; j++) { - const morphTarget = morphTargets[j].vertices; - morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]); - } + add(v1, v2) { + return [v1[0] + v2[0], v1[1] + v2[1]]; + }, - for (let j = 0; j < morphNormalsLength; j++) { - const morphNormal = morphNormals[j].vertexNormals[i]; - morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c); - } // skins + sub(v1, v2) { + return [v1[0] - v2[0], v1[1] - v2[1]]; + }, + addTo(v1, v2) { + v1[0] += v2[0]; + v1[1] += v2[1]; + }, - if (hasSkinIndices) { - this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]); - } + subTo(v1, v2) { + v1[0] -= v2[0]; + v1[1] -= v2[1]; + } - if (hasSkinWeights) { - this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]); - } - } +}; - this.computeGroups(geometry); - this.verticesNeedUpdate = geometry.verticesNeedUpdate; - this.normalsNeedUpdate = geometry.normalsNeedUpdate; - this.colorsNeedUpdate = geometry.colorsNeedUpdate; - this.uvsNeedUpdate = geometry.uvsNeedUpdate; - this.groupsNeedUpdate = geometry.groupsNeedUpdate; +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } - if (geometry.boundingSphere !== null) { - this.boundingSphere = geometry.boundingSphere.clone(); - } + return obj; +} - if (geometry.boundingBox !== null) { - this.boundingBox = geometry.boundingBox.clone(); - } +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - return this; + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); } + return keys; } -class Face3 { - constructor(a, b, c, normal, color, materialIndex = 0) { - this.a = a; - this.b = b; - this.c = c; - this.normal = normal && normal.isVector3 ? normal : new Vector3(); - this.vertexNormals = Array.isArray(normal) ? normal : []; - this.color = color && color.isColor ? color : new Color(); - this.vertexColors = Array.isArray(color) ? color : []; - this.materialIndex = materialIndex; +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - clone() { - return new this.constructor().copy(this); + return target; +} + +function call(v, ...args) { + if (typeof v === 'function') { + return v(...args); + } else { + return v; } +} +function assignDefault(value, fallback) { + return Object.assign({}, fallback, value || {}); +} - copy(source) { - this.a = source.a; - this.b = source.b; - this.c = source.c; - this.normal.copy(source.normal); - this.color.copy(source.color); - this.materialIndex = source.materialIndex; +const identity = v => v; +const DEFAULT_RUBBERBAND = 0.15; +const commonConfigResolver = { + enabled(value = true) { + return value; + }, - for (let i = 0, il = source.vertexNormals.length; i < il; i++) { - this.vertexNormals[i] = source.vertexNormals[i].clone(); - } + eventOptions(value, _k, config) { + return _objectSpread2(_objectSpread2({}, config.shared.eventOptions), value); + }, - for (let i = 0, il = source.vertexColors.length; i < il; i++) { - this.vertexColors[i] = source.vertexColors[i].clone(); - } + preventDefault(value = false) { + return value; + }, - return this; - } + triggerAllEvents(value = false) { + return value; + }, -} + rubberband(value = 0) { + switch (value) { + case true: + return [DEFAULT_RUBBERBAND, DEFAULT_RUBBERBAND]; -class NodeMaterial extends ShaderMaterial { - constructor() { - super(); - this.type = this.constructor.name; - this.lights = true; - } + case false: + return [0, 0]; - setDefaultValues(values) { - // This approach is to reuse the native refreshUniforms* - // and turn available the use of features like transmission and environment in core - let value; + default: + return V.toVector(value); + } + }, - for (const property in values) { - value = values[property]; + from(value) { + if (typeof value === 'function') return value; + if (value != null) return V.toVector(value); + }, - if (this[property] === undefined) { - if (value && typeof value.clone === 'function') { - this[property] = value.clone(); - } else { - this[property] = value; - } - } - } + transform(value, _k, config) { + const transform = value || config.shared.transform; + this.hasCustomTransform = !!transform; - Object.assign(this.defines, values.defines); - } + if (process.env.NODE_ENV === 'development') { + const originalTransform = transform || identity; + return v => { + const r = originalTransform(v); - toJSON(meta) { - const isRoot = meta === undefined || typeof meta === 'string'; + if (!isFinite(r[0]) || !isFinite(r[1])) { + console.warn(`[@use-gesture]: config.transform() must produce a valid result, but it was: [${r[0]},${[1]}]`); + } - if (isRoot) { - meta = { - textures: {}, - images: {}, - nodes: {} + return r; }; } - const data = Material.prototype.toJSON.call(this, meta); - const nodeKeys = getNodesKeys(this); - data.inputNodes = {}; + return transform || identity; + }, + + threshold(value) { + return V.toVector(value, 0); + } - for (const name of nodeKeys) { - data.inputNodes[name] = this[name].toJSON(meta).uuid; - } // TODO: Copied from Object3D.toJSON +}; +if (process.env.NODE_ENV === 'development') { + Object.assign(commonConfigResolver, { + domTarget(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`); + } - function extractFromCache(cache) { - const values = []; + return NaN; + }, - for (const key in cache) { - const data = cache[key]; - delete data.metadata; - values.push(data); + lockDirection(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`lockDirection\` option has been merged with \`axis\`. Use it as in \`{ axis: 'lock' }\``); } - return values; - } + return NaN; + }, - if (isRoot) { - const textures = extractFromCache(meta.textures); - const images = extractFromCache(meta.images); - const nodes = extractFromCache(meta.nodes); - if (textures.length > 0) data.textures = textures; - if (images.length > 0) data.images = images; - if (nodes.length > 0) data.nodes = nodes; - } + initial(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`initial\` option has been renamed to \`from\`.`); + } - return data; - } + return NaN; + } + }); } -NodeMaterial.prototype.isNodeMaterial = true; +const DEFAULT_AXIS_THRESHOLD = 0; +const coordinatesConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { + axis(_v, _k, { + axis + }) { + this.lockDirection = axis === 'lock'; + if (!this.lockDirection) return axis; + }, -const defaultValues$3 = new LineBasicMaterial(); + axisThreshold(value = DEFAULT_AXIS_THRESHOLD) { + return value; + }, -class LineBasicNodeMaterial extends NodeMaterial { - constructor(parameters) { - super(); - this.colorNode = null; - this.opacityNode = null; - this.alphaTestNode = null; - this.lightNode = null; - this.positionNode = null; - this.setDefaultValues(defaultValues$3); - this.setValues(parameters); - } + bounds(value = {}) { + if (typeof value === 'function') { + return state => coordinatesConfigResolver.bounds(value(state)); + } - copy(source) { - this.colorNode = source.colorNode; - this.opacityNode = source.opacityNode; - this.alphaTestNode = source.alphaTestNode; - this.lightNode = source.lightNode; - this.positionNode = source.positionNode; - return super.copy(source); - } + if ('current' in value) { + return () => value.current; + } -} + if (typeof HTMLElement === 'function' && value instanceof HTMLElement) { + return value; + } -LineBasicNodeMaterial.prototype.isLineBasicNodeMaterial = true; + const { + left = -Infinity, + right = Infinity, + top = -Infinity, + bottom = Infinity + } = value; + return [[left, right], [top, bottom]]; + } -const defaultValues$2 = new MeshBasicMaterial(); +}); -class MeshBasicNodeMaterial extends NodeMaterial { - constructor(parameters) { - super(); - this.lights = true; - this.colorNode = null; - this.opacityNode = null; - this.alphaTestNode = null; - this.lightNode = null; - this.positionNode = null; - this.setDefaultValues(defaultValues$2); - this.setValues(parameters); - } +const isBrowser = typeof window !== 'undefined' && window.document && window.document.createElement; - copy(source) { - this.colorNode = source.colorNode; - this.opacityNode = source.opacityNode; - this.alphaTestNode = source.alphaTestNode; - this.lightNode = source.lightNode; - this.positionNode = source.positionNode; - return super.copy(source); - } +function supportsTouchEvents() { + return isBrowser && 'ontouchstart' in window; +} +function isTouchScreen() { + return supportsTouchEvents() || isBrowser && window.navigator.maxTouchPoints > 1; } -MeshBasicNodeMaterial.prototype.isMeshBasicNodeMaterial = true; +function supportsPointerEvents() { + return isBrowser && 'onpointerdown' in window; +} -const defaultValues$1 = new MeshStandardMaterial(); -class MeshStandardNodeMaterial extends NodeMaterial { - constructor(parameters) { - super(); - this.colorNode = null; - this.opacityNode = null; - this.alphaTestNode = null; - this.normalNode = null; - this.emissiveNode = null; - this.metalnessNode = null; - this.roughnessNode = null; - this.clearcoatNode = null; - this.clearcoatRoughnessNode = null; - this.envNode = null; - this.lightNode = null; - this.positionNode = null; - this.setDefaultValues(defaultValues$1); - this.setValues(parameters); - } +function supportsPointerLock() { + return isBrowser && 'exitPointerLock' in window.document; +} - copy(source) { - this.colorNode = source.colorNode; - this.opacityNode = source.opacityNode; - this.alphaTestNode = source.alphaTestNode; - this.normalNode = source.normalNode; - this.emissiveNode = source.emissiveNode; - this.metalnessNode = source.metalnessNode; - this.roughnessNode = source.roughnessNode; - this.clearcoatNode = source.clearcoatNode; - this.clearcoatRoughnessNode = source.clearcoatRoughnessNode; - this.envNode = source.envNode; - this.lightNode = source.lightNode; - this.positionNode = source.positionNode; - return super.copy(source); +function supportsGestureEvents() { + try { + return 'constructor' in GestureEvent; + } catch (e) { + return false; } - } -MeshStandardNodeMaterial.prototype.isMeshStandardNodeMaterial = true; - -const defaultValues = new PointsMaterial(); -class PointsNodeMaterial extends NodeMaterial { - constructor(parameters) { - super(); - this.transparent = true; - this.colorNode = null; - this.opacityNode = null; - this.alphaTestNode = null; - this.lightNode = null; - this.sizeNode = null; - this.positionNode = null; - this.setDefaultValues(defaultValues); - this.setValues(parameters); - } +const SUPPORT = { + isBrowser, + gesture: supportsGestureEvents(), + touch: isTouchScreen(), + touchscreen: isTouchScreen(), + pointer: supportsPointerEvents(), + pointerLock: supportsPointerLock() +}; - copy(source) { - this.colorNode = source.colorNode; - this.opacityNode = source.opacityNode; - this.alphaTestNode = source.alphaTestNode; - this.lightNode = source.lightNode; - this.sizeNode = source.sizeNode; - this.positionNode = source.positionNode; - return super.copy(source); - } +const DEFAULT_PREVENT_SCROLL_DELAY = 250; +const DEFAULT_DRAG_DELAY = 180; +const DEFAULT_SWIPE_VELOCITY = 0.5; +const DEFAULT_SWIPE_DISTANCE = 50; +const DEFAULT_SWIPE_DURATION = 250; +const DEFAULT_DRAG_AXIS_THRESHOLD = { + mouse: 0, + touch: 0, + pen: 8 +}; +const dragConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { + device(_v, _k, { + pointer: { + touch = false, + lock = false, + mouse = false + } = {} + }) { + this.pointerLock = lock && SUPPORT.pointerLock; + if (SUPPORT.touch && touch) return 'touch'; + if (this.pointerLock) return 'mouse'; + if (SUPPORT.pointer && !mouse) return 'pointer'; + if (SUPPORT.touch) return 'touch'; + return 'mouse'; + }, -} + preventScrollAxis(value, _k, { + preventScroll + }) { + this.preventScrollDelay = typeof preventScroll === 'number' ? preventScroll : preventScroll || preventScroll === undefined && value ? DEFAULT_PREVENT_SCROLL_DELAY : undefined; + if (!SUPPORT.touchscreen || preventScroll === false) return undefined; + return value ? value : preventScroll !== undefined ? 'y' : undefined; + }, -PointsNodeMaterial.prototype.isPointsNodeMaterial = true; + pointerCapture(_v, _k, { + pointer: { + capture = true, + buttons = 1 + } = {} + }) { + this.pointerButtons = buttons; + return !this.pointerLock && this.device === 'pointer' && capture; + }, -/** - * Color correction - */ + threshold(value, _k, { + filterTaps = false, + tapsThreshold = 3, + axis = undefined + }) { + const threshold = V.toVector(value, filterTaps ? tapsThreshold : axis ? 1 : 0); + this.filterTaps = filterTaps; + this.tapsThreshold = tapsThreshold; + return threshold; + }, -({ - uniforms: { - tDiffuse: { - value: null - }, - powRGB: { - value: new Vector3(2, 2, 2) - }, - mulRGB: { - value: new Vector3(1, 1, 1) - }, - addRGB: { - value: new Vector3(0, 0, 0) - } + swipe({ + velocity = DEFAULT_SWIPE_VELOCITY, + distance = DEFAULT_SWIPE_DISTANCE, + duration = DEFAULT_SWIPE_DURATION + } = {}) { + return { + velocity: this.transform(V.toVector(velocity)), + distance: this.transform(V.toVector(distance)), + duration + }; }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform vec3 powRGB;', 'uniform vec3 mulRGB;', 'uniform vec3 addRGB;', 'varying vec2 vUv;', 'void main() {', ' gl_FragColor = texture2D( tDiffuse, vUv );', ' gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB );', '}'].join('\n') -}); -/** - * Colorify shader - */ + delay(value = 0) { + switch (value) { + case true: + return DEFAULT_DRAG_DELAY; -({ - uniforms: { - tDiffuse: { - value: null - }, - color: { - value: new Color(0xffffff) + case false: + return 0; + + default: + return value; } }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform vec3 color;', 'uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'void main() {', ' vec4 texel = texture2D( tDiffuse, vUv );', ' vec3 luma = vec3( 0.299, 0.587, 0.114 );', ' float v = dot( texel.xyz, luma );', ' gl_FragColor = vec4( v * color, texel.w );', '}'].join('\n') -}); -/** - * NVIDIA FXAA by Timothy Lottes - * http://timothylottes.blogspot.com/2011/06/fxaa3-source-released.html - * - WebGL port by @supereggbert - * http://www.glge.org/demos/fxaa/ - */ + axisThreshold(value) { + if (!value) return DEFAULT_DRAG_AXIS_THRESHOLD; + return _objectSpread2(_objectSpread2({}, DEFAULT_DRAG_AXIS_THRESHOLD), value); + } -({ - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2(1 / 1024, 1 / 512) - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['precision highp float;', '', 'uniform sampler2D tDiffuse;', '', 'uniform vec2 resolution;', '', 'varying vec2 vUv;', '', '// FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)', '', '//----------------------------------------------------------------------------------', '// File: es3-keplerFXAAassetsshaders/FXAA_DefaultES.frag', '// SDK Version: v3.00', '// Email: gameworks@nvidia.com', '// Site: http://developer.nvidia.com/', '//', '// Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.', '//', '// Redistribution and use in source and binary forms, with or without', '// modification, are permitted provided that the following conditions', '// are met:', '// * Redistributions of source code must retain the above copyright', '// notice, this list of conditions and the following disclaimer.', '// * Redistributions in binary form must reproduce the above copyright', '// notice, this list of conditions and the following disclaimer in the', '// documentation and/or other materials provided with the distribution.', '// * Neither the name of NVIDIA CORPORATION nor the names of its', '// contributors may be used to endorse or promote products derived', '// from this software without specific prior written permission.', '//', "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY", '// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE', '// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR', '// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR', '// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,', '// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,', '// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR', '// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY', '// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT', '// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE', '// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.', '//', '//----------------------------------------------------------------------------------', '', '#define FXAA_PC 1', '#define FXAA_GLSL_100 1', '#define FXAA_QUALITY_PRESET 12', '', '#define FXAA_GREEN_AS_LUMA 1', '', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_PC_CONSOLE', ' //', ' // The console algorithm for PC is included', ' // for developers targeting really low spec machines.', ' // Likely better to just run FXAA_PC, and use a really low preset.', ' //', ' #define FXAA_PC_CONSOLE 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_GLSL_120', ' #define FXAA_GLSL_120 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_GLSL_130', ' #define FXAA_GLSL_130 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_HLSL_3', ' #define FXAA_HLSL_3 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_HLSL_4', ' #define FXAA_HLSL_4 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_HLSL_5', ' #define FXAA_HLSL_5 0', '#endif', '/*==========================================================================*/', '#ifndef FXAA_GREEN_AS_LUMA', ' //', ' // For those using non-linear color,', ' // and either not able to get luma in alpha, or not wanting to,', ' // this enables FXAA to run using green as a proxy for luma.', ' // So with this enabled, no need to pack luma in alpha.', ' //', ' // This will turn off AA on anything which lacks some amount of green.', ' // Pure red and blue or combination of only R and B, will get no AA.', ' //', ' // Might want to lower the settings for both,', ' // fxaaConsoleEdgeThresholdMin', ' // fxaaQualityEdgeThresholdMin', ' // In order to insure AA does not get turned off on colors', ' // which contain a minor amount of green.', ' //', ' // 1 = On.', ' // 0 = Off.', ' //', ' #define FXAA_GREEN_AS_LUMA 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_EARLY_EXIT', ' //', " // Controls algorithm's early exit path.", ' // On PS3 turning this ON adds 2 cycles to the shader.', ' // On 360 turning this OFF adds 10ths of a millisecond to the shader.', ' // Turning this off on console will result in a more blurry image.', ' // So this defaults to on.', ' //', ' // 1 = On.', ' // 0 = Off.', ' //', ' #define FXAA_EARLY_EXIT 1', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_DISCARD', ' //', ' // Only valid for PC OpenGL currently.', ' // Probably will not work when FXAA_GREEN_AS_LUMA = 1.', ' //', " // 1 = Use discard on pixels which don't need AA.", ' // For APIs which enable concurrent TEX+ROP from same surface.', " // 0 = Return unchanged color on pixels which don't need AA.", ' //', ' #define FXAA_DISCARD 0', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_FAST_PIXEL_OFFSET', ' //', ' // Used for GLSL 120 only.', ' //', ' // 1 = GL API supports fast pixel offsets', ' // 0 = do not use fast pixel offsets', ' //', ' #ifdef GL_EXT_gpu_shader4', ' #define FXAA_FAST_PIXEL_OFFSET 1', ' #endif', ' #ifdef GL_NV_gpu_shader5', ' #define FXAA_FAST_PIXEL_OFFSET 1', ' #endif', ' #ifdef GL_ARB_gpu_shader5', ' #define FXAA_FAST_PIXEL_OFFSET 1', ' #endif', ' #ifndef FXAA_FAST_PIXEL_OFFSET', ' #define FXAA_FAST_PIXEL_OFFSET 0', ' #endif', '#endif', '/*--------------------------------------------------------------------------*/', '#ifndef FXAA_GATHER4_ALPHA', ' //', ' // 1 = API supports gather4 on alpha channel.', ' // 0 = API does not support gather4 on alpha channel.', ' //', ' #if (FXAA_HLSL_5 == 1)', ' #define FXAA_GATHER4_ALPHA 1', ' #endif', ' #ifdef GL_ARB_gpu_shader5', ' #define FXAA_GATHER4_ALPHA 1', ' #endif', ' #ifdef GL_NV_gpu_shader5', ' #define FXAA_GATHER4_ALPHA 1', ' #endif', ' #ifndef FXAA_GATHER4_ALPHA', ' #define FXAA_GATHER4_ALPHA 0', ' #endif', '#endif', '', '', '/*============================================================================', ' FXAA QUALITY - TUNING KNOBS', '------------------------------------------------------------------------------', 'NOTE the other tuning knobs are now in the shader function inputs!', '============================================================================*/', '#ifndef FXAA_QUALITY_PRESET', ' //', ' // Choose the quality preset.', ' // This needs to be compiled into the shader as it effects code.', ' // Best option to include multiple presets is to', ' // in each shader define the preset, then include this file.', ' //', ' // OPTIONS', ' // -----------------------------------------------------------------------', ' // 10 to 15 - default medium dither (10=fastest, 15=highest quality)', ' // 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality)', ' // 39 - no dither, very expensive', ' //', ' // NOTES', ' // -----------------------------------------------------------------------', ' // 12 = slightly faster then FXAA 3.9 and higher edge quality (default)', ' // 13 = about same speed as FXAA 3.9 and better than 12', ' // 23 = closest to FXAA 3.9 visually and performance wise', ' // _ = the lowest digit is directly related to performance', ' // _ = the highest digit is directly related to style', ' //', ' #define FXAA_QUALITY_PRESET 12', '#endif', '', '', '/*============================================================================', '', ' FXAA QUALITY - PRESETS', '', '============================================================================*/', '', '/*============================================================================', ' FXAA QUALITY - MEDIUM DITHER PRESETS', '============================================================================*/', '#if (FXAA_QUALITY_PRESET == 10)', ' #define FXAA_QUALITY_PS 3', ' #define FXAA_QUALITY_P0 1.5', ' #define FXAA_QUALITY_P1 3.0', ' #define FXAA_QUALITY_P2 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 11)', ' #define FXAA_QUALITY_PS 4', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 3.0', ' #define FXAA_QUALITY_P3 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 12)', ' #define FXAA_QUALITY_PS 5', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 4.0', ' #define FXAA_QUALITY_P4 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 13)', ' #define FXAA_QUALITY_PS 6', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 4.0', ' #define FXAA_QUALITY_P5 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 14)', ' #define FXAA_QUALITY_PS 7', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 4.0', ' #define FXAA_QUALITY_P6 12.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 15)', ' #define FXAA_QUALITY_PS 8', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 4.0', ' #define FXAA_QUALITY_P7 12.0', '#endif', '', '/*============================================================================', ' FXAA QUALITY - LOW DITHER PRESETS', '============================================================================*/', '#if (FXAA_QUALITY_PRESET == 20)', ' #define FXAA_QUALITY_PS 3', ' #define FXAA_QUALITY_P0 1.5', ' #define FXAA_QUALITY_P1 2.0', ' #define FXAA_QUALITY_P2 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 21)', ' #define FXAA_QUALITY_PS 4', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 22)', ' #define FXAA_QUALITY_PS 5', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 23)', ' #define FXAA_QUALITY_PS 6', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 24)', ' #define FXAA_QUALITY_PS 7', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 3.0', ' #define FXAA_QUALITY_P6 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 25)', ' #define FXAA_QUALITY_PS 8', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 4.0', ' #define FXAA_QUALITY_P7 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 26)', ' #define FXAA_QUALITY_PS 9', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 4.0', ' #define FXAA_QUALITY_P8 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 27)', ' #define FXAA_QUALITY_PS 10', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 2.0', ' #define FXAA_QUALITY_P8 4.0', ' #define FXAA_QUALITY_P9 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 28)', ' #define FXAA_QUALITY_PS 11', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 2.0', ' #define FXAA_QUALITY_P8 2.0', ' #define FXAA_QUALITY_P9 4.0', ' #define FXAA_QUALITY_P10 8.0', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_QUALITY_PRESET == 29)', ' #define FXAA_QUALITY_PS 12', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.5', ' #define FXAA_QUALITY_P2 2.0', ' #define FXAA_QUALITY_P3 2.0', ' #define FXAA_QUALITY_P4 2.0', ' #define FXAA_QUALITY_P5 2.0', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 2.0', ' #define FXAA_QUALITY_P8 2.0', ' #define FXAA_QUALITY_P9 2.0', ' #define FXAA_QUALITY_P10 4.0', ' #define FXAA_QUALITY_P11 8.0', '#endif', '', '/*============================================================================', ' FXAA QUALITY - EXTREME QUALITY', '============================================================================*/', '#if (FXAA_QUALITY_PRESET == 39)', ' #define FXAA_QUALITY_PS 12', ' #define FXAA_QUALITY_P0 1.0', ' #define FXAA_QUALITY_P1 1.0', ' #define FXAA_QUALITY_P2 1.0', ' #define FXAA_QUALITY_P3 1.0', ' #define FXAA_QUALITY_P4 1.0', ' #define FXAA_QUALITY_P5 1.5', ' #define FXAA_QUALITY_P6 2.0', ' #define FXAA_QUALITY_P7 2.0', ' #define FXAA_QUALITY_P8 2.0', ' #define FXAA_QUALITY_P9 2.0', ' #define FXAA_QUALITY_P10 4.0', ' #define FXAA_QUALITY_P11 8.0', '#endif', '', '', '', '/*============================================================================', '', ' API PORTING', '', '============================================================================*/', '#if (FXAA_GLSL_100 == 1) || (FXAA_GLSL_120 == 1) || (FXAA_GLSL_130 == 1)', ' #define FxaaBool bool', ' #define FxaaDiscard discard', ' #define FxaaFloat float', ' #define FxaaFloat2 vec2', ' #define FxaaFloat3 vec3', ' #define FxaaFloat4 vec4', ' #define FxaaHalf float', ' #define FxaaHalf2 vec2', ' #define FxaaHalf3 vec3', ' #define FxaaHalf4 vec4', ' #define FxaaInt2 ivec2', ' #define FxaaSat(x) clamp(x, 0.0, 1.0)', ' #define FxaaTex sampler2D', '#else', ' #define FxaaBool bool', ' #define FxaaDiscard clip(-1)', ' #define FxaaFloat float', ' #define FxaaFloat2 float2', ' #define FxaaFloat3 float3', ' #define FxaaFloat4 float4', ' #define FxaaHalf half', ' #define FxaaHalf2 half2', ' #define FxaaHalf3 half3', ' #define FxaaHalf4 half4', ' #define FxaaSat(x) saturate(x)', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_GLSL_100 == 1)', ' #define FxaaTexTop(t, p) texture2D(t, p, 0.0)', ' #define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r), 0.0)', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_GLSL_120 == 1)', ' // Requires,', ' // #version 120', ' // And at least,', ' // #extension GL_EXT_gpu_shader4 : enable', ' // (or set FXAA_FAST_PIXEL_OFFSET 1 to work like DX9)', ' #define FxaaTexTop(t, p) texture2DLod(t, p, 0.0)', ' #if (FXAA_FAST_PIXEL_OFFSET == 1)', ' #define FxaaTexOff(t, p, o, r) texture2DLodOffset(t, p, 0.0, o)', ' #else', ' #define FxaaTexOff(t, p, o, r) texture2DLod(t, p + (o * r), 0.0)', ' #endif', ' #if (FXAA_GATHER4_ALPHA == 1)', ' // use #extension GL_ARB_gpu_shader5 : enable', ' #define FxaaTexAlpha4(t, p) textureGather(t, p, 3)', ' #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)', ' #define FxaaTexGreen4(t, p) textureGather(t, p, 1)', ' #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)', ' #endif', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_GLSL_130 == 1)', ' // Requires "#version 130" or better', ' #define FxaaTexTop(t, p) textureLod(t, p, 0.0)', ' #define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o)', ' #if (FXAA_GATHER4_ALPHA == 1)', ' // use #extension GL_ARB_gpu_shader5 : enable', ' #define FxaaTexAlpha4(t, p) textureGather(t, p, 3)', ' #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)', ' #define FxaaTexGreen4(t, p) textureGather(t, p, 1)', ' #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)', ' #endif', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_HLSL_3 == 1)', ' #define FxaaInt2 float2', ' #define FxaaTex sampler2D', ' #define FxaaTexTop(t, p) tex2Dlod(t, float4(p, 0.0, 0.0))', ' #define FxaaTexOff(t, p, o, r) tex2Dlod(t, float4(p + (o * r), 0, 0))', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_HLSL_4 == 1)', ' #define FxaaInt2 int2', ' struct FxaaTex { SamplerState smpl; Texture2D tex; };', ' #define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0)', ' #define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o)', '#endif', '/*--------------------------------------------------------------------------*/', '#if (FXAA_HLSL_5 == 1)', ' #define FxaaInt2 int2', ' struct FxaaTex { SamplerState smpl; Texture2D tex; };', ' #define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0)', ' #define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o)', ' #define FxaaTexAlpha4(t, p) t.tex.GatherAlpha(t.smpl, p)', ' #define FxaaTexOffAlpha4(t, p, o) t.tex.GatherAlpha(t.smpl, p, o)', ' #define FxaaTexGreen4(t, p) t.tex.GatherGreen(t.smpl, p)', ' #define FxaaTexOffGreen4(t, p, o) t.tex.GatherGreen(t.smpl, p, o)', '#endif', '', '', '/*============================================================================', ' GREEN AS LUMA OPTION SUPPORT FUNCTION', '============================================================================*/', '#if (FXAA_GREEN_AS_LUMA == 0)', ' FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.w; }', '#else', ' FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; }', '#endif', '', '', '', '', '/*============================================================================', '', ' FXAA3 QUALITY - PC', '', '============================================================================*/', '#if (FXAA_PC == 1)', '/*--------------------------------------------------------------------------*/', 'FxaaFloat4 FxaaPixelShader(', ' //', ' // Use noperspective interpolation here (turn off perspective interpolation).', ' // {xy} = center of pixel', ' FxaaFloat2 pos,', ' //', ' // Used only for FXAA Console, and not used on the 360 version.', ' // Use noperspective interpolation here (turn off perspective interpolation).', ' // {xy_} = upper left of pixel', ' // {_zw} = lower right of pixel', ' FxaaFloat4 fxaaConsolePosPos,', ' //', ' // Input color texture.', ' // {rgb_} = color in linear or perceptual color space', ' // if (FXAA_GREEN_AS_LUMA == 0)', ' // {__a} = luma in perceptual color space (not linear)', ' FxaaTex tex,', ' //', ' // Only used on the optimized 360 version of FXAA Console.', ' // For everything but 360, just use the same input here as for "tex".', ' // For 360, same texture, just alias with a 2nd sampler.', ' // This sampler needs to have an exponent bias of -1.', ' FxaaTex fxaaConsole360TexExpBiasNegOne,', ' //', ' // Only used on the optimized 360 version of FXAA Console.', ' // For everything but 360, just use the same input here as for "tex".', ' // For 360, same texture, just alias with a 3nd sampler.', ' // This sampler needs to have an exponent bias of -2.', ' FxaaTex fxaaConsole360TexExpBiasNegTwo,', ' //', ' // Only used on FXAA Quality.', ' // This must be from a constant/uniform.', ' // {x_} = 1.0/screenWidthInPixels', ' // {_y} = 1.0/screenHeightInPixels', ' FxaaFloat2 fxaaQualityRcpFrame,', ' //', ' // Only used on FXAA Console.', ' // This must be from a constant/uniform.', ' // This effects sub-pixel AA quality and inversely sharpness.', ' // Where N ranges between,', ' // N = 0.50 (default)', ' // N = 0.33 (sharper)', ' // {x__} = -N/screenWidthInPixels', ' // {_y_} = -N/screenHeightInPixels', ' // {_z_} = N/screenWidthInPixels', ' // {__w} = N/screenHeightInPixels', ' FxaaFloat4 fxaaConsoleRcpFrameOpt,', ' //', ' // Only used on FXAA Console.', ' // Not used on 360, but used on PS3 and PC.', ' // This must be from a constant/uniform.', ' // {x__} = -2.0/screenWidthInPixels', ' // {_y_} = -2.0/screenHeightInPixels', ' // {_z_} = 2.0/screenWidthInPixels', ' // {__w} = 2.0/screenHeightInPixels', ' FxaaFloat4 fxaaConsoleRcpFrameOpt2,', ' //', ' // Only used on FXAA Console.', ' // Only used on 360 in place of fxaaConsoleRcpFrameOpt2.', ' // This must be from a constant/uniform.', ' // {x__} = 8.0/screenWidthInPixels', ' // {_y_} = 8.0/screenHeightInPixels', ' // {_z_} = -4.0/screenWidthInPixels', ' // {__w} = -4.0/screenHeightInPixels', ' FxaaFloat4 fxaaConsole360RcpFrameOpt2,', ' //', ' // Only used on FXAA Quality.', ' // This used to be the FXAA_QUALITY_SUBPIX define.', ' // It is here now to allow easier tuning.', ' // Choose the amount of sub-pixel aliasing removal.', ' // This can effect sharpness.', ' // 1.00 - upper limit (softer)', ' // 0.75 - default amount of filtering', ' // 0.50 - lower limit (sharper, less sub-pixel aliasing removal)', ' // 0.25 - almost off', ' // 0.00 - completely off', ' FxaaFloat fxaaQualitySubpix,', ' //', ' // Only used on FXAA Quality.', ' // This used to be the FXAA_QUALITY_EDGE_THRESHOLD define.', ' // It is here now to allow easier tuning.', ' // The minimum amount of local contrast required to apply algorithm.', ' // 0.333 - too little (faster)', ' // 0.250 - low quality', ' // 0.166 - default', ' // 0.125 - high quality', ' // 0.063 - overkill (slower)', ' FxaaFloat fxaaQualityEdgeThreshold,', ' //', ' // Only used on FXAA Quality.', ' // This used to be the FXAA_QUALITY_EDGE_THRESHOLD_MIN define.', ' // It is here now to allow easier tuning.', ' // Trims the algorithm from processing darks.', ' // 0.0833 - upper limit (default, the start of visible unfiltered edges)', ' // 0.0625 - high quality (faster)', ' // 0.0312 - visible limit (slower)', ' // Special notes when using FXAA_GREEN_AS_LUMA,', ' // Likely want to set this to zero.', ' // As colors that are mostly not-green', ' // will appear very dark in the green channel!', ' // Tune by looking at mostly non-green content,', ' // then start at zero and increase until aliasing is a problem.', ' FxaaFloat fxaaQualityEdgeThresholdMin,', ' //', ' // Only used on FXAA Console.', ' // This used to be the FXAA_CONSOLE_EDGE_SHARPNESS define.', ' // It is here now to allow easier tuning.', ' // This does not effect PS3, as this needs to be compiled in.', ' // Use FXAA_CONSOLE_PS3_EDGE_SHARPNESS for PS3.', ' // Due to the PS3 being ALU bound,', ' // there are only three safe values here: 2 and 4 and 8.', ' // These options use the shaders ability to a free *|/ by 2|4|8.', ' // For all other platforms can be a non-power of two.', ' // 8.0 is sharper (default!!!)', ' // 4.0 is softer', ' // 2.0 is really soft (good only for vector graphics inputs)', ' FxaaFloat fxaaConsoleEdgeSharpness,', ' //', ' // Only used on FXAA Console.', ' // This used to be the FXAA_CONSOLE_EDGE_THRESHOLD define.', ' // It is here now to allow easier tuning.', ' // This does not effect PS3, as this needs to be compiled in.', ' // Use FXAA_CONSOLE_PS3_EDGE_THRESHOLD for PS3.', ' // Due to the PS3 being ALU bound,', ' // there are only two safe values here: 1/4 and 1/8.', ' // These options use the shaders ability to a free *|/ by 2|4|8.', ' // The console setting has a different mapping than the quality setting.', ' // Other platforms can use other values.', ' // 0.125 leaves less aliasing, but is softer (default!!!)', ' // 0.25 leaves more aliasing, and is sharper', ' FxaaFloat fxaaConsoleEdgeThreshold,', ' //', ' // Only used on FXAA Console.', ' // This used to be the FXAA_CONSOLE_EDGE_THRESHOLD_MIN define.', ' // It is here now to allow easier tuning.', ' // Trims the algorithm from processing darks.', ' // The console setting has a different mapping than the quality setting.', ' // This only applies when FXAA_EARLY_EXIT is 1.', ' // This does not apply to PS3,', ' // PS3 was simplified to avoid more shader instructions.', ' // 0.06 - faster but more aliasing in darks', ' // 0.05 - default', ' // 0.04 - slower and less aliasing in darks', ' // Special notes when using FXAA_GREEN_AS_LUMA,', ' // Likely want to set this to zero.', ' // As colors that are mostly not-green', ' // will appear very dark in the green channel!', ' // Tune by looking at mostly non-green content,', ' // then start at zero and increase until aliasing is a problem.', ' FxaaFloat fxaaConsoleEdgeThresholdMin,', ' //', ' // Extra constants for 360 FXAA Console only.', ' // Use zeros or anything else for other platforms.', ' // These must be in physical constant registers and NOT immediates.', ' // Immediates will result in compiler un-optimizing.', ' // {xyzw} = float4(1.0, -1.0, 0.25, -0.25)', ' FxaaFloat4 fxaaConsole360ConstDir', ') {', '/*--------------------------------------------------------------------------*/', ' FxaaFloat2 posM;', ' posM.x = pos.x;', ' posM.y = pos.y;', ' #if (FXAA_GATHER4_ALPHA == 1)', ' #if (FXAA_DISCARD == 0)', ' FxaaFloat4 rgbyM = FxaaTexTop(tex, posM);', ' #if (FXAA_GREEN_AS_LUMA == 0)', ' #define lumaM rgbyM.w', ' #else', ' #define lumaM rgbyM.y', ' #endif', ' #endif', ' #if (FXAA_GREEN_AS_LUMA == 0)', ' FxaaFloat4 luma4A = FxaaTexAlpha4(tex, posM);', ' FxaaFloat4 luma4B = FxaaTexOffAlpha4(tex, posM, FxaaInt2(-1, -1));', ' #else', ' FxaaFloat4 luma4A = FxaaTexGreen4(tex, posM);', ' FxaaFloat4 luma4B = FxaaTexOffGreen4(tex, posM, FxaaInt2(-1, -1));', ' #endif', ' #if (FXAA_DISCARD == 1)', ' #define lumaM luma4A.w', ' #endif', ' #define lumaE luma4A.z', ' #define lumaS luma4A.x', ' #define lumaSE luma4A.y', ' #define lumaNW luma4B.w', ' #define lumaN luma4B.z', ' #define lumaW luma4B.x', ' #else', ' FxaaFloat4 rgbyM = FxaaTexTop(tex, posM);', ' #if (FXAA_GREEN_AS_LUMA == 0)', ' #define lumaM rgbyM.w', ' #else', ' #define lumaM rgbyM.y', ' #endif', ' #if (FXAA_GLSL_100 == 1)', ' FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 0.0, 1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 1.0, 0.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 0.0,-1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2(-1.0, 0.0), fxaaQualityRcpFrame.xy));', ' #else', ' FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy));', ' #endif', ' #endif', '/*--------------------------------------------------------------------------*/', ' FxaaFloat maxSM = max(lumaS, lumaM);', ' FxaaFloat minSM = min(lumaS, lumaM);', ' FxaaFloat maxESM = max(lumaE, maxSM);', ' FxaaFloat minESM = min(lumaE, minSM);', ' FxaaFloat maxWN = max(lumaN, lumaW);', ' FxaaFloat minWN = min(lumaN, lumaW);', ' FxaaFloat rangeMax = max(maxWN, maxESM);', ' FxaaFloat rangeMin = min(minWN, minESM);', ' FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold;', ' FxaaFloat range = rangeMax - rangeMin;', ' FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled);', ' FxaaBool earlyExit = range < rangeMaxClamped;', '/*--------------------------------------------------------------------------*/', ' if(earlyExit)', ' #if (FXAA_DISCARD == 1)', ' FxaaDiscard;', ' #else', ' return rgbyM;', ' #endif', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_GATHER4_ALPHA == 0)', ' #if (FXAA_GLSL_100 == 1)', ' FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2(-1.0,-1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 1.0, 1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 1.0,-1.0), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2(-1.0, 1.0), fxaaQualityRcpFrame.xy));', ' #else', ' FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));', ' #endif', ' #else', ' FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy));', ' FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));', ' #endif', '/*--------------------------------------------------------------------------*/', ' FxaaFloat lumaNS = lumaN + lumaS;', ' FxaaFloat lumaWE = lumaW + lumaE;', ' FxaaFloat subpixRcpRange = 1.0/range;', ' FxaaFloat subpixNSWE = lumaNS + lumaWE;', ' FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS;', ' FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat lumaNESE = lumaNE + lumaSE;', ' FxaaFloat lumaNWNE = lumaNW + lumaNE;', ' FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE;', ' FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat lumaNWSW = lumaNW + lumaSW;', ' FxaaFloat lumaSWSE = lumaSW + lumaSE;', ' FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2);', ' FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2);', ' FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW;', ' FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE;', ' FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4;', ' FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE;', ' FxaaFloat lengthSign = fxaaQualityRcpFrame.x;', ' FxaaBool horzSpan = edgeHorz >= edgeVert;', ' FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE;', '/*--------------------------------------------------------------------------*/', ' if(!horzSpan) lumaN = lumaW;', ' if(!horzSpan) lumaS = lumaE;', ' if(horzSpan) lengthSign = fxaaQualityRcpFrame.y;', ' FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat gradientN = lumaN - lumaM;', ' FxaaFloat gradientS = lumaS - lumaM;', ' FxaaFloat lumaNN = lumaN + lumaM;', ' FxaaFloat lumaSS = lumaS + lumaM;', ' FxaaBool pairN = abs(gradientN) >= abs(gradientS);', ' FxaaFloat gradient = max(abs(gradientN), abs(gradientS));', ' if(pairN) lengthSign = -lengthSign;', ' FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange);', '/*--------------------------------------------------------------------------*/', ' FxaaFloat2 posB;', ' posB.x = posM.x;', ' posB.y = posM.y;', ' FxaaFloat2 offNP;', ' offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;', ' offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;', ' if(!horzSpan) posB.x += lengthSign * 0.5;', ' if( horzSpan) posB.y += lengthSign * 0.5;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat2 posN;', ' posN.x = posB.x - offNP.x * FXAA_QUALITY_P0;', ' posN.y = posB.y - offNP.y * FXAA_QUALITY_P0;', ' FxaaFloat2 posP;', ' posP.x = posB.x + offNP.x * FXAA_QUALITY_P0;', ' posP.y = posB.y + offNP.y * FXAA_QUALITY_P0;', ' FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0;', ' FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN));', ' FxaaFloat subpixE = subpixC * subpixC;', ' FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP));', '/*--------------------------------------------------------------------------*/', ' if(!pairN) lumaNN = lumaSS;', ' FxaaFloat gradientScaled = gradient * 1.0/4.0;', ' FxaaFloat lumaMM = lumaM - lumaNN * 0.5;', ' FxaaFloat subpixF = subpixD * subpixE;', ' FxaaBool lumaMLTZero = lumaMM < 0.0;', '/*--------------------------------------------------------------------------*/', ' lumaEndN -= lumaNN * 0.5;', ' lumaEndP -= lumaNN * 0.5;', ' FxaaBool doneN = abs(lumaEndN) >= gradientScaled;', ' FxaaBool doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P1;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P1;', ' FxaaBool doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P1;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P1;', '/*--------------------------------------------------------------------------*/', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P2;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P2;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P2;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P2;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 3)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P3;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P3;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P3;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P3;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 4)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P4;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P4;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P4;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P4;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 5)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P5;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P5;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P5;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P5;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 6)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P6;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P6;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P6;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P6;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 7)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P7;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P7;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P7;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P7;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 8)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P8;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P8;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P8;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P8;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 9)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P9;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P9;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P9;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P9;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 10)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P10;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P10;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P10;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P10;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 11)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P11;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P11;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P11;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P11;', '/*--------------------------------------------------------------------------*/', ' #if (FXAA_QUALITY_PS > 12)', ' if(doneNP) {', ' if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));', ' if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));', ' if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;', ' if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;', ' doneN = abs(lumaEndN) >= gradientScaled;', ' doneP = abs(lumaEndP) >= gradientScaled;', ' if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P12;', ' if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P12;', ' doneNP = (!doneN) || (!doneP);', ' if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P12;', ' if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P12;', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', ' #endif', '/*--------------------------------------------------------------------------*/', ' }', '/*--------------------------------------------------------------------------*/', ' FxaaFloat dstN = posM.x - posN.x;', ' FxaaFloat dstP = posP.x - posM.x;', ' if(!horzSpan) dstN = posM.y - posN.y;', ' if(!horzSpan) dstP = posP.y - posM.y;', '/*--------------------------------------------------------------------------*/', ' FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero;', ' FxaaFloat spanLength = (dstP + dstN);', ' FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero;', ' FxaaFloat spanLengthRcp = 1.0/spanLength;', '/*--------------------------------------------------------------------------*/', ' FxaaBool directionN = dstN < dstP;', ' FxaaFloat dst = min(dstN, dstP);', ' FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP;', ' FxaaFloat subpixG = subpixF * subpixF;', ' FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5;', ' FxaaFloat subpixH = subpixG * fxaaQualitySubpix;', '/*--------------------------------------------------------------------------*/', ' FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0;', ' FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH);', ' if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign;', ' if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign;', ' #if (FXAA_DISCARD == 1)', ' return FxaaTexTop(tex, posM);', ' #else', ' return FxaaFloat4(FxaaTexTop(tex, posM).xyz, lumaM);', ' #endif', '}', '/*==========================================================================*/', '#endif', '', 'void main() {', ' gl_FragColor = FxaaPixelShader(', ' vUv,', ' vec4(0.0),', ' tDiffuse,', ' tDiffuse,', ' tDiffuse,', ' resolution,', ' vec4(0.0),', ' vec4(0.0),', ' vec4(0.0),', ' 0.75,', ' 0.166,', ' 0.0833,', ' 0.0,', ' 0.0,', ' 0.0,', ' vec4(0.0)', ' );', '', ' // TODO avoid querying texture twice for same texel', ' gl_FragColor.a = texture2D(tDiffuse, vUv).a;', '}'].join('\n') }); -/** - * Edge Detection Shader using Frei-Chen filter - * Based on http://rastergrid.com/blog/2011/01/frei-chen-edge-detector - * - * aspect: vec2 of (1/width, 1/height) - */ +if (process.env.NODE_ENV === 'development') { + Object.assign(dragConfigResolver, { + useTouch(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`useTouch\` option has been renamed to \`pointer.touch\`. Use it as in \`{ pointer: { touch: true } }\`.`); + } -({ - uniforms: { - tDiffuse: { - value: null + return NaN; }, - aspect: { - value: new Vector2(512, 512) - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'varying vec2 vUv;', 'uniform vec2 aspect;', 'vec2 texel = vec2(1.0 / aspect.x, 1.0 / aspect.y);', 'mat3 G[9];', // hard coded matrix values!!!! as suggested in https://github.com/neilmendoza/ofxPostProcessing/blob/master/src/EdgePass.cpp#L45 - 'const mat3 g0 = mat3( 0.3535533845424652, 0, -0.3535533845424652, 0.5, 0, -0.5, 0.3535533845424652, 0, -0.3535533845424652 );', 'const mat3 g1 = mat3( 0.3535533845424652, 0.5, 0.3535533845424652, 0, 0, 0, -0.3535533845424652, -0.5, -0.3535533845424652 );', 'const mat3 g2 = mat3( 0, 0.3535533845424652, -0.5, -0.3535533845424652, 0, 0.3535533845424652, 0.5, -0.3535533845424652, 0 );', 'const mat3 g3 = mat3( 0.5, -0.3535533845424652, 0, -0.3535533845424652, 0, 0.3535533845424652, 0, 0.3535533845424652, -0.5 );', 'const mat3 g4 = mat3( 0, -0.5, 0, 0.5, 0, 0.5, 0, -0.5, 0 );', 'const mat3 g5 = mat3( -0.5, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5 );', 'const mat3 g6 = mat3( 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.6666666865348816, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204 );', 'const mat3 g7 = mat3( -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, 0.6666666865348816, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408 );', 'const mat3 g8 = mat3( 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408 );', 'void main(void)', '{', ' G[0] = g0,', ' G[1] = g1,', ' G[2] = g2,', ' G[3] = g3,', ' G[4] = g4,', ' G[5] = g5,', ' G[6] = g6,', ' G[7] = g7,', ' G[8] = g8;', ' mat3 I;', ' float cnv[9];', ' vec3 sample;', - /* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */ - ' for (float i=0.0; i<3.0; i++) {', ' for (float j=0.0; j<3.0; j++) {', ' sample = texture2D(tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb;', ' I[int(i)][int(j)] = length(sample);', ' }', ' }', - /* calculate the convolution values for all the masks */ - ' for (int i=0; i<9; i++) {', ' float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);', ' cnv[i] = dp3 * dp3;', ' }', ' float M = (cnv[0] + cnv[1]) + (cnv[2] + cnv[3]);', ' float S = (cnv[4] + cnv[5]) + (cnv[6] + cnv[7]) + (cnv[8] + M);', ' gl_FragColor = vec4(vec3(sqrt(M/S)), 1.0);', '}'].join('\n') -}); -/** - * The god-ray generation shader. - * - * First pass: - * - * The depth map is blurred along radial lines towards the "sun". The - * output is written to a temporary render target (I used a 1/4 sized - * target). - * - * Pass two & three: - * - * The results of the previous pass are re-blurred, each time with a - * decreased distance between samples. - */ + experimental_preventWindowScrollY(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`experimental_preventWindowScrollY\` option has been renamed to \`preventScroll\`.`); + } -({ - uniforms: { - tInput: { - value: null - }, - fStepSize: { - value: 1.0 + return NaN; }, - vSunPositionScreenSpace: { - value: new Vector3() - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#define TAPS_PER_PASS 6.0', 'varying vec2 vUv;', 'uniform sampler2D tInput;', 'uniform vec3 vSunPositionScreenSpace;', 'uniform float fStepSize;', // filter step size - 'void main() {', // delta from current pixel to "sun" position - ' vec2 delta = vSunPositionScreenSpace.xy - vUv;', ' float dist = length( delta );', // Step vector (uv space) - ' vec2 stepv = fStepSize * delta / dist;', // Number of iterations between pixel and sun - ' float iters = dist/fStepSize;', ' vec2 uv = vUv.xy;', ' float col = 0.0;', // This breaks ANGLE in Chrome 22 - // - see http://code.google.com/p/chromium/issues/detail?id=153105 - /* - // Unrolling didnt do much on my hardware (ATI Mobility Radeon 3450), - // so i've just left the loop - "for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {", - // Accumulate samples, making sure we dont walk past the light source. - // The check for uv.y < 1 would not be necessary with "border" UV wrap - // mode, with a black border color. I don't think this is currently - // exposed by three.js. As a result there might be artifacts when the - // sun is to the left, right or bottom of screen as these cases are - // not specifically handled. - " col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );", - " uv += stepv;", - "}", - */ - // Unrolling loop manually makes it work in ANGLE - ' float f = min( 1.0, max( vSunPositionScreenSpace.z / 1000.0, 0.0 ) );', // used to fade out godrays - ' if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', ' if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;', ' uv += stepv;', // Should technically be dividing by 'iters', but 'TAPS_PER_PASS' smooths out - // objectionable artifacts, in particular near the sun position. The side - // effect is that the result is darker than it should be around the sun, as - // TAPS_PER_PASS is greater than the number of samples actually accumulated. - // When the result is inverted (in the shader 'godrays_combine', this produces - // a slight bright spot at the position of the sun, even when it is occluded. - ' gl_FragColor = vec4( col/TAPS_PER_PASS );', ' gl_FragColor.a = 1.0;', '}'].join('\n') -}); -/** - * A dodgy sun/sky shader. Makes a bright spot at the sun location. Would be - * cheaper/faster/simpler to implement this as a simple sun sprite. - */ + swipeVelocity(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`swipeVelocity\` option has been renamed to \`swipe.velocity\`. Use it as in \`{ swipe: { velocity: 0.5 } }\`.`); + } -({ - uniforms: { - vSunPositionScreenSpace: { - value: new Vector3() - }, - fAspect: { - value: 1.0 - }, - sunColor: { - value: new Color(0xffee00) + return NaN; }, - bgColor: { - value: new Color(0x000000) - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['varying vec2 vUv;', 'uniform vec3 vSunPositionScreenSpace;', 'uniform float fAspect;', 'uniform vec3 sunColor;', 'uniform vec3 bgColor;', 'void main() {', ' vec2 diff = vUv - vSunPositionScreenSpace.xy;', // Correct for aspect ratio - ' diff.x *= fAspect;', ' float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 );', ' prop = 0.35 * pow( 1.0 - prop, 3.0 );', ' gl_FragColor.xyz = ( vSunPositionScreenSpace.z > 0.0 ) ? mix( sunColor, bgColor, 1.0 - prop ) : bgColor;', ' gl_FragColor.w = 1.0;', '}'].join('\n') -}); -/** - * Normal map shader - * - compute normals from heightmap - */ + swipeDistance(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`swipeDistance\` option has been renamed to \`swipe.distance\`. Use it as in \`{ swipe: { distance: 50 } }\`.`); + } -({ - uniforms: { - heightMap: { - value: null - }, - resolution: { - value: new Vector2(512, 512) - }, - scale: { - value: new Vector2(1, 1) + return NaN; }, - height: { - value: 0.05 - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform float height;', 'uniform vec2 resolution;', 'uniform sampler2D heightMap;', 'varying vec2 vUv;', 'void main() {', ' float val = texture2D( heightMap, vUv ).x;', ' float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x;', ' float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x;', ' gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 );', '}'].join('\n') -}); -/** - * Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM) - * - * As mentioned in the video the Sobel operator expects a grayscale image as input. - * - */ + swipeDuration(value) { + if (value !== undefined) { + throw Error(`[@use-gesture]: \`swipeDuration\` option has been renamed to \`swipe.duration\`. Use it as in \`{ swipe: { duration: 250 } }\`.`); + } -({ - uniforms: { - tDiffuse: { - value: null - }, - resolution: { - value: new Vector2() + return NaN; } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['uniform sampler2D tDiffuse;', 'uniform vec2 resolution;', 'varying vec2 vUv;', 'void main() {', ' vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y );', // kernel definition (in glsl matrices are filled in column-major order) - ' const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 );', // x direction kernel - ' const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 );', // y direction kernel - // fetch the 3x3 neighbourhood of a fragment - // first column - ' float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r;', ' float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r;', ' float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r;', // second column - ' float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r;', ' float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r;', ' float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r;', // third column - ' float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r;', ' float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r;', ' float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r;', // gradient value in x direction - ' float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 + ', ' Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 + ', ' Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2; ', // gradient value in y direction - ' float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 + ', ' Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 + ', ' Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2; ', // magnitute of the total gradient - ' float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) );', ' gl_FragColor = vec4( vec3( G ), 1 );', '}'].join('\n') -}); - -/** - * ------------------------------------------------------------------------------------------ - * Subsurface Scattering shader - * Based on GDC 2011 – Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look - * https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/ - *------------------------------------------------------------------------------------------ - */ -function replaceAll(string, find, replace) { - return string.split(find).join(replace); + }); } -const meshphong_frag_head = ShaderChunk['meshphong_frag'].slice(0, ShaderChunk['meshphong_frag'].indexOf('void main() {')); -const meshphong_frag_body = ShaderChunk['meshphong_frag'].slice(ShaderChunk['meshphong_frag'].indexOf('void main() {')); -({ - uniforms: UniformsUtils.merge([ShaderLib['phong'].uniforms, { - thicknessMap: { - value: null - }, - thicknessColor: { - value: new Color(0xffffff) - }, - thicknessDistortion: { - value: 0.1 - }, - thicknessAmbient: { - value: 0.0 - }, - thicknessAttenuation: { - value: 0.1 - }, - thicknessPower: { - value: 2.0 - }, - thicknessScale: { - value: 10.0 - } - }]), - vertexShader: ['#define USE_UV', ShaderChunk['meshphong_vert']].join('\n'), - fragmentShader: ['#define USE_UV', '#define SUBSURFACE', meshphong_frag_head, 'uniform sampler2D thicknessMap;', 'uniform float thicknessPower;', 'uniform float thicknessScale;', 'uniform float thicknessDistortion;', 'uniform float thicknessAmbient;', 'uniform float thicknessAttenuation;', 'uniform vec3 thicknessColor;', 'void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in GeometricContext geometry, inout ReflectedLight reflectedLight) {', ' vec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;', ' vec3 scatteringHalf = normalize(directLight.direction + (geometry.normal * thicknessDistortion));', ' float scatteringDot = pow(saturate(dot(geometry.viewDir, -scatteringHalf)), thicknessPower) * thicknessScale;', ' vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;', ' reflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;', '}', meshphong_frag_body.replace('#include ', replaceAll(ShaderChunk['lights_fragment_begin'], 'RE_Direct( directLight, geometry, material, reflectedLight );', ['RE_Direct( directLight, geometry, material, reflectedLight );', '#if defined( SUBSURFACE ) && defined( USE_UV )', ' RE_Direct_Scattering(directLight, vUv, geometry, reflectedLight);', '#endif'].join('\n')))].join('\n') -}); - -/** - * Currently contains: - * - * toon1 - * toon2 - * hatching - * dotted - */ +_objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { + device(_v, _k, { + shared, + pointer: { + touch = false + } = {} + }) { + const sharedConfig = shared; + if (sharedConfig.target && !SUPPORT.touch && SUPPORT.gesture) return 'gesture'; + if (SUPPORT.touch && touch) return 'touch'; -({ - uniforms: { - uDirLightPos: { - value: new Vector3() - }, - uDirLightColor: { - value: new Color(0xeeeeee) - }, - uAmbientLightColor: { - value: new Color(0x050505) - }, - uBaseColor: { - value: new Color(0xffffff) - } - }, - vertexShader: ['varying vec3 vNormal;', 'varying vec3 vRefract;', 'void main() {', ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );', ' vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );', ' vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );', ' vNormal = normalize( normalMatrix * normal );', ' vec3 I = worldPosition.xyz - cameraPosition;', ' vRefract = refract( normalize( I ), worldNormal, 1.02 );', ' gl_Position = projectionMatrix * mvPosition;', '}'].join('\n'), - fragmentShader: ['uniform vec3 uBaseColor;', 'uniform vec3 uDirLightPos;', 'uniform vec3 uDirLightColor;', 'uniform vec3 uAmbientLightColor;', 'varying vec3 vNormal;', 'varying vec3 vRefract;', 'void main() {', ' float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);', ' vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;', ' float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) );', ' intensity += length(lightWeighting) * 0.2;', ' float cameraWeighting = dot( normalize( vNormal ), vRefract );', ' intensity += pow( 1.0 - length( cameraWeighting ), 6.0 );', ' intensity = intensity * 0.2 + 0.3;', ' if ( intensity < 0.50 ) {', ' gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 );', ' } else {', ' gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 );', '}', '}'].join('\n') -}); -({ - uniforms: { - uDirLightPos: { - value: new Vector3() - }, - uDirLightColor: { - value: new Color(0xeeeeee) - }, - uAmbientLightColor: { - value: new Color(0x050505) - }, - uBaseColor: { - value: new Color(0xeeeeee) - }, - uLineColor1: { - value: new Color(0x808080) - }, - uLineColor2: { - value: new Color(0x000000) - }, - uLineColor3: { - value: new Color(0x000000) - }, - uLineColor4: { - value: new Color(0x000000) + if (SUPPORT.touchscreen) { + if (SUPPORT.pointer) return 'pointer'; + if (SUPPORT.touch) return 'touch'; } }, - vertexShader: ['varying vec3 vNormal;', 'void main() {', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', ' vNormal = normalize( normalMatrix * normal );', '}'].join('\n'), - fragmentShader: ['uniform vec3 uBaseColor;', 'uniform vec3 uLineColor1;', 'uniform vec3 uLineColor2;', 'uniform vec3 uLineColor3;', 'uniform vec3 uLineColor4;', 'uniform vec3 uDirLightPos;', 'uniform vec3 uDirLightColor;', 'uniform vec3 uAmbientLightColor;', 'varying vec3 vNormal;', 'void main() {', ' float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4);', ' float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);', ' gl_FragColor = vec4( uBaseColor, 1.0 );', ' if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) {', ' gl_FragColor *= vec4( uLineColor1, 1.0 );', ' }', ' if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) {', ' gl_FragColor *= vec4( uLineColor2, 1.0 );', ' }', '}'].join('\n') -}); -({ - uniforms: { - uDirLightPos: { - value: new Vector3() - }, - uDirLightColor: { - value: new Color(0xeeeeee) - }, - uAmbientLightColor: { - value: new Color(0x050505) - }, - uBaseColor: { - value: new Color(0xffffff) - }, - uLineColor1: { - value: new Color(0x000000) - }, - uLineColor2: { - value: new Color(0x000000) - }, - uLineColor3: { - value: new Color(0x000000) - }, - uLineColor4: { - value: new Color(0x000000) - } + + bounds(_v, _k, { + scaleBounds = {}, + angleBounds = {} + }) { + const _scaleBounds = state => { + const D = assignDefault(call(scaleBounds, state), { + min: -Infinity, + max: Infinity + }); + return [D.min, D.max]; + }; + + const _angleBounds = state => { + const A = assignDefault(call(angleBounds, state), { + min: -Infinity, + max: Infinity + }); + return [A.min, A.max]; + }; + + if (typeof scaleBounds !== 'function' && typeof angleBounds !== 'function') return [_scaleBounds(), _angleBounds()]; + return state => [_scaleBounds(state), _angleBounds(state)]; }, - vertexShader: ['varying vec3 vNormal;', 'void main() {', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', ' vNormal = normalize( normalMatrix * normal );', '}'].join('\n'), - fragmentShader: ['uniform vec3 uBaseColor;', 'uniform vec3 uLineColor1;', 'uniform vec3 uLineColor2;', 'uniform vec3 uLineColor3;', 'uniform vec3 uLineColor4;', 'uniform vec3 uDirLightPos;', 'uniform vec3 uDirLightColor;', 'uniform vec3 uAmbientLightColor;', 'varying vec3 vNormal;', 'void main() {', ' float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);', ' vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;', ' gl_FragColor = vec4( uBaseColor, 1.0 );', ' if ( length(lightWeighting) < 1.00 ) {', ' if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {', ' gl_FragColor = vec4( uLineColor1, 1.0 );', ' }', ' }', ' if ( length(lightWeighting) < 0.75 ) {', ' if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {', ' gl_FragColor = vec4( uLineColor2, 1.0 );', ' }', ' }', ' if ( length(lightWeighting) < 0.50 ) {', ' if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {', ' gl_FragColor = vec4( uLineColor3, 1.0 );', ' }', ' }', ' if ( length(lightWeighting) < 0.3465 ) {', ' if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {', ' gl_FragColor = vec4( uLineColor4, 1.0 );', ' }', ' }', '}'].join('\n') -}); -({ - uniforms: { - uDirLightPos: { - value: new Vector3() - }, - uDirLightColor: { - value: new Color(0xeeeeee) - }, - uAmbientLightColor: { - value: new Color(0x050505) - }, - uBaseColor: { - value: new Color(0xffffff) - }, - uLineColor1: { - value: new Color(0x000000) - } + + threshold(value, _k, config) { + this.lockDirection = config.axis === 'lock'; + const threshold = V.toVector(value, this.lockDirection ? [0.1, 3] : 0); + return threshold; }, - vertexShader: ['varying vec3 vNormal;', 'void main() {', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', ' vNormal = normalize( normalMatrix * normal );', '}'].join('\n'), - fragmentShader: ['uniform vec3 uBaseColor;', 'uniform vec3 uLineColor1;', 'uniform vec3 uLineColor2;', 'uniform vec3 uLineColor3;', 'uniform vec3 uLineColor4;', 'uniform vec3 uDirLightPos;', 'uniform vec3 uDirLightColor;', 'uniform vec3 uAmbientLightColor;', 'varying vec3 vNormal;', 'void main() {', 'float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);', 'vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;', 'gl_FragColor = vec4( uBaseColor, 1.0 );', 'if ( length(lightWeighting) < 1.00 ) {', ' if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) {', ' gl_FragColor = vec4( uLineColor1, 1.0 );', ' }', ' }', ' if ( length(lightWeighting) < 0.50 ) {', ' if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) {', ' gl_FragColor = vec4( uLineColor1, 1.0 );', ' }', ' }', '}'].join('\n') -}); -/** - * Triangle blur shader - * based on glfx.js triangle blur shader - * https://github.com/evanw/glfx.js - * - * A basic blur filter, which convolves the image with a - * pyramid filter. The pyramid filter is separable and is applied as two - * perpendicular triangle filters. - */ + modifierKey(value) { + if (value === undefined) return 'ctrlKey'; + return value; + } -({ - uniforms: { - texture: { - value: null - }, - delta: { - value: new Vector2(1, 1) - } - }, - vertexShader: ['varying vec2 vUv;', 'void main() {', ' vUv = uv;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'), - fragmentShader: ['#include ', '#define ITERATIONS 10.0', 'uniform sampler2D texture;', 'uniform vec2 delta;', 'varying vec2 vUv;', 'void main() {', ' vec4 color = vec4( 0.0 );', ' float total = 0.0;', // randomize the lookup values to hide the fixed number of samples - ' float offset = rand( vUv );', ' for ( float t = -ITERATIONS; t <= ITERATIONS; t ++ ) {', ' float percent = ( t + offset - 0.5 ) / ITERATIONS;', ' float weight = 1.0 - abs( percent );', ' color += texture2D( texture, vUv + delta * percent ) * weight;', ' total += weight;', ' }', ' gl_FragColor = color / total;', '}'].join('\n') }); -/** - * Shaders to render 3D volumes using raycasting. - * The applied techniques are based on similar implementations in the Visvis and Vispy projects. - * This is not the only approach, therefore it's marked 1. - */ +_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { + mouseOnly: (value = true) => value +}); -({ - uniforms: { - u_size: { - value: new Vector3(1, 1, 1) - }, - u_renderstyle: { - value: 0 - }, - u_renderthreshold: { - value: 0.5 - }, - u_clim: { - value: new Vector2(1, 1) - }, - u_data: { - value: null - }, - u_cmdata: { - value: null - } - }, - vertexShader: [' varying vec4 v_nearpos;', ' varying vec4 v_farpos;', ' varying vec3 v_position;', ' void main() {', // Prepare transforms to map to "camera view". See also: - // https://threejs.org/docs/#api/renderers/webgl/WebGLProgram - ' mat4 viewtransformf = modelViewMatrix;', ' mat4 viewtransformi = inverse(modelViewMatrix);', // Project local vertex coordinate to camera position. Then do a step - // backward (in cam coords) to the near clipping plane, and project back. Do - // the same for the far clipping plane. This gives us all the information we - // need to calculate the ray and truncate it to the viewing cone. - ' vec4 position4 = vec4(position, 1.0);', ' vec4 pos_in_cam = viewtransformf * position4;', // Intersection of ray and near clipping plane (z = -1 in clip coords) - ' pos_in_cam.z = -pos_in_cam.w;', ' v_nearpos = viewtransformi * pos_in_cam;', // Intersection of ray and far clipping plane (z = +1 in clip coords) - ' pos_in_cam.z = pos_in_cam.w;', ' v_farpos = viewtransformi * pos_in_cam;', // Set varyings and output pos - ' v_position = position;', ' gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4;', ' }'].join('\n'), - fragmentShader: [' precision highp float;', ' precision mediump sampler3D;', ' uniform vec3 u_size;', ' uniform int u_renderstyle;', ' uniform float u_renderthreshold;', ' uniform vec2 u_clim;', ' uniform sampler3D u_data;', ' uniform sampler2D u_cmdata;', ' varying vec3 v_position;', ' varying vec4 v_nearpos;', ' varying vec4 v_farpos;', // The maximum distance through our rendering volume is sqrt(3). - ' const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3', ' const int REFINEMENT_STEPS = 4;', ' const float relative_step_size = 1.0;', ' const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0);', ' const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0);', ' const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0);', ' const float shininess = 40.0;', ' void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);', ' void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);', ' float sample1(vec3 texcoords);', ' vec4 apply_colormap(float val);', ' vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray);', ' void main() {', // Normalize clipping plane info - ' vec3 farpos = v_farpos.xyz / v_farpos.w;', ' vec3 nearpos = v_nearpos.xyz / v_nearpos.w;', // Calculate unit vector pointing in the view direction through this fragment. - ' vec3 view_ray = normalize(nearpos.xyz - farpos.xyz);', // Compute the (negative) distance to the front surface or near clipping plane. - // v_position is the back face of the cuboid, so the initial distance calculated in the dot - // product below is the distance from near clip plane to the back of the cuboid - ' float distance = dot(nearpos - v_position, view_ray);', ' distance = max(distance, min((-0.5 - v_position.x) / view_ray.x,', ' (u_size.x - 0.5 - v_position.x) / view_ray.x));', ' distance = max(distance, min((-0.5 - v_position.y) / view_ray.y,', ' (u_size.y - 0.5 - v_position.y) / view_ray.y));', ' distance = max(distance, min((-0.5 - v_position.z) / view_ray.z,', ' (u_size.z - 0.5 - v_position.z) / view_ray.z));', // Now we have the starting position on the front surface - ' vec3 front = v_position + view_ray * distance;', // Decide how many steps to take - ' int nsteps = int(-distance / relative_step_size + 0.5);', ' if ( nsteps < 1 )', ' discard;', // Get starting location and step vector in texture coordinates - ' vec3 step = ((v_position - front) / u_size) / float(nsteps);', ' vec3 start_loc = front / u_size;', // For testing: show the number of steps. This helps to establish - // whether the rays are correctly oriented - //'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0);', - //'return;', - ' if (u_renderstyle == 0)', ' cast_mip(start_loc, step, nsteps, view_ray);', ' else if (u_renderstyle == 1)', ' cast_iso(start_loc, step, nsteps, view_ray);', ' if (gl_FragColor.a < 0.05)', ' discard;', ' }', ' float sample1(vec3 texcoords) {', ' /* Sample float value from a 3D texture. Assumes intensity data. */', ' return texture(u_data, texcoords.xyz).r;', ' }', ' vec4 apply_colormap(float val) {', ' val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]);', ' return texture2D(u_cmdata, vec2(val, 0.5));', ' }', ' void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {', ' float max_val = -1e6;', ' int max_i = 100;', ' vec3 loc = start_loc;', // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with - // non-constant expression. So we use a hard-coded max, and an additional condition - // inside the loop. - ' for (int iter=0; iter= nsteps)', ' break;', // Sample from the 3D texture - ' float val = sample1(loc);', // Apply MIP operation - ' if (val > max_val) {', ' max_val = val;', ' max_i = iter;', ' }', // Advance location deeper into the volume - ' loc += step;', ' }', // Refine location, gives crispier images - ' vec3 iloc = start_loc + step * (float(max_i) - 0.5);', ' vec3 istep = step / float(REFINEMENT_STEPS);', ' for (int i=0; i= nsteps)', ' break;', // Sample from the 3D texture - ' float val = sample1(loc);', ' if (val > low_threshold) {', // Take the last interval in smaller steps - ' vec3 iloc = loc - 0.5 * step;', ' vec3 istep = step / float(REFINEMENT_STEPS);', ' for (int i=0; i u_renderthreshold) {', ' gl_FragColor = add_lighting(val, iloc, dstep, view_ray);', ' return;', ' }', ' iloc += istep;', ' }', ' }', // Advance location deeper into the volume - ' loc += step;', ' }', ' }', ' vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray)', ' {', // Calculate color by incorporating lighting - // View direction - ' vec3 V = normalize(view_ray);', // calculate normal vector from gradient - ' vec3 N;', ' float val1, val2;', ' val1 = sample1(loc + vec3(-step[0], 0.0, 0.0));', ' val2 = sample1(loc + vec3(+step[0], 0.0, 0.0));', ' N[0] = val1 - val2;', ' val = max(max(val1, val2), val);', ' val1 = sample1(loc + vec3(0.0, -step[1], 0.0));', ' val2 = sample1(loc + vec3(0.0, +step[1], 0.0));', ' N[1] = val1 - val2;', ' val = max(max(val1, val2), val);', ' val1 = sample1(loc + vec3(0.0, 0.0, -step[2]));', ' val2 = sample1(loc + vec3(0.0, 0.0, +step[2]));', ' N[2] = val1 - val2;', ' val = max(max(val1, val2), val);', ' float gm = length(N); // gradient magnitude', ' N = normalize(N);', // Flip normal so it points towards viewer - ' float Nselect = float(dot(N, V) > 0.0);', ' N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N;', // Init colors - ' vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0);', ' vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0);', ' vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0);', // note: could allow multiple lights - ' for (int i=0; i<1; i++)', ' {', // Get light direction (make sure to prevent zero devision) - ' vec3 L = normalize(view_ray); //lightDirs[i];', ' float lightEnabled = float( length(L) > 0.0 );', ' L = normalize(L + (1.0 - lightEnabled));', // Calculate lighting properties - ' float lambertTerm = clamp(dot(N, L), 0.0, 1.0);', ' vec3 H = normalize(L+V); // Halfway vector', ' float specularTerm = pow(max(dot(H, N), 0.0), shininess);', // Calculate mask - ' float mask1 = lightEnabled;', // Calculate colors - ' ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient;', ' diffuse_color += mask1 * lambertTerm;', ' specular_color += mask1 * specularTerm * specular_color;', ' }', // Calculate final color by componing different components - ' vec4 final_color;', ' vec4 color = apply_colormap(val);', ' final_color = color * (ambient_color + diffuse_color) + specular_color;', ' final_color.a = color.a;', ' return final_color;', ' }'].join('\n') +_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { + mouseOnly: (value = true) => value }); /** @@ -148939,11 +77575,11 @@ const Line$1 = /*#__PURE__*/React__namespace.forwardRef(function Line({ dashed, ...rest }, ref) { - const [line2] = React__namespace.useState(() => new Line2()); - const [lineMaterial] = React__namespace.useState(() => new LineMaterial()); + const [line2] = React__namespace.useState(() => new threeStdlib.Line2()); + const [lineMaterial] = React__namespace.useState(() => new threeStdlib.LineMaterial()); const [resolution] = React__namespace.useState(() => new Vector2(512, 512)); const lineGeom = React__namespace.useMemo(() => { - const geom = new LineGeometry(); + const geom = new threeStdlib.LineGeometry(); const pValues = points.map(p => p instanceof Vector3 ? p.toArray() : p); geom.setPositions(pValues.flat()); @@ -155330,7 +83966,7 @@ const OrbitControls = /*#__PURE__*/React__namespace.forwardRef(({ const performance = useThree(state => state.performance); const explCamera = camera || defaultCamera; const explDomElement = domElement || events.connected || gl.domElement; - const controls = React__namespace.useMemo(() => new OrbitControls$1(explCamera), [explCamera]); + const controls = React__namespace.useMemo(() => new threeStdlib.OrbitControls(explCamera), [explCamera]); useFrame(() => { if (controls.enabled) controls.update(); }, -1); @@ -163149,7 +91785,7 @@ const subscribeWithSelectorImpl = (fn) => (set, get, api) => { }; const subscribeWithSelector = subscribeWithSelectorImpl; -function n(n){for(var r=arguments.length,t=Array(r>1?r-1:0),e=1;e3?r.i-4:r.i:Array.isArray(n)?1:s(n)?2:v(n)?3:0}function u(n,r){return 2===o(n)?n.has(r):Object.prototype.hasOwnProperty.call(n,r)}function a(n,r){return 2===o(n)?n.get(r):n[r]}function f(n,r,t){var e=o(n);2===e?n.set(r,t):3===e?(n.delete(r),n.add(t)):n[r]=t;}function c(n,r){return n===r?0!==n||1/n==1/r:n!=n&&r!=r}function s(n){return X&&n instanceof Map}function v(n){return q&&n instanceof Set}function p(n){return n.o||n.t}function l(n){if(Array.isArray(n))return Array.prototype.slice.call(n);var r=rn(n);delete r[Q];for(var t=nn(r),e=0;e1&&(n.set=n.add=n.clear=n.delete=h),Object.freeze(n),e&&i$1(n,(function(n,r){return d(r,!0)}),!0),n)}function h(){n(2);}function y(n){return null==n||"object"!=typeof n||Object.isFrozen(n)}function b(r){var t=tn[r];return t||n(18,r),t}function _(){return "production"===process.env.NODE_ENV||U||n(0),U}function j(n,r){r&&(b("Patches"),n.u=[],n.s=[],n.v=r);}function O(n){g(n),n.p.forEach(S),n.p=null;}function g(n){n===U&&(U=n.l);}function w(n){return U={p:[],l:U,h:n,m:!0,_:0}}function S(n){var r=n[Q];0===r.i||1===r.i?r.j():r.O=!0;}function P(r,e){e._=e.p.length;var i=e.p[0],o=void 0!==r&&r!==i;return e.h.g||b("ES5").S(e,r,o),o?(i[Q].P&&(O(e),n(4)),t(r)&&(r=M(e,r),e.l||x(e,r)),e.u&&b("Patches").M(i[Q].t,r,e.u,e.s)):r=M(e,i,[]),O(e),e.u&&e.v(e.u,e.s),r!==H?r:void 0}function M(n,r,t){if(y(r))return r;var e=r[Q];if(!e)return i$1(r,(function(i,o){return A(n,e,r,i,o,t)}),!0),r;if(e.A!==n)return r;if(!e.P)return x(n,e.t,!0),e.t;if(!e.I){e.I=!0,e.A._--;var o=4===e.i||5===e.i?e.o=l(e.k):e.o;i$1(3===e.i?new Set(o):o,(function(r,i){return A(n,e,o,r,i,t)})),x(n,o,!1),t&&n.u&&b("Patches").R(e,t,n.u,n.s);}return e.o}function A(e,i,o,a,c,s){if("production"!==process.env.NODE_ENV&&c===o&&n(5),r(c)){var v=M(e,c,s&&i&&3!==i.i&&!u(i.D,a)?s.concat(a):void 0);if(f(o,a,v),!r(v))return;e.m=!1;}if(t(c)&&!y(c)){if(!e.h.F&&e._<1)return;M(e,c),i&&i.A.l||x(e,c);}}function x(n,r,t){void 0===t&&(t=!1),n.h.F&&n.m&&d(r,t);}function z(n,r){var t=n[Q];return (t?p(t):n)[r]}function I(n,r){if(r in n)for(var t=Object.getPrototypeOf(n);t;){var e=Object.getOwnPropertyDescriptor(t,r);if(e)return e;t=Object.getPrototypeOf(t);}}function k(n){n.P||(n.P=!0,n.l&&k(n.l));}function E(n){n.o||(n.o=l(n.t));}function R(n,r,t){var e=s(r)?b("MapSet").N(r,t):v(r)?b("MapSet").T(r,t):n.g?function(n,r){var t=Array.isArray(n),e={i:t?1:0,A:r?r.A:_(),P:!1,I:!1,D:{},l:r,t:n,k:null,o:null,j:null,C:!1},i=e,o=en;t&&(i=[e],o=on);var u=Proxy.revocable(i,o),a=u.revoke,f=u.proxy;return e.k=f,e.j=a,f}(r,t):b("ES5").J(r,t);return (t?t.A:_()).p.push(e),e}function D(e){return r(e)||n(22,e),function n(r){if(!t(r))return r;var e,u=r[Q],c=o(r);if(u){if(!u.P&&(u.i<4||!b("ES5").K(u)))return u.t;u.I=!0,e=F(r,c),u.I=!1;}else e=F(r,c);return i$1(e,(function(r,t){u&&a(u.t,r)===t||f(e,r,n(t));})),3===c?new Set(e):e}(e)}function F(n,r){switch(r){case 2:return new Map(n);case 3:return Array.from(n)}return l(n)}var G,U,W="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),X="undefined"!=typeof Map,q="undefined"!=typeof Set,B="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,H=W?Symbol.for("immer-nothing"):((G={})["immer-nothing"]=!0,G),L=W?Symbol.for("immer-draftable"):"__$immer_draftable",Q=W?Symbol.for("immer-state"):"__$immer_state",Y={0:"Illegal state",1:"Immer drafts cannot have computed properties",2:"This object has been frozen and should not be mutated",3:function(n){return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+n},4:"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",5:"Immer forbids circular references",6:"The first or second argument to `produce` must be a function",7:"The third argument to `produce` must be a function or undefined",8:"First argument to `createDraft` must be a plain object, an array, or an immerable object",9:"First argument to `finishDraft` must be a draft returned by `createDraft`",10:"The given draft is already finalized",11:"Object.defineProperty() cannot be used on an Immer draft",12:"Object.setPrototypeOf() cannot be used on an Immer draft",13:"Immer only supports deleting array indices",14:"Immer only supports setting array indices and the 'length' property",15:function(n){return "Cannot apply patch, path doesn't resolve: "+n},16:'Sets cannot have "replace" patches.',17:function(n){return "Unsupported patch operation: "+n},18:function(n){return "The plugin for '"+n+"' has not been loaded into Immer. To enable the plugin, import and call `enable"+n+"()` when initializing your application."},20:"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",21:function(n){return "produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '"+n+"'"},22:function(n){return "'current' expects a draft, got: "+n},23:function(n){return "'original' expects a draft, got: "+n},24:"Patching reserved attributes like __proto__, prototype and constructor is not allowed"},Z=""+Object.prototype.constructor,nn="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n))}:Object.getOwnPropertyNames,rn=Object.getOwnPropertyDescriptors||function(n){var r={};return nn(n).forEach((function(t){r[t]=Object.getOwnPropertyDescriptor(n,t);})),r},tn={},en={get:function(n,r){if(r===Q)return n;var e=p(n);if(!u(e,r))return function(n,r,t){var e,i=I(r,t);return i?"value"in i?i.value:null===(e=i.get)||void 0===e?void 0:e.call(n.k):void 0}(n,e,r);var i=e[r];return n.I||!t(i)?i:i===z(n.t,r)?(E(n),n.o[r]=R(n.A.h,i,n)):i},has:function(n,r){return r in p(n)},ownKeys:function(n){return Reflect.ownKeys(p(n))},set:function(n,r,t){var e=I(p(n),r);if(null==e?void 0:e.set)return e.set.call(n.k,t),!0;if(!n.P){var i=z(p(n),r),o=null==i?void 0:i[Q];if(o&&o.t===t)return n.o[r]=t,n.D[r]=!1,!0;if(c(t,i)&&(void 0!==t||u(n.t,r)))return !0;E(n),k(n);}return n.o[r]===t&&"number"!=typeof t&&(void 0!==t||r in n.o)||(n.o[r]=t,n.D[r]=!0,!0)},deleteProperty:function(n,r){return void 0!==z(n.t,r)||r in n.t?(n.D[r]=!1,E(n),k(n)):delete n.D[r],n.o&&delete n.o[r],!0},getOwnPropertyDescriptor:function(n,r){var t=p(n),e=Reflect.getOwnPropertyDescriptor(t,r);return e?{writable:!0,configurable:1!==n.i||"length"!==r,enumerable:e.enumerable,value:t[r]}:e},defineProperty:function(){n(11);},getPrototypeOf:function(n){return Object.getPrototypeOf(n.t)},setPrototypeOf:function(){n(12);}},on={};i$1(en,(function(n,r){on[n]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)};})),on.deleteProperty=function(r,t){return "production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&n(13),on.set.call(this,r,t,void 0)},on.set=function(r,t,e){return "production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&n(14),en.set.call(this,r[0],t,e,r[0])};var un=function(){function e(r){var e=this;this.g=B,this.F=!0,this.produce=function(r,i,o){if("function"==typeof r&&"function"!=typeof i){var u=i;i=r;var a=e;return function(n){var r=this;void 0===n&&(n=u);for(var t=arguments.length,e=Array(t>1?t-1:0),o=1;o1?t-1:0),o=1;o=0;e--){var i=t[e];if(0===i.path.length&&"replace"===i.op){n=i.value;break}}e>-1&&(t=t.slice(e+1));var o=b("Patches").$;return r(n)?o(n,t):this.produce(n,(function(n){return o(n,t)}))},e}(),an=new un,fn=an.produce;an.produceWithPatches.bind(an);an.setAutoFreeze.bind(an);an.setUseProxies.bind(an);an.applyPatches.bind(an);an.createDraft.bind(an);an.finishDraft.bind(an);var produce = fn; +function n(n){for(var r=arguments.length,t=Array(r>1?r-1:0),e=1;e3?r.i-4:r.i:Array.isArray(n)?1:s(n)?2:v(n)?3:0}function u(n,r){return 2===o(n)?n.has(r):Object.prototype.hasOwnProperty.call(n,r)}function a(n,r){return 2===o(n)?n.get(r):n[r]}function f(n,r,t){var e=o(n);2===e?n.set(r,t):3===e?(n.delete(r),n.add(t)):n[r]=t;}function c(n,r){return n===r?0!==n||1/n==1/r:n!=n&&r!=r}function s(n){return X&&n instanceof Map}function v(n){return q&&n instanceof Set}function p(n){return n.o||n.t}function l(n){if(Array.isArray(n))return Array.prototype.slice.call(n);var r=rn(n);delete r[Q];for(var t=nn(r),e=0;e1&&(n.set=n.add=n.clear=n.delete=h),Object.freeze(n),e&&i(n,(function(n,r){return d(r,!0)}),!0),n)}function h(){n(2);}function y(n){return null==n||"object"!=typeof n||Object.isFrozen(n)}function b(r){var t=tn[r];return t||n(18,r),t}function _(){return "production"===process.env.NODE_ENV||U||n(0),U}function j(n,r){r&&(b("Patches"),n.u=[],n.s=[],n.v=r);}function O(n){g(n),n.p.forEach(S),n.p=null;}function g(n){n===U&&(U=n.l);}function w(n){return U={p:[],l:U,h:n,m:!0,_:0}}function S(n){var r=n[Q];0===r.i||1===r.i?r.j():r.O=!0;}function P(r,e){e._=e.p.length;var i=e.p[0],o=void 0!==r&&r!==i;return e.h.g||b("ES5").S(e,r,o),o?(i[Q].P&&(O(e),n(4)),t(r)&&(r=M(e,r),e.l||x(e,r)),e.u&&b("Patches").M(i[Q].t,r,e.u,e.s)):r=M(e,i,[]),O(e),e.u&&e.v(e.u,e.s),r!==H?r:void 0}function M(n,r,t){if(y(r))return r;var e=r[Q];if(!e)return i(r,(function(i,o){return A(n,e,r,i,o,t)}),!0),r;if(e.A!==n)return r;if(!e.P)return x(n,e.t,!0),e.t;if(!e.I){e.I=!0,e.A._--;var o=4===e.i||5===e.i?e.o=l(e.k):e.o;i(3===e.i?new Set(o):o,(function(r,i){return A(n,e,o,r,i,t)})),x(n,o,!1),t&&n.u&&b("Patches").R(e,t,n.u,n.s);}return e.o}function A(e,i,o,a,c,s){if("production"!==process.env.NODE_ENV&&c===o&&n(5),r(c)){var v=M(e,c,s&&i&&3!==i.i&&!u(i.D,a)?s.concat(a):void 0);if(f(o,a,v),!r(v))return;e.m=!1;}if(t(c)&&!y(c)){if(!e.h.F&&e._<1)return;M(e,c),i&&i.A.l||x(e,c);}}function x(n,r,t){void 0===t&&(t=!1),n.h.F&&n.m&&d(r,t);}function z(n,r){var t=n[Q];return (t?p(t):n)[r]}function I(n,r){if(r in n)for(var t=Object.getPrototypeOf(n);t;){var e=Object.getOwnPropertyDescriptor(t,r);if(e)return e;t=Object.getPrototypeOf(t);}}function k(n){n.P||(n.P=!0,n.l&&k(n.l));}function E(n){n.o||(n.o=l(n.t));}function R(n,r,t){var e=s(r)?b("MapSet").N(r,t):v(r)?b("MapSet").T(r,t):n.g?function(n,r){var t=Array.isArray(n),e={i:t?1:0,A:r?r.A:_(),P:!1,I:!1,D:{},l:r,t:n,k:null,o:null,j:null,C:!1},i=e,o=en;t&&(i=[e],o=on);var u=Proxy.revocable(i,o),a=u.revoke,f=u.proxy;return e.k=f,e.j=a,f}(r,t):b("ES5").J(r,t);return (t?t.A:_()).p.push(e),e}function D(e){return r(e)||n(22,e),function n(r){if(!t(r))return r;var e,u=r[Q],c=o(r);if(u){if(!u.P&&(u.i<4||!b("ES5").K(u)))return u.t;u.I=!0,e=F(r,c),u.I=!1;}else e=F(r,c);return i(e,(function(r,t){u&&a(u.t,r)===t||f(e,r,n(t));})),3===c?new Set(e):e}(e)}function F(n,r){switch(r){case 2:return new Map(n);case 3:return Array.from(n)}return l(n)}var G,U,W="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),X="undefined"!=typeof Map,q="undefined"!=typeof Set,B="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,H=W?Symbol.for("immer-nothing"):((G={})["immer-nothing"]=!0,G),L=W?Symbol.for("immer-draftable"):"__$immer_draftable",Q=W?Symbol.for("immer-state"):"__$immer_state",Y={0:"Illegal state",1:"Immer drafts cannot have computed properties",2:"This object has been frozen and should not be mutated",3:function(n){return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+n},4:"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",5:"Immer forbids circular references",6:"The first or second argument to `produce` must be a function",7:"The third argument to `produce` must be a function or undefined",8:"First argument to `createDraft` must be a plain object, an array, or an immerable object",9:"First argument to `finishDraft` must be a draft returned by `createDraft`",10:"The given draft is already finalized",11:"Object.defineProperty() cannot be used on an Immer draft",12:"Object.setPrototypeOf() cannot be used on an Immer draft",13:"Immer only supports deleting array indices",14:"Immer only supports setting array indices and the 'length' property",15:function(n){return "Cannot apply patch, path doesn't resolve: "+n},16:'Sets cannot have "replace" patches.',17:function(n){return "Unsupported patch operation: "+n},18:function(n){return "The plugin for '"+n+"' has not been loaded into Immer. To enable the plugin, import and call `enable"+n+"()` when initializing your application."},20:"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",21:function(n){return "produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '"+n+"'"},22:function(n){return "'current' expects a draft, got: "+n},23:function(n){return "'original' expects a draft, got: "+n},24:"Patching reserved attributes like __proto__, prototype and constructor is not allowed"},Z=""+Object.prototype.constructor,nn="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n))}:Object.getOwnPropertyNames,rn=Object.getOwnPropertyDescriptors||function(n){var r={};return nn(n).forEach((function(t){r[t]=Object.getOwnPropertyDescriptor(n,t);})),r},tn={},en={get:function(n,r){if(r===Q)return n;var e=p(n);if(!u(e,r))return function(n,r,t){var e,i=I(r,t);return i?"value"in i?i.value:null===(e=i.get)||void 0===e?void 0:e.call(n.k):void 0}(n,e,r);var i=e[r];return n.I||!t(i)?i:i===z(n.t,r)?(E(n),n.o[r]=R(n.A.h,i,n)):i},has:function(n,r){return r in p(n)},ownKeys:function(n){return Reflect.ownKeys(p(n))},set:function(n,r,t){var e=I(p(n),r);if(null==e?void 0:e.set)return e.set.call(n.k,t),!0;if(!n.P){var i=z(p(n),r),o=null==i?void 0:i[Q];if(o&&o.t===t)return n.o[r]=t,n.D[r]=!1,!0;if(c(t,i)&&(void 0!==t||u(n.t,r)))return !0;E(n),k(n);}return n.o[r]===t&&"number"!=typeof t&&(void 0!==t||r in n.o)||(n.o[r]=t,n.D[r]=!0,!0)},deleteProperty:function(n,r){return void 0!==z(n.t,r)||r in n.t?(n.D[r]=!1,E(n),k(n)):delete n.D[r],n.o&&delete n.o[r],!0},getOwnPropertyDescriptor:function(n,r){var t=p(n),e=Reflect.getOwnPropertyDescriptor(t,r);return e?{writable:!0,configurable:1!==n.i||"length"!==r,enumerable:e.enumerable,value:t[r]}:e},defineProperty:function(){n(11);},getPrototypeOf:function(n){return Object.getPrototypeOf(n.t)},setPrototypeOf:function(){n(12);}},on={};i(en,(function(n,r){on[n]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)};})),on.deleteProperty=function(r,t){return "production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&n(13),on.set.call(this,r,t,void 0)},on.set=function(r,t,e){return "production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&n(14),en.set.call(this,r[0],t,e,r[0])};var un=function(){function e(r){var e=this;this.g=B,this.F=!0,this.produce=function(r,i,o){if("function"==typeof r&&"function"!=typeof i){var u=i;i=r;var a=e;return function(n){var r=this;void 0===n&&(n=u);for(var t=arguments.length,e=Array(t>1?t-1:0),o=1;o1?t-1:0),o=1;o=0;e--){var i=t[e];if(0===i.path.length&&"replace"===i.op){n=i.value;break}}e>-1&&(t=t.slice(e+1));var o=b("Patches").$;return r(n)?o(n,t):this.produce(n,(function(n){return o(n,t)}))},e}(),an=new un,fn=an.produce;an.produceWithPatches.bind(an);an.setAutoFreeze.bind(an);an.setUseProxies.bind(an);an.applyPatches.bind(an);an.createDraft.bind(an);an.finishDraft.bind(an);var produce = fn; // Credit to Mugen87 while we wait for this to be added to three.js // https://github.com/Mugen87/three.js/blob/3a6d8139367e710a3d4fef274d530dda485f1110/examples/jsm/misc/Timer.js @@ -180785,6 +109421,8 @@ class TransformControls extends Object3D { } + this.isTransformControls = true; + this.visible = false; this.domElement = domElement; this.domElement.style.touchAction = 'none'; // disable touch scroll @@ -180939,7 +109577,15 @@ class TransformControls extends Object3D { this.camera.updateMatrixWorld(); this.camera.matrixWorld.decompose( this.cameraPosition, this.cameraQuaternion, this._cameraScale ); - this.eye.copy( this.cameraPosition ).sub( this.worldPosition ).normalize(); + if ( this.camera.isOrthographicCamera ) { + + this.camera.getWorldDirection( this.eye ); + + } else { + + this.eye.copy( this.cameraPosition ).sub( this.worldPosition ).normalize(); + + } super.updateMatrixWorld( this ); @@ -181377,8 +110023,6 @@ class TransformControls extends Object3D { } -TransformControls.prototype.isTransformControls = true; - // mouse / touch event handlers function getPointer( event ) { @@ -181502,6 +110146,8 @@ class TransformControlsGizmo extends Object3D { super(); + this.isTransformControlsGizmo = true; + this.type = 'TransformControlsGizmo'; // shared materials @@ -182192,8 +110838,6 @@ class TransformControlsGizmo extends Object3D { } -TransformControlsGizmo.prototype.isTransformControlsGizmo = true; - // class TransformControlsPlane extends Mesh { @@ -182205,6 +110849,8 @@ class TransformControlsPlane extends Mesh { new MeshBasicMaterial( { visible: false, wireframe: true, side: DoubleSide, transparent: true, opacity: 0.1, toneMapped: false } ) ); + this.isTransformControlsPlane = true; + this.type = 'TransformControlsPlane'; } @@ -182287,8 +110933,6 @@ class TransformControlsPlane extends Mesh { } -TransformControlsPlane.prototype.isTransformControlsPlane = true; - /* * Box Mesh */ @@ -182309,10 +110953,8 @@ var BOX_GEOM = function BOX_GEOM(params) { x = x === undefined ? boxGeomDefaultDim : x; y = y === undefined ? boxGeomDefaultDim : y; - z = z === undefined ? boxGeomDefaultDim : z; // RoundedBoxGeometry() - // return new RoundedBoxGeometry(x, y, z, 2, 0.05) - - return new BoxGeometry(x, y, z); + z = z === undefined ? boxGeomDefaultDim : z; + return new threeStdlib.RoundedBoxGeometry(x, y, z, 2, 0.05); }; /* * Sphere Mesh @@ -182368,7 +111010,7 @@ var ARROW_GEOM = function ARROW_GEOM(params) { ARROW_BASE_GEOM.applyMatrix4(m); m.setPosition(new Vector3(0, shaftLength + capLength * 0.5, 0)); ARROW_CAP_GEOM.applyMatrix4(m); - return mergeBufferGeometries([ARROW_CAP_GEOM, ARROW_BASE_GEOM]); + return BufferGeometryUtils.mergeBufferGeometries([ARROW_CAP_GEOM, ARROW_BASE_GEOM]); }; var CAPSULE_GEOM = function CAPSULE_GEOM(params) { var _ref5 = params === undefined ? {} : params, @@ -182388,7 +111030,7 @@ var CAPSULE_GEOM = function CAPSULE_GEOM(params) { lowerM.setPosition(0, -height / 2, 0); UPPER_SPHERE_GEOM.applyMatrix4(upperM); LOWER_SPHERE_GEOM.applyMatrix4(lowerM); - return mergeBufferGeometries([INNER_GEOM, UPPER_SPHERE_GEOM, LOWER_SPHERE_GEOM]); + return BufferGeometryUtils.mergeBufferGeometries([INNER_GEOM, UPPER_SPHERE_GEOM, LOWER_SPHERE_GEOM]); }; /* * Mesh Lookup Table @@ -185342,7 +113984,7 @@ const EffectComposer = /*#__PURE__*/React__default["default"].memo( /*#__PURE__* scene = scene || defaultScene; camera = camera || defaultCamera; const [composer, normalPass, downSamplingPass] = React.useMemo(() => { - const webGL2Available = isWebGL2Available(); // Initialize composer + const webGL2Available = threeStdlib.isWebGL2Available(); // Initialize composer const effectComposer = new EffectComposer$1(gl, { depthBuffer, @@ -185871,7 +114513,7 @@ var Hull = /*#__PURE__*/React.forwardRef(function (_ref, forwardedRef) { var frontRef = React.useRef(); var backRef = React.useRef(); var initialVertices = typeof vertices === 'function' ? vertices(0) : vertices; - var geometry = new ConvexGeometry(initialVertices.map(function (v) { + var geometry = new threeStdlib.ConvexGeometry(initialVertices.map(function (v) { return new Vector3(v.x, v.y, v.z); })); useFrame(React.useCallback(function () { @@ -185882,7 +114524,7 @@ var Hull = /*#__PURE__*/React.forwardRef(function (_ref, forwardedRef) { var currentVertices = typeof vertices === 'function' ? vertices(time) : vertices; if (currentVertices !== initialVertices) { - var newGeom = new ConvexGeometry(currentVertices.map(function (v) { + var newGeom = new threeStdlib.ConvexGeometry(currentVertices.map(function (v) { return new Vector3(v.x, v.y, v.z); })); frontRef.current.geometry = newGeom; diff --git a/docs/617.727c3ef4.iframe.bundle.js b/docs/819.e97b45b2.iframe.bundle.js similarity index 68% rename from docs/617.727c3ef4.iframe.bundle.js rename to docs/819.e97b45b2.iframe.bundle.js index 9fa1d0f..866f002 100644 --- a/docs/617.727c3ef4.iframe.bundle.js +++ b/docs/819.e97b45b2.iframe.bundle.js @@ -1,2 +1,2 @@ -/*! For license information please see 617.727c3ef4.iframe.bundle.js.LICENSE.txt */ -(self.webpackChunkrobot_scene=self.webpackChunkrobot_scene||[]).push([[617],{"./node_modules/@base2/pretty-print-object/dist/index.js":function(__unused_webpack_module,exports){"use strict";var __assign=this&&this.__assign||function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;idepth?ro.activeTargets.push(ot):ro.skippedTargets.push(ot))}))}))},process=function(){var event,depth=0;for(gatherActiveObservationsAtDepth(depth);resizeObservers.some((function(ro){return ro.activeTargets.length>0}));)depth=broadcastActiveObservations(),gatherActiveObservationsAtDepth(depth);return resizeObservers.some((function(ro){return ro.skippedTargets.length>0}))&&("function"==typeof ErrorEvent?event=new ErrorEvent("error",{message:msg}):((event=document.createEvent("Event")).initEvent("error",!1,!1),event.message=msg),window.dispatchEvent(event)),depth>0},callbacks=[],queueMicroTask=function(callback){if(!trigger){var toggle_1=0,el_1=document.createTextNode("");new MutationObserver((function(){return callbacks.splice(0).forEach((function(cb){return cb()}))})).observe(el_1,{characterData:!0}),trigger=function(){el_1.textContent=""+(toggle_1?toggle_1--:toggle_1++)}}callbacks.push(callback),trigger()},watching=0,observerConfig={attributes:!0,characterData:!0,childList:!0,subtree:!0},events=["resize","load","transitionend","animationend","animationstart","animationiteration","keyup","keydown","mouseup","mousedown","mouseover","mouseout","blur","focus"],time=function(timeout){return void 0===timeout&&(timeout=0),Date.now()+timeout},scheduled=!1,scheduler=new(function(){function Scheduler(){var _this=this;this.stopped=!0,this.listener=function(){return _this.schedule()}}return Scheduler.prototype.run=function(timeout){var _this=this;if(void 0===timeout&&(timeout=250),!scheduled){scheduled=!0;var cb,until=time(timeout);cb=function(){var elementsHaveResized=!1;try{elementsHaveResized=process()}finally{if(scheduled=!1,timeout=until-time(),!watching)return;elementsHaveResized?_this.run(1e3):timeout>0?_this.run(timeout):_this.start()}},queueMicroTask((function ResizeObserver(){requestAnimationFrame(cb)}))}},Scheduler.prototype.schedule=function(){this.stop(),this.run()},Scheduler.prototype.observe=function(){var _this=this,cb=function(){return _this.observer&&_this.observer.observe(document.body,observerConfig)};document.body?cb():global.addEventListener("DOMContentLoaded",cb)},Scheduler.prototype.start=function(){var _this=this;this.stopped&&(this.stopped=!1,this.observer=new MutationObserver(this.listener),this.observe(),events.forEach((function(name){return global.addEventListener(name,_this.listener,!0)})))},Scheduler.prototype.stop=function(){var _this=this;this.stopped||(this.observer&&this.observer.disconnect(),events.forEach((function(name){return global.removeEventListener(name,_this.listener,!0)})),this.stopped=!0)},Scheduler}()),updateCount=function(n){!watching&&n>0&&scheduler.start(),!(watching+=n)&&scheduler.stop()},ResizeObservation=function(){function ResizeObservation(target,observedBox){this.target=target,this.observedBox=observedBox||ResizeObserverBoxOptions.CONTENT_BOX,this.lastReportedSize={inlineSize:0,blockSize:0}}return ResizeObservation.prototype.isActive=function(){var target,size=calculateBoxSize(this.target,this.observedBox,!0);return target=this.target,isSVG(target)||function(target){switch(target.tagName){case"INPUT":if("image"!==target.type)break;case"VIDEO":case"AUDIO":case"EMBED":case"OBJECT":case"CANVAS":case"IFRAME":case"IMG":return!0}return!1}(target)||"inline"!==getComputedStyle(target).display||(this.lastReportedSize=size),this.lastReportedSize.inlineSize!==size.inlineSize||this.lastReportedSize.blockSize!==size.blockSize},ResizeObservation}(),ResizeObserverDetail=function ResizeObserverDetail(resizeObserver,callback){this.activeTargets=[],this.skippedTargets=[],this.observationTargets=[],this.observer=resizeObserver,this.callback=callback},observerMap=new WeakMap,getObservationIndex=function(observationTargets,target){for(var i=0;i=0&&(lastObservation&&resizeObservers.splice(resizeObservers.indexOf(detail),1),detail.observationTargets.splice(index,1),updateCount(-1))},ResizeObserverController.disconnect=function(resizeObserver){var _this=this,detail=observerMap.get(resizeObserver);detail.observationTargets.slice().forEach((function(ot){return _this.unobserve(resizeObserver,ot.target)})),detail.activeTargets.splice(0,detail.activeTargets.length)},ResizeObserverController}(),ResizeObserver=function(){function ResizeObserver(callback){if(0===arguments.length)throw new TypeError("Failed to construct 'ResizeObserver': 1 argument required, but only 0 present.");if("function"!=typeof callback)throw new TypeError("Failed to construct 'ResizeObserver': The callback provided as parameter 1 is not a function.");ResizeObserverController.connect(this,callback)}return ResizeObserver.prototype.observe=function(target,options){if(0===arguments.length)throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': 1 argument required, but only 0 present.");if(!isElement(target))throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element");ResizeObserverController.observe(this,target,options)},ResizeObserver.prototype.unobserve=function(target){if(0===arguments.length)throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': 1 argument required, but only 0 present.");if(!isElement(target))throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': parameter 1 is not of type 'Element");ResizeObserverController.unobserve(this,target)},ResizeObserver.prototype.disconnect=function(){ResizeObserverController.disconnect(this)},ResizeObserver.toString=function(){return"function ResizeObserver () { [polyfill code] }"},ResizeObserver}()},"./node_modules/@react-three/drei/core/Billboard.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{V:function(){return Billboard}});var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/extends.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_react_three_fiber__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./node_modules/@react-three/fiber/dist/index-4f1a8e2f.esm.js"),react_merge_refs__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/react-merge-refs/dist/react-merge-refs.esm.js");const Billboard=react__WEBPACK_IMPORTED_MODULE_0__.forwardRef((function Billboard({follow:follow=!0,lockX:lockX=!1,lockY:lockY=!1,lockZ:lockZ=!1,...props},ref){const localRef=react__WEBPACK_IMPORTED_MODULE_0__.useRef();return(0,_react_three_fiber__WEBPACK_IMPORTED_MODULE_1__.x)((({camera:camera})=>{if(!follow||!localRef.current)return;const prevRotation=localRef.current.rotation.clone();localRef.current.quaternion.copy(camera.quaternion),lockX&&(localRef.current.rotation.x=prevRotation.x),lockY&&(localRef.current.rotation.y=prevRotation.y),lockZ&&(localRef.current.rotation.z=prevRotation.z)})),react__WEBPACK_IMPORTED_MODULE_0__.createElement("group",(0,_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_2__.Z)({ref:(0,react_merge_refs__WEBPACK_IMPORTED_MODULE_3__.Z)([localRef,ref])},props))}))},"./node_modules/@react-three/drei/core/Line.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{x:function(){return Line}});var esm_extends=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/extends.js"),react=__webpack_require__("./node_modules/react/index.js"),three_module=__webpack_require__("./node_modules/three/build/three.module.js"),defineProperty=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/defineProperty.js");class LineSegmentsGeometry extends three_module.InstancedBufferGeometry{constructor(){super(),(0,defineProperty.Z)(this,"isLineSegmentsGeometry",!0),(0,defineProperty.Z)(this,"type","LineSegmentsGeometry"),(0,defineProperty.Z)(this,"boundingBox",null),(0,defineProperty.Z)(this,"boundingSphere",null),(0,defineProperty.Z)(this,"box",new three_module.Box3),(0,defineProperty.Z)(this,"vector",new three_module.Vector3);this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute("position",new three_module.Float32BufferAttribute([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute("uv",new three_module.Float32BufferAttribute([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(matrix){const start=this.attributes.instanceStart,end=this.attributes.instanceEnd;return void 0!==start&&(start.applyMatrix4(matrix),end.applyMatrix4(matrix),start.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}setPositions(array){let lineSegments;if(array instanceof Float32Array)lineSegments=array;else{if(!Array.isArray(array))return console.error("LineSegmentsGeometry.setPosition requires either a Float32Array or regular array of numbers"),this;lineSegments=new Float32Array(array)}const instanceBuffer=new three_module.InstancedInterleavedBuffer(lineSegments,6,1);return this.setAttribute("instanceStart",new three_module.InterleavedBufferAttribute(instanceBuffer,3,0)),this.setAttribute("instanceEnd",new three_module.InterleavedBufferAttribute(instanceBuffer,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(array){let colors;if(array instanceof Float32Array)colors=array;else{if(!Array.isArray(array))return console.error("LineSegmentsGeometry.setColors requires either a Float32Array or regular array of numbers"),this;colors=new Float32Array(array)}const instanceColorBuffer=new three_module.InstancedInterleavedBuffer(colors,6,1);return this.setAttribute("instanceColorStart",new three_module.InterleavedBufferAttribute(instanceColorBuffer,3,0)),this.setAttribute("instanceColorEnd",new three_module.InterleavedBufferAttribute(instanceColorBuffer,3,3)),this}fromWireframeGeometry(geometry){return this.setPositions(Array.from(geometry.attributes.position.array)),this}fromEdgesGeometry(geometry){return this.setPositions(Array.from(geometry.attributes.position.array)),this}fromMesh(mesh){return this.fromWireframeGeometry(new three_module.WireframeGeometry(mesh.geometry)),this}fromLineSegments(lineSegments){const geometry=lineSegments.geometry;return geometry.isBufferGeometry&&this.setPositions(Array.from(geometry.attributes.position.array)),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new three_module.Box3);const start=this.attributes.instanceStart,end=this.attributes.instanceEnd;void 0!==start&&void 0!==end&&(this.boundingBox.setFromBufferAttribute(start),this.box.setFromBufferAttribute(end),this.boundingBox.union(this.box))}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new three_module.Sphere),null===this.boundingBox&&this.computeBoundingBox();const start=this.attributes.instanceStart,end=this.attributes.instanceEnd;if(void 0!==start&&void 0!==end){const center=this.boundingSphere.center;this.boundingBox&&this.boundingBox.getCenter(center);let maxRadiusSq=0;for(let i=0,il=start.count;i\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\n\t\tuniform float linewidth;\n\t\tuniform vec2 resolution;\n\n\t\tattribute vec3 instanceStart;\n\t\tattribute vec3 instanceEnd;\n\n\t\tattribute vec3 instanceColorStart;\n\t\tattribute vec3 instanceColorEnd;\n\n\t\tvarying vec2 vUv;\n\n\t\t#ifdef USE_DASH\n\n\t\t\tuniform float dashScale;\n\t\t\tattribute float instanceDistanceStart;\n\t\t\tattribute float instanceDistanceEnd;\n\t\t\tvarying float vLineDistance;\n\n\t\t#endif\n\n\t\tvoid trimSegment( const in vec4 start, inout vec4 end ) {\n\n\t\t\t// trim end segment so it terminates between the camera plane and the near plane\n\n\t\t\t// conservative estimate of the near plane\n\t\t\tfloat a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column\n\t\t\tfloat b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column\n\t\t\tfloat nearEstimate = - 0.5 * b / a;\n\n\t\t\tfloat alpha = ( nearEstimate - start.z ) / ( end.z - start.z );\n\n\t\t\tend.xyz = mix( start.xyz, end.xyz, alpha );\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\t#ifdef USE_COLOR\n\n\t\t\t\tvColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;\n\n\t\t\t#endif\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;\n\n\t\t\t#endif\n\n\t\t\tfloat aspect = resolution.x / resolution.y;\n\n\t\t\tvUv = uv;\n\n\t\t\t// camera space\n\t\t\tvec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );\n\t\t\tvec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );\n\n\t\t\t// special case for perspective projection, and segments that terminate either in, or behind, the camera plane\n\t\t\t// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space\n\t\t\t// but we need to perform ndc-space calculations in the shader, so we must address this issue directly\n\t\t\t// perhaps there is a more elegant solution -- WestLangley\n\n\t\t\tbool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column\n\n\t\t\tif ( perspective ) {\n\n\t\t\t\tif ( start.z < 0.0 && end.z >= 0.0 ) {\n\n\t\t\t\t\ttrimSegment( start, end );\n\n\t\t\t\t} else if ( end.z < 0.0 && start.z >= 0.0 ) {\n\n\t\t\t\t\ttrimSegment( end, start );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// clip space\n\t\t\tvec4 clipStart = projectionMatrix * start;\n\t\t\tvec4 clipEnd = projectionMatrix * end;\n\n\t\t\t// ndc space\n\t\t\tvec2 ndcStart = clipStart.xy / clipStart.w;\n\t\t\tvec2 ndcEnd = clipEnd.xy / clipEnd.w;\n\n\t\t\t// direction\n\t\t\tvec2 dir = ndcEnd - ndcStart;\n\n\t\t\t// account for clip-space aspect ratio\n\t\t\tdir.x *= aspect;\n\t\t\tdir = normalize( dir );\n\n\t\t\t// perpendicular to dir\n\t\t\tvec2 offset = vec2( dir.y, - dir.x );\n\n\t\t\t// undo aspect ratio adjustment\n\t\t\tdir.x /= aspect;\n\t\t\toffset.x /= aspect;\n\n\t\t\t// sign flip\n\t\t\tif ( position.x < 0.0 ) offset *= - 1.0;\n\n\t\t\t// endcaps\n\t\t\tif ( position.y < 0.0 ) {\n\n\t\t\t\toffset += - dir;\n\n\t\t\t} else if ( position.y > 1.0 ) {\n\n\t\t\t\toffset += dir;\n\n\t\t\t}\n\n\t\t\t// adjust for linewidth\n\t\t\toffset *= linewidth;\n\n\t\t\t// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...\n\t\t\toffset /= resolution.y;\n\n\t\t\t// select end\n\t\t\tvec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;\n\n\t\t\t// back to clip space\n\t\t\toffset *= clip.w;\n\n\t\t\tclip.xy += offset;\n\n\t\t\tgl_Position = clip;\n\n\t\t\tvec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation\n\n\t\t\t#include \n\t\t\t#include \n\t\t\t#include \n\n\t\t}\n\t\t",fragmentShader:"\n\t\tuniform vec3 diffuse;\n\t\tuniform float opacity;\n\n\t\t#ifdef USE_DASH\n\n\t\t\tuniform float dashSize;\n\t\t\tuniform float dashOffset;\n\t\t\tuniform float gapSize;\n\n\t\t#endif\n\n\t\tvarying float vLineDistance;\n\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\t#include \n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tif ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps\n\n\t\t\t\tif ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX\n\n\t\t\t#endif\n\n\t\t\tfloat alpha = opacity;\n\n\t\t\t#ifdef ALPHA_TO_COVERAGE\n\n\t\t\t// artifacts appear on some hardware if a derivative is taken within a conditional\n\t\t\tfloat a = vUv.x;\n\t\t\tfloat b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;\n\t\t\tfloat len2 = a * a + b * b;\n\t\t\tfloat dlen = fwidth( len2 );\n\n\t\t\tif ( abs( vUv.y ) > 1.0 ) {\n\n\t\t\t\talpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );\n\n\t\t\t}\n\n\t\t\t#else\n\n\t\t\tif ( abs( vUv.y ) > 1.0 ) {\n\n\t\t\t\tfloat a = vUv.x;\n\t\t\t\tfloat b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;\n\t\t\t\tfloat len2 = a * a + b * b;\n\n\t\t\t\tif ( len2 > 1.0 ) discard;\n\n\t\t\t}\n\n\t\t\t#endif\n\n\t\t\tvec4 diffuseColor = vec4( diffuse, alpha );\n\n\t\t\t#include \n\t\t\t#include \n\n\t\t\tgl_FragColor = vec4( diffuseColor.rgb, alpha );\n\n\t\t\t#include \n\t\t\t#include \n\t\t\t#include \n\t\t\t#include \n\n\t\t}\n\t\t"};class LineMaterial extends three_module.ShaderMaterial{constructor(parameters={}){super({uniforms:three_module.UniformsUtils.clone(three_module.ShaderLib.line.uniforms),vertexShader:three_module.ShaderLib.line.vertexShader,fragmentShader:three_module.ShaderLib.line.fragmentShader,clipping:!0}),(0,defineProperty.Z)(this,"isLineMaterial",!0),(0,defineProperty.Z)(this,"dashed",!1),(0,defineProperty.Z)(this,"color",new three_module.Color(0)),(0,defineProperty.Z)(this,"lineWidth",0),(0,defineProperty.Z)(this,"dashScale",0),(0,defineProperty.Z)(this,"dashOffset",0),(0,defineProperty.Z)(this,"dashSize",0),(0,defineProperty.Z)(this,"opacity",0),(0,defineProperty.Z)(this,"resolution",new three_module.Vector2),(0,defineProperty.Z)(this,"alphaToCoverage",!1),Object.defineProperties(this,{color:{enumerable:!0,get:function(){return this.uniforms.diffuse.value},set:function(value){const colorObj=new three_module.Color(value);this.uniforms.diffuse.value=colorObj.getHex()}},linewidth:{enumerable:!0,get:function(){return this.uniforms.linewidth.value},set:function(value){this.uniforms.linewidth.value=value}},dashScale:{enumerable:!0,get:function(){return this.uniforms.dashScale.value},set:function(value){this.uniforms.dashScale.value=value}},dashSize:{enumerable:!0,get:function(){return this.uniforms.dashSize.value},set:function(value){this.uniforms.dashSize.value=value}},dashOffset:{enumerable:!0,get:function(){return this.uniforms.dashOffset.value},set:function(value){this.uniforms.dashOffset.value=value}},gapSize:{enumerable:!0,get:function(){return this.uniforms.gapSize.value},set:function(value){this.uniforms.gapSize.value=value}},opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(value){this.uniforms.opacity.value=value}},resolution:{enumerable:!0,get:function(){return this.uniforms.resolution.value},set:function(value){this.uniforms.resolution.value.copy(value)}},alphaToCoverage:{enumerable:!0,get:function(){return Boolean("ALPHA_TO_COVERAGE"in this.defines)},set:function(value){Boolean(value)!==Boolean("ALPHA_TO_COVERAGE"in this.defines)&&(this.needsUpdate=!0),value?(this.defines.ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.ALPHA_TO_COVERAGE,this.extensions.derivatives=!1)}},dashed:{enumerable:!0,get:function(){return Boolean("USE_DASH"in this.defines)},set:function(value){Boolean(value)!==Boolean("USE_DASH"in this.defines)&&(this.needsUpdate=!0),value?this.defines.USE_DASH="":delete this.defines.USE_DASH}}}),this.setValues(parameters)}}class LineSegments2 extends three_module.Mesh{constructor(_geometry=new LineSegmentsGeometry,_material=new LineMaterial({color:16777215*Math.random()})){super(_geometry,_material),(0,defineProperty.Z)(this,"type","LineSegments2"),(0,defineProperty.Z)(this,"isLineSegments2",!0),(0,defineProperty.Z)(this,"distStart",new three_module.Vector3),(0,defineProperty.Z)(this,"distEnd",new three_module.Vector3),(0,defineProperty.Z)(this,"computeLineDistances",(()=>{const geometry=this.geometry,instanceStart=geometry.attributes.instanceStart,instanceEnd=geometry.attributes.instanceEnd,lineDistances=new Float32Array(2*instanceStart.data.count);for(let i=0,j=0,l=instanceStart.data.count;i{null===raycaster.camera&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2.');const ray=raycaster.ray,camera=raycaster.camera,projectionMatrix=camera.projectionMatrix,geometry=this.geometry,material=this.material,resolution=material.resolution,lineWidth=material.linewidth+0,instanceStart=geometry.attributes.instanceStart,instanceEnd=geometry.attributes.instanceEnd,near=-camera.near;ray.at(1,this.ssOrigin),this.ssOrigin.w=1,this.ssOrigin.applyMatrix4(camera.matrixWorldInverse),this.ssOrigin.applyMatrix4(projectionMatrix),this.ssOrigin.multiplyScalar(1/this.ssOrigin.w),this.ssOrigin.x*=resolution.x/2,this.ssOrigin.y*=resolution.y/2,this.ssOrigin.z=0,this.ssOrigin3.set(this.ssOrigin.x,this.ssOrigin.y,this.ssOrigin.z);const matrixWorld=this.matrixWorld;this.mvMatrix.multiplyMatrices(camera.matrixWorldInverse,matrixWorld);for(let i=0,l=instanceStart.count;inear&&this.rayEnd.z>near)continue;if(this.rayStart.z>near){const deltaDist=this.rayStart.z-this.rayEnd.z,t=(this.rayStart.z-near)/deltaDist;this.rayStart.lerp(this.rayEnd,t)}else if(this.rayEnd.z>near){const deltaDist=this.rayEnd.z-this.rayStart.z,t=(this.rayEnd.z-near)/deltaDist;this.rayEnd.lerp(this.rayStart,t)}this.rayStart.applyMatrix4(projectionMatrix),this.rayEnd.applyMatrix4(projectionMatrix),this.rayStart.multiplyScalar(1/this.rayStart.w),this.rayEnd.multiplyScalar(1/this.rayEnd.w),this.rayStart.x*=resolution.x/2,this.rayStart.y*=resolution.y/2,this.rayEnd.x*=resolution.x/2,this.rayEnd.y*=resolution.y/2,this.line.start.set(this.rayStart.x,this.rayStart.y,this.rayStart.z),this.line.start.z=0,this.line.end.set(this.rayEnd.x,this.rayEnd.y,this.rayEnd.z),this.line.end.z=0;const param=this.line.closestPointToPointParameter(this.ssOrigin3,!0);this.line.at(param,this.closestPoint);const zPos=three_module.MathUtils.lerp(this.rayStart.z,this.rayEnd.z,param),isInClipSpace=zPos>=-1&&zPos<=1,isInside=this.ssOrigin3.distanceTo(this.closestPoint)<.5*lineWidth;if(isInClipSpace&&isInside){this.line.start.fromBufferAttribute(instanceStart,i),this.line.end.fromBufferAttribute(instanceEnd,i),this.line.start.applyMatrix4(matrixWorld),this.line.end.applyMatrix4(matrixWorld);const pointOnLine=new three_module.Vector3,point=new three_module.Vector3;ray.distanceSqToSegment(this.line.start,this.line.end,point,pointOnLine),intersects.push({distance:ray.origin.distanceTo(point),point:point,face:null,faceIndex:i,object:this,uv:void 0,pointOnLine:pointOnLine})}}}))}}class LineGeometry extends LineSegmentsGeometry{constructor(){super(),(0,defineProperty.Z)(this,"type","LineGeometry"),(0,defineProperty.Z)(this,"isLineGeometry",!0),(0,defineProperty.Z)(this,"setColors",(array=>{const length=array.length-3,colors=new Float32Array(2*length);for(let i=0;i{const geometry=line.geometry;return geometry.isBufferGeometry&&this.setPositions(Array.from(geometry.attributes.position.array)),this})),(0,defineProperty.Z)(this,"copy",(()=>this))}setPositions(array){const length=array.length-3,points=new Float32Array(2*length);for(let i=0;inew Line2)),[lineMaterial]=react.useState((()=>new LineMaterial)),[resolution]=react.useState((()=>new three_module.Vector2(512,512))),lineGeom=react.useMemo((()=>{const geom=new LineGeometry,pValues=points.map((p=>p instanceof three_module.Vector3?p.toArray():p));if(geom.setPositions(pValues.flat()),vertexColors){const cValues=vertexColors.map((c=>c instanceof three_module.Color?c.toArray():c));geom.setColors(cValues.flat())}return geom}),[points,vertexColors]);return react.useLayoutEffect((()=>{line2.computeLineDistances()}),[points,line2]),react.useLayoutEffect((()=>{dashed?lineMaterial.defines.USE_DASH="":delete lineMaterial.defines.USE_DASH,lineMaterial.needsUpdate=!0}),[dashed,lineMaterial]),react.useEffect((()=>()=>lineGeom.dispose()),[lineGeom]),react.createElement("primitive",(0,esm_extends.Z)({object:line2,ref:ref},rest),react.createElement("primitive",{object:lineGeom,attach:"geometry"}),react.createElement("primitive",(0,esm_extends.Z)({object:lineMaterial,attach:"material",color:color,vertexColors:Boolean(vertexColors),resolution:resolution,linewidth:lineWidth,dashed:dashed},rest)))}))},"./node_modules/@react-three/drei/core/OrbitControls.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{z:function(){return OrbitControls_OrbitControls}});var esm_extends=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/extends.js"),index_4f1a8e2f_esm=__webpack_require__("./node_modules/@react-three/fiber/dist/index-4f1a8e2f.esm.js"),react=__webpack_require__("./node_modules/react/index.js"),defineProperty=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),three_module=__webpack_require__("./node_modules/three/build/three.module.js");const moduloWrapAround=(offset,capacity)=>(offset%capacity+capacity)%capacity;class OrbitControls extends three_module.EventDispatcher{constructor(object,domElement){super(),(0,defineProperty.Z)(this,"object",void 0),(0,defineProperty.Z)(this,"domElement",void 0),(0,defineProperty.Z)(this,"enabled",!0),(0,defineProperty.Z)(this,"target",new three_module.Vector3),(0,defineProperty.Z)(this,"minDistance",0),(0,defineProperty.Z)(this,"maxDistance",1/0),(0,defineProperty.Z)(this,"minZoom",0),(0,defineProperty.Z)(this,"maxZoom",1/0),(0,defineProperty.Z)(this,"minPolarAngle",0),(0,defineProperty.Z)(this,"maxPolarAngle",Math.PI),(0,defineProperty.Z)(this,"minAzimuthAngle",-1/0),(0,defineProperty.Z)(this,"maxAzimuthAngle",1/0),(0,defineProperty.Z)(this,"enableDamping",!1),(0,defineProperty.Z)(this,"dampingFactor",.05),(0,defineProperty.Z)(this,"enableZoom",!0),(0,defineProperty.Z)(this,"zoomSpeed",1),(0,defineProperty.Z)(this,"enableRotate",!0),(0,defineProperty.Z)(this,"rotateSpeed",1),(0,defineProperty.Z)(this,"enablePan",!0),(0,defineProperty.Z)(this,"panSpeed",1),(0,defineProperty.Z)(this,"screenSpacePanning",!0),(0,defineProperty.Z)(this,"keyPanSpeed",7),(0,defineProperty.Z)(this,"autoRotate",!1),(0,defineProperty.Z)(this,"autoRotateSpeed",2),(0,defineProperty.Z)(this,"reverseOrbit",!1),(0,defineProperty.Z)(this,"keys",{LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"}),(0,defineProperty.Z)(this,"mouseButtons",{LEFT:three_module.MOUSE.ROTATE,MIDDLE:three_module.MOUSE.DOLLY,RIGHT:three_module.MOUSE.PAN}),(0,defineProperty.Z)(this,"touches",{ONE:three_module.TOUCH.ROTATE,TWO:three_module.TOUCH.DOLLY_PAN}),(0,defineProperty.Z)(this,"target0",void 0),(0,defineProperty.Z)(this,"position0",void 0),(0,defineProperty.Z)(this,"zoom0",void 0),(0,defineProperty.Z)(this,"_domElementKeyEvents",null),(0,defineProperty.Z)(this,"getPolarAngle",void 0),(0,defineProperty.Z)(this,"getAzimuthalAngle",void 0),(0,defineProperty.Z)(this,"setPolarAngle",void 0),(0,defineProperty.Z)(this,"setAzimuthalAngle",void 0),(0,defineProperty.Z)(this,"getDistance",void 0),(0,defineProperty.Z)(this,"listenToKeyEvents",void 0),(0,defineProperty.Z)(this,"saveState",void 0),(0,defineProperty.Z)(this,"reset",void 0),(0,defineProperty.Z)(this,"update",void 0),(0,defineProperty.Z)(this,"connect",void 0),(0,defineProperty.Z)(this,"dispose",void 0),this.object=object,this.domElement=domElement,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object instanceof three_module.PerspectiveCamera?this.object.zoom:1,this.getPolarAngle=()=>spherical.phi,this.getAzimuthalAngle=()=>spherical.theta,this.setPolarAngle=value=>{let phi=moduloWrapAround(value,2*Math.PI),currentPhi=spherical.phi;currentPhi<0&&(currentPhi+=2*Math.PI),phi<0&&(phi+=2*Math.PI);let phiDist=Math.abs(phi-currentPhi);2*Math.PI-phiDist{let theta=moduloWrapAround(value,2*Math.PI),currentTheta=spherical.theta;currentTheta<0&&(currentTheta+=2*Math.PI),theta<0&&(theta+=2*Math.PI);let thetaDist=Math.abs(theta-currentTheta);2*Math.PI-thetaDistscope.object.position.distanceTo(scope.target),this.listenToKeyEvents=domElement=>{domElement.addEventListener("keydown",onKeyDown),this._domElementKeyEvents=domElement},this.saveState=()=>{scope.target0.copy(scope.target),scope.position0.copy(scope.object.position),scope.zoom0=scope.object instanceof three_module.PerspectiveCamera?scope.object.zoom:1},this.reset=()=>{scope.target.copy(scope.target0),scope.object.position.copy(scope.position0),scope.object instanceof three_module.PerspectiveCamera&&(scope.object.zoom=scope.zoom0,scope.object.updateProjectionMatrix()),scope.dispatchEvent(changeEvent),scope.update(),state=STATE.NONE},this.update=(()=>{const offset=new three_module.Vector3,quat=(new three_module.Quaternion).setFromUnitVectors(object.up,new three_module.Vector3(0,1,0)),quatInverse=quat.clone().invert(),lastPosition=new three_module.Vector3,lastQuaternion=new three_module.Quaternion,twoPI=2*Math.PI;return function update(){const position=scope.object.position;offset.copy(position).sub(scope.target),offset.applyQuaternion(quat),spherical.setFromVector3(offset),scope.autoRotate&&state===STATE.NONE&&rotateLeft(function getAutoRotationAngle(){return 2*Math.PI/60/60*scope.autoRotateSpeed}()),scope.enableDamping?(spherical.theta+=sphericalDelta.theta*scope.dampingFactor,spherical.phi+=sphericalDelta.phi*scope.dampingFactor):(spherical.theta+=sphericalDelta.theta,spherical.phi+=sphericalDelta.phi);let min=scope.minAzimuthAngle,max=scope.maxAzimuthAngle;return isFinite(min)&&isFinite(max)&&(min<-Math.PI?min+=twoPI:min>Math.PI&&(min-=twoPI),max<-Math.PI?max+=twoPI:max>Math.PI&&(max-=twoPI),spherical.theta=min<=max?Math.max(min,Math.min(max,spherical.theta)):spherical.theta>(min+max)/2?Math.max(min,spherical.theta):Math.min(max,spherical.theta)),spherical.phi=Math.max(scope.minPolarAngle,Math.min(scope.maxPolarAngle,spherical.phi)),spherical.makeSafe(),spherical.radius*=scale,spherical.radius=Math.max(scope.minDistance,Math.min(scope.maxDistance,spherical.radius)),!0===scope.enableDamping?scope.target.addScaledVector(panOffset,scope.dampingFactor):scope.target.add(panOffset),offset.setFromSpherical(spherical),offset.applyQuaternion(quatInverse),position.copy(scope.target).add(offset),scope.object.lookAt(scope.target),!0===scope.enableDamping?(sphericalDelta.theta*=1-scope.dampingFactor,sphericalDelta.phi*=1-scope.dampingFactor,panOffset.multiplyScalar(1-scope.dampingFactor)):(sphericalDelta.set(0,0,0),panOffset.set(0,0,0)),scale=1,!!(zoomChanged||lastPosition.distanceToSquared(scope.object.position)>EPS||8*(1-lastQuaternion.dot(scope.object.quaternion))>EPS)&&(scope.dispatchEvent(changeEvent),lastPosition.copy(scope.object.position),lastQuaternion.copy(scope.object.quaternion),zoomChanged=!1,!0)}})(),this.connect=domElement=>{domElement===document&&console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'),scope.domElement=domElement,scope.domElement.style.touchAction="none",scope.domElement.addEventListener("contextmenu",onContextMenu),scope.domElement.addEventListener("pointerdown",onPointerDown),scope.domElement.addEventListener("pointercancel",onPointerCancel),scope.domElement.addEventListener("wheel",onMouseWheel)},this.dispose=()=>{var _scope$domElement,_scope$domElement2,_scope$domElement3,_scope$domElement4,_scope$domElement5,_scope$domElement6;null===(_scope$domElement=scope.domElement)||void 0===_scope$domElement||_scope$domElement.removeEventListener("contextmenu",onContextMenu),null===(_scope$domElement2=scope.domElement)||void 0===_scope$domElement2||_scope$domElement2.removeEventListener("pointerdown",onPointerDown),null===(_scope$domElement3=scope.domElement)||void 0===_scope$domElement3||_scope$domElement3.removeEventListener("pointercancel",onPointerCancel),null===(_scope$domElement4=scope.domElement)||void 0===_scope$domElement4||_scope$domElement4.removeEventListener("wheel",onMouseWheel),null===(_scope$domElement5=scope.domElement)||void 0===_scope$domElement5||_scope$domElement5.ownerDocument.removeEventListener("pointermove",onPointerMove),null===(_scope$domElement6=scope.domElement)||void 0===_scope$domElement6||_scope$domElement6.ownerDocument.removeEventListener("pointerup",onPointerUp),null!==scope._domElementKeyEvents&&scope._domElementKeyEvents.removeEventListener("keydown",onKeyDown)};const scope=this,changeEvent={type:"change"},startEvent={type:"start"},endEvent={type:"end"},STATE={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let state=STATE.NONE;const EPS=1e-6,spherical=new three_module.Spherical,sphericalDelta=new three_module.Spherical;let scale=1;const panOffset=new three_module.Vector3;let zoomChanged=!1;const rotateStart=new three_module.Vector2,rotateEnd=new three_module.Vector2,rotateDelta=new three_module.Vector2,panStart=new three_module.Vector2,panEnd=new three_module.Vector2,panDelta=new three_module.Vector2,dollyStart=new three_module.Vector2,dollyEnd=new three_module.Vector2,dollyDelta=new three_module.Vector2,pointers=[],pointerPositions={};function getZoomScale(){return Math.pow(.95,scope.zoomSpeed)}function rotateLeft(angle){scope.reverseOrbit?sphericalDelta.theta+=angle:sphericalDelta.theta-=angle}function rotateUp(angle){scope.reverseOrbit?sphericalDelta.phi+=angle:sphericalDelta.phi-=angle}const panLeft=(()=>{const v=new three_module.Vector3;return function panLeft(distance,objectMatrix){v.setFromMatrixColumn(objectMatrix,0),v.multiplyScalar(-distance),panOffset.add(v)}})(),panUp=(()=>{const v=new three_module.Vector3;return function panUp(distance,objectMatrix){!0===scope.screenSpacePanning?v.setFromMatrixColumn(objectMatrix,1):(v.setFromMatrixColumn(objectMatrix,0),v.crossVectors(scope.object.up,v)),v.multiplyScalar(distance),panOffset.add(v)}})(),pan=(()=>{const offset=new three_module.Vector3;return function pan(deltaX,deltaY){const element=scope.domElement;if(element&&scope.object instanceof three_module.PerspectiveCamera&&scope.object.isPerspectiveCamera){const position=scope.object.position;offset.copy(position).sub(scope.target);let targetDistance=offset.length();targetDistance*=Math.tan(scope.object.fov/2*Math.PI/180),panLeft(2*deltaX*targetDistance/element.clientHeight,scope.object.matrix),panUp(2*deltaY*targetDistance/element.clientHeight,scope.object.matrix)}else element&&scope.object instanceof three_module.OrthographicCamera&&scope.object.isOrthographicCamera?(panLeft(deltaX*(scope.object.right-scope.object.left)/scope.object.zoom/element.clientWidth,scope.object.matrix),panUp(deltaY*(scope.object.top-scope.object.bottom)/scope.object.zoom/element.clientHeight,scope.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),scope.enablePan=!1)}})();function dollyOut(dollyScale){scope.object instanceof three_module.PerspectiveCamera&&scope.object.isPerspectiveCamera?scale/=dollyScale:scope.object instanceof three_module.OrthographicCamera&&scope.object.isOrthographicCamera?(scope.object.zoom=Math.max(scope.minZoom,Math.min(scope.maxZoom,scope.object.zoom*dollyScale)),scope.object.updateProjectionMatrix(),zoomChanged=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),scope.enableZoom=!1)}function dollyIn(dollyScale){scope.object instanceof three_module.PerspectiveCamera&&scope.object.isPerspectiveCamera?scale*=dollyScale:scope.object instanceof three_module.OrthographicCamera&&scope.object.isOrthographicCamera?(scope.object.zoom=Math.max(scope.minZoom,Math.min(scope.maxZoom,scope.object.zoom/dollyScale)),scope.object.updateProjectionMatrix(),zoomChanged=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),scope.enableZoom=!1)}function handleMouseDownRotate(event){rotateStart.set(event.clientX,event.clientY)}function handleMouseDownPan(event){panStart.set(event.clientX,event.clientY)}function handleTouchStartRotate(){if(1==pointers.length)rotateStart.set(pointers[0].pageX,pointers[0].pageY);else{const x=.5*(pointers[0].pageX+pointers[1].pageX),y=.5*(pointers[0].pageY+pointers[1].pageY);rotateStart.set(x,y)}}function handleTouchStartPan(){if(1==pointers.length)panStart.set(pointers[0].pageX,pointers[0].pageY);else{const x=.5*(pointers[0].pageX+pointers[1].pageX),y=.5*(pointers[0].pageY+pointers[1].pageY);panStart.set(x,y)}}function handleTouchStartDolly(){const dx=pointers[0].pageX-pointers[1].pageX,dy=pointers[0].pageY-pointers[1].pageY,distance=Math.sqrt(dx*dx+dy*dy);dollyStart.set(0,distance)}function handleTouchMoveRotate(event){if(1==pointers.length)rotateEnd.set(event.pageX,event.pageY);else{const position=getSecondPointerPosition(event),x=.5*(event.pageX+position.x),y=.5*(event.pageY+position.y);rotateEnd.set(x,y)}rotateDelta.subVectors(rotateEnd,rotateStart).multiplyScalar(scope.rotateSpeed);const element=scope.domElement;element&&(rotateLeft(2*Math.PI*rotateDelta.x/element.clientHeight),rotateUp(2*Math.PI*rotateDelta.y/element.clientHeight)),rotateStart.copy(rotateEnd)}function handleTouchMovePan(event){if(1==pointers.length)panEnd.set(event.pageX,event.pageY);else{const position=getSecondPointerPosition(event),x=.5*(event.pageX+position.x),y=.5*(event.pageY+position.y);panEnd.set(x,y)}panDelta.subVectors(panEnd,panStart).multiplyScalar(scope.panSpeed),pan(panDelta.x,panDelta.y),panStart.copy(panEnd)}function handleTouchMoveDolly(event){const position=getSecondPointerPosition(event),dx=event.pageX-position.x,dy=event.pageY-position.y,distance=Math.sqrt(dx*dx+dy*dy);dollyEnd.set(0,distance),dollyDelta.set(0,Math.pow(dollyEnd.y/dollyStart.y,scope.zoomSpeed)),dollyOut(dollyDelta.y),dollyStart.copy(dollyEnd)}function onPointerDown(event){if(!1!==scope.enabled){var _scope$domElement7,_scope$domElement8;if(0===pointers.length)null===(_scope$domElement7=scope.domElement)||void 0===_scope$domElement7||_scope$domElement7.ownerDocument.addEventListener("pointermove",onPointerMove),null===(_scope$domElement8=scope.domElement)||void 0===_scope$domElement8||_scope$domElement8.ownerDocument.addEventListener("pointerup",onPointerUp);!function addPointer(event){pointers.push(event)}(event),"touch"===event.pointerType?function onTouchStart(event){switch(trackPointer(event),pointers.length){case 1:switch(scope.touches.ONE){case three_module.TOUCH.ROTATE:if(!1===scope.enableRotate)return;handleTouchStartRotate(),state=STATE.TOUCH_ROTATE;break;case three_module.TOUCH.PAN:if(!1===scope.enablePan)return;handleTouchStartPan(),state=STATE.TOUCH_PAN;break;default:state=STATE.NONE}break;case 2:switch(scope.touches.TWO){case three_module.TOUCH.DOLLY_PAN:if(!1===scope.enableZoom&&!1===scope.enablePan)return;!function handleTouchStartDollyPan(){scope.enableZoom&&handleTouchStartDolly(),scope.enablePan&&handleTouchStartPan()}(),state=STATE.TOUCH_DOLLY_PAN;break;case three_module.TOUCH.DOLLY_ROTATE:if(!1===scope.enableZoom&&!1===scope.enableRotate)return;!function handleTouchStartDollyRotate(){scope.enableZoom&&handleTouchStartDolly(),scope.enableRotate&&handleTouchStartRotate()}(),state=STATE.TOUCH_DOLLY_ROTATE;break;default:state=STATE.NONE}break;default:state=STATE.NONE}state!==STATE.NONE&&scope.dispatchEvent(startEvent)}(event):function onMouseDown(event){let mouseAction;switch(event.button){case 0:mouseAction=scope.mouseButtons.LEFT;break;case 1:mouseAction=scope.mouseButtons.MIDDLE;break;case 2:mouseAction=scope.mouseButtons.RIGHT;break;default:mouseAction=-1}switch(mouseAction){case three_module.MOUSE.DOLLY:if(!1===scope.enableZoom)return;!function handleMouseDownDolly(event){dollyStart.set(event.clientX,event.clientY)}(event),state=STATE.DOLLY;break;case three_module.MOUSE.ROTATE:if(event.ctrlKey||event.metaKey||event.shiftKey){if(!1===scope.enablePan)return;handleMouseDownPan(event),state=STATE.PAN}else{if(!1===scope.enableRotate)return;handleMouseDownRotate(event),state=STATE.ROTATE}break;case three_module.MOUSE.PAN:if(event.ctrlKey||event.metaKey||event.shiftKey){if(!1===scope.enableRotate)return;handleMouseDownRotate(event),state=STATE.ROTATE}else{if(!1===scope.enablePan)return;handleMouseDownPan(event),state=STATE.PAN}break;default:state=STATE.NONE}state!==STATE.NONE&&scope.dispatchEvent(startEvent)}(event)}}function onPointerMove(event){!1!==scope.enabled&&("touch"===event.pointerType?function onTouchMove(event){switch(trackPointer(event),state){case STATE.TOUCH_ROTATE:if(!1===scope.enableRotate)return;handleTouchMoveRotate(event),scope.update();break;case STATE.TOUCH_PAN:if(!1===scope.enablePan)return;handleTouchMovePan(event),scope.update();break;case STATE.TOUCH_DOLLY_PAN:if(!1===scope.enableZoom&&!1===scope.enablePan)return;!function handleTouchMoveDollyPan(event){scope.enableZoom&&handleTouchMoveDolly(event),scope.enablePan&&handleTouchMovePan(event)}(event),scope.update();break;case STATE.TOUCH_DOLLY_ROTATE:if(!1===scope.enableZoom&&!1===scope.enableRotate)return;!function handleTouchMoveDollyRotate(event){scope.enableZoom&&handleTouchMoveDolly(event),scope.enableRotate&&handleTouchMoveRotate(event)}(event),scope.update();break;default:state=STATE.NONE}}(event):function onMouseMove(event){if(!1===scope.enabled)return;switch(state){case STATE.ROTATE:if(!1===scope.enableRotate)return;!function handleMouseMoveRotate(event){rotateEnd.set(event.clientX,event.clientY),rotateDelta.subVectors(rotateEnd,rotateStart).multiplyScalar(scope.rotateSpeed);const element=scope.domElement;element&&(rotateLeft(2*Math.PI*rotateDelta.x/element.clientHeight),rotateUp(2*Math.PI*rotateDelta.y/element.clientHeight)),rotateStart.copy(rotateEnd),scope.update()}(event);break;case STATE.DOLLY:if(!1===scope.enableZoom)return;!function handleMouseMoveDolly(event){dollyEnd.set(event.clientX,event.clientY),dollyDelta.subVectors(dollyEnd,dollyStart),dollyDelta.y>0?dollyOut(getZoomScale()):dollyDelta.y<0&&dollyIn(getZoomScale()),dollyStart.copy(dollyEnd),scope.update()}(event);break;case STATE.PAN:if(!1===scope.enablePan)return;!function handleMouseMovePan(event){panEnd.set(event.clientX,event.clientY),panDelta.subVectors(panEnd,panStart).multiplyScalar(scope.panSpeed),pan(panDelta.x,panDelta.y),panStart.copy(panEnd),scope.update()}(event)}}(event))}function onPointerUp(event){var _scope$domElement9,_scope$domElement10,_scope$domElement11;(removePointer(event),0===pointers.length)&&(null===(_scope$domElement9=scope.domElement)||void 0===_scope$domElement9||_scope$domElement9.releasePointerCapture(event.pointerId),null===(_scope$domElement10=scope.domElement)||void 0===_scope$domElement10||_scope$domElement10.ownerDocument.removeEventListener("pointermove",onPointerMove),null===(_scope$domElement11=scope.domElement)||void 0===_scope$domElement11||_scope$domElement11.ownerDocument.removeEventListener("pointerup",onPointerUp));scope.dispatchEvent(endEvent),state=STATE.NONE}function onPointerCancel(event){removePointer(event)}function onMouseWheel(event){!1===scope.enabled||!1===scope.enableZoom||state!==STATE.NONE&&state!==STATE.ROTATE||(event.preventDefault(),scope.dispatchEvent(startEvent),function handleMouseWheel(event){event.deltaY<0?dollyIn(getZoomScale()):event.deltaY>0&&dollyOut(getZoomScale()),scope.update()}(event),scope.dispatchEvent(endEvent))}function onKeyDown(event){!1!==scope.enabled&&!1!==scope.enablePan&&function handleKeyDown(event){let needsUpdate=!1;switch(event.code){case scope.keys.UP:pan(0,scope.keyPanSpeed),needsUpdate=!0;break;case scope.keys.BOTTOM:pan(0,-scope.keyPanSpeed),needsUpdate=!0;break;case scope.keys.LEFT:pan(scope.keyPanSpeed,0),needsUpdate=!0;break;case scope.keys.RIGHT:pan(-scope.keyPanSpeed,0),needsUpdate=!0}needsUpdate&&(event.preventDefault(),scope.update())}(event)}function onContextMenu(event){!1!==scope.enabled&&event.preventDefault()}function removePointer(event){delete pointerPositions[event.pointerId];for(let i=0;i{const invalidate=(0,index_4f1a8e2f_esm.w)((state=>state.invalidate)),defaultCamera=(0,index_4f1a8e2f_esm.w)((state=>state.camera)),gl=(0,index_4f1a8e2f_esm.w)((state=>state.gl)),events=(0,index_4f1a8e2f_esm.w)((state=>state.events)),set=(0,index_4f1a8e2f_esm.w)((state=>state.set)),get=(0,index_4f1a8e2f_esm.w)((state=>state.get)),performance=(0,index_4f1a8e2f_esm.w)((state=>state.performance)),explCamera=camera||defaultCamera,explDomElement=domElement||events.connected||gl.domElement,controls=react.useMemo((()=>new OrbitControls(explCamera)),[explCamera]);return(0,index_4f1a8e2f_esm.x)((()=>{controls.enabled&&controls.update()}),-1),react.useEffect((()=>(controls.connect(explDomElement),()=>{controls.dispose()})),[explDomElement,regress,controls,invalidate]),react.useEffect((()=>{const callback=e=>{invalidate(),regress&&performance.regress(),onChange&&onChange(e)};return controls.addEventListener("change",callback),onStart&&controls.addEventListener("start",onStart),onEnd&&controls.addEventListener("end",onEnd),()=>{onStart&&controls.removeEventListener("start",onStart),onEnd&&controls.removeEventListener("end",onEnd),controls.removeEventListener("change",callback)}}),[onChange,onStart,onEnd,controls,invalidate]),react.useEffect((()=>{if(makeDefault){const old=get().controls;return set({controls:controls}),()=>set({controls:old})}}),[makeDefault,controls]),react.createElement("primitive",(0,esm_extends.Z)({ref:ref,object:controls,enableDamping:enableDamping},restProps))}))},"./node_modules/@react-three/drei/core/Text.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{x:function(){return Text_Text}});var esm_extends=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/extends.js"),react=__webpack_require__("./node_modules/react/index.js"),three_module=__webpack_require__("./node_modules/three/build/three.module.js");__webpack_require__("./node_modules/process/browser.js");function BespokeThenable(){var value,state=0,queue=[],scheduled=0,completeCalled=0;var resolve=oneTime((function(val){completeCalled||complete(1,val)})),reject=oneTime((function(reason){completeCalled||complete(-1,reason)}));function complete(st,val){completeCalled++;var ignoreThrow=0;try{val===thenableObj&&recursiveError();var valThen=st>0&&getThenableThen(val);valThen?valThen.call(val,oneTime((function(v){ignoreThrow++,complete(1,v)})),oneTime((function(v){ignoreThrow++,complete(-1,v)}))):(state=st,value=val,scheduleQueueFlush())}catch(e){state||ignoreThrow||complete(-1,e)}}function scheduleQueueFlush(){scheduled||(setTimeout(flushQueue,0),scheduled=1)}function flushQueue(){var q=queue;scheduled=0,queue=[],q.forEach(callIt)}function callIt(fn){fn()}function getThenableThen(val){var valThen=val&&(isFn(val)||"object"==typeof val)&&val.then;return isFn(valThen)&&valThen}function oneTime(fn){var called=0;return function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];called++||fn.apply(this,args)}}function recursiveError(){throw new TypeError("Chaining cycle detected")}var isFn=function(v){return"function"==typeof v},thenableObj={then:function then(onResolve,onReject){var nextThenable=BespokeThenable();return queue.push((function handleNext(){var cb=state>0?onResolve:onReject;if(isFn(cb))try{var result=cb(value);result===nextThenable&&recursiveError();var resultThen=getThenableThen(result);resultThen?resultThen.call(result,nextThenable.resolve,nextThenable.reject):nextThenable.resolve(result)}catch(err){nextThenable.reject(err)}else nextThenable[state>0?"resolve":"reject"](value)})),state&&scheduleQueueFlush(),nextThenable},resolve:resolve,reject:reject};return thenableObj}function NativePromiseThenable(){var resolve,reject,promise=new Promise((function(res,rej){resolve=res,reject=rej}));return{then:promise.then.bind(promise),resolve:resolve,reject:reject}}BespokeThenable.all=NativePromiseThenable.all=function(items){var resultCount=0,results=[],out=DefaultThenable();return 0===items.length?out.resolve([]):items.forEach((function(item,i){var itemThenable=DefaultThenable();itemThenable.resolve(item),itemThenable.then((function(res){resultCount++,results[i]=res,resultCount===items.length&&out.resolve(results)}),out.reject)})),out};var DefaultThenable="function"==typeof Promise?NativePromiseThenable:BespokeThenable;function workerBootstrap(){var modules=Object.create(null);function registerModule(ref,callback){var id=ref.id,name=ref.name,dependencies=ref.dependencies;void 0===dependencies&&(dependencies=[]);var init=ref.init;void 0===init&&(init=function(){});var getTransferables=ref.getTransferables;if(void 0===getTransferables&&(getTransferables=null),!modules[id])try{dependencies=dependencies.map((function(dep){return dep&&dep.isWorkerModule&&(registerModule(dep,(function(depResult){if(depResult instanceof Error)throw depResult})),dep=modules[dep.id].value),dep})),init=rehydrate("<"+name+">.init",init),getTransferables&&(getTransferables=rehydrate("<"+name+">.getTransferables",getTransferables));var value=null;"function"==typeof init?value=init.apply(void 0,dependencies):console.error("worker module init function failed to rehydrate"),modules[id]={id:id,value:value,getTransferables:getTransferables},callback(value)}catch(err){err&&err.noLog||console.error(err),callback(err)}}function rehydrate(name,str){var result=void 0;self.troikaDefine=function(r){return result=r};var url=URL.createObjectURL(new Blob(["/** "+name.replace(/\*/g,"")+" **/\n\ntroikaDefine(\n"+str+"\n)"],{type:"application/javascript"}));try{importScripts(url)}catch(err){console.error(err)}return URL.revokeObjectURL(url),delete self.troikaDefine,result}self.addEventListener("message",(function(e){var ref=e.data,messageId=ref.messageId,action=ref.action,data=ref.data;try{"registerModule"===action&®isterModule(data,(function(result){result instanceof Error?postMessage({messageId:messageId,success:!1,error:result.message}):postMessage({messageId:messageId,success:!0,result:{isCallable:"function"==typeof result}})})),"callModule"===action&&function callModule(ref,callback){var ref$1,id=ref.id,args=ref.args;modules[id]&&"function"==typeof modules[id].value||callback(new Error("Worker module "+id+": not found or its 'init' did not return a function"));try{var result=(ref$1=modules[id]).value.apply(ref$1,args);result&&"function"==typeof result.then?result.then(handleResult,(function(rej){return callback(rej instanceof Error?rej:new Error(""+rej))})):handleResult(result)}catch(err){callback(err)}function handleResult(result){try{var tx=modules[id].getTransferables&&modules[id].getTransferables(result);tx&&Array.isArray(tx)&&tx.length||(tx=void 0),callback(result,tx)}catch(err){console.error(err),callback(err)}}}(data,(function(result,transferables){result instanceof Error?postMessage({messageId:messageId,success:!1,error:result.message}):postMessage({messageId:messageId,success:!0,result:result},transferables||void 0)}))}catch(err){postMessage({messageId:messageId,success:!1,error:err.stack})}}))}var supportsWorkers=function(){var supported=!1;if("undefined"!=typeof window&&void 0!==window.document)try{new Worker(URL.createObjectURL(new Blob([""],{type:"application/javascript"}))).terminate(),supported=!0}catch(err){console.log("Troika createWorkerModule: web workers not allowed; falling back to main thread execution. Cause: ["+err.message+"]")}return supportsWorkers=function(){return supported},supported},_workerModuleId=0,_messageId=0,_allowInitAsString=!1,workers=Object.create(null),registeredModules=Object.create(null),openRequests=Object.create(null);function defineWorkerModule(options){if(!(options&&"function"==typeof options.init||_allowInitAsString))throw new Error("requires `options.init` function");var dependencies=options.dependencies,init=options.init,getTransferables=options.getTransferables,workerId=options.workerId;if(!supportsWorkers())return function defineMainThreadModule(options){var moduleFunc=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return moduleFunc._getInitResult().then((function(initResult){if("function"==typeof initResult)return initResult.apply(void 0,args);throw new Error("Worker module function was called but `init` did not return a callable function")}))};return moduleFunc._getInitResult=function(){var dependencies=options.dependencies,init=options.init;dependencies=Array.isArray(dependencies)?dependencies.map((function(dep){return dep&&dep._getInitResult?dep._getInitResult():dep})):[];var initThenable=DefaultThenable.all(dependencies).then((function(deps){return init.apply(null,deps)}));return moduleFunc._getInitResult=function(){return initThenable},initThenable},moduleFunc}(options);null==workerId&&(workerId="#default");var id="workerModule"+ ++_workerModuleId,name=options.name||id,registrationThenable=null;function moduleFunc(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(!registrationThenable){registrationThenable=callWorker(workerId,"registerModule",moduleFunc.workerModuleData);var unregister=function(){registrationThenable=null,registeredModules[workerId].delete(unregister)};(registeredModules[workerId]||(registeredModules[workerId]=new Set)).add(unregister)}return registrationThenable.then((function(ref){if(ref.isCallable)return callWorker(workerId,"callModule",{id:id,args:args});throw new Error("Worker module function was called but `init` did not return a callable function")}))}return dependencies=dependencies&&dependencies.map((function(dep){return"function"!=typeof dep||dep.workerModuleData||(_allowInitAsString=!0,dep=defineWorkerModule({workerId:workerId,name:"<"+name+"> function dependency: "+dep.name,init:"function(){return (\n"+stringifyFunction(dep)+"\n)}"}),_allowInitAsString=!1),dep&&dep.workerModuleData&&(dep=dep.workerModuleData),dep})),moduleFunc.workerModuleData={isWorkerModule:!0,id:id,name:name,dependencies:dependencies,init:stringifyFunction(init),getTransferables:getTransferables&&stringifyFunction(getTransferables)},moduleFunc}function stringifyFunction(fn){var str=fn.toString();return!/^function/.test(str)&&/^\w+\s*\(/.test(str)&&(str="function "+str),str}function callWorker(workerId,action,data){var thenable=DefaultThenable(),messageId=++_messageId;return openRequests[messageId]=function(response){response.success?thenable.resolve(response.result):thenable.reject(new Error("Error in worker "+action+" call: "+response.error))},function getWorker(workerId){var worker=workers[workerId];if(!worker){var bootstrap=stringifyFunction(workerBootstrap);(worker=workers[workerId]=new Worker(URL.createObjectURL(new Blob(["/** Worker Module Bootstrap: "+workerId.replace(/\*/g,"")+" **/\n\n;("+bootstrap+")()"],{type:"application/javascript"})))).onmessage=function(e){var response=e.data,msgId=response.messageId,callback=openRequests[msgId];if(!callback)throw new Error("WorkerModule response with empty or unknown messageId");delete openRequests[msgId],callback(response)}}return worker}(workerId).postMessage({messageId:messageId,action:action,data:data}),thenable}var ThenableWorkerModule=defineWorkerModule({name:"Thenable",dependencies:[DefaultThenable],init:function(Thenable){return Thenable}});function SDFGenerator(){var exports=function(exports){function pointOnCubicBezier(x0,y0,x1,y1,x2,y2,x3,y3,t,pointOut){var t2=1-t;pointOut.x=t2*t2*t2*x0+3*t2*t2*t*x1+3*t2*t*t*x2+t*t*t*x3,pointOut.y=t2*t2*t2*y0+3*t2*t2*t*y1+3*t2*t*t*y2+t*t*t*y3}function forEachPathCommand(pathString,commandCallback){for(var match,firstX,firstY,prevX,prevY,segmentRE=/([MLQCZ])([^MLQCZ]*)/g;match=segmentRE.exec(pathString);){var args=match[2].replace(/^\s*|\s*$/g,"").split(/[,\s]+/).map((function(v){return parseFloat(v)}));switch(match[1]){case"M":prevX=firstX=args[0],prevY=firstY=args[1];break;case"L":args[0]===prevX&&args[1]===prevY||commandCallback("L",prevX,prevY,prevX=args[0],prevY=args[1]);break;case"Q":commandCallback("Q",prevX,prevY,prevX=args[2],prevY=args[3],args[0],args[1]);break;case"C":commandCallback("C",prevX,prevY,prevX=args[4],prevY=args[5],args[0],args[1],args[2],args[3]);break;case"Z":prevX===firstX&&prevY===firstY||commandCallback("L",prevX,prevY,firstX,firstY)}}}function pathToLineSegments(pathString,segmentCallback,curvePoints){void 0===curvePoints&&(curvePoints=16);var tempPoint={x:0,y:0};forEachPathCommand(pathString,(function(command,startX,startY,endX,endY,ctrl1X,ctrl1Y,ctrl2X,ctrl2Y){switch(command){case"L":segmentCallback(startX,startY,endX,endY);break;case"Q":for(var prevCurveX=startX,prevCurveY=startY,i=1;i0;)values[len]=arguments[len+2];var uniformLoc=uniforms[name]||(uniforms[name]=gl.getUniformLocation(program,name));gl["uniform"+type].apply(gl,[uniformLoc].concat(values))},setAttribute:function setAttribute(name,size,usage,instancingDivisor,data){var attr=attributes[name];attr||(attr=attributes[name]={buf:gl.createBuffer(),loc:gl.getAttribLocation(program,name),data:null}),gl.bindBuffer(gl.ARRAY_BUFFER,attr.buf),gl.vertexAttribPointer(attr.loc,size,gl.FLOAT,!1,0,0),gl.enableVertexAttribArray(attr.loc),isWebGL2?gl.vertexAttribDivisor(attr.loc,instancingDivisor):getExtension("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(attr.loc,instancingDivisor),data!==attr.data&&(gl.bufferData(gl.ARRAY_BUFFER,data,usage),attr.data=data)}})}}}programs[name].transaction(func)}function withTexture(name,func){textureUnit++;try{gl.activeTexture(gl.TEXTURE0+textureUnit);var texture=textures[name];texture||(texture=textures[name]=gl.createTexture(),gl.bindTexture(gl.TEXTURE_2D,texture),gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST),gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST)),gl.bindTexture(gl.TEXTURE_2D,texture),func(texture,textureUnit)}finally{textureUnit--}}function withTextureFramebuffer(texture,textureUnit,func){var framebuffer=gl.createFramebuffer();framebufferStack.push(framebuffer),gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer),gl.activeTexture(gl.TEXTURE0+textureUnit),gl.bindTexture(gl.TEXTURE_2D,texture),gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);try{func(framebuffer)}finally{gl.deleteFramebuffer(framebuffer),gl.bindFramebuffer(gl.FRAMEBUFFER,framebufferStack[--framebufferStack.length-1]||null)}}function handleContextLoss(){extensions={},programs={},textures={},textureUnit=-1,framebufferStack.length=0}gl.canvas.addEventListener("webglcontextlost",(function(e){handleContextLoss(),e.preventDefault()}),!1),cache.set(gl,wrapper={gl:gl,isWebGL2:isWebGL2,getExtension:getExtension,withProgram:withProgram,withTexture:withTexture,withTextureFramebuffer:withTextureFramebuffer,handleContextLoss:handleContextLoss})}callback(wrapper)}function renderImageData(glOrCanvas,imageData,x,y,width,height,channels,framebuffer){void 0===channels&&(channels=15),void 0===framebuffer&&(framebuffer=null),withWebGLContext(glOrCanvas,(function(ref){var gl=ref.gl,withProgram=ref.withProgram;(0,ref.withTexture)("copy",(function(tex,texUnit){gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,width,height,0,gl.RGBA,gl.UNSIGNED_BYTE,imageData),withProgram("copy",viewportQuadVertex,"precision highp float;uniform sampler2D tex;varying vec2 vUV;void main(){gl_FragColor=texture2D(tex,vUV);}",(function(ref){var setUniform=ref.setUniform;(0,ref.setAttribute)("aUV",2,gl.STATIC_DRAW,0,new Float32Array([0,0,2,0,0,2])),setUniform("1i","image",texUnit),gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer||null),gl.disable(gl.BLEND),gl.colorMask(8&channels,4&channels,2&channels,1&channels),gl.viewport(x,y,width,height),gl.scissor(x,y,width,height),gl.drawArrays(gl.TRIANGLES,0,3)}))}))}))}var webglUtils=Object.freeze({__proto__:null,withWebGLContext:withWebGLContext,renderImageData:renderImageData,resizeWebGLCanvasWithoutClearing:function resizeWebGLCanvasWithoutClearing(canvas,newWidth,newHeight){var width=canvas.width,height=canvas.height;withWebGLContext(canvas,(function(ref){var gl=ref.gl,data=new Uint8Array(width*height*4);gl.readPixels(0,0,width,height,gl.RGBA,gl.UNSIGNED_BYTE,data),canvas.width=newWidth,canvas.height=newHeight,renderImageData(gl,data,0,0,width,height)}))}});function generate$2(sdfWidth,sdfHeight,path,viewBox,maxDistance,sdfExponent){void 0===sdfExponent&&(sdfExponent=1);var textureData=new Uint8Array(sdfWidth*sdfHeight),viewBoxWidth=viewBox[2]-viewBox[0],viewBoxHeight=viewBox[3]-viewBox[1],segments=[];pathToLineSegments(path,(function(x1,y1,x2,y2){segments.push({x1:x1,y1:y1,x2:x2,y2:y2,minX:Math.min(x1,x2),minY:Math.min(y1,y2),maxX:Math.max(x1,x2),maxY:Math.max(y1,y2)})})),segments.sort((function(a,b){return a.maxX-b.maxX}));for(var sdfX=0;sdfXseg.minX&&y-closestDistseg.minY){var distSq=absSquareDistanceToLineSegment(x,y,seg.x1,seg.y1,seg.x2,seg.y2);distSqy!=seg.y2>y&&x<(seg.x2-seg.x1)*(y-seg.y1)/(seg.y2-seg.y1)+seg.x1&&(winding+=seg.y1p.y!=seg.w>p.y)&&(p.x<(seg.z-seg.x)*(p.y-seg.y)/(seg.w-seg.y)+seg.x);bool crossingUp=crossing&&vLineSegment.y"),a=ref[0],b=ref[1];a=String.fromCodePoint(lastCode+=parseInt(a,36)),b=String.fromCodePoint(lastCode+=parseInt(b,36)),map.set(a,b),includeReverse&&reverseMap.set(b,a)}})),{map:map,reverseMap:reverseMap}}function parse$1(){if(!openToClose){var ref=parseCharacterMap(data$1_pairs,!0),map=ref.map,reverseMap=ref.reverseMap;openToClose=map,closeToOpen=reverseMap,canonical=parseCharacterMap(data$1_canonical,!1).map}}function openingToClosingBracket(char){return parse$1(),openToClose.get(char)||null}function closingToOpeningBracket(char){return parse$1(),closeToOpen.get(char)||null}function getCanonicalBracket(char){return parse$1(),canonical.get(char)||null}var TYPE_L=TYPES.L,TYPE_R=TYPES.R,TYPE_EN=TYPES.EN,TYPE_ES=TYPES.ES,TYPE_ET=TYPES.ET,TYPE_AN=TYPES.AN,TYPE_CS=TYPES.CS,TYPE_B=TYPES.B,TYPE_S=TYPES.S,TYPE_ON=TYPES.ON,TYPE_BN=TYPES.BN,TYPE_NSM=TYPES.NSM,TYPE_AL=TYPES.AL,TYPE_LRO=TYPES.LRO,TYPE_RLO=TYPES.RLO,TYPE_LRE=TYPES.LRE,TYPE_RLE=TYPES.RLE,TYPE_PDF=TYPES.PDF,TYPE_LRI=TYPES.LRI,TYPE_RLI=TYPES.RLI,TYPE_FSI=TYPES.FSI,TYPE_PDI=TYPES.PDI;var mirrorMap;function getMirroredCharacter(char){return function parse(){if(!mirrorMap){var ref=parseCharacterMap("14>1,j>2,t>2,u>2,1a>g,2v3>1,1>1,1ge>1,1wd>1,b>1,1j>1,f>1,ai>3,-2>3,+1,8>1k0,-1jq>1y7,-1y6>1hf,-1he>1h6,-1h5>1ha,-1h8>1qi,-1pu>1,6>3u,-3s>7,6>1,1>1,f>1,1>1,+2,3>1,1>1,+13,4>1,1>1,6>1eo,-1ee>1,3>1mg,-1me>1mk,-1mj>1mi,-1mg>1mi,-1md>1,1>1,+2,1>10k,-103>1,1>1,4>1,5>1,1>1,+10,3>1,1>8,-7>8,+1,-6>7,+1,a>1,1>1,u>1,u6>1,1>1,+5,26>1,1>1,2>1,2>2,8>1,7>1,4>1,1>1,+5,b8>1,1>1,+3,1>3,-2>1,2>1,1>1,+2,c>1,3>1,1>1,+2,h>1,3>1,a>1,1>1,2>1,3>1,1>1,d>1,f>1,3>1,1a>1,1>1,6>1,7>1,13>1,k>1,1>1,+19,4>1,1>1,+2,2>1,1>1,+18,m>1,a>1,1>1,lk>1,1>1,4>1,2>1,f>1,3>1,1>1,+3,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,6>1,4j>1,j>2,t>2,u>2,2>1,+1",!0),map=ref.map;ref.reverseMap.forEach((function(value,key){map.set(key,value)})),mirrorMap=map}}(),mirrorMap.get(char)||null}function getReorderSegments(string,embeddingLevelsResult,start,end){var strLen=string.length;start=Math.max(0,null==start?0:+start),end=Math.min(strLen-1,null==end?strLen-1:+end);var segments=[];return embeddingLevelsResult.paragraphs.forEach((function(paragraph){var lineStart=Math.max(start,paragraph.start),lineEnd=Math.min(end,paragraph.end);if(lineStart=lineStart&&getBidiCharType(string[i])&TRAILING_TYPES;i--)lineLevels[i]=paragraph.level;for(var maxLevel=paragraph.level,minOddLevel=1/0,i$1=0;i$1maxLevel&&(maxLevel=level),level=minOddLevel;lvl--)for(var i$2=0;i$2=lvl){for(var segStart=i$2;i$2+1=lvl;)i$2++;i$2>segStart&&segments.push([segStart+start,i$2+start])}}})),segments}function getReorderedIndices(string,embedLevelsResult,start,end){for(var segments=getReorderSegments(string,embedLevelsResult,start,end),indices=[],i=0;i0)overflowIsolateCount--;else if(validIsolateCount>0){for(overflowEmbeddingCount=0;!statusStack[statusStack.length-1]._isolate;)statusStack.pop();var isolInitIndex=statusStack[statusStack.length-1]._isolInitIndex;null!=isolInitIndex&&(isolationPairs.set(isolInitIndex,i$2),isolationPairs.set(i$2,isolInitIndex)),statusStack.pop(),validIsolateCount--}stackTop=statusStack[statusStack.length-1],embedLevels[i$2]=stackTop._level,stackTop._override&&changeCharType(i$2,stackTop._override)}else charType&TYPE_PDF?(0===overflowIsolateCount&&(overflowEmbeddingCount>0?overflowEmbeddingCount--:!stackTop._isolate&&statusStack.length>1&&(statusStack.pop(),stackTop=statusStack[statusStack.length-1])),embedLevels[i$2]=stackTop._level):charType&TYPE_B&&(embedLevels[i$2]=paragraph.level);else embedLevels[i$2]=stackTop._level,stackTop._override&&charType!==TYPE_BN&&changeCharType(i$2,stackTop._override)}for(var levelRuns=[],currentRun=null,i$3=paragraph.start;i$3<=paragraph.end;i$3++){var charType$1=charTypes[i$3];if(!(charType$1&BN_LIKE_TYPES)){var lvl=embedLevels[i$3],isIsolInit=charType$1&ISOLATE_INIT_TYPES,isPDI=charType$1===TYPE_PDI;currentRun&&lvl===currentRun._level?(currentRun._end=i$3,currentRun._endsWithIsolInit=isIsolInit):levelRuns.push(currentRun={_start:i$3,_end:i$3,_level:lvl,_startsWithPDI:isPDI,_endsWithIsolInit:isIsolInit})}}for(var isolatingRunSeqs=[],runIdx=0;runIdx=0;i$6--)if(!(charTypes[i$6]&BN_LIKE_TYPES)){prevLevel=embedLevels[i$6];break}var lastIndex=seqIndices[seqIndices.length-1],lastLevel=embedLevels[lastIndex],nextLevel=paragraph.level;if(!(charTypes[lastIndex]&ISOLATE_INIT_TYPES))for(var i$7=lastIndex+1;i$7<=paragraph.end;i$7++)if(!(charTypes[i$7]&BN_LIKE_TYPES)){nextLevel=embedLevels[i$7];break}isolatingRunSeqs.push({_seqIndices:seqIndices,_sosType:Math.max(prevLevel,firstLevel)%2?TYPE_R:TYPE_L,_eosType:Math.max(nextLevel,lastLevel)%2?TYPE_R:TYPE_L})}}for(var seqIdx=0;seqIdx=0;sj--)if(!(charTypes[seqIndices$1[sj]]&BN_LIKE_TYPES)){prevType=charTypes[seqIndices$1[sj]];break}changeCharType(i$8,prevType&(ISOLATE_INIT_TYPES|TYPE_PDI)?TYPE_ON:prevType)}}if(charTypeCounts.get(TYPE_EN))for(var si$1=0;si$1=-1;sj$1--){var prevCharType=-1===sj$1?sosType:charTypes[seqIndices$1[sj$1]];if(prevCharType&STRONG_TYPES){prevCharType===TYPE_AL&&changeCharType(i$9,TYPE_AN);break}}}if(charTypeCounts.get(TYPE_AL))for(var si$2=0;si$2=0&&(prevType$1=charTypes[seqIndices$1[sj$2]])&BN_LIKE_TYPES;sj$2--);for(var sj$3=si$3+1;sj$3=0&&charTypes[seqIndices$1[sj$4]]&(TYPE_ET|BN_LIKE_TYPES);sj$4--)changeCharType(seqIndices$1[sj$4],TYPE_EN);for(var sj$5=si$4+1;sj$5=0&&charTypes[seqIndices$1[sj$6]]&BN_LIKE_TYPES;sj$6--)changeCharType(seqIndices$1[sj$6],TYPE_ON);for(var sj$7=si$5+1;sj$7=0;stackIdx--){var stackChar=openerStack[stackIdx].char;if(stackChar===oppositeBracket||stackChar===closingToOpeningBracket(getCanonicalBracket(char))||openingToClosingBracket(getCanonicalBracket(stackChar))===char){bracketPairs.push([openerStack[stackIdx].seqIndex,si$7]),openerStack.length=stackIdx;break}}}bracketPairs.sort((function(a,b){return a[0]-b[0]}));for(var pairIdx=0;pairIdx=0;si$9--){var i$16=seqIndices$1[si$9];if(charTypes[i$16]&STRONG_TYPES_FOR_N_STEPS){var lr$1=charTypes[i$16]&R_TYPES_FOR_N_STEPS?TYPE_R:TYPE_L;useStrongType=lr$1!==getEmbedDirection(i$16)?lr$1:getEmbedDirection(i$16);break}}}if(useStrongType){if(charTypes[seqIndices$1[openSeqIdx]]=charTypes[seqIndices$1[closeSeqIdx]]=useStrongType,useStrongType!==getEmbedDirection(seqIndices$1[openSeqIdx]))for(var si$10=openSeqIdx+1;si$10=0;si2--){if(!(charTypes[seqIndices$1[si2]]&BN_LIKE_TYPES)){prevType$2=charTypes[seqIndices$1[si2]]&R_TYPES_FOR_N_STEPS?TYPE_R:TYPE_L;break}niRunStart=si2}for(var nextType$1=eosType,si2$1=si$12+1;si2$1=0&&getBidiCharType(string[j$1])&TRAILING_TYPES;j$1--)embedLevels[j$1]=paragraph.level}}return{levels:embedLevels,paragraphs:paragraphs};function determineAutoEmbedLevel(start,isFSI){for(var i=start;i/gm,(function replace(match,include){let chunk=three_module.ShaderChunk[include];return chunk?expandShaderIncludes(chunk):match}))}const _lut=[];for(let i=0;i<256;i++)_lut[i]=(i<16?"0":"")+i.toString(16);const troika_three_utils_esm_assign=Object.assign||function(){let target=arguments[0];for(let i=1,len=arguments.length;i/gm,"\n//!BEGIN_POST_CHUNK $1\n$&\n//!END_POST_CHUNK\n")));if(customRewriter){let res=customRewriter({vertexShader:vertexShader,fragmentShader:fragmentShader});vertexShader=res.vertexShader,fragmentShader=res.fragmentShader}if(fragmentColorTransform){let postChunks=[];fragmentShader=fragmentShader.replace(/^\/\/!BEGIN_POST_CHUNK[^]+?^\/\/!END_POST_CHUNK/gm,(match=>(postChunks.push(match),""))),fragmentMainOutro=`${fragmentColorTransform}\n${postChunks.join("\n")}\n${fragmentMainOutro}`}if(timeUniform){const code=`\nuniform float ${timeUniform};\n`;vertexDefs=code+vertexDefs,fragmentDefs=code+fragmentDefs}vertexTransform&&(vertexDefs=`${vertexDefs}\nvoid troikaVertexTransform${key}(inout vec3 position, inout vec3 normal, inout vec2 uv) {\n ${vertexTransform}\n}\n`,vertexMainIntro=`\ntroika_position_${key} = vec3(position);\ntroika_normal_${key} = vec3(normal);\ntroika_uv_${key} = vec2(uv);\ntroikaVertexTransform${key}(troika_position_${key}, troika_normal_${key}, troika_uv_${key});\n${vertexMainIntro}\n`,vertexShader=(vertexShader=`vec3 troika_position_${key};\nvec3 troika_normal_${key};\nvec2 troika_uv_${key};\n${vertexShader}\n`).replace(/\b(position|normal|uv)\b/g,((match,match1,index,fullStr)=>/\battribute\s+vec[23]\s+$/.test(fullStr.substr(0,index))?match1:`troika_${match1}_${key}`)));return vertexShader=injectIntoShaderCode(vertexShader,key,vertexDefs,vertexMainIntro,vertexMainOutro),fragmentShader=injectIntoShaderCode(fragmentShader,key,fragmentDefs,fragmentMainIntro,fragmentMainOutro),{vertexShader:vertexShader,fragmentShader:fragmentShader}}(shaderInfo,options,optionsKey);upgradedShaders=SHADER_UPGRADE_CACHE[cacheKey]=upgraded}shaderInfo.vertexShader=upgradedShaders.vertexShader,shaderInfo.fragmentShader=upgradedShaders.fragmentShader,troika_three_utils_esm_assign(shaderInfo.uniforms,this.uniforms),options.timeUniform&&(shaderInfo.uniforms[options.timeUniform]={get value(){return Date.now()-epoch}}),this[privateBeforeCompileProp]&&this[privateBeforeCompileProp](shaderInfo)},DerivedMaterial=function DerivedMaterial(){return derive(options.chained?baseMaterial:baseMaterial.clone())},derive=function(base){const derived=Object.create(base,descriptor);return Object.defineProperty(derived,"baseMaterial",{value:baseMaterial}),Object.defineProperty(derived,"id",{value:materialInstanceId++}),derived.uuid=function generateUUID(){const d0=4294967295*Math.random()|0,d1=4294967295*Math.random()|0,d2=4294967295*Math.random()|0,d3=4294967295*Math.random()|0;return(_lut[255&d0]+_lut[d0>>8&255]+_lut[d0>>16&255]+_lut[d0>>24&255]+"-"+_lut[255&d1]+_lut[d1>>8&255]+"-"+_lut[d1>>16&15|64]+_lut[d1>>24&255]+"-"+_lut[63&d2|128]+_lut[d2>>8&255]+"-"+_lut[d2>>16&255]+_lut[d2>>24&255]+_lut[255&d3]+_lut[d3>>8&255]+_lut[d3>>16&255]+_lut[d3>>24&255]).toUpperCase()}(),derived.uniforms=troika_three_utils_esm_assign({},base.uniforms,options.uniforms),derived.defines=troika_three_utils_esm_assign({},base.defines,options.defines),derived.defines[`TROIKA_DERIVED_MATERIAL_${optionsKey}`]="",derived.extensions=troika_three_utils_esm_assign({},base.extensions,options.extensions),derived._listeners=void 0,derived},descriptor={constructor:{value:DerivedMaterial},isDerivedMaterial:{value:!0},customProgramCacheKey:{writable:!0,configurable:!0,value:function(){return baseMaterial.customProgramCacheKey()+"|"+optionsKey}},onBeforeCompile:{get:()=>onBeforeCompile,set(fn){this[privateBeforeCompileProp]=fn}},copy:{writable:!0,configurable:!0,value:function(source){return baseMaterial.copy.call(this,source),baseMaterial.isShaderMaterial||baseMaterial.isDerivedMaterial||(troika_three_utils_esm_assign(this.extensions,source.extensions),troika_three_utils_esm_assign(this.defines,source.defines),troika_three_utils_esm_assign(this.uniforms,three_module.UniformsUtils.clone(source.uniforms))),this}},clone:{writable:!0,configurable:!0,value:function(){const newBase=new baseMaterial.constructor;return derive(newBase).copy(this)}},getDepthMaterial:{writable:!0,configurable:!0,value:function(){let depthMaterial=this._depthMaterial;return depthMaterial||(depthMaterial=this._depthMaterial=createDerivedMaterial(baseMaterial.isDerivedMaterial?baseMaterial.getDepthMaterial():new three_module.MeshDepthMaterial({depthPacking:three_module.RGBADepthPacking}),options),depthMaterial.defines.IS_DEPTH_MATERIAL="",depthMaterial.uniforms=this.uniforms),depthMaterial}},getDistanceMaterial:{writable:!0,configurable:!0,value:function(){let distanceMaterial=this._distanceMaterial;return distanceMaterial||(distanceMaterial=this._distanceMaterial=createDerivedMaterial(baseMaterial.isDerivedMaterial?baseMaterial.getDistanceMaterial():new three_module.MeshDistanceMaterial,options),distanceMaterial.defines.IS_DISTANCE_MATERIAL="",distanceMaterial.uniforms=this.uniforms),distanceMaterial}},dispose:{writable:!0,configurable:!0,value(){const{_depthMaterial:_depthMaterial,_distanceMaterial:_distanceMaterial}=this;_depthMaterial&&_depthMaterial.dispose(),_distanceMaterial&&_distanceMaterial.dispose(),baseMaterial.dispose.call(this)}}};return ctorsByDerivation[optionsKey]=DerivedMaterial,new DerivedMaterial}function injectIntoShaderCode(shaderCode,id,defs,intro,outro){return(intro||outro||defs)&&(shaderCode=shaderCode.replace(voidMainRegExp,`\n${defs}\nvoid troikaOrigMain${id}() {`),shaderCode+=`\nvoid main() {\n ${intro}\n troikaOrigMain${id}();\n ${outro}\n}`),shaderCode}function optionsJsonReplacer(key,value){return"uniforms"===key?void 0:"function"==typeof value?value.toString():value}let _idCtr=0;const optionsHashesToIds=new Map;three_module.DoubleSide;const now=()=>(self.performance||Date).now(),mainThreadGenerator=SDFGenerator();let warned;const generateSDF_GL=function(){const queue=[];let timer=0;function nextChunk(){const start=now();for(;queue.length&&now()-start<5;)queue.shift()();timer=queue.length?setTimeout(nextChunk,0):0}return(...args)=>{const thenable=DefaultThenable();return queue.push((()=>{const start=now();try{mainThreadGenerator.webgl.generateIntoCanvas(...args),thenable.resolve({timing:now()-start})}catch(err){thenable.reject(err)}})),timer||(timer=setTimeout(nextChunk,0)),thenable}}(),generateSDF_JS_Worker=function(){const threads={};let callNum=0;return function(width,height,path,viewBox,distance,exponent,canvas,x,y,channel){const workerId="TroikaTextSDFGenerator_JS_"+callNum++%4;let thread=threads[workerId];return thread||(thread=threads[workerId]={workerModule:defineWorkerModule({name:workerId,workerId:workerId,dependencies:[SDFGenerator,now],init(_createSDFGenerator,now){const generate=_createSDFGenerator().javascript.generate;return function(...args){const start=now();return{textureData:generate(...args),timing:now()-start}}},getTransferables:result=>[result.textureData.buffer]}),requests:0,idleTimer:null}),thread.requests++,clearTimeout(thread.idleTimer),thread.workerModule(width,height,path,viewBox,distance,exponent).then((({textureData:textureData,timing:timing})=>{const start=now(),imageData=new Uint8Array(4*textureData.length);for(let i=0;i{!function terminateWorker(workerId){registeredModules[workerId]&®isteredModules[workerId].forEach((function(unregister){unregister()})),workers[workerId]&&(workers[workerId].terminate(),delete workers[workerId])}(workerId)}),2e3)),{timing:timing}}))}}();const resizeWebGLCanvasWithoutClearing=mainThreadGenerator.webglUtils.resizeWebGLCanvasWithoutClearing;const workerModule=defineWorkerModule({name:"Typr Font Parser",dependencies:[function typrFactory(){return"undefined"==typeof window&&(self.window=self),function(r){var e={parse:function(r){var t=e._bin,a=new Uint8Array(r);if("ttcf"==t.readASCII(a,0,4)){var n=4;t.readUshort(a,n),n+=2,t.readUshort(a,n),n+=2;var o=t.readUint(a,n);n+=4;for(var s=[],i=0;i>>t&1)&&e++;return e},e._lctf.readClassDef=function(r,t){var a=e._bin,n=[],o=a.readUshort(r,t);if(t+=2,1==o){var s=a.readUshort(r,t);t+=2;var i=a.readUshort(r,t);t+=2;for(var h=0;h0&&(o.featureParams=n+s);var i=a.readUshort(r,t);t+=2,o.tab=[];for(var h=0;h255?-1:e.CFF.glyphByUnicode(r,e.CFF.tableSE[t])},e.CFF.readEncoding=function(r,t,a){e._bin;var n=[".notdef"],o=r[t];if(t++,0!=o)throw"error: unknown encoding format: "+o;var s=r[t];t++;for(var i=0;i>4,p=15&v;if(15!=c&&u.push(c),15!=p&&u.push(p),15==p)break}for(var U="",g=[0,1,2,3,4,5,6,7,8,9,".","e","e-","reserved","-","endOfNumber"],S=0;S=s.xMax||s.yMin>=s.yMax)return null;if(s.noc>0){s.endPts=[];for(var i=0;i=1&&i.fmt<=2){f=o.readUshort(r,a),a+=2;var l=o.readUshort(r,a);a+=2,d=e._lctf.numOfOnes(f);var u=e._lctf.numOfOnes(l);if(1==i.fmt){i.pairsets=[];var v=o.readUshort(r,a);a+=2;for(var c=0;c=1&&i.fmt<=2){if(1==i.fmt)i.delta=o.readShort(r,a),a+=2;else if(2==i.fmt){var f=o.readUshort(r,a);a+=2,i.newg=o.readUshorts(r,a,f),a+=2*i.newg.length}}else if(4==t){i.vals=[],f=o.readUshort(r,a),a+=2;for(var d=0;d>>8;if(0!=(l&=15))throw"unknown kern table format: "+l;t=e.kern.readFormat0(r,t,h)}return h},e.kern.parseV1=function(r,t,a,n){var o=e._bin;o.readFixed(r,t),t+=4;var s=o.readUint(r,t);t+=4;for(var i={glyph1:[],rval:[]},h=0;h>>8;if(0!=(d&=15))throw"unknown kern table format: "+d;t=e.kern.readFormat0(r,t,i)}return i},e.kern.readFormat0=function(r,t,a){var n=e._bin,o=-1,s=n.readUshort(r,t);t+=2,n.readUshort(r,t),t+=2,n.readUshort(r,t),t+=2,n.readUshort(r,t),t+=2;for(var i=0;i=n.map.length?0:n.map[e];if(4==n.format){for(var o=-1,s=0;se?0:65535&(0!=n.idRangeOffset[o]?n.glyphIdArray[e-n.startCount[o]+(n.idRangeOffset[o]>>1)-(n.idRangeOffset.length-o)]:e+n.idDelta[o])}if(12==n.format){if(e>n.groups[n.groups.length-1][1])return 0;for(s=0;s-1?e.U._simpleGlyph(n,a):e.U._compoGlyph(n,t,a))},e.U._simpleGlyph=function(r,t){for(var a=0;ao)){for(var v=!0,c=0,p=0;po)){for(v=!0,p=0;p>1,s.length=0,h=!0;else if("o3"==x||"o23"==x)s.length%2!=0&&!h&&(f=s.shift()+n.nominalWidthX),i+=s.length>>1,s.length=0,h=!0;else if("o4"==x)s.length>1&&!h&&(f=s.shift()+n.nominalWidthX,h=!0),d&&e.U.P.closePath(o),v+=s.pop(),e.U.P.moveTo(o,u,v),d=!0;else if("o5"==x)for(;s.length>0;)u+=s.shift(),v+=s.shift(),e.U.P.lineTo(o,u,v);else if("o6"==x||"o7"==x)for(var P=s.length,I="o6"==x,w=0;wMath.abs(y-v)?u=b+s.shift():v=y+s.shift(),e.U.P.curveTo(o,c,p,U,g,F,_),e.U.P.curveTo(o,S,m,b,y,u,v));else if("o14"==x){if(s.length>0&&!h&&(f=s.shift()+a.nominalWidthX,h=!0),4==s.length){var k=s.shift(),G=s.shift(),D=s.shift(),B=s.shift(),L=e.CFF.glyphBySE(a,D),R=e.CFF.glyphBySE(a,B);e.U._drawCFF(a.CharStrings[L],t,a,n,o),t.x=k,t.y=G,e.U._drawCFF(a.CharStrings[R],t,a,n,o)}d&&(e.U.P.closePath(o),d=!1)}else if("o19"==x||"o20"==x)s.length%2!=0&&!h&&(f=s.shift()+n.nominalWidthX),i+=s.length>>1,s.length=0,h=!0,l+=i+7>>3;else if("o21"==x)s.length>2&&!h&&(f=s.shift()+n.nominalWidthX,h=!0),v+=s.pop(),u+=s.pop(),d&&e.U.P.closePath(o),e.U.P.moveTo(o,u,v),d=!0;else if("o22"==x)s.length>1&&!h&&(f=s.shift()+n.nominalWidthX,h=!0),u+=s.pop(),d&&e.U.P.closePath(o),e.U.P.moveTo(o,u,v),d=!0;else if("o25"==x){for(;s.length>6;)u+=s.shift(),v+=s.shift(),e.U.P.lineTo(o,u,v);c=u+s.shift(),p=v+s.shift(),U=c+s.shift(),g=p+s.shift(),u=U+s.shift(),v=g+s.shift(),e.U.P.curveTo(o,c,p,U,g,u,v)}else if("o26"==x)for(s.length%2&&(u+=s.shift());s.length>0;)c=u,p=v+s.shift(),u=U=c+s.shift(),v=(g=p+s.shift())+s.shift(),e.U.P.curveTo(o,c,p,U,g,u,v);else if("o27"==x)for(s.length%2&&(v+=s.shift());s.length>0;)p=v,U=(c=u+s.shift())+s.shift(),g=p+s.shift(),u=U+s.shift(),v=g,e.U.P.curveTo(o,c,p,U,g,u,v);else if("o10"==x||"o29"==x){var A="o10"==x?n:a;if(0==s.length)console.debug("error: empty stack");else{var W=s.pop(),M=A.Subrs[W+A.Bias];t.x=u,t.y=v,t.nStems=i,t.haveWidth=h,t.width=f,t.open=d,e.U._drawCFF(M,t,a,n,o),u=t.x,v=t.y,i=t.nStems,h=t.haveWidth,f=t.width,d=t.open}}else if("o30"==x||"o31"==x){var V=s.length,N=(T=0,"o31"==x);for(T+=V-(P=-3&V);T>>1|(21845&g)<<1;h=(61680&(h=(52428&h)>>>2|(13107&h)<<2))>>>4|(3855&h)<<4,c[g]=((65280&h)>>>8|(255&h)<<8)>>>1}var w=function(r,e,t){for(var a=r.length,i=0,o=new n(e);i>>v]=s}else for(f=new n(a),i=0;i>>15-r[i]);return f},d=new e(288);for(g=0;g<144;++g)d[g]=8;for(g=144;g<256;++g)d[g]=9;for(g=256;g<280;++g)d[g]=7;for(g=280;g<288;++g)d[g]=8;var m=new e(32);for(g=0;g<32;++g)m[g]=5;var b=w(d,9,1),p=w(m,5,1),y=function(r){for(var e=r[0],n=1;ne&&(e=r[n]);return e},L=function(r,e,n){var t=e/8|0;return(r[t]|r[t+1]<<8)>>(7&e)&n},U=function(r,e){var n=e/8|0;return(r[n]|r[n+1]<<8|r[n+2]<<16)>>(7&e)},k=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],T=function(r,e,n){var t=new Error(e||k[r]);if(t.code=r,Error.captureStackTrace&&Error.captureStackTrace(t,T),!n)throw t;return t},O=function(r,f,u){var s=r.length;if(!s||u&&!u.l&&s<5)return f||new e(0);var c=!f||u,g=!u||u.i;u||(u={}),f||(f=new e(3*s));var h,d=function(r){var n=f.length;if(r>n){var t=new e(Math.max(2*n,r));t.set(f),f=t}},m=u.f||0,k=u.p||0,O=u.b||0,A=u.l,x=u.d,E=u.m,D=u.n,M=8*s;do{if(!A){u.f=m=L(r,k,1);var S=L(r,k+1,3);if(k+=3,!S){var V=r[(I=((h=k)/8|0)+(7&h&&1)+4)-4]|r[I-3]<<8,_=I+V;if(_>s){g&&T(0);break}c&&d(O+V),f.set(r.subarray(I,_),O),u.b=O+=V,u.p=k=8*_;continue}if(1==S)A=b,x=p,E=9,D=5;else if(2==S){var j=L(r,k,31)+257,z=L(r,k+10,15)+4,C=j+L(r,k+5,31)+1;k+=14;for(var F=new e(C),P=new e(19),q=0;q>>4)<16)F[q++]=I;else{var K=0,N=0;for(16==I?(N=3+L(r,k,3),k+=2,K=F[q-1]):17==I?(N=3+L(r,k,7),k+=3):18==I&&(N=11+L(r,k,127),k+=7);N--;)F[q++]=K}}var Q=F.subarray(0,j),R=F.subarray(j);E=y(Q),D=y(R),A=w(Q,E,1),x=w(R,D,1)}else T(1);if(k>M){g&&T(0);break}}c&&d(O+131072);for(var W=(1<>>4;if((k+=15&K)>M){g&&T(0);break}if(K||T(2),Z<256)f[O++]=Z;else{if(256==Z){Y=k,A=null;break}var $=Z-254;if(Z>264){var rr=a[q=Z-257];$=L(r,k,(1<>>4;if(er||T(3),k+=15&er,R=l[nr],nr>3&&(rr=i[nr],R+=U(r,k)&(1<M){g&&T(0);break}c&&d(O+131072);for(var tr=O+$;Or.length)&&(i=r.length);var o=new(r instanceof n?n:r instanceof t?t:e)(i-a);return o.set(r.subarray(a,i)),o}(f,0,O)},A=new e(0),x="undefined"!=typeof TextDecoder&&new TextDecoder;try{x.decode(A,{stream:!0})}catch(r){}return r.convert_streams=function(r){var e=new DataView(r),n=0;function t(){var r=e.getUint16(n);return n+=2,r}function a(){var r=e.getUint32(n);return n+=4,r}function i(r){m.setUint16(b,r),b+=2}function o(r){m.setUint32(b,r),b+=4}for(var f={signature:a(),flavor:a(),length:a(),numTables:t(),reserved:t(),totalSfntSize:a(),majorVersion:t(),minorVersion:t(),metaOffset:a(),metaLength:a(),metaOrigLength:a(),privOffset:a(),privLength:a()},u=0;Math.pow(2,u)<=f.numTables;)u++;u--;for(var v=16*Math.pow(2,u),s=16*f.numTables-v,l=12,c=[],g=0;g{let[skip,step]=range.split("+");skip=parseInt(skip,36),step=step?parseInt(step,36):0,joiningTypeMap.set(lastCode+=skip,m[type]);for(let i=step;i--;)joiningTypeMap.set(++lastCode,m[type])}))}}return joiningTypeMap.get(ch)||32}const formsToFeatures=[null,"isol","init","fina","medi"];function detectJoiningForms(str){const joiningForms=new Uint8Array(str.length);let prevJoiningType=32,prevForm=1,prevIndex=-1;for(let i=0;i65535&&i++)}return joiningForms}function wrapFontObj(typrFont){const glyphMap=Object.create(null),fontObj={unitsPerEm:typrFont.head.unitsPerEm,ascender:typrFont.hhea.ascender,descender:typrFont.hhea.descender,forEachGlyph(text,fontSize,letterSpacing,callback){let glyphX=0;const fontScale=1/fontObj.unitsPerEm*fontSize,glyphIndices=function stringToGlyphs(font,str){const glyphIds=[];for(let i=0;i65535&&i++,glyphIds.push(Typr.U.codeToGlyph(font,cc))}const gsub=font.GSUB;if(gsub){const{lookupList:lookupList,featureList:featureList}=gsub;let joiningForms;const supportedFeatures=/^(rlig|liga|mset|isol|init|fina|medi|half|pres|blws)$/,usedLookups=[];featureList.forEach((feature=>{if(supportedFeatures.test(feature.tag))for(let ti=0;ti{if(-1!==glyphIndex){let glyphObj=glyphMap[glyphIndex];if(!glyphObj){const{cmds:cmds,crds:crds}=Typr.U.glyphToPath(typrFont,glyphIndex);let xMin,yMin,xMax,yMax,path="",crdsIdx=0;for(let i=0,len=cmds.length;i1?",":"")+crds[crdsIdx++]}if(crds.length){xMin=yMin=1/0,xMax=yMax=-1/0;for(let i=0,len=crds.length;ixMax&&(xMax=x),y>yMax&&(yMax=y)}}else xMin=xMax=yMin=yMax=0;glyphObj=glyphMap[glyphIndex]={index:glyphIndex,advanceWidth:typrFont.hmtx.aWidth[glyphIndex],xMin:xMin,yMin:yMin,xMax:xMax,yMax:yMax,path:path,pathCommandCount:cmds.length}}-1!==prevGlyphIndex&&(glyphX+=Typr.U.getPairAdjustment(typrFont,prevGlyphIndex,glyphIndex)*fontScale),callback.call(null,glyphObj,glyphX,charIndex),glyphObj.advanceWidth&&(glyphX+=glyphObj.advanceWidth*fontScale),letterSpacing&&(glyphX+=letterSpacing*fontSize),prevGlyphIndex=glyphIndex}charIndex+=text.codePointAt(charIndex)>65535?2:1})),glyphX}};return fontObj}return function parse(buffer){const peek=new Uint8Array(buffer,0,4),tag=Typr._bin.readASCII(peek,0,4);if("wOFF"===tag)buffer=woff2otf(buffer);else if("wOF2"===tag)throw new Error("woff2 fonts not supported");return wrapFontObj(Typr.parse(buffer)[0])}}],init:(typrFactory,woff2otfFactory,parserFactory)=>parserFactory(typrFactory(),woff2otfFactory())}),CONFIG={defaultFontURL:"https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4mxM.woff",sdfGlyphSize:64,sdfMargin:1/16,sdfExponent:9,textureWidth:2048},tempColor=new three_module.Color;let hasRequested=!1;function now$1(){return(self.performance||Date).now()}const atlases=Object.create(null);function getTextRenderInfo(args,callback){hasRequested=!0,args=troika_three_text_esm_assign({},args);const totalStart=now$1();if(args.font=function toAbsoluteURL(path){linkEl||(linkEl="undefined"==typeof document?{}:document.createElement("a"));return linkEl.href=path,linkEl.href}(args.font||CONFIG.defaultFontURL),args.text=""+args.text,args.sdfGlyphSize=args.sdfGlyphSize||CONFIG.sdfGlyphSize,null!=args.colorRanges){let colors={};for(let key in args.colorRanges)if(args.colorRanges.hasOwnProperty(key)){let val=args.colorRanges[key];"number"!=typeof val&&(val=tempColor.set(val).getHex()),colors[key]=val}args.colorRanges=colors}Object.freeze(args);const{textureWidth:textureWidth,sdfExponent:sdfExponent}=CONFIG,{sdfGlyphSize:sdfGlyphSize}=args,glyphsPerRow=textureWidth/sdfGlyphSize*4;let atlas=atlases[sdfGlyphSize];if(!atlas){const canvas=document.createElement("canvas");canvas.width=textureWidth,canvas.height=256*sdfGlyphSize/glyphsPerRow,atlas=atlases[sdfGlyphSize]={glyphCount:0,sdfGlyphSize:sdfGlyphSize,sdfCanvas:canvas,sdfTexture:new three_module.Texture(canvas,void 0,void 0,void 0,three_module.LinearFilter,three_module.LinearFilter),contextLost:!1,glyphsByFont:new Map},atlas.sdfTexture.generateMipmaps=!1,function initContextLossHandling(atlas){const canvas=atlas.sdfCanvas;canvas.addEventListener("webglcontextlost",(event=>{console.log("Context Lost",event),event.preventDefault(),atlas.contextLost=!0})),canvas.addEventListener("webglcontextrestored",(event=>{console.log("Context Restored",event),atlas.contextLost=!1;const promises=[];atlas.glyphsByFont.forEach((glyphMap=>{glyphMap.forEach((glyph=>{promises.push(generateGlyphSDF(glyph,atlas,!0))}))})),DefaultThenable.all(promises).then((()=>{safariPre15Workaround(atlas),atlas.sdfTexture.needsUpdate=!0}))}))}(atlas)}const{sdfTexture:sdfTexture,sdfCanvas:sdfCanvas}=atlas;let fontGlyphs=atlas.glyphsByFont.get(args.font);fontGlyphs||atlas.glyphsByFont.set(args.font,fontGlyphs=new Map),typesetInWorker(args).then((result=>{const{glyphIds:glyphIds,glyphPositions:glyphPositions,fontSize:fontSize,unitsPerEm:unitsPerEm,timings:timings}=result,neededSDFs=[],glyphBounds=new Float32Array(4*glyphIds.length),fontSizeMult=fontSize/unitsPerEm;let boundsIdx=0,positionsIdx=0;const quadsStart=now$1();glyphIds.forEach(((glyphId,i)=>{let glyphInfo=fontGlyphs.get(glyphId);if(!glyphInfo){const{path:path,pathBounds:pathBounds}=result.glyphData[glyphId],fontUnitsMargin=Math.max(pathBounds[2]-pathBounds[0],pathBounds[3]-pathBounds[1])/sdfGlyphSize*(CONFIG.sdfMargin*sdfGlyphSize+.5),atlasIndex=atlas.glyphCount++,sdfViewBox=[pathBounds[0]-fontUnitsMargin,pathBounds[1]-fontUnitsMargin,pathBounds[2]+fontUnitsMargin,pathBounds[3]+fontUnitsMargin];fontGlyphs.set(glyphId,glyphInfo={path:path,atlasIndex:atlasIndex,sdfViewBox:sdfViewBox}),neededSDFs.push(glyphInfo)}const{sdfViewBox:sdfViewBox}=glyphInfo,posX=glyphPositions[positionsIdx++],posY=glyphPositions[positionsIdx++];glyphBounds[boundsIdx++]=posX+sdfViewBox[0]*fontSizeMult,glyphBounds[boundsIdx++]=posY+sdfViewBox[1]*fontSizeMult,glyphBounds[boundsIdx++]=posX+sdfViewBox[2]*fontSizeMult,glyphBounds[boundsIdx++]=posY+sdfViewBox[3]*fontSizeMult,glyphIds[i]=glyphInfo.atlasIndex})),timings.quads=(timings.quads||0)+(now$1()-quadsStart);const sdfStart=now$1();timings.sdf={};const currentHeight=sdfCanvas.height,neededRows=Math.ceil(atlas.glyphCount/glyphsPerRow),neededHeight=Math.pow(2,Math.ceil(Math.log2(neededRows*sdfGlyphSize)));neededHeight>currentHeight&&(console.info(`Increasing SDF texture size ${currentHeight}->${neededHeight}`),resizeWebGLCanvasWithoutClearing(sdfCanvas,textureWidth,neededHeight),sdfTexture.dispose()),DefaultThenable.all(neededSDFs.map((glyphInfo=>generateGlyphSDF(glyphInfo,atlas,args.gpuAccelerateSDF).then((({timing:timing})=>{timings.sdf[glyphInfo.atlasIndex]=timing}))))).then((()=>{neededSDFs.length&&!atlas.contextLost&&(safariPre15Workaround(atlas),sdfTexture.needsUpdate=!0),timings.sdfTotal=now$1()-sdfStart,timings.total=now$1()-totalStart,callback(Object.freeze({parameters:args,sdfTexture:sdfTexture,sdfGlyphSize:sdfGlyphSize,sdfExponent:sdfExponent,glyphBounds:glyphBounds,glyphAtlasIndices:glyphIds,glyphColors:result.glyphColors,caretPositions:result.caretPositions,caretHeight:result.caretHeight,chunkedBounds:result.chunkedBounds,ascender:result.ascender,descender:result.descender,lineHeight:result.lineHeight,topBaseline:result.topBaseline,blockBounds:result.blockBounds,visibleBounds:result.visibleBounds,timings:result.timings,get totalBounds(){return console.log("totalBounds deprecated, use blockBounds instead"),result.blockBounds},get totalBlockSize(){console.log("totalBlockSize deprecated, use blockBounds instead");const[x0,y0,x1,y1]=result.blockBounds;return[x1-x0,y1-y0]}}))}))})),DefaultThenable.all([]).then((()=>{atlas.contextLost||function warmUpSDFCanvas(canvas){canvas._warm||(mainThreadGenerator.webgl.isSupported(canvas),canvas._warm=!0)}(sdfCanvas)}))}function generateGlyphSDF({path:path,atlasIndex:atlasIndex,sdfViewBox:sdfViewBox},{sdfGlyphSize:sdfGlyphSize,sdfCanvas:sdfCanvas,contextLost:contextLost},useGPU){if(contextLost)return Promise.resolve({timing:-1});const{textureWidth:textureWidth,sdfExponent:sdfExponent}=CONFIG,maxDist=Math.max(sdfViewBox[2]-sdfViewBox[0],sdfViewBox[3]-sdfViewBox[1]),squareIndex=Math.floor(atlasIndex/4);return function generateSDF(width,height,path,viewBox,distance,exponent,canvas,x,y,channel,useWebGL=!0){return useWebGL?generateSDF_GL(width,height,path,viewBox,distance,exponent,canvas,x,y,channel).then(null,(err=>(warned||(console.warn("WebGL SDF generation failed, falling back to JS",err),warned=!0),generateSDF_JS_Worker(width,height,path,viewBox,distance,exponent,canvas,x,y,channel)))):generateSDF_JS_Worker(width,height,path,viewBox,distance,exponent,canvas,x,y,channel)}(sdfGlyphSize,sdfGlyphSize,path,sdfViewBox,maxDist,sdfExponent,sdfCanvas,squareIndex%(textureWidth/sdfGlyphSize)*sdfGlyphSize,Math.floor(squareIndex/(textureWidth/sdfGlyphSize))*sdfGlyphSize,atlasIndex%4,useGPU)}function troika_three_text_esm_assign(toObj,fromObj){for(let key in fromObj)fromObj.hasOwnProperty(key)&&(toObj[key]=fromObj[key]);return toObj}let linkEl;function safariPre15Workaround(atlas){if("function"!=typeof createImageBitmap){console.info("Safari<15: applying SDF canvas workaround");const{sdfCanvas:sdfCanvas,sdfTexture:sdfTexture}=atlas,{width:width,height:height}=sdfCanvas,gl=atlas.sdfCanvas.getContext("webgl");let pixels=sdfTexture.image.data;pixels&&pixels.length===width*height*4||(pixels=new Uint8Array(width*height*4),sdfTexture.image={width:width,height:height,data:pixels},sdfTexture.flipY=!1,sdfTexture.isDataTexture=!0),gl.readPixels(0,0,width,height,gl.RGBA,gl.UNSIGNED_BYTE,pixels)}}const typesetterWorkerModule=defineWorkerModule({name:"Typesetter",dependencies:[CONFIG,workerModule,function createTypesetter(fontParser,bidi,config){const{defaultFontURL:defaultFontURL}=config,fonts=Object.create(null),INF=1/0,DEFAULT_IGNORABLE_CHARS=/[\u00AD\u034F\u061C\u115F-\u1160\u17B4-\u17B5\u180B-\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\u3164\uFE00-\uFE0F\uFEFF\uFFA0\uFFF0-\uFFF8]/,BREAK_AFTER_CHARS=/[\s\-\u007C\u00AD\u2010\u2012-\u2014\u2027\u2056\u2E17\u2E40]/;function loadFont(fontUrl,callback){fontUrl||(fontUrl=defaultFontURL);let font=fonts[fontUrl];font?font.pending?font.pending.push(callback):callback(font):(fonts[fontUrl]={pending:[callback]},function doLoadFont(url,callback){!function tryLoad(){const onError=err=>{console.error(`Failure loading font ${url}${url===defaultFontURL?"":"; trying fallback"}`,err),url!==defaultFontURL&&(url=defaultFontURL,tryLoad())};try{const request=new XMLHttpRequest;request.open("get",url,!0),request.responseType="arraybuffer",request.onload=function(){if(request.status>=400)onError(new Error(request.statusText));else if(request.status>0)try{const fontObj=fontParser(request.response);callback(fontObj)}catch(e){onError(e)}},request.onerror=onError,request.send()}catch(err){onError(err)}}()}(fontUrl,(fontObj=>{let callbacks=fonts[fontUrl].pending;fonts[fontUrl]=fontObj,callbacks.forEach((cb=>cb(fontObj)))})))}function typeset({text:text="",font:font=defaultFontURL,sdfGlyphSize:sdfGlyphSize=64,fontSize:fontSize=1,letterSpacing:letterSpacing=0,lineHeight:lineHeight="normal",maxWidth:maxWidth=INF,direction:direction,textAlign:textAlign="left",textIndent:textIndent=0,whiteSpace:whiteSpace="normal",overflowWrap:overflowWrap="normal",anchorX:anchorX=0,anchorY:anchorY=0,includeCaretPositions:includeCaretPositions=!1,chunkedBoundsSize:chunkedBoundsSize=8192,colorRanges:colorRanges=null},callback,metricsOnly=!1){const mainStart=now(),timings={fontLoad:0,typesetting:0};text.indexOf("\r")>-1&&(console.info("Typesetter: got text with \\r chars; normalizing to \\n"),text=text.replace(/\r\n/g,"\n").replace(/\r/g,"\n")),fontSize=+fontSize,letterSpacing=+letterSpacing,maxWidth=+maxWidth,lineHeight=lineHeight||"normal",textIndent=+textIndent,loadFont(font,(fontObj=>{const hasMaxWidth=isFinite(maxWidth);let glyphIds=null,glyphPositions=null,glyphData=null,glyphColors=null,caretPositions=null,visibleBounds=null,chunkedBounds=null,maxLineWidth=0,renderableGlyphCount=0,canWrap="nowrap"!==whiteSpace;const{ascender:ascender,descender:descender,unitsPerEm:unitsPerEm}=fontObj;timings.fontLoad=now()-mainStart;const typesetStart=now(),fontSizeMult=fontSize/unitsPerEm;"normal"===lineHeight&&(lineHeight=(ascender-descender)/unitsPerEm);const halfLeading=((lineHeight*=fontSize)-(ascender-descender)*fontSizeMult)/2,topBaseline=-(ascender*fontSizeMult+halfLeading),caretHeight=Math.min(lineHeight,(ascender-descender)*fontSizeMult),caretBottomOffset=(ascender+descender)/2*fontSizeMult-caretHeight/2;let lineXOffset=textIndent,currentLine=new TextLine;const lines=[currentLine];fontObj.forEachGlyph(text,fontSize,letterSpacing,((glyphObj,glyphX,charIndex)=>{const char=text.charAt(charIndex),glyphWidth=glyphObj.advanceWidth*fontSizeMult,curLineCount=currentLine.count;let nextLine;if("isEmpty"in glyphObj||(glyphObj.isWhitespace=!!char&&/\s/.test(char),glyphObj.canBreakAfter=!!char&&BREAK_AFTER_CHARS.test(char),glyphObj.isEmpty=glyphObj.xMin===glyphObj.xMax||glyphObj.yMin===glyphObj.yMax||DEFAULT_IGNORABLE_CHARS.test(char)),glyphObj.isWhitespace||glyphObj.isEmpty||renderableGlyphCount++,canWrap&&hasMaxWidth&&!glyphObj.isWhitespace&&glyphX+glyphWidth+lineXOffset>maxWidth&&curLineCount){if(currentLine.glyphAt(curLineCount-1).glyphObj.canBreakAfter)nextLine=new TextLine,lineXOffset=-glyphX;else for(let i=curLineCount;i--;){if(0===i&&"break-word"===overflowWrap){nextLine=new TextLine,lineXOffset=-glyphX;break}if(currentLine.glyphAt(i).glyphObj.canBreakAfter){nextLine=currentLine.splitAt(i+1);const adjustX=nextLine.glyphAt(0).x;lineXOffset-=adjustX;for(let j=nextLine.count;j--;)nextLine.glyphAt(j).x-=adjustX;break}}nextLine&&(currentLine.isSoftWrapped=!0,currentLine=nextLine,lines.push(currentLine),maxLineWidth=maxWidth)}let fly=currentLine.glyphAt(currentLine.count);fly.glyphObj=glyphObj,fly.x=glyphX+lineXOffset,fly.width=glyphWidth,fly.charIndex=charIndex,"\n"===char&&(currentLine=new TextLine,lines.push(currentLine),lineXOffset=-(glyphX+glyphWidth+letterSpacing*fontSize)+textIndent)})),lines.forEach((line=>{for(let i=line.count;i--;){let{glyphObj:glyphObj,x:x,width:width}=line.glyphAt(i);if(!glyphObj.isWhitespace)return line.width=x+width,void(line.width>maxLineWidth&&(maxLineWidth=line.width))}}));let anchorXOffset=0,anchorYOffset=0;if(anchorX&&("number"==typeof anchorX?anchorXOffset=-anchorX:"string"==typeof anchorX&&(anchorXOffset=-maxLineWidth*("left"===anchorX?0:"center"===anchorX?.5:"right"===anchorX?1:parsePercent(anchorX)))),anchorY)if("number"==typeof anchorY)anchorYOffset=-anchorY;else if("string"==typeof anchorY){let height=lines.length*lineHeight;anchorYOffset="top"===anchorY?0:"top-baseline"===anchorY?-topBaseline:"middle"===anchorY?height/2:"bottom"===anchorY?height:"bottom-baseline"===anchorY?height-halfLeading+descender*fontSizeMult:parsePercent(anchorY)*height}if(!metricsOnly){const bidiLevelsResult=bidi.getEmbeddingLevels(text,direction);glyphIds=new Uint16Array(renderableGlyphCount),glyphPositions=new Float32Array(2*renderableGlyphCount),glyphData={},visibleBounds=[INF,INF,-1/0,-1/0],chunkedBounds=[];let lineYOffset=topBaseline;includeCaretPositions&&(caretPositions=new Float32Array(3*text.length)),colorRanges&&(glyphColors=new Uint8Array(3*renderableGlyphCount));let chunk,currentColor,renderableGlyphIndex=0,prevCharIndex=-1,colorCharIndex=-1;if(lines.forEach(((line,lineIndex)=>{let{count:lineGlyphCount,width:lineWidth}=line;if(lineGlyphCount>0){let trailingWhitespaceCount=0;for(let i=lineGlyphCount;i--&&line.glyphAt(i).glyphObj.isWhitespace;)trailingWhitespaceCount++;let lineXOffset=0,justifyAdjust=0;if("center"===textAlign)lineXOffset=(maxLineWidth-lineWidth)/2;else if("right"===textAlign)lineXOffset=maxLineWidth-lineWidth;else if("justify"===textAlign&&line.isSoftWrapped){let whitespaceCount=0;for(let i=lineGlyphCount-trailingWhitespaceCount;i--;)line.glyphAt(i).glyphObj.isWhitespace&&whitespaceCount++;justifyAdjust=(maxLineWidth-lineWidth)/whitespaceCount}if(justifyAdjust||lineXOffset){let justifyOffset=0;for(let i=0;i=start){let startInLine=i,endInLine=i;for(;endInLineend)break;endInLineglyphObj=g;for(let i=0;i1&&fillLigatureCaretPositions(caretPositions,prevCharIndex,ligCount),prevCharIndex=charIndex}if(colorRanges){const{charIndex:charIndex}=glyphInfo;for(;charIndex>colorCharIndex;)colorCharIndex++,colorRanges.hasOwnProperty(colorCharIndex)&&(currentColor=colorRanges[colorCharIndex])}if(!glyphObj.isWhitespace&&!glyphObj.isEmpty){const idx=renderableGlyphIndex++;glyphData[glyphId]||(glyphData[glyphId]={path:glyphObj.path,pathBounds:[glyphObj.xMin,glyphObj.yMin,glyphObj.xMax,glyphObj.yMax]});const glyphX=glyphInfo.x+anchorXOffset,glyphY=lineYOffset+anchorYOffset;glyphPositions[2*idx]=glyphX,glyphPositions[2*idx+1]=glyphY;const visX0=glyphX+glyphObj.xMin*fontSizeMult,visY0=glyphY+glyphObj.yMin*fontSizeMult,visX1=glyphX+glyphObj.xMax*fontSizeMult,visY1=glyphY+glyphObj.yMax*fontSizeMult;visX0visibleBounds[2]&&(visibleBounds[2]=visX1),visY1>visibleBounds[3]&&(visibleBounds[3]=visY1),idx%chunkedBoundsSize==0&&(chunk={start:idx,end:idx,rect:[INF,INF,-1/0,-1/0]},chunkedBounds.push(chunk)),chunk.end++;const chunkRect=chunk.rect;if(visX0chunkRect[2]&&(chunkRect[2]=visX1),visY1>chunkRect[3]&&(chunkRect[3]=visY1),glyphIds[idx]=glyphId,colorRanges){const start=3*idx;glyphColors[start]=currentColor>>16&255,glyphColors[start+1]=currentColor>>8&255,glyphColors[start+2]=255¤tColor}}}}lineYOffset-=lineHeight})),caretPositions){const ligCount=text.length-prevCharIndex;ligCount>1&&fillLigatureCaretPositions(caretPositions,prevCharIndex,ligCount)}}timings.typesetting=now()-typesetStart,callback({glyphIds:glyphIds,glyphPositions:glyphPositions,glyphData:glyphData,caretPositions:caretPositions,caretHeight:caretHeight,glyphColors:glyphColors,chunkedBounds:chunkedBounds,fontSize:fontSize,unitsPerEm:unitsPerEm,ascender:ascender*fontSizeMult,descender:descender*fontSizeMult,lineHeight:lineHeight,topBaseline:topBaseline,blockBounds:[anchorXOffset,anchorYOffset-lines.length*lineHeight,anchorXOffset+maxLineWidth,anchorYOffset],visibleBounds:visibleBounds,timings:timings})}))}function parsePercent(str){let match=str.match(/^([\d.]+)%$/),pct=match?parseFloat(match[1]):NaN;return isNaN(pct)?0:pct/100}function fillLigatureCaretPositions(caretPositions,ligStartIndex,ligCount){const ligStartX=caretPositions[3*ligStartIndex],ligEndX=caretPositions[3*ligStartIndex+1],ligY=caretPositions[3*ligStartIndex+2],guessedAdvanceX=(ligEndX-ligStartX)/ligCount;for(let i=0;i(Object.defineProperty(obj,prop,{get(){return this.data[this.index*textLineProps.length+i]},set(val){this.data[this.index*textLineProps.length+i]=val}}),obj)),{data:null,index:0}),{typeset:typeset,measure:function measure(args,callback){typeset(args,(result=>{const[x0,y0,x1,y1]=result.blockBounds;callback({width:x1-x0,height:y1-y0})}),{metricsOnly:!0})},loadFont:loadFont}},bidi],init(config,fontParser,createTypesetter,bidiFactory){const{defaultFontURL:defaultFontURL}=config;return createTypesetter(fontParser,bidiFactory(),{defaultFontURL:defaultFontURL})}}),typesetInWorker=defineWorkerModule({name:"Typesetter",dependencies:[typesetterWorkerModule,ThenableWorkerModule],init:(typesetter,Thenable)=>function(args){const thenable=new Thenable;return typesetter.typeset(args,thenable.resolve),thenable},getTransferables(result){const transferables=[result.glyphPositions.buffer,result.glyphIds.buffer];return result.caretPositions&&transferables.push(result.caretPositions.buffer),result.glyphColors&&transferables.push(result.glyphColors.buffer),transferables}});const GlyphsGeometry=(()=>{const templateGeometries={};class GlyphsGeometry extends three_module.InstancedBufferGeometry{constructor(){super(),this.detail=1,this.curveRadius=0,this.groups=[{start:0,count:1/0,materialIndex:0},{start:0,count:1/0,materialIndex:1}],this.boundingSphere=new three_module.Sphere,this.boundingBox=new three_module.Box3}computeBoundingSphere(){}computeBoundingBox(){}setSide(side){const verts=this.getIndex().count;this.setDrawRange(side===three_module.BackSide?verts/2:0,side===three_module.DoubleSide?verts:verts/2)}set detail(detail){if(detail!==this._detail){this._detail=detail,("number"!=typeof detail||detail<1)&&(detail=1);let tpl=function getTemplateGeometry(detail){let geom=templateGeometries[detail];if(!geom){const front=new three_module.PlaneBufferGeometry(1,1,detail,detail),back=front.clone(),frontAttrs=front.attributes,backAttrs=back.attributes,combined=new three_module.BufferGeometry,vertCount=frontAttrs.uv.count;for(let i=0;i{combined.setAttribute(name,new three_module.Float32BufferAttribute([...frontAttrs[name].array,...backAttrs[name].array],frontAttrs[name].itemSize))})),combined.setIndex([...front.index.array,...back.index.array.map((n=>n+vertCount))]),combined.translate(.5,.5,0),geom=templateGeometries[detail]=combined}return geom}(detail);["position","normal","uv"].forEach((attr=>{this.attributes[attr]=tpl.attributes[attr].clone()})),this.setIndex(tpl.getIndex().clone())}}get detail(){return this._detail}set curveRadius(r){r!==this._curveRadius&&(this._curveRadius=r,this._updateBounds())}get curveRadius(){return this._curveRadius}updateGlyphs(glyphBounds,glyphAtlasIndices,blockBounds,chunkedBounds,glyphColors){updateBufferAttr(this,"aTroikaGlyphBounds",glyphBounds,4),updateBufferAttr(this,"aTroikaGlyphIndex",glyphAtlasIndices,1),updateBufferAttr(this,"aTroikaGlyphColor",glyphColors,3),this._blockBounds=blockBounds,this._chunkedBounds=chunkedBounds,setInstanceCount(this,glyphAtlasIndices.length),this._updateBounds()}_updateBounds(){const bounds=this._blockBounds;if(bounds){const{curveRadius:curveRadius,boundingBox:bbox}=this;if(curveRadius){const{PI:PI,floor:floor,min:min,max:max,sin:sin,cos:cos}=Math,halfPi=PI/2,twoPi=2*PI,absR=Math.abs(curveRadius),leftAngle=bounds[0]/absR,rightAngle=bounds[2]/absR,minX=floor((leftAngle+halfPi)/twoPi)!==floor((rightAngle+halfPi)/twoPi)?-absR:min(sin(leftAngle)*absR,sin(rightAngle)*absR),maxX=floor((leftAngle-halfPi)/twoPi)!==floor((rightAngle-halfPi)/twoPi)?absR:max(sin(leftAngle)*absR,sin(rightAngle)*absR),maxZ=floor((leftAngle+PI)/twoPi)!==floor((rightAngle+PI)/twoPi)?2*absR:max(absR-cos(leftAngle)*absR,absR-cos(rightAngle)*absR);bbox.min.set(minX,bounds[1],curveRadius<0?-maxZ:0),bbox.max.set(maxX,bounds[3],curveRadius<0?0:maxZ)}else bbox.min.set(bounds[0],bounds[1],0),bbox.max.set(bounds[2],bounds[3],0);bbox.getBoundingSphere(this.boundingSphere)}}applyClipRect(clipRect){let count=this.getAttribute("aTroikaGlyphIndex").count,chunks=this._chunkedBounds;if(chunks)for(let i=chunks.length;i--;){count=chunks[i].end;let rect=chunks[i].rect;if(rect[1]clipRect.y&&rect[0]clipRect.x)break}setInstanceCount(this,count)}}function updateBufferAttr(geom,attrName,newArray,itemSize){const attr=geom.getAttribute(attrName);newArray?attr&&attr.array.length===newArray.length?(attr.array.set(newArray),attr.needsUpdate=!0):(geom.setAttribute(attrName,new three_module.InstancedBufferAttribute(newArray,itemSize)),delete geom._maxInstanceCount,geom.dispose()):attr&&geom.deleteAttribute(attrName)}function setInstanceCount(geom,count){geom[geom.hasOwnProperty("instanceCount")?"instanceCount":"maxInstancedCount"]=count}return GlyphsGeometry.prototype.setAttribute||(GlyphsGeometry.prototype.setAttribute=function(name,attribute){return this.attributes[name]=attribute,this}),GlyphsGeometry})();const Text=(()=>{const defaultMaterial=new three_module.MeshBasicMaterial({color:16777215,side:three_module.DoubleSide,transparent:!0}),tempMat4=new three_module.Matrix4,tempVec3a=new three_module.Vector3,tempVec3b=new three_module.Vector3,tempArray=[],origin=new three_module.Vector3;function first(o){return Array.isArray(o)?o[0]:o}let getFlatRaycastMesh=()=>{const mesh=new three_module.Mesh(new three_module.PlaneBufferGeometry(1,1),defaultMaterial);return getFlatRaycastMesh=()=>mesh,mesh},getCurvedRaycastMesh=()=>{const mesh=new three_module.Mesh(new three_module.PlaneBufferGeometry(1,1,32,1),defaultMaterial);return getCurvedRaycastMesh=()=>mesh,mesh};const syncStartEvent={type:"syncstart"},syncCompleteEvent={type:"synccomplete"},SYNCABLE_PROPS=["font","fontSize","letterSpacing","lineHeight","maxWidth","overflowWrap","text","direction","textAlign","textIndent","whiteSpace","anchorX","anchorY","colorRanges","sdfGlyphSize"],COPYABLE_PROPS=SYNCABLE_PROPS.concat("material","color","depthOffset","clipRect","curveRadius","orientation","glyphGeometryDetail");class Text extends three_module.Mesh{constructor(){super(new GlyphsGeometry,null),this.text="",this.anchorX=0,this.anchorY=0,this.curveRadius=0,this.direction="auto",this.font=null,this.fontSize=.1,this.letterSpacing=0,this.lineHeight="normal",this.maxWidth=1/0,this.overflowWrap="normal",this.textAlign="left",this.textIndent=0,this.whiteSpace="normal",this.material=null,this.color=null,this.colorRanges=null,this.outlineWidth=0,this.outlineColor=0,this.outlineOpacity=1,this.outlineBlur=0,this.outlineOffsetX=0,this.outlineOffsetY=0,this.strokeWidth=0,this.strokeColor=8421504,this.strokeOpacity=1,this.fillOpacity=1,this.depthOffset=0,this.clipRect=null,this.orientation="+x+y",this.glyphGeometryDetail=1,this.sdfGlyphSize=null,this.gpuAccelerateSDF=!0,this.debugSDF=!1}sync(callback){this._needsSync&&(this._needsSync=!1,this._isSyncing?(this._queuedSyncs||(this._queuedSyncs=[])).push(callback):(this._isSyncing=!0,this.dispatchEvent(syncStartEvent),getTextRenderInfo({text:this.text,font:this.font,fontSize:this.fontSize||.1,letterSpacing:this.letterSpacing||0,lineHeight:this.lineHeight||"normal",maxWidth:this.maxWidth,direction:this.direction||"auto",textAlign:this.textAlign,textIndent:this.textIndent,whiteSpace:this.whiteSpace,overflowWrap:this.overflowWrap,anchorX:this.anchorX,anchorY:this.anchorY,colorRanges:this.colorRanges,includeCaretPositions:!0,sdfGlyphSize:this.sdfGlyphSize,gpuAccelerateSDF:this.gpuAccelerateSDF},(textRenderInfo=>{this._isSyncing=!1,this._textRenderInfo=textRenderInfo,this.geometry.updateGlyphs(textRenderInfo.glyphBounds,textRenderInfo.glyphAtlasIndices,textRenderInfo.blockBounds,textRenderInfo.chunkedBounds,textRenderInfo.glyphColors);const queued=this._queuedSyncs;queued&&(this._queuedSyncs=null,this._needsSync=!0,this.sync((()=>{queued.forEach((fn=>fn&&fn()))}))),this.dispatchEvent(syncCompleteEvent),callback&&callback()}))))}onBeforeRender(renderer,scene,camera,geometry,material,group){this.sync(),material.isTroikaTextMaterial&&this._prepareForRender(material),material._hadOwnSide=material.hasOwnProperty("side"),this.geometry.setSide(material._actualSide=material.side),material.side=three_module.FrontSide}onAfterRender(renderer,scene,camera,geometry,material,group){material._hadOwnSide?material.side=material._actualSide:delete material.side}dispose(){this.geometry.dispose()}get textRenderInfo(){return this._textRenderInfo||null}get material(){let derivedMaterial=this._derivedMaterial;const baseMaterial=this._baseMaterial||this._defaultMaterial||(this._defaultMaterial=defaultMaterial.clone());if(derivedMaterial&&derivedMaterial.baseMaterial===baseMaterial||(derivedMaterial=this._derivedMaterial=function createTextDerivedMaterial(baseMaterial){const textMaterial=createDerivedMaterial(baseMaterial,{chained:!0,extensions:{derivatives:!0},uniforms:{uTroikaSDFTexture:{value:null},uTroikaSDFTextureSize:{value:new three_module.Vector2},uTroikaSDFGlyphSize:{value:0},uTroikaSDFExponent:{value:0},uTroikaTotalBounds:{value:new three_module.Vector4(0,0,0,0)},uTroikaClipRect:{value:new three_module.Vector4(0,0,0,0)},uTroikaDistanceOffset:{value:0},uTroikaOutlineOpacity:{value:0},uTroikaFillOpacity:{value:1},uTroikaPositionOffset:{value:new three_module.Vector2},uTroikaCurveRadius:{value:0},uTroikaBlurRadius:{value:0},uTroikaStrokeWidth:{value:0},uTroikaStrokeColor:{value:new three_module.Color},uTroikaStrokeOpacity:{value:1},uTroikaOrient:{value:new three_module.Matrix3},uTroikaUseGlyphColors:{value:!0},uTroikaSDFDebug:{value:!1}},vertexDefs:"\nuniform vec2 uTroikaSDFTextureSize;\nuniform float uTroikaSDFGlyphSize;\nuniform vec4 uTroikaTotalBounds;\nuniform vec4 uTroikaClipRect;\nuniform mat3 uTroikaOrient;\nuniform bool uTroikaUseGlyphColors;\nuniform float uTroikaDistanceOffset;\nuniform float uTroikaBlurRadius;\nuniform vec2 uTroikaPositionOffset;\nuniform float uTroikaCurveRadius;\nattribute vec4 aTroikaGlyphBounds;\nattribute float aTroikaGlyphIndex;\nattribute vec3 aTroikaGlyphColor;\nvarying vec2 vTroikaGlyphUV;\nvarying vec4 vTroikaTextureUVBounds;\nvarying float vTroikaTextureChannel;\nvarying vec3 vTroikaGlyphColor;\nvarying vec2 vTroikaGlyphDimensions;\n",vertexTransform:"\nvec4 bounds = aTroikaGlyphBounds;\nbounds.xz += uTroikaPositionOffset.x;\nbounds.yw -= uTroikaPositionOffset.y;\n\nvec4 outlineBounds = vec4(\n bounds.xy - uTroikaDistanceOffset - uTroikaBlurRadius,\n bounds.zw + uTroikaDistanceOffset + uTroikaBlurRadius\n);\nvec4 clippedBounds = vec4(\n clamp(outlineBounds.xy, uTroikaClipRect.xy, uTroikaClipRect.zw),\n clamp(outlineBounds.zw, uTroikaClipRect.xy, uTroikaClipRect.zw)\n);\n\nvec2 clippedXY = (mix(clippedBounds.xy, clippedBounds.zw, position.xy) - bounds.xy) / (bounds.zw - bounds.xy);\n\nposition.xy = mix(bounds.xy, bounds.zw, clippedXY);\n\nuv = (position.xy - uTroikaTotalBounds.xy) / (uTroikaTotalBounds.zw - uTroikaTotalBounds.xy);\n\nfloat rad = uTroikaCurveRadius;\nif (rad != 0.0) {\n float angle = position.x / rad;\n position.xz = vec2(sin(angle) * rad, rad - cos(angle) * rad);\n normal.xz = vec2(sin(angle), cos(angle));\n}\n \nposition = uTroikaOrient * position;\nnormal = uTroikaOrient * normal;\n\nvTroikaGlyphUV = clippedXY.xy;\nvTroikaGlyphDimensions = vec2(bounds[2] - bounds[0], bounds[3] - bounds[1]);\n\n\nfloat txCols = uTroikaSDFTextureSize.x / uTroikaSDFGlyphSize;\nvec2 txUvPerSquare = uTroikaSDFGlyphSize / uTroikaSDFTextureSize;\nvec2 txStartUV = txUvPerSquare * vec2(\n mod(floor(aTroikaGlyphIndex / 4.0), txCols),\n floor(floor(aTroikaGlyphIndex / 4.0) / txCols)\n);\nvTroikaTextureUVBounds = vec4(txStartUV, vec2(txStartUV) + txUvPerSquare);\nvTroikaTextureChannel = mod(aTroikaGlyphIndex, 4.0);\n",fragmentDefs:"\nuniform sampler2D uTroikaSDFTexture;\nuniform vec2 uTroikaSDFTextureSize;\nuniform float uTroikaSDFGlyphSize;\nuniform float uTroikaSDFExponent;\nuniform float uTroikaDistanceOffset;\nuniform float uTroikaFillOpacity;\nuniform float uTroikaOutlineOpacity;\nuniform float uTroikaBlurRadius;\nuniform vec3 uTroikaStrokeColor;\nuniform float uTroikaStrokeWidth;\nuniform float uTroikaStrokeOpacity;\nuniform bool uTroikaSDFDebug;\nvarying vec2 vTroikaGlyphUV;\nvarying vec4 vTroikaTextureUVBounds;\nvarying float vTroikaTextureChannel;\nvarying vec2 vTroikaGlyphDimensions;\n\nfloat troikaSdfValueToSignedDistance(float alpha) {\n // Inverse of exponential encoding in webgl-sdf-generator\n \n float maxDimension = max(vTroikaGlyphDimensions.x, vTroikaGlyphDimensions.y);\n float absDist = (1.0 - pow(2.0 * (alpha > 0.5 ? 1.0 - alpha : alpha), 1.0 / uTroikaSDFExponent)) * maxDimension;\n float signedDist = absDist * (alpha > 0.5 ? -1.0 : 1.0);\n return signedDist;\n}\n\nfloat troikaGlyphUvToSdfValue(vec2 glyphUV) {\n vec2 textureUV = mix(vTroikaTextureUVBounds.xy, vTroikaTextureUVBounds.zw, glyphUV);\n vec4 rgba = texture2D(uTroikaSDFTexture, textureUV);\n float ch = floor(vTroikaTextureChannel + 0.5); //NOTE: can't use round() in WebGL1\n return ch == 0.0 ? rgba.r : ch == 1.0 ? rgba.g : ch == 2.0 ? rgba.b : rgba.a;\n}\n\nfloat troikaGlyphUvToDistance(vec2 uv) {\n return troikaSdfValueToSignedDistance(troikaGlyphUvToSdfValue(uv));\n}\n\nfloat troikaGetAADist() {\n \n #if defined(GL_OES_standard_derivatives) || __VERSION__ >= 300\n return length(fwidth(vTroikaGlyphUV * vTroikaGlyphDimensions)) * 0.5;\n #else\n return vTroikaGlyphDimensions.x / 64.0;\n #endif\n}\n\nfloat troikaGetFragDistValue() {\n vec2 clampedGlyphUV = clamp(vTroikaGlyphUV, 0.5 / uTroikaSDFGlyphSize, 1.0 - 0.5 / uTroikaSDFGlyphSize);\n float distance = troikaGlyphUvToDistance(clampedGlyphUV);\n \n // Extrapolate distance when outside bounds:\n distance += clampedGlyphUV == vTroikaGlyphUV ? 0.0 : \n length((vTroikaGlyphUV - clampedGlyphUV) * vTroikaGlyphDimensions);\n\n \n\n return distance;\n}\n\nfloat troikaGetEdgeAlpha(float distance, float distanceOffset, float aaDist) {\n #if defined(IS_DEPTH_MATERIAL) || defined(IS_DISTANCE_MATERIAL)\n float alpha = step(-distanceOffset, -distance);\n #else\n\n float alpha = smoothstep(\n distanceOffset + aaDist,\n distanceOffset - aaDist,\n distance\n );\n #endif\n\n return alpha;\n}\n",fragmentColorTransform:"\nfloat aaDist = troikaGetAADist();\nfloat fragDistance = troikaGetFragDistValue();\nfloat edgeAlpha = uTroikaSDFDebug ?\n troikaGlyphUvToSdfValue(vTroikaGlyphUV) :\n troikaGetEdgeAlpha(fragDistance, uTroikaDistanceOffset, max(aaDist, uTroikaBlurRadius));\n\n#if !defined(IS_DEPTH_MATERIAL) && !defined(IS_DISTANCE_MATERIAL)\nvec4 fillRGBA = gl_FragColor;\nfillRGBA.a *= uTroikaFillOpacity;\nvec4 strokeRGBA = uTroikaStrokeWidth == 0.0 ? fillRGBA : vec4(uTroikaStrokeColor, uTroikaStrokeOpacity);\nif (fillRGBA.a == 0.0) fillRGBA.rgb = strokeRGBA.rgb;\ngl_FragColor = mix(fillRGBA, strokeRGBA, smoothstep(\n -uTroikaStrokeWidth - aaDist,\n -uTroikaStrokeWidth + aaDist,\n fragDistance\n));\ngl_FragColor.a *= edgeAlpha;\n#endif\n\nif (edgeAlpha == 0.0) {\n discard;\n}\n",customRewriter({vertexShader:vertexShader,fragmentShader:fragmentShader}){let uDiffuseRE=/\buniform\s+vec3\s+diffuse\b/;return uDiffuseRE.test(fragmentShader)&&(fragmentShader=fragmentShader.replace(uDiffuseRE,"varying vec3 vTroikaGlyphColor").replace(/\bdiffuse\b/g,"vTroikaGlyphColor"),uDiffuseRE.test(vertexShader)||(vertexShader=vertexShader.replace(voidMainRegExp,"uniform vec3 diffuse;\n$&\nvTroikaGlyphColor = uTroikaUseGlyphColors ? aTroikaGlyphColor / 255.0 : diffuse;\n"))),{vertexShader:vertexShader,fragmentShader:fragmentShader}}});return textMaterial.transparent=!0,Object.defineProperties(textMaterial,{isTroikaTextMaterial:{value:!0},shadowSide:{get(){return this.side},set(){}}}),textMaterial}(baseMaterial),baseMaterial.addEventListener("dispose",(function onDispose(){baseMaterial.removeEventListener("dispose",onDispose),derivedMaterial.dispose()}))),this.outlineWidth||this.outlineBlur||this.outlineOffsetX||this.outlineOffsetY){let outlineMaterial=derivedMaterial._outlineMtl;return outlineMaterial||(outlineMaterial=derivedMaterial._outlineMtl=Object.create(derivedMaterial,{id:{value:derivedMaterial.id+.1}}),outlineMaterial.isTextOutlineMaterial=!0,outlineMaterial.depthWrite=!1,outlineMaterial.map=null,derivedMaterial.addEventListener("dispose",(function onDispose(){derivedMaterial.removeEventListener("dispose",onDispose),outlineMaterial.dispose()}))),[outlineMaterial,derivedMaterial]}return derivedMaterial}set material(baseMaterial){baseMaterial&&baseMaterial.isTroikaTextMaterial?(this._derivedMaterial=baseMaterial,this._baseMaterial=baseMaterial.baseMaterial):this._baseMaterial=baseMaterial}get glyphGeometryDetail(){return this.geometry.detail}set glyphGeometryDetail(detail){this.geometry.detail=detail}get curveRadius(){return this.geometry.curveRadius}set curveRadius(r){this.geometry.curveRadius=r}get customDepthMaterial(){return first(this.material).getDepthMaterial()}get customDistanceMaterial(){return first(this.material).getDistanceMaterial()}_prepareForRender(material){const isOutline=material.isTextOutlineMaterial,uniforms=material.uniforms,textInfo=this.textRenderInfo;if(textInfo){const{sdfTexture:sdfTexture,blockBounds:blockBounds}=textInfo;uniforms.uTroikaSDFTexture.value=sdfTexture,uniforms.uTroikaSDFTextureSize.value.set(sdfTexture.image.width,sdfTexture.image.height),uniforms.uTroikaSDFGlyphSize.value=textInfo.sdfGlyphSize,uniforms.uTroikaSDFExponent.value=textInfo.sdfExponent,uniforms.uTroikaTotalBounds.value.fromArray(blockBounds),uniforms.uTroikaUseGlyphColors.value=!isOutline&&!!textInfo.glyphColors;let fillOpacity,strokeOpacity,strokeColor,distanceOffset=0,blurRadius=0,strokeWidth=0,offsetX=0,offsetY=0;if(isOutline){let{outlineWidth:outlineWidth,outlineOffsetX:outlineOffsetX,outlineOffsetY:outlineOffsetY,outlineBlur:outlineBlur,outlineOpacity:outlineOpacity}=this;distanceOffset=this._parsePercent(outlineWidth)||0,blurRadius=Math.max(0,this._parsePercent(outlineBlur)||0),fillOpacity=outlineOpacity,offsetX=this._parsePercent(outlineOffsetX)||0,offsetY=this._parsePercent(outlineOffsetY)||0}else strokeWidth=Math.max(0,this._parsePercent(this.strokeWidth)||0),strokeWidth&&(strokeColor=this.strokeColor,uniforms.uTroikaStrokeColor.value.set(null==strokeColor?8421504:strokeColor),strokeOpacity=this.strokeOpacity,null==strokeOpacity&&(strokeOpacity=1)),fillOpacity=this.fillOpacity;uniforms.uTroikaDistanceOffset.value=distanceOffset,uniforms.uTroikaPositionOffset.value.set(offsetX,offsetY),uniforms.uTroikaBlurRadius.value=blurRadius,uniforms.uTroikaStrokeWidth.value=strokeWidth,uniforms.uTroikaStrokeOpacity.value=strokeOpacity,uniforms.uTroikaFillOpacity.value=null==fillOpacity?1:fillOpacity,uniforms.uTroikaCurveRadius.value=this.curveRadius||0;let clipRect=this.clipRect;if(clipRect&&Array.isArray(clipRect)&&4===clipRect.length)uniforms.uTroikaClipRect.value.fromArray(clipRect);else{const pad=100*(this.fontSize||.1);uniforms.uTroikaClipRect.value.set(blockBounds[0]-pad,blockBounds[1]-pad,blockBounds[2]+pad,blockBounds[3]+pad)}this.geometry.applyClipRect(uniforms.uTroikaClipRect.value)}uniforms.uTroikaSDFDebug.value=!!this.debugSDF,material.polygonOffset=!!this.depthOffset,material.polygonOffsetFactor=material.polygonOffsetUnits=this.depthOffset||0;const color=isOutline?this.outlineColor||0:this.color;if(null==color)delete material.color;else{const colorObj=material.hasOwnProperty("color")?material.color:material.color=new three_module.Color;color===colorObj._input&&"object"!=typeof color||colorObj.set(colorObj._input=color)}let orient=this.orientation||"+x+y";if(orient!==material._orientation){let rotMat=uniforms.uTroikaOrient.value;orient=orient.replace(/[^-+xyz]/g,"");let match="+x+y"!==orient&&orient.match(/^([-+])([xyz])([-+])([xyz])$/);if(match){let[,hSign,hAxis,vSign,vAxis]=match;tempVec3a.set(0,0,0)[hAxis]="-"===hSign?1:-1,tempVec3b.set(0,0,0)[vAxis]="-"===vSign?-1:1,tempMat4.lookAt(origin,tempVec3a.cross(tempVec3b),tempVec3b),rotMat.setFromMatrix4(tempMat4)}else rotMat.identity();material._orientation=orient}}_parsePercent(value){if("string"==typeof value){let match=value.match(/^(-?[\d.]+)%$/),pct=match?parseFloat(match[1]):NaN;value=(isNaN(pct)?0:pct/100)*this.fontSize}return value}localPositionToTextCoords(position,target=new three_module.Vector2){target.copy(position);const r=this.curveRadius;return r&&(target.x=Math.atan2(position.x,Math.abs(r)-Math.abs(position.z))*Math.abs(r)),target}worldPositionToTextCoords(position,target=new three_module.Vector2){return tempVec3a.copy(position),this.localPositionToTextCoords(this.worldToLocal(tempVec3a),target)}raycast(raycaster,intersects){const{textRenderInfo:textRenderInfo,curveRadius:curveRadius}=this;if(textRenderInfo){const bounds=textRenderInfo.blockBounds,raycastMesh=curveRadius?getCurvedRaycastMesh():getFlatRaycastMesh(),geom=raycastMesh.geometry,{position:position,uv:uv}=geom.attributes;for(let i=0;i{this[prop]=source[prop]})),this}clone(){return(new this.constructor).copy(this)}}SYNCABLE_PROPS.forEach((prop=>{const privateKey="_private_"+prop;Object.defineProperty(Text.prototype,prop,{get(){return this[privateKey]},set(value){value!==this[privateKey]&&(this[privateKey]=value,this._needsSync=!0)}})}));let deprMsgShown=!1;return Object.defineProperty(Text.prototype,"anchor",{get(){return this._deprecated_anchor},set(val){this._deprecated_anchor=val,deprMsgShown||(console.warn("TextMesh: `anchor` has been deprecated; use `anchorX` and `anchorY` instead."),deprMsgShown=!0),Array.isArray(val)?(this.anchorX=100*(+val[0]||0)+"%",this.anchorY=100*(+val[1]||0)+"%"):this.anchorX=this.anchorY=0}}),Text})();new WeakMap;new WeakMap;var index_4f1a8e2f_esm=__webpack_require__("./node_modules/@react-three/fiber/dist/index-4f1a8e2f.esm.js"),dist=__webpack_require__("./node_modules/suspend-react/dist/index.js");const Text_Text=react.forwardRef((({anchorX:anchorX="center",anchorY:anchorY="middle",font:font,children:children,characters:characters,onSync:onSync,...props},ref)=>{const invalidate=(0,index_4f1a8e2f_esm.w)((({invalidate:invalidate})=>invalidate)),[troikaMesh]=react.useState((()=>new Text)),[nodes,text]=react.useMemo((()=>{const n=[];let t="";return react.Children.forEach(children,(child=>{"string"==typeof child||"number"==typeof child?t+=child:n.push(child)})),[n,t]}),[children]);return(0,dist.Rq)((()=>new Promise((res=>function preloadFont({font:font,characters:characters,sdfGlyphSize:sdfGlyphSize},callback){getTextRenderInfo({font:font,sdfGlyphSize:sdfGlyphSize,text:Array.isArray(characters)?characters.join("\n"):""+characters},callback)}({font:font,characters:characters},res)))),["troika-text",font,characters]),react.useLayoutEffect((()=>{troikaMesh.sync((()=>{invalidate(),onSync&&onSync(troikaMesh)}))})),react.useEffect((()=>()=>troikaMesh.dispose()),[troikaMesh]),react.createElement("primitive",(0,esm_extends.Z)({object:troikaMesh,ref:ref,font:font,text:text,anchorX:anchorX,anchorY:anchorY},props),nodes)}))},"./node_modules/@react-three/drei/core/shapes.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{Cd:function(){return Circle}});var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/extends.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js");function create(type){const El=type+"BufferGeometry";return react__WEBPACK_IMPORTED_MODULE_0__.forwardRef((({args:args,children:children,...props},ref)=>react__WEBPACK_IMPORTED_MODULE_0__.createElement("mesh",(0,_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__.Z)({ref:ref},props),react__WEBPACK_IMPORTED_MODULE_0__.createElement(El,{attach:"geometry",args:args}),children)))}create("box");const Circle=create("circle");create("cone"),create("cylinder"),create("sphere"),create("plane"),create("tube"),create("torus"),create("torusKnot"),create("tetrahedron"),create("ring"),create("polyhedron"),create("icosahedron"),create("octahedron"),create("dodecahedron"),create("extrude"),create("lathe"),create("capsule")},"./node_modules/@react-three/drei/core/useGLTF.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{L:function(){return useGLTF}});var three_module=__webpack_require__("./node_modules/three/build/three.module.js");const _taskCache=new WeakMap;class DRACOLoader extends three_module.Loader{constructor(manager){super(manager),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(path){return this.decoderPath=path,this}setDecoderConfig(config){return this.decoderConfig=config,this}setWorkerLimit(workerLimit){return this.workerLimit=workerLimit,this}load(url,onLoad,onProgress,onError){const loader=new three_module.FileLoader(this.manager);loader.setPath(this.path),loader.setResponseType("arraybuffer"),loader.setRequestHeader(this.requestHeader),loader.setWithCredentials(this.withCredentials),loader.load(url,(buffer=>{const taskConfig={attributeIDs:this.defaultAttributeIDs,attributeTypes:this.defaultAttributeTypes,useUniqueIDs:!1};this.decodeGeometry(buffer,taskConfig).then(onLoad).catch(onError)}),onProgress,onError)}decodeDracoFile(buffer,callback,attributeIDs,attributeTypes){const taskConfig={attributeIDs:attributeIDs||this.defaultAttributeIDs,attributeTypes:attributeTypes||this.defaultAttributeTypes,useUniqueIDs:!!attributeIDs};this.decodeGeometry(buffer,taskConfig).then(callback)}decodeGeometry(buffer,taskConfig){for(const attribute in taskConfig.attributeTypes){const type=taskConfig.attributeTypes[attribute];void 0!==type.BYTES_PER_ELEMENT&&(taskConfig.attributeTypes[attribute]=type.name)}const taskKey=JSON.stringify(taskConfig);if(_taskCache.has(buffer)){const cachedTask=_taskCache.get(buffer);if(cachedTask.key===taskKey)return cachedTask.promise;if(0===buffer.byteLength)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let worker;const taskID=this.workerNextTaskID++,taskCost=buffer.byteLength,geometryPending=this._getWorker(taskID,taskCost).then((_worker=>(worker=_worker,new Promise(((resolve,reject)=>{worker._callbacks[taskID]={resolve:resolve,reject:reject},worker.postMessage({type:"decode",id:taskID,taskConfig:taskConfig,buffer:buffer},[buffer])}))))).then((message=>this._createGeometry(message.geometry)));return geometryPending.catch((()=>!0)).then((()=>{worker&&taskID&&this._releaseTask(worker,taskID)})),_taskCache.set(buffer,{key:taskKey,promise:geometryPending}),geometryPending}_createGeometry(geometryData){const geometry=new three_module.BufferGeometry;geometryData.index&&geometry.setIndex(new three_module.BufferAttribute(geometryData.index.array,1));for(let i=0;i{loader.load(url,resolve,void 0,reject)}))}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const useJS="object"!=typeof WebAssembly||"js"===this.decoderConfig.type,librariesPending=[];return useJS?librariesPending.push(this._loadLibrary("draco_decoder.js","text")):(librariesPending.push(this._loadLibrary("draco_wasm_wrapper.js","text")),librariesPending.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(librariesPending).then((libraries=>{const jsContent=libraries[0];useJS||(this.decoderConfig.wasmBinary=libraries[1]);const fn=DRACOWorker.toString(),body=["/* draco decoder */",jsContent,"","/* worker */",fn.substring(fn.indexOf("{")+1,fn.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([body]))})),this.decoderPending}_getWorker(taskID,taskCost){return this._initDecoder().then((()=>{if(this.workerPool.lengthb._taskLoad?-1:1}));const worker=this.workerPool[this.workerPool.length-1];return worker._taskCosts[taskID]=taskCost,worker._taskLoad+=taskCost,worker}))}_releaseTask(worker,taskID){worker._taskLoad-=worker._taskCosts[taskID],delete worker._callbacks[taskID],delete worker._taskCosts[taskID]}debug(){console.log("Task load: ",this.workerPool.map((worker=>worker._taskLoad)))}dispose(){for(let i=0;i{const draco=module.draco,decoder=new draco.Decoder,decoderBuffer=new draco.DecoderBuffer;decoderBuffer.Init(new Int8Array(buffer),buffer.byteLength);try{const geometry=function decodeGeometry(draco,decoder,decoderBuffer,taskConfig){const attributeIDs=taskConfig.attributeIDs,attributeTypes=taskConfig.attributeTypes;let dracoGeometry,decodingStatus;const geometryType=decoder.GetEncodedGeometryType(decoderBuffer);if(geometryType===draco.TRIANGULAR_MESH)dracoGeometry=new draco.Mesh,decodingStatus=decoder.DecodeBufferToMesh(decoderBuffer,dracoGeometry);else{if(geometryType!==draco.POINT_CLOUD)throw new Error("THREE.DRACOLoader: Unexpected geometry type.");dracoGeometry=new draco.PointCloud,decodingStatus=decoder.DecodeBufferToPointCloud(decoderBuffer,dracoGeometry)}if(!decodingStatus.ok()||0===dracoGeometry.ptr)throw new Error("THREE.DRACOLoader: Decoding failed: "+decodingStatus.error_msg());const geometry={index:null,attributes:[]};for(const attributeName in attributeIDs){const attributeType=self[attributeTypes[attributeName]];let attribute,attributeID;if(taskConfig.useUniqueIDs)attributeID=attributeIDs[attributeName],attribute=decoder.GetAttributeByUniqueId(dracoGeometry,attributeID);else{if(attributeID=decoder.GetAttributeId(dracoGeometry,draco[attributeIDs[attributeName]]),-1===attributeID)continue;attribute=decoder.GetAttribute(dracoGeometry,attributeID)}geometry.attributes.push(decodeAttribute(draco,decoder,dracoGeometry,attributeName,attributeType,attribute))}geometryType===draco.TRIANGULAR_MESH&&(geometry.index=function decodeIndex(draco,decoder,dracoGeometry){const numIndices=3*dracoGeometry.num_faces(),byteLength=4*numIndices,ptr=draco._malloc(byteLength);decoder.GetTrianglesUInt32Array(dracoGeometry,byteLength,ptr);const index=new Uint32Array(draco.HEAPF32.buffer,ptr,numIndices).slice();return draco._free(ptr),{array:index,itemSize:1}}(draco,decoder,dracoGeometry));return draco.destroy(dracoGeometry),geometry}(draco,decoder,decoderBuffer,taskConfig),buffers=geometry.attributes.map((attr=>attr.array.buffer));geometry.index&&buffers.push(geometry.index.array.buffer),self.postMessage({type:"decode",id:message.id,geometry:geometry},buffers)}catch(error){console.error(error),self.postMessage({type:"error",id:message.id,error:error.message})}finally{draco.destroy(decoderBuffer),draco.destroy(decoder)}}))}}}let generated;const MeshoptDecoder=()=>{if(generated)return generated;const detector=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),wasmpack=new Uint8Array([32,0,65,253,3,1,2,34,4,106,6,5,11,8,7,20,13,33,12,16,128,9,116,64,19,113,127,15,10,21,22,14,255,66,24,54,136,107,18,23,192,26,114,118,132,17,77,101,130,144,27,87,131,44,45,74,156,154,70,167]);if("object"!=typeof WebAssembly)return{supported:!1};let instance,wasm="B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB";WebAssembly.validate(detector)&&(wasm="B9h9z9tFBBBFiI9gBB9gLaaaaaFa9gEaaaB9gFaFaEMcBBFBFFGGGEILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBOn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBNI9z9iqlBVc+N9IcIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMk8lLbaE97F9+FaL978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAeDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAeDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBReCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBH8ZCFD9tA8ZAPD9OD9hD9RH8ZDQBTFtGmEYIPLdKeOnHpAIAQJDBIBHyCFD9tAyAPD9OD9hD9RHyAIASJDBIBH8cCFD9tA8cAPD9OD9hD9RH8cDQBTFtGmEYIPLdKeOnH8dDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAeD9uHeDyBjGBAEAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeApA8dDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNiV8ZcpMyS8cQ8df8eb8fHdAyA8cDQNiV8ZcpMyS8cQ8df8eb8fH8ZDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/dLEK97FaF97GXGXAGCI9HQBAF9FQFCBRGEXABABDBBBHECiD+rFCiD+sFD/6FHIAECND+rFCiD+sFD/6FAID/gFAECTD+rFCiD+sFD/6FHLD/gFD/kFD/lFHKCBDtD+2FHOAICUUUU94DtHND9OD9RD/kFHI9DBB/+hDYAIAID/mFAKAKD/mFALAOALAND9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHLD/mF9DBBX9LDYHOD/kFCgFDtD9OAECUUU94DtD9OD9QAIALD/mFAOD/kFCND+rFCU/+EDtD9OD9QAKALD/mFAOD/kFCTD+rFCUU/8ODtD9OD9QDMBBABCTJRBAGCIJHGAF9JQBSGMMAF9FQBCBRGEXABCTJHVAVDBBBHECBDtHOCUU98D8cFCUU98D8cEHND9OABDBBBHKAEDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAKAEDQBFGENVcMTtmYi8ZpyHECTD+sFD/6FHID/gFAECTD+rFCTD+sFD/6FHLD/gFD/kFD/lFHE9DB/+g6DYALAEAOD+2FHOALCUUUU94DtHcD9OD9RD/kFHLALD/mFAEAED/mFAIAOAIAcD9OD9RD/kFHEAED/mFD/kFD/kFD/jFD/nFHID/mF9DBBX9LDYHOD/kFCTD+rFALAID/mFAOD/kFCggEDtD9OD9QHLAEAID/mFAOD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHEDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAKAND9OALAEDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM/hEIGaF97FaL978jUUUUBCTlREGXAF9FQBCBRIEXAEABDBBBHLABCTJHKDBBBHODQILKOSQfbPden8c8d8e8fHNCTD+sFHVCID+rFDMIBAB9DBBU8/DY9D/zI818/DYAVCEDtD9QD/6FD/nFHVALAODQBFGENVcMTtmYi8ZpyHLCTD+rFCTD+sFD/6FD/mFHOAOD/mFAVALCTD+sFD/6FD/mFHcAcD/mFAVANCTD+rFCTD+sFD/6FD/mFHNAND/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHVD/mF9DBBX9LDYHLD/kFCggEDtHMD9OAcAVD/mFALD/kFCTD+rFD9QHcANAVD/mFALD/kFCTD+rFAOAVD/mFALD/kFAMD9OD9QHVDQBFTtGEmYILPdKOenHLD8dBAEDBIBDyB+t+J83EBABCNJALD8dFAEDBIBDyF+t+J83EBAKAcAVDQNVi8ZcMpySQ8c8dfb8e8fHVD8dBAEDBIBDyG+t+J83EBABCiJAVD8dFAEDBIBDyE+t+J83EBABCAJRBAICIJHIAF9JQBMMM9jFF97GXAGCGrAF9sHG9FQBCBRFEXABABDBBBHECND+rFCND+sFD/6FAECiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBABCTJRBAFCIJHFAG9JQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB");const promise=WebAssembly.instantiate(function unpack(data){const result=new Uint8Array(data.length);for(let i=0;i96?ch-71:ch>64?ch-65:ch>47?ch+4:ch>46?63:62}let write=0;for(let i=0;i{instance=result.instance,instance.exports.__wasm_call_ctors()}));function decode(fun,target,count,size,source,filter){const sbrk=instance.exports.sbrk,count4=count+3&-4,tp=sbrk(count4*size),sp=sbrk(source.length),heap=new Uint8Array(instance.exports.memory.buffer);heap.set(source,sp);const res=fun(tp,count,size,sp,source.length);if(0===res&&filter&&filter(tp,count4,size),target.set(heap.subarray(tp,tp+count*size)),sbrk(tp-sbrk(0)),0!==res)throw new Error(`Malformed buffer data: ${res}`)}const filters={0:"",1:"meshopt_decodeFilterOct",2:"meshopt_decodeFilterQuat",3:"meshopt_decodeFilterExp",NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},decoders={0:"meshopt_decodeVertexBuffer",1:"meshopt_decodeIndexBuffer",2:"meshopt_decodeIndexSequence",ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return generated={ready:promise,supported:!0,decodeVertexBuffer(target,count,size,source,filter){decode(instance.exports.meshopt_decodeVertexBuffer,target,count,size,source,instance.exports[filters[filter]])},decodeIndexBuffer(target,count,size,source){decode(instance.exports.meshopt_decodeIndexBuffer,target,count,size,source)},decodeIndexSequence(target,count,size,source){decode(instance.exports.meshopt_decodeIndexSequence,target,count,size,source)},decodeGltfBuffer(target,count,size,source,mode,filter){decode(instance.exports[decoders[mode]],target,count,size,source,instance.exports[filters[filter]])}},generated};class GLTFLoader extends three_module.Loader{constructor(manager){super(manager),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register((function(parser){return new GLTFMaterialsClearcoatExtension(parser)})),this.register((function(parser){return new GLTFTextureBasisUExtension(parser)})),this.register((function(parser){return new GLTFTextureWebPExtension(parser)})),this.register((function(parser){return new GLTFMaterialsSheenExtension(parser)})),this.register((function(parser){return new GLTFMaterialsTransmissionExtension(parser)})),this.register((function(parser){return new GLTFMaterialsVolumeExtension(parser)})),this.register((function(parser){return new GLTFMaterialsIorExtension(parser)})),this.register((function(parser){return new GLTFMaterialsSpecularExtension(parser)})),this.register((function(parser){return new GLTFLightsExtension(parser)})),this.register((function(parser){return new GLTFMeshoptCompression(parser)}))}load(url,onLoad,onProgress,onError){const scope=this;let resourcePath;resourcePath=""!==this.resourcePath?this.resourcePath:""!==this.path?this.path:three_module.LoaderUtils.extractUrlBase(url),this.manager.itemStart(url);const _onError=function(e){onError?onError(e):console.error(e),scope.manager.itemError(url),scope.manager.itemEnd(url)},loader=new three_module.FileLoader(this.manager);loader.setPath(this.path),loader.setResponseType("arraybuffer"),loader.setRequestHeader(this.requestHeader),loader.setWithCredentials(this.withCredentials),loader.load(url,(function(data){try{scope.parse(data,resourcePath,(function(gltf){onLoad(gltf),scope.manager.itemEnd(url)}),_onError)}catch(e){_onError(e)}}),onProgress,_onError)}setDRACOLoader(dracoLoader){return this.dracoLoader=dracoLoader,this}setDDSLoader(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')}setKTX2Loader(ktx2Loader){return this.ktx2Loader=ktx2Loader,this}setMeshoptDecoder(meshoptDecoder){return this.meshoptDecoder=meshoptDecoder,this}register(callback){return-1===this.pluginCallbacks.indexOf(callback)&&this.pluginCallbacks.push(callback),this}unregister(callback){return-1!==this.pluginCallbacks.indexOf(callback)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback),1),this}parse(data,path,onLoad,onError){let content;const extensions={},plugins={};if("string"==typeof data)content=data;else{if(three_module.LoaderUtils.decodeText(new Uint8Array(data,0,4))===BINARY_EXTENSION_HEADER_MAGIC){try{extensions[EXTENSIONS.KHR_BINARY_GLTF]=new GLTFBinaryExtension(data)}catch(error){return void(onError&&onError(error))}content=extensions[EXTENSIONS.KHR_BINARY_GLTF].content}else content=three_module.LoaderUtils.decodeText(new Uint8Array(data))}const json=JSON.parse(content);if(void 0===json.asset||json.asset.version[0]<2)return void(onError&&onError(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")));const parser=new GLTFParser(json,{path:path||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});parser.fileLoader.setRequestHeader(this.requestHeader);for(let i=0;i=0&&void 0===plugins[extensionName]&&console.warn('THREE.GLTFLoader: Unknown extension "'+extensionName+'".')}}parser.setExtensions(extensions),parser.setPlugins(plugins),parser.parse(onLoad,onError)}parseAsync(data,path){const scope=this;return new Promise((function(resolve,reject){scope.parse(data,path,resolve,reject)}))}}function GLTFRegistry(){let objects={};return{get:function(key){return objects[key]},add:function(key,object){objects[key]=object},remove:function(key){delete objects[key]},removeAll:function(){objects={}}}}const EXTENSIONS={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:"KHR_materials_pbrSpecularGlossiness",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression"};class GLTFLightsExtension{constructor(parser){this.parser=parser,this.name=EXTENSIONS.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const parser=this.parser,nodeDefs=this.parser.json.nodes||[];for(let nodeIndex=0,nodeLength=nodeDefs.length;nodeIndex=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return parser.loadTextureImage(textureIndex,source,loader)}}class GLTFTextureWebPExtension{constructor(parser){this.parser=parser,this.name=EXTENSIONS.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(textureIndex){const name=this.name,parser=this.parser,json=parser.json,textureDef=json.textures[textureIndex];if(!textureDef.extensions||!textureDef.extensions[name])return null;const extension=textureDef.extensions[name],source=json.images[extension.source];let loader=parser.textureLoader;if(source.uri){const handler=parser.options.manager.getHandler(source.uri);null!==handler&&(loader=handler)}return this.detectSupport().then((function(isSupported){if(isSupported)return parser.loadTextureImage(textureIndex,source,loader);if(json.extensionsRequired&&json.extensionsRequired.indexOf(name)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return parser.loadTexture(textureIndex)}))}detectSupport(){return this.isSupported||(this.isSupported=new Promise((function(resolve){const image=new Image;image.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",image.onload=image.onerror=function(){resolve(1===image.height)}}))),this.isSupported}}class GLTFMeshoptCompression{constructor(parser){this.name=EXTENSIONS.EXT_MESHOPT_COMPRESSION,this.parser=parser}loadBufferView(index){const json=this.parser.json,bufferView=json.bufferViews[index];if(bufferView.extensions&&bufferView.extensions[this.name]){const extensionDef=bufferView.extensions[this.name],buffer=this.parser.getDependency("buffer",extensionDef.buffer),decoder=this.parser.options.meshoptDecoder;if(!decoder||!decoder.supported){if(json.extensionsRequired&&json.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return Promise.all([buffer,decoder.ready]).then((function(res){const byteOffset=extensionDef.byteOffset||0,byteLength=extensionDef.byteLength||0,count=extensionDef.count,stride=extensionDef.byteStride,result=new ArrayBuffer(count*stride),source=new Uint8Array(res[0],byteOffset,byteLength);return decoder.decodeGltfBuffer(new Uint8Array(result),count,stride,source,extensionDef.mode,extensionDef.filter),result}))}return null}}const BINARY_EXTENSION_HEADER_MAGIC="glTF",BINARY_EXTENSION_CHUNK_TYPES_JSON=1313821514,BINARY_EXTENSION_CHUNK_TYPES_BIN=5130562;class GLTFBinaryExtension{constructor(data){this.name=EXTENSIONS.KHR_BINARY_GLTF,this.content=null,this.body=null;const headerView=new DataView(data,0,12);if(this.header={magic:three_module.LoaderUtils.decodeText(new Uint8Array(data.slice(0,4))),version:headerView.getUint32(4,!0),length:headerView.getUint32(8,!0)},this.header.magic!==BINARY_EXTENSION_HEADER_MAGIC)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const chunkContentsLength=this.header.length-12,chunkView=new DataView(data,12);let chunkIndex=0;for(;chunkIndex",specularMapParsFragmentChunk).replace("#include ",glossinessMapParsFragmentChunk).replace("#include ",specularMapFragmentChunk).replace("#include ",glossinessMapFragmentChunk).replace("#include ",lightPhysicalFragmentChunk)},Object.defineProperties(this,{specular:{get:function(){return uniforms.specular.value},set:function(v){uniforms.specular.value=v}},specularMap:{get:function(){return uniforms.specularMap.value},set:function(v){uniforms.specularMap.value=v,v?this.defines.USE_SPECULARMAP="":delete this.defines.USE_SPECULARMAP}},glossiness:{get:function(){return uniforms.glossiness.value},set:function(v){uniforms.glossiness.value=v}},glossinessMap:{get:function(){return uniforms.glossinessMap.value},set:function(v){uniforms.glossinessMap.value=v,v?(this.defines.USE_GLOSSINESSMAP="",this.defines.USE_UV=""):(delete this.defines.USE_GLOSSINESSMAP,delete this.defines.USE_UV)}}}),delete this.metalness,delete this.roughness,delete this.metalnessMap,delete this.roughnessMap,this.setValues(params)}copy(source){return super.copy(source),this.specularMap=source.specularMap,this.specular.copy(source.specular),this.glossinessMap=source.glossinessMap,this.glossiness=source.glossiness,delete this.metalness,delete this.roughness,delete this.metalnessMap,delete this.roughnessMap,this}}class GLTFMaterialsPbrSpecularGlossinessExtension{constructor(){this.name=EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,this.specularGlossinessParams=["color","map","lightMap","lightMapIntensity","aoMap","aoMapIntensity","emissive","emissiveIntensity","emissiveMap","bumpMap","bumpScale","normalMap","normalMapType","displacementMap","displacementScale","displacementBias","specularMap","specular","glossinessMap","glossiness","alphaMap","envMap","envMapIntensity","refractionRatio"]}getMaterialType(){return GLTFMeshStandardSGMaterial}extendParams(materialParams,materialDef,parser){const pbrSpecularGlossiness=materialDef.extensions[this.name];materialParams.color=new three_module.Color(1,1,1),materialParams.opacity=1;const pending=[];if(Array.isArray(pbrSpecularGlossiness.diffuseFactor)){const array=pbrSpecularGlossiness.diffuseFactor;materialParams.color.fromArray(array),materialParams.opacity=array[3]}if(void 0!==pbrSpecularGlossiness.diffuseTexture&&pending.push(parser.assignTexture(materialParams,"map",pbrSpecularGlossiness.diffuseTexture)),materialParams.emissive=new three_module.Color(0,0,0),materialParams.glossiness=void 0!==pbrSpecularGlossiness.glossinessFactor?pbrSpecularGlossiness.glossinessFactor:1,materialParams.specular=new three_module.Color(1,1,1),Array.isArray(pbrSpecularGlossiness.specularFactor)&&materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor),void 0!==pbrSpecularGlossiness.specularGlossinessTexture){const specGlossMapDef=pbrSpecularGlossiness.specularGlossinessTexture;pending.push(parser.assignTexture(materialParams,"glossinessMap",specGlossMapDef)),pending.push(parser.assignTexture(materialParams,"specularMap",specGlossMapDef))}return Promise.all(pending)}createMaterial(materialParams){const material=new GLTFMeshStandardSGMaterial(materialParams);return material.fog=!0,material.color=materialParams.color,material.map=void 0===materialParams.map?null:materialParams.map,material.lightMap=null,material.lightMapIntensity=1,material.aoMap=void 0===materialParams.aoMap?null:materialParams.aoMap,material.aoMapIntensity=1,material.emissive=materialParams.emissive,material.emissiveIntensity=1,material.emissiveMap=void 0===materialParams.emissiveMap?null:materialParams.emissiveMap,material.bumpMap=void 0===materialParams.bumpMap?null:materialParams.bumpMap,material.bumpScale=1,material.normalMap=void 0===materialParams.normalMap?null:materialParams.normalMap,material.normalMapType=three_module.TangentSpaceNormalMap,materialParams.normalScale&&(material.normalScale=materialParams.normalScale),material.displacementMap=null,material.displacementScale=1,material.displacementBias=0,material.specularMap=void 0===materialParams.specularMap?null:materialParams.specularMap,material.specular=materialParams.specular,material.glossinessMap=void 0===materialParams.glossinessMap?null:materialParams.glossinessMap,material.glossiness=materialParams.glossiness,material.alphaMap=null,material.envMap=void 0===materialParams.envMap?null:materialParams.envMap,material.envMapIntensity=1,material.refractionRatio=.98,material}}class GLTFMeshQuantizationExtension{constructor(){this.name=EXTENSIONS.KHR_MESH_QUANTIZATION}}class GLTFCubicSplineInterpolant extends three_module.Interpolant{constructor(parameterPositions,sampleValues,sampleSize,resultBuffer){super(parameterPositions,sampleValues,sampleSize,resultBuffer)}copySampleValue_(index){const result=this.resultBuffer,values=this.sampleValues,valueSize=this.valueSize,offset=index*valueSize*3+valueSize;for(let i=0;i!==valueSize;i++)result[i]=values[offset+i];return result}}GLTFCubicSplineInterpolant.prototype.beforeStart_=GLTFCubicSplineInterpolant.prototype.copySampleValue_,GLTFCubicSplineInterpolant.prototype.afterEnd_=GLTFCubicSplineInterpolant.prototype.copySampleValue_,GLTFCubicSplineInterpolant.prototype.interpolate_=function(i1,t0,t,t1){const result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,stride2=2*stride,stride3=3*stride,td=t1-t0,p=(t-t0)/td,pp=p*p,ppp=pp*p,offset1=i1*stride3,offset0=offset1-stride3,s2=-2*ppp+3*pp,s3=ppp-pp,s0=1-s2,s1=s3-pp+p;for(let i=0;i!==stride;i++){const p0=values[offset0+i+stride],m0=values[offset0+i+stride2]*td,p1=values[offset1+i+stride],m1=values[offset1+i]*td;result[i]=s0*p0+s1*m0+s2*p1+s3*m1}return result};const _q=new three_module.Quaternion;class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant{interpolate_(i1,t0,t,t1){const result=super.interpolate_(i1,t0,t,t1);return _q.fromArray(result).normalize().toArray(result),result}}const WEBGL_CONSTANTS_POINTS=0,WEBGL_CONSTANTS_LINES=1,WEBGL_CONSTANTS_LINE_LOOP=2,WEBGL_CONSTANTS_LINE_STRIP=3,WEBGL_CONSTANTS_TRIANGLES=4,WEBGL_CONSTANTS_TRIANGLE_STRIP=5,WEBGL_CONSTANTS_TRIANGLE_FAN=6,WEBGL_COMPONENT_TYPES={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},WEBGL_FILTERS={9728:three_module.NearestFilter,9729:three_module.LinearFilter,9984:three_module.NearestMipmapNearestFilter,9985:three_module.LinearMipmapNearestFilter,9986:three_module.NearestMipmapLinearFilter,9987:three_module.LinearMipmapLinearFilter},WEBGL_WRAPPINGS={33071:three_module.ClampToEdgeWrapping,33648:three_module.MirroredRepeatWrapping,10497:three_module.RepeatWrapping},WEBGL_TYPE_SIZES={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},ATTRIBUTES={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv2",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},PATH_PROPERTIES={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},INTERPOLATION={CUBICSPLINE:void 0,LINEAR:three_module.InterpolateLinear,STEP:three_module.InterpolateDiscrete},ALPHA_MODES_OPAQUE="OPAQUE",ALPHA_MODES_MASK="MASK",ALPHA_MODES_BLEND="BLEND";function addUnknownExtensionsToUserData(knownExtensions,object,objectDef){for(const name in objectDef.extensions)void 0===knownExtensions[name]&&(object.userData.gltfExtensions=object.userData.gltfExtensions||{},object.userData.gltfExtensions[name]=objectDef.extensions[name])}function assignExtrasToUserData(object,gltfDef){void 0!==gltfDef.extras&&("object"==typeof gltfDef.extras?Object.assign(object.userData,gltfDef.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+gltfDef.extras))}function updateMorphTargets(mesh,meshDef){if(mesh.updateMorphTargets(),void 0!==meshDef.weights)for(let i=0,il=meshDef.weights.length;i{const mappings=this.associations.get(original);null!=mappings&&this.associations.set(clone,mappings);for(const[i,child]of original.children.entries())updateMappings(child,clone.children[i])};return updateMappings(object,ref),ref.name+="_instance_"+cache.uses[index]++,ref}_invokeOne(func){const extensions=Object.values(this.plugins);extensions.push(this);for(let i=0;i=2&&bufferAttribute.setY(index,sparseValues[i*itemSize+1]),itemSize>=3&&bufferAttribute.setZ(index,sparseValues[i*itemSize+2]),itemSize>=4&&bufferAttribute.setW(index,sparseValues[i*itemSize+3]),itemSize>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return bufferAttribute}))}loadTexture(textureIndex){const json=this.json,options=this.options,textureDef=json.textures[textureIndex],source=json.images[textureDef.source];let loader=this.textureLoader;if(source.uri){const handler=options.manager.getHandler(source.uri);null!==handler&&(loader=handler)}return this.loadTextureImage(textureIndex,source,loader)}loadTextureImage(textureIndex,source,loader){const parser=this,json=this.json,options=this.options,textureDef=json.textures[textureIndex],cacheKey=(source.uri||source.bufferView)+":"+textureDef.sampler;if(this.textureCache[cacheKey])return this.textureCache[cacheKey];const URL=self.URL||self.webkitURL;let sourceURI=source.uri||"",isObjectURL=!1;if(void 0!==source.bufferView)sourceURI=parser.getDependency("bufferView",source.bufferView).then((function(bufferView){isObjectURL=!0;const blob=new Blob([bufferView],{type:source.mimeType});return sourceURI=URL.createObjectURL(blob),sourceURI}));else if(void 0===source.uri)throw new Error("THREE.GLTFLoader: Image "+textureIndex+" is missing URI and bufferView");const promise=Promise.resolve(sourceURI).then((function(sourceURI){return new Promise((function(resolve,reject){let onLoad=resolve;!0===loader.isImageBitmapLoader&&(onLoad=function(imageBitmap){const texture=new three_module.Texture(imageBitmap);texture.needsUpdate=!0,resolve(texture)}),loader.load(three_module.LoaderUtils.resolveURL(sourceURI,options.path),onLoad,void 0,reject)}))})).then((function(texture){!0===isObjectURL&&URL.revokeObjectURL(sourceURI),texture.flipY=!1,textureDef.name&&(texture.name=textureDef.name);const sampler=(json.samplers||{})[textureDef.sampler]||{};return texture.magFilter=WEBGL_FILTERS[sampler.magFilter]||three_module.LinearFilter,texture.minFilter=WEBGL_FILTERS[sampler.minFilter]||three_module.LinearMipmapLinearFilter,texture.wrapS=WEBGL_WRAPPINGS[sampler.wrapS]||three_module.RepeatWrapping,texture.wrapT=WEBGL_WRAPPINGS[sampler.wrapT]||three_module.RepeatWrapping,parser.associations.set(texture,{textures:textureIndex}),texture})).catch((function(){return console.error("THREE.GLTFLoader: Couldn't load texture",sourceURI),null}));return this.textureCache[cacheKey]=promise,promise}assignTexture(materialParams,mapName,mapDef){const parser=this;return this.getDependency("texture",mapDef.index).then((function(texture){if(void 0===mapDef.texCoord||0==mapDef.texCoord||"aoMap"===mapName&&1==mapDef.texCoord||console.warn("THREE.GLTFLoader: Custom UV set "+mapDef.texCoord+" for texture "+mapName+" not yet supported."),parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]){const transform=void 0!==mapDef.extensions?mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]:void 0;if(transform){const gltfReference=parser.associations.get(texture);texture=parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture,transform),parser.associations.set(texture,gltfReference)}}return materialParams[mapName]=texture,texture}))}assignFinalMaterial(mesh){const geometry=mesh.geometry;let material=mesh.material;const useDerivativeTangents=void 0===geometry.attributes.tangent,useVertexColors=void 0!==geometry.attributes.color,useFlatShading=void 0===geometry.attributes.normal;if(mesh.isPoints){const cacheKey="PointsMaterial:"+material.uuid;let pointsMaterial=this.cache.get(cacheKey);pointsMaterial||(pointsMaterial=new three_module.PointsMaterial,three_module.Material.prototype.copy.call(pointsMaterial,material),pointsMaterial.color.copy(material.color),pointsMaterial.map=material.map,pointsMaterial.sizeAttenuation=!1,this.cache.add(cacheKey,pointsMaterial)),material=pointsMaterial}else if(mesh.isLine){const cacheKey="LineBasicMaterial:"+material.uuid;let lineMaterial=this.cache.get(cacheKey);lineMaterial||(lineMaterial=new three_module.LineBasicMaterial,three_module.Material.prototype.copy.call(lineMaterial,material),lineMaterial.color.copy(material.color),this.cache.add(cacheKey,lineMaterial)),material=lineMaterial}if(useDerivativeTangents||useVertexColors||useFlatShading){let cacheKey="ClonedMaterial:"+material.uuid+":";material.isGLTFSpecularGlossinessMaterial&&(cacheKey+="specular-glossiness:"),useDerivativeTangents&&(cacheKey+="derivative-tangents:"),useVertexColors&&(cacheKey+="vertex-colors:"),useFlatShading&&(cacheKey+="flat-shading:");let cachedMaterial=this.cache.get(cacheKey);cachedMaterial||(cachedMaterial=material.clone(),useVertexColors&&(cachedMaterial.vertexColors=!0),useFlatShading&&(cachedMaterial.flatShading=!0),useDerivativeTangents&&(cachedMaterial.normalScale&&(cachedMaterial.normalScale.y*=-1),cachedMaterial.clearcoatNormalScale&&(cachedMaterial.clearcoatNormalScale.y*=-1)),this.cache.add(cacheKey,cachedMaterial),this.associations.set(cachedMaterial,this.associations.get(material))),material=cachedMaterial}material.aoMap&&void 0===geometry.attributes.uv2&&void 0!==geometry.attributes.uv&&geometry.setAttribute("uv2",geometry.attributes.uv),mesh.material=material}getMaterialType(){return three_module.MeshStandardMaterial}loadMaterial(materialIndex){const parser=this,json=this.json,extensions=this.extensions,materialDef=json.materials[materialIndex];let materialType;const materialParams={},materialExtensions=materialDef.extensions||{},pending=[];if(materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]){const sgExtension=extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];materialType=sgExtension.getMaterialType(),pending.push(sgExtension.extendParams(materialParams,materialDef,parser))}else if(materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]){const kmuExtension=extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];materialType=kmuExtension.getMaterialType(),pending.push(kmuExtension.extendParams(materialParams,materialDef,parser))}else{const metallicRoughness=materialDef.pbrMetallicRoughness||{};if(materialParams.color=new three_module.Color(1,1,1),materialParams.opacity=1,Array.isArray(metallicRoughness.baseColorFactor)){const array=metallicRoughness.baseColorFactor;materialParams.color.fromArray(array),materialParams.opacity=array[3]}void 0!==metallicRoughness.baseColorTexture&&pending.push(parser.assignTexture(materialParams,"map",metallicRoughness.baseColorTexture)),materialParams.metalness=void 0!==metallicRoughness.metallicFactor?metallicRoughness.metallicFactor:1,materialParams.roughness=void 0!==metallicRoughness.roughnessFactor?metallicRoughness.roughnessFactor:1,void 0!==metallicRoughness.metallicRoughnessTexture&&(pending.push(parser.assignTexture(materialParams,"metalnessMap",metallicRoughness.metallicRoughnessTexture)),pending.push(parser.assignTexture(materialParams,"roughnessMap",metallicRoughness.metallicRoughnessTexture))),materialType=this._invokeOne((function(ext){return ext.getMaterialType&&ext.getMaterialType(materialIndex)})),pending.push(Promise.all(this._invokeAll((function(ext){return ext.extendMaterialParams&&ext.extendMaterialParams(materialIndex,materialParams)}))))}!0===materialDef.doubleSided&&(materialParams.side=three_module.DoubleSide);const alphaMode=materialDef.alphaMode||ALPHA_MODES_OPAQUE;if(alphaMode===ALPHA_MODES_BLEND?(materialParams.transparent=!0,materialParams.depthWrite=!1):(materialParams.transparent=!1,alphaMode===ALPHA_MODES_MASK&&(materialParams.alphaTest=void 0!==materialDef.alphaCutoff?materialDef.alphaCutoff:.5)),void 0!==materialDef.normalTexture&&materialType!==three_module.MeshBasicMaterial&&(pending.push(parser.assignTexture(materialParams,"normalMap",materialDef.normalTexture)),materialParams.normalScale=new three_module.Vector2(1,1),void 0!==materialDef.normalTexture.scale)){const scale=materialDef.normalTexture.scale;materialParams.normalScale.set(scale,scale)}return void 0!==materialDef.occlusionTexture&&materialType!==three_module.MeshBasicMaterial&&(pending.push(parser.assignTexture(materialParams,"aoMap",materialDef.occlusionTexture)),void 0!==materialDef.occlusionTexture.strength&&(materialParams.aoMapIntensity=materialDef.occlusionTexture.strength)),void 0!==materialDef.emissiveFactor&&materialType!==three_module.MeshBasicMaterial&&(materialParams.emissive=(new three_module.Color).fromArray(materialDef.emissiveFactor)),void 0!==materialDef.emissiveTexture&&materialType!==three_module.MeshBasicMaterial&&pending.push(parser.assignTexture(materialParams,"emissiveMap",materialDef.emissiveTexture)),Promise.all(pending).then((function(){let material;return material=materialType===GLTFMeshStandardSGMaterial?extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams):new materialType(materialParams),materialDef.name&&(material.name=materialDef.name),material.map&&(material.map.encoding=three_module.sRGBEncoding),material.emissiveMap&&(material.emissiveMap.encoding=three_module.sRGBEncoding),assignExtrasToUserData(material,materialDef),parser.associations.set(material,{materials:materialIndex}),materialDef.extensions&&addUnknownExtensionsToUserData(extensions,material,materialDef),material}))}createUniqueName(originalName){const sanitizedName=three_module.PropertyBinding.sanitizeNodeName(originalName||"");let name=sanitizedName;for(let i=1;this.nodeNamesUsed[name];++i)name=sanitizedName+"_"+i;return this.nodeNamesUsed[name]=!0,name}loadGeometries(primitives){const parser=this,extensions=this.extensions,cache=this.primitiveCache;function createDracoPrimitive(primitive){return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive,parser).then((function(geometry){return addPrimitiveAttributes(geometry,primitive,parser)}))}const pending=[];for(let i=0,il=primitives.length;i0&&updateMorphTargets(mesh,meshDef),mesh.name=parser.createUniqueName(meshDef.name||"mesh_"+meshIndex),assignExtrasToUserData(mesh,meshDef),primitive.extensions&&addUnknownExtensionsToUserData(extensions,mesh,primitive),parser.assignFinalMaterial(mesh),meshes.push(mesh)}for(let i=0,il=meshes.length;i1?new three_module.Group:1===objects.length?objects[0]:new three_module.Object3D,node!==objects[0])for(let i=0,il=objects.length;i{const reducedAssociations=new Map;for(const[key,value]of parser.associations)(key instanceof three_module.Material||key instanceof three_module.Texture)&&reducedAssociations.set(key,value);return node.traverse((node=>{const mappings=parser.associations.get(node);null!=mappings&&reducedAssociations.set(node,mappings)})),reducedAssociations})(scene),scene}))}}function buildNodeHierarchy(nodeId,parentObject,json,parser){const nodeDef=json.nodes[nodeId];return parser.getDependency("node",nodeId).then((function(node){if(void 0===nodeDef.skin)return node;let skinEntry;return parser.getDependency("skin",nodeDef.skin).then((function(skin){skinEntry=skin;const pendingJoints=[];for(let i=0,il=skinEntry.joints.length;i{extendLoader&&extendLoader(loader),useDraco&&(dracoLoader||(dracoLoader=new DRACOLoader),dracoLoader.setDecoderPath("string"==typeof useDraco?useDraco:"https://www.gstatic.com/draco/versioned/decoders/1.4.3/"),loader.setDRACOLoader(dracoLoader)),useMeshopt&&loader.setMeshoptDecoder(MeshoptDecoder())}}function useGLTF(path,useDraco=!0,useMeshOpt=!0,extendLoader){return(0,index_4f1a8e2f_esm.z)(GLTFLoader,path,extensions(useDraco,useMeshOpt,extendLoader))}useGLTF.preload=(path,useDraco=!0,useMeshOpt=!0,extendLoader)=>index_4f1a8e2f_esm.z.preload(GLTFLoader,path,extensions(useDraco,useMeshOpt,extendLoader)),useGLTF.clear=input=>index_4f1a8e2f_esm.z.clear(GLTFLoader,input)},"./node_modules/@react-three/drei/web/Html.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{V:function(){return Html}});var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/extends.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),react_dom_client__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./node_modules/react-dom/client.js"),three__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./node_modules/three/build/three.module.js"),_react_three_fiber__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/@react-three/fiber/dist/index-4f1a8e2f.esm.js");const v1=new three__WEBPACK_IMPORTED_MODULE_2__.Vector3,v2=new three__WEBPACK_IMPORTED_MODULE_2__.Vector3,v3=new three__WEBPACK_IMPORTED_MODULE_2__.Vector3;function defaultCalculatePosition(el,camera,size){const objectPos=v1.setFromMatrixPosition(el.matrixWorld);objectPos.project(camera);const widthHalf=size.width/2,heightHalf=size.height/2;return[objectPos.x*widthHalf+widthHalf,-objectPos.y*heightHalf+heightHalf]}const epsilon=value=>Math.abs(value)<1e-10?0:value;function getCSSMatrix(matrix,multipliers,prepend=""){let matrix3d="matrix3d(";for(let i=0;16!==i;i++)matrix3d+=epsilon(multipliers[i]*matrix.elements[i])+(15!==i?",":")");return prepend+matrix3d}const getCameraCSSMatrix=(multipliers=[1,-1,1,1,1,-1,1,1,1,-1,1,1,1,-1,1,1],matrix=>getCSSMatrix(matrix,multipliers));var multipliers;const getObjectCSSMatrix=(matrix,factor)=>{return getCSSMatrix(matrix,[1/(f=factor),1/f,1/f,1,-1/f,-1/f,-1/f,-1,1/f,1/f,1/f,1,1,1,1,1],"translate(-50%,-50%)");var f},Html=react__WEBPACK_IMPORTED_MODULE_0__.forwardRef((({children:children,eps:eps=.001,style:style,className:className,prepend:prepend,center:center,fullscreen:fullscreen,portal:portal,distanceFactor:distanceFactor,sprite:sprite=!1,transform:transform=!1,occlude:occlude,onOcclude:onOcclude,zIndexRange:zIndexRange=[16777271,0],calculatePosition:calculatePosition=defaultCalculatePosition,as:as="div",wrapperClass:wrapperClass,pointerEvents:pointerEvents="auto",...props},ref)=>{var _portal$current;const gl=(0,_react_three_fiber__WEBPACK_IMPORTED_MODULE_3__.w)((({gl:gl})=>gl)),camera=(0,_react_three_fiber__WEBPACK_IMPORTED_MODULE_3__.w)((({camera:camera})=>camera)),scene=(0,_react_three_fiber__WEBPACK_IMPORTED_MODULE_3__.w)((({scene:scene})=>scene)),size=(0,_react_three_fiber__WEBPACK_IMPORTED_MODULE_3__.w)((({size:size})=>size)),raycaster=(0,_react_three_fiber__WEBPACK_IMPORTED_MODULE_3__.w)((({raycaster:raycaster})=>raycaster)),[el]=react__WEBPACK_IMPORTED_MODULE_0__.useState((()=>document.createElement(as))),root=react__WEBPACK_IMPORTED_MODULE_0__.useRef(),group=react__WEBPACK_IMPORTED_MODULE_0__.useRef(null),oldZoom=react__WEBPACK_IMPORTED_MODULE_0__.useRef(0),oldPosition=react__WEBPACK_IMPORTED_MODULE_0__.useRef([0,0]),transformOuterRef=react__WEBPACK_IMPORTED_MODULE_0__.useRef(null),transformInnerRef=react__WEBPACK_IMPORTED_MODULE_0__.useRef(null),target=null!==(_portal$current=null==portal?void 0:portal.current)&&void 0!==_portal$current?_portal$current:gl.domElement.parentNode;react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect((()=>{if(group.current){const currentRoot=root.current=react_dom_client__WEBPACK_IMPORTED_MODULE_1__.createRoot(el);if(scene.updateMatrixWorld(),transform)el.style.cssText="position:absolute;top:0;left:0;pointer-events:none;overflow:hidden;";else{const vec=calculatePosition(group.current,camera,size);el.style.cssText=`position:absolute;top:0;left:0;transform:translate3d(${vec[0]}px,${vec[1]}px,0);transform-origin:0 0;`}return target&&(prepend?target.prepend(el):target.appendChild(el)),()=>{target&&target.removeChild(el),currentRoot.unmount()}}}),[target,transform]),react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect((()=>{wrapperClass&&(el.className=wrapperClass)}),[wrapperClass]);const styles=react__WEBPACK_IMPORTED_MODULE_0__.useMemo((()=>transform?{position:"absolute",top:0,left:0,width:size.width,height:size.height,transformStyle:"preserve-3d",pointerEvents:"none"}:{position:"absolute",transform:center?"translate3d(-50%,-50%,0)":"none",...fullscreen&&{top:-size.height/2,left:-size.width/2,width:size.width,height:size.height},...style}),[style,center,fullscreen,size,transform]),transformInnerStyles=react__WEBPACK_IMPORTED_MODULE_0__.useMemo((()=>({position:"absolute",pointerEvents:pointerEvents})),[pointerEvents]);react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect((()=>{var _root$current,_root$current2;transform?null==(_root$current=root.current)||_root$current.render(react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{ref:transformOuterRef,style:styles},react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{ref:transformInnerRef,style:transformInnerStyles},react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{ref:ref,className:className,style:style,children:children})))):null==(_root$current2=root.current)||_root$current2.render(react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{ref:ref,style:styles,className:className,children:children}))}));const visible=react__WEBPACK_IMPORTED_MODULE_0__.useRef(!0);return(0,_react_three_fiber__WEBPACK_IMPORTED_MODULE_3__.x)((()=>{if(group.current){camera.updateMatrixWorld(),group.current.updateWorldMatrix(!0,!1);const vec=transform?oldPosition.current:calculatePosition(group.current,camera,size);if(transform||Math.abs(oldZoom.current-camera.zoom)>eps||Math.abs(oldPosition.current[0]-vec[0])>eps||Math.abs(oldPosition.current[1]-vec[1])>eps){const isBehindCamera=function isObjectBehindCamera(el,camera){const objectPos=v1.setFromMatrixPosition(el.matrixWorld),cameraPos=v2.setFromMatrixPosition(camera.matrixWorld),deltaCamObj=objectPos.sub(cameraPos),camDir=camera.getWorldDirection(v3);return deltaCamObj.angleTo(camDir)>Math.PI/2}(group.current,camera);let raytraceTarget=!1;"boolean"==typeof occlude?!0===occlude&&(raytraceTarget=[scene]):Array.isArray(occlude)&&(raytraceTarget=occlude.map((item=>item.current)));const previouslyVisible=visible.current;if(raytraceTarget){const isvisible=function isObjectVisible(el,camera,raycaster,occlude){const elPos=v1.setFromMatrixPosition(el.matrixWorld),screenPos=elPos.clone();screenPos.project(camera),raycaster.setFromCamera(screenPos,camera);const intersects=raycaster.intersectObjects(occlude,!0);if(intersects.length){const intersectionDistance=intersects[0].distance;return elPos.distanceTo(raycaster.ray.origin){const nextState="function"==typeof partial?partial(state):partial;if(nextState!==state){const previousState=state;state=replace?nextState:Object.assign({},state,nextState),listeners.forEach((listener=>listener(state,previousState)))}},getState=()=>state,api={setState:setState,getState:getState,subscribe:(listener,selector,equalityFn)=>selector||equalityFn?((listener,selector=getState,equalityFn=Object.is)=>{console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware");let currentSlice=selector(state);function listenerToAdd(){const nextSlice=selector(state);if(!equalityFn(currentSlice,nextSlice)){const previousSlice=currentSlice;listener(currentSlice=nextSlice,previousSlice)}}return listeners.add(listenerToAdd),()=>listeners.delete(listenerToAdd)})(listener,selector,equalityFn):(listeners.add(listener),()=>listeners.delete(listener)),destroy:()=>listeners.clear()};return state=createState(setState,getState,api),api}const useIsomorphicLayoutEffect="undefined"==typeof window||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent)?react.useEffect:react.useLayoutEffect;var react_reconciler=__webpack_require__("./node_modules/react-reconciler/index.js"),react_reconciler_default=__webpack_require__.n(react_reconciler),scheduler=__webpack_require__("./node_modules/scheduler/index.js"),dist=__webpack_require__("./node_modules/suspend-react/dist/index.js");const isOrthographicCamera=def=>def&&def.isOrthographicCamera,index_4f1a8e2f_esm_useIsomorphicLayoutEffect="undefined"==typeof window||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent)?react.useEffect:react.useLayoutEffect;function useMutableCallback(fn){const ref=react.useRef(fn);return index_4f1a8e2f_esm_useIsomorphicLayoutEffect((()=>{ref.current=fn}),[fn]),ref}function Block({set:set}){return index_4f1a8e2f_esm_useIsomorphicLayoutEffect((()=>(set(new Promise((()=>null))),()=>set(!1))),[set]),null}class ErrorBoundary extends react.Component{constructor(...args){super(...args),this.state={error:!1}}componentDidCatch(error){this.props.set(error)}render(){return this.state.error?null:this.props.children}}ErrorBoundary.getDerivedStateFromError=()=>({error:!0});function calculateDpr(dpr){return Array.isArray(dpr)?Math.min(Math.max(dpr[0],window.devicePixelRatio),dpr[1]):dpr}const getRootState=obj=>{var _r3f;return null==(_r3f=obj.__r3f)?void 0:_r3f.root.getState()},is={obj:a=>a===Object(a)&&!is.arr(a)&&"function"!=typeof a,fun:a=>"function"==typeof a,str:a=>"string"==typeof a,num:a=>"number"==typeof a,boo:a=>"boolean"==typeof a,und:a=>void 0===a,arr:a=>Array.isArray(a),equ(a,b,{arrays:arrays="shallow",objects:objects="reference",strict:strict=!0}={}){if(typeof a!=typeof b||!!a!=!!b)return!1;if(is.str(a)||is.num(a))return a===b;const isObj=is.obj(a);if(isObj&&"reference"===objects)return a===b;const isArr=is.arr(a);if(isArr&&"reference"===arrays)return a===b;if((isArr||isObj)&&a===b)return!0;let i;for(i in a)if(!(i in b))return!1;for(i in strict?b:a)if(a[i]!==b[i])return!1;if(is.und(i)){if(isArr&&0===a.length&&0===b.length)return!0;if(isObj&&0===Object.keys(a).length&&0===Object.keys(b).length)return!0;if(a!==b)return!1}return!0}};function buildGraph(object){const data={nodes:{},materials:{}};return object&&object.traverse((obj=>{obj.name&&(data.nodes[obj.name]=obj),obj.material&&!data.materials[obj.material.name]&&(data.materials[obj.material.name]=obj.material)})),data}function prepare(object,state){const instance=object;return(null!=state&&state.primitive||!instance.__r3f)&&(instance.__r3f={type:"",root:null,previousAttach:null,memoizedProps:{},eventCount:0,handlers:{},objects:[],parent:null,...state}),object}function resolve(instance,key){let target=instance;if(key.includes("-")){const entries=key.split("-"),last=entries.pop();return target=entries.reduce(((acc,key)=>acc[key]),instance),{target:target,key:last}}return{target:target,key:key}}const INDEX_REGEX=/-\d+$/;function attach(parent,child,type){if(is.str(type)){if(INDEX_REGEX.test(type)){const root=type.replace(INDEX_REGEX,""),{target:target,key:key}=resolve(parent,root);Array.isArray(target[key])||(target[key]=[])}const{target:target,key:key}=resolve(parent,type);child.__r3f.previousAttach=target[key],target[key]=child}else child.__r3f.previousAttach=type(parent,child)}function detach(parent,child,type){var _child$__r3f,_child$__r3f2;if(is.str(type)){const{target:target,key:key}=resolve(parent,type),previous=child.__r3f.previousAttach;void 0===previous?delete target[key]:target[key]=previous}else null==(_child$__r3f=child.__r3f)||null==_child$__r3f.previousAttach||_child$__r3f.previousAttach(parent,child);null==(_child$__r3f2=child.__r3f)||delete _child$__r3f2.previousAttach}function diffProps(instance,{children:cN,key:kN,ref:rN,...props},{children:cP,key:kP,ref:rP,...previous}={},remove=!1){var _instance$__r3f;const localState=null!=(_instance$__r3f=null==instance?void 0:instance.__r3f)?_instance$__r3f:{},entries=Object.entries(props),changes=[];if(remove){const previousKeys=Object.keys(previous);for(let i=0;i{var _instance$__r3f2;if(null!=(_instance$__r3f2=instance.__r3f)&&_instance$__r3f2.primitive&&"object"===key)return;if(is.equ(value,previous[key]))return;if(/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key))return changes.push([key,value,!0,[]]);let entries=[];key.includes("-")&&(entries=key.split("-")),changes.push([key,value,!1,entries])}));const memoized={...props};return localState.memoizedProps&&localState.memoizedProps.args&&(memoized.args=localState.memoizedProps.args),localState.memoizedProps&&localState.memoizedProps.attach&&(memoized.attach=localState.memoizedProps.attach),{memoized:memoized,changes:changes}}function applyProps$1(instance,data){var _instance$__r3f3,_root$getState;const localState=null!=(_instance$__r3f3=instance.__r3f)?_instance$__r3f3:{},root=localState.root,rootState=null!=(_root$getState=null==root||null==root.getState?void 0:root.getState())?_root$getState:{},{memoized:memoized,changes:changes}=(def=data)&&def.memoized&&def.changes?data:diffProps(instance,data);var def;const prevHandlers=localState.eventCount;if(instance.__r3f&&(instance.__r3f.memoizedProps=memoized),changes.forEach((([key,value,isEvent,keys])=>{let currentInstance=instance,targetProp=currentInstance[key];if(keys.length&&(targetProp=keys.reduce(((acc,key)=>acc[key]),instance),!targetProp||!targetProp.set)){const[name,...reverseEntries]=keys.reverse();currentInstance=reverseEntries.reverse().reduce(((acc,key)=>acc[key]),instance),key=name}var _memoized$args;if("__defaultremove"===value)if(targetProp&&targetProp.constructor)value=new targetProp.constructor(...null!=(_memoized$args=memoized.args)?_memoized$args:[]);else if(currentInstance.constructor){var _currentInstance$__r;const defaultClassCall=new currentInstance.constructor(...null!=(_currentInstance$__r=currentInstance.__r3f.memoizedProps.args)?_currentInstance$__r:[]);value=defaultClassCall[targetProp],defaultClassCall.dispose&&defaultClassCall.dispose()}else value=0;if(isEvent)value?localState.handlers[key]=value:delete localState.handlers[key],localState.eventCount=Object.keys(localState.handlers).length;else if(targetProp&&targetProp.set&&(targetProp.copy||targetProp instanceof three_module.Layers)){if(Array.isArray(value))targetProp.fromArray?targetProp.fromArray(value):targetProp.set(...value);else if(targetProp.copy&&value&&value.constructor&&targetProp.constructor.name===value.constructor.name)targetProp.copy(value);else if(void 0!==value){const isColor=targetProp instanceof three_module.Color;!isColor&&targetProp.setScalar?targetProp.setScalar(value):targetProp instanceof three_module.Layers&&value instanceof three_module.Layers?targetProp.mask=value.mask:targetProp.set(value);!0||rootState.linear||!isColor||targetProp.convertSRGBToLinear()}}else currentInstance[key]=value,!rootState.linear&¤tInstance[key]instanceof three_module.Texture&&(currentInstance[key].encoding=three_module.sRGBEncoding);invalidateInstance(instance)})),localState.parent&&rootState.internal&&instance.raycast&&prevHandlers!==localState.eventCount){const index=rootState.internal.interaction.indexOf(instance);index>-1&&rootState.internal.interaction.splice(index,1),localState.eventCount&&rootState.internal.interaction.push(instance)}return changes.length&&instance.parent&&updateInstance(instance),instance}function invalidateInstance(instance){var _instance$__r3f4,_instance$__r3f4$root;const state=null==(_instance$__r3f4=instance.__r3f)||null==(_instance$__r3f4$root=_instance$__r3f4.root)||null==_instance$__r3f4$root.getState?void 0:_instance$__r3f4$root.getState();state&&0===state.internal.frames&&state.invalidate()}function updateInstance(instance){null==instance.onUpdate||instance.onUpdate(instance)}function updateCamera(camera,size){camera.manual||(isOrthographicCamera(camera)?(camera.left=size.width/-2,camera.right=size.width/2,camera.top=size.height/2,camera.bottom=size.height/-2):camera.aspect=size.width/size.height,camera.updateProjectionMatrix(),camera.updateMatrixWorld())}function makeId(event){return(event.eventObject||event.object).uuid+"/"+event.index+event.instanceId}function releaseInternalPointerCapture(capturedMap,obj,captures,pointerId){const captureData=captures.get(obj);captureData&&(captures.delete(obj),0===captures.size&&(capturedMap.delete(pointerId),captureData.target.releasePointerCapture(pointerId)))}function createEvents(store){const temp=new three_module.Vector3;function filterPointerEvents(objects){return objects.filter((obj=>["Move","Over","Enter","Out","Leave"].some((name=>{var _r3f;return null==(_r3f=obj.__r3f)?void 0:_r3f.handlers["onPointer"+name]}))))}function cancelPointer(intersections){const{internal:internal}=store.getState();Array.from(internal.hovered.values()).forEach((hoveredObj=>{if(!intersections.length||!intersections.find((hit=>hit.object===hoveredObj.object&&hit.index===hoveredObj.index&&hit.instanceId===hoveredObj.instanceId))){const instance=hoveredObj.eventObject.__r3f,handlers=null==instance?void 0:instance.handlers;if(internal.hovered.delete(makeId(hoveredObj)),null!=instance&&instance.eventCount){const data={...hoveredObj,intersections:intersections};null==handlers.onPointerOut||handlers.onPointerOut(data),null==handlers.onPointerLeave||handlers.onPointerLeave(data)}}}))}function pointerMissed(event,objects){objects.forEach((object=>{var _r3f3;return null==(_r3f3=object.__r3f)||null==_r3f3.handlers.onPointerMissed?void 0:_r3f3.handlers.onPointerMissed(event)}))}return{handlePointer:name=>{switch(name){case"onPointerLeave":case"onPointerCancel":return()=>cancelPointer([]);case"onLostPointerCapture":return event=>{const{internal:internal}=store.getState();"pointerId"in event&&!internal.capturedMap.has(event.pointerId)&&(internal.capturedMap.delete(event.pointerId),cancelPointer([]))}}return event=>{const{onPointerMissed:onPointerMissed,internal:internal}=store.getState();internal.lastEvent.current=event;const isPointerMove="onPointerMove"===name,isClickEvent="onClick"===name||"onContextMenu"===name||"onDoubleClick"===name,hits=function intersect(event,filter){const state=store.getState(),duplicates=new Set,intersections=[],eventsObjects=filter?filter(state.internal.interaction):state.internal.interaction;eventsObjects.forEach((obj=>{const state=getRootState(obj);state&&(state.raycaster.camera=void 0)})),state.previousRoot||null==state.events.compute||state.events.compute(event,state);let hits=eventsObjects.flatMap((obj=>{const state=getRootState(obj);return state&&state.events.enabled&&null!==state.raycaster.camera?(void 0===state.raycaster.camera&&(null==state.events.compute||state.events.compute(event,state,null==(_state$previousRoot=state.previousRoot)?void 0:_state$previousRoot.getState()),void 0===state.raycaster.camera&&(state.raycaster.camera=null)),state.raycaster.camera?state.raycaster.intersectObject(obj,!0):[]):[];var _state$previousRoot})).sort(((a,b)=>{const aState=getRootState(a.object),bState=getRootState(b.object);return aState&&bState?bState.events.priority-aState.events.priority||a.distance-b.distance:0})).filter((item=>{const id=makeId(item);return!duplicates.has(id)&&(duplicates.add(id),!0)}));state.events.filter&&(hits=state.events.filter(hits,state));for(const hit of hits){let eventObject=hit.object;for(;eventObject;){var _r3f2;null!=(_r3f2=eventObject.__r3f)&&_r3f2.eventCount&&intersections.push({...hit,eventObject:eventObject}),eventObject=eventObject.parent}}if("pointerId"in event&&state.internal.capturedMap.has(event.pointerId))for(let captureData of state.internal.capturedMap.get(event.pointerId).values())intersections.push(captureData.intersection);return intersections}(event,isPointerMove?filterPointerEvents:void 0),delta=isClickEvent?function calculateDistance(event){const{internal:internal}=store.getState(),dx=event.offsetX-internal.initialClick[0],dy=event.offsetY-internal.initialClick[1];return Math.round(Math.sqrt(dx*dx+dy*dy))}(event):0;"onPointerDown"===name&&(internal.initialClick=[event.offsetX,event.offsetY],internal.initialHits=hits.map((hit=>hit.eventObject))),isClickEvent&&!hits.length&&delta<=2&&(pointerMissed(event,internal.interaction),onPointerMissed&&onPointerMissed(event)),isPointerMove&&cancelPointer(hits),function handleIntersects(intersections,event,delta,callback){const{raycaster:raycaster,pointer:pointer,camera:camera,internal:internal}=store.getState();if(intersections.length){const unprojectedPoint=temp.set(pointer.x,pointer.y,0).unproject(camera),localState={stopped:!1};for(const hit of intersections){const hasPointerCapture=id=>{var _internal$capturedMap,_internal$capturedMap2;return null!=(_internal$capturedMap=null==(_internal$capturedMap2=internal.capturedMap.get(id))?void 0:_internal$capturedMap2.has(hit.eventObject))&&_internal$capturedMap},setPointerCapture=id=>{const captureData={intersection:hit,target:event.target};internal.capturedMap.has(id)?internal.capturedMap.get(id).set(hit.eventObject,captureData):internal.capturedMap.set(id,new Map([[hit.eventObject,captureData]])),event.target.setPointerCapture(id)},releasePointerCapture=id=>{const captures=internal.capturedMap.get(id);captures&&releaseInternalPointerCapture(internal.capturedMap,hit.eventObject,captures,id)};let extractEventProps={};for(let prop in event){let property=event[prop];"function"!=typeof property&&(extractEventProps[prop]=property)}let raycastEvent={...hit,...extractEventProps,pointer:pointer,intersections:intersections,stopped:localState.stopped,delta:delta,unprojectedPoint:unprojectedPoint,ray:raycaster.ray,camera:camera,stopPropagation:()=>{const capturesForPointer="pointerId"in event&&internal.capturedMap.get(event.pointerId);(!capturesForPointer||capturesForPointer.has(hit.eventObject))&&(raycastEvent.stopped=localState.stopped=!0,internal.hovered.size&&Array.from(internal.hovered.values()).find((i=>i.eventObject===hit.eventObject)))&&cancelPointer([...intersections.slice(0,intersections.indexOf(hit)),hit])},target:{hasPointerCapture:hasPointerCapture,setPointerCapture:setPointerCapture,releasePointerCapture:releasePointerCapture},currentTarget:{hasPointerCapture:hasPointerCapture,setPointerCapture:setPointerCapture,releasePointerCapture:releasePointerCapture},nativeEvent:event};if(callback(raycastEvent),!0===localState.stopped)break}}return intersections}(hits,event,delta,(data=>{const eventObject=data.eventObject,instance=eventObject.__r3f,handlers=null==instance?void 0:instance.handlers;if(null!=instance&&instance.eventCount)if(isPointerMove){if(handlers.onPointerOver||handlers.onPointerEnter||handlers.onPointerOut||handlers.onPointerLeave){const id=makeId(data),hoveredItem=internal.hovered.get(id);hoveredItem?hoveredItem.stopped&&data.stopPropagation():(internal.hovered.set(id,data),null==handlers.onPointerOver||handlers.onPointerOver(data),null==handlers.onPointerEnter||handlers.onPointerEnter(data))}null==handlers.onPointerMove||handlers.onPointerMove(data)}else{const handler=handlers[name];handler?isClickEvent&&!internal.initialHits.includes(eventObject)||(pointerMissed(event,internal.interaction.filter((object=>!internal.initialHits.includes(object)))),handler(data)):isClickEvent&&internal.initialHits.includes(eventObject)&&pointerMissed(event,internal.interaction.filter((object=>!internal.initialHits.includes(object))))}}))}}}}let catalogue={},extend=objects=>{catalogue={...catalogue,...objects}};const isRenderer=def=>!(null==def||!def.render),context=react.createContext(null),index_4f1a8e2f_esm_createStore=(invalidate,advance)=>{const rootState=function esm_create(createState){const api="function"==typeof createState?createStore(createState):createState,useStore=(selector=api.getState,equalityFn=Object.is)=>{const[,forceUpdate]=(0,react.useReducer)((c=>c+1),0),state=api.getState(),stateRef=(0,react.useRef)(state),selectorRef=(0,react.useRef)(selector),equalityFnRef=(0,react.useRef)(equalityFn),erroredRef=(0,react.useRef)(!1),currentSliceRef=(0,react.useRef)();let newStateSlice;void 0===currentSliceRef.current&&(currentSliceRef.current=selector(state));let hasNewStateSlice=!1;(stateRef.current!==state||selectorRef.current!==selector||equalityFnRef.current!==equalityFn||erroredRef.current)&&(newStateSlice=selector(state),hasNewStateSlice=!equalityFn(currentSliceRef.current,newStateSlice)),useIsomorphicLayoutEffect((()=>{hasNewStateSlice&&(currentSliceRef.current=newStateSlice),stateRef.current=state,selectorRef.current=selector,equalityFnRef.current=equalityFn,erroredRef.current=!1}));const stateBeforeSubscriptionRef=(0,react.useRef)(state);useIsomorphicLayoutEffect((()=>{const listener=()=>{try{const nextState=api.getState(),nextStateSlice=selectorRef.current(nextState);equalityFnRef.current(currentSliceRef.current,nextStateSlice)||(stateRef.current=nextState,currentSliceRef.current=nextStateSlice,forceUpdate())}catch(error){erroredRef.current=!0,forceUpdate()}},unsubscribe=api.subscribe(listener);return api.getState()!==stateBeforeSubscriptionRef.current&&listener(),unsubscribe}),[]);const sliceToReturn=hasNewStateSlice?newStateSlice:currentSliceRef.current;return(0,react.useDebugValue)(sliceToReturn),sliceToReturn};return Object.assign(useStore,api),useStore[Symbol.iterator]=function(){console.warn("[useStore, api] = create() is deprecated and will be removed in v4");const items=[useStore,api];return{next(){const done=items.length<=0;return{value:items.shift(),done:done}}}},useStore}(((set,get)=>{const position=new three_module.Vector3,defaultTarget=new three_module.Vector3,tempTarget=new three_module.Vector3;function getCurrentViewport(camera=get().camera,target=defaultTarget,size=get().size){const{width:width,height:height}=size,aspect=width/height;target instanceof three_module.Vector3?tempTarget.copy(target):tempTarget.set(...target);const distance=camera.getWorldPosition(position).distanceTo(tempTarget);if(isOrthographicCamera(camera))return{width:width/camera.zoom,height:height/camera.zoom,factor:1,distance:distance,aspect:aspect};{const fov=camera.fov*Math.PI/180,h=2*Math.tan(fov/2)*distance,w=h*(width/height);return{width:w,height:h,factor:width/w,distance:distance,aspect:aspect}}}let performanceTimeout;const setPerformanceCurrent=current=>set((state=>({performance:{...state.performance,current:current}}))),pointer=new three_module.Vector2;return{set:set,get:get,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},xr:null,invalidate:(frames=1)=>invalidate(get(),frames),advance:(timestamp,runGlobalEffects)=>advance(timestamp,runGlobalEffects,get()),legacy:!1,linear:!1,flat:!1,scene:prepare(new three_module.Scene),controls:null,clock:new three_module.Clock,pointer:pointer,mouse:pointer,frameloop:"always",onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{const state=get();performanceTimeout&&clearTimeout(performanceTimeout),state.performance.current!==state.performance.min&&setPerformanceCurrent(state.performance.min),performanceTimeout=setTimeout((()=>setPerformanceCurrent(get().performance.max)),state.performance.debounce)}},size:{width:0,height:0,updateStyle:!1},viewport:{initialDpr:0,dpr:0,width:0,height:0,aspect:0,distance:0,factor:0,getCurrentViewport:getCurrentViewport},setEvents:events=>set((state=>({...state,events:{...state.events,...events}}))),setSize:(width,height,updateStyle)=>{const camera=get().camera,size={width:width,height:height,updateStyle:updateStyle};set((state=>({size:size,viewport:{...state.viewport,...getCurrentViewport(camera,defaultTarget,size)}})))},setDpr:dpr=>set((state=>{const resolved=calculateDpr(dpr);return{viewport:{...state.viewport,dpr:resolved,initialDpr:state.viewport.initialDpr||resolved}}})),setFrameloop:(frameloop="always")=>{const clock=get().clock;clock.stop(),clock.elapsedTime=0,"never"!==frameloop&&(clock.start(),clock.elapsedTime=0),set((()=>({frameloop:frameloop})))},previousRoot:void 0,internal:{active:!1,priority:0,frames:0,lastEvent:react.createRef(),interaction:[],hovered:new Map,subscribers:[],initialClick:[0,0],initialHits:[],capturedMap:new Map,subscribe:(ref,priority,store)=>{const internal=get().internal;return internal.priority=internal.priority+(priority>0?1:0),internal.subscribers.push({ref:ref,priority:priority,store:store}),internal.subscribers=internal.subscribers.sort(((a,b)=>a.priority-b.priority)),()=>{const internal=get().internal;null!=internal&&internal.subscribers&&(internal.priority=internal.priority-(priority>0?1:0),internal.subscribers=internal.subscribers.filter((s=>s.ref!==ref)))}}}}})),state=rootState.getState();let oldSize=state.size,oldDpr=state.viewport.dpr,oldCamera=state.camera;return rootState.subscribe((()=>{const{camera:camera,size:size,viewport:viewport,gl:gl,set:set}=rootState.getState();size===oldSize&&viewport.dpr===oldDpr||(oldSize=size,oldDpr=viewport.dpr,updateCamera(camera,size),gl.setPixelRatio(viewport.dpr),gl.setSize(size.width,size.height,size.updateStyle)),camera!==oldCamera&&(oldCamera=camera,set((state=>({viewport:{...state.viewport,...state.viewport.getCurrentViewport(camera)}}))))})),rootState.subscribe((state=>invalidate(state))),rootState};let i,globalEffects=[],globalAfterEffects=[],globalTailEffects=[];function run(effects,timestamp){for(i=0;istate),equalityFn){return useStore()(selector,equalityFn)}function useFrame(callback,renderPriority=0){const store=useStore(),subscribe=store.getState().internal.subscribe,ref=useMutableCallback(callback);return index_4f1a8e2f_esm_useIsomorphicLayoutEffect((()=>subscribe(ref,renderPriority,store)),[renderPriority,subscribe,store]),null}function loadingFn(extensions,onProgress){return function(Proto,...input){const loader=new Proto;return extensions&&extensions(loader),Promise.all(input.map((input=>new Promise(((res,reject)=>loader.load(input,(data=>{data.scene&&Object.assign(data,buildGraph(data.scene)),res(data)}),onProgress,(error=>reject(`Could not load ${input}: ${error.message}`))))))))}}function useLoader(Proto,input,extensions,onProgress){const keys=Array.isArray(input)?input:[input],results=(0,dist.Rq)(loadingFn(extensions,onProgress),[Proto,...keys],{equal:is.equ});return Array.isArray(input)?results:results[0]}useLoader.preload=function(Proto,input,extensions){const keys=Array.isArray(input)?input:[input];return(0,dist.MA)(loadingFn(extensions),[Proto,...keys])},useLoader.clear=function(Proto,input){const keys=Array.isArray(input)?input:[input];return(0,dist.ZH)([Proto,...keys])};const roots=new Map,{invalidate:invalidate,advance:advance}=function createLoop(roots){let repeat,frame,state,running=!1;function loop(timestamp){if(frame=requestAnimationFrame(loop),running=!0,repeat=0,globalEffects.length&&run(globalEffects,timestamp),roots.forEach((root=>{var _state$gl$xr;state=root.store.getState(),!state.internal.active||!("always"===state.frameloop||state.internal.frames>0)||null!=(_state$gl$xr=state.gl.xr)&&_state$gl$xr.isPresenting||(repeat+=render$1(timestamp,state))})),globalAfterEffects.length&&run(globalAfterEffects,timestamp),0===repeat)return globalTailEffects.length&&run(globalTailEffects,timestamp),running=!1,cancelAnimationFrame(frame)}return{loop:loop,invalidate:function invalidate(state,frames=1){var _state$gl$xr2;if(!state)return roots.forEach((root=>invalidate(root.store.getState())),frames);null!=(_state$gl$xr2=state.gl.xr)&&_state$gl$xr2.isPresenting||!state.internal.active||"never"===state.frameloop||(state.internal.frames=Math.min(60,state.internal.frames+frames),running||(running=!0,requestAnimationFrame(loop)))},advance:function advance(timestamp,runGlobalEffects=!0,state,frame){runGlobalEffects&&run(globalEffects,timestamp),state?render$1(timestamp,state,frame):roots.forEach((root=>render$1(timestamp,root.store.getState()))),runGlobalEffects&&run(globalAfterEffects,timestamp)}}}(roots),{reconciler:reconciler,applyProps:applyProps}=function createRenderer(roots,getEventPriority){function createInstance(type,{args:args=[],attach:attach,...props},root){let instance,name=`${type[0].toUpperCase()}${type.slice(1)}`;if(void 0===attach&&(name.endsWith("Geometry")?attach="geometry":name.endsWith("Material")&&(attach="material")),"primitive"===type){if(void 0===props.object)throw"Primitives without 'object' are invalid!";instance=prepare(props.object,{type:type,root:root,attach:attach,primitive:!0})}else{const target=catalogue[name];if(!target)throw`${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`;if(!Array.isArray(args))throw"The args prop must be an array!";instance=prepare(new target(...args),{type:type,root:root,attach:attach,memoizedProps:{args:args}})}return"inject"!==name&&applyProps$1(instance,props),instance}function appendChild(parentInstance,child){let added=!1;var _child$__r3f,_parentInstance$__r3f;child&&(null!=(_child$__r3f=child.__r3f)&&_child$__r3f.attach?attach(parentInstance,child,child.__r3f.attach):child.isObject3D&&parentInstance.isObject3D&&(parentInstance.add(child),added=!0),added||null==(_parentInstance$__r3f=parentInstance.__r3f)||_parentInstance$__r3f.objects.push(child),child.__r3f||prepare(child,{}),child.__r3f.parent=parentInstance,updateInstance(child),invalidateInstance(child))}function insertBefore(parentInstance,child,beforeChild){let added=!1;if(child){var _child$__r3f2,_parentInstance$__r3f2;if(null!=(_child$__r3f2=child.__r3f)&&_child$__r3f2.attach)attach(parentInstance,child,child.__r3f.attach);else if(child.isObject3D&&parentInstance.isObject3D){child.parent=parentInstance,child.dispatchEvent({type:"added"});const restSiblings=parentInstance.children.filter((sibling=>sibling!==child)),index=restSiblings.indexOf(beforeChild);parentInstance.children=[...restSiblings.slice(0,index),child,...restSiblings.slice(index)],added=!0}added||null==(_parentInstance$__r3f2=parentInstance.__r3f)||_parentInstance$__r3f2.objects.push(child),child.__r3f||prepare(child,{}),child.__r3f.parent=parentInstance,updateInstance(child),invalidateInstance(child)}}function removeRecursive(array,parent,dispose=!1){array&&[...array].forEach((child=>removeChild(parent,child,dispose)))}function removeChild(parentInstance,child,dispose){if(child){var _parentInstance$__r3f3,_child$__r3f3,_child$__r3f5;if(child.__r3f&&(child.__r3f.parent=null),null!=(_parentInstance$__r3f3=parentInstance.__r3f)&&_parentInstance$__r3f3.objects&&(parentInstance.__r3f.objects=parentInstance.__r3f.objects.filter((x=>x!==child))),null!=(_child$__r3f3=child.__r3f)&&_child$__r3f3.attach)detach(parentInstance,child,child.__r3f.attach);else if(child.isObject3D&&parentInstance.isObject3D){var _child$__r3f4;parentInstance.remove(child),null!=(_child$__r3f4=child.__r3f)&&_child$__r3f4.root&&function removeInteractivity(store,object){const{internal:internal}=store.getState();internal.interaction=internal.interaction.filter((o=>o!==object)),internal.initialHits=internal.initialHits.filter((o=>o!==object)),internal.hovered.forEach(((value,key)=>{value.eventObject!==object&&value.object!==object||internal.hovered.delete(key)})),internal.capturedMap.forEach(((captures,pointerId)=>{releaseInternalPointerCapture(internal.capturedMap,object,captures,pointerId)}))}(child.__r3f.root,child)}const isPrimitive=null==(_child$__r3f5=child.__r3f)?void 0:_child$__r3f5.primitive,shouldDispose=void 0===dispose?null!==child.dispose&&!isPrimitive:dispose;var _child$__r3f6;if(!isPrimitive)removeRecursive(null==(_child$__r3f6=child.__r3f)?void 0:_child$__r3f6.objects,child,shouldDispose),removeRecursive(child.children,child,shouldDispose);child.__r3f&&(delete child.__r3f.root,delete child.__r3f.objects,delete child.__r3f.handlers,delete child.__r3f.memoizedProps,isPrimitive||delete child.__r3f),shouldDispose&&child.dispose&&"Scene"!==child.type&&(0,scheduler.unstable_scheduleCallback)(scheduler.unstable_IdlePriority,(()=>{try{child.dispose()}catch(e){}})),invalidateInstance(parentInstance)}}return{reconciler:react_reconciler_default()({createInstance:createInstance,removeChild:removeChild,appendChild:appendChild,appendInitialChild:appendChild,insertBefore:insertBefore,supportsMicrotask:!0,warnsIfNotActing:!0,supportsMutation:!0,isPrimaryRenderer:!1,noTimeout:-1,appendChildToContainer:(container,child)=>{const scene=container.getState().scene;scene.__r3f.root=container,appendChild(scene,child)},removeChildFromContainer:(container,child)=>removeChild(container.getState().scene,child),insertInContainerBefore:(container,child,beforeChild)=>insertBefore(container.getState().scene,child,beforeChild),getRootHostContext:()=>null,getChildHostContext:parentHostContext=>parentHostContext,finalizeInitialChildren(instance){var _instance$__r3f2;return!!(null!=(_instance$__r3f2=null==instance?void 0:instance.__r3f)?_instance$__r3f2:{}).handlers},prepareUpdate(instance,type,oldProps,newProps){if(instance.__r3f.primitive&&newProps.object&&newProps.object!==instance)return[!0];{const{args:argsNew=[],children:cN,...restNew}=newProps,{args:argsOld=[],children:cO,...restOld}=oldProps;if(!Array.isArray(argsNew))throw"The args prop must be an array!";if(argsNew.some(((value,index)=>value!==argsOld[index])))return[!0];const diff=diffProps(instance,restNew,restOld,!0);return diff.changes.length?[!1,diff]:null}},commitUpdate(instance,[reconstruct,diff],type,oldProps,newProps,fiber){reconstruct?function switchInstance(instance,type,newProps,fiber){var _instance$__r3f;const parent=null==(_instance$__r3f=instance.__r3f)?void 0:_instance$__r3f.parent;if(!parent)return;const newInstance=createInstance(type,newProps,instance.__r3f.root);"primitive"!==type&&instance.children&&(instance.children.forEach((child=>appendChild(newInstance,child))),instance.children=[]),instance.__r3f.objects.forEach((child=>appendChild(newInstance,child))),instance.__r3f.objects=[],removeChild(parent,instance),appendChild(parent,newInstance),newInstance.raycast&&newInstance.__r3f.eventCount&&newInstance.__r3f.root.getState().internal.interaction.push(newInstance);[fiber,fiber.alternate].forEach((fiber=>{null!==fiber&&(fiber.stateNode=newInstance,fiber.ref&&("function"==typeof fiber.ref?fiber.ref(newInstance):fiber.ref.current=newInstance))}))}(instance,type,newProps,fiber):applyProps$1(instance,diff)},commitMount(instance,type,props,int){var _instance$__r3f3;const localState=null!=(_instance$__r3f3=instance.__r3f)?_instance$__r3f3:{};instance.raycast&&localState.handlers&&localState.eventCount&&instance.__r3f.root.getState().internal.interaction.push(instance)},getPublicInstance:instance=>instance,shouldDeprioritizeSubtree:()=>!1,prepareForCommit:()=>null,preparePortalMount:container=>prepare(container.getState().scene),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,detachDeletedInstance:()=>{},hideInstance(instance){var _instance$__r3f4;const{attach:type,parent:parent}=null!=(_instance$__r3f4=null==instance?void 0:instance.__r3f)?_instance$__r3f4:{};type&&parent&&detach(parent,instance,type),instance.isObject3D&&(instance.visible=!1),invalidateInstance(instance)},unhideInstance(instance,props){var _instance$__r3f5;const{attach:type,parent:parent}=null!=(_instance$__r3f5=null==instance?void 0:instance.__r3f)?_instance$__r3f5:{};type&&parent&&attach(parent,instance,type),(instance.isObject3D&&null==props.visible||props.visible)&&(instance.visible=!0),invalidateInstance(instance)},createTextInstance:()=>{},hideTextInstance:()=>{throw new Error("Text is not allowed in the R3F tree.")},unhideTextInstance:()=>{},getCurrentEventPriority:()=>getEventPriority?getEventPriority():constants.DefaultEventPriority,now:"undefined"!=typeof performance&&is.fun(performance.now)?performance.now:is.fun(Date.now)?Date.now:void 0,scheduleTimeout:is.fun(setTimeout)?setTimeout:void 0,cancelTimeout:is.fun(clearTimeout)?clearTimeout:void 0,setTimeout:is.fun(setTimeout)?setTimeout:void 0,clearTimeout:is.fun(clearTimeout)?clearTimeout:void 0}),applyProps:applyProps$1}}(0,(function getEventPriority(){var _window,_window$event;switch(null==(_window=window)||null==(_window$event=_window.event)?void 0:_window$event.type){case"click":case"contextmenu":case"dblclick":case"pointercancel":case"pointerdown":case"pointerup":return constants.DiscreteEventPriority;case"pointermove":case"pointerout":case"pointerover":case"pointerenter":case"pointerleave":case"wheel":return constants.ContinuousEventPriority;default:return constants.DefaultEventPriority}})),shallowLoose={objects:"shallow",strict:!1},createRendererInstance=(gl,canvas)=>{const customRenderer="function"==typeof gl?gl(canvas):gl;return isRenderer(customRenderer)?customRenderer:new three_module.WebGLRenderer({powerPreference:"high-performance",canvas:canvas,antialias:!0,alpha:!0,...gl})};function createRoot(canvas){let prevRoot=roots.get(canvas),prevFiber=null==prevRoot?void 0:prevRoot.fiber,prevStore=null==prevRoot?void 0:prevRoot.store;prevRoot&&console.warn("R3F.createRoot should only be called once!");const logRecoverableError="function"==typeof reportError?reportError:console.error,store=prevStore||index_4f1a8e2f_esm_createStore(invalidate,advance),fiber=prevFiber||reconciler.createContainer(store,constants.ConcurrentRoot,null,!1,null,"",logRecoverableError,null);let onCreated;prevRoot||roots.set(canvas,{fiber:fiber,store:store});let configured=!1;return{configure(props={}){var _canvas$parentElement,_canvas$parentElement2,_canvas$parentElement3,_canvas$parentElement4;let{gl:glConfig,size:size,events:events,onCreated:onCreatedCallback,shadows:shadows=!1,linear:linear=!1,flat:flat=!1,legacy:legacy=!1,orthographic:orthographic=!1,frameloop:frameloop="always",dpr:dpr=[1,2],performance:performance,raycaster:raycastOptions,camera:cameraOptions,onPointerMissed:onPointerMissed}=props,state=store.getState(),gl=state.gl;state.gl||state.set({gl:gl=createRendererInstance(glConfig,canvas)});let raycaster=state.raycaster;raycaster||state.set({raycaster:raycaster=new three_module.Raycaster});const{params:params,...options}=raycastOptions||{};if(is.equ(options,raycaster,shallowLoose)||applyProps(raycaster,{...options}),is.equ(params,raycaster.params,shallowLoose)||applyProps(raycaster,{params:{...raycaster.params,...params}}),!state.camera){const isCamera=cameraOptions instanceof three_module.Camera,camera=isCamera?cameraOptions:orthographic?new three_module.OrthographicCamera(0,0,0,0,.1,1e3):new three_module.PerspectiveCamera(75,0,.1,1e3);isCamera||(camera.position.z=5,cameraOptions&&applyProps(camera,cameraOptions),null!=cameraOptions&&cameraOptions.rotation||camera.lookAt(0,0,0)),state.set({camera:camera})}if(!state.xr){const handleXRFrame=(timestamp,frame)=>{const state=store.getState();"never"!==state.frameloop&&advance(timestamp,!0,state,frame)},handleSessionChange=()=>{const state=store.getState();state.gl.xr.enabled=state.gl.xr.isPresenting,state.gl.xr.setAnimationLoop(state.gl.xr.isPresenting?handleXRFrame:null),state.gl.xr.isPresenting||invalidate(state)},xr={connect(){const gl=store.getState().gl;gl.xr.addEventListener("sessionstart",handleSessionChange),gl.xr.addEventListener("sessionend",handleSessionChange)},disconnect(){const gl=store.getState().gl;gl.xr.removeEventListener("sessionstart",handleSessionChange),gl.xr.removeEventListener("sessionend",handleSessionChange)}};gl.xr&&xr.connect(),state.set({xr:xr})}if(gl.shadowMap){const isBoolean=is.boo(shadows);if(isBoolean&&gl.shadowMap.enabled!==shadows||!is.equ(shadows,gl.shadowMap,shallowLoose)){const old=gl.shadowMap.enabled;gl.shadowMap.enabled=!!shadows,isBoolean?gl.shadowMap.type=three_module.PCFSoftShadowMap:Object.assign(gl.shadowMap,shadows),old!==gl.shadowMap.enabled&&(gl.shadowMap.needsUpdate=!0)}}(function setDeep(obj,value,keys){const key=keys.pop(),target=keys.reduce(((acc,key)=>acc[key]),obj);return target[key]=value})(three_module,legacy,["ColorManagement","legacyMode"]);const outputEncoding=linear?three_module.LinearEncoding:three_module.sRGBEncoding,toneMapping=flat?three_module.NoToneMapping:three_module.ACESFilmicToneMapping;return gl.outputEncoding!==outputEncoding&&(gl.outputEncoding=outputEncoding),gl.toneMapping!==toneMapping&&(gl.toneMapping=toneMapping),state.legacy!==legacy&&state.set((()=>({legacy:legacy}))),state.linear!==linear&&state.set((()=>({linear:linear}))),state.flat!==flat&&state.set((()=>({flat:flat}))),!glConfig||is.fun(glConfig)||isRenderer(glConfig)||is.equ(glConfig,gl,shallowLoose)||applyProps(gl,glConfig),events&&!state.events.handlers&&state.set({events:events(store)}),dpr&&state.viewport.dpr!==calculateDpr(dpr)&&state.setDpr(dpr),size=size||{width:null!=(_canvas$parentElement=null==(_canvas$parentElement2=canvas.parentElement)?void 0:_canvas$parentElement2.clientWidth)?_canvas$parentElement:0,height:null!=(_canvas$parentElement3=null==(_canvas$parentElement4=canvas.parentElement)?void 0:_canvas$parentElement4.clientHeight)?_canvas$parentElement3:0},is.equ(size,state.size,shallowLoose)||state.setSize(size.width,size.height,size.updateStyle),state.frameloop!==frameloop&&state.setFrameloop(frameloop),state.onPointerMissed||state.set({onPointerMissed:onPointerMissed}),performance&&!is.equ(performance,state.performance,shallowLoose)&&state.set((state=>({performance:{...state.performance,...performance}}))),onCreated=onCreatedCallback,configured=!0,this},render(children){return configured||this.configure(),reconciler.updateContainer(react.createElement(Provider,{store:store,children:children,onCreated:onCreated,rootElement:canvas}),fiber,null,(()=>{})),store},unmount(){unmountComponentAtNode(canvas)}}}function Provider({store:store,children:children,onCreated:onCreated,rootElement:rootElement}){return index_4f1a8e2f_esm_useIsomorphicLayoutEffect((()=>{const state=store.getState();state.set((state=>({internal:{...state.internal,active:!0}}))),onCreated&&onCreated(state),store.getState().events.connected||null==state.events.connect||state.events.connect(rootElement)}),[]),react.createElement(context.Provider,{value:store},children)}function unmountComponentAtNode(canvas,callback){const root=roots.get(canvas),fiber=null==root?void 0:root.fiber;if(fiber){const state=null==root?void 0:root.store.getState();state&&(state.internal.active=!1),reconciler.updateContainer(null,fiber,null,(()=>{state&&setTimeout((()=>{try{var _state$gl,_state$gl$renderLists,_state$gl2,_state$gl3;null==state.events.disconnect||state.events.disconnect(),null==(_state$gl=state.gl)||null==(_state$gl$renderLists=_state$gl.renderLists)||null==_state$gl$renderLists.dispose||_state$gl$renderLists.dispose(),null==(_state$gl2=state.gl)||null==_state$gl2.forceContextLoss||_state$gl2.forceContextLoss(),null!=(_state$gl3=state.gl)&&_state$gl3.xr&&state.xr.disconnect(),function dispose(obj){obj.dispose&&"Scene"!==obj.type&&obj.dispose();for(const p in obj)null==p.dispose||p.dispose(),delete obj[p]}(state),roots.delete(canvas),callback&&callback(canvas)}catch(e){}}),500)}))}}reconciler.injectIntoDevTools({bundleType:0,rendererPackageName:"@react-three/fiber",version:react.version});react.unstable_act},"./node_modules/@react-three/fiber/dist/react-three-fiber.esm.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{Xz:function(){return Canvas}});var index_4f1a8e2f_esm=__webpack_require__("./node_modules/@react-three/fiber/dist/index-4f1a8e2f.esm.js"),esm_extends=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/extends.js"),react=__webpack_require__("./node_modules/react/index.js"),three_module=__webpack_require__("./node_modules/three/build/three.module.js"),node_modules_debounce=__webpack_require__("./node_modules/debounce/index.js"),debounce_default=__webpack_require__.n(node_modules_debounce);function useMeasure(_temp){let{debounce:debounce,scroll:scroll,polyfill:polyfill,offsetSize:offsetSize}=void 0===_temp?{debounce:0,scroll:!1,offsetSize:!1}:_temp;const ResizeObserver=polyfill||("undefined"==typeof window?class ResizeObserver{}:window.ResizeObserver);if(!ResizeObserver)throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");const[bounds,set]=(0,react.useState)({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),state=(0,react.useRef)({element:null,scrollContainers:null,resizeObserver:null,lastBounds:bounds}),scrollDebounce=debounce?"number"==typeof debounce?debounce:debounce.scroll:null,resizeDebounce=debounce?"number"==typeof debounce?debounce:debounce.resize:null,mounted=(0,react.useRef)(!1);(0,react.useEffect)((()=>(mounted.current=!0,()=>{mounted.current=!1})));const[forceRefresh,resizeChange,scrollChange]=(0,react.useMemo)((()=>{const callback=()=>{if(!state.current.element)return;const{left:left,top:top,width:width,height:height,bottom:bottom,right:right,x:x,y:y}=state.current.element.getBoundingClientRect(),size={left:left,top:top,width:width,height:height,bottom:bottom,right:right,x:x,y:y};state.current.element instanceof HTMLElement&&offsetSize&&(size.height=state.current.element.offsetHeight,size.width=state.current.element.offsetWidth),Object.freeze(size),mounted.current&&!areBoundsEqual(state.current.lastBounds,size)&&set(state.current.lastBounds=size)};return[callback,resizeDebounce?debounce_default()(callback,resizeDebounce):callback,scrollDebounce?debounce_default()(callback,scrollDebounce):callback]}),[set,offsetSize,scrollDebounce,resizeDebounce]);function removeListeners(){state.current.scrollContainers&&(state.current.scrollContainers.forEach((element=>element.removeEventListener("scroll",scrollChange,!0))),state.current.scrollContainers=null),state.current.resizeObserver&&(state.current.resizeObserver.disconnect(),state.current.resizeObserver=null)}function addListeners(){state.current.element&&(state.current.resizeObserver=new ResizeObserver(scrollChange),state.current.resizeObserver.observe(state.current.element),scroll&&state.current.scrollContainers&&state.current.scrollContainers.forEach((scrollContainer=>scrollContainer.addEventListener("scroll",scrollChange,{capture:!0,passive:!0}))))}return function useOnWindowScroll(onScroll,enabled){(0,react.useEffect)((()=>{if(enabled){const cb=onScroll;return window.addEventListener("scroll",cb,{capture:!0,passive:!0}),()=>{window.removeEventListener("scroll",cb,!0)}}}),[onScroll,enabled])}(scrollChange,Boolean(scroll)),function useOnWindowResize(onWindowResize){(0,react.useEffect)((()=>{const cb=onWindowResize;return window.addEventListener("resize",cb),()=>{window.removeEventListener("resize",cb)}}),[onWindowResize])}(resizeChange),(0,react.useEffect)((()=>{removeListeners(),addListeners()}),[scroll,scrollChange,resizeChange]),(0,react.useEffect)((()=>removeListeners),[]),[node=>{node&&node!==state.current.element&&(removeListeners(),state.current.element=node,state.current.scrollContainers=findScrollContainers(node),addListeners())},bounds,forceRefresh]}function findScrollContainers(element){const result=[];if(!element||element===document.body)return result;const{overflow:overflow,overflowX:overflowX,overflowY:overflowY}=window.getComputedStyle(element);return[overflow,overflowX,overflowY].some((prop=>"auto"===prop||"scroll"===prop))&&result.push(element),[...result,...findScrollContainers(element.parentElement)]}const keys=["x","y","top","bottom","left","right","width","height"],areBoundsEqual=(a,b)=>keys.every((key=>a[key]===b[key]));__webpack_require__("./node_modules/react-reconciler/constants.js"),__webpack_require__("./node_modules/react-reconciler/index.js"),__webpack_require__("./node_modules/scheduler/index.js");const DOM_EVENTS={onClick:["click",!1],onContextMenu:["contextmenu",!1],onDoubleClick:["dblclick",!1],onWheel:["wheel",!0],onPointerDown:["pointerdown",!0],onPointerUp:["pointerup",!0],onPointerLeave:["pointerleave",!0],onPointerMove:["pointermove",!0],onPointerCancel:["pointercancel",!0],onLostPointerCapture:["lostpointercapture",!0]};function createPointerEvents(store){const{handlePointer:handlePointer}=(0,index_4f1a8e2f_esm.c)(store);return{priority:1,enabled:!0,compute(event,state,previous){state.pointer.set(event.offsetX/state.size.width*2-1,-event.offsetY/state.size.height*2+1),state.raycaster.setFromCamera(state.pointer,state.camera)},connected:void 0,handlers:Object.keys(DOM_EVENTS).reduce(((acc,key)=>({...acc,[key]:handlePointer(key)})),{}),connect:target=>{var _events$handlers;const{set:set,events:events}=store.getState();null==events.disconnect||events.disconnect(),set((state=>({events:{...state.events,connected:target}}))),Object.entries(null!=(_events$handlers=events.handlers)?_events$handlers:[]).forEach((([name,event])=>{const[eventName,passive]=DOM_EVENTS[name];target.addEventListener(eventName,event,{passive:passive})}))},disconnect:()=>{const{set:set,events:events}=store.getState();var _events$handlers2;events.connected&&(Object.entries(null!=(_events$handlers2=events.handlers)?_events$handlers2:[]).forEach((([name,event])=>{if(events&&events.connected instanceof HTMLElement){const[eventName]=DOM_EVENTS[name];events.connected.removeEventListener(eventName,event)}})),set((state=>({events:{...state.events,connected:void 0}}))))}}}const Canvas=react.forwardRef((function Canvas({children:children,fallback:fallback,resize:resize,style:style,gl:gl,events:events=createPointerEvents,shadows:shadows,linear:linear,flat:flat,legacy:legacy,orthographic:orthographic,frameloop:frameloop,dpr:dpr,performance:performance,raycaster:raycaster,camera:camera,onPointerMissed:onPointerMissed,onCreated:onCreated,...props},forwardedRef){react.useMemo((()=>(0,index_4f1a8e2f_esm.e)(three_module)),[]);const[containerRef,{width:width,height:height}]=useMeasure({scroll:!0,debounce:{scroll:50,resize:0},...resize}),canvasRef=react.useRef(null),divRef=react.useRef(null),[canvas,setCanvas]=react.useState(null);react.useImperativeHandle(forwardedRef,(()=>canvasRef.current));const handlePointerMissed=(0,index_4f1a8e2f_esm.u)(onPointerMissed),[block,setBlock]=react.useState(!1),[error,setError]=react.useState(!1);if(block)throw block;if(error)throw error;const root=react.useRef(null);return width>0&&height>0&&canvas&&(root.current||(root.current=(0,index_4f1a8e2f_esm.a)(canvas)),root.current.configure({gl:gl,events:events,shadows:shadows,linear:linear,flat:flat,legacy:legacy,orthographic:orthographic,frameloop:frameloop,dpr:dpr,performance:performance,raycaster:raycaster,camera:camera,size:{width:width,height:height},onPointerMissed:(...args)=>null==handlePointerMissed.current?void 0:handlePointerMissed.current(...args),onCreated:state=>{null==state.events.connect||state.events.connect(divRef.current),null==onCreated||onCreated(state)}}),root.current.render(react.createElement(index_4f1a8e2f_esm.E,{set:setError},react.createElement(react.Suspense,{fallback:react.createElement(index_4f1a8e2f_esm.B,{set:setBlock})},children)))),(0,index_4f1a8e2f_esm.b)((()=>{setCanvas(canvasRef.current)}),[]),react.useEffect((()=>{if(canvas)return()=>(0,index_4f1a8e2f_esm.d)(canvas)}),[canvas]),react.createElement("div",(0,esm_extends.Z)({ref:divRef,style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",...style}},props),react.createElement("div",{ref:containerRef,style:{width:"100%",height:"100%"}},react.createElement("canvas",{ref:canvasRef,style:{display:"block"}},fallback)))}))},"./node_modules/@storybook/addon-actions/dist/esm/index.js":function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{action:function(){return action},withActions:function(){return withActions}});"".concat("storybook/actions","/panel");var EVENT_ID="".concat("storybook/actions","/action-event"),v4=(__webpack_require__("./node_modules/@storybook/addon-actions/dist/esm/models/index.js"),__webpack_require__("./node_modules/core-js/modules/es.object.get-prototype-of.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.exec.js"),__webpack_require__("./node_modules/core-js/modules/es.function.name.js"),__webpack_require__("./node_modules/core-js/modules/es.object.get-own-property-descriptors.js"),__webpack_require__("./node_modules/core-js/modules/es.object.get-own-property-descriptor.js"),__webpack_require__("./node_modules/core-js/modules/es.object.assign.js"),__webpack_require__("./node_modules/core-js/modules/es.array.map.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.description.js"),__webpack_require__("./node_modules/core-js/modules/es.object.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.array.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.string.iterator.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.iterator.js"),__webpack_require__("./node_modules/uuid-browser/v4.js")),v4_default=__webpack_require__.n(v4),esm=__webpack_require__("./node_modules/@storybook/addons/dist/esm/index.js"),config={depth:10,clearOnStoryChange:!0,limit:50};function _typeof(obj){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}var findProto=function findProto(obj,callback){var proto=Object.getPrototypeOf(obj);return!proto||callback(proto)?proto:findProto(proto,callback)},isReactSyntheticEvent=function isReactSyntheticEvent(e){return Boolean("object"===_typeof(e)&&e&&findProto(e,(function(proto){return/^Synthetic(?:Base)?Event$/.test(proto.constructor.name)}))&&"function"==typeof e.persist)},serializeArg=function serializeArg(a){if(isReactSyntheticEvent(a)){var e=Object.create(a.constructor.prototype,Object.getOwnPropertyDescriptors(a));e.persist();var viewDescriptor=Object.getOwnPropertyDescriptor(e,"view"),view=null==viewDescriptor?void 0:viewDescriptor.value;return"object"===_typeof(view)&&"Window"===(null==view?void 0:view.constructor.name)&&Object.defineProperty(e,"view",Object.assign({},viewDescriptor,{value:Object.create(view.constructor.prototype)})),e}return a};function action(name){var options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},actionOptions=Object.assign({},config,options),handler=function actionHandler(){for(var channel=esm.KP.getChannel(),id=v4_default()(),minDepth=5,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];var serializedArgs=args.map(serializeArg),normalizedArgs=args.length>1?serializedArgs:serializedArgs[0],actionDisplayToEmit={id:id,count:0,data:{name:name,args:normalizedArgs},options:Object.assign({},actionOptions,{maxDepth:minDepth+(actionOptions.depth||3),allowFunction:actionOptions.allowFunction||!1})};channel.emit(EVENT_ID,actionDisplayToEmit)};return handler}__webpack_require__("./node_modules/core-js/modules/web.dom-collections.for-each.js"),__webpack_require__("./node_modules/core-js/modules/es.object.keys.js"),__webpack_require__("./node_modules/core-js/modules/es.array.slice.js"),__webpack_require__("./node_modules/core-js/modules/es.array.from.js");function _slicedToArray(arr,i){return function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function _iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function _unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}(arr,i)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i1?_len-1:0),_key=1;_key<_len;_key++)handles[_key-1]=arguments[_key];var actionsObject=actionsFn.apply(void 0,handles);return Object.entries(actionsObject).map((function(_ref){var _ref2=withActions_slicedToArray(_ref,2),key=_ref2[0],action=_ref2[1],_key$match2=withActions_slicedToArray(key.match(delegateEventSplitter),3),eventName=(_key$match2[0],_key$match2[1]),selector=_key$match2[2];return{eventName:eventName,handler:function handler(e){selector&&!hasMatchInAncestry(e.target,selector)||action(e)}}}))},applyEventHandlers=browser_default()((function(actionsFn){for(var _len2=arguments.length,handles=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++)handles[_key2-1]=arguments[_key2];(0,hooks.d4)((function(){if(null!=root){var handlers=createHandlers.apply(void 0,[actionsFn].concat(handles));return handlers.forEach((function(_ref3){var eventName=_ref3.eventName,handler=_ref3.handler;return root.addEventListener(eventName,handler)})),function(){return handlers.forEach((function(_ref4){var eventName=_ref4.eventName,handler=_ref4.handler;return root.removeEventListener(eventName,handler)}))}}}),[root,actionsFn,handles])}),(0,ts_dedent_esm.C)(withActions_templateObject||(withActions_templateObject=function withActions_taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}(["\n withActions(options) is deprecated, please configure addon-actions using the addParameter api:\n\n addParameters({\n actions: {\n handles: options\n },\n });\n "])))),withActions=(0,make_decorator.h)({name:"withActions",parameterName:"actions",skipIfNoParametersOrOptions:!0,wrapper:function wrapper(getStory,context,_ref5){var parameters=_ref5.parameters,options=_ref5.options;return function applyDeprecatedOptions(actionsFn,options){options&&applyEventHandlers(actionsFn,options)}(actions,options),parameters&¶meters.handles&&applyEventHandlers.apply(void 0,[actions].concat(_toConsumableArray(parameters.handles))),getStory(context)}});(module=__webpack_require__.hmd(module))&&module.hot},"./node_modules/@storybook/addon-actions/dist/esm/models/DecoratorFunction.js":function(){},"./node_modules/@storybook/addon-actions/dist/esm/models/HandlerFunction.js":function(){},"./node_modules/@storybook/addon-actions/dist/esm/models/index.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";var _DecoratorFunction__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/@storybook/addon-actions/dist/esm/models/DecoratorFunction.js");__webpack_require__.o(_DecoratorFunction__WEBPACK_IMPORTED_MODULE_0__,"action")&&__webpack_require__.d(__webpack_exports__,{action:function(){return _DecoratorFunction__WEBPACK_IMPORTED_MODULE_0__.action}}),__webpack_require__.o(_DecoratorFunction__WEBPACK_IMPORTED_MODULE_0__,"withActions")&&__webpack_require__.d(__webpack_exports__,{withActions:function(){return _DecoratorFunction__WEBPACK_IMPORTED_MODULE_0__.withActions}});var _HandlerFunction__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./node_modules/@storybook/addon-actions/dist/esm/models/HandlerFunction.js");__webpack_require__.o(_HandlerFunction__WEBPACK_IMPORTED_MODULE_1__,"action")&&__webpack_require__.d(__webpack_exports__,{action:function(){return _HandlerFunction__WEBPACK_IMPORTED_MODULE_1__.action}}),__webpack_require__.o(_HandlerFunction__WEBPACK_IMPORTED_MODULE_1__,"withActions")&&__webpack_require__.d(__webpack_exports__,{withActions:function(){return _HandlerFunction__WEBPACK_IMPORTED_MODULE_1__.withActions}})},"./node_modules/@storybook/addon-actions/preview.js-generated-config-entry.js":function(__unused_webpack_module,__unused_webpack___webpack_exports__,__webpack_require__){"use strict";var addon_actions_preview_namespaceObject={};__webpack_require__.r(addon_actions_preview_namespaceObject),__webpack_require__.d(addon_actions_preview_namespaceObject,{argsEnhancers:function(){return argsEnhancers},decorators:function(){return decorators}});var ClientApi=__webpack_require__("./node_modules/@storybook/client-api/dist/esm/ClientApi.js"),esm=__webpack_require__("./node_modules/@storybook/addon-actions/dist/esm/index.js"),decorators=[esm.withActions];__webpack_require__("./node_modules/core-js/modules/es.regexp.constructor.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.exec.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.array.filter.js"),__webpack_require__("./node_modules/core-js/modules/es.object.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.object.entries.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.description.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.array.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.string.iterator.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.array.slice.js"),__webpack_require__("./node_modules/core-js/modules/es.function.name.js"),__webpack_require__("./node_modules/core-js/modules/es.array.from.js");function _slicedToArray(arr,i){return function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function _iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function _unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}(arr,i)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i1&&void 0!==arguments[1]?arguments[1]:[],defaultName=arguments.length>2?arguments[2]:void 0;if("transparent"===currentSelectedValue)return"transparent";if(backgrounds.find((function(background){return background.value===currentSelectedValue})))return currentSelectedValue;var defaultBackground=backgrounds.find((function(background){return background.name===defaultName}));if(defaultBackground)return defaultBackground.value;if(defaultName){var availableColors=backgrounds.map((function(background){return background.name})).join(", ");dist_esm.kg.warn((0,esm.C)(_templateObject||(_templateObject=_taggedTemplateLiteral(['\n Backgrounds Addon: could not find the default color "','".\n These are the available colors for your story based on your configuration:\n ',".\n "])),defaultName,availableColors))}return"transparent"}(globalsBackgroundColor,backgroundsConfig.values,backgroundsConfig.default)}),[backgroundsConfig,globalsBackgroundColor]),isActive=(0,hooks.Ye)((function(){return selectedBackgroundColor&&"transparent"!==selectedBackgroundColor}),[selectedBackgroundColor]),selector="docs"===context.viewMode?"#anchor--".concat(context.id," .docs-story"):".sb-show-main",backgroundStyles=(0,hooks.Ye)((function(){return"\n ".concat(selector," {\n background: ").concat(selectedBackgroundColor," !important;\n ").concat(function isReduceMotionEnabled(){return helpers_window.matchMedia("(prefers-reduced-motion: reduce)").matches}()?"":"transition: background-color 0.3s;","\n }\n ")}),[selectedBackgroundColor,selector]);return(0,hooks.d4)((function(){var selectorId="docs"===context.viewMode?"addon-backgrounds-docs-".concat(context.id):"addon-backgrounds-color";isActive?function addBackgroundStyle(selector,css,storyId){var existingStyle=helpers_document.getElementById(selector);if(existingStyle)existingStyle.innerHTML!==css&&(existingStyle.innerHTML=css);else{var style=helpers_document.createElement("style");style.setAttribute("id",selector),style.innerHTML=css;var gridStyleSelector="addon-backgrounds-grid".concat(storyId?"-docs-".concat(storyId):""),existingGridStyle=helpers_document.getElementById(gridStyleSelector);existingGridStyle?existingGridStyle.parentElement.insertBefore(style,existingGridStyle):helpers_document.head.appendChild(style)}}(selectorId,backgroundStyles,"docs"===context.viewMode?context.id:null):clearStyles(selectorId)}),[isActive,backgroundStyles,context]),StoryFn()}],parameters={backgrounds:{grid:{cellSize:20,opacity:.5,cellAmount:5},values:[{name:"light",value:"#F8F8F8"},{name:"dark",value:"#333333"}]}};function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.keys(addon_backgrounds_preview_namespaceObject).forEach((function(key){var value=addon_backgrounds_preview_namespaceObject[key];switch(key){case"args":return(0,ClientApi.uc)(value);case"argTypes":return(0,ClientApi.v9)(value);case"decorators":return value.forEach((function(decorator){return(0,ClientApi.$9)(decorator,!1)}));case"loaders":return value.forEach((function(loader){return(0,ClientApi.HZ)(loader,!1)}));case"parameters":return(0,ClientApi.h1)(function _objectSpread(target){for(var i=1;i4&&void 0!==arguments[4]&&arguments[4],_positionCoordinate=positionCoordinate(position,measurements),x=_positionCoordinate.x,y=_positionCoordinate.y,_offset=offset(type,position,measurements,7,external),offsetX=_offset.offsetX,offsetY=_offset.offsetY;x+=offsetX,y+=offsetY;var _configureText=configureText(context,text),w=_configureText.w,h=_configureText.h;if(prevRect&&collide({x:x,y:y,w:w,h:h},prevRect)){var adjusted=overlapAdjustment(position,{x:x,y:y,w:w,h:h},prevRect);x=adjusted.x,y=adjusted.y}return textWithRect(context,type,{x:x,y:y,w:w,h:h},text)}(context,measurements,l,rects[idx-1],external);rects[idx]=rect}))}function _toConsumableArray(arr){return function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr)}(arr)||function _iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}(arr)||function _unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}(arr)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);iMath.abs(windowExtremities_right-extremities.right)?"left":"right",y:distances_top>distances_bottom?"top":"bottom"}}function drawBoxModel(element){return function(context){if(element&&context){var measurements=function measureElement(element){var style=window_default().getComputedStyle(element),_element$getBoundingC=element.getBoundingClientRect(),top=_element$getBoundingC.top,left=_element$getBoundingC.left,right=_element$getBoundingC.right,bottom=_element$getBoundingC.bottom,width=_element$getBoundingC.width,height=_element$getBoundingC.height,marginTop=style.marginTop,marginBottom=style.marginBottom,marginLeft=style.marginLeft,marginRight=style.marginRight,paddingTop=style.paddingTop,paddingBottom=style.paddingBottom,paddingLeft=style.paddingLeft,paddingRight=style.paddingRight,borderBottomWidth=style.borderBottomWidth,borderTopWidth=style.borderTopWidth,borderLeftWidth=style.borderLeftWidth,borderRightWidth=style.borderRightWidth;top+=window_default().window.scrollY,left+=window_default().window.scrollX,bottom+=window_default().window.scrollY,right+=window_default().window.scrollX;var margin={top:pxToNumber(marginTop),bottom:pxToNumber(marginBottom),left:pxToNumber(marginLeft),right:pxToNumber(marginRight)},padding={top:pxToNumber(paddingTop),bottom:pxToNumber(paddingBottom),left:pxToNumber(paddingLeft),right:pxToNumber(paddingRight)},border={top:pxToNumber(borderTopWidth),bottom:pxToNumber(borderBottomWidth),left:pxToNumber(borderLeftWidth),right:pxToNumber(borderRightWidth)},extremities={top:top-margin.top,bottom:bottom+margin.bottom,left:left-margin.left,right:right+margin.right};return{margin:margin,padding:padding,border:border,top:top,left:left,bottom:bottom,right:right,width:width,height:height,extremities:extremities,floatingAlignment:floatingAlignment(extremities)}}(element),marginLabels=function drawMargin(context,_ref){var margin=_ref.margin,width=_ref.width,height=_ref.height,top=_ref.top,left=_ref.left,bottom=_ref.bottom,right=_ref.right,marginHeight=height+margin.bottom+margin.top;return context.fillStyle=visualizer_colors_margin,context.fillRect(left,top-margin.top,width,margin.top),context.fillRect(right,top-margin.top,margin.right,marginHeight),context.fillRect(left,bottom,width,margin.bottom),context.fillRect(left-margin.left,top-margin.top,margin.left,marginHeight),filterZeroValues([{type:"margin",text:round(margin.top),position:"top"},{type:"margin",text:round(margin.right),position:"right"},{type:"margin",text:round(margin.bottom),position:"bottom"},{type:"margin",text:round(margin.left),position:"left"}])}(context,measurements),paddingLabels=function drawPadding(context,_ref2){var padding=_ref2.padding,border=_ref2.border,width=_ref2.width,height=_ref2.height,top=_ref2.top,left=_ref2.left,bottom=_ref2.bottom,right=_ref2.right,paddingWidth=width-border.left-border.right,paddingHeight=height-padding.top-padding.bottom-border.top-border.bottom;return context.fillStyle=visualizer_colors_padding,context.fillRect(left+border.left,top+border.top,paddingWidth,padding.top),context.fillRect(right-padding.right-border.right,top+padding.top+border.top,padding.right,paddingHeight),context.fillRect(left+border.left,bottom-padding.bottom-border.bottom,paddingWidth,padding.bottom),context.fillRect(left+border.left,top+padding.top+border.top,padding.left,paddingHeight),filterZeroValues([{type:"padding",text:padding.top,position:"top"},{type:"padding",text:padding.right,position:"right"},{type:"padding",text:padding.bottom,position:"bottom"},{type:"padding",text:padding.left,position:"left"}])}(context,measurements),borderLabels=function drawBorder(context,_ref3){var border=_ref3.border,width=_ref3.width,height=_ref3.height,top=_ref3.top,left=_ref3.left,bottom=_ref3.bottom,right=_ref3.right,borderHeight=height-border.top-border.bottom;return context.fillStyle=visualizer_colors_border,context.fillRect(left,top,width,border.top),context.fillRect(left,bottom-border.bottom,width,border.bottom),context.fillRect(left,top+border.top,border.left,borderHeight),context.fillRect(right-border.right,top+border.top,border.right,borderHeight),filterZeroValues([{type:"border",text:border.top,position:"top"},{type:"border",text:border.right,position:"right"},{type:"border",text:border.bottom,position:"bottom"},{type:"border",text:border.left,position:"left"}])}(context,measurements),contentLabels=function drawContent(context,_ref4){var padding=_ref4.padding,border=_ref4.border,width=_ref4.width,height=_ref4.height,top=_ref4.top,left=_ref4.left,contentWidth=width-border.left-border.right-padding.left-padding.right,contentHeight=height-padding.top-padding.bottom-border.top-border.bottom;return context.fillStyle=visualizer_colors_content,context.fillRect(left+border.left+padding.left,top+border.top+padding.top,contentWidth,contentHeight),[{type:"content",position:"center",text:"".concat(round(contentWidth)," x ").concat(round(contentHeight))}]}(context,measurements),externalLabels=measurements.width<=90||measurements.height<=30;!function labelStacks(context,measurements,labels,externalLabels){var stacks=labels.reduce((function(acc,l){return Object.prototype.hasOwnProperty.call(acc,l.position)||(acc[l.position]=[]),acc[l.position].push(l),acc}),{});stacks.top&&drawStack(context,measurements,stacks.top,externalLabels),stacks.right&&drawStack(context,measurements,stacks.right,externalLabels),stacks.bottom&&drawStack(context,measurements,stacks.bottom,externalLabels),stacks.left&&drawStack(context,measurements,stacks.left,externalLabels),stacks.center&&drawStack(context,measurements,stacks.center,externalLabels)}(context,measurements,[].concat(_toConsumableArray(contentLabels),_toConsumableArray(paddingLabels),_toConsumableArray(borderLabels),_toConsumableArray(marginLabels)),externalLabels)}}}function drawSelectedElement(element){!function draw(callback){clear(),callback(state.context)}(drawBoxModel(element))}var nodeAtPointerRef,pointer={x:0,y:0};function findAndDrawElement(x,y){nodeAtPointerRef=function deepElementFromPoint(x,y){var element=window_default().document.elementFromPoint(x,y);return function crawlShadows(node){if(node&&node.shadowRoot){var nestedElement=node.shadowRoot.elementFromPoint(x,y);return node.isEqualNode(nestedElement)?node:nestedElement.shadowRoot?crawlShadows(nestedElement):nestedElement}return node}(element)||element}(x,y),drawSelectedElement(nodeAtPointerRef)}var ADDON_ID="storybook/measure-addon";"".concat(ADDON_ID,"/tool"),"".concat(ADDON_ID,"/result"),"".concat(ADDON_ID,"/request"),"".concat(ADDON_ID,"/clear");var decorators=[function withMeasure(StoryFn,context){var measureEnabled=context.globals.measureEnabled;return(0,hooks.d4)((function(){var onMouseMove=function onMouseMove(event){window.requestAnimationFrame((function(){event.stopPropagation(),pointer.x=event.clientX,pointer.y=event.clientY}))};return document.addEventListener("mousemove",onMouseMove),function(){document.removeEventListener("mousemove",onMouseMove)}}),[]),(0,hooks.d4)((function(){var onResize=function onResize(){window.requestAnimationFrame((function(){!function rescale(){setCanvasWidthAndHeight(state.canvas,state.context,{width:0,height:0});var _getDocumentWidthAndH2=getDocumentWidthAndHeight(),width=_getDocumentWidthAndH2.width,height=_getDocumentWidthAndH2.height;setCanvasWidthAndHeight(state.canvas,state.context,{width:width,height:height}),state.width=width,state.height=height}()}))};return measureEnabled&&(document.addEventListener("mouseover",(function onMouseOver(event){window.requestAnimationFrame((function(){event.stopPropagation(),findAndDrawElement(event.clientX,event.clientY)}))})),init(),window.addEventListener("resize",onResize),findAndDrawElement(pointer.x,pointer.y)),function(){window.removeEventListener("resize",onResize),function destroy(){state.canvas&&(clear(),state.canvas.parentNode.removeChild(state.canvas),state={})}()}}),[measureEnabled]),StoryFn()}],globals=function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}({},"measureEnabled",!1);function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function preview_js_generated_config_entry_defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.keys(addon_measure_preview_namespaceObject).forEach((function(key){var value=addon_measure_preview_namespaceObject[key];switch(key){case"args":return(0,ClientApi.uc)(value);case"argTypes":return(0,ClientApi.v9)(value);case"decorators":return value.forEach((function(decorator){return(0,ClientApi.$9)(decorator,!1)}));case"loaders":return value.forEach((function(loader){return(0,ClientApi.HZ)(loader,!1)}));case"parameters":return(0,ClientApi.h1)(function _objectSpread(target){for(var i=1;iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i25)throw new Error("Too many re-renders. Storybook limits the number of renders to prevent an infinite loop.");return hooks.addRenderListeners(),result}}},invalidHooksError=function invalidHooksError(){return new Error("Storybook preview hooks can only be called inside decorators and story functions.")};function getHooksContextOrNull(){return globalWindow.STORYBOOK_HOOKS_CONTEXT||null}function getHooksContextOrThrow(){var hooks=getHooksContextOrNull();if(null==hooks)throw invalidHooksError();return hooks}function useMemoLike(name,nextCreate,deps){var _useHook=function useHook(name,callback,deps){var hooks=getHooksContextOrThrow();if("MOUNT"===hooks.currentPhase){null==deps||Array.isArray(deps)||_storybook_client_logger__WEBPACK_IMPORTED_MODULE_23__.kg.warn("".concat(name," received a final argument that is not an array (instead, received ").concat(deps,"). When specified, the final argument must be an array."));var _hook={name:name,deps:deps};return hooks.currentHooks.push(_hook),callback(_hook),_hook}if("UPDATE"===hooks.currentPhase){var _hook2=hooks.getNextHook();if(null==_hook2)throw new Error("Rendered more hooks than during the previous render.");return _hook2.name!==name&&_storybook_client_logger__WEBPACK_IMPORTED_MODULE_23__.kg.warn("Storybook has detected a change in the order of Hooks".concat(hooks.currentDecoratorName?" called by ".concat(hooks.currentDecoratorName):"",". This will lead to bugs and errors if not fixed.")),null!=deps&&null==_hook2.deps&&_storybook_client_logger__WEBPACK_IMPORTED_MODULE_23__.kg.warn("".concat(name," received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.")),null!=deps&&null!=_hook2.deps&&deps.length!==_hook2.deps.length&&_storybook_client_logger__WEBPACK_IMPORTED_MODULE_23__.kg.warn("The final argument passed to ".concat(name," changed size between renders. The order and size of this array must remain constant.\nPrevious: ").concat(_hook2.deps,"\nIncoming: ").concat(deps)),null!=deps&&null!=_hook2.deps&&function areDepsEqual(deps,nextDeps){return deps.length===nextDeps.length&&deps.every((function(dep,i){return dep===nextDeps[i]}))}(deps,_hook2.deps)||(callback(_hook2),_hook2.deps=deps),_hook2}throw invalidHooksError()}(name,(function(hook){hook.memoizedState=nextCreate()}),deps);return _useHook.memoizedState}function useMemo(nextCreate,deps){return useMemoLike("useMemo",nextCreate,deps)}function useEffect(create,deps){var hooks=getHooksContextOrThrow(),effect=useMemoLike("useEffect",(function(){return{create:create}}),deps);hooks.currentEffects.includes(effect)||hooks.currentEffects.push(effect)}},"./node_modules/@storybook/addons/dist/esm/index.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{KP:function(){return addons}});__webpack_require__("./node_modules/core-js/modules/es.object.assign.js"),__webpack_require__("./node_modules/core-js/modules/es.object.to-string.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.for-each.js"),__webpack_require__("./node_modules/core-js/modules/es.object.values.js"),__webpack_require__("./node_modules/core-js/modules/es.promise.js");var global_window=__webpack_require__("./node_modules/global/window.js"),window_default=__webpack_require__.n(global_window),esm=__webpack_require__("./node_modules/@storybook/client-logger/dist/esm/index.js"),dist_esm=__webpack_require__("./node_modules/@storybook/channels/dist/esm/index.js");var types;__webpack_require__("./node_modules/core-js/modules/es.array.find.js");function _defineProperties(target,props){for(var i=0;i1)return args.length>1?decorator(args).apply(void 0,arguments):decorator.apply(void 0,args).apply(void 0,arguments);throw new Error("Passing stories directly into ".concat(name,"() is not allowed,\n instead use addDecorator(").concat(name,") and pass options with the '").concat(parameterName,"' parameter"))}}}},"./node_modules/@storybook/channels/dist/esm/index.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__("./node_modules/core-js/modules/es.object.freeze.js"),__webpack_require__("./node_modules/core-js/modules/es.array.slice.js"),__webpack_require__("./node_modules/core-js/modules/es.object.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.to-string.js"),__webpack_require__("./node_modules/core-js/modules/web.immediate.js"),__webpack_require__("./node_modules/core-js/modules/es.object.keys.js"),__webpack_require__("./node_modules/core-js/modules/es.array.filter.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.for-each.js");var _templateObject,util_deprecate__WEBPACK_IMPORTED_MODULE_8__=__webpack_require__("./node_modules/util-deprecate/browser.js"),util_deprecate__WEBPACK_IMPORTED_MODULE_8___default=__webpack_require__.n(util_deprecate__WEBPACK_IMPORTED_MODULE_8__),ts_dedent__WEBPACK_IMPORTED_MODULE_9__=__webpack_require__("./node_modules/ts-dedent/esm/index.js");function _taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:{},transport=_ref.transport,_ref$async=_ref.async,async=void 0!==_ref$async&&_ref$async;_classCallCheck(this,Channel),this.isAsync=void 0,this.sender=generateRandomId(),this.events={},this.data={},this.transport=void 0,this.addPeerListener=util_deprecate__WEBPACK_IMPORTED_MODULE_8___default()((function(eventName,listener){_this.addListener(eventName,listener)}),(0,ts_dedent__WEBPACK_IMPORTED_MODULE_9__.C)(_templateObject||(_templateObject=_taggedTemplateLiteral(["\n channel.addPeerListener is deprecated\n "])))),this.isAsync=async,transport&&(this.transport=transport,this.transport.setHandler((function(event){return _this.handleEvent(event)})))}return function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}(Channel,[{key:"hasTransport",get:function get(){return!!this.transport}},{key:"addListener",value:function addListener(eventName,listener){this.events[eventName]=this.events[eventName]||[],this.events[eventName].push(listener)}},{key:"emit",value:function emit(eventName){for(var _this2=this,_len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];var event={type:eventName,args:args,from:this.sender},options={};args.length>=1&&args[0]&&args[0].options&&(options=args[0].options);var handler=function handler(){_this2.transport&&_this2.transport.send(event,options),_this2.handleEvent(event)};this.isAsync?setImmediate(handler):handler()}},{key:"last",value:function last(eventName){return this.data[eventName]}},{key:"eventNames",value:function eventNames(){return Object.keys(this.events)}},{key:"listenerCount",value:function listenerCount(eventName){var listeners=this.listeners(eventName);return listeners?listeners.length:0}},{key:"listeners",value:function listeners(eventName){var listeners=this.events[eventName];return listeners||void 0}},{key:"once",value:function once(eventName,listener){var onceListener=this.onceListener(eventName,listener);this.addListener(eventName,onceListener)}},{key:"removeAllListeners",value:function removeAllListeners(eventName){eventName?this.events[eventName]&&delete this.events[eventName]:this.events={}}},{key:"removeListener",value:function removeListener(eventName,listener){var listeners=this.listeners(eventName);listeners&&(this.events[eventName]=listeners.filter((function(l){return l!==listener})))}},{key:"on",value:function on(eventName,listener){this.addListener(eventName,listener)}},{key:"off",value:function off(eventName,listener){this.removeListener(eventName,listener)}},{key:"handleEvent",value:function handleEvent(event){var listeners=this.listeners(event.type);listeners&&listeners.length&&listeners.forEach((function(fn){fn.apply(event,event.args)})),this.data[event.type]=event.args}},{key:"onceListener",value:function onceListener(eventName,listener){var _this3=this,onceListener=function onceListener(){return _this3.removeListener(eventName,onceListener),listener.apply(void 0,arguments)};return onceListener}}]),Channel}();__webpack_exports__.Z=Channel},"./node_modules/@storybook/client-api/dist/esm/ClientApi.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{ti:function(){return ClientApi},v9:function(){return addArgTypes},My:function(){return addArgTypesEnhancer},uc:function(){return addArgs},_C:function(){return addArgsEnhancer},$9:function(){return addDecorator},HZ:function(){return addLoader},h1:function(){return addParameters},$P:function(){return setGlobalRender}});__webpack_require__("./node_modules/core-js/modules/es.array.slice.js"),__webpack_require__("./node_modules/core-js/modules/es.object.freeze.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.description.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.array.from.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.exec.js"),__webpack_require__("./node_modules/core-js/modules/es.array.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.object.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.set.js"),__webpack_require__("./node_modules/core-js/modules/es.string.iterator.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.object.assign.js"),__webpack_require__("./node_modules/core-js/modules/es.object.get-prototype-of.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.object.keys.js"),__webpack_require__("./node_modules/core-js/modules/es.array.concat.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.for-each.js"),__webpack_require__("./node_modules/core-js/modules/es.object.entries.js"),__webpack_require__("./node_modules/core-js/modules/es.function.name.js"),__webpack_require__("./node_modules/core-js/modules/es.object.values.js");var browser=__webpack_require__("./node_modules/util-deprecate/browser.js"),browser_default=__webpack_require__.n(browser),esm=__webpack_require__("./node_modules/ts-dedent/esm/index.js"),global_window=__webpack_require__("./node_modules/global/window.js"),window_default=__webpack_require__.n(global_window),dist_esm=__webpack_require__("./node_modules/@storybook/client-logger/dist/esm/index.js"),dist=__webpack_require__("./node_modules/@storybook/csf/dist/index.js"),esm_parameters=__webpack_require__("./node_modules/@storybook/store/dist/esm/parameters.js"),normalizeInputTypes=__webpack_require__("./node_modules/@storybook/store/dist/esm/csf/normalizeInputTypes.js"),synchronous_promise=(__webpack_require__("./node_modules/core-js/modules/es.array.map.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.constructor.js"),__webpack_require__("./node_modules/core-js/modules/es.array.filter.js"),__webpack_require__("./node_modules/synchronous-promise/index.js")),stable=__webpack_require__("./node_modules/stable/stable.js"),stable_default=__webpack_require__.n(stable),STORY_KIND_PATH_SEPARATOR=(__webpack_require__("./node_modules/core-js/modules/es.string.split.js"),__webpack_require__("./node_modules/core-js/modules/es.string.trim.js"),/\s*\/\s*/);var autoTitle_templateObject,sortStoriesCommon=function sortStoriesCommon(stories,storySortParameter,fileNameOrder){var sortFn;storySortParameter?(sortFn="function"==typeof storySortParameter?storySortParameter:function storySort(){var options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(a,b){if(a.title===b.title&&!options.includeNames)return 0;var method=options.method||"configure",order=options.order||[],storyTitleA=a.title.trim().split(STORY_KIND_PATH_SEPARATOR),storyTitleB=b.title.trim().split(STORY_KIND_PATH_SEPARATOR);options.includeNames&&(storyTitleA.push(a.name),storyTitleB.push(b.name));for(var depth=0;storyTitleA[depth]||storyTitleB[depth];){if(!storyTitleA[depth])return-1;if(!storyTitleB[depth])return 1;var nameA=storyTitleA[depth],nameB=storyTitleB[depth];if(nameA!==nameB){var indexA=order.indexOf(nameA),indexB=order.indexOf(nameB),indexWildcard=order.indexOf("*");return-1!==indexA||-1!==indexB?(-1===indexA&&(indexA=-1!==indexWildcard?indexWildcard:order.length),-1===indexB&&(indexB=-1!==indexWildcard?indexWildcard:order.length),indexA-indexB):"configure"===method?0:nameA.localeCompare(nameB,options.locales?options.locales:void 0,{numeric:!0,sensitivity:"accent"})}var index=order.indexOf(nameA);order=-1!==index&&Array.isArray(order[index+1])?order[index+1]:[],depth+=1}return 0}}(storySortParameter),stable_default().inplace(stories,sortFn)):stable_default().inplace(stories,(function(s1,s2){return fileNameOrder.indexOf(s1.importPath)-fileNameOrder.indexOf(s2.importPath)}));return stories},toIndexEntry=function toIndexEntry(story){return{id:story.id,title:story.title,name:story.name,importPath:story.parameters.fileName}},slash=(__webpack_require__("./node_modules/core-js/modules/es.string.replace.js"),__webpack_require__("./node_modules/core-js/modules/es.array.join.js"),__webpack_require__("./node_modules/slash/index.js")),slash_default=__webpack_require__.n(slash);function _toArray(arr){return function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _toConsumableArray(arr){return function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr)}(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(o,minLen){if(o){if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(o,minLen):void 0}}function _iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0?last.substr(0,dotIndex):last;parts[parts.length-1]=stripped;var _parts2=_toArray(parts),first=_parts2[0],rest=_parts2.slice(1);return""===first&&(parts=rest),parts}(path))).join("/")}return titlePrefix?slash_default()(pathJoin([titlePrefix,userTitle])):userTitle}},_excluded=["default","__namedExportsOrder"];function _objectWithoutProperties(source,excluded){if(null==source)return{};var key,i,target=function _objectWithoutPropertiesLoose(source,excluded){if(null==source)return{};var key,i,target={},sourceKeys=Object.keys(source);for(i=0;i=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}function _slicedToArray(arr,i){return function StoryStoreFacade_arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function _iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function StoryStoreFacade_unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return StoryStoreFacade_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return StoryStoreFacade_arrayLikeToArray(o,minLen)}(arr,i)||function StoryStoreFacade_nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function StoryStoreFacade_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i ","\n \n Are you using a V7-style sort function in V6 compatibility mode?\n \n More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort\n "])),storySortParameter,err.message));throw err}return{v:3,stories:sortedV7.reduce((function(acc,s){return acc[s.id]=_this2.stories[s.id],acc}),{})}}},{key:"clearFilenameExports",value:function clearFilenameExports(fileName){var _this3=this;this.csfExports[fileName]&&(Object.entries(this.stories).forEach((function(_ref3){var _ref4=_slicedToArray(_ref3,2),id=_ref4[0];_ref4[1].importPath===fileName&&delete _this3.stories[id]})),this.csfExports[fileName]={})}},{key:"addStoriesFromExports",value:function addStoriesFromExports(fileName,fileExports){var _this4=this;if(this.csfExports[fileName]!==fileExports){this.clearFilenameExports(fileName);var defaultExport=fileExports.default,__namedExportsOrder=fileExports.__namedExportsOrder,namedExports=_objectWithoutProperties(fileExports,_excluded),_ref5=defaultExport||{},componentId=_ref5.id,title=_ref5.title,specifiers=(window_default().STORIES||[]).map((function(specifier){return Object.assign({},specifier,{importPathMatcher:new RegExp(specifier.importPathMatcher)})}));if(title=function userOrAutoTitle(fileName,storiesEntries,userTitle){for(var i=0;iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}function ClientApi_classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function ClientApi_defineProperties(target,props){for(var i=0;i1&&void 0!==arguments[1])||arguments[1];checkMethod("addDecorator",deprecationWarning),singleton.addDecorator(decorator)},addParameters=function addParameters(parameters){var deprecationWarning=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];checkMethod("addParameters",deprecationWarning),singleton.addParameters(parameters)},addLoader=function addLoader(loader){var deprecationWarning=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];checkMethod("addLoader",deprecationWarning),singleton.addLoader(loader)},addArgs=function addArgs(args){checkMethod("addArgs",!1),singleton.addArgs(args)},addArgTypes=function addArgTypes(argTypes){checkMethod("addArgTypes",!1),singleton.addArgTypes(argTypes)},addArgsEnhancer=function addArgsEnhancer(enhancer){checkMethod("addArgsEnhancer",!1),singleton.addArgsEnhancer(enhancer)},addArgTypesEnhancer=function addArgTypesEnhancer(enhancer){checkMethod("addArgTypesEnhancer",!1),singleton.addArgTypesEnhancer(enhancer)},setGlobalRender=function setGlobalRender(render){checkMethod("setGlobalRender",!1),singleton.facade.projectAnnotations.render=render},invalidStoryTypes=new Set(["string","number","boolean","symbol"]),ClientApi=function(){function ClientApi(){var _this=this,_ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},storyStore=_ref.storyStore;ClientApi_classCallCheck(this,ClientApi),this.facade=void 0,this.storyStore=void 0,this.addons=void 0,this.onImportFnChanged=void 0,this.lastFileName=0,this.setAddon=browser_default()((function(addon){_this.addons=Object.assign({},_this.addons,addon)}),(0,esm.C)(_templateObject3||(_templateObject3=ClientApi_taggedTemplateLiteral(["\n `setAddon` is deprecated and will be removed in Storybook 7.0.\n\n https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-setaddon\n "],["\n \\`setAddon\\` is deprecated and will be removed in Storybook 7.0.\n\n https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-setaddon\n "])))),this.addDecorator=function(decorator){_this.facade.projectAnnotations.decorators.push(decorator)},this.clearDecorators=browser_default()((function(){_this.facade.projectAnnotations.decorators=[]}),(0,esm.C)(_templateObject4||(_templateObject4=ClientApi_taggedTemplateLiteral(["\n `clearDecorators` is deprecated and will be removed in Storybook 7.0.\n\n https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-cleardecorators\n "],["\n \\`clearDecorators\\` is deprecated and will be removed in Storybook 7.0.\n\n https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-cleardecorators\n "])))),this.addParameters=function(_ref2){var globals=_ref2.globals,globalTypes=_ref2.globalTypes,parameters=ClientApi_objectWithoutProperties(_ref2,ClientApi_excluded);_this.facade.projectAnnotations.parameters=(0,esm_parameters.f)(_this.facade.projectAnnotations.parameters,parameters),globals&&(_this.facade.projectAnnotations.globals=Object.assign({},_this.facade.projectAnnotations.globals,globals)),globalTypes&&(_this.facade.projectAnnotations.globalTypes=Object.assign({},_this.facade.projectAnnotations.globalTypes,(0,normalizeInputTypes.x)(globalTypes)))},this.addLoader=function(loader){_this.facade.projectAnnotations.loaders.push(loader)},this.addArgs=function(args){_this.facade.projectAnnotations.args=Object.assign({},_this.facade.projectAnnotations.args,args)},this.addArgTypes=function(argTypes){_this.facade.projectAnnotations.argTypes=Object.assign({},_this.facade.projectAnnotations.argTypes,(0,normalizeInputTypes.x)(argTypes))},this.addArgsEnhancer=function(enhancer){_this.facade.projectAnnotations.argsEnhancers.push(enhancer)},this.addArgTypesEnhancer=function(enhancer){_this.facade.projectAnnotations.argTypesEnhancers.push(enhancer)},this.storiesOf=function(kind,m){if(!kind&&"string"!=typeof kind)throw new Error("Invalid or missing kind provided for stories, should be a string");if(m||dist_esm.kg.warn("Missing 'module' parameter for story with a kind of '".concat(kind,"'. It will break your HMR")),m){var proto=Object.getPrototypeOf(m);proto.exports&&proto.exports.default&&dist_esm.kg.error("Illegal mix of CSF default export and storiesOf calls in a single file: ".concat(proto.i))}for(var baseFilename=m&&m.id?"".concat(m.id):(_this.lastFileName++).toString(),fileName=baseFilename,i=1;_this.facade.csfExports[fileName]&&Object.keys(_this.facade.csfExports[fileName]).length>0;)i+=1,fileName="".concat(baseFilename,"-").concat(i);m&&m.hot&&m.hot.accept&&(m.hot.accept(),m.hot.dispose((function(){_this.facade.clearFilenameExports(fileName),setTimeout((function(){var _this$onImportFnChang;null===(_this$onImportFnChang=_this.onImportFnChanged)||void 0===_this$onImportFnChang||_this$onImportFnChang.call(_this,{importFn:_this.importFn.bind(_this)})}),0)})));var hasAdded=!1,api={kind:kind.toString(),add:function add(){return api},addDecorator:function addDecorator(){return api},addLoader:function addLoader(){return api},addParameters:function addParameters(){return api}};Object.keys(_this.addons).forEach((function(name){var addon=_this.addons[name];api[name]=function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return addon.apply(api,args),api}}));var meta={id:(0,dist.sanitize)(kind),title:kind,decorators:[],loaders:[],parameters:{}};_this.facade.csfExports[fileName]={default:meta};var counter=0;return api.add=function(storyName,storyFn){var parameters=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(hasAdded=!0,"string"!=typeof storyName)throw new Error('Invalid or missing storyName provided for a "'.concat(kind,'" story.'));if(!storyFn||Array.isArray(storyFn)||invalidStoryTypes.has(_typeof(storyFn)))throw new Error('Cannot load story "'.concat(storyName,'" in "').concat(kind,'" due to invalid format. Storybook expected a function/object but received ').concat(_typeof(storyFn)," instead."));var decorators=parameters.decorators,loaders=parameters.loaders,component=parameters.component,args=parameters.args,argTypes=parameters.argTypes,storyParameters=ClientApi_objectWithoutProperties(parameters,_excluded2),storyId=parameters.__id||(0,dist.toId)(kind,storyName),csfExports=_this.facade.csfExports[fileName];return csfExports["story".concat(counter)]={name:storyName,parameters:Object.assign({fileName:fileName,__id:storyId},storyParameters),decorators:decorators,loaders:loaders,args:args,argTypes:argTypes,component:component,render:storyFn},counter+=1,_this.facade.stories[storyId]={id:storyId,title:csfExports.default.title,name:storyName,importPath:fileName},api},api.addDecorator=function(decorator){if(hasAdded)throw new Error("You cannot add a decorator after the first story for a kind.\nRead more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories");return meta.decorators.push(decorator),api},api.addLoader=function(loader){if(hasAdded)throw new Error("You cannot add a loader after the first story for a kind.");return meta.loaders.push(loader),api},api.addParameters=function(_ref3){var component=_ref3.component,args=_ref3.args,argTypes=_ref3.argTypes,parameters=ClientApi_objectWithoutProperties(_ref3,_excluded3);if(hasAdded)throw new Error("You cannot add parameters after the first story for a kind.\nRead more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories");return meta.parameters=(0,esm_parameters.f)(meta.parameters,parameters),component&&(meta.component=component),args&&(meta.args=Object.assign({},meta.args,args)),argTypes&&(meta.argTypes=Object.assign({},meta.argTypes,argTypes)),api},api},this.getStorybook=function(){var stories=_this.storyStore.storyIndex.stories,kinds={};return Object.entries(stories).forEach((function(_ref4){var _ref5=ClientApi_slicedToArray(_ref4,2),storyId=_ref5[0],_ref5$=_ref5[1],title=_ref5$.title,name=_ref5$.name,importPath=_ref5$.importPath;kinds[title]||(kinds[title]={kind:title,fileName:importPath,stories:[]});var storyFn=_this.storyStore.fromId(storyId).storyFn;kinds[title].stories.push({name:name,render:storyFn})})),Object.values(kinds)},this.raw=function(){return _this.storyStore.raw()},this.facade=new StoryStoreFacade,this.addons={},this.storyStore=storyStore,singleton=this}return function ClientApi_createClass(Constructor,protoProps,staticProps){return protoProps&&ClientApi_defineProperties(Constructor.prototype,protoProps),staticProps&&ClientApi_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}(ClientApi,[{key:"importFn",value:function importFn(path){return this.facade.importFn(path)}},{key:"getStoryIndex",value:function getStoryIndex(){if(!this.storyStore)throw new Error("Cannot get story index before setting storyStore");return this.facade.getStoryIndex(this.storyStore)}},{key:"_storyStore",get:function get(){return this.storyStore}}]),ClientApi}()},"./node_modules/@storybook/client-logger/dist/esm/index.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{IC:function(){return pretty},IH:function(){return once},kg:function(){return logger}});__webpack_require__("./node_modules/core-js/modules/es.array.concat.js"),__webpack_require__("./node_modules/core-js/modules/es.array.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.object.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.set.js"),__webpack_require__("./node_modules/core-js/modules/es.string.iterator.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.exec.js"),__webpack_require__("./node_modules/core-js/modules/es.string.replace.js");var global__WEBPACK_IMPORTED_MODULE_8__=__webpack_require__("./node_modules/global/window.js"),global__WEBPACK_IMPORTED_MODULE_8___default=__webpack_require__.n(global__WEBPACK_IMPORTED_MODULE_8__),LOGLEVEL=global__WEBPACK_IMPORTED_MODULE_8___default().LOGLEVEL,console=global__WEBPACK_IMPORTED_MODULE_8___default().console,levels={trace:1,debug:2,info:3,warn:4,error:5,silent:10},currentLogLevelNumber=levels[LOGLEVEL]||levels.info,logger={trace:function trace(message){for(var _len=arguments.length,rest=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)rest[_key-1]=arguments[_key];return currentLogLevelNumber<=levels.trace&&console.trace.apply(console,[message].concat(rest))},debug:function debug(message){for(var _len2=arguments.length,rest=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++)rest[_key2-1]=arguments[_key2];return currentLogLevelNumber<=levels.debug&&console.debug.apply(console,[message].concat(rest))},info:function info(message){for(var _len3=arguments.length,rest=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++)rest[_key3-1]=arguments[_key3];return currentLogLevelNumber<=levels.info&&console.info.apply(console,[message].concat(rest))},warn:function warn(message){for(var _len4=arguments.length,rest=new Array(_len4>1?_len4-1:0),_key4=1;_key4<_len4;_key4++)rest[_key4-1]=arguments[_key4];return currentLogLevelNumber<=levels.warn&&console.warn.apply(console,[message].concat(rest))},error:function error(message){for(var _len5=arguments.length,rest=new Array(_len5>1?_len5-1:0),_key5=1;_key5<_len5;_key5++)rest[_key5-1]=arguments[_key5];return currentLogLevelNumber<=levels.error&&console.error.apply(console,[message].concat(rest))},log:function log(message){for(var _len6=arguments.length,rest=new Array(_len6>1?_len6-1:0),_key6=1;_key6<_len6;_key6++)rest[_key6-1]=arguments[_key6];return currentLogLevelNumber1?_len7-1:0),_key7=1;_key7<_len7;_key7++)rest[_key7-1]=arguments[_key7];return logger[type].apply(logger,[message].concat(rest))}}};once.clear=function(){return logged.clear()},once.trace=once("trace"),once.debug=once("debug"),once.info=once("info"),once.warn=once("warn"),once.error=once("error"),once.log=once("log");var pretty=function pretty(type){return function(){for(var argArray=[],_len8=arguments.length,args=new Array(_len8),_key8=0;_key8<_len8;_key8++)args[_key8]=arguments[_key8];if(args.length){var reResultArray,startTagRe=//gi,endTagRe=/<\/span>/gi;for(argArray.push(args[0].replace(startTagRe,"%c").replace(endTagRe,"%c"));reResultArray=startTagRe.exec(args[0]);)argArray.push(reResultArray[2]),argArray.push("");for(var j=1;j1)throw new Error("Invalid conditional test ".concat(JSON.stringify({exists:exists,eq:eq,neq:neq})));if(void 0!==eq)return(0,_isEqual.default)(value,eq);if(void 0!==neq)return!(0,_isEqual.default)(value,neq);if(void 0!==exists){var valueExists=void 0!==value;return exists?valueExists:!valueExists}return void 0===truthy||truthy?!!value:!value};exports.testValue=testValue;exports.includeConditionalArg=function includeConditionalArg(argType,args,globals){if(!argType.if)return!0;var _ref2=argType.if,arg=_ref2.arg,global=_ref2.global;if(1!==count([arg,global]))throw new Error("Invalid conditional value ".concat(JSON.stringify({arg:arg,global:global})));var value=arg?args[arg]:globals[global];return testValue(argType.if,value)}},"./node_modules/@storybook/csf/dist/index.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _exportNames={sanitize:!0,toId:!0,storyNameFromExport:!0,isExportStory:!0,parseKind:!0,includeConditionalArg:!0};exports.isExportStory=function isExportStory(key,_ref){var includeStories=_ref.includeStories,excludeStories=_ref.excludeStories;return"__esModule"!==key&&(!includeStories||matches(key,includeStories))&&(!excludeStories||!matches(key,excludeStories))},Object.defineProperty(exports,"includeConditionalArg",{enumerable:!0,get:function get(){return _includeConditionalArg.includeConditionalArg}}),exports.parseKind=exports.storyNameFromExport=exports.toId=exports.sanitize=void 0;var _startCase=function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}(__webpack_require__("./node_modules/lodash/startCase.js")),_includeConditionalArg=__webpack_require__("./node_modules/@storybook/csf/dist/includeConditionalArg.js"),_story=__webpack_require__("./node_modules/@storybook/csf/dist/story.js");function _slicedToArray(arr,i){return function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function _iterableToArrayLimit(arr,i){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(arr)))return;var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function _unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}(arr,i)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i\{\}\[\]\\\/]/gi,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,"")};exports.sanitize=sanitize;var sanitizeSafe=function sanitizeSafe(string,part){var sanitized=sanitize(string);if(""===sanitized)throw new Error("Invalid ".concat(part," '").concat(string,"', must include alphanumeric characters"));return sanitized};exports.toId=function toId(kind,name){return"".concat(sanitizeSafe(kind,"kind")).concat(name?"--".concat(sanitizeSafe(name,"name")):"")};function matches(storyKey,arrayOrRegex){return Array.isArray(arrayOrRegex)?arrayOrRegex.includes(storyKey):storyKey.match(arrayOrRegex)}exports.storyNameFromExport=function storyNameFromExport(key){return(0,_startCase.default)(key)};exports.parseKind=function parseKind(kind,_ref2){var rootSeparator=_ref2.rootSeparator,groupSeparator=_ref2.groupSeparator,_kind$split2=_slicedToArray(kind.split(rootSeparator,2),2),root=_kind$split2[0],remainder=_kind$split2[1];return{root:remainder?root:null,groups:(remainder||kind).split(groupSeparator).filter((function(i){return!!i}))}}},"./node_modules/@storybook/csf/dist/story.js":function(__unused_webpack_module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _SBType=__webpack_require__("./node_modules/@storybook/csf/dist/SBType.js");Object.keys(_SBType).forEach((function(key){"default"!==key&&"__esModule"!==key&&Object.defineProperty(exports,key,{enumerable:!0,get:function get(){return _SBType[key]}})}))},"./node_modules/@storybook/docs-tools/dist/esm/argTypes/docgen/utils/string.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{B:function(){return str}});var str=function str(obj){if(!obj)return"";if("string"==typeof obj)return obj;throw new Error("Description: expected string, got: ".concat(JSON.stringify(obj)))}},"./node_modules/@storybook/react/dist/esm/client/docs/config-generated-config-entry.js":function(__unused_webpack_module,__unused_webpack___webpack_exports__,__webpack_require__){"use strict";var config_namespaceObject={};__webpack_require__.r(config_namespaceObject),__webpack_require__.d(config_namespaceObject,{argTypesEnhancers:function(){return argTypesEnhancers},decorators:function(){return decorators},parameters:function(){return config_parameters}});var ClientApi=__webpack_require__("./node_modules/@storybook/client-api/dist/esm/ClientApi.js"),doctrine=(__webpack_require__("./node_modules/core-js/modules/es.array.map.js"),__webpack_require__("./node_modules/core-js/modules/es.object.assign.js"),__webpack_require__("./node_modules/core-js/modules/es.function.name.js"),__webpack_require__("./node_modules/core-js/modules/es.object.keys.js"),__webpack_require__("./node_modules/core-js/modules/es.array.filter.js"),__webpack_require__("./node_modules/core-js/modules/es.object.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.description.js"),__webpack_require__("./node_modules/core-js/modules/es.array.includes.js"),__webpack_require__("./node_modules/core-js/modules/es.string.includes.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.exec.js"),__webpack_require__("./node_modules/core-js/modules/es.string.replace.js"),__webpack_require__("./node_modules/core-js/modules/es.array.concat.js"),__webpack_require__("./node_modules/core-js/modules/es.array.join.js"),__webpack_require__("./node_modules/doctrine/lib/doctrine.js"));function containsJsDoc(value){return null!=value&&value.includes("@")}function parse(content,tags){var ast;try{ast=doctrine.parse(content,{tags:tags,sloppy:!0})}catch(e){throw console.error(e),new Error("Cannot parse JSDoc tags.")}return ast}var TypeSystem,DEFAULT_OPTIONS={tags:["param","arg","argument","returns","ignore"]};function extractJsDocTags(ast){for(var extractedTags={params:null,returns:null,ignore:!1},i=0;i90}function isTooLongForDefaultValueSummary(value){return value.length>50}function createSummaryValue(summary,detail){return summary===detail?{summary:summary}:{summary:summary,detail:detail}}var FlowTypesType;function generateUnionElement(_ref){var name=_ref.name,value=_ref.value,elements=_ref.elements,raw=_ref.raw;return null!=value?value:null!=elements?elements.map(generateUnionElement).join(" | "):null!=raw?raw:name}function generateSignature(flowType){return"object"===flowType.type?function generateObjectSignature(_ref4){var type=_ref4.type,raw=_ref4.raw;return null!=raw?isTooLongForTypeSummary(raw)?createSummaryValue(type,raw):createSummaryValue(raw):createSummaryValue(type)}(flowType):function generateFuncSignature(_ref3){var type=_ref3.type,raw=_ref3.raw;return createSummaryValue(null!=raw?raw:type)}(flowType)}function createType(type){if(null==type)return null;switch(type.name){case FlowTypesType.UNION:return function generateUnion(_ref2){var name=_ref2.name,raw=_ref2.raw,elements=_ref2.elements;return createSummaryValue(null!=elements?elements.map(generateUnionElement).join(" | "):null!=raw?raw.replace(/^\|\s*/,""):name)}(type);case FlowTypesType.SIGNATURE:return generateSignature(type);default:return function generateDefault(_ref5){var name=_ref5.name,raw=_ref5.raw;return null!=raw?isTooLongForTypeSummary(raw)?createSummaryValue(name,raw):createSummaryValue(raw):createSummaryValue(name)}(type)}}!function(FlowTypesType){FlowTypesType.UNION="union",FlowTypesType.SIGNATURE="signature"}(FlowTypesType||(FlowTypesType={}));var BLACKLIST=["null","undefined"];function isDefaultValueBlacklisted(value){return BLACKLIST.some((function(x){return x===value}))}function createDefaultValue(defaultValue,type){if(null!=defaultValue){var value=defaultValue.value;if(!isDefaultValueBlacklisted(value))return isTooLongForDefaultValueSummary(value)?createSummaryValue(type.name,value):createSummaryValue(value)}return null}function createType_createType(_ref){var tsType=_ref.tsType,required=_ref.required;return null==tsType?null:createSummaryValue(required?tsType.name:tsType.name.replace(" | undefined",""))}function createDefaultValue_createDefaultValue(_ref){var defaultValue=_ref.defaultValue;if(null!=defaultValue){var value=defaultValue.value;if(!isDefaultValueBlacklisted(value))return createSummaryValue(value)}return null}__webpack_require__("./node_modules/core-js/modules/web.dom-collections.for-each.js");var convert_convert=function convert(type){var name=type.name,raw=type.raw,base={};switch(void 0!==raw&&(base.raw=raw),type.name){case"string":case"number":case"symbol":case"boolean":return Object.assign({},base,{name:name});case"Array":return Object.assign({},base,{name:"array",value:type.elements.map(convert)});case"signature":return Object.assign({},base,function convertSig(type){switch(type.type){case"function":return{name:"function"};case"object":var values={};return type.signature.properties.forEach((function(prop){values[prop.key]=convert_convert(prop.value)})),{name:"object",value:values};default:throw new Error("Unknown: ".concat(type))}}(type));case"union":case"intersection":return Object.assign({},base,{name:name,value:type.elements.map(convert)});default:return Object.assign({},base,{name:"other",value:name})}},isLiteral=function isLiteral(type){return"literal"===type.name},toEnumOption=function toEnumOption(element){return element.value.replace(/['|"]/g,"")},flow_convert_convert=function convert(type){var name=type.name,raw=type.raw,base={};switch(void 0!==raw&&(base.raw=raw),type.name){case"literal":return Object.assign({},base,{name:"other",value:type.value});case"string":case"number":case"symbol":case"boolean":return Object.assign({},base,{name:name});case"Array":return Object.assign({},base,{name:"array",value:type.elements.map(convert)});case"signature":return Object.assign({},base,function convertSig(type){switch(type.type){case"function":return{name:"function"};case"object":var values={};return type.signature.properties.forEach((function(prop){values[prop.key]=flow_convert_convert(prop.value)})),{name:"object",value:values};default:throw new Error("Unknown: ".concat(type))}}(type));case"union":return type.elements.every(isLiteral)?Object.assign({},base,{name:"enum",value:type.elements.map(toEnumOption)}):Object.assign({},base,{name:name,value:type.elements.map(convert)});case"intersection":return Object.assign({},base,{name:name,value:type.elements.map(convert)});default:return Object.assign({},base,{name:"other",value:name})}},mapValues=(__webpack_require__("./node_modules/core-js/modules/es.number.is-nan.js"),__webpack_require__("./node_modules/core-js/modules/es.number.constructor.js"),__webpack_require__("./node_modules/core-js/modules/es.string.split.js"),__webpack_require__("./node_modules/lodash/mapValues.js")),mapValues_default=__webpack_require__.n(mapValues),QUOTE_REGEX=/^['"]|['"]$/g,SIGNATURE_REGEXP=/^\(.*\) => /,proptypes_convert_convert=function convert(type){var name=type.name,raw=type.raw,computed=type.computed,value=type.value,base={};switch(void 0!==raw&&(base.raw=raw),name){case"enum":var _values=computed?value:value.map((function(v){var trimmedValue=function trimQuotes(str){return str.replace(QUOTE_REGEX,"")}(v.value);return function includesQuotes(str){return QUOTE_REGEX.test(str)}(v.value)||Number.isNaN(Number(trimmedValue))?trimmedValue:Number(trimmedValue)}));return Object.assign({},base,{name:name,value:_values});case"string":case"number":case"symbol":case"object":return Object.assign({},base,{name:name});case"func":return Object.assign({},base,{name:"function"});case"bool":case"boolean":return Object.assign({},base,{name:"boolean"});case"arrayOf":case"array":return Object.assign({},base,{name:"array",value:value&&convert(value)});case"objectOf":return Object.assign({},base,{name:name,value:convert(value)});case"shape":case"exact":var values=mapValues_default()(value,(function(field){return convert(field)}));return Object.assign({},base,{name:"object",value:values});case"union":return Object.assign({},base,{name:"union",value:value.map((function(v){return convert(v)}))});default:if((null==name?void 0:name.indexOf("|"))>0)try{var literalValues=name.split("|").map((function(v){return JSON.parse(v)}));return Object.assign({},base,{name:"enum",value:literalValues})}catch(err){}var otherVal=value?"".concat(name,"(").concat(value,")"):name,otherName=SIGNATURE_REGEXP.test(name)?"function":"other";return Object.assign({},base,{name:otherName,value:otherVal})}},convert=function convert(docgenInfo){var type=docgenInfo.type,tsType=docgenInfo.tsType,flowType=docgenInfo.flowType;return null!=type?proptypes_convert_convert(type):null!=tsType?convert_convert(tsType):null!=flowType?flow_convert_convert(flowType):null};function createPropDef_createType(type){return null!=type?createSummaryValue(type.name):null}function createPropDef_createDefaultValue(defaultValue,type){if(null!=defaultValue){var value=defaultValue.value;if(!isDefaultValueBlacklisted(value))return function isReactDocgenTypescript(defaultValue){var computed=defaultValue.computed,func=defaultValue.func;return void 0===computed&&void 0===func}(defaultValue)&&function isStringValued(type){return!!type&&("string"===type.name||"enum"===type.name&&Array.isArray(type.value)&&type.value.every((function(_ref){var tv=_ref.value;return"string"==typeof tv&&'"'===tv[0]&&'"'===tv[tv.length-1]})))}(type)?createSummaryValue(JSON.stringify(value)):createSummaryValue(value)}return null}function createBasicPropDef(name,type,docgenInfo){var description=docgenInfo.description,required=docgenInfo.required,defaultValue=docgenInfo.defaultValue;return{name:name,type:createPropDef_createType(type),required:required,description:description,defaultValue:createPropDef_createDefaultValue(defaultValue,type)}}function applyJsDocResult(propDef,jsDocParsingResult){if(jsDocParsingResult.includesJsDoc){var description=jsDocParsingResult.description,extractedTags=jsDocParsingResult.extractedTags;null!=description&&(propDef.description=jsDocParsingResult.description);var hasParams=null!=extractedTags.params,hasReturns=null!=extractedTags.returns&&null!=extractedTags.returns.type;(hasParams||hasReturns)&&(propDef.jsDocTags={params:hasParams&&extractedTags.params.map((function(x){return{name:x.getPrettyName(),description:x.description}})),returns:hasReturns&&{description:extractedTags.returns.description}})}return propDef}var javaScriptFactory=function javaScriptFactory(propName,docgenInfo,jsDocParsingResult){var propDef=createBasicPropDef(propName,docgenInfo.type,docgenInfo);return propDef.sbType=convert(docgenInfo),applyJsDocResult(propDef,jsDocParsingResult)},tsFactory=function tsFactory(propName,docgenInfo,jsDocParsingResult){var propDef=function createTsPropDef(propName,docgenInfo){var description=docgenInfo.description,required=docgenInfo.required;return{name:propName,type:createType_createType(docgenInfo),required:required,description:description,defaultValue:createDefaultValue_createDefaultValue(docgenInfo)}}(propName,docgenInfo);return propDef.sbType=convert(docgenInfo),applyJsDocResult(propDef,jsDocParsingResult)},flowFactory=function flowFactory(propName,docgenInfo,jsDocParsingResult){var propDef=function createFlowPropDef(propName,docgenInfo){var flowType=docgenInfo.flowType,description=docgenInfo.description,required=docgenInfo.required,defaultValue=docgenInfo.defaultValue;return{name:propName,type:createType(flowType),required:required,description:description,defaultValue:createDefaultValue(defaultValue,flowType)}}(propName,docgenInfo);return propDef.sbType=convert(docgenInfo),applyJsDocResult(propDef,jsDocParsingResult)},unknownFactory=function unknownFactory(propName,docgenInfo,jsDocParsingResult){return applyJsDocResult(createBasicPropDef(propName,{name:"unknown"},docgenInfo),jsDocParsingResult)},getPropDefFactory=function getPropDefFactory(typeSystem){switch(typeSystem){case TypeSystem.JAVASCRIPT:return javaScriptFactory;case TypeSystem.TYPESCRIPT:return tsFactory;case TypeSystem.FLOW:return flowFactory;default:return unknownFactory}},getTypeSystem=function getTypeSystem(docgenInfo){return null!=docgenInfo.type?TypeSystem.JAVASCRIPT:null!=docgenInfo.flowType?TypeSystem.FLOW:null!=docgenInfo.tsType?TypeSystem.TYPESCRIPT:TypeSystem.UNKNOWN},extractComponentProps=function extractComponentProps(component,section){var docgenSection=getDocgenSection(component,section);return function isValidDocgenSection(docgenSection){return null!=docgenSection&&Object.keys(docgenSection).length>0}(docgenSection)?Array.isArray(docgenSection)?function extractComponentSectionArray(docgenSection){var typeSystem=getTypeSystem(docgenSection[0]),createPropDef=getPropDefFactory(typeSystem);return docgenSection.map((function(item){var _item$type,sanitizedItem=item;return null!==(_item$type=item.type)&&void 0!==_item$type&&_item$type.elements&&(sanitizedItem=Object.assign({},item,{type:Object.assign({},item.type,{value:item.type.elements})})),extractProp(sanitizedItem.name,sanitizedItem,typeSystem,createPropDef)}))}(docgenSection):function extractComponentSectionObject(docgenSection){var docgenPropsKeys=Object.keys(docgenSection),typeSystem=getTypeSystem(docgenSection[docgenPropsKeys[0]]),createPropDef=getPropDefFactory(typeSystem);return docgenPropsKeys.map((function(propName){var docgenInfo=docgenSection[propName];return null!=docgenInfo?extractProp(propName,docgenInfo,typeSystem,createPropDef):null})).filter(Boolean)}(docgenSection):[]};function extractProp(propName,docgenInfo,typeSystem,createPropDef){var jsDocParsingResult=function parseJsDoc(value){var options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:DEFAULT_OPTIONS;if(!containsJsDoc(value))return{includesJsDoc:!1,ignore:!1};var jsDocAst=parse(value,options.tags),extractedTags=extractJsDocTags(jsDocAst);return extractedTags.ignore?{includesJsDoc:!0,ignore:!0}:{includesJsDoc:!0,ignore:!1,description:jsDocAst.description,extractedTags:extractedTags}}(docgenInfo.description);return jsDocParsingResult.includesJsDoc&&jsDocParsingResult.ignore?null:{propDef:createPropDef(propName,docgenInfo,jsDocParsingResult),jsDocTags:jsDocParsingResult.extractedTags,docgenInfo:docgenInfo,typeSystem:typeSystem}}var parameters=__webpack_require__("./node_modules/@storybook/store/dist/esm/parameters.js"),prop_types=(__webpack_require__("./node_modules/core-js/modules/es.array.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.map.js"),__webpack_require__("./node_modules/core-js/modules/es.string.iterator.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.iterator.js"),__webpack_require__("./node_modules/prop-types/index.js")),prop_types_default=__webpack_require__.n(prop_types);function generateFuncSignature_generateFuncSignature(params,returns){var hasParams=null!=params,hasReturns=null!=returns;if(!hasParams&&!hasReturns)return"";var funcParts=[];if(hasParams){var funcParams=params.map((function(x){var prettyName=x.getPrettyName(),typeName=x.getTypeName();return null!=typeName?"".concat(prettyName,": ").concat(typeName):prettyName}));funcParts.push("(".concat(funcParams.join(", "),")"))}else funcParts.push("()");return hasReturns&&funcParts.push("=> ".concat(returns.getTypeName())),funcParts.join(" ")}function generateShortFuncSignature(params,returns){var hasParams=null!=params,hasReturns=null!=returns;if(!hasParams&&!hasReturns)return"";var funcParts=[];return hasParams?funcParts.push("( ... )"):funcParts.push("()"),hasReturns&&funcParts.push("=> ".concat(returns.getTypeName())),funcParts.join(" ")}var html_tags=__webpack_require__("./node_modules/html-tags/index.js");function isHtmlTag(tagName){return html_tags.includes(tagName.toLowerCase())}__webpack_require__("./node_modules/core-js/modules/es.string.ends-with.js"),__webpack_require__("./node_modules/core-js/modules/es.array.slice.js"),__webpack_require__("./node_modules/core-js/modules/es.string.starts-with.js");var escodegen=__webpack_require__("./node_modules/escodegen/escodegen.js"),esm=__webpack_require__("./node_modules/ts-dedent/esm/index.js"),BASIC_OPTIONS={format:{indent:{style:" "},semicolons:!1}},COMPACT_OPTIONS=Object.assign({},BASIC_OPTIONS,{format:{newline:""}}),PRETTY_OPTIONS=Object.assign({},BASIC_OPTIONS);function generateCode(ast){var compact=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return(0,escodegen.R_)(ast,compact?COMPACT_OPTIONS:PRETTY_OPTIONS)}function generateObjectCode(ast){var compact=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return compact?generateCompactObjectCode(ast):generateCode(ast)}function generateCompactObjectCode(ast){var result=generateCode(ast,!0);return result.endsWith(" }")||(result="".concat(result.slice(0,-1)," }")),result}function generateArrayCode(ast){var compact=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return compact?generateCompactArrayCode(ast):generateMultilineArrayCode(ast)}function generateMultilineArrayCode(ast){var result=generateCode(ast);return result.endsWith(" }]")&&(result=(0,esm.C)(result)),result}function generateCompactArrayCode(ast){var result=generateCode(ast,!0);return result.startsWith("[ ")&&(result=result.replace("[ ","[")),result}var InspectionType,isMemo=function isMemo(component){return component.$$typeof===Symbol.for("react.memo")};!function(InspectionType){InspectionType.IDENTIFIER="Identifier",InspectionType.LITERAL="Literal",InspectionType.OBJECT="Object",InspectionType.ARRAY="Array",InspectionType.FUNCTION="Function",InspectionType.CLASS="Class",InspectionType.ELEMENT="Element",InspectionType.UNKNOWN="Unknown"}(InspectionType||(InspectionType={}));var acorn=__webpack_require__("./node_modules/@storybook/react/node_modules/acorn/dist/acorn.mjs"),acorn_jsx=__webpack_require__("./node_modules/@storybook/react/node_modules/acorn-jsx/index.js"),acorn_jsx_default=__webpack_require__.n(acorn_jsx);function simple(node,visitors,baseVisitor,state,override){baseVisitor||(baseVisitor=base),function c(node,st,override){var type=override||node.type,found=visitors[type];baseVisitor[type](node,st,c),found&&found(node,st)}(node,state,override)}Object.create;function skipThrough(node,st,c){c(node,st)}function ignore(_node,_st,_c){}var base={};base.Program=base.BlockStatement=function(node,st,c){for(var i=0,list=node.body;i1&&void 0!==arguments[1]&&arguments[1];return cleanPropTypes(generateObjectCode(ast,compact))}function prettyArray(ast){var compact=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return cleanPropTypes(generateCode(ast,compact))}function generateTypeFromString(value,originalTypeName){var short,compact,full,_inspectValue=inspectValue(value),inferredType=_inspectValue.inferredType,ast=_inspectValue.ast,type=inferredType.type;switch(type){case InspectionType.IDENTIFIER:case InspectionType.LITERAL:short=value,compact=value;break;case InspectionType.OBJECT:short="object",compact=1===inferredType.depth?prettyObject(ast,!0):null,full=prettyObject(ast);break;case InspectionType.ELEMENT:var identifier=inferredType.identifier;short=null==identifier||isHtmlTag(identifier)?"element":identifier,compact=1===splitIntoLines(value).length?value:null,full=value;break;case InspectionType.ARRAY:short="array",compact=inferredType.depth<=2?prettyArray(ast,!0):null,full=prettyArray(ast);break;default:short=function getCaptionForInspectionType(type){switch(type){case InspectionType.OBJECT:return"object";case InspectionType.ARRAY:return"array";case InspectionType.CLASS:return"class";case InspectionType.FUNCTION:return"func";case InspectionType.ELEMENT:return"element";default:return"custom"}}(type),compact=1===splitIntoLines(value).length?value:null,full=value}return createTypeDef({name:originalTypeName,short:short,compact:compact,full:full,inferredType:type})}function objectOf(of){return"objectOf(".concat(of,")")}function generateEnum(type){if(Array.isArray(type.value)){var values=type.value.reduce((function(acc,v){var _generateEnumValue=function generateEnumValue(_ref7){var value=_ref7.value;return _ref7.computed?generateTypeFromString(value,"enumvalue"):createTypeDef({name:"enumvalue",short:value,compact:value})}(v),short=_generateEnumValue.short,compact=_generateEnumValue.compact,full=_generateEnumValue.full;return acc.short.push(short),acc.compact.push(compact),acc.full.push(full),acc}),{short:[],compact:[],full:[]});return createTypeDef({name:PropTypesType.ENUM,short:values.short.join(" | "),compact:values.compact.every((function(x){return null!=x}))?values.compact.join(" | "):null,full:values.full.join(" | ")})}return createTypeDef({name:PropTypesType.ENUM,short:type.value,compact:type.value})}function braceAfter(of){return"".concat(of,"[]")}function braceAround(of){return"[".concat(of,"]")}function createArrayOfObjectTypeDef(short,compact,full){return createTypeDef({name:PropTypesType.ARRAYOF,short:braceAfter(short),compact:null!=compact?braceAround(compact):null,full:braceAround(full)})}function generateType(type,extractedProp){try{switch(type.name){case PropTypesType.CUSTOM:return function generateCustom(_ref5){var raw=_ref5.raw;return null!=raw?generateTypeFromString(raw,PropTypesType.CUSTOM):createTypeDef({name:PropTypesType.CUSTOM,short:"custom",compact:"custom"})}(type);case PropTypesType.FUNC:return function generateFunc(extractedProp){var jsDocTags=extractedProp.jsDocTags;return null==jsDocTags||null==jsDocTags.params&&null==jsDocTags.returns?createTypeDef({name:PropTypesType.FUNC,short:"func",compact:"func"}):createTypeDef({name:PropTypesType.FUNC,short:generateShortFuncSignature(jsDocTags.params,jsDocTags.returns),compact:null,full:generateFuncSignature_generateFuncSignature(jsDocTags.params,jsDocTags.returns)})}(extractedProp);case PropTypesType.SHAPE:return function generateShape(type,extractedProp){var fields=Object.keys(type.value).map((function(key){return"".concat(key,": ").concat(generateType(type.value[key],extractedProp).full)})).join(", "),_inspectValue2=inspectValue("{ ".concat(fields," }")),inferredType=_inspectValue2.inferredType,ast=_inspectValue2.ast,depth=inferredType.depth;return createTypeDef({name:PropTypesType.SHAPE,short:"object",compact:1===depth&&ast?prettyObject(ast,!0):null,full:ast?prettyObject(ast):null})}(type,extractedProp);case PropTypesType.INSTANCEOF:return createTypeDef({name:PropTypesType.INSTANCEOF,short:type.value,compact:type.value});case PropTypesType.OBJECTOF:return function generateObjectOf(type,extractedProp){var _generateType=generateType(type.value,extractedProp),short=_generateType.short,compact=_generateType.compact,full=_generateType.full;return createTypeDef({name:PropTypesType.OBJECTOF,short:objectOf(short),compact:null!=compact?objectOf(compact):null,full:objectOf(full)})}(type,extractedProp);case PropTypesType.UNION:return function createType_generateUnion(type,extractedProp){if(Array.isArray(type.value)){var values=type.value.reduce((function(acc,v){var _generateType2=generateType(v,extractedProp),short=_generateType2.short,compact=_generateType2.compact,full=_generateType2.full;return acc.short.push(short),acc.compact.push(compact),acc.full.push(full),acc}),{short:[],compact:[],full:[]});return createTypeDef({name:PropTypesType.UNION,short:values.short.join(" | "),compact:values.compact.every((function(x){return null!=x}))?values.compact.join(" | "):null,full:values.full.join(" | ")})}return createTypeDef({name:PropTypesType.UNION,short:type.value,compact:null})}(type,extractedProp);case PropTypesType.ENUM:return generateEnum(type);case PropTypesType.ARRAYOF:return function generateArray(type,extractedProp){var _generateType3=generateType(type.value,extractedProp),name=_generateType3.name,short=_generateType3.short,compact=_generateType3.compact,full=_generateType3.full,inferredType=_generateType3.inferredType;if(name===PropTypesType.CUSTOM){if(inferredType===InspectionType.OBJECT)return createArrayOfObjectTypeDef(short,compact,full)}else if(name===PropTypesType.SHAPE)return createArrayOfObjectTypeDef(short,compact,full);return createTypeDef({name:PropTypesType.ARRAYOF,short:braceAfter(short),compact:braceAfter(short)})}(type,extractedProp);default:return createTypeDef({name:type.name,short:type.name,compact:type.name})}}catch(e){console.error(e)}return createTypeDef({name:"unknown",short:"unknown",compact:"unknown"})}function generateObject(_ref){var inferredType=_ref.inferredType,ast=_ref.ast;if(1===inferredType.depth){var compactObject=generateObjectCode(ast,!0);if(!isTooLongForDefaultValueSummary(compactObject))return createSummaryValue(compactObject)}return createSummaryValue("object",generateObjectCode(ast))}function generateArray_generateArray(_ref){var inferredType=_ref.inferredType,ast=_ref.ast;if(inferredType.depth<=2){var compactArray=generateArrayCode(ast,!0);if(!isTooLongForDefaultValueSummary(compactArray))return createSummaryValue(compactArray)}return createSummaryValue("array",generateArrayCode(ast))}function getPrettyIdentifier(inferredType){var type=inferredType.type,identifier=inferredType.identifier;switch(type){case InspectionType.FUNCTION:return getPrettyFuncIdentifier(identifier,inferredType.hasParams);case InspectionType.ELEMENT:return getPrettyElementIdentifier(identifier);default:return identifier}}function getPrettyFuncIdentifier(identifier,hasArguments){return"".concat(identifier,hasArguments?"( ... )":"()")}function getPrettyElementIdentifier(identifier){return"<".concat(identifier," />")}function defaultValues_createDefaultValue_createDefaultValue(defaultValue){try{var inspectionResult=inspectValue(defaultValue);switch(inspectionResult.inferredType.type){case InspectionType.OBJECT:return generateObject(inspectionResult);case InspectionType.FUNCTION:return function createDefaultValue_generateFunc(_ref){var inferredType=_ref.inferredType,ast=_ref.ast;if(null!=inferredType.identifier)return createSummaryValue(getPrettyIdentifier(inferredType),generateCode(ast));var prettyCaption=generateCode(ast,!0);return isTooLongForDefaultValueSummary(prettyCaption)?createSummaryValue("func",generateCode(ast)):createSummaryValue(prettyCaption)}(inspectionResult);case InspectionType.ELEMENT:return function generateElement(defaultValue,inspectionResult){var inferredType=inspectionResult.inferredType,identifier=inferredType.identifier;return null==identifier||isHtmlTag(identifier)?isTooLongForDefaultValueSummary(defaultValue)?createSummaryValue("element",defaultValue):createSummaryValue(defaultValue):createSummaryValue(getPrettyIdentifier(inferredType),defaultValue)}(defaultValue,inspectionResult);case InspectionType.ARRAY:return generateArray_generateArray(inspectionResult);default:return null}}catch(e){console.error(e)}return null}!function(PropTypesType){PropTypesType.CUSTOM="custom",PropTypesType.ANY="any",PropTypesType.FUNC="func",PropTypesType.SHAPE="shape",PropTypesType.OBJECT="object",PropTypesType.INSTANCEOF="instanceOf",PropTypesType.OBJECTOF="objectOf",PropTypesType.UNION="union",PropTypesType.ENUM="enum",PropTypesType.ARRAYOF="arrayOf",PropTypesType.ELEMENT="element",PropTypesType.ELEMENTTYPE="elementType",PropTypesType.NODE="node"}(PropTypesType||(PropTypesType={}));__webpack_require__("./node_modules/core-js/modules/es.regexp.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.iterator.js");var isPlainObject=__webpack_require__("./node_modules/lodash/isPlainObject.js"),isPlainObject_default=__webpack_require__.n(isPlainObject),isFunction=__webpack_require__("./node_modules/lodash/isFunction.js"),isFunction_default=__webpack_require__.n(isFunction),isString=__webpack_require__("./node_modules/lodash/isString.js"),isString_default=__webpack_require__.n(isString),cjs=__webpack_require__("./node_modules/react-element-to-jsx-string/dist/cjs/index.js");function _typeof(obj){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}function isReactElement(element){return null!=element.$$typeof}function extractFunctionName(func,propName){var name=func.name;return""!==name&&"anonymous"!==name&&name!==propName?name:null}var DEFAULT_TYPE_RESOLVERS={string:function stringResolver(rawDefaultProp){return createSummaryValue(JSON.stringify(rawDefaultProp))},object:function objectResolver(rawDefaultProp){return isReactElement(rawDefaultProp)&&null!=rawDefaultProp.type?function generateReactObject(rawDefaultProp){var type=rawDefaultProp.type,displayName=type.displayName,jsx=(0,cjs.ZP)(rawDefaultProp,{});if(null!=displayName)return createSummaryValue(getPrettyElementIdentifier(displayName),jsx);if(isString_default()(type)&&isHtmlTag(type)){var jsxSummary=(0,cjs.ZP)(rawDefaultProp,{tabStop:0}).replace(/\r?\n|\r/g,"");if(!isTooLongForDefaultValueSummary(jsxSummary))return createSummaryValue(jsxSummary)}return createSummaryValue("element",jsx)}(rawDefaultProp):isPlainObject_default()(rawDefaultProp)?generateObject(inspectValue(JSON.stringify(rawDefaultProp))):Array.isArray(rawDefaultProp)?generateArray_generateArray(inspectValue(JSON.stringify(rawDefaultProp))):createSummaryValue("object")},function:function functionResolver(rawDefaultProp,propDef){var inspectionResult,isElement=!1;if(isFunction_default()(rawDefaultProp.render))isElement=!0;else if(null!=rawDefaultProp.prototype&&isFunction_default()(rawDefaultProp.prototype.render))isElement=!0;else{var innerElement;try{var _ref=(inspectionResult=inspectValue(rawDefaultProp.toString())).inferredType,hasParams=_ref.hasParams,params=_ref.params;hasParams?1===params.length&&"ObjectPattern"===params[0].type&&(innerElement=rawDefaultProp({})):innerElement=rawDefaultProp(),null!=innerElement&&isReactElement(innerElement)&&(isElement=!0)}catch(e){}}var funcName=extractFunctionName(rawDefaultProp,propDef.name);return null!=funcName?isElement?createSummaryValue(getPrettyElementIdentifier(funcName)):(null!=inspectionResult&&(inspectionResult=inspectValue(rawDefaultProp.toString())),createSummaryValue(getPrettyFuncIdentifier(funcName,inspectionResult.inferredType.hasParams))):createSummaryValue(isElement?"element":"func")},default:function defaultResolver(rawDefaultProp){return createSummaryValue(rawDefaultProp.toString())}};function createDefaultValueFromRawDefaultProp(rawDefaultProp,propDef){var typeResolvers=arguments.length>2&&void 0!==arguments[2]?arguments[2]:DEFAULT_TYPE_RESOLVERS;try{switch(_typeof(rawDefaultProp)){case"string":return typeResolvers.string(rawDefaultProp,propDef);case"object":return typeResolvers.object(rawDefaultProp,propDef);case"function":return typeResolvers.function(rawDefaultProp,propDef);default:return typeResolvers.default(rawDefaultProp,propDef)}}catch(e){console.error(e)}return null}__webpack_require__("./node_modules/core-js/modules/es.array.find.js");var rawDefaultPropTypeResolvers=function createTypeResolvers(){var customResolvers=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object.assign({},DEFAULT_TYPE_RESOLVERS,customResolvers)}({function:function funcResolver(rawDefaultProp,_ref){var name=_ref.name,type=_ref.type,isElement="element"===type.summary||"elementType"===type.summary,funcName=extractFunctionName(rawDefaultProp,name);return createSummaryValue(null!=funcName?isElement?getPrettyElementIdentifier(funcName):getPrettyFuncIdentifier(funcName,inspectValue(rawDefaultProp.toString()).inferredType.hasParams):isElement?"element":"func")}});function enhancePropTypesProp(extractedProp,rawDefaultProp){var propDef=extractedProp.propDef,newtype=function propTypes_createType_createType(extractedProp){var type=extractedProp.docgenInfo.type;if(null==type)return null;try{switch(type.name){case PropTypesType.CUSTOM:case PropTypesType.SHAPE:case PropTypesType.INSTANCEOF:case PropTypesType.OBJECTOF:case PropTypesType.UNION:case PropTypesType.ENUM:case PropTypesType.ARRAYOF:var _generateType4=generateType(type,extractedProp),short=_generateType4.short,compact=_generateType4.compact,full=_generateType4.full;return null==compact||isTooLongForTypeSummary(compact)?createSummaryValue(short,full):createSummaryValue(compact);case PropTypesType.FUNC:var detail,_generateType5=generateType(type,extractedProp),_short=_generateType5.short,_full=_generateType5.full,summary=_short;return _full.length<150?summary=_full:detail=function toMultilineSignature(signature){return signature.replace(/,/g,",\r\n")}(_full),createSummaryValue(summary,detail);default:return null}}catch(e){console.error(e)}return null}(extractedProp);null!=newtype&&(propDef.type=newtype);var defaultValue=extractedProp.docgenInfo.defaultValue;if(null!=defaultValue&&null!=defaultValue.value){var newDefaultValue=defaultValues_createDefaultValue_createDefaultValue(defaultValue.value);null!=newDefaultValue&&(propDef.defaultValue=newDefaultValue)}else if(null!=rawDefaultProp){var _newDefaultValue=createDefaultValueFromRawDefaultProp(rawDefaultProp,propDef,rawDefaultPropTypeResolvers);null!=_newDefaultValue&&(propDef.defaultValue=_newDefaultValue)}return propDef}function enhancePropTypesProps(extractedProps,component){var rawDefaultProps=null!=component.defaultProps?component.defaultProps:{};return function keepOriginalDefinitionOrder(extractedProps,component){var propTypes=component.propTypes;return null!=propTypes?Object.keys(propTypes).map((function(x){return extractedProps.find((function(y){return y.name===x}))})).filter((function(x){return x})):extractedProps}(extractedProps.map((function(x){return enhancePropTypesProp(x,rawDefaultProps[x.propDef.name])})),component)}function enhanceTypeScriptProps(extractedProps){return extractedProps.map((function(prop){return function enhanceTypeScriptProp(extractedProp,rawDefaultProp){var propDef=extractedProp.propDef,defaultValue=extractedProp.docgenInfo.defaultValue;if(null!=defaultValue&&null!=defaultValue.value){var newDefaultValue=defaultValues_createDefaultValue_createDefaultValue(defaultValue.value);null!=newDefaultValue&&(propDef.defaultValue=newDefaultValue)}else if(null!=rawDefaultProp){var _newDefaultValue=createDefaultValueFromRawDefaultProp(rawDefaultProp,propDef);null!=_newDefaultValue&&(propDef.defaultValue=_newDefaultValue)}return propDef}(prop)}))}var propTypesMap=new Map;function getPropDefs(component,section){var processedComponent=component;hasDocgen(component)||component.propTypes||!isMemo(component)||(processedComponent=component.type);var extractedProps=extractComponentProps(processedComponent,section);if(0===extractedProps.length)return[];switch(extractedProps[0].typeSystem){case TypeSystem.JAVASCRIPT:return enhancePropTypesProps(extractedProps,component);case TypeSystem.TYPESCRIPT:return enhanceTypeScriptProps(extractedProps);default:return extractedProps.map((function(x){return x.propDef}))}}Object.keys(prop_types_default()).forEach((function(typeName){var type=prop_types_default()[typeName];propTypesMap.set(type,typeName),propTypesMap.set(type.isRequired,typeName)}));__webpack_require__("./node_modules/core-js/modules/es.object.freeze.js"),__webpack_require__("./node_modules/core-js/modules/es.array.from.js"),__webpack_require__("./node_modules/core-js/modules/es.string.match.js");var SourceType,react=__webpack_require__("./node_modules/react/index.js"),browser=__webpack_require__("./node_modules/util-deprecate/browser.js"),browser_default=__webpack_require__.n(browser),dist_esm=__webpack_require__("./node_modules/@storybook/addons/dist/esm/index.js"),hooks=__webpack_require__("./node_modules/@storybook/addons/dist/esm/hooks.js"),SNIPPET_RENDERED=("".concat("storybook/docs","/panel"),"".concat("storybook/docs","/snippet-rendered"));!function(SourceType){SourceType.AUTO="auto",SourceType.CODE="code",SourceType.DYNAMIC="dynamic"}(SourceType||(SourceType={}));var _templateObject,client_logger_dist_esm=__webpack_require__("./node_modules/@storybook/client-logger/dist/esm/index.js"),_excluded=["mdxType","originalType","children"];function _toConsumableArray(arr){return function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr)}(arr)||function _iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}(arr)||function _unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}(arr)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}var applyBeforeRender=function applyBeforeRender(domString,options){return"function"!=typeof options.onBeforeRender?domString:browser_default()(options.onBeforeRender,(0,esm.C)(_templateObject||(_templateObject=function _taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}(["\n StoryFn.parameters.jsx.onBeforeRender was deprecated.\n Prefer StoryFn.parameters.jsx.transformSource instead.\n See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-onbeforerender for details.\n "]))))(domString)},renderJsx=function renderJsx(code,options){if(void 0===code)return client_logger_dist_esm.kg.warn("Too many skip or undefined component"),null;for(var renderedJSX=code,Type=renderedJSX.type,i=0;i1)return client_logger_dist_esm.kg.warn("Trying to skip an array of elements"),null;void 0===renderedJSX.props.children?(client_logger_dist_esm.kg.warn("Not enough children to skip elements."),"function"==typeof renderedJSX.type&&""===renderedJSX.type.name&&(renderedJSX=react.createElement(Type,renderedJSX.props))):renderedJSX="function"==typeof renderedJSX.props.children?renderedJSX.props.children():renderedJSX.props.children}var displayNameDefaults="string"==typeof options.displayName?{showFunctions:!0,displayName:function displayName(){return options.displayName}}:{displayName:function displayName(el){return el.type.displayName||getDocgenSection(el.type,"displayName")||("_default"!==el.type.name?el.type.name:null)||("function"==typeof el.type?"No Display Name":null)||(function isForwardRef(component){return component.$$typeof===Symbol.for("react.forward_ref")}(el.type)?el.type.render.name:null)||(isMemo(el.type)?el.type.type.name:null)||el.type}},filterDefaults={filterProps:function filterProps(value,key){return void 0!==value}},opts=Object.assign({},displayNameDefaults,filterDefaults,options),result=react.Children.map(code,(function(c){var child="number"==typeof c?c.toString():c,string=applyBeforeRender((0,cjs.ZP)(child,opts),options);if(string.indexOf(""")>-1){var matches=string.match(/\S+=\\"([^"]*)\\"/g);matches&&matches.forEach((function(match){string=string.replace(match,match.replace(/"/g,"'"))}))}return string})).join("\n");return result.replace(/function\s+noRefCheck\(\)\s+\{\}/,"() => {}")},defaultOpts={skip:0,showFunctions:!1,enableBeautify:!0,showDefaultProps:!1},mdxToJsx=function mdxToJsx(node){if(!function isMdx(node){var _node$type,_node$props;return"MDXCreateElement"===(null===(_node$type=node.type)||void 0===_node$type?void 0:_node$type.displayName)&&!(null===(_node$props=node.props)||void 0===_node$props||!_node$props.mdxType)}(node))return node;var _node$props2=node.props,originalType=(_node$props2.mdxType,_node$props2.originalType),children=_node$props2.children,rest=_objectWithoutProperties(_node$props2,_excluded),jsxChildren=[];children&&(jsxChildren=(Array.isArray(children)?children:[children]).map(mdxToJsx));return react.createElement.apply(void 0,[originalType,rest].concat(_toConsumableArray(jsxChildren)))},config_parameters={docs:{inlineStories:!0,prepareForInline:function prepareForInline(storyFn){return storyFn()},extractArgTypes:function extractArgTypes(component){if(component){var _extractProps=function extractProps(component){return{rows:getPropDefs(component,"props")}}(component),rows=_extractProps.rows;if(rows)return rows.reduce((function(acc,row){var name=row.name,description=row.description,type=row.type,sbType=row.sbType,defaultSummary=row.defaultValue,jsDocTags=row.jsDocTags,required=row.required;return acc[name]={name:name,description:description,type:Object.assign({required:required},sbType),table:{type:type,jsDocTags:jsDocTags,defaultValue:defaultSummary}},acc}),{})}return null},extractComponentDescription:function extractComponentDescription(component){return null!=component&&function getDocgenDescription(component){return hasDocgen(component)&&(0,string.B)(component.__docgenInfo.description)}(component)}}},decorators=[function jsxDecorator(storyFn,context){var _context$parameters$d2,_context$parameters$d3,channel=dist_esm.KP.getChannel(),skip=function skipJsxRender(context){var _context$parameters$d,sourceParams=null==context||null===(_context$parameters$d=context.parameters.docs)||void 0===_context$parameters$d?void 0:_context$parameters$d.source,isArgsStory=null==context?void 0:context.parameters.__isArgsStory;return(null==sourceParams?void 0:sourceParams.type)!==SourceType.DYNAMIC&&(!isArgsStory||(null==sourceParams?void 0:sourceParams.code)||(null==sourceParams?void 0:sourceParams.type)===SourceType.CODE)}(context),story=storyFn(),jsx="";if((0,hooks.d4)((function(){skip||channel.emit(SNIPPET_RENDERED,(context||{}).id,jsx)})),skip)return story;var options=Object.assign({},defaultOpts,(null==context?void 0:context.parameters.jsx)||{}),storyJsx=null!=context&&null!==(_context$parameters$d2=context.parameters.docs)&&void 0!==_context$parameters$d2&&null!==(_context$parameters$d3=_context$parameters$d2.source)&&void 0!==_context$parameters$d3&&_context$parameters$d3.excludeDecorators?context.originalStoryFn(context.args,context):story,sourceJsx=mdxToJsx(storyJsx),rendered=renderJsx(sourceJsx,options);return rendered&&(jsx=function applyTransformSource(domString,options,context){return"function"!=typeof options.transformSource?domString:options.transformSource(domString,context)}(rendered,options,context)),story}],argTypesEnhancers=[function enhanceArgTypes(context){var component=context.component,userArgTypes=context.argTypes,_context$parameters$d=context.parameters.docs,extractArgTypes=(void 0===_context$parameters$d?{}:_context$parameters$d).extractArgTypes,extractedArgTypes=extractArgTypes&&component?extractArgTypes(component):{};return extractedArgTypes?(0,parameters.f)(extractedArgTypes,userArgTypes):userArgTypes}];function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.keys(config_namespaceObject).forEach((function(key){var value=config_namespaceObject[key];switch(key){case"args":return(0,ClientApi.uc)(value);case"argTypes":return(0,ClientApi.v9)(value);case"decorators":return value.forEach((function(decorator){return(0,ClientApi.$9)(decorator,!1)}));case"loaders":return value.forEach((function(loader){return(0,ClientApi.HZ)(loader,!1)}));case"parameters":return(0,ClientApi.h1)(function _objectSpread(target){for(var i=1;iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0&&void 0!==arguments[0]?arguments[0]:{v:3,stories:{}},stories=_ref.stories;_classCallCheck(this,StoryIndexStore),this.channel=void 0,this.stories=void 0,this.stories=stories}return function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}(StoryIndexStore,[{key:"storyIdFromSpecifier",value:function storyIdFromSpecifier(specifier){var storyIds=Object.keys(this.stories);if("*"===specifier)return storyIds[0];if("string"==typeof specifier)return storyIds.indexOf(specifier)>=0?specifier:storyIds.find((function(storyId){return storyId.startsWith(specifier)}));var name=specifier.name,title=specifier.title,match=Object.entries(this.stories).find((function(_ref2){var _ref3=_slicedToArray(_ref2,2),story=(_ref3[0],_ref3[1]);return story.name===name&&story.title===title}));return match&&match[0]}},{key:"storyIdToEntry",value:function storyIdToEntry(storyId){var storyEntry=this.stories[storyId];if(!storyEntry)throw new Error((0,esm.C)(_templateObject||(_templateObject=function _taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}(["Couldn't find story matching '","' after HMR.\n - Did you remove it from your CSF file?\n - Are you sure a story with that id exists?\n - Please check your stories field of your main.js config.\n - Also check the browser console and terminal for error messages."])),storyId));return storyEntry}}]),StoryIndexStore}(),fast_deep_equal=(__webpack_require__("./node_modules/core-js/modules/es.number.constructor.js"),__webpack_require__("./node_modules/core-js/modules/es.array.includes.js"),__webpack_require__("./node_modules/core-js/modules/es.array.find-index.js"),__webpack_require__("./node_modules/core-js/modules/es.string.includes.js"),__webpack_require__("./node_modules/core-js/modules/es.array.join.js"),__webpack_require__("./node_modules/core-js/modules/es.array.fill.js"),__webpack_require__("./node_modules/fast-deep-equal/index.js")),fast_deep_equal_default=__webpack_require__.n(fast_deep_equal),dist_esm=__webpack_require__("./node_modules/@storybook/client-logger/dist/esm/index.js"),isPlainObject=__webpack_require__("./node_modules/lodash/isPlainObject.js"),isPlainObject_default=__webpack_require__.n(isPlainObject);function args_taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}function _toConsumableArray(arr){return function _arrayWithoutHoles(arr){if(Array.isArray(arr))return args_arrayLikeToArray(arr)}(arr)||function _iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}(arr)||args_unsupportedIterableToArray(arr)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function args_slicedToArray(arr,i){return function args_arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function args_iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||args_unsupportedIterableToArray(arr,i)||function args_nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function args_unsupportedIterableToArray(o,minLen){if(o){if("string"==typeof o)return args_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?args_arrayLikeToArray(o,minLen):void 0}}function args_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i=value.length?res:res.concat(new Array(value.length-update.length).fill(void 0))}return isPlainObject_default()(value)&&isPlainObject_default()(update)?Object.keys(Object.assign({},value,update)).reduce((function(acc,key){var diff=deepDiff(null==value?void 0:value[key],null==update?void 0:update[key]);return diff===DEEPLY_EQUAL?acc:Object.assign(acc,_defineProperty({},key,diff))}),{}):update};function groupArgsByTarget(_ref7){var args=_ref7.args,argTypes=_ref7.argTypes,groupedArgs={};return Object.entries(args).forEach((function(_ref8){var _ref9=args_slicedToArray(_ref8,2),name=_ref9[0],value=_ref9[1],_ref10$target=(argTypes[name]||{}).target,target=void 0===_ref10$target?"":_ref10$target;groupedArgs[target]=groupedArgs[target]||{},groupedArgs[target][name]=value})),groupedArgs}function ArgsStore_defineProperties(target,props){for(var i=0;iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0&&void 0!==arguments[0]?arguments[0]:{};return Object.entries(argTypes).reduce((function(acc,_ref){var _ref2=getValuesFromArgTypes_slicedToArray(_ref,2),arg=_ref2[0],defaultValue=_ref2[1].defaultValue;return void 0!==defaultValue&&(acc[arg]=defaultValue),acc}),{})};function GlobalsStore_slicedToArray(arr,i){return function GlobalsStore_arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function GlobalsStore_iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||GlobalsStore_unsupportedIterableToArray(arr,i)||function GlobalsStore_nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function GlobalsStore_toConsumableArray(arr){return function GlobalsStore_arrayWithoutHoles(arr){if(Array.isArray(arr))return GlobalsStore_arrayLikeToArray(arr)}(arr)||function GlobalsStore_iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}(arr)||GlobalsStore_unsupportedIterableToArray(arr)||function GlobalsStore_nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function GlobalsStore_unsupportedIterableToArray(o,minLen){if(o){if("string"==typeof o)return GlobalsStore_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?GlobalsStore_arrayLikeToArray(o,minLen):void 0}}function GlobalsStore_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i StoryFn.storyName\n- StoryFn.story.(parameters|decorators) => StoryFn.(parameters|decorators)\nSee https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-annotations for details and codemod.\n"]))),deprecatedStoryAnnotationWarning=browser_default()((function(){}),deprecatedStoryAnnotation);function normalizeStory(key,storyAnnotations,meta){var userStoryFn,storyObject;"function"==typeof storyAnnotations?(userStoryFn=storyAnnotations,storyObject=storyAnnotations):storyObject=storyAnnotations;var story=storyObject.story;story&&(dist_esm.kg.debug("deprecated story",story),deprecatedStoryAnnotationWarning());var exportName=(0,dist.storyNameFromExport)(key),name="function"!=typeof storyObject&&storyObject.name||storyObject.storyName||(null==story?void 0:story.name)||exportName,decorators=[].concat(normalizeStory_toConsumableArray(storyObject.decorators||[]),normalizeStory_toConsumableArray((null==story?void 0:story.decorators)||[])),parameters=Object.assign({},null==story?void 0:story.parameters,storyObject.parameters),args=Object.assign({},null==story?void 0:story.args,storyObject.args),argTypes=Object.assign({},null==story?void 0:story.argTypes,storyObject.argTypes),loaders=[].concat(normalizeStory_toConsumableArray(storyObject.loaders||[]),normalizeStory_toConsumableArray((null==story?void 0:story.loaders)||[])),_storyObject2=storyObject,render=_storyObject2.render,play=_storyObject2.play,id=parameters.__id||(0,dist.toId)(meta.id||meta.title,exportName);return Object.assign({id:id,name:name,decorators:decorators,parameters:parameters,args:args,argTypes:(0,normalizeInputTypes.x)(argTypes),loaders:loaders},render&&{render:render},userStoryFn&&{userStoryFn:userStoryFn},play&&{play:play})}function normalizeComponentAnnotations(defaultExport){var title=arguments.length>1&&void 0!==arguments[1]?arguments[1]:defaultExport.title,importPath=arguments.length>2?arguments[2]:void 0,id=defaultExport.id,argTypes=defaultExport.argTypes;return Object.assign({id:(0,dist.sanitize)(id||title)},defaultExport,{title:title},argTypes&&{argTypes:(0,normalizeInputTypes.x)(argTypes)},{parameters:Object.assign({fileName:importPath},defaultExport.parameters)})}var _excluded=["default","__namedExportsOrder"];function _objectWithoutProperties(source,excluded){if(null==source)return{};var key,i,target=function _objectWithoutPropertiesLoose(source,excluded){if(null==source)return{};var key,i,target={},sourceKeys=Object.keys(source);for(i=0;i=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}var checkDisallowedParameters=function checkDisallowedParameters(parameters){parameters&&(function checkGlobals(parameters){var globals=parameters.globals,globalTypes=parameters.globalTypes;(globals||globalTypes)&&dist_esm.kg.error("Global args/argTypes can only be set globally",JSON.stringify({globals:globals,globalTypes:globalTypes}))}(parameters),function checkStorySort(parameters){var options=parameters.options;null!=options&&options.storySort&&dist_esm.kg.error("The storySort option parameter can only be set globally")}(parameters))};function processCSFFile(moduleExports,importPath,title){var defaultExport=moduleExports.default,namedExports=(moduleExports.__namedExportsOrder,_objectWithoutProperties(moduleExports,_excluded)),meta=normalizeComponentAnnotations(defaultExport,title,importPath);checkDisallowedParameters(meta.parameters);var csfFile={meta:meta,stories:{}};return Object.keys(namedExports).forEach((function(key){if((0,dist.isExportStory)(key,meta)){var storyMeta=normalizeStory(key,namedExports[key],meta);checkDisallowedParameters(storyMeta.parameters),csfFile.stories[storyMeta.id]=storyMeta}})),csfFile}var prepareStory_templateObject,esm_parameters=__webpack_require__("./node_modules/@storybook/store/dist/esm/parameters.js"),hooks=__webpack_require__("./node_modules/@storybook/addons/dist/esm/hooks.js"),decorators_excluded=["componentId","title","kind","id","name","story","parameters","initialArgs","argTypes"];function decorators_objectWithoutProperties(source,excluded){if(null==source)return{};var key,i,target=function decorators_objectWithoutPropertiesLoose(source,excluded){if(null==source)return{};var key,i,target={},sourceKeys=Object.keys(source);for(i=0;i=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}function defaultDecorateStory(storyFn,decorators){var contextStore={},bindWithContext=function bindWithContext(decoratedStoryFn){return function(update){return contextStore.value=Object.assign({},contextStore.value,function sanitizeStoryContextUpdate(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return _ref.componentId,_ref.title,_ref.kind,_ref.id,_ref.name,_ref.story,_ref.parameters,_ref.initialArgs,_ref.argTypes,decorators_objectWithoutProperties(_ref,decorators_excluded)}(update)),decoratedStoryFn(contextStore.value)}},decoratedWithContextStore=decorators.reduce((function(story,decorator){return function decorateStory(storyFn,decorator,bindWithContext){var boundStoryFunction=bindWithContext(storyFn);return function(context){return decorator(boundStoryFunction,context)}}(story,decorator,bindWithContext)}),storyFn);return function(context){return contextStore.value=context,decoratedWithContextStore(context)}}function prepareStory_slicedToArray(arr,i){return function prepareStory_arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function prepareStory_iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||prepareStory_unsupportedIterableToArray(arr,i)||function prepareStory_nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function prepareStory_toConsumableArray(arr){return function prepareStory_arrayWithoutHoles(arr){if(Array.isArray(arr))return prepareStory_arrayLikeToArray(arr)}(arr)||function prepareStory_iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}(arr)||prepareStory_unsupportedIterableToArray(arr)||function prepareStory_nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function prepareStory_unsupportedIterableToArray(o,minLen){if(o){if("string"==typeof o)return prepareStory_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?prepareStory_arrayLikeToArray(o,minLen):void 0}}function prepareStory_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0;var passedArgs=Object.assign({},projectAnnotations.args,componentAnnotations.args,storyAnnotations.args),contextForEnhancers={componentId:componentAnnotations.id,title:title,kind:title,id:id,name:name,story:name,component:componentAnnotations.component,subcomponents:componentAnnotations.subcomponents,parameters:parameters,initialArgs:passedArgs,argTypes:passedArgTypes};contextForEnhancers.argTypes=argTypesEnhancers.reduce((function(accumulatedArgTypes,enhancer){return enhancer(Object.assign({},contextForEnhancers,{argTypes:accumulatedArgTypes}))}),contextForEnhancers.argTypes);var defaultArgs=getValuesFromArgTypes(contextForEnhancers.argTypes);Object.keys(defaultArgs).length>0&&argTypeDefaultValueWarning();var initialArgsBeforeEnhancers=Object.assign({},defaultArgs,passedArgs);contextForEnhancers.initialArgs=argsEnhancers.reduce((function(accumulatedArgs,enhancer){return Object.assign({},accumulatedArgs,enhancer(Object.assign({},contextForEnhancers,{initialArgs:accumulatedArgs})))}),initialArgsBeforeEnhancers),null!==(_global$FEATURES=window_default().FEATURES)&&void 0!==_global$FEATURES&&_global$FEATURES.breakingChangesV7||(contextForEnhancers.parameters=Object.assign({},contextForEnhancers.parameters,{__id:id,globals:projectAnnotations.globals,globalTypes:projectAnnotations.globalTypes,args:contextForEnhancers.initialArgs,argTypes:contextForEnhancers.argTypes}));var applyLoaders=function(){var _ref=function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise((function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)}))}}(regeneratorRuntime.mark((function _callee(context){var loadResults,loaded;return regeneratorRuntime.wrap((function _callee$(_context){for(;;)switch(_context.prev=_context.next){case 0:return _context.next=2,Promise.all(loaders.map((function(loader){return loader(context)})));case 2:return loadResults=_context.sent,loaded=Object.assign.apply(Object,[{}].concat(prepareStory_toConsumableArray(loadResults))),_context.abrupt("return",Object.assign({},context,{loaded:loaded}));case 5:case"end":return _context.stop()}}),_callee)})));return function applyLoaders(_x){return _ref.apply(this,arguments)}}(),undecoratedStoryFn=function undecoratedStoryFn(context){var mappedArgs=Object.entries(context.args).reduce((function(acc,_ref2){var _context$argTypes$key,_ref3=prepareStory_slicedToArray(_ref2,2),key=_ref3[0],val=_ref3[1],mapping=null===(_context$argTypes$key=context.argTypes[key])||void 0===_context$argTypes$key?void 0:_context$argTypes$key.mapping;return acc[key]=mapping&&val in mapping?mapping[val]:val,acc}),{}),includedArgs=Object.entries(mappedArgs).reduce((function(acc,_ref4){var _ref5=prepareStory_slicedToArray(_ref4,2),key=_ref5[0],val=_ref5[1],argType=context.argTypes[key]||{};return(0,dist.includeConditionalArg)(argType,mappedArgs,context.globals)&&(acc[key]=val),acc}),{}),includedContext=Object.assign({},context,{args:includedArgs}),_context$parameters$p=context.parameters.passArgsFirst;return void 0===_context$parameters$p||_context$parameters$p?render(includedContext.args,includedContext):render(includedContext)},decoratedStoryFn=(0,hooks.DM)(applyDecorators)(undecoratedStoryFn,decorators),playFunction=storyAnnotations.play;return Object.freeze(Object.assign({},contextForEnhancers,{originalStoryFn:render,undecoratedStoryFn:undecoratedStoryFn,unboundStoryFn:function unboundStoryFn(context){var _global$FEATURES2,finalContext=context;if(null!==(_global$FEATURES2=window_default().FEATURES)&&void 0!==_global$FEATURES2&&_global$FEATURES2.argTypeTargetsV7){var argsByTarget=groupArgsByTarget(Object.assign({args:context.args},context));finalContext=Object.assign({},context,{allArgs:context.args,argsByTarget:argsByTarget,args:argsByTarget[""]||{}})}return decoratedStoryFn(finalContext)},applyLoaders:applyLoaders,playFunction:playFunction}))}function inferArgTypes_typeof(obj){return inferArgTypes_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},inferArgTypes_typeof(obj)}var inferType=function inferType(value,name,visited){var type=inferArgTypes_typeof(value);switch(type){case"boolean":case"string":case"number":case"function":case"symbol":return{name:type}}return value?visited.has(value)?(dist_esm.kg.warn((0,esm.C)(inferArgTypes_templateObject||(inferArgTypes_templateObject=function inferArgTypes_taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}(["\n We've detected a cycle in arg '","'. Args should be JSON-serializable.\n\n Consider using the mapping feature or fully custom args:\n - Mapping: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values\n - Custom args: https://storybook.js.org/docs/react/essentials/controls#fully-custom-args\n "])),name)),{name:"other",value:"cyclic object"}):(visited.add(value),Array.isArray(value)?{name:"array",value:value.length>0?inferType(value[0],name,new Set(visited)):{name:"other",value:"unknown"}}:{name:"object",value:mapValues_default()(value,(function(field){return inferType(field,name,new Set(visited))}))}):{name:"object",value:{}}},inferArgTypes=function inferArgTypes(context){var id=context.id,_context$argTypes=context.argTypes,userArgTypes=void 0===_context$argTypes?{}:_context$argTypes,_context$initialArgs=context.initialArgs,initialArgs=void 0===_context$initialArgs?{}:_context$initialArgs,argTypes=mapValues_default()(initialArgs,(function(arg,key){return{name:key,type:inferType(arg,"".concat(id,".").concat(key),new Set)}})),userArgTypesNames=mapValues_default()(userArgTypes,(function(argType,key){return{name:key}}));return(0,esm_parameters.f)(argTypes,userArgTypesNames,userArgTypes)};inferArgTypes.secondPass=!0;var filterArgTypes=__webpack_require__("./node_modules/@storybook/store/dist/esm/filterArgTypes.js"),inferControls=function inferControls(context){var argTypes=context.argTypes,_context$parameters=context.parameters,__isArgsStory=_context$parameters.__isArgsStory,_context$parameters$c=_context$parameters.controls,_context$parameters$c2=(_context$parameters$c=void 0===_context$parameters$c?{}:_context$parameters$c).include,include=void 0===_context$parameters$c2?null:_context$parameters$c2,_context$parameters$c3=_context$parameters$c.exclude,exclude=void 0===_context$parameters$c3?null:_context$parameters$c3,_context$parameters$c4=_context$parameters$c.matchers,matchers=void 0===_context$parameters$c4?{}:_context$parameters$c4;if(!__isArgsStory)return argTypes;var filteredArgTypes=(0,filterArgTypes.h)(argTypes,include,exclude),withControls=mapValues_default()(filteredArgTypes,(function(argType,name){return(null==argType?void 0:argType.type)&&function inferControl(argType,name,matchers){var type=argType.type,options=argType.options;if(type||options){if(matchers.color&&matchers.color.test(name)){var controlType=argType.type.name;if("string"===controlType)return{control:{type:"color"}};dist_esm.kg.warn('Addon controls: Control of type color only supports string, received "'.concat(controlType,'" instead'))}if(matchers.date&&matchers.date.test(name))return{control:{type:"date"}};switch(type.name){case"array":return{control:{type:"object"}};case"boolean":return{control:{type:"boolean"}};case"string":return{control:{type:"text"}};case"number":return{control:{type:"number"}};case"enum":var value=type.value;return{control:{type:(null==value?void 0:value.length)<=5?"radio":"select"},options:value};case"function":case"symbol":return null;default:return{control:{type:options?"select":"object"}}}}}(argType,name,matchers)}));return(0,esm_parameters.f)(withControls,filteredArgTypes)};inferControls.secondPass=!0;var normalizeProjectAnnotations_excluded=["argTypes","globalTypes","argTypesEnhancers"];function normalizeProjectAnnotations_toConsumableArray(arr){return function normalizeProjectAnnotations_arrayWithoutHoles(arr){if(Array.isArray(arr))return normalizeProjectAnnotations_arrayLikeToArray(arr)}(arr)||function normalizeProjectAnnotations_iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}(arr)||function normalizeProjectAnnotations_unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return normalizeProjectAnnotations_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return normalizeProjectAnnotations_arrayLikeToArray(o,minLen)}(arr)||function normalizeProjectAnnotations_nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function normalizeProjectAnnotations_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}function normalizeProjectAnnotations(_ref){var argTypes=_ref.argTypes,globalTypes=_ref.globalTypes,argTypesEnhancers=_ref.argTypesEnhancers,annotations=normalizeProjectAnnotations_objectWithoutProperties(_ref,normalizeProjectAnnotations_excluded);return Object.assign({},argTypes&&{argTypes:(0,normalizeInputTypes.x)(argTypes)},globalTypes&&{globalTypes:(0,normalizeInputTypes.x)(globalTypes)},{argTypesEnhancers:[].concat(normalizeProjectAnnotations_toConsumableArray(argTypesEnhancers||[]),[inferArgTypes,inferControls])},annotations)}function StoryStore_defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function StoryStore_slicedToArray(arr,i){return function StoryStore_arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function StoryStore_iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function StoryStore_unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return StoryStore_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return StoryStore_arrayLikeToArray(o,minLen)}(arr,i)||function StoryStore_nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function StoryStore_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0&&void 0!==arguments[0]?arguments[0]:{includeDocsOnly:!1};if(!this.cachedCSFFiles)throw new Error("Cannot call extract() unless you call cacheAllCSFFiles() first.");return Object.entries(this.storyIndex.stories).reduce((function(acc,_ref11){var _ref12=StoryStore_slicedToArray(_ref11,2),storyId=_ref12[0],importPath=_ref12[1].importPath,csfFile=_this6.cachedCSFFiles[importPath],story=_this6.storyFromCSFFile({storyId:storyId,csfFile:csfFile});return!options.includeDocsOnly&&story.parameters.docsOnly||(acc[storyId]=Object.entries(story).reduce((function(storyAcc,_ref13){var _ref14=StoryStore_slicedToArray(_ref13,2),key=_ref14[0],value=_ref14[1];return"function"==typeof value?storyAcc:Array.isArray(value)?Object.assign(storyAcc,StoryStore_defineProperty({},key,value.slice().sort())):Object.assign(storyAcc,StoryStore_defineProperty({},key,value))}),{args:story.initialArgs})),acc}),{})}},{key:"getSetStoriesPayload",value:function getSetStoriesPayload(){var stories=this.extract({includeDocsOnly:!0}),kindParameters=Object.values(stories).reduce((function(acc,_ref15){return acc[_ref15.title]={},acc}),{});return{v:2,globals:this.globals.get(),globalParameters:{},kindParameters:kindParameters,stories:stories}}},{key:"raw",value:function raw(){var _this7=this;return Object.values(this.extract()).map((function(_ref16){var id=_ref16.id;return _this7.fromId(id)}))}},{key:"fromId",value:function fromId(storyId){var importPath,_this8=this;if(!this.cachedCSFFiles)throw new Error("Cannot call fromId/raw() unless you call cacheAllCSFFiles() first.");try{importPath=this.storyIndex.storyIdToEntry(storyId).importPath}catch(err){return null}var csfFile=this.cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId:storyId,csfFile:csfFile});return Object.assign({},story,{storyFn:function storyFn(update){var context=Object.assign({},_this8.getStoryContext(story),{viewMode:"story"});return story.unboundStoryFn(Object.assign({},context,update))}})}}]),StoryStore}(),core_events_dist_esm=(__webpack_require__("./node_modules/core-js/modules/es.object.get-prototype-of.js"),__webpack_require__("./node_modules/core-js/modules/es.reflect.construct.js"),__webpack_require__("./node_modules/core-js/modules/es.reflect.get.js"),__webpack_require__("./node_modules/core-js/modules/es.object.get-own-property-descriptor.js"),__webpack_require__("./node_modules/@storybook/core-events/dist/esm/index.js")),addons_dist_esm=__webpack_require__("./node_modules/@storybook/addons/dist/esm/index.js");function StoryRender_asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function StoryRender_asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise((function(resolve,reject){var gen=fn.apply(self,args);function _next(value){StoryRender_asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){StoryRender_asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)}))}}function StoryRender_defineProperties(target,props){for(var i=0;i0&&void 0!==_args9[0]?_args9[0]:{},_ref2$initial=_ref2.initial,initial=void 0!==_ref2$initial&&_ref2$initial,_ref2$forceRemount=_ref2.forceRemount,forceRemount=void 0!==_ref2$forceRemount&&_ref2$forceRemount,this.story){_context9.next=3;break}throw new Error("cannot render when not prepared");case 3:return _this$story=this.story,id=_this$story.id,componentId=_this$story.componentId,title=_this$story.title,name=_this$story.name,applyLoaders=_this$story.applyLoaders,unboundStoryFn=_this$story.unboundStoryFn,playFunction=_this$story.playFunction,forceRemount&&!initial&&(this.cancelRender(),this.abortController=createController()),abortSignal=this.abortController.signal,_context9.prev=6,_context9.next=9,this.runPhase(abortSignal,"loading",StoryRender_asyncToGenerator(regeneratorRuntime.mark((function _callee5(){return regeneratorRuntime.wrap((function _callee5$(_context5){for(;;)switch(_context5.prev=_context5.next){case 0:return _context5.next=2,applyLoaders(Object.assign({},_this2.context(),{viewMode:_this2.viewMode}));case 2:loadedContext=_context5.sent;case 3:case"end":return _context5.stop()}}),_callee5)}))));case 9:if(!abortSignal.aborted){_context9.next=11;break}return _context9.abrupt("return");case 11:return renderStoryContext=Object.assign({},loadedContext,this.context(),{abortSignal:abortSignal,canvasElement:this.canvasElement}),_renderContext=Object.assign({componentId:componentId,title:title,kind:title,id:id,name:name,story:name},this.callbacks,{forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:function storyFn(){return unboundStoryFn(renderStoryContext)},unboundStoryFn:unboundStoryFn}),_context9.next=15,this.runPhase(abortSignal,"rendering",StoryRender_asyncToGenerator(regeneratorRuntime.mark((function _callee6(){return regeneratorRuntime.wrap((function _callee6$(_context6){for(;;)switch(_context6.prev=_context6.next){case 0:return _context6.abrupt("return",_this2.renderToScreen(_renderContext,_this2.canvasElement));case 1:case"end":return _context6.stop()}}),_callee6)}))));case 15:if(this.notYetRendered=!1,!abortSignal.aborted){_context9.next=18;break}return _context9.abrupt("return");case 18:if(!forceRemount||!playFunction){_context9.next=27;break}return this.disableKeyListeners=!0,_context9.next=22,this.runPhase(abortSignal,"playing",StoryRender_asyncToGenerator(regeneratorRuntime.mark((function _callee7(){return regeneratorRuntime.wrap((function _callee7$(_context7){for(;;)switch(_context7.prev=_context7.next){case 0:return _context7.abrupt("return",playFunction(_renderContext.storyContext));case 1:case"end":return _context7.stop()}}),_callee7)}))));case 22:return _context9.next=24,this.runPhase(abortSignal,"played");case 24:if(this.disableKeyListeners=!1,!abortSignal.aborted){_context9.next=27;break}return _context9.abrupt("return");case 27:return _context9.next=29,this.runPhase(abortSignal,"completed",StoryRender_asyncToGenerator(regeneratorRuntime.mark((function _callee8(){return regeneratorRuntime.wrap((function _callee8$(_context8){for(;;)switch(_context8.prev=_context8.next){case 0:return _context8.abrupt("return",_this2.channel.emit(core_events_dist_esm.STORY_RENDERED,id));case 1:case"end":return _context8.stop()}}),_callee8)}))));case 29:_context9.next=34;break;case 31:_context9.prev=31,_context9.t0=_context9.catch(6),this.callbacks.showException(_context9.t0);case 34:case"end":return _context9.stop()}}),_callee9,this,[[6,31]])}))),function render(){return _render.apply(this,arguments)})},{key:"rerender",value:(_rerender=StoryRender_asyncToGenerator(regeneratorRuntime.mark((function _callee10(){return regeneratorRuntime.wrap((function _callee10$(_context10){for(;;)switch(_context10.prev=_context10.next){case 0:return _context10.abrupt("return",this.render());case 1:case"end":return _context10.stop()}}),_callee10,this)}))),function rerender(){return _rerender.apply(this,arguments)})},{key:"remount",value:(_remount=StoryRender_asyncToGenerator(regeneratorRuntime.mark((function _callee11(){return regeneratorRuntime.wrap((function _callee11$(_context11){for(;;)switch(_context11.prev=_context11.next){case 0:return _context11.abrupt("return",this.render({forceRemount:!0}));case 1:case"end":return _context11.stop()}}),_callee11,this)}))),function remount(){return _remount.apply(this,arguments)})},{key:"cancelRender",value:function cancelRender(){this.abortController.abort()}},{key:"teardown",value:(_teardown=StoryRender_asyncToGenerator(regeneratorRuntime.mark((function _callee12(){var i,_args12=arguments;return regeneratorRuntime.wrap((function _callee12$(_context12){for(;;)switch(_context12.prev=_context12.next){case 0:_args12.length>0&&void 0!==_args12[0]&&_args12[0],this.cancelRender(),this.story&&this.store.cleanupStory(this.story),i=0;case 4:if(!(i<3)){_context12.next=12;break}if(this.isPending()){_context12.next=7;break}return _context12.abrupt("return");case 7:return _context12.next=9,new Promise((function(resolve){return setTimeout(resolve,0)}));case 9:i+=1,_context12.next=4;break;case 12:return window_default().window.location.reload(),_context12.next=15,new Promise((function(){}));case 15:case"end":return _context12.stop()}}),_callee12,this)}))),function teardown(){return _teardown.apply(this,arguments)})}]),StoryRender}();function Preview_toConsumableArray(arr){return function Preview_arrayWithoutHoles(arr){if(Array.isArray(arr))return Preview_arrayLikeToArray(arr)}(arr)||function Preview_iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}(arr)||function Preview_unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return Preview_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Preview_arrayLikeToArray(o,minLen)}(arr)||function Preview_nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Preview_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i1&&void 0!==_args12[1]?_args12[1]:{},viewModeChanged=_ref9.viewModeChanged,this.storyRenders=this.storyRenders.filter((function(r){return r!==render})),_context12.next=4,null==render?void 0:render.teardown({viewModeChanged:viewModeChanged});case 4:case"end":return _context12.stop()}}),_callee12,this)}))),function teardownRender(_x7){return _teardownRender.apply(this,arguments)})},{key:"extract",value:(_extract=Preview_asyncToGenerator(regeneratorRuntime.mark((function _callee13(options){var _global$FEATURES4;return regeneratorRuntime.wrap((function _callee13$(_context13){for(;;)switch(_context13.prev=_context13.next){case 0:if(!this.previewEntryError){_context13.next=2;break}throw this.previewEntryError;case 2:if(this.storyStore.projectAnnotations){_context13.next=4;break}throw new Error((0,esm.C)(Preview_templateObject2||(Preview_templateObject2=Preview_taggedTemplateLiteral(["Failed to initialize Storybook.\n \n Do you have an error in your `preview.js`? Check your Storybook's browser console for errors."],["Failed to initialize Storybook.\n \n Do you have an error in your \\`preview.js\\`? Check your Storybook's browser console for errors."]))));case 4:if(null===(_global$FEATURES4=window_default().FEATURES)||void 0===_global$FEATURES4||!_global$FEATURES4.storyStoreV7){_context13.next=7;break}return _context13.next=7,this.storyStore.cacheAllCSFFiles();case 7:return _context13.abrupt("return",this.storyStore.extract(options));case 8:case"end":return _context13.stop()}}),_callee13,this)}))),function extract(_x8){return _extract.apply(this,arguments)})},{key:"inlineStoryCallbacks",value:function inlineStoryCallbacks(storyId){return{showMain:function showMain(){},showError:function showError(err){return dist_esm.kg.error("Error rendering docs story (".concat(storyId,")"),err)},showException:function showException(err){return dist_esm.kg.error("Error rendering docs story (".concat(storyId,")"),err)}}}},{key:"renderPreviewEntryError",value:function renderPreviewEntryError(reason,err){this.previewEntryError=err,dist_esm.kg.error(reason),dist_esm.kg.error(err),this.channel.emit(core_events_dist_esm.CONFIG_ERROR,err)}}]),Preview}(),lib=(__webpack_require__("./node_modules/core-js/modules/es.string.match.js"),__webpack_require__("./node_modules/core-js/modules/es.string.search.js"),__webpack_require__("./node_modules/qs/lib/index.js")),lib_default=__webpack_require__.n(lib);__webpack_require__("./node_modules/core-js/modules/es.regexp.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.string.ends-with.js"),__webpack_require__("./node_modules/core-js/modules/es.string.split.js"),__webpack_require__("./node_modules/core-js/modules/es.string.replace.js");function parseArgsParam_slicedToArray(arr,i){return function parseArgsParam_arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function parseArgsParam_iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function parseArgsParam_unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return parseArgsParam_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return parseArgsParam_arrayLikeToArray(o,minLen)}(arr,i)||function parseArgsParam_nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function parseArgsParam_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0&&void 0!==arguments[0]?arguments[0]:"",value=arguments.length>1?arguments[1]:void 0;return null!==key&&(!(""===key||!VALIDATION_REGEXP.test(key))&&(null==value||(value instanceof Date||("number"==typeof value||"boolean"==typeof value||("string"==typeof value?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every((function(v){return validateArgs(key,v)})):!!isPlainObject_default()(value)&&Object.entries(value).every((function(_ref){var _ref2=parseArgsParam_slicedToArray(_ref,2),k=_ref2[0],v=_ref2[1];return validateArgs(k,v)})))))))},QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder:function(_decoder){function decoder(_x,_x2,_x3,_x4){return _decoder.apply(this,arguments)}return decoder.toString=function(){return _decoder.toString()},decoder}((function(str,defaultDecoder,charset,type){if("value"===type&&str.startsWith("!")){if("!undefined"===str)return;if("!null"===str)return null;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return"#".concat(str.slice(5,-1));var color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?"".concat(color[1],"(").concat(color[2],", ").concat(color[3],", ").concat(color[4],", ").concat(color[5],")"):str.startsWith("!hsla")?"".concat(color[1],"(").concat(color[2],", ").concat(color[3],"%, ").concat(color[4],"%, ").concat(color[5],")"):str.startsWith("!rgb")?"".concat(color[1],"(").concat(color[2],", ").concat(color[3],", ").concat(color[4],")"):"".concat(color[1],"(").concat(color[2],", ").concat(color[3],"%, ").concat(color[4],"%)")}return"value"===type&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}))},parseArgsParam=function parseArgsParam(argsString){var parts=argsString.split(";").map((function(part){return part.replace("=","~").replace(":","=")}));return Object.entries(lib_default().parse(parts.join(";"),QS_OPTIONS)).reduce((function(acc,_ref3){var _ref4=parseArgsParam_slicedToArray(_ref3,2),key=_ref4[0],value=_ref4[1];return validateArgs(key,value)?Object.assign(acc,function parseArgsParam_defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}({},key,value)):(dist_esm.IH.warn((0,esm.C)(parseArgsParam_templateObject||(parseArgsParam_templateObject=function parseArgsParam_taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}(["\n Omitted potentially unsafe URL args.\n\n More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url\n "])))),acc)}),{})},UrlStore_excluded=["path","selectedKind","selectedStory"];function UrlStore_defineProperties(target,props){for(var i=0;i=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}var UrlStore_history=window_default().history,UrlStore_document=window_default().document;var WebView_templateObject,getQueryString=function getQueryString(_ref){var selection=_ref.selection,extraParams=_ref.extraParams,_document$location$se=UrlStore_document.location.search,search=void 0===_document$location$se?"":_document$location$se,_qs$parse=lib_default().parse(search,{ignoreQueryPrefix:!0}),rest=(_qs$parse.path,_qs$parse.selectedKind,_qs$parse.selectedStory,UrlStore_objectWithoutProperties(_qs$parse,UrlStore_excluded));return lib_default().stringify(Object.assign({},rest,extraParams,selection&&{id:selection.storyId,viewMode:selection.viewMode}),{encode:!1,addQueryPrefix:!0})},getFirstString=function getFirstString(v){return"string"==typeof v?v:Array.isArray(v)?getFirstString(v[0]):function isObject(val){return null!=val&&"object"===UrlStore_typeof(val)&&!1===Array.isArray(val)}(v)?getFirstString(Object.values(v)):void 0},deprecatedLegacyQuery=browser_default()((function(){return 0}),"URL formats with `selectedKind` and `selectedName` query parameters are deprecated.\nUse `id=$storyId` instead.\nSee https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#new-url-structure"),getSelectionSpecifierFromPath=function getSelectionSpecifierFromPath(){var query=lib_default().parse(UrlStore_document.location.search,{ignoreQueryPrefix:!0}),args="string"==typeof query.args?parseArgsParam(query.args):void 0,globals="string"==typeof query.globals?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);"string"==typeof viewMode&&viewMode.match(/docs|story/)||(viewMode="story");var path=getFirstString(query.path),storyId=path?function pathToId(path){var match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error("Invalid path '".concat(path,"', must start with '/story/'"));return match[1]}(path):getFirstString(query.id);if(storyId)return{storySpecifier:storyId,args:args,globals:globals,viewMode:viewMode};var title=getFirstString(query.selectedKind),name=getFirstString(query.selectedStory);return title&&name?(deprecatedLegacyQuery(),{storySpecifier:{title:title,name:name},args:args,globals:globals,viewMode:viewMode}):null},UrlStore=function(){function UrlStore(){!function UrlStore_classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}(this,UrlStore),this.selectionSpecifier=void 0,this.selection=void 0,this.selectionSpecifier=getSelectionSpecifierFromPath()}return function UrlStore_createClass(Constructor,protoProps,staticProps){return protoProps&&UrlStore_defineProperties(Constructor.prototype,protoProps),staticProps&&UrlStore_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}(UrlStore,[{key:"setSelection",value:function setSelection(selection){this.selection=selection,function setPath(selection){if(selection){var query=getQueryString({selection:selection}),_document$location$ha=UrlStore_document.location.hash,hash=void 0===_document$location$ha?"":_document$location$ha;UrlStore_document.title=selection.storyId,UrlStore_history.replaceState({},"","".concat(UrlStore_document.location.pathname).concat(query).concat(hash))}}(this.selection)}},{key:"setQueryParams",value:function setQueryParams(queryParams){var query=getQueryString({extraParams:queryParams}),_document$location$ha2=UrlStore_document.location.hash,hash=void 0===_document$location$ha2?"":_document$location$ha2;UrlStore_history.replaceState({},"","".concat(UrlStore_document.location.pathname).concat(query).concat(hash))}}]),UrlStore}(),ansi_to_html=__webpack_require__("./node_modules/ansi-to-html/lib/ansi_to_html.js"),ansi_to_html_default=__webpack_require__.n(ansi_to_html);function WebView_slicedToArray(arr,i){return function WebView_arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function WebView_iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function WebView_unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return WebView_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return WebView_arrayLikeToArray(o,minLen)}(arr,i)||function WebView_nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function WebView_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0&&void 0!==arguments[0]?arguments[0]:"padded";if("none"===layout)return WebView_document.body.classList.remove(this.currentLayoutClass),void(this.currentLayoutClass=null);this.checkIfLayoutExists(layout);var layoutClass=layoutClassMap[layout];WebView_document.body.classList.remove(this.currentLayoutClass),WebView_document.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass}},{key:"checkIfLayoutExists",value:function checkIfLayoutExists(layout){layoutClassMap[layout]||dist_esm.kg.warn((0,esm.C)(WebView_templateObject||(WebView_templateObject=function WebView_taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}(["The desired layout: "," is not a valid option.\n The possible options are: ",", none."])),layout,Object.keys(layoutClassMap).join(", ")))}},{key:"showMode",value:function showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach((function(otherMode){otherMode===mode?WebView_document.body.classList.add(classes[otherMode]):WebView_document.body.classList.remove(classes[otherMode])}))}},{key:"showErrorDisplay",value:function showErrorDisplay(_ref){var _ref$message=_ref.message,message=void 0===_ref$message?"":_ref$message,_ref$stack=_ref.stack,header=message,detail=void 0===_ref$stack?"":_ref$stack,parts=message.split("\n");parts.length>1&&(header=WebView_slicedToArray(parts,1)[0],detail=parts.slice(1).join("\n"));WebView_document.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),WebView_document.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode(Mode.ERROR)}},{key:"showNoPreview",value:function showNoPreview(){var _this$storyRoot,_this$docsRoot;this.testing||(this.showMode(Mode.NOPREVIEW),null===(_this$storyRoot=this.storyRoot())||void 0===_this$storyRoot||_this$storyRoot.setAttribute("hidden","true"),null===(_this$docsRoot=this.docsRoot())||void 0===_this$docsRoot||_this$docsRoot.setAttribute("hidden","true"))}},{key:"showPreparingStory",value:function showPreparingStory(){var _this=this,_ref2=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},_ref2$immediate=_ref2.immediate,immediate=void 0!==_ref2$immediate&&_ref2$immediate;clearTimeout(this.preparingTimeout),immediate?this.showMode(Mode.PREPARING_STORY):this.preparingTimeout=setTimeout((function(){return _this.showMode(Mode.PREPARING_STORY)}),100)}},{key:"showPreparingDocs",value:function showPreparingDocs(){var _this2=this;clearTimeout(this.preparingTimeout),this.preparingTimeout=setTimeout((function(){return _this2.showMode(Mode.PREPARING_DOCS)}),100)}},{key:"showMain",value:function showMain(){this.showMode(Mode.MAIN)}},{key:"showDocs",value:function showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}},{key:"showStory",value:function showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}},{key:"showStoryDuringRender",value:function showStoryDuringRender(){WebView_document.body.classList.add(classes.MAIN)}}]),WebView}();function DocsRender_asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function DocsRender_asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise((function(resolve,reject){var gen=fn.apply(self,args);function _next(value){DocsRender_asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){DocsRender_asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)}))}}function DocsRender_defineProperties(target,props){for(var i=0;i0&&void 0!==_args4[0]?_args4[0]:{}).viewModeChanged&&this.canvasElement){_context4.next=3;break}return _context4.abrupt("return");case 3:return _context4.next=5,__webpack_require__.e(701).then(__webpack_require__.bind(__webpack_require__,"./node_modules/@storybook/preview-web/dist/esm/renderDocs.js"));case 5:_context4.sent.unmountDocs(this.canvasElement);case 7:case"end":return _context4.stop()}}),_callee4,this)}))),function teardown(){return _teardown.apply(this,arguments)})}],[{key:"fromStoryRender",value:function fromStoryRender(storyRender){return new DocsRender(storyRender.channel,storyRender.store,storyRender.id,storyRender.story)}}]),DocsRender}();function PreviewWeb_typeof(obj){return PreviewWeb_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},PreviewWeb_typeof(obj)}function PreviewWeb_asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function PreviewWeb_asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise((function(resolve,reject){var gen=fn.apply(self,args);function _next(value){PreviewWeb_asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){PreviewWeb_asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)}))}}function PreviewWeb_taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}function PreviewWeb_defineProperties(target,props){for(var i=0;i0&&void 0!==_args8[0]?_args8[0]:{},persistedArgs=_ref6.persistedArgs,selection=this.urlStore.selection){_context8.next=4;break}throw new Error("Cannot render story as no selection was made");case 4:if(storyId=selection.storyId,storyIdChanged=(null===(_this$currentSelectio=this.currentSelection)||void 0===_this$currentSelectio?void 0:_this$currentSelectio.storyId)!==storyId,viewModeChanged=(null===(_this$currentSelectio2=this.currentSelection)||void 0===_this$currentSelectio2?void 0:_this$currentSelectio2.viewMode)!==selection.viewMode,"story"===selection.viewMode?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs(),lastSelection=this.currentSelection,lastRender=this.currentRender,null===(_lastRender=lastRender)||void 0===_lastRender||!_lastRender.isPreparing()){_context8.next=14;break}return _context8.next=13,this.teardownRender(lastRender);case 13:lastRender=null;case 14:return storyRender=new StoryRender(this.channel,this.storyStore,(function(){return _this5.view.showStoryDuringRender(),_this5.renderToDOM.apply(_this5,arguments)}),this.mainStoryCallbacks(storyId),storyId,"story"),this.currentSelection=selection,this.currentRender=storyRender,_context8.prev=17,_context8.next=20,storyRender.prepare();case 20:_context8.next=29;break;case 22:if(_context8.prev=22,_context8.t0=_context8.catch(17),_context8.t0===PREPARE_ABORTED){_context8.next=28;break}return _context8.next=27,this.teardownRender(lastRender);case 27:this.renderStoryLoadingException(storyId,_context8.t0);case 28:return _context8.abrupt("return");case 29:if(implementationChanged=!storyIdChanged&&!storyRender.isEqual(lastRender),persistedArgs&&this.storyStore.args.updateFromPersisted(storyRender.story,persistedArgs),_storyRender$context=storyRender.context(),parameters=_storyRender$context.parameters,initialArgs=_storyRender$context.initialArgs,argTypes=_storyRender$context.argTypes,args=_storyRender$context.args,!lastRender||storyIdChanged||implementationChanged||viewModeChanged){_context8.next=37;break}return this.currentRender=lastRender,this.channel.emit(core_events_dist_esm.STORY_UNCHANGED,storyId),this.view.showMain(),_context8.abrupt("return");case 37:return _context8.next=39,this.teardownRender(lastRender,{viewModeChanged:viewModeChanged});case 39:lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(core_events_dist_esm.STORY_CHANGED,storyId),null!==(_global$FEATURES3=window_default().FEATURES)&&void 0!==_global$FEATURES3&&_global$FEATURES3.storyStoreV7&&this.channel.emit(core_events_dist_esm.STORY_PREPARED,{id:storyId,parameters:parameters,initialArgs:initialArgs,argTypes:argTypes,args:args}),(implementationChanged||persistedArgs)&&this.channel.emit(core_events_dist_esm.STORY_ARGS_UPDATED,{storyId:storyId,args:args}),"docs"===selection.viewMode||parameters.docsOnly?(this.currentRender=DocsRender.fromStoryRender(storyRender),this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))):(this.storyRenders.push(storyRender),this.currentRender.renderToElement(this.view.prepareForStory(storyRender.story)));case 43:case"end":return _context8.stop()}}),_callee8,this,[[17,22]])}))),function renderSelection(){return _renderSelection.apply(this,arguments)})},{key:"renderStoryToElement",value:function renderStoryToElement(story,element){var _this6=this,render=new StoryRender(this.channel,this.storyStore,this.renderToDOM,this.inlineStoryCallbacks(story.id),story.id,"docs",story);return render.renderToElement(element),this.storyRenders.push(render),PreviewWeb_asyncToGenerator(regeneratorRuntime.mark((function _callee9(){return regeneratorRuntime.wrap((function _callee9$(_context9){for(;;)switch(_context9.prev=_context9.next){case 0:return _context9.next=2,_this6.teardownRender(render);case 2:case"end":return _context9.stop()}}),_callee9)})))}},{key:"teardownRender",value:(_teardownRender=PreviewWeb_asyncToGenerator(regeneratorRuntime.mark((function _callee10(render){var _ref8,viewModeChanged,_args10=arguments;return regeneratorRuntime.wrap((function _callee10$(_context10){for(;;)switch(_context10.prev=_context10.next){case 0:return _ref8=_args10.length>1&&void 0!==_args10[1]?_args10[1]:{},viewModeChanged=_ref8.viewModeChanged,this.storyRenders=this.storyRenders.filter((function(r){return r!==render})),_context10.next=4,null==render?void 0:render.teardown({viewModeChanged:viewModeChanged});case 4:case"end":return _context10.stop()}}),_callee10,this)}))),function teardownRender(_x6){return _teardownRender.apply(this,arguments)})},{key:"extract",value:(_extract=PreviewWeb_asyncToGenerator(regeneratorRuntime.mark((function _callee11(options){var _global$FEATURES4;return regeneratorRuntime.wrap((function _callee11$(_context11){for(;;)switch(_context11.prev=_context11.next){case 0:if(!this.previewEntryError){_context11.next=2;break}throw this.previewEntryError;case 2:if(this.storyStore.projectAnnotations){_context11.next=4;break}throw new Error((0,esm.C)(_templateObject4||(_templateObject4=PreviewWeb_taggedTemplateLiteral(["Failed to initialize Storybook.\n \n Do you have an error in your `preview.js`? Check your Storybook's browser console for errors."],["Failed to initialize Storybook.\n \n Do you have an error in your \\`preview.js\\`? Check your Storybook's browser console for errors."]))));case 4:if(null===(_global$FEATURES4=window_default().FEATURES)||void 0===_global$FEATURES4||!_global$FEATURES4.storyStoreV7){_context11.next=7;break}return _context11.next=7,this.storyStore.cacheAllCSFFiles();case 7:return _context11.abrupt("return",this.storyStore.extract(options));case 8:case"end":return _context11.stop()}}),_callee11,this)}))),function extract(_x7){return _extract.apply(this,arguments)})},{key:"mainStoryCallbacks",value:function mainStoryCallbacks(storyId){var _this7=this;return{showMain:function showMain(){return _this7.view.showMain()},showError:function showError(err){return _this7.renderError(storyId,err)},showException:function showException(err){return _this7.renderException(storyId,err)}}}},{key:"inlineStoryCallbacks",value:function inlineStoryCallbacks(storyId){return{showMain:function showMain(){},showError:function showError(err){return dist_esm.kg.error("Error rendering docs story (".concat(storyId,")"),err)},showException:function showException(err){return dist_esm.kg.error("Error rendering docs story (".concat(storyId,")"),err)}}}},{key:"renderPreviewEntryError",value:function renderPreviewEntryError(reason,err){_get(_getPrototypeOf(PreviewWeb.prototype),"renderPreviewEntryError",this).call(this,reason,err),this.view.showErrorDisplay(err)}},{key:"renderMissingStory",value:function renderMissingStory(){this.view.showNoPreview(),this.channel.emit(core_events_dist_esm.STORY_MISSING)}},{key:"renderStoryLoadingException",value:function renderStoryLoadingException(storySpecifier,err){dist_esm.kg.error("Unable to load story '".concat(storySpecifier,"':")),dist_esm.kg.error(err),this.view.showErrorDisplay(err),this.channel.emit(core_events_dist_esm.STORY_MISSING,storySpecifier)}},{key:"renderException",value:function renderException(storyId,err){this.channel.emit(core_events_dist_esm.STORY_THREW_EXCEPTION,err),this.channel.emit(core_events_dist_esm.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId:storyId}),err!==core_events_dist_esm.IGNORED_EXCEPTION&&(this.view.showErrorDisplay(err),dist_esm.kg.error("Error rendering story '".concat(storyId,"':")),dist_esm.kg.error(err))}},{key:"renderError",value:function renderError(storyId,_ref9){var title=_ref9.title,description=_ref9.description;dist_esm.kg.error("Error rendering story ".concat(title,": ").concat(description)),this.channel.emit(core_events_dist_esm.STORY_ERRORED,{title:title,description:description}),this.channel.emit(core_events_dist_esm.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId:storyId}),this.view.showErrorDisplay({message:title,stack:description})}}]),PreviewWeb}(Preview),channels_dist_esm=(__webpack_require__("./node_modules/core-js/modules/es.object.from-entries.js"),__webpack_require__("./node_modules/core-js/modules/es.number.is-integer.js"),__webpack_require__("./node_modules/core-js/modules/web.url.js"),__webpack_require__("./node_modules/core-js/modules/web.url-search-params.js"),__webpack_require__("./node_modules/@storybook/channels/dist/esm/index.js")),telejson_dist_esm=__webpack_require__("./node_modules/telejson/dist/esm/index.js");function esm_toConsumableArray(arr){return function esm_arrayWithoutHoles(arr){if(Array.isArray(arr))return esm_arrayLikeToArray(arr)}(arr)||esm_iterableToArray(arr)||esm_unsupportedIterableToArray(arr)||function esm_nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function esm_iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}function esm_slicedToArray(arr,i){return esm_arrayWithHoles(arr)||function esm_iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||esm_unsupportedIterableToArray(arr,i)||esm_nonIterableRest()}function esm_nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function esm_unsupportedIterableToArray(o,minLen){if(o){if("string"==typeof o)return esm_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?esm_arrayLikeToArray(o,minLen):void 0}}function esm_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i manager ':' preview ',eventString=Object.values(core_events_dist_esm).includes(event.type)?''.concat(event.type,""):''.concat(event.type,"");if(refId&&(event.refId=refId),event.source="preview"===this.config.page?rawEvent.origin:getEventSourceUrl(rawEvent),!event.source)return void dist_esm.IC.error("".concat(pageString," received ").concat(eventString," but was unable to determine the source of the event"));var message="".concat(pageString," received ").concat(eventString," (").concat(data.length,")");dist_esm.IC.debug.apply(dist_esm.IC,[esm_location.origin!==event.source?message:"".concat(message,' (on ').concat(esm_location.origin," from ").concat(event.source,")")].concat(esm_toConsumableArray(event.args))),this.handler(event)}}catch(error){dist_esm.kg.error(error)}}}]),PostmsgTransport}(),getEventSourceUrl=function getEventSourceUrl(event){var _frames$filter=esm_toConsumableArray(esm_document.querySelectorAll("iframe[data-is-storybook]")).filter((function(element){try{return element.contentWindow===event.source}catch(err){}var origin,src=element.getAttribute("src");try{origin=new URL(src,esm_document.location).origin}catch(err){return!1}return origin===event.origin})),_frames$filter2=function _toArray(arr){return esm_arrayWithHoles(arr)||esm_iterableToArray(arr)||esm_unsupportedIterableToArray(arr)||esm_nonIterableRest()}(_frames$filter),frame=_frames$filter2[0],remainder=_frames$filter2.slice(1);if(frame&&0===remainder.length){var src=frame.getAttribute("src"),_URL2=new URL(src,esm_document.location),protocol=_URL2.protocol,host=_URL2.host,pathname=_URL2.pathname;return"".concat(protocol,"//").concat(host).concat(pathname)}return remainder.length>0&&dist_esm.kg.error("found multiple candidates for event source"),null};function createChannel(_ref5){var page=_ref5.page,transport=new PostmsgTransport({page:page});return new channels_dist_esm.Z({transport:transport})}__webpack_require__("./node_modules/core-js/modules/es.map.js");function executeLoadable_slicedToArray(arr,i){return function executeLoadable_arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function executeLoadable_iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function executeLoadable_unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return executeLoadable_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return executeLoadable_arrayLikeToArray(o,minLen)}(arr,i)||function executeLoadable_nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function executeLoadable_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i1&&void 0!==arguments[1]?arguments[1]:{},decorateStory=_ref.decorateStory,render=_ref.render;if(start_globalWindow&&(start_globalWindow.IS_STORYBOOK=!0),null!=FEATURES&&FEATURES.storyStoreV7)return{forceReRender:removedApi("forceReRender"),getStorybook:removedApi("getStorybook"),configure:removedApi("configure"),clientApi:{addDecorator:removedApi("clientApi.addDecorator"),addParameters:removedApi("clientApi.addParameters"),clearDecorators:removedApi("clientApi.clearDecorators"),addLoader:removedApi("clientApi.addLoader"),setAddon:removedApi("clientApi.setAddon"),getStorybook:removedApi("clientApi.getStorybook"),storiesOf:removedApi("clientApi.storiesOf"),raw:removedApi("raw")}};var channel=createChannel({page:"preview"});addons_dist_esm.KP.setChannel(channel);var clientApi=new ClientApi.ti,preview=new PreviewWeb,initialized=!1,importFn=function importFn(path){return clientApi.importFn(path)};function onStoriesChanged(){var storyIndex=clientApi.getStoryIndex();preview.onStoriesChanged({storyIndex:storyIndex,importFn:importFn})}return clientApi.onImportFnChanged=onStoriesChanged,clientApi.storyStore=preview.storyStore,start_globalWindow&&(start_globalWindow.__STORYBOOK_CLIENT_API__=clientApi,start_globalWindow.__STORYBOOK_ADDONS_CHANNEL__=channel,start_globalWindow.__STORYBOOK_PREVIEW__=preview,start_globalWindow.__STORYBOOK_STORY_STORE__=preview.storyStore),{forceReRender:function forceReRender(){return channel.emit(core_events_dist_esm.default.FORCE_RE_RENDER)},getStorybook:function getStorybook(){return[]},raw:function raw(){},clientApi:clientApi,configure:function configure(framework,loadable,m){var showDeprecationWarning=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];showDeprecationWarning&&configureDeprecationWarning(),clientApi.addParameters({framework:framework});var getProjectAnnotations=function getProjectAnnotations(){var _executeLoadableForCh=executeLoadableForChanges(loadable,m),added=_executeLoadableForCh.added,removed=_executeLoadableForCh.removed;return Array.from(added.entries()).forEach((function(_ref2){var _ref3=start_slicedToArray(_ref2,2),fileName=_ref3[0],fileExports=_ref3[1];return clientApi.facade.addStoriesFromExports(fileName,fileExports)})),Array.from(removed.entries()).forEach((function(_ref4){var fileName=start_slicedToArray(_ref4,1)[0];return clientApi.facade.clearFilenameExports(fileName)})),Object.assign({render:render},clientApi.facade.projectAnnotations,{renderToDOM:renderToDOM,applyDecorators:decorateStory})};initialized?(getProjectAnnotations(),onStoriesChanged()):(preview.initialize({getStoryIndex:function getStoryIndex(){return clientApi.getStoryIndex()},importFn:importFn,getProjectAnnotations:getProjectAnnotations}),initialized=!0)}}}dist.toId,ClientApi.ti;var globals_globalWindow=window_default().window;globals_globalWindow&&(globals_globalWindow.STORYBOOK_ENV="react");var render=__webpack_require__("./node_modules/@storybook/react/dist/esm/client/preview/render.js"),framework="react",api=start(render.A,{render:render.s}),storiesOf=function storiesOf(kind,m){return api.clientApi.storiesOf(kind,m).addParameters({framework:framework})},configure=function configure(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return api.configure.apply(api,[framework].concat(args))},addDecorator=api.clientApi.addDecorator,addParameters=api.clientApi.addParameters,setAddon=(api.clientApi.clearDecorators,api.clientApi.setAddon),forceReRender=api.forceReRender,getStorybook=api.clientApi.getStorybook,raw=api.clientApi.raw;function composeConfigs_toConsumableArray(arr){return function composeConfigs_arrayWithoutHoles(arr){if(Array.isArray(arr))return composeConfigs_arrayLikeToArray(arr)}(arr)||function composeConfigs_iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}(arr)||function composeConfigs_unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return composeConfigs_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return composeConfigs_arrayLikeToArray(o,minLen)}(arr)||function composeConfigs_nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function composeConfigs_arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}var GLOBAL_STORYBOOK_PROJECT_ANNOTATIONS={};function setProjectAnnotations(projectAnnotations){GLOBAL_STORYBOOK_PROJECT_ANNOTATIONS=Array.isArray(projectAnnotations)?function composeConfigs(moduleExportList){var allArgTypeEnhancers=getArrayField(moduleExportList,"argTypesEnhancers");return{parameters:esm_parameters.f.apply(void 0,composeConfigs_toConsumableArray(getField(moduleExportList,"parameters"))),decorators:getArrayField(moduleExportList,"decorators"),args:getObjectField(moduleExportList,"args"),argsEnhancers:getArrayField(moduleExportList,"argsEnhancers"),argTypes:getObjectField(moduleExportList,"argTypes"),argTypesEnhancers:[].concat(composeConfigs_toConsumableArray(allArgTypeEnhancers.filter((function(e){return!e.secondPass}))),composeConfigs_toConsumableArray(allArgTypeEnhancers.filter((function(e){return e.secondPass})))),globals:getObjectField(moduleExportList,"globals"),globalTypes:getObjectField(moduleExportList,"globalTypes"),loaders:getArrayField(moduleExportList,"loaders"),render:getSingletonField(moduleExportList,"render"),renderToDOM:getSingletonField(moduleExportList,"renderToDOM"),applyDecorators:getSingletonField(moduleExportList,"applyDecorators")}}(projectAnnotations):projectAnnotations}function composeStories(storiesImport,globalConfig,composeStoryFn){var meta=storiesImport.default,stories=(storiesImport.__esModule,storiesImport.__namedExportsOrder,testing_utils_objectWithoutProperties(storiesImport,testing_utils_excluded));return Object.entries(stories).reduce((function(storiesMap,_ref){var _ref2=testing_utils_slicedToArray(_ref,2),exportsName=_ref2[0],story=_ref2[1];return(0,dist.isExportStory)(exportsName,meta)?Object.assign(storiesMap,function testing_utils_defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}({},exportsName,composeStoryFn(story,meta,globalConfig,exportsName))):storiesMap}),{})}function testing_setProjectAnnotations(projectAnnotations){setProjectAnnotations(projectAnnotations)}function setGlobalConfig(projectAnnotations){dist_esm.IH.warn("setGlobalConfig is deprecated. Use setProjectAnnotations instead."),testing_setProjectAnnotations(projectAnnotations)}var defaultProjectAnnotations={render:render.s};function testing_composeStory(story,componentAnnotations,projectAnnotations,exportsName){return function composeStory(storyAnnotations,componentAnnotations){var _componentAnnotations,_storyAnnotations$sto,projectAnnotations=arguments.length>2&&void 0!==arguments[2]?arguments[2]:GLOBAL_STORYBOOK_PROJECT_ANNOTATIONS,defaultConfig=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},exportsName=arguments.length>4?arguments[4]:void 0;if(void 0===storyAnnotations)throw new Error("Expected a story but received undefined.");componentAnnotations.title=null!==(_componentAnnotations=componentAnnotations.title)&&void 0!==_componentAnnotations?_componentAnnotations:"ComposedStory";var normalizedComponentAnnotations=normalizeComponentAnnotations(componentAnnotations),storyName=exportsName||storyAnnotations.storyName||(null===(_storyAnnotations$sto=storyAnnotations.story)||void 0===_storyAnnotations$sto?void 0:_storyAnnotations$sto.name)||storyAnnotations.name,normalizedStory=normalizeStory(storyName,storyAnnotations,normalizedComponentAnnotations),normalizedProjectAnnotations=normalizeProjectAnnotations(Object.assign({},projectAnnotations,defaultConfig)),story=prepareStory(normalizedStory,normalizedComponentAnnotations,normalizedProjectAnnotations),defaultGlobals=getValuesFromArgTypes(projectAnnotations.globalTypes),composedStory=function composedStory(extraArgs){var context=Object.assign({},story,{hooks:new hooks.c8,globals:defaultGlobals,args:Object.assign({},story.initialArgs,extraArgs)});return story.unboundStoryFn(context)};return composedStory.storyName=storyName,composedStory.args=story.initialArgs,composedStory.play=story.playFunction,composedStory.parameters=story.parameters,composedStory}(story,componentAnnotations,projectAnnotations,defaultProjectAnnotations,exportsName)}function testing_composeStories(csfExports,projectAnnotations){return composeStories(csfExports,projectAnnotations,testing_composeStory)}(module=__webpack_require__.hmd(module))&&module.hot},"./node_modules/@storybook/react/dist/esm/client/preview/config-generated-config-entry.js":function(__unused_webpack_module,__unused_webpack___webpack_exports__,__webpack_require__){"use strict";var config_namespaceObject={};__webpack_require__.r(config_namespaceObject),__webpack_require__.d(config_namespaceObject,{parameters:function(){return parameters},render:function(){return render.s},renderToDOM:function(){return render.A}});var ClientApi=__webpack_require__("./node_modules/@storybook/client-api/dist/esm/ClientApi.js"),render=__webpack_require__("./node_modules/@storybook/react/dist/esm/client/preview/render.js"),parameters={framework:"react"};function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.keys(config_namespaceObject).forEach((function(key){var value=config_namespaceObject[key];switch(key){case"args":return(0,ClientApi.uc)(value);case"argTypes":return(0,ClientApi.v9)(value);case"decorators":return value.forEach((function(decorator){return(0,ClientApi.$9)(decorator,!1)}));case"loaders":return value.forEach((function(loader){return(0,ClientApi.HZ)(loader,!1)}));case"parameters":return(0,ClientApi.h1)(function _objectSpread(target){for(var i=1;i...",!0,!0),tokContexts={tc_oTag:tc_oTag,tc_cTag:tc_cTag,tc_expr:tc_expr},tokTypes={jsxName:new TokenType("jsxName"),jsxText:new TokenType("jsxText",{beforeExpr:!0}),jsxTagStart:new TokenType("jsxTagStart",{startsExpr:!0}),jsxTagEnd:new TokenType("jsxTagEnd")};tokTypes.jsxTagStart.updateContext=function(){this.context.push(tc_expr),this.context.push(tc_oTag),this.exprAllowed=!1},tokTypes.jsxTagEnd.updateContext=function(prevType){let out=this.context.pop();out===tc_oTag&&prevType===tt.slash||out===tc_cTag?(this.context.pop(),this.exprAllowed=this.curContext()===tc_expr):this.exprAllowed=!0},acornJsx={tokContexts:tokContexts,tokTypes:tokTypes},acornJsxMap.set(acorn,acornJsx)}return acornJsx}function getQualifiedJSXName(object){return object?"JSXIdentifier"===object.type?object.name:"JSXNamespacedName"===object.type?object.namespace.name+":"+object.name.name:"JSXMemberExpression"===object.type?getQualifiedJSXName(object.object)+"."+getQualifiedJSXName(object.property):void 0:object}module.exports=function(options){return options=options||{},function(Parser){return function plugin(options,Parser){const acorn=Parser.acorn||__webpack_require__("./node_modules/@storybook/react/node_modules/acorn/dist/acorn.mjs"),acornJsx=getJsxTokens(acorn),tt=acorn.tokTypes,tok=acornJsx.tokTypes,tokContexts=acorn.tokContexts,tc_oTag=acornJsx.tokContexts.tc_oTag,tc_cTag=acornJsx.tokContexts.tc_cTag,tc_expr=acornJsx.tokContexts.tc_expr,isNewLine=acorn.isNewLine,isIdentifierStart=acorn.isIdentifierStart,isIdentifierChar=acorn.isIdentifierChar;return class extends Parser{static get acornJsx(){return acornJsx}jsx_readToken(){let out="",chunkStart=this.pos;for(;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated JSX contents");let ch=this.input.charCodeAt(this.pos);switch(ch){case 60:case 123:return this.pos===this.start?60===ch&&this.exprAllowed?(++this.pos,this.finishToken(tok.jsxTagStart)):this.getTokenFromCode(ch):(out+=this.input.slice(chunkStart,this.pos),this.finishToken(tok.jsxText,out));case 38:out+=this.input.slice(chunkStart,this.pos),out+=this.jsx_readEntity(),chunkStart=this.pos;break;case 62:case 125:this.raise(this.pos,"Unexpected token `"+this.input[this.pos]+"`. Did you mean `"+(62===ch?">":"}")+'` or `{"'+this.input[this.pos]+'"}`?');default:isNewLine(ch)?(out+=this.input.slice(chunkStart,this.pos),out+=this.jsx_readNewLine(!0),chunkStart=this.pos):++this.pos}}}jsx_readNewLine(normalizeCRLF){let out,ch=this.input.charCodeAt(this.pos);return++this.pos,13===ch&&10===this.input.charCodeAt(this.pos)?(++this.pos,out=normalizeCRLF?"\n":"\r\n"):out=String.fromCharCode(ch),this.options.locations&&(++this.curLine,this.lineStart=this.pos),out}jsx_readString(quote){let out="",chunkStart=++this.pos;for(;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");let ch=this.input.charCodeAt(this.pos);if(ch===quote)break;38===ch?(out+=this.input.slice(chunkStart,this.pos),out+=this.jsx_readEntity(),chunkStart=this.pos):isNewLine(ch)?(out+=this.input.slice(chunkStart,this.pos),out+=this.jsx_readNewLine(!1),chunkStart=this.pos):++this.pos}return out+=this.input.slice(chunkStart,this.pos++),this.finishToken(tt.string,out)}jsx_readEntity(){let entity,str="",count=0,ch=this.input[this.pos];"&"!==ch&&this.raise(this.pos,"Entity must start with an ampersand");let startPos=++this.pos;for(;this.pos")}let fragmentOrElement=openingElement.name?"Element":"Fragment";return node["opening"+fragmentOrElement]=openingElement,node["closing"+fragmentOrElement]=closingElement,node.children=children,this.type===tt.relational&&"<"===this.value&&this.raise(this.start,"Adjacent JSX elements must be wrapped in an enclosing tag"),this.finishNode(node,"JSX"+fragmentOrElement)}jsx_parseText(){let node=this.parseLiteral(this.value);return node.type="JSXText",node}jsx_parseElement(){let startPos=this.start,startLoc=this.startLoc;return this.next(),this.jsx_parseElementAt(startPos,startLoc)}parseExprAtom(refShortHandDefaultPos){return this.type===tok.jsxText?this.jsx_parseText():this.type===tok.jsxTagStart?this.jsx_parseElement():super.parseExprAtom(refShortHandDefaultPos)}readToken(code){let context=this.curContext();if(context===tc_expr)return this.jsx_readToken();if(context===tc_oTag||context===tc_cTag){if(isIdentifierStart(code))return this.jsx_readWord();if(62==code)return++this.pos,this.finishToken(tok.jsxTagEnd);if((34===code||39===code)&&context==tc_oTag)return this.jsx_readString(code)}return 60===code&&this.exprAllowed&&33!==this.input.charCodeAt(this.pos+1)?(++this.pos,this.finishToken(tok.jsxTagStart)):super.readToken(code)}updateContext(prevType){if(this.type==tt.braceL){var curContext=this.curContext();curContext==tc_oTag?this.context.push(tokContexts.b_expr):curContext==tc_expr?this.context.push(tokContexts.b_tmpl):super.updateContext(prevType),this.exprAllowed=!0}else{if(this.type!==tt.slash||prevType!==tok.jsxTagStart)return super.updateContext(prevType);this.context.length-=2,this.context.push(tc_cTag),this.exprAllowed=!1}}}}({allowNamespaces:!1!==options.allowNamespaces,allowNamespacedObjects:!!options.allowNamespacedObjects},Parser)}},Object.defineProperty(module.exports,"tokTypes",{get:function get_tokTypes(){return getJsxTokens(__webpack_require__("./node_modules/@storybook/react/node_modules/acorn/dist/acorn.mjs")).tokTypes},configurable:!0,enumerable:!0})},"./node_modules/@storybook/react/node_modules/acorn-jsx/xhtml.js":function(module){module.exports={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"}},"./node_modules/@storybook/store/dist/esm/csf/normalizeInputTypes.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{x:function(){return normalizeInputTypes}});__webpack_require__("./node_modules/core-js/modules/es.object.keys.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.js"),__webpack_require__("./node_modules/core-js/modules/es.object.assign.js");var lodash_mapValues__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/lodash/mapValues.js"),lodash_mapValues__WEBPACK_IMPORTED_MODULE_3___default=__webpack_require__.n(lodash_mapValues__WEBPACK_IMPORTED_MODULE_3__),_excluded=["type","control"];function _objectWithoutProperties(source,excluded){if(null==source)return{};var key,i,target=function _objectWithoutPropertiesLoose(source,excluded){if(null==source)return{};var key,i,target={},sourceKeys=Object.keys(source);for(i=0;i=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}var normalizeInputType=function normalizeInputType(inputType,key){var type=inputType.type,control=inputType.control,rest=_objectWithoutProperties(inputType,_excluded),normalized=Object.assign({name:key},rest);return type&&(normalized.type=function normalizeType(type){return"string"==typeof type?{name:type}:type}(type)),control?normalized.control=function normalizeControl(control){return"string"==typeof control?{type:control}:control}(control):!1===control&&(normalized.control={disable:!0}),normalized},normalizeInputTypes=function normalizeInputTypes(inputTypes){return lodash_mapValues__WEBPACK_IMPORTED_MODULE_3___default()(inputTypes,normalizeInputType)}},"./node_modules/@storybook/store/dist/esm/filterArgTypes.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{h:function(){return filterArgTypes}});__webpack_require__("./node_modules/core-js/modules/es.array.includes.js"),__webpack_require__("./node_modules/core-js/modules/es.string.includes.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.exec.js"),__webpack_require__("./node_modules/core-js/modules/es.string.match.js"),__webpack_require__("./node_modules/core-js/modules/es.function.name.js");var lodash_pickBy__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/lodash/pickBy.js"),lodash_pickBy__WEBPACK_IMPORTED_MODULE_5___default=__webpack_require__.n(lodash_pickBy__WEBPACK_IMPORTED_MODULE_5__),matches=function matches(name,descriptor){return Array.isArray(descriptor)?descriptor.includes(name):name.match(descriptor)},filterArgTypes=function filterArgTypes(argTypes,include,exclude){return include||exclude?argTypes&&lodash_pickBy__WEBPACK_IMPORTED_MODULE_5___default()(argTypes,(function(argType,key){var name=argType.name||key;return(!include||matches(name,include))&&(!exclude||!matches(name,exclude))})):argTypes}},"./node_modules/@storybook/store/dist/esm/parameters.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{f:function(){return combineParameters}});__webpack_require__("./node_modules/core-js/modules/es.object.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.array.filter.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.for-each.js"),__webpack_require__("./node_modules/core-js/modules/es.object.entries.js"),__webpack_require__("./node_modules/core-js/modules/es.object.keys.js"),__webpack_require__("./node_modules/core-js/modules/es.array.map.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.description.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.array.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.string.iterator.js"),__webpack_require__("./node_modules/core-js/modules/web.dom-collections.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.array.slice.js"),__webpack_require__("./node_modules/core-js/modules/es.function.name.js"),__webpack_require__("./node_modules/core-js/modules/es.array.from.js"),__webpack_require__("./node_modules/core-js/modules/es.regexp.exec.js");var lodash_isPlainObject__WEBPACK_IMPORTED_MODULE_16__=__webpack_require__("./node_modules/lodash/isPlainObject.js"),lodash_isPlainObject__WEBPACK_IMPORTED_MODULE_16___default=__webpack_require__.n(lodash_isPlainObject__WEBPACK_IMPORTED_MODULE_16__);function _toConsumableArray(arr){return function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr)}(arr)||function _iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}(arr)||_unsupportedIterableToArray(arr)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _slicedToArray(arr,i){return function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function _iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null==_i)return;var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||_unsupportedIterableToArray(arr,i)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(o,minLen){if(o){if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(o,minLen):void 0}}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0?charat(characters,--position):0,column--,10===character&&(column=1,line--),character}function next(){return character=position2||token(character)>3?"":" "}function escaping(index,count){for(;--count&&next()&&!(character<48||character>102||character>57&&character<65||character>70&&character<97););return slice(index,caret()+(count<6&&32==peek()&&32==next()))}function delimiter(type){for(;next();)switch(character){case type:return position;case 34:case 39:34!==type&&39!==type&&delimiter(character);break;case 40:41===type&&delimiter(type);break;case 92:next()}return position}function commenter(type,index){for(;next()&&type+character!==57&&(type+character!==84||47!==peek()););return"/*"+slice(index,position-1)+"*"+from(47===type?type:next())}function identifier(index){for(;!token(peek());)next();return slice(index,position)}function compile(value){return dealloc(parse("",null,null,null,[""],value=alloc(value),0,[0],value))}function parse(value,root,parent,rule,rules,rulesets,pseudo,points,declarations){for(var index=0,offset=0,length=pseudo,atrule=0,property=0,previous=0,variable=1,scanning=1,ampersand=1,character=0,type="",props=rules,children=rulesets,reference=rule,characters=type;scanning;)switch(previous=character,character=next()){case 40:if(108!=previous&&58==characters.charCodeAt(length-1)){-1!=indexof(characters+=replace(delimit(character),"&","&\f"),"&\f")&&(ampersand=-1);break}case 34:case 39:case 91:characters+=delimit(character);break;case 9:case 10:case 13:case 32:characters+=whitespace(previous);break;case 92:characters+=escaping(caret()-1,7);continue;case 47:switch(peek()){case 42:case 47:append(comment(commenter(next(),caret()),root,parent),declarations);break;default:characters+="/"}break;case 123*variable:points[index++]=strlen(characters)*ampersand;case 125*variable:case 59:case 0:switch(character){case 0:case 125:scanning=0;case 59+offset:property>0&&strlen(characters)-length&&append(property>32?declaration(characters+";",rule,parent,length-1):declaration(replace(characters," ","")+";",rule,parent,length-2),declarations);break;case 59:characters+=";";default:if(append(reference=ruleset(characters,root,parent,index,offset,rules,points,type,props=[],children=[],length),rulesets),123===character)if(0===offset)parse(characters,root,reference,reference,props,rulesets,length,points,children);else switch(atrule){case 100:case 109:case 115:parse(value,reference,reference,rule&&append(ruleset(value,reference,reference,0,0,rules,points,type,rules,props=[],length),children),rules,children,length,points,rule?props:children);break;default:parse(characters,reference,reference,reference,[""],children,0,points,children)}}index=offset=property=0,variable=ampersand=1,type=characters="",length=pseudo;break;case 58:length=1+strlen(characters),property=previous;default:if(variable<1)if(123==character)--variable;else if(125==character&&0==variable++&&125==prev())continue;switch(characters+=from(character),character*variable){case 38:ampersand=offset>0?1:(characters+="\f",-1);break;case 44:points[index++]=(strlen(characters)-1)*ampersand,ampersand=1;break;case 64:45===peek()&&(characters+=delimit(next())),atrule=peek(),offset=length=strlen(type=characters+=identifier(caret())),character++;break;case 45:45===previous&&2==strlen(characters)&&(variable=0)}}return rulesets}function ruleset(value,root,parent,index,offset,rules,points,type,props,children,length){for(var post=offset-1,rule=0===offset?rules:[""],size=sizeof(rule),i=0,j=0,k=0;i0?rule[x]+" "+y:replace(y,/&\f/g,rule[x])))&&(props[k++]=z);return node(value,root,parent,0===offset?"rule":type,props,children,length)}function comment(value,root,parent){return node(value,root,parent,"comm",from(function char(){return character}()),substr(value,2,-2),0)}function declaration(value,root,parent,length){return node(value,root,parent,"decl",substr(value,0,length),substr(value,length+1,-1),length)}function prefix(value,length){switch(function hash(value,length){return(((length<<2^charat(value,0))<<2^charat(value,1))<<2^charat(value,2))<<2^charat(value,3)}(value,length)){case 5103:return WEBKIT+"print-"+value+value;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return WEBKIT+value+value;case 5349:case 4246:case 4810:case 6968:case 2756:return WEBKIT+value+MOZ+value+MS+value+value;case 6828:case 4268:return WEBKIT+value+MS+value+value;case 6165:return WEBKIT+value+MS+"flex-"+value+value;case 5187:return WEBKIT+value+replace(value,/(\w+).+(:[^]+)/,"-webkit-box-$1$2-ms-flex-$1$2")+value;case 5443:return WEBKIT+value+MS+"flex-item-"+replace(value,/flex-|-self/,"")+value;case 4675:return WEBKIT+value+MS+"flex-line-pack"+replace(value,/align-content|flex-|-self/,"")+value;case 5548:return WEBKIT+value+MS+replace(value,"shrink","negative")+value;case 5292:return WEBKIT+value+MS+replace(value,"basis","preferred-size")+value;case 6060:return WEBKIT+"box-"+replace(value,"-grow","")+WEBKIT+value+MS+replace(value,"grow","positive")+value;case 4554:return WEBKIT+replace(value,/([^-])(transform)/g,"$1-webkit-$2")+value;case 6187:return replace(replace(replace(value,/(zoom-|grab)/,WEBKIT+"$1"),/(image-set)/,WEBKIT+"$1"),value,"")+value;case 5495:case 3959:return replace(value,/(image-set\([^]*)/,WEBKIT+"$1$`$1");case 4968:return replace(replace(value,/(.+:)(flex-)?(.*)/,"-webkit-box-pack:$3-ms-flex-pack:$3"),/s.+-b[^;]+/,"justify")+WEBKIT+value+value;case 4095:case 3583:case 4068:case 2532:return replace(value,/(.+)-inline(.+)/,WEBKIT+"$1$2")+value;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(strlen(value)-1-length>6)switch(charat(value,length+1)){case 109:if(45!==charat(value,length+4))break;case 102:return replace(value,/(.+:)(.+)-([^]+)/,"$1-webkit-$2-$3$1"+MOZ+(108==charat(value,length+3)?"$3":"$2-$3"))+value;case 115:return~indexof(value,"stretch")?prefix(replace(value,"stretch","fill-available"),length)+value:value}break;case 4949:if(115!==charat(value,length+1))break;case 6444:switch(charat(value,strlen(value)-3-(~indexof(value,"!important")&&10))){case 107:return replace(value,":",":"+WEBKIT)+value;case 101:return replace(value,/(.+:)([^;!]+)(;|!.+)?/,"$1"+WEBKIT+(45===charat(value,14)?"inline-":"")+"box$3$1"+WEBKIT+"$2$3$1"+MS+"$2box$3")+value}break;case 5936:switch(charat(value,length+11)){case 114:return WEBKIT+value+MS+replace(value,/[svh]\w+-[tblr]{2}/,"tb")+value;case 108:return WEBKIT+value+MS+replace(value,/[svh]\w+-[tblr]{2}/,"tb-rl")+value;case 45:return WEBKIT+value+MS+replace(value,/[svh]\w+-[tblr]{2}/,"lr")+value}return WEBKIT+value+MS+value+value}return value}function serialize(children,callback){for(var output="",length=sizeof(children),i=0;i-1&&!element.return)switch(element.type){case"decl":element.return=prefix(element.value,element.length);break;case"@keyframes":return serialize([copy(element,{value:replace(element.value,"@","@"+WEBKIT)})],callback);case"rule":if(element.length)return function combine(array,callback){return array.map(callback).join("")}(element.props,(function(value){switch(function match(value,pattern){return(value=pattern.exec(value))?value[0]:value}(value,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return serialize([copy(element,{props:[replace(value,/:(read-\w+)/,":-moz-$1")]})],callback);case"::placeholder":return serialize([copy(element,{props:[replace(value,/:(plac\w+)/,":-webkit-input-$1")]}),copy(element,{props:[replace(value,/:(plac\w+)/,":-moz-$1")]}),copy(element,{props:[replace(value,/:(plac\w+)/,MS+"input-$1")]})],callback)}return""}))}}],createCache=function createCache(options){var key=options.key;if(isBrowser$6&&"css"===key){var ssrStyles=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(ssrStyles,(function(node){-1!==node.getAttribute("data-emotion").indexOf(" ")&&(document.head.appendChild(node),node.setAttribute("data-s",""))}))}var stylisPlugins=options.stylisPlugins||defaultStylisPlugins;var container,_insert,inserted={},nodesToHydrate=[];isBrowser$6&&(container=options.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+key+' "]'),(function(node){for(var attrib=node.getAttribute("data-emotion").split(" "),i=1;i=4;++i,len-=4)k=1540483477*(65535&(k=255&str.charCodeAt(i)|(255&str.charCodeAt(++i))<<8|(255&str.charCodeAt(++i))<<16|(255&str.charCodeAt(++i))<<24))+(59797*(k>>>16)<<16),h=1540483477*(65535&(k^=k>>>24))+(59797*(k>>>16)<<16)^1540483477*(65535&h)+(59797*(h>>>16)<<16);switch(len){case 3:h^=(255&str.charCodeAt(i+2))<<16;case 2:h^=(255&str.charCodeAt(i+1))<<8;case 1:h=1540483477*(65535&(h^=255&str.charCodeAt(i)))+(59797*(h>>>16)<<16)}return(((h=1540483477*(65535&(h^=h>>>13))+(59797*(h>>>16)<<16))^h>>>15)>>>0).toString(36)}var unitlessKeys={animationIterationCount:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},hyphenateRegex$1=/[A-Z]|^ms/g,animationRegex$1=/_EMO_([^_]+?)_([^]*?)_EMO_/g,isCustomProperty$1=function isCustomProperty(property){return 45===property.charCodeAt(1)},isProcessableValue$1=function isProcessableValue(value){return null!=value&&"boolean"!=typeof value},processStyleName$1=memoize((function(styleName){return isCustomProperty$1(styleName)?styleName:styleName.replace(hyphenateRegex$1,"-$&").toLowerCase()})),processStyleValue$1=function processStyleValue(key,value){switch(key){case"animation":case"animationName":if("string"==typeof value)return value.replace(animationRegex$1,(function(match,p1,p2){return cursor$1={name:p1,styles:p2,next:cursor$1},p1}))}return 1===unitlessKeys[key]||isCustomProperty$1(key)||"number"!=typeof value||0===value?value:value+"px"};function handleInterpolation$1(mergedProps,registered,interpolation){if(null==interpolation)return"";if(void 0!==interpolation.__emotion_styles)return interpolation;switch(_typeof(interpolation)){case"boolean":return"";case"object":if(1===interpolation.anim)return cursor$1={name:interpolation.name,styles:interpolation.styles,next:cursor$1},interpolation.name;if(void 0!==interpolation.styles){var next=interpolation.next;if(void 0!==next)for(;void 0!==next;)cursor$1={name:next.name,styles:next.styles,next:cursor$1},next=next.next;return interpolation.styles+";"}return function createStringFromObject$1(mergedProps,registered,obj){var string="";if(Array.isArray(obj))for(var i=0;i96?testOmitPropsOnStringTag:testOmitPropsOnComponent},composeShouldForwardProps=function composeShouldForwardProps(tag,options,isReal){var shouldForwardProp;if(options){var optionsShouldForwardProp=options.shouldForwardProp;shouldForwardProp=tag.__emotion_forwardProp&&optionsShouldForwardProp?function(propName){return tag.__emotion_forwardProp(propName)&&optionsShouldForwardProp(propName)}:optionsShouldForwardProp}return"function"!=typeof shouldForwardProp&&isReal&&(shouldForwardProp=tag.__emotion_forwardProp),shouldForwardProp},isBrowser="undefined"!=typeof document,useInsertionEffect=(react__WEBPACK_IMPORTED_MODULE_37___namespace_cache||(react__WEBPACK_IMPORTED_MODULE_37___namespace_cache=__webpack_require__.t(react__WEBPACK_IMPORTED_MODULE_37__,2))).useInsertionEffect?(react__WEBPACK_IMPORTED_MODULE_37___namespace_cache||(react__WEBPACK_IMPORTED_MODULE_37___namespace_cache=__webpack_require__.t(react__WEBPACK_IMPORTED_MODULE_37__,2))).useInsertionEffect:function useInsertionEffect(create){create()};var isBrowser$1="undefined"!=typeof document,Insertion=function Insertion(_ref){var cache=_ref.cache,serialized=_ref.serialized,isStringTag=_ref.isStringTag;registerStyles(cache,serialized,isStringTag);var rules=function useInsertionEffectMaybe(create){if(!isBrowser)return create();useInsertionEffect(create)}((function(){return function insertStyles(cache,serialized,isStringTag){registerStyles(cache,serialized,isStringTag);var className=cache.key+"-"+serialized.name;if(void 0===cache.inserted[serialized.name]){var stylesForSSR="",current=serialized;do{var maybeStyles=cache.insert(serialized===current?"."+className:"",current,cache.sheet,!0);isBrowser$2||void 0===maybeStyles||(stylesForSSR+=maybeStyles),current=current.next}while(void 0!==current);if(!isBrowser$2&&0!==stylesForSSR.length)return stylesForSSR}}(cache,serialized,isStringTag)}));if(!isBrowser$1&&void 0!==rules){for(var _ref2,serializedNames=serialized.name,next=serialized.next;void 0!==next;)serializedNames+=" "+next.name,next=next.next;return(0,react__WEBPACK_IMPORTED_MODULE_37__.createElement)("style",((_ref2={})["data-emotion"]=cache.key+" "+serializedNames,_ref2.dangerouslySetInnerHTML={__html:rules},_ref2.nonce=cache.sheet.nonce,_ref2))}return null},newStyled=function createStyled(tag,options){var identifierName,targetClassName,isReal=tag.__emotion_real===tag,baseTag=isReal&&tag.__emotion_base||tag;void 0!==options&&(identifierName=options.label,targetClassName=options.target);var shouldForwardProp=composeShouldForwardProps(tag,options,isReal),defaultShouldForwardProp=shouldForwardProp||getDefaultShouldForwardProp(baseTag),shouldUseAs=!defaultShouldForwardProp("as");return function(){var args=arguments,styles=isReal&&void 0!==tag.__emotion_styles?tag.__emotion_styles.slice(0):[];if(void 0!==identifierName&&styles.push("label:"+identifierName+";"),null==args[0]||void 0===args[0].raw)styles.push.apply(styles,args);else{0,styles.push(args[0][0]);for(var len=args.length,i=1;i=0&&huePrime<1?(red=chroma,green=secondComponent):huePrime>=1&&huePrime<2?(red=secondComponent,green=chroma):huePrime>=2&&huePrime<3?(green=chroma,blue=secondComponent):huePrime>=3&&huePrime<4?(green=secondComponent,blue=chroma):huePrime>=4&&huePrime<5?(red=secondComponent,blue=chroma):huePrime>=5&&huePrime<6&&(red=chroma,blue=secondComponent);var lightnessModification=lightness-chroma/2;return convert(red+lightnessModification,green+lightnessModification,blue+lightnessModification)}var namedColorMap={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var hexRegex=/^#[a-fA-F0-9]{6}$/,hexRgbaRegex=/^#[a-fA-F0-9]{8}$/,reducedHexRegex=/^#[a-fA-F0-9]{3}$/,reducedRgbaHexRegex=/^#[a-fA-F0-9]{4}$/,rgbRegex=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,rgbaRegex=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,hslRegex=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,hslaRegex=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function parseToRgb(color){if("string"!=typeof color)throw new PolishedError(3);var normalizedColor=function nameToHex(color){if("string"!=typeof color)return color;var normalizedColorName=color.toLowerCase();return namedColorMap[normalizedColorName]?"#"+namedColorMap[normalizedColorName]:color}(color);if(normalizedColor.match(hexRegex))return{red:parseInt(""+normalizedColor[1]+normalizedColor[2],16),green:parseInt(""+normalizedColor[3]+normalizedColor[4],16),blue:parseInt(""+normalizedColor[5]+normalizedColor[6],16)};if(normalizedColor.match(hexRgbaRegex)){var alpha=parseFloat((parseInt(""+normalizedColor[7]+normalizedColor[8],16)/255).toFixed(2));return{red:parseInt(""+normalizedColor[1]+normalizedColor[2],16),green:parseInt(""+normalizedColor[3]+normalizedColor[4],16),blue:parseInt(""+normalizedColor[5]+normalizedColor[6],16),alpha:alpha}}if(normalizedColor.match(reducedHexRegex))return{red:parseInt(""+normalizedColor[1]+normalizedColor[1],16),green:parseInt(""+normalizedColor[2]+normalizedColor[2],16),blue:parseInt(""+normalizedColor[3]+normalizedColor[3],16)};if(normalizedColor.match(reducedRgbaHexRegex)){var _alpha=parseFloat((parseInt(""+normalizedColor[4]+normalizedColor[4],16)/255).toFixed(2));return{red:parseInt(""+normalizedColor[1]+normalizedColor[1],16),green:parseInt(""+normalizedColor[2]+normalizedColor[2],16),blue:parseInt(""+normalizedColor[3]+normalizedColor[3],16),alpha:_alpha}}var rgbMatched=rgbRegex.exec(normalizedColor);if(rgbMatched)return{red:parseInt(""+rgbMatched[1],10),green:parseInt(""+rgbMatched[2],10),blue:parseInt(""+rgbMatched[3],10)};var rgbaMatched=rgbaRegex.exec(normalizedColor.substring(0,50));if(rgbaMatched)return{red:parseInt(""+rgbaMatched[1],10),green:parseInt(""+rgbaMatched[2],10),blue:parseInt(""+rgbaMatched[3],10),alpha:parseFloat(""+rgbaMatched[4])>1?parseFloat(""+rgbaMatched[4])/100:parseFloat(""+rgbaMatched[4])};var hslMatched=hslRegex.exec(normalizedColor);if(hslMatched){var rgbColorString="rgb("+hslToRgb(parseInt(""+hslMatched[1],10),parseInt(""+hslMatched[2],10)/100,parseInt(""+hslMatched[3],10)/100)+")",hslRgbMatched=rgbRegex.exec(rgbColorString);if(!hslRgbMatched)throw new PolishedError(4,normalizedColor,rgbColorString);return{red:parseInt(""+hslRgbMatched[1],10),green:parseInt(""+hslRgbMatched[2],10),blue:parseInt(""+hslRgbMatched[3],10)}}var hslaMatched=hslaRegex.exec(normalizedColor.substring(0,50));if(hslaMatched){var _rgbColorString="rgb("+hslToRgb(parseInt(""+hslaMatched[1],10),parseInt(""+hslaMatched[2],10)/100,parseInt(""+hslaMatched[3],10)/100)+")",_hslRgbMatched=rgbRegex.exec(_rgbColorString);if(!_hslRgbMatched)throw new PolishedError(4,normalizedColor,_rgbColorString);return{red:parseInt(""+_hslRgbMatched[1],10),green:parseInt(""+_hslRgbMatched[2],10),blue:parseInt(""+_hslRgbMatched[3],10),alpha:parseFloat(""+hslaMatched[4])>1?parseFloat(""+hslaMatched[4])/100:parseFloat(""+hslaMatched[4])}}throw new PolishedError(5)}function parseToHsl(color){return function rgbToHsl(color){var hue,red=color.red/255,green=color.green/255,blue=color.blue/255,max=Math.max(red,green,blue),min=Math.min(red,green,blue),lightness=(max+min)/2;if(max===min)return void 0!==color.alpha?{hue:0,saturation:0,lightness:lightness,alpha:color.alpha}:{hue:0,saturation:0,lightness:lightness};var delta=max-min,saturation=lightness>.5?delta/(2-max-min):delta/(max+min);switch(max){case red:hue=(green-blue)/delta+(green=1?rgb(firstValue,secondValue,thirdValue):"rgba("+firstValue+","+secondValue+","+thirdValue+","+fourthValue+")";if("object"===_typeof(firstValue)&&void 0===secondValue&&void 0===thirdValue&&void 0===fourthValue)return firstValue.alpha>=1?rgb(firstValue.red,firstValue.green,firstValue.blue):"rgba("+firstValue.red+","+firstValue.green+","+firstValue.blue+","+firstValue.alpha+")";throw new PolishedError(7)}function toColorString(color){if("object"!==_typeof(color))throw new PolishedError(8);if(function isRgba(color){return"number"==typeof color.red&&"number"==typeof color.green&&"number"==typeof color.blue&&"number"==typeof color.alpha}(color))return rgba(color);if(function isRgb(color){return"number"==typeof color.red&&"number"==typeof color.green&&"number"==typeof color.blue&&("number"!=typeof color.alpha||void 0===color.alpha)}(color))return rgb(color);if(function isHsla(color){return"number"==typeof color.hue&&"number"==typeof color.saturation&&"number"==typeof color.lightness&&"number"==typeof color.alpha}(color))return function hsla(value,saturation,lightness,alpha){if("number"==typeof value&&"number"==typeof saturation&&"number"==typeof lightness&&"number"==typeof alpha)return alpha>=1?hslToHex(value,saturation,lightness):"rgba("+hslToRgb(value,saturation,lightness)+","+alpha+")";if("object"===_typeof(value)&&void 0===saturation&&void 0===lightness&&void 0===alpha)return value.alpha>=1?hslToHex(value.hue,value.saturation,value.lightness):"rgba("+hslToRgb(value.hue,value.saturation,value.lightness)+","+value.alpha+")";throw new PolishedError(2)}(color);if(function isHsl(color){return"number"==typeof color.hue&&"number"==typeof color.saturation&&"number"==typeof color.lightness&&("number"!=typeof color.alpha||void 0===color.alpha)}(color))return function hsl(value,saturation,lightness){if("number"==typeof value&&"number"==typeof saturation&&"number"==typeof lightness)return hslToHex(value,saturation,lightness);if("object"===_typeof(value)&&void 0===saturation&&void 0===lightness)return hslToHex(value.hue,value.saturation,value.lightness);throw new PolishedError(1)}(color);throw new PolishedError(8)}function curried(f,length,acc){return function fn(){var combined=acc.concat(Array.prototype.slice.call(arguments));return combined.length>=length?f.apply(this,combined):curried(f,length,combined)}}function curry(f){return curried(f,f.length,[])}function guard(lowerBoundary,upperBoundary,value){return Math.max(lowerBoundary,Math.min(upperBoundary,value))}function darken(amount,color){if("transparent"===color)return color;var hslColor=parseToHsl(color);return toColorString(_extends({},hslColor,{lightness:guard(0,1,hslColor.lightness-parseFloat(amount))}))}var curriedDarken$1=curry(darken);function lighten(amount,color){if("transparent"===color)return color;var hslColor=parseToHsl(color);return toColorString(_extends({},hslColor,{lightness:guard(0,1,hslColor.lightness+parseFloat(amount))}))}var curriedLighten$1=curry(lighten);function opacify(amount,color){if("transparent"===color)return color;var parsedColor=parseToRgb(color);return rgba(_extends({},parsedColor,{alpha:guard(0,1,(100*("number"==typeof parsedColor.alpha?parsedColor.alpha:1)+100*parseFloat(amount))/100)}))}var curriedOpacify$1=curry(opacify);function transparentize(amount,color){if("transparent"===color)return color;var parsedColor=parseToRgb(color);return rgba(_extends({},parsedColor,{alpha:guard(0,1,+(100*("number"==typeof parsedColor.alpha?parsedColor.alpha:1)-100*parseFloat(amount)).toFixed(2)/100)}))}var color_secondary="#1EA7FD",color_tertiary="#FAFBFC",color_ancillary="#22a699",color_orange="#FC521F",color_gold="#FFAE00",color_green="#66BF3C",color_seafoam="#37D5D3",color_purple="#6F2CAC",color_ultraviolet="#2A0481",color_lightest="#FFFFFF",color_lighter="#F8F8F8",color_light="#F3F3F3",color_mediumlight="#EEEEEE",color_medium="#DDDDDD",color_mediumdark="#999999",color_dark="#666666",color_darker="#444444",color_darkest="#333333",color_border="rgba(0,0,0,.1)",color_positive="#66BF3C",color_negative="#FF4400",color_warning="#E69D00",color_critical="#FFFFFF",background={app:"#F6F9FC",bar:"#FFFFFF",content:color_lightest,gridCellSize:10,hoverable:curry(transparentize)(.93,color_secondary),positive:"#E1FFD4",negative:"#FEDED2",warning:"#FFF5CF",critical:"#FF4400"},typography={fonts:{base:['"Nunito Sans"',"-apple-system",'".SFNSText-Regular"','"San Francisco"',"BlinkMacSystemFont",'"Segoe UI"','"Helvetica Neue"',"Helvetica","Arial","sans-serif"].join(", "),mono:["ui-monospace","Menlo","Monaco",'"Roboto Mono"','"Oxygen Mono"','"Ubuntu Monospace"','"Source Code Pro"','"Droid Sans Mono"','"Courier New"',"monospace"].join(", ")},weight:{regular:400,bold:700,black:900},size:{s1:12,s2:14,s3:16,m1:20,m2:24,m3:28,l1:32,l2:40,l3:48,code:90}},createReset=memoizerific__WEBPACK_IMPORTED_MODULE_38___default()(1)((function(_ref3){var typography=_ref3.typography;return{body:{fontFamily:typography.fonts.base,fontSize:typography.size.s3,margin:0,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale",WebkitTapHighlightColor:"rgba(0, 0, 0, 0)",WebkitOverflowScrolling:"touch"},"*":{boxSizing:"border-box"},"h1, h2, h3, h4, h5, h6":{fontWeight:typography.weight.regular,margin:0,padding:0},"button, input, textarea, select":{fontFamily:"inherit",fontSize:"inherit",boxSizing:"border-box"},sub:{fontSize:"0.8em",bottom:"-0.2em"},sup:{fontSize:"0.8em",top:"-0.2em"},"b, strong":{fontWeight:typography.weight.bold},hr:{border:"none",borderTop:"1px solid silver",clear:"both",marginBottom:"1.25rem"},code:{fontFamily:typography.fonts.mono,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale",display:"inline-block",paddingLeft:2,paddingRight:2,verticalAlign:"baseline",color:"inherit"},pre:{fontFamily:typography.fonts.mono,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale",lineHeight:"18px",padding:"11px 1rem",whiteSpace:"pre-wrap",color:"inherit",borderRadius:3,margin:"1rem 0"}}})),theme$1=(memoizerific__WEBPACK_IMPORTED_MODULE_38___default()(1)((function(_ref4){var color=_ref4.color,background=_ref4.background,typography=_ref4.typography,resetStyles=createReset({typography:typography});return Object.assign(Object.assign({},resetStyles),{body:Object.assign(Object.assign({},resetStyles.body),{color:color.defaultText,background:background.app,overflow:"hidden"}),hr:Object.assign(Object.assign({},resetStyles.hr),{borderTop:"1px solid ".concat(color.border)})})})),{base:"light",colorPrimary:"#FF4785",colorSecondary:"#1EA7FD",appBg:background.app,appContentBg:color_lightest,appBorderColor:color_border,appBorderRadius:4,fontBase:typography.fonts.base,fontCode:typography.fonts.mono,textColor:color_darkest,textInverseColor:color_lightest,textMutedColor:color_dark,barTextColor:color_mediumdark,barSelectedColor:color_secondary,barBg:color_lightest,inputBg:color_lightest,inputBorder:color_border,inputTextColor:color_darkest,inputBorderRadius:4}),theme={base:"dark",colorPrimary:"#FF4785",colorSecondary:"#1EA7FD",appBg:"#2f2f2f",appContentBg:color_darkest,appBorderColor:"rgba(255,255,255,.1)",appBorderRadius:4,fontBase:typography.fonts.base,fontCode:typography.fonts.mono,textColor:color_lightest,textInverseColor:color_darkest,textMutedColor:color_mediumdark,barTextColor:"#999999",barSelectedColor:color_secondary,barBg:color_darkest,inputBg:"#3f3f3f",inputBorder:"rgba(0,0,0,.3)",inputTextColor:color_lightest,inputBorderRadius:4},globalWindow=("undefined"!=typeof window?window:void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{}).window,colorFactory=function colorFactory(type){return function(color){if(!function isColorString(color){return"string"==typeof color||(_storybook_client_logger__WEBPACK_IMPORTED_MODULE_39__.kg.warn("Color passed to theme object should be a string. Instead "+"".concat(color,"(").concat(_typeof(color),") was passed.")),!1)}(color))return color;if(!function isValidColorForPolished(color){return!/(gradient|var|calc)/.test(color)}(color))return color;try{return function applyPolished(type,color){return"darken"===type?rgba("".concat(curriedDarken$1(1,color)),.95):"lighten"===type?rgba("".concat(curriedLighten$1(1,color)),.95):color}(type,color)}catch(error){return color}}},lightenColor=colorFactory("lighten"),darkenColor=colorFactory("darken"),getPreferredColorScheme=function getPreferredColorScheme(){return globalWindow&&globalWindow.matchMedia&&globalWindow.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"},themes={light:theme$1,dark:theme,normal:theme$1};getPreferredColorScheme();function __rest(s,e){var t={};for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(null!=s&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(p=Object.getOwnPropertySymbols(s);i0&&void 0!==arguments[0]?arguments[0]:themes[getPreferredColorScheme()],base=inherit.base,colorSecondary=(inherit.colorPrimary,inherit.colorSecondary),appBg=inherit.appBg,appContentBg=inherit.appContentBg,appBorderColor=inherit.appBorderColor,appBorderRadius=inherit.appBorderRadius,fontBase=inherit.fontBase,fontCode=inherit.fontCode,textColor=inherit.textColor,barTextColor=(inherit.textInverseColor,inherit.barTextColor),barSelectedColor=inherit.barSelectedColor,barBg=inherit.barBg,inputBg=inherit.inputBg,inputBorder=inherit.inputBorder,inputTextColor=inherit.inputTextColor,inputBorderRadius=inherit.inputBorderRadius,brandTitle=inherit.brandTitle,brandUrl=inherit.brandUrl,brandImage=inherit.brandImage,brandTarget=inherit.brandTarget,gridCellSize=inherit.gridCellSize,rest=__rest(inherit,["base","colorPrimary","colorSecondary","appBg","appContentBg","appBorderColor","appBorderRadius","fontBase","fontCode","textColor","textInverseColor","barTextColor","barSelectedColor","barBg","inputBg","inputBorder","inputTextColor","inputBorderRadius","brandTitle","brandUrl","brandImage","brandTarget","gridCellSize"]);return Object.assign(Object.assign({},rest||{}),{base:base,color:createColors(inherit),background:{app:appBg,bar:barBg,content:appContentBg,gridCellSize:gridCellSize||background.gridCellSize,hoverable:background.hoverable,positive:background.positive,negative:background.negative,warning:background.warning,critical:background.critical},typography:{fonts:{base:fontBase,mono:fontCode},weight:typography.weight,size:typography.size},animation:animation,easing:easing,input:{border:inputBorder,background:inputBg,color:inputTextColor,borderRadius:inputBorderRadius},layoutMargin:10,appBorderColor:appBorderColor,appBorderRadius:appBorderRadius,barTextColor:barTextColor,barSelectedColor:barSelectedColor||colorSecondary,barBg:barBg,brand:{title:brandTitle,url:brandUrl,image:brandImage||(brandTitle?null:void 0),target:brandTarget},code:create({colors:"light"===base?lightSyntaxColors:darkSyntaxColors,mono:fontCode}),addonActionsTheme:Object.assign(Object.assign({},"light"===base?chromeLight:chromeDark),{BASE_FONT_FAMILY:fontCode,BASE_FONT_SIZE:typography.size.s2-1,BASE_LINE_HEIGHT:"18px",BASE_BACKGROUND_COLOR:"transparent",BASE_COLOR:textColor,ARROW_COLOR:curriedOpacify$1(.2,appBorderColor),ARROW_MARGIN_RIGHT:4,ARROW_FONT_SIZE:8,TREENODE_FONT_FAMILY:fontCode,TREENODE_FONT_SIZE:typography.size.s2-1,TREENODE_LINE_HEIGHT:"18px",TREENODE_PADDING_LEFT:12})})},isObject=function isObject(o){return null!=o&&"object"===_typeof(o)},deletedDiff=function deletedDiff(lhs,rhs){if(lhs===rhs||!isObject(lhs)||!isObject(rhs))return{};var l=lhs,r=rhs;return Object.keys(l).reduce((function(acc,key){if(function hasOwnProperty(o){for(var _Object$prototype$has,_len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++)args[_key3-1]=arguments[_key3];return(_Object$prototype$has=Object.prototype.hasOwnProperty).call.apply(_Object$prototype$has,[o].concat(args))}(r,key)){var difference=deletedDiff(l[key],r[key]);return isObject(difference)&&function isEmpty(o){return 0===Object.keys(o).length}(difference)||(acc[key]=difference),acc}return acc[key]=void 0,acc}),{})};var ensure=function ensure(input){if(!input)return convert(theme$1);var missing=deletedDiff(theme$1,input);return Object.keys(missing).length&&_storybook_client_logger__WEBPACK_IMPORTED_MODULE_39__.kg.warn(function dedent(templ){for(var values=[],_i=1;_i=o.length?{done:!0}:{done:!1,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var it,err,normalCompletion=!0,didErr=!1;return{s:function s(){it=o[Symbol.iterator]()},n:function n(){var step=it.next();return normalCompletion=step.done,step},e:function e(_e2){didErr=!0,err=_e2},f:function f(){try{normalCompletion||null==it.return||it.return()}finally{if(didErr)throw err}}}}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0?40*red+55:0,g=green>0?40*green+55:0,b=blue>0?40*blue+55:0;colors[16+36*red+6*green+blue]=function toColorHexString(ref){var _step,results=[],_iterator=_createForOfIteratorHelper(ref);try{for(_iterator.s();!(_step=_iterator.n()).done;){var r=_step.value;results.push(toHexString(r))}}catch(err){_iterator.e(err)}finally{_iterator.f()}return"#"+results.join("")}([r,g,b])}(red,green,blue,colors)}))}))})),range(0,23).forEach((function(gray){var c=gray+232,l=toHexString(10*gray+8);colors[c]="#"+l+l+l})),colors}()};function toHexString(num){for(var str=num.toString(16);str.length<2;)str="0"+str;return str}function generateOutput(stack,token,data,options){var result;return"text"===token?result=function pushText(text,options){if(options.escapeXML)return entities.encodeXML(text);return text}(data,options):"display"===token?result=function handleDisplay(stack,code,options){code=parseInt(code,10);var result,codeMap={"-1":function _(){return"
"},0:function _(){return stack.length&&resetStyles(stack)},1:function _(){return pushTag(stack,"b")},3:function _(){return pushTag(stack,"i")},4:function _(){return pushTag(stack,"u")},8:function _(){return pushStyle(stack,"display:none")},9:function _(){return pushTag(stack,"strike")},22:function _(){return pushStyle(stack,"font-weight:normal;text-decoration:none;font-style:normal")},23:function _(){return closeTag(stack,"i")},24:function _(){return closeTag(stack,"u")},39:function _(){return pushForegroundColor(stack,options.fg)},49:function _(){return pushBackgroundColor(stack,options.bg)},53:function _(){return pushStyle(stack,"text-decoration:overline")}};codeMap[code]?result=codeMap[code]():4"})).join("")}function range(low,high){for(var results=[],j=low;j<=high;j++)results.push(j);return results}function categoryForCode(code){var result=null;return 0===(code=parseInt(code,10))?result="all":1===code?result="bold":2")}function pushStyle(stack,style){return pushTag(stack,"span",style)}function pushForegroundColor(stack,color){return pushTag(stack,"span","color:"+color)}function pushBackgroundColor(stack,color){return pushTag(stack,"span","background-color:"+color)}function closeTag(stack,style){var last;if(stack.slice(-1)[0]===style&&(last=stack.pop()),last)return""}var Filter=function(){function Filter(options){!function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}(this,Filter),(options=options||{}).colors&&(options.colors=Object.assign({},defaults.colors,options.colors)),this.options=Object.assign({},defaults,options),this.stack=[],this.stickyStack=[]}return function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}(Filter,[{key:"toHtml",value:function toHtml(input){var _this=this;input="string"==typeof input?[input]:input;var stack=this.stack,options=this.options,buf=[];return this.stickyStack.forEach((function(element){var output=generateOutput(stack,element.token,element.data,options);output&&buf.push(output)})),function tokenize(text,options,callback){var ansiMatch=!1;function remove(){return""}function newline(m){return options.newline?callback("display",-1):callback("text",m),""}var tokens=[{pattern:/^\x08+/,sub:remove},{pattern:/^\x1b\[[012]?K/,sub:remove},{pattern:/^\x1b\[\(B/,sub:remove},{pattern:/^\x1b\[[34]8;2;\d+;\d+;\d+m/,sub:function rgb(m){return callback("rgb",m),""}},{pattern:/^\x1b\[38;5;(\d+)m/,sub:function removeXterm256(m,g1){return callback("xterm256",g1),""}},{pattern:/^\n/,sub:newline},{pattern:/^\r+\n/,sub:newline},{pattern:/^\x1b\[((?:\d{1,3};?)+|)m/,sub:function ansiMess(m,g1){ansiMatch=!0,0===g1.trim().length&&(g1="0");var _step2,_iterator2=_createForOfIteratorHelper(g1=g1.trimRight(";").split(";"));try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var g=_step2.value;callback("display",g)}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}return""}},{pattern:/^\x1b\[\d?J/,sub:remove},{pattern:/^\x1b\[\d{0,3};\d{0,3}f/,sub:remove},{pattern:/^\x1b\[?[\d;]{0,3}/,sub:remove},{pattern:/^(([^\x1b\x08\r\n])+)/,sub:function realText(m){return callback("text",m),""}}];function process(handler,i){i>3&&ansiMatch||(ansiMatch=!1,text=text.replace(handler.pattern,handler.sub))}var results1=[],length=text.length;outer:for(;length>0;){for(var i=0,o=0,len=tokens.length;o1?ToIntegerOrInfinity(arguments[1]):0;if($indexOf&&!$isNaN(searchElement)&&$isFinite(fromIndex)&&void 0!==searchElement)return $indexOf.apply(this,arguments)>-1;var O=ToObject(this),length=ToLength(O.length);if(0===length)return!1;for(var k=fromIndex>=0?fromIndex:$max(0,length+fromIndex);k0&&void 0!==arguments[0]&&(depthNum=ToIntegerOrInfinity(arguments[0]));var A=ArraySpeciesCreate(O,0);return FlattenIntoArray(A,O,sourceLen,0,depthNum),A}},"./node_modules/array.prototype.flat/polyfill.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var implementation=__webpack_require__("./node_modules/array.prototype.flat/implementation.js");module.exports=function getPolyfill(){return Array.prototype.flat||implementation}},"./node_modules/array.prototype.flat/shim.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var define=__webpack_require__("./node_modules/define-properties/index.js"),shimUnscopables=__webpack_require__("./node_modules/es-shim-unscopables/index.js"),getPolyfill=__webpack_require__("./node_modules/array.prototype.flat/polyfill.js");module.exports=function shimFlat(){var polyfill=getPolyfill();return define(Array.prototype,{flat:polyfill},{flat:function(){return Array.prototype.flat!==polyfill}}),shimUnscopables("flat"),polyfill}},"./node_modules/array.prototype.flatmap/auto.js":function(__unused_webpack_module,__unused_webpack_exports,__webpack_require__){"use strict";__webpack_require__("./node_modules/array.prototype.flatmap/shim.js")()},"./node_modules/array.prototype.flatmap/implementation.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var ArraySpeciesCreate=__webpack_require__("./node_modules/es-abstract/2021/ArraySpeciesCreate.js"),FlattenIntoArray=__webpack_require__("./node_modules/es-abstract/2021/FlattenIntoArray.js"),Get=__webpack_require__("./node_modules/es-abstract/2021/Get.js"),IsCallable=__webpack_require__("./node_modules/es-abstract/2021/IsCallable.js"),ToLength=__webpack_require__("./node_modules/es-abstract/2021/ToLength.js"),ToObject=__webpack_require__("./node_modules/es-abstract/2021/ToObject.js");module.exports=function flatMap(mapperFunction){var T,O=ToObject(this),sourceLen=ToLength(Get(O,"length"));if(!IsCallable(mapperFunction))throw new TypeError("mapperFunction must be a function");arguments.length>1&&(T=arguments[1]);var A=ArraySpeciesCreate(O,0);return FlattenIntoArray(A,O,sourceLen,0,1,mapperFunction,T),A}},"./node_modules/array.prototype.flatmap/polyfill.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var implementation=__webpack_require__("./node_modules/array.prototype.flatmap/implementation.js");module.exports=function getPolyfill(){return Array.prototype.flatMap||implementation}},"./node_modules/array.prototype.flatmap/shim.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var define=__webpack_require__("./node_modules/define-properties/index.js"),shimUnscopables=__webpack_require__("./node_modules/es-shim-unscopables/index.js"),getPolyfill=__webpack_require__("./node_modules/array.prototype.flatmap/polyfill.js");module.exports=function shimFlatMap(){var polyfill=getPolyfill();return define(Array.prototype,{flatMap:polyfill},{flatMap:function(){return Array.prototype.flatMap!==polyfill}}),shimUnscopables("flatMap"),polyfill}},"./node_modules/array.prototype.map/implementation.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var ArraySpeciesCreate=__webpack_require__("./node_modules/es-abstract/2021/ArraySpeciesCreate.js"),Call=__webpack_require__("./node_modules/es-abstract/2021/Call.js"),CreateDataPropertyOrThrow=__webpack_require__("./node_modules/es-abstract/2021/CreateDataPropertyOrThrow.js"),Get=__webpack_require__("./node_modules/es-abstract/2021/Get.js"),HasProperty=__webpack_require__("./node_modules/es-abstract/2021/HasProperty.js"),IsCallable=__webpack_require__("./node_modules/es-abstract/2021/IsCallable.js"),ToUint32=__webpack_require__("./node_modules/es-abstract/2021/ToUint32.js"),ToObject=__webpack_require__("./node_modules/es-abstract/2021/ToObject.js"),ToString=__webpack_require__("./node_modules/es-abstract/2021/ToString.js"),callBound=__webpack_require__("./node_modules/call-bind/callBound.js"),isString=__webpack_require__("./node_modules/is-string/index.js"),boxedString=Object("a"),splitString="a"!==boxedString[0]||!(0 in boxedString),strSplit=callBound("String.prototype.split");module.exports=function map(callbackfn){var T,O=ToObject(this),self=splitString&&isString(O)?strSplit(O,""):O,len=ToUint32(self.length);if(!IsCallable(callbackfn))throw new TypeError("Array.prototype.map callback must be a function");arguments.length>1&&(T=arguments[1]);for(var A=ArraySpeciesCreate(O,len),k=0;k1)accumulator=arguments[1];else{for(kPresent=!1;!kPresent&&k=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(!_deepEqual(a[key=ka[i]],b[key],strict,actualVisitedObjects))return!1;return!0}(actual,expected,strict,memos))}return strict?actual===expected:actual==expected}function isArguments(object){return"[object Arguments]"==Object.prototype.toString.call(object)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnexpectedException=!shouldThrow&&actual&&!expected;if((!shouldThrow&&util.isError(actual)&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}assert.AssertionError=function AssertionError(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=function getMessage(self){return truncate(inspect(self.actual),128)+" "+self.operator+" "+truncate(inspect(self.expected),128)}(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function equal(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function notEqual(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function deepEqual(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function deepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function notDeepEqual(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)},assert.strictEqual=function strictEqual(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function notStrictEqual(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err},assert.strict=objectAssign((function strict(value,message){value||fail(value,!0,message,"==",strict)}),assert,{equal:assert.strictEqual,deepEqual:assert.deepStrictEqual,notEqual:assert.notStrictEqual,notDeepEqual:assert.notDeepStrictEqual}),assert.strict.strict=assert.strict;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}},"./node_modules/assert/node_modules/inherits/inherits_browser.js":function(module){"function"==typeof Object.create?module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},"./node_modules/assert/node_modules/util/support/isBufferBrowser.js":function(module){module.exports=function isBuffer(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},"./node_modules/assert/node_modules/util/util.js":function(__unused_webpack_module,exports,__webpack_require__){var process=__webpack_require__("./node_modules/process/browser.js"),formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}})),x=args[i];i=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=function arrayToHash(array){var hash={};return array.forEach((function(val,idx){hash[val]=!0})),hash}(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var output,base="",array=!1,braces=["{","}"];(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value))&&(base=" [Function"+(value.name?": "+value.name:"")+"]");return isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0!==keys.length||array&&0!=value.length?recurseTimes<0?isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special"):(ctx.seen.push(value),output=array?function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i=0&&0,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1}),0)>60)return braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1];return braces[0]+base+" "+output.join(", ")+" "+braces[1]}(output,base,braces)):braces[0]+base+braces[1]}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if((desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]}).get?str=desc.set?ctx.stylize("[Getter/Setter]","special"):ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(ctx.seen.indexOf(desc.value)<0?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1)).indexOf("\n")>-1&&(str=array?str.split("\n").map((function(line){return" "+line})).join("\n").substr(2):"\n"+str.split("\n").map((function(line){return" "+line})).join("\n")):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;(name=JSON.stringify(""+key)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!debugs[set])if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=function isNullOrUndefined(arg){return null==arg},exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=function isSymbol(arg){return"symbol"==typeof arg},exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg},exports.isBuffer=__webpack_require__("./node_modules/assert/node_modules/util/support/isBufferBrowser.js");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=__webpack_require__("./node_modules/assert/node_modules/inherits/inherits_browser.js"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}},"./node_modules/call-bind/callBound.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var GetIntrinsic=__webpack_require__("./node_modules/get-intrinsic/index.js"),callBind=__webpack_require__("./node_modules/call-bind/index.js"),$indexOf=callBind(GetIntrinsic("String.prototype.indexOf"));module.exports=function callBoundIntrinsic(name,allowMissing){var intrinsic=GetIntrinsic(name,!!allowMissing);return"function"==typeof intrinsic&&$indexOf(name,".prototype.")>-1?callBind(intrinsic):intrinsic}},"./node_modules/call-bind/index.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var bind=__webpack_require__("./node_modules/function-bind/index.js"),GetIntrinsic=__webpack_require__("./node_modules/get-intrinsic/index.js"),$apply=GetIntrinsic("%Function.prototype.apply%"),$call=GetIntrinsic("%Function.prototype.call%"),$reflectApply=GetIntrinsic("%Reflect.apply%",!0)||bind.call($call,$apply),$gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%",!0),$defineProperty=GetIntrinsic("%Object.defineProperty%",!0),$max=GetIntrinsic("%Math.max%");if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=null}module.exports=function callBind(originalFunction){var func=$reflectApply(bind,$call,arguments);if($gOPD&&$defineProperty){var desc=$gOPD(func,"length");desc.configurable&&$defineProperty(func,"length",{value:1+$max(0,originalFunction.length-(arguments.length-1))})}return func};var applyBind=function applyBind(){return $reflectApply(bind,$apply,arguments)};$defineProperty?$defineProperty(module.exports,"apply",{value:applyBind}):module.exports.apply=applyBind},"./node_modules/core-js/actual/symbol/index.js":function(module,__unused_webpack_exports,__webpack_require__){var parent=__webpack_require__("./node_modules/core-js/stable/symbol/index.js");module.exports=parent},"./node_modules/core-js/es/symbol/index.js":function(module,__unused_webpack_exports,__webpack_require__){__webpack_require__("./node_modules/core-js/modules/es.array.concat.js"),__webpack_require__("./node_modules/core-js/modules/es.object.to-string.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.async-iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.description.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.has-instance.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.is-concat-spreadable.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.iterator.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.match.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.match-all.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.replace.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.search.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.species.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.split.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.to-primitive.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.to-string-tag.js"),__webpack_require__("./node_modules/core-js/modules/es.symbol.unscopables.js"),__webpack_require__("./node_modules/core-js/modules/es.json.to-string-tag.js"),__webpack_require__("./node_modules/core-js/modules/es.math.to-string-tag.js"),__webpack_require__("./node_modules/core-js/modules/es.reflect.to-string-tag.js");var path=__webpack_require__("./node_modules/core-js/internals/path.js");module.exports=path.Symbol},"./node_modules/core-js/features/symbol/index.js":function(module,__unused_webpack_exports,__webpack_require__){__webpack_require__("./node_modules/core-js/full/symbol/index.js")},"./node_modules/core-js/full/symbol/index.js":function(module,__unused_webpack_exports,__webpack_require__){var parent=__webpack_require__("./node_modules/core-js/actual/symbol/index.js");__webpack_require__("./node_modules/core-js/modules/esnext.symbol.async-dispose.js"),__webpack_require__("./node_modules/core-js/modules/esnext.symbol.dispose.js"),__webpack_require__("./node_modules/core-js/modules/esnext.symbol.matcher.js"),__webpack_require__("./node_modules/core-js/modules/esnext.symbol.metadata-key.js"),__webpack_require__("./node_modules/core-js/modules/esnext.symbol.observable.js"),__webpack_require__("./node_modules/core-js/modules/esnext.symbol.metadata.js"),__webpack_require__("./node_modules/core-js/modules/esnext.symbol.pattern-match.js"),__webpack_require__("./node_modules/core-js/modules/esnext.symbol.replace-all.js"),module.exports=parent},"./node_modules/core-js/internals/a-callable.js":function(module,__unused_webpack_exports,__webpack_require__){var isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),tryToString=__webpack_require__("./node_modules/core-js/internals/try-to-string.js"),$TypeError=TypeError;module.exports=function(argument){if(isCallable(argument))return argument;throw $TypeError(tryToString(argument)+" is not a function")}},"./node_modules/core-js/internals/a-constructor.js":function(module,__unused_webpack_exports,__webpack_require__){var isConstructor=__webpack_require__("./node_modules/core-js/internals/is-constructor.js"),tryToString=__webpack_require__("./node_modules/core-js/internals/try-to-string.js"),$TypeError=TypeError;module.exports=function(argument){if(isConstructor(argument))return argument;throw $TypeError(tryToString(argument)+" is not a constructor")}},"./node_modules/core-js/internals/a-possible-prototype.js":function(module,__unused_webpack_exports,__webpack_require__){var isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),$String=String,$TypeError=TypeError;module.exports=function(argument){if("object"==typeof argument||isCallable(argument))return argument;throw $TypeError("Can't set "+$String(argument)+" as a prototype")}},"./node_modules/core-js/internals/add-to-unscopables.js":function(module,__unused_webpack_exports,__webpack_require__){var wellKnownSymbol=__webpack_require__("./node_modules/core-js/internals/well-known-symbol.js"),create=__webpack_require__("./node_modules/core-js/internals/object-create.js"),defineProperty=__webpack_require__("./node_modules/core-js/internals/object-define-property.js").f,UNSCOPABLES=wellKnownSymbol("unscopables"),ArrayPrototype=Array.prototype;null==ArrayPrototype[UNSCOPABLES]&&defineProperty(ArrayPrototype,UNSCOPABLES,{configurable:!0,value:create(null)}),module.exports=function(key){ArrayPrototype[UNSCOPABLES][key]=!0}},"./node_modules/core-js/internals/advance-string-index.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var charAt=__webpack_require__("./node_modules/core-js/internals/string-multibyte.js").charAt;module.exports=function(S,index,unicode){return index+(unicode?charAt(S,index).length:1)}},"./node_modules/core-js/internals/an-instance.js":function(module,__unused_webpack_exports,__webpack_require__){var isPrototypeOf=__webpack_require__("./node_modules/core-js/internals/object-is-prototype-of.js"),$TypeError=TypeError;module.exports=function(it,Prototype){if(isPrototypeOf(Prototype,it))return it;throw $TypeError("Incorrect invocation")}},"./node_modules/core-js/internals/an-object.js":function(module,__unused_webpack_exports,__webpack_require__){var isObject=__webpack_require__("./node_modules/core-js/internals/is-object.js"),$String=String,$TypeError=TypeError;module.exports=function(argument){if(isObject(argument))return argument;throw $TypeError($String(argument)+" is not an object")}},"./node_modules/core-js/internals/array-buffer-non-extensible.js":function(module,__unused_webpack_exports,__webpack_require__){var fails=__webpack_require__("./node_modules/core-js/internals/fails.js");module.exports=fails((function(){if("function"==typeof ArrayBuffer){var buffer=new ArrayBuffer(8);Object.isExtensible(buffer)&&Object.defineProperty(buffer,"a",{value:8})}}))},"./node_modules/core-js/internals/array-fill.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var toObject=__webpack_require__("./node_modules/core-js/internals/to-object.js"),toAbsoluteIndex=__webpack_require__("./node_modules/core-js/internals/to-absolute-index.js"),lengthOfArrayLike=__webpack_require__("./node_modules/core-js/internals/length-of-array-like.js");module.exports=function fill(value){for(var O=toObject(this),length=lengthOfArrayLike(O),argumentsLength=arguments.length,index=toAbsoluteIndex(argumentsLength>1?arguments[1]:void 0,length),end=argumentsLength>2?arguments[2]:void 0,endPos=void 0===end?length:toAbsoluteIndex(end,length);endPos>index;)O[index++]=value;return O}},"./node_modules/core-js/internals/array-for-each.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var $forEach=__webpack_require__("./node_modules/core-js/internals/array-iteration.js").forEach,STRICT_METHOD=__webpack_require__("./node_modules/core-js/internals/array-method-is-strict.js")("forEach");module.exports=STRICT_METHOD?[].forEach:function forEach(callbackfn){return $forEach(this,callbackfn,arguments.length>1?arguments[1]:void 0)}},"./node_modules/core-js/internals/array-from.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var bind=__webpack_require__("./node_modules/core-js/internals/function-bind-context.js"),call=__webpack_require__("./node_modules/core-js/internals/function-call.js"),toObject=__webpack_require__("./node_modules/core-js/internals/to-object.js"),callWithSafeIterationClosing=__webpack_require__("./node_modules/core-js/internals/call-with-safe-iteration-closing.js"),isArrayIteratorMethod=__webpack_require__("./node_modules/core-js/internals/is-array-iterator-method.js"),isConstructor=__webpack_require__("./node_modules/core-js/internals/is-constructor.js"),lengthOfArrayLike=__webpack_require__("./node_modules/core-js/internals/length-of-array-like.js"),createProperty=__webpack_require__("./node_modules/core-js/internals/create-property.js"),getIterator=__webpack_require__("./node_modules/core-js/internals/get-iterator.js"),getIteratorMethod=__webpack_require__("./node_modules/core-js/internals/get-iterator-method.js"),$Array=Array;module.exports=function from(arrayLike){var O=toObject(arrayLike),IS_CONSTRUCTOR=isConstructor(this),argumentsLength=arguments.length,mapfn=argumentsLength>1?arguments[1]:void 0,mapping=void 0!==mapfn;mapping&&(mapfn=bind(mapfn,argumentsLength>2?arguments[2]:void 0));var length,result,step,iterator,next,value,iteratorMethod=getIteratorMethod(O),index=0;if(!iteratorMethod||this===$Array&&isArrayIteratorMethod(iteratorMethod))for(length=lengthOfArrayLike(O),result=IS_CONSTRUCTOR?new this(length):$Array(length);length>index;index++)value=mapping?mapfn(O[index],index):O[index],createProperty(result,index,value);else for(next=(iterator=getIterator(O,iteratorMethod)).next,result=IS_CONSTRUCTOR?new this:[];!(step=call(next,iterator)).done;index++)value=mapping?callWithSafeIterationClosing(iterator,mapfn,[step.value,index],!0):step.value,createProperty(result,index,value);return result.length=index,result}},"./node_modules/core-js/internals/array-includes.js":function(module,__unused_webpack_exports,__webpack_require__){var toIndexedObject=__webpack_require__("./node_modules/core-js/internals/to-indexed-object.js"),toAbsoluteIndex=__webpack_require__("./node_modules/core-js/internals/to-absolute-index.js"),lengthOfArrayLike=__webpack_require__("./node_modules/core-js/internals/length-of-array-like.js"),createMethod=function(IS_INCLUDES){return function($this,el,fromIndex){var value,O=toIndexedObject($this),length=lengthOfArrayLike(O),index=toAbsoluteIndex(fromIndex,length);if(IS_INCLUDES&&el!=el){for(;length>index;)if((value=O[index++])!=value)return!0}else for(;length>index;index++)if((IS_INCLUDES||index in O)&&O[index]===el)return IS_INCLUDES||index||0;return!IS_INCLUDES&&-1}};module.exports={includes:createMethod(!0),indexOf:createMethod(!1)}},"./node_modules/core-js/internals/array-iteration.js":function(module,__unused_webpack_exports,__webpack_require__){var bind=__webpack_require__("./node_modules/core-js/internals/function-bind-context.js"),uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),IndexedObject=__webpack_require__("./node_modules/core-js/internals/indexed-object.js"),toObject=__webpack_require__("./node_modules/core-js/internals/to-object.js"),lengthOfArrayLike=__webpack_require__("./node_modules/core-js/internals/length-of-array-like.js"),arraySpeciesCreate=__webpack_require__("./node_modules/core-js/internals/array-species-create.js"),push=uncurryThis([].push),createMethod=function(TYPE){var IS_MAP=1==TYPE,IS_FILTER=2==TYPE,IS_SOME=3==TYPE,IS_EVERY=4==TYPE,IS_FIND_INDEX=6==TYPE,IS_FILTER_REJECT=7==TYPE,NO_HOLES=5==TYPE||IS_FIND_INDEX;return function($this,callbackfn,that,specificCreate){for(var value,result,O=toObject($this),self=IndexedObject(O),boundFunction=bind(callbackfn,that),length=lengthOfArrayLike(self),index=0,create=specificCreate||arraySpeciesCreate,target=IS_MAP?create($this,length):IS_FILTER||IS_FILTER_REJECT?create($this,0):void 0;length>index;index++)if((NO_HOLES||index in self)&&(result=boundFunction(value=self[index],index,O),TYPE))if(IS_MAP)target[index]=result;else if(result)switch(TYPE){case 3:return!0;case 5:return value;case 6:return index;case 2:push(target,value)}else switch(TYPE){case 4:return!1;case 7:push(target,value)}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:target}};module.exports={forEach:createMethod(0),map:createMethod(1),filter:createMethod(2),some:createMethod(3),every:createMethod(4),find:createMethod(5),findIndex:createMethod(6),filterReject:createMethod(7)}},"./node_modules/core-js/internals/array-method-has-species-support.js":function(module,__unused_webpack_exports,__webpack_require__){var fails=__webpack_require__("./node_modules/core-js/internals/fails.js"),wellKnownSymbol=__webpack_require__("./node_modules/core-js/internals/well-known-symbol.js"),V8_VERSION=__webpack_require__("./node_modules/core-js/internals/engine-v8-version.js"),SPECIES=wellKnownSymbol("species");module.exports=function(METHOD_NAME){return V8_VERSION>=51||!fails((function(){var array=[];return(array.constructor={})[SPECIES]=function(){return{foo:1}},1!==array[METHOD_NAME](Boolean).foo}))}},"./node_modules/core-js/internals/array-method-is-strict.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var fails=__webpack_require__("./node_modules/core-js/internals/fails.js");module.exports=function(METHOD_NAME,argument){var method=[][METHOD_NAME];return!!method&&fails((function(){method.call(null,argument||function(){return 1},1)}))}},"./node_modules/core-js/internals/array-slice-simple.js":function(module,__unused_webpack_exports,__webpack_require__){var toAbsoluteIndex=__webpack_require__("./node_modules/core-js/internals/to-absolute-index.js"),lengthOfArrayLike=__webpack_require__("./node_modules/core-js/internals/length-of-array-like.js"),createProperty=__webpack_require__("./node_modules/core-js/internals/create-property.js"),$Array=Array,max=Math.max;module.exports=function(O,start,end){for(var length=lengthOfArrayLike(O),k=toAbsoluteIndex(start,length),fin=toAbsoluteIndex(void 0===end?length:end,length),result=$Array(max(fin-k,0)),n=0;k0;)array[j]=array[--j];j!==i++&&(array[j]=element)}return array},merge=function(array,left,right,comparefn){for(var llength=left.length,rlength=right.length,lindex=0,rindex=0;lindex1?arguments[1]:void 0);entry=entry?entry.next:state.first;)for(boundFunction(entry.value,entry.key,this);entry&&entry.removed;)entry=entry.previous},has:function has(key){return!!getEntry(this,key)}}),defineBuiltIns(Prototype,IS_MAP?{get:function get(key){var entry=getEntry(this,key);return entry&&entry.value},set:function set(key,value){return define(this,0===key?0:key,value)}}:{add:function add(value){return define(this,value=0===value?0:value,value)}}),DESCRIPTORS&&defineProperty(Prototype,"size",{get:function(){return getInternalState(this).size}}),Constructor},setStrong:function(Constructor,CONSTRUCTOR_NAME,IS_MAP){var ITERATOR_NAME=CONSTRUCTOR_NAME+" Iterator",getInternalCollectionState=internalStateGetterFor(CONSTRUCTOR_NAME),getInternalIteratorState=internalStateGetterFor(ITERATOR_NAME);defineIterator(Constructor,CONSTRUCTOR_NAME,(function(iterated,kind){setInternalState(this,{type:ITERATOR_NAME,target:iterated,state:getInternalCollectionState(iterated),kind:kind,last:void 0})}),(function(){for(var state=getInternalIteratorState(this),kind=state.kind,entry=state.last;entry&&entry.removed;)entry=entry.previous;return state.target&&(state.last=entry=entry?entry.next:state.state.first)?"keys"==kind?{value:entry.key,done:!1}:"values"==kind?{value:entry.value,done:!1}:{value:[entry.key,entry.value],done:!1}:(state.target=void 0,{value:void 0,done:!0})}),IS_MAP?"entries":"values",!IS_MAP,!0),setSpecies(CONSTRUCTOR_NAME)}}},"./node_modules/core-js/internals/collection-weak.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),defineBuiltIns=__webpack_require__("./node_modules/core-js/internals/define-built-ins.js"),getWeakData=__webpack_require__("./node_modules/core-js/internals/internal-metadata.js").getWeakData,anObject=__webpack_require__("./node_modules/core-js/internals/an-object.js"),isObject=__webpack_require__("./node_modules/core-js/internals/is-object.js"),anInstance=__webpack_require__("./node_modules/core-js/internals/an-instance.js"),iterate=__webpack_require__("./node_modules/core-js/internals/iterate.js"),ArrayIterationModule=__webpack_require__("./node_modules/core-js/internals/array-iteration.js"),hasOwn=__webpack_require__("./node_modules/core-js/internals/has-own-property.js"),InternalStateModule=__webpack_require__("./node_modules/core-js/internals/internal-state.js"),setInternalState=InternalStateModule.set,internalStateGetterFor=InternalStateModule.getterFor,find=ArrayIterationModule.find,findIndex=ArrayIterationModule.findIndex,splice=uncurryThis([].splice),id=0,uncaughtFrozenStore=function(store){return store.frozen||(store.frozen=new UncaughtFrozenStore)},UncaughtFrozenStore=function(){this.entries=[]},findUncaughtFrozen=function(store,key){return find(store.entries,(function(it){return it[0]===key}))};UncaughtFrozenStore.prototype={get:function(key){var entry=findUncaughtFrozen(this,key);if(entry)return entry[1]},has:function(key){return!!findUncaughtFrozen(this,key)},set:function(key,value){var entry=findUncaughtFrozen(this,key);entry?entry[1]=value:this.entries.push([key,value])},delete:function(key){var index=findIndex(this.entries,(function(it){return it[0]===key}));return~index&&splice(this.entries,index,1),!!~index}},module.exports={getConstructor:function(wrapper,CONSTRUCTOR_NAME,IS_MAP,ADDER){var Constructor=wrapper((function(that,iterable){anInstance(that,Prototype),setInternalState(that,{type:CONSTRUCTOR_NAME,id:id++,frozen:void 0}),null!=iterable&&iterate(iterable,that[ADDER],{that:that,AS_ENTRIES:IS_MAP})})),Prototype=Constructor.prototype,getInternalState=internalStateGetterFor(CONSTRUCTOR_NAME),define=function(that,key,value){var state=getInternalState(that),data=getWeakData(anObject(key),!0);return!0===data?uncaughtFrozenStore(state).set(key,value):data[state.id]=value,that};return defineBuiltIns(Prototype,{delete:function(key){var state=getInternalState(this);if(!isObject(key))return!1;var data=getWeakData(key);return!0===data?uncaughtFrozenStore(state).delete(key):data&&hasOwn(data,state.id)&&delete data[state.id]},has:function has(key){var state=getInternalState(this);if(!isObject(key))return!1;var data=getWeakData(key);return!0===data?uncaughtFrozenStore(state).has(key):data&&hasOwn(data,state.id)}}),defineBuiltIns(Prototype,IS_MAP?{get:function get(key){var state=getInternalState(this);if(isObject(key)){var data=getWeakData(key);return!0===data?uncaughtFrozenStore(state).get(key):data?data[state.id]:void 0}},set:function set(key,value){return define(this,key,value)}}:{add:function add(value){return define(this,value,!0)}}),Constructor}}},"./node_modules/core-js/internals/collection.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var $=__webpack_require__("./node_modules/core-js/internals/export.js"),global=__webpack_require__("./node_modules/core-js/internals/global.js"),uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),isForced=__webpack_require__("./node_modules/core-js/internals/is-forced.js"),defineBuiltIn=__webpack_require__("./node_modules/core-js/internals/define-built-in.js"),InternalMetadataModule=__webpack_require__("./node_modules/core-js/internals/internal-metadata.js"),iterate=__webpack_require__("./node_modules/core-js/internals/iterate.js"),anInstance=__webpack_require__("./node_modules/core-js/internals/an-instance.js"),isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),isObject=__webpack_require__("./node_modules/core-js/internals/is-object.js"),fails=__webpack_require__("./node_modules/core-js/internals/fails.js"),checkCorrectnessOfIteration=__webpack_require__("./node_modules/core-js/internals/check-correctness-of-iteration.js"),setToStringTag=__webpack_require__("./node_modules/core-js/internals/set-to-string-tag.js"),inheritIfRequired=__webpack_require__("./node_modules/core-js/internals/inherit-if-required.js");module.exports=function(CONSTRUCTOR_NAME,wrapper,common){var IS_MAP=-1!==CONSTRUCTOR_NAME.indexOf("Map"),IS_WEAK=-1!==CONSTRUCTOR_NAME.indexOf("Weak"),ADDER=IS_MAP?"set":"add",NativeConstructor=global[CONSTRUCTOR_NAME],NativePrototype=NativeConstructor&&NativeConstructor.prototype,Constructor=NativeConstructor,exported={},fixMethod=function(KEY){var uncurriedNativeMethod=uncurryThis(NativePrototype[KEY]);defineBuiltIn(NativePrototype,KEY,"add"==KEY?function add(value){return uncurriedNativeMethod(this,0===value?0:value),this}:"delete"==KEY?function(key){return!(IS_WEAK&&!isObject(key))&&uncurriedNativeMethod(this,0===key?0:key)}:"get"==KEY?function get(key){return IS_WEAK&&!isObject(key)?void 0:uncurriedNativeMethod(this,0===key?0:key)}:"has"==KEY?function has(key){return!(IS_WEAK&&!isObject(key))&&uncurriedNativeMethod(this,0===key?0:key)}:function set(key,value){return uncurriedNativeMethod(this,0===key?0:key,value),this})};if(isForced(CONSTRUCTOR_NAME,!isCallable(NativeConstructor)||!(IS_WEAK||NativePrototype.forEach&&!fails((function(){(new NativeConstructor).entries().next()})))))Constructor=common.getConstructor(wrapper,CONSTRUCTOR_NAME,IS_MAP,ADDER),InternalMetadataModule.enable();else if(isForced(CONSTRUCTOR_NAME,!0)){var instance=new Constructor,HASNT_CHAINING=instance[ADDER](IS_WEAK?{}:-0,1)!=instance,THROWS_ON_PRIMITIVES=fails((function(){instance.has(1)})),ACCEPT_ITERABLES=checkCorrectnessOfIteration((function(iterable){new NativeConstructor(iterable)})),BUGGY_ZERO=!IS_WEAK&&fails((function(){for(var $instance=new NativeConstructor,index=5;index--;)$instance[ADDER](index,index);return!$instance.has(-0)}));ACCEPT_ITERABLES||((Constructor=wrapper((function(dummy,iterable){anInstance(dummy,NativePrototype);var that=inheritIfRequired(new NativeConstructor,dummy,Constructor);return null!=iterable&&iterate(iterable,that[ADDER],{that:that,AS_ENTRIES:IS_MAP}),that}))).prototype=NativePrototype,NativePrototype.constructor=Constructor),(THROWS_ON_PRIMITIVES||BUGGY_ZERO)&&(fixMethod("delete"),fixMethod("has"),IS_MAP&&fixMethod("get")),(BUGGY_ZERO||HASNT_CHAINING)&&fixMethod(ADDER),IS_WEAK&&NativePrototype.clear&&delete NativePrototype.clear}return exported[CONSTRUCTOR_NAME]=Constructor,$({global:!0,constructor:!0,forced:Constructor!=NativeConstructor},exported),setToStringTag(Constructor,CONSTRUCTOR_NAME),IS_WEAK||common.setStrong(Constructor,CONSTRUCTOR_NAME,IS_MAP),Constructor}},"./node_modules/core-js/internals/copy-constructor-properties.js":function(module,__unused_webpack_exports,__webpack_require__){var hasOwn=__webpack_require__("./node_modules/core-js/internals/has-own-property.js"),ownKeys=__webpack_require__("./node_modules/core-js/internals/own-keys.js"),getOwnPropertyDescriptorModule=__webpack_require__("./node_modules/core-js/internals/object-get-own-property-descriptor.js"),definePropertyModule=__webpack_require__("./node_modules/core-js/internals/object-define-property.js");module.exports=function(target,source,exceptions){for(var keys=ownKeys(source),defineProperty=definePropertyModule.f,getOwnPropertyDescriptor=getOwnPropertyDescriptorModule.f,i=0;i"+S+""}},"./node_modules/core-js/internals/create-iterator-constructor.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var IteratorPrototype=__webpack_require__("./node_modules/core-js/internals/iterators-core.js").IteratorPrototype,create=__webpack_require__("./node_modules/core-js/internals/object-create.js"),createPropertyDescriptor=__webpack_require__("./node_modules/core-js/internals/create-property-descriptor.js"),setToStringTag=__webpack_require__("./node_modules/core-js/internals/set-to-string-tag.js"),Iterators=__webpack_require__("./node_modules/core-js/internals/iterators.js"),returnThis=function(){return this};module.exports=function(IteratorConstructor,NAME,next,ENUMERABLE_NEXT){var TO_STRING_TAG=NAME+" Iterator";return IteratorConstructor.prototype=create(IteratorPrototype,{next:createPropertyDescriptor(+!ENUMERABLE_NEXT,next)}),setToStringTag(IteratorConstructor,TO_STRING_TAG,!1,!0),Iterators[TO_STRING_TAG]=returnThis,IteratorConstructor}},"./node_modules/core-js/internals/create-non-enumerable-property.js":function(module,__unused_webpack_exports,__webpack_require__){var DESCRIPTORS=__webpack_require__("./node_modules/core-js/internals/descriptors.js"),definePropertyModule=__webpack_require__("./node_modules/core-js/internals/object-define-property.js"),createPropertyDescriptor=__webpack_require__("./node_modules/core-js/internals/create-property-descriptor.js");module.exports=DESCRIPTORS?function(object,key,value){return definePropertyModule.f(object,key,createPropertyDescriptor(1,value))}:function(object,key,value){return object[key]=value,object}},"./node_modules/core-js/internals/create-property-descriptor.js":function(module){module.exports=function(bitmap,value){return{enumerable:!(1&bitmap),configurable:!(2&bitmap),writable:!(4&bitmap),value:value}}},"./node_modules/core-js/internals/create-property.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var toPropertyKey=__webpack_require__("./node_modules/core-js/internals/to-property-key.js"),definePropertyModule=__webpack_require__("./node_modules/core-js/internals/object-define-property.js"),createPropertyDescriptor=__webpack_require__("./node_modules/core-js/internals/create-property-descriptor.js");module.exports=function(object,key,value){var propertyKey=toPropertyKey(key);propertyKey in object?definePropertyModule.f(object,propertyKey,createPropertyDescriptor(0,value)):object[propertyKey]=value}},"./node_modules/core-js/internals/define-built-in-accessor.js":function(module,__unused_webpack_exports,__webpack_require__){var makeBuiltIn=__webpack_require__("./node_modules/core-js/internals/make-built-in.js"),defineProperty=__webpack_require__("./node_modules/core-js/internals/object-define-property.js");module.exports=function(target,name,descriptor){return descriptor.get&&makeBuiltIn(descriptor.get,name,{getter:!0}),descriptor.set&&makeBuiltIn(descriptor.set,name,{setter:!0}),defineProperty.f(target,name,descriptor)}},"./node_modules/core-js/internals/define-built-in.js":function(module,__unused_webpack_exports,__webpack_require__){var isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),definePropertyModule=__webpack_require__("./node_modules/core-js/internals/object-define-property.js"),makeBuiltIn=__webpack_require__("./node_modules/core-js/internals/make-built-in.js"),defineGlobalProperty=__webpack_require__("./node_modules/core-js/internals/define-global-property.js");module.exports=function(O,key,value,options){options||(options={});var simple=options.enumerable,name=void 0!==options.name?options.name:key;if(isCallable(value)&&makeBuiltIn(value,name,options),options.global)simple?O[key]=value:defineGlobalProperty(key,value);else{try{options.unsafe?O[key]&&(simple=!0):delete O[key]}catch(error){}simple?O[key]=value:definePropertyModule.f(O,key,{value:value,enumerable:!1,configurable:!options.nonConfigurable,writable:!options.nonWritable})}return O}},"./node_modules/core-js/internals/define-built-ins.js":function(module,__unused_webpack_exports,__webpack_require__){var defineBuiltIn=__webpack_require__("./node_modules/core-js/internals/define-built-in.js");module.exports=function(target,src,options){for(var key in src)defineBuiltIn(target,key,src[key],options);return target}},"./node_modules/core-js/internals/define-global-property.js":function(module,__unused_webpack_exports,__webpack_require__){var global=__webpack_require__("./node_modules/core-js/internals/global.js"),defineProperty=Object.defineProperty;module.exports=function(key,value){try{defineProperty(global,key,{value:value,configurable:!0,writable:!0})}catch(error){global[key]=value}return value}},"./node_modules/core-js/internals/define-iterator.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var $=__webpack_require__("./node_modules/core-js/internals/export.js"),call=__webpack_require__("./node_modules/core-js/internals/function-call.js"),IS_PURE=__webpack_require__("./node_modules/core-js/internals/is-pure.js"),FunctionName=__webpack_require__("./node_modules/core-js/internals/function-name.js"),isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),createIteratorConstructor=__webpack_require__("./node_modules/core-js/internals/create-iterator-constructor.js"),getPrototypeOf=__webpack_require__("./node_modules/core-js/internals/object-get-prototype-of.js"),setPrototypeOf=__webpack_require__("./node_modules/core-js/internals/object-set-prototype-of.js"),setToStringTag=__webpack_require__("./node_modules/core-js/internals/set-to-string-tag.js"),createNonEnumerableProperty=__webpack_require__("./node_modules/core-js/internals/create-non-enumerable-property.js"),defineBuiltIn=__webpack_require__("./node_modules/core-js/internals/define-built-in.js"),wellKnownSymbol=__webpack_require__("./node_modules/core-js/internals/well-known-symbol.js"),Iterators=__webpack_require__("./node_modules/core-js/internals/iterators.js"),IteratorsCore=__webpack_require__("./node_modules/core-js/internals/iterators-core.js"),PROPER_FUNCTION_NAME=FunctionName.PROPER,CONFIGURABLE_FUNCTION_NAME=FunctionName.CONFIGURABLE,IteratorPrototype=IteratorsCore.IteratorPrototype,BUGGY_SAFARI_ITERATORS=IteratorsCore.BUGGY_SAFARI_ITERATORS,ITERATOR=wellKnownSymbol("iterator"),returnThis=function(){return this};module.exports=function(Iterable,NAME,IteratorConstructor,next,DEFAULT,IS_SET,FORCED){createIteratorConstructor(IteratorConstructor,NAME,next);var CurrentIteratorPrototype,methods,KEY,getIterationMethod=function(KIND){if(KIND===DEFAULT&&defaultIterator)return defaultIterator;if(!BUGGY_SAFARI_ITERATORS&&KIND in IterablePrototype)return IterablePrototype[KIND];switch(KIND){case"keys":return function keys(){return new IteratorConstructor(this,KIND)};case"values":return function values(){return new IteratorConstructor(this,KIND)};case"entries":return function entries(){return new IteratorConstructor(this,KIND)}}return function(){return new IteratorConstructor(this)}},TO_STRING_TAG=NAME+" Iterator",INCORRECT_VALUES_NAME=!1,IterablePrototype=Iterable.prototype,nativeIterator=IterablePrototype[ITERATOR]||IterablePrototype["@@iterator"]||DEFAULT&&IterablePrototype[DEFAULT],defaultIterator=!BUGGY_SAFARI_ITERATORS&&nativeIterator||getIterationMethod(DEFAULT),anyNativeIterator="Array"==NAME&&IterablePrototype.entries||nativeIterator;if(anyNativeIterator&&(CurrentIteratorPrototype=getPrototypeOf(anyNativeIterator.call(new Iterable)))!==Object.prototype&&CurrentIteratorPrototype.next&&(IS_PURE||getPrototypeOf(CurrentIteratorPrototype)===IteratorPrototype||(setPrototypeOf?setPrototypeOf(CurrentIteratorPrototype,IteratorPrototype):isCallable(CurrentIteratorPrototype[ITERATOR])||defineBuiltIn(CurrentIteratorPrototype,ITERATOR,returnThis)),setToStringTag(CurrentIteratorPrototype,TO_STRING_TAG,!0,!0),IS_PURE&&(Iterators[TO_STRING_TAG]=returnThis)),PROPER_FUNCTION_NAME&&"values"==DEFAULT&&nativeIterator&&"values"!==nativeIterator.name&&(!IS_PURE&&CONFIGURABLE_FUNCTION_NAME?createNonEnumerableProperty(IterablePrototype,"name","values"):(INCORRECT_VALUES_NAME=!0,defaultIterator=function values(){return call(nativeIterator,this)})),DEFAULT)if(methods={values:getIterationMethod("values"),keys:IS_SET?defaultIterator:getIterationMethod("keys"),entries:getIterationMethod("entries")},FORCED)for(KEY in methods)(BUGGY_SAFARI_ITERATORS||INCORRECT_VALUES_NAME||!(KEY in IterablePrototype))&&defineBuiltIn(IterablePrototype,KEY,methods[KEY]);else $({target:NAME,proto:!0,forced:BUGGY_SAFARI_ITERATORS||INCORRECT_VALUES_NAME},methods);return IS_PURE&&!FORCED||IterablePrototype[ITERATOR]===defaultIterator||defineBuiltIn(IterablePrototype,ITERATOR,defaultIterator,{name:DEFAULT}),Iterators[NAME]=defaultIterator,methods}},"./node_modules/core-js/internals/define-well-known-symbol.js":function(module,__unused_webpack_exports,__webpack_require__){var path=__webpack_require__("./node_modules/core-js/internals/path.js"),hasOwn=__webpack_require__("./node_modules/core-js/internals/has-own-property.js"),wrappedWellKnownSymbolModule=__webpack_require__("./node_modules/core-js/internals/well-known-symbol-wrapped.js"),defineProperty=__webpack_require__("./node_modules/core-js/internals/object-define-property.js").f;module.exports=function(NAME){var Symbol=path.Symbol||(path.Symbol={});hasOwn(Symbol,NAME)||defineProperty(Symbol,NAME,{value:wrappedWellKnownSymbolModule.f(NAME)})}},"./node_modules/core-js/internals/delete-property-or-throw.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var tryToString=__webpack_require__("./node_modules/core-js/internals/try-to-string.js"),$TypeError=TypeError;module.exports=function(O,P){if(!delete O[P])throw $TypeError("Cannot delete property "+tryToString(P)+" of "+tryToString(O))}},"./node_modules/core-js/internals/descriptors.js":function(module,__unused_webpack_exports,__webpack_require__){var fails=__webpack_require__("./node_modules/core-js/internals/fails.js");module.exports=!fails((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},"./node_modules/core-js/internals/document-create-element.js":function(module,__unused_webpack_exports,__webpack_require__){var global=__webpack_require__("./node_modules/core-js/internals/global.js"),isObject=__webpack_require__("./node_modules/core-js/internals/is-object.js"),document=global.document,EXISTS=isObject(document)&&isObject(document.createElement);module.exports=function(it){return EXISTS?document.createElement(it):{}}},"./node_modules/core-js/internals/does-not-exceed-safe-integer.js":function(module){var $TypeError=TypeError;module.exports=function(it){if(it>9007199254740991)throw $TypeError("Maximum allowed index exceeded");return it}},"./node_modules/core-js/internals/dom-iterables.js":function(module){module.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},"./node_modules/core-js/internals/dom-token-list-prototype.js":function(module,__unused_webpack_exports,__webpack_require__){var classList=__webpack_require__("./node_modules/core-js/internals/document-create-element.js")("span").classList,DOMTokenListPrototype=classList&&classList.constructor&&classList.constructor.prototype;module.exports=DOMTokenListPrototype===Object.prototype?void 0:DOMTokenListPrototype},"./node_modules/core-js/internals/engine-ff-version.js":function(module,__unused_webpack_exports,__webpack_require__){var firefox=__webpack_require__("./node_modules/core-js/internals/engine-user-agent.js").match(/firefox\/(\d+)/i);module.exports=!!firefox&&+firefox[1]},"./node_modules/core-js/internals/engine-is-browser.js":function(module){module.exports="object"==typeof window&&"object"!=typeof Deno},"./node_modules/core-js/internals/engine-is-ie-or-edge.js":function(module,__unused_webpack_exports,__webpack_require__){var UA=__webpack_require__("./node_modules/core-js/internals/engine-user-agent.js");module.exports=/MSIE|Trident/.test(UA)},"./node_modules/core-js/internals/engine-is-ios-pebble.js":function(module,__unused_webpack_exports,__webpack_require__){var userAgent=__webpack_require__("./node_modules/core-js/internals/engine-user-agent.js"),global=__webpack_require__("./node_modules/core-js/internals/global.js");module.exports=/ipad|iphone|ipod/i.test(userAgent)&&void 0!==global.Pebble},"./node_modules/core-js/internals/engine-is-ios.js":function(module,__unused_webpack_exports,__webpack_require__){var userAgent=__webpack_require__("./node_modules/core-js/internals/engine-user-agent.js");module.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent)},"./node_modules/core-js/internals/engine-is-node.js":function(module,__unused_webpack_exports,__webpack_require__){var classof=__webpack_require__("./node_modules/core-js/internals/classof-raw.js"),global=__webpack_require__("./node_modules/core-js/internals/global.js");module.exports="process"==classof(global.process)},"./node_modules/core-js/internals/engine-is-webos-webkit.js":function(module,__unused_webpack_exports,__webpack_require__){var userAgent=__webpack_require__("./node_modules/core-js/internals/engine-user-agent.js");module.exports=/web0s(?!.*chrome)/i.test(userAgent)},"./node_modules/core-js/internals/engine-user-agent.js":function(module,__unused_webpack_exports,__webpack_require__){var getBuiltIn=__webpack_require__("./node_modules/core-js/internals/get-built-in.js");module.exports=getBuiltIn("navigator","userAgent")||""},"./node_modules/core-js/internals/engine-v8-version.js":function(module,__unused_webpack_exports,__webpack_require__){var match,version,global=__webpack_require__("./node_modules/core-js/internals/global.js"),userAgent=__webpack_require__("./node_modules/core-js/internals/engine-user-agent.js"),process=global.process,Deno=global.Deno,versions=process&&process.versions||Deno&&Deno.version,v8=versions&&versions.v8;v8&&(version=(match=v8.split("."))[0]>0&&match[0]<4?1:+(match[0]+match[1])),!version&&userAgent&&(!(match=userAgent.match(/Edge\/(\d+)/))||match[1]>=74)&&(match=userAgent.match(/Chrome\/(\d+)/))&&(version=+match[1]),module.exports=version},"./node_modules/core-js/internals/engine-webkit-version.js":function(module,__unused_webpack_exports,__webpack_require__){var webkit=__webpack_require__("./node_modules/core-js/internals/engine-user-agent.js").match(/AppleWebKit\/(\d+)\./);module.exports=!!webkit&&+webkit[1]},"./node_modules/core-js/internals/enum-bug-keys.js":function(module){module.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},"./node_modules/core-js/internals/export.js":function(module,__unused_webpack_exports,__webpack_require__){var global=__webpack_require__("./node_modules/core-js/internals/global.js"),getOwnPropertyDescriptor=__webpack_require__("./node_modules/core-js/internals/object-get-own-property-descriptor.js").f,createNonEnumerableProperty=__webpack_require__("./node_modules/core-js/internals/create-non-enumerable-property.js"),defineBuiltIn=__webpack_require__("./node_modules/core-js/internals/define-built-in.js"),defineGlobalProperty=__webpack_require__("./node_modules/core-js/internals/define-global-property.js"),copyConstructorProperties=__webpack_require__("./node_modules/core-js/internals/copy-constructor-properties.js"),isForced=__webpack_require__("./node_modules/core-js/internals/is-forced.js");module.exports=function(options,source){var target,key,targetProperty,sourceProperty,descriptor,TARGET=options.target,GLOBAL=options.global,STATIC=options.stat;if(target=GLOBAL?global:STATIC?global[TARGET]||defineGlobalProperty(TARGET,{}):(global[TARGET]||{}).prototype)for(key in source){if(sourceProperty=source[key],targetProperty=options.dontCallGetSet?(descriptor=getOwnPropertyDescriptor(target,key))&&descriptor.value:target[key],!isForced(GLOBAL?key:TARGET+(STATIC?".":"#")+key,options.forced)&&void 0!==targetProperty){if(typeof sourceProperty==typeof targetProperty)continue;copyConstructorProperties(sourceProperty,targetProperty)}(options.sham||targetProperty&&targetProperty.sham)&&createNonEnumerableProperty(sourceProperty,"sham",!0),defineBuiltIn(target,key,sourceProperty,options)}}},"./node_modules/core-js/internals/fails.js":function(module){module.exports=function(exec){try{return!!exec()}catch(error){return!0}}},"./node_modules/core-js/internals/fix-regexp-well-known-symbol-logic.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";__webpack_require__("./node_modules/core-js/modules/es.regexp.exec.js");var uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),defineBuiltIn=__webpack_require__("./node_modules/core-js/internals/define-built-in.js"),regexpExec=__webpack_require__("./node_modules/core-js/internals/regexp-exec.js"),fails=__webpack_require__("./node_modules/core-js/internals/fails.js"),wellKnownSymbol=__webpack_require__("./node_modules/core-js/internals/well-known-symbol.js"),createNonEnumerableProperty=__webpack_require__("./node_modules/core-js/internals/create-non-enumerable-property.js"),SPECIES=wellKnownSymbol("species"),RegExpPrototype=RegExp.prototype;module.exports=function(KEY,exec,FORCED,SHAM){var SYMBOL=wellKnownSymbol(KEY),DELEGATES_TO_SYMBOL=!fails((function(){var O={};return O[SYMBOL]=function(){return 7},7!=""[KEY](O)})),DELEGATES_TO_EXEC=DELEGATES_TO_SYMBOL&&!fails((function(){var execCalled=!1,re=/a/;return"split"===KEY&&((re={}).constructor={},re.constructor[SPECIES]=function(){return re},re.flags="",re[SYMBOL]=/./[SYMBOL]),re.exec=function(){return execCalled=!0,null},re[SYMBOL](""),!execCalled}));if(!DELEGATES_TO_SYMBOL||!DELEGATES_TO_EXEC||FORCED){var uncurriedNativeRegExpMethod=uncurryThis(/./[SYMBOL]),methods=exec(SYMBOL,""[KEY],(function(nativeMethod,regexp,str,arg2,forceStringMethod){var uncurriedNativeMethod=uncurryThis(nativeMethod),$exec=regexp.exec;return $exec===regexpExec||$exec===RegExpPrototype.exec?DELEGATES_TO_SYMBOL&&!forceStringMethod?{done:!0,value:uncurriedNativeRegExpMethod(regexp,str,arg2)}:{done:!0,value:uncurriedNativeMethod(str,regexp,arg2)}:{done:!1}}));defineBuiltIn(String.prototype,KEY,methods[0]),defineBuiltIn(RegExpPrototype,SYMBOL,methods[1])}SHAM&&createNonEnumerableProperty(RegExpPrototype[SYMBOL],"sham",!0)}},"./node_modules/core-js/internals/freezing.js":function(module,__unused_webpack_exports,__webpack_require__){var fails=__webpack_require__("./node_modules/core-js/internals/fails.js");module.exports=!fails((function(){return Object.isExtensible(Object.preventExtensions({}))}))},"./node_modules/core-js/internals/function-apply.js":function(module,__unused_webpack_exports,__webpack_require__){var NATIVE_BIND=__webpack_require__("./node_modules/core-js/internals/function-bind-native.js"),FunctionPrototype=Function.prototype,apply=FunctionPrototype.apply,call=FunctionPrototype.call;module.exports="object"==typeof Reflect&&Reflect.apply||(NATIVE_BIND?call.bind(apply):function(){return call.apply(apply,arguments)})},"./node_modules/core-js/internals/function-bind-context.js":function(module,__unused_webpack_exports,__webpack_require__){var uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),aCallable=__webpack_require__("./node_modules/core-js/internals/a-callable.js"),NATIVE_BIND=__webpack_require__("./node_modules/core-js/internals/function-bind-native.js"),bind=uncurryThis(uncurryThis.bind);module.exports=function(fn,that){return aCallable(fn),void 0===that?fn:NATIVE_BIND?bind(fn,that):function(){return fn.apply(that,arguments)}}},"./node_modules/core-js/internals/function-bind-native.js":function(module,__unused_webpack_exports,__webpack_require__){var fails=__webpack_require__("./node_modules/core-js/internals/fails.js");module.exports=!fails((function(){var test=function(){}.bind();return"function"!=typeof test||test.hasOwnProperty("prototype")}))},"./node_modules/core-js/internals/function-bind.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),aCallable=__webpack_require__("./node_modules/core-js/internals/a-callable.js"),isObject=__webpack_require__("./node_modules/core-js/internals/is-object.js"),hasOwn=__webpack_require__("./node_modules/core-js/internals/has-own-property.js"),arraySlice=__webpack_require__("./node_modules/core-js/internals/array-slice.js"),NATIVE_BIND=__webpack_require__("./node_modules/core-js/internals/function-bind-native.js"),$Function=Function,concat=uncurryThis([].concat),join=uncurryThis([].join),factories={},construct=function(C,argsLength,args){if(!hasOwn(factories,argsLength)){for(var list=[],i=0;i]*>)/g,SUBSTITUTION_SYMBOLS_NO_NAMED=/\$([$&'`]|\d{1,2})/g;module.exports=function(matched,str,position,captures,namedCaptures,replacement){var tailPos=position+matched.length,m=captures.length,symbols=SUBSTITUTION_SYMBOLS_NO_NAMED;return void 0!==namedCaptures&&(namedCaptures=toObject(namedCaptures),symbols=SUBSTITUTION_SYMBOLS),replace(replacement,symbols,(function(match,ch){var capture;switch(charAt(ch,0)){case"$":return"$";case"&":return matched;case"`":return stringSlice(str,0,position);case"'":return stringSlice(str,tailPos);case"<":capture=namedCaptures[stringSlice(ch,1,-1)];break;default:var n=+ch;if(0===n)return match;if(n>m){var f=floor(n/10);return 0===f?match:f<=m?void 0===captures[f-1]?charAt(ch,1):captures[f-1]+charAt(ch,1):match}capture=captures[n-1]}return void 0===capture?"":capture}))}},"./node_modules/core-js/internals/global.js":function(module,__unused_webpack_exports,__webpack_require__){var check=function(it){return it&&it.Math==Math&&it};module.exports=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof __webpack_require__.g&&__webpack_require__.g)||function(){return this}()||Function("return this")()},"./node_modules/core-js/internals/has-own-property.js":function(module,__unused_webpack_exports,__webpack_require__){var uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),toObject=__webpack_require__("./node_modules/core-js/internals/to-object.js"),hasOwnProperty=uncurryThis({}.hasOwnProperty);module.exports=Object.hasOwn||function hasOwn(it,key){return hasOwnProperty(toObject(it),key)}},"./node_modules/core-js/internals/hidden-keys.js":function(module){module.exports={}},"./node_modules/core-js/internals/host-report-errors.js":function(module,__unused_webpack_exports,__webpack_require__){var global=__webpack_require__("./node_modules/core-js/internals/global.js");module.exports=function(a,b){var console=global.console;console&&console.error&&(1==arguments.length?console.error(a):console.error(a,b))}},"./node_modules/core-js/internals/html.js":function(module,__unused_webpack_exports,__webpack_require__){var getBuiltIn=__webpack_require__("./node_modules/core-js/internals/get-built-in.js");module.exports=getBuiltIn("document","documentElement")},"./node_modules/core-js/internals/ie8-dom-define.js":function(module,__unused_webpack_exports,__webpack_require__){var DESCRIPTORS=__webpack_require__("./node_modules/core-js/internals/descriptors.js"),fails=__webpack_require__("./node_modules/core-js/internals/fails.js"),createElement=__webpack_require__("./node_modules/core-js/internals/document-create-element.js");module.exports=!DESCRIPTORS&&!fails((function(){return 7!=Object.defineProperty(createElement("div"),"a",{get:function(){return 7}}).a}))},"./node_modules/core-js/internals/indexed-object.js":function(module,__unused_webpack_exports,__webpack_require__){var uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),fails=__webpack_require__("./node_modules/core-js/internals/fails.js"),classof=__webpack_require__("./node_modules/core-js/internals/classof-raw.js"),$Object=Object,split=uncurryThis("".split);module.exports=fails((function(){return!$Object("z").propertyIsEnumerable(0)}))?function(it){return"String"==classof(it)?split(it,""):$Object(it)}:$Object},"./node_modules/core-js/internals/inherit-if-required.js":function(module,__unused_webpack_exports,__webpack_require__){var isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),isObject=__webpack_require__("./node_modules/core-js/internals/is-object.js"),setPrototypeOf=__webpack_require__("./node_modules/core-js/internals/object-set-prototype-of.js");module.exports=function($this,dummy,Wrapper){var NewTarget,NewTargetPrototype;return setPrototypeOf&&isCallable(NewTarget=dummy.constructor)&&NewTarget!==Wrapper&&isObject(NewTargetPrototype=NewTarget.prototype)&&NewTargetPrototype!==Wrapper.prototype&&setPrototypeOf($this,NewTargetPrototype),$this}},"./node_modules/core-js/internals/inspect-source.js":function(module,__unused_webpack_exports,__webpack_require__){var uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),store=__webpack_require__("./node_modules/core-js/internals/shared-store.js"),functionToString=uncurryThis(Function.toString);isCallable(store.inspectSource)||(store.inspectSource=function(it){return functionToString(it)}),module.exports=store.inspectSource},"./node_modules/core-js/internals/internal-metadata.js":function(module,__unused_webpack_exports,__webpack_require__){var $=__webpack_require__("./node_modules/core-js/internals/export.js"),uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),hiddenKeys=__webpack_require__("./node_modules/core-js/internals/hidden-keys.js"),isObject=__webpack_require__("./node_modules/core-js/internals/is-object.js"),hasOwn=__webpack_require__("./node_modules/core-js/internals/has-own-property.js"),defineProperty=__webpack_require__("./node_modules/core-js/internals/object-define-property.js").f,getOwnPropertyNamesModule=__webpack_require__("./node_modules/core-js/internals/object-get-own-property-names.js"),getOwnPropertyNamesExternalModule=__webpack_require__("./node_modules/core-js/internals/object-get-own-property-names-external.js"),isExtensible=__webpack_require__("./node_modules/core-js/internals/object-is-extensible.js"),uid=__webpack_require__("./node_modules/core-js/internals/uid.js"),FREEZING=__webpack_require__("./node_modules/core-js/internals/freezing.js"),REQUIRED=!1,METADATA=uid("meta"),id=0,setMetadata=function(it){defineProperty(it,METADATA,{value:{objectID:"O"+id++,weakData:{}}})},meta=module.exports={enable:function(){meta.enable=function(){},REQUIRED=!0;var getOwnPropertyNames=getOwnPropertyNamesModule.f,splice=uncurryThis([].splice),test={};test[METADATA]=1,getOwnPropertyNames(test).length&&(getOwnPropertyNamesModule.f=function(it){for(var result=getOwnPropertyNames(it),i=0,length=result.length;iindex;index++)if((result=callFn(iterable[index]))&&isPrototypeOf(ResultPrototype,result))return result;return new Result(!1)}iterator=getIterator(iterable,iterFn)}for(next=iterator.next;!(step=call(next,iterator)).done;){try{result=callFn(step.value)}catch(error){iteratorClose(iterator,"throw",error)}if("object"==typeof result&&result&&isPrototypeOf(ResultPrototype,result))return result}return new Result(!1)}},"./node_modules/core-js/internals/iterator-close.js":function(module,__unused_webpack_exports,__webpack_require__){var call=__webpack_require__("./node_modules/core-js/internals/function-call.js"),anObject=__webpack_require__("./node_modules/core-js/internals/an-object.js"),getMethod=__webpack_require__("./node_modules/core-js/internals/get-method.js");module.exports=function(iterator,kind,value){var innerResult,innerError;anObject(iterator);try{if(!(innerResult=getMethod(iterator,"return"))){if("throw"===kind)throw value;return value}innerResult=call(innerResult,iterator)}catch(error){innerError=!0,innerResult=error}if("throw"===kind)throw value;if(innerError)throw innerResult;return anObject(innerResult),value}},"./node_modules/core-js/internals/iterators-core.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var IteratorPrototype,PrototypeOfArrayIteratorPrototype,arrayIterator,fails=__webpack_require__("./node_modules/core-js/internals/fails.js"),isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),create=__webpack_require__("./node_modules/core-js/internals/object-create.js"),getPrototypeOf=__webpack_require__("./node_modules/core-js/internals/object-get-prototype-of.js"),defineBuiltIn=__webpack_require__("./node_modules/core-js/internals/define-built-in.js"),wellKnownSymbol=__webpack_require__("./node_modules/core-js/internals/well-known-symbol.js"),IS_PURE=__webpack_require__("./node_modules/core-js/internals/is-pure.js"),ITERATOR=wellKnownSymbol("iterator"),BUGGY_SAFARI_ITERATORS=!1;[].keys&&("next"in(arrayIterator=[].keys())?(PrototypeOfArrayIteratorPrototype=getPrototypeOf(getPrototypeOf(arrayIterator)))!==Object.prototype&&(IteratorPrototype=PrototypeOfArrayIteratorPrototype):BUGGY_SAFARI_ITERATORS=!0),null==IteratorPrototype||fails((function(){var test={};return IteratorPrototype[ITERATOR].call(test)!==test}))?IteratorPrototype={}:IS_PURE&&(IteratorPrototype=create(IteratorPrototype)),isCallable(IteratorPrototype[ITERATOR])||defineBuiltIn(IteratorPrototype,ITERATOR,(function(){return this})),module.exports={IteratorPrototype:IteratorPrototype,BUGGY_SAFARI_ITERATORS:BUGGY_SAFARI_ITERATORS}},"./node_modules/core-js/internals/iterators.js":function(module){module.exports={}},"./node_modules/core-js/internals/length-of-array-like.js":function(module,__unused_webpack_exports,__webpack_require__){var toLength=__webpack_require__("./node_modules/core-js/internals/to-length.js");module.exports=function(obj){return toLength(obj.length)}},"./node_modules/core-js/internals/make-built-in.js":function(module,__unused_webpack_exports,__webpack_require__){var fails=__webpack_require__("./node_modules/core-js/internals/fails.js"),isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),hasOwn=__webpack_require__("./node_modules/core-js/internals/has-own-property.js"),DESCRIPTORS=__webpack_require__("./node_modules/core-js/internals/descriptors.js"),CONFIGURABLE_FUNCTION_NAME=__webpack_require__("./node_modules/core-js/internals/function-name.js").CONFIGURABLE,inspectSource=__webpack_require__("./node_modules/core-js/internals/inspect-source.js"),InternalStateModule=__webpack_require__("./node_modules/core-js/internals/internal-state.js"),enforceInternalState=InternalStateModule.enforce,getInternalState=InternalStateModule.get,defineProperty=Object.defineProperty,CONFIGURABLE_LENGTH=DESCRIPTORS&&!fails((function(){return 8!==defineProperty((function(){}),"length",{value:8}).length})),TEMPLATE=String(String).split("String"),makeBuiltIn=module.exports=function(value,name,options){"Symbol("===String(name).slice(0,7)&&(name="["+String(name).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),options&&options.getter&&(name="get "+name),options&&options.setter&&(name="set "+name),(!hasOwn(value,"name")||CONFIGURABLE_FUNCTION_NAME&&value.name!==name)&&(DESCRIPTORS?defineProperty(value,"name",{value:name,configurable:!0}):value.name=name),CONFIGURABLE_LENGTH&&options&&hasOwn(options,"arity")&&value.length!==options.arity&&defineProperty(value,"length",{value:options.arity});try{options&&hasOwn(options,"constructor")&&options.constructor?DESCRIPTORS&&defineProperty(value,"prototype",{writable:!1}):value.prototype&&(value.prototype=void 0)}catch(error){}var state=enforceInternalState(value);return hasOwn(state,"source")||(state.source=TEMPLATE.join("string"==typeof name?name:"")),value};Function.prototype.toString=makeBuiltIn((function toString(){return isCallable(this)&&getInternalState(this).source||inspectSource(this)}),"toString")},"./node_modules/core-js/internals/math-trunc.js":function(module){var ceil=Math.ceil,floor=Math.floor;module.exports=Math.trunc||function trunc(x){var n=+x;return(n>0?floor:ceil)(n)}},"./node_modules/core-js/internals/microtask.js":function(module,__unused_webpack_exports,__webpack_require__){var flush,head,last,notify,toggle,node,promise,then,global=__webpack_require__("./node_modules/core-js/internals/global.js"),bind=__webpack_require__("./node_modules/core-js/internals/function-bind-context.js"),getOwnPropertyDescriptor=__webpack_require__("./node_modules/core-js/internals/object-get-own-property-descriptor.js").f,macrotask=__webpack_require__("./node_modules/core-js/internals/task.js").set,IS_IOS=__webpack_require__("./node_modules/core-js/internals/engine-is-ios.js"),IS_IOS_PEBBLE=__webpack_require__("./node_modules/core-js/internals/engine-is-ios-pebble.js"),IS_WEBOS_WEBKIT=__webpack_require__("./node_modules/core-js/internals/engine-is-webos-webkit.js"),IS_NODE=__webpack_require__("./node_modules/core-js/internals/engine-is-node.js"),MutationObserver=global.MutationObserver||global.WebKitMutationObserver,document=global.document,process=global.process,Promise=global.Promise,queueMicrotaskDescriptor=getOwnPropertyDescriptor(global,"queueMicrotask"),queueMicrotask=queueMicrotaskDescriptor&&queueMicrotaskDescriptor.value;queueMicrotask||(flush=function(){var parent,fn;for(IS_NODE&&(parent=process.domain)&&parent.exit();head;){fn=head.fn,head=head.next;try{fn()}catch(error){throw head?notify():last=void 0,error}}last=void 0,parent&&parent.enter()},IS_IOS||IS_NODE||IS_WEBOS_WEBKIT||!MutationObserver||!document?!IS_IOS_PEBBLE&&Promise&&Promise.resolve?((promise=Promise.resolve(void 0)).constructor=Promise,then=bind(promise.then,promise),notify=function(){then(flush)}):IS_NODE?notify=function(){process.nextTick(flush)}:(macrotask=bind(macrotask,global),notify=function(){macrotask(flush)}):(toggle=!0,node=document.createTextNode(""),new MutationObserver(flush).observe(node,{characterData:!0}),notify=function(){node.data=toggle=!toggle})),module.exports=queueMicrotask||function(fn){var task={fn:fn,next:void 0};last&&(last.next=task),head||(head=task,notify()),last=task}},"./node_modules/core-js/internals/native-symbol-registry.js":function(module,__unused_webpack_exports,__webpack_require__){var NATIVE_SYMBOL=__webpack_require__("./node_modules/core-js/internals/native-symbol.js");module.exports=NATIVE_SYMBOL&&!!Symbol.for&&!!Symbol.keyFor},"./node_modules/core-js/internals/native-symbol.js":function(module,__unused_webpack_exports,__webpack_require__){var V8_VERSION=__webpack_require__("./node_modules/core-js/internals/engine-v8-version.js"),fails=__webpack_require__("./node_modules/core-js/internals/fails.js");module.exports=!!Object.getOwnPropertySymbols&&!fails((function(){var symbol=Symbol();return!String(symbol)||!(Object(symbol)instanceof Symbol)||!Symbol.sham&&V8_VERSION&&V8_VERSION<41}))},"./node_modules/core-js/internals/native-url.js":function(module,__unused_webpack_exports,__webpack_require__){var fails=__webpack_require__("./node_modules/core-js/internals/fails.js"),wellKnownSymbol=__webpack_require__("./node_modules/core-js/internals/well-known-symbol.js"),IS_PURE=__webpack_require__("./node_modules/core-js/internals/is-pure.js"),ITERATOR=wellKnownSymbol("iterator");module.exports=!fails((function(){var url=new URL("b?a=1&b=2&c=3","http://a"),searchParams=url.searchParams,result="";return url.pathname="c%20d",searchParams.forEach((function(value,key){searchParams.delete("b"),result+=key+value})),IS_PURE&&!url.toJSON||!searchParams.sort||"http://a/c%20d?a=1&c=3"!==url.href||"3"!==searchParams.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!searchParams[ITERATOR]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==result||"x"!==new URL("http://x",void 0).host}))},"./node_modules/core-js/internals/native-weak-map.js":function(module,__unused_webpack_exports,__webpack_require__){var global=__webpack_require__("./node_modules/core-js/internals/global.js"),isCallable=__webpack_require__("./node_modules/core-js/internals/is-callable.js"),inspectSource=__webpack_require__("./node_modules/core-js/internals/inspect-source.js"),WeakMap=global.WeakMap;module.exports=isCallable(WeakMap)&&/native code/.test(inspectSource(WeakMap))},"./node_modules/core-js/internals/new-promise-capability.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var aCallable=__webpack_require__("./node_modules/core-js/internals/a-callable.js"),PromiseCapability=function(C){var resolve,reject;this.promise=new C((function($$resolve,$$reject){if(void 0!==resolve||void 0!==reject)throw TypeError("Bad Promise constructor");resolve=$$resolve,reject=$$reject})),this.resolve=aCallable(resolve),this.reject=aCallable(reject)};module.exports.f=function(C){return new PromiseCapability(C)}},"./node_modules/core-js/internals/not-a-regexp.js":function(module,__unused_webpack_exports,__webpack_require__){var isRegExp=__webpack_require__("./node_modules/core-js/internals/is-regexp.js"),$TypeError=TypeError;module.exports=function(it){if(isRegExp(it))throw $TypeError("The method doesn't accept regular expressions");return it}},"./node_modules/core-js/internals/object-assign.js":function(module,__unused_webpack_exports,__webpack_require__){"use strict";var DESCRIPTORS=__webpack_require__("./node_modules/core-js/internals/descriptors.js"),uncurryThis=__webpack_require__("./node_modules/core-js/internals/function-uncurry-this.js"),call=__webpack_require__("./node_modules/core-js/internals/function-call.js"),fails=__webpack_require__("./node_modules/core-js/internals/fails.js"),objectKeys=__webpack_require__("./node_modules/core-js/internals/object-keys.js"),getOwnPropertySymbolsModule=__webpack_require__("./node_modules/core-js/internals/object-get-own-property-symbols.js"),propertyIsEnumerableModule=__webpack_require__("./node_modules/core-js/internals/object-property-is-enumerable.js"),toObject=__webpack_require__("./node_modules/core-js/internals/to-object.js"),IndexedObject=__webpack_require__("./node_modules/core-js/internals/indexed-object.js"),$assign=Object.assign,defineProperty=Object.defineProperty,concat=uncurryThis([].concat);module.exports=!$assign||fails((function(){if(DESCRIPTORS&&1!==$assign({b:1},$assign(defineProperty({},"a",{enumerable:!0,get:function(){defineProperty(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var A={},B={},symbol=Symbol();return A[symbol]=7,"abcdefghijklmnopqrst".split("").forEach((function(chr){B[chr]=chr})),7!=$assign({},A)[symbol]||"abcdefghijklmnopqrst"!=objectKeys($assign({},B)).join("")}))?function assign(target,source){for(var T=toObject(target),argumentsLength=arguments.length,index=1,getOwnPropertySymbols=getOwnPropertySymbolsModule.f,propertyIsEnumerable=propertyIsEnumerableModule.f;argumentsLength>index;)for(var key,S=IndexedObject(arguments[index++]),keys=getOwnPropertySymbols?concat(objectKeys(S),getOwnPropertySymbols(S)):objectKeys(S),length=keys.length,j=0;length>j;)key=keys[j++],DESCRIPTORS&&!call(propertyIsEnumerable,S,key)||(T[key]=S[key]);return T}:$assign},"./node_modules/core-js/internals/object-create.js":function(module,__unused_webpack_exports,__webpack_require__){var activeXDocument,anObject=__webpack_require__("./node_modules/core-js/internals/an-object.js"),definePropertiesModule=__webpack_require__("./node_modules/core-js/internals/object-define-properties.js"),enumBugKeys=__webpack_require__("./node_modules/core-js/internals/enum-bug-keys.js"),hiddenKeys=__webpack_require__("./node_modules/core-js/internals/hidden-keys.js"),html=__webpack_require__("./node_modules/core-js/internals/html.js"),documentCreateElement=__webpack_require__("./node_modules/core-js/internals/document-create-element.js"),sharedKey=__webpack_require__("./node_modules/core-js/internals/shared-key.js"),IE_PROTO=sharedKey("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(content){return" \ No newline at end of file + window['STORIES'] = [{"titlePrefix":"","directory":"./src","files":"**/*.stories.mdx","importPathMatcher":"^\\.[\\\\/](?:src(?:\\/(?!\\.)(?:(?:(?!(?:^|\\/)\\.).)*?)\\/|\\/|$)(?!\\.)(?=.)[^/]*?\\.stories\\.mdx)$"},{"titlePrefix":"","directory":"./src","files":"**/*.stories.@(js|jsx|ts|tsx)","importPathMatcher":"^\\.[\\\\/](?:src(?:\\/(?!\\.)(?:(?:(?!(?:^|\\/)\\.).)*?)\\/|\\/|$)(?!\\.)(?=.)[^/]*?\\.stories\\.(js|jsx|ts|tsx))$"}]; \ No newline at end of file diff --git a/docs/main.36c98c07.iframe.bundle.js b/docs/main.36c98c07.iframe.bundle.js new file mode 100644 index 0000000..092ff39 --- /dev/null +++ b/docs/main.36c98c07.iframe.bundle.js @@ -0,0 +1 @@ +(self.webpackChunkrobot_scene=self.webpackChunkrobot_scene||[]).push([[179],{"./src/stories/Animation.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{Animation:function(){return Animation},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/slicedToArray.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"Animation",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var Animation=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__.Z)(args,_excluded),_useDefaultSceneStore=(0,_components__WEBPACK_IMPORTED_MODULE_2__.x2)((function(state){return[state.play,state.pause,state.reset]})),_useDefaultSceneStore2=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__.Z)(_useDefaultSceneStore,3),play=_useDefaultSceneStore2[0],pause=_useDefaultSceneStore2[1],reset=_useDefaultSceneStore2[2];return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)("div",{style:{height:"calc(100vh - 3rem)",width:"calc(100vw - 2rem)"},children:[(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2})),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)("div",{style:{textAlign:"center"},children:[(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return play()},children:"Play"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return play(.5)},children:"Play (0.5x)"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return play(2)},children:"Play (2x)"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return pause()},children:"Pause"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return reset(0)},children:"Reset"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return reset(Math.PI/2)},children:"Reset (0.25)"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return reset(Math.PI)},children:"Reset (0.5)"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return reset(3*Math.PI/2)},children:"Reset (0.75)"})]})]})}.bind({});Animation.args={tfs:{movingFrame:{frame:"world",position:{x:function x(time){return Math.cos(time/1e3)},y:function y(time){return Math.sin(time/1e3)},z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:function x(time){return.25*Math.cos(time/1e3)+1},y:1,z:1}}},items:{colorshiftlift:{shape:"cube",name:"ColorShift/Lift",frame:"movingFrame",position:{x:0,y:0,z:function z(time){return Math.sin(time/1e3)+1}},rotation:{w:1,x:0,y:0,z:0},color:{r:function r(time){return 255*(Math.sin(time/1e3)/2+.5)},g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!0},opacity:{shape:"cube",name:"Opacity",frame:"movingFrame",position:{x:1,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:10,a:function a(time){return Math.sin(time/1e3)/2+.5}},scale:{x:.5,y:.5,z:.5},highlighted:!1},scale:{shape:"cube",name:"Scale",frame:"movingFrame",position:{x:1,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:255,b:10,a:1},scale:{x:.5,y:function y(time){return Math.sin(time/1e3)/2+1},z:.5},highlighted:!1},hidden:{shape:"cube",name:"Hidden",frame:"movingFrame",position:{x:0,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:255,a:1},scale:{x:.5,y:.5,z:.5},hidden:function hidden(time){return Math.sin(time/1e3)>0}}},lines:{},hulls:{},texts:{colorshiftlift:{value:"ColorShift/Lift",frame:"movingFrame",position:{x:0,y:0,z:function z(time){return Math.sin(time/1e3)+1.5}},color:{r:function r(time){return 255*(Math.sin(time/1e3)/2+.5)},g:10,b:10,a:1}},opacity:{value:"Opacity",frame:"movingFrame",position:{x:1,y:1,z:1.5},color:{r:10,g:10,b:10,a:function a(time){return Math.sin(time/1e3)/2+.5}}},scale:{value:"Scale",frame:"movingFrame",position:{x:1,y:0,z:1.5},color:{r:10,g:255,b:10,a:1}},hidden:{value:"Hidden",frame:"movingFrame",position:{x:0,y:1,z:1.5},color:{r:10,g:10,b:255,a:1},hidden:function hidden(time){return Math.sin(time/1e3)>0}}},displayTfs:!0,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},Animation.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n\n const [play, pause, reset] = useDefaultSceneStore(state=>[state.play,state.pause,state.reset]);\n\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n\n return (\n
\n \n
\n \n \n \n \n \n \n \n \n
\n
)\n}"}},Animation.parameters);var __namedExportsOrder=["Animation"]},"./src/stories/CoFrame.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{CoFrame:function(){return CoFrame},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./src/stories/meshes/MeshLookup.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"CoFrame",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var CoFrame=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_5__.Z)(args,_excluded);return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)("div",{style:{height:"calc(100vh - 2rem)",width:"calc(100vw - 2rem)"},children:(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2,meshLookup:_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__.z}))})}.bind({});CoFrame.storyName="CoFrame",CoFrame.args={tfs:{"thingType-98892a7c1c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892b3a1c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892bd01c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892ce81c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892d7e1c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892e001c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"robot-agent-988926121c1911eccbe2600155d1a70a2":{frame:"pedestal",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"human-agent-ccbe2600155d1a70a2988926121c1911e":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10":{frame:"table",position:{x:-.28,y:-.04,z:.67},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"toolType-assembly-jig":{frame:"world",position:{x:.2,y:.28,z:.14},rotation:{w:-.5,x:.5,y:-.5,z:-.5},scale:{x:1,y:1,z:1}},"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7":{frame:"world",position:{x:-.85,y:-.25,z:-.75},rotation:{w:.707,x:0,y:0,z:.707},scale:{x:1,y:1,z:1},transformMode:"translate"},"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b":{frame:"world",position:{x:-.85,y:-.25,z:-.75},rotation:{w:.707,x:0,y:0,z:.707},scale:{x:1,y:1,z:1}},"machine-9133367a-f691-4d94-9764-50d9685db30a":{frame:"world",position:{x:.85,y:-.25,z:-.75},rotation:{w:.707,x:0,y:0,z:-.707},scale:{x:1,y:1,z:1}},"machine-67d870e0-511d-4662-bf0d-8478f5e860f8":{frame:"world",position:{x:.85,y:-.25,z:-.75},rotation:{w:.707,x:0,y:0,z:-.707},scale:{x:1,y:1,z:1}},"toolType-transport-jig":{frame:"world",position:{x:.3,y:.28,z:.14},rotation:{w:-.5,x:.5,y:-.5,z:-.5},scale:{x:1,y:1,z:1}},table:{frame:"world",position:{x:0,y:.36,z:-.37},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},pedestal:{frame:"world",position:{x:0,y:-.15,z:-.38},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},simulatedTool0:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:.11666648089885712,y:.2694645017385483,z:.6366749751567841},rotation:{w:-.37005797028541565,x:.9280606508255005,y:-.01538957841694355,z:.039035625755786896},scale:{x:1,y:1,z:1}},robotBase:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:0,y:0,z:.38},rotation:{w:0,x:0,y:0,z:1},scale:{x:1,y:1,z:1}},robotShoulderLink:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:0,y:0,z:.53185},rotation:{w:.6669439077377319,x:0,y:0,z:.745107889175415},scale:{x:1,y:1,z:1}},robotUpperArmLink:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:0,y:0,z:.53185},rotation:{w:-.4478497803211212,x:.5932892560958862,y:-.3847179114818573,z:.5472025871276855},scale:{x:1,y:1,z:1}},robotForearmLink:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:-.02560272067785263,y:.23055101335048675,z:.45763859629631043},rotation:{w:.6748411655426025,x:.1353885531425476,y:.694024384021759,z:.2111620008945465},scale:{x:1,y:1,z:1}},robotWrist1Link:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:.11584359407424927,y:.14418705981224775,z:.6451554048061371},rotation:{w:-.29463568329811096,x:.6713905930519104,y:-.22188881039619446,z:.6427983641624451},scale:{x:1,y:1,z:1}},robotWrist2Link:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:.1089443638920784,y:.20631420761346816,z:.7032694268226624},rotation:{w:.9164819121360779,x:-.39580079913139343,y:-.05381776764988899,z:-.022500555962324142},scale:{x:1,y:1,z:1}},robotWrist3Link:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:.11666648089885712,y:.2694645017385483,z:.6366749751567841},rotation:{w:-.37005797028541565,x:.9280606508255005,y:-.01538957841694355,z:.039035625755786896},scale:{x:1,y:1,z:1}},gripperBaseLink:{frame:"simulatedTool0",position:{x:0,y:0,z:0},rotation:{w:.5,x:.5,y:-.5,z:.5},scale:{x:1,y:1,z:1}},gripperLeftKnuckle:{frame:"gripperBaseLink",position:{x:.05490451627,y:.03060114443,z:0},rotation:{w:0,x:1,y:0,z:0},scale:{x:1,y:1,z:1}},gripperRightKnuckle:{frame:"gripperBaseLink",position:{x:.05490451627,y:-.03060114443,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperLeftFinger:{frame:"gripperLeftKnuckle",position:{x:-.00408552455,y:-.03148604435,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperRightFinger:{frame:"gripperRightKnuckle",position:{x:-.00408552455,y:-.03148604435,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperLeftInnerKnuckle:{frame:"gripperBaseLink",position:{x:.06142,y:.0127,z:0},rotation:{w:0,x:1,y:0,z:0},scale:{x:1,y:1,z:1}},gripperRightInnerKnuckle:{frame:"gripperBaseLink",position:{x:.06142,y:-.0127,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperLeftFingerTip:{frame:"gripperLeftInnerKnuckle",position:{x:.04303959807,y:-.03759940821,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperRightFingerTip:{frame:"gripperRightInnerKnuckle",position:{x:.04303959807,y:-.03759940821,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}},items:{"zone-988926121c1911ecbe2600155d1a70a2":{shape:"cube",name:"Human Workspace Occupancy Zone",frame:"world",position:{x:0,y:1,z:.4},rotation:{x:0,y:0,z:0,w:1},color:{r:233,g:53,b:152,a:.2},scale:{x:2,y:1,z:.8},transformMode:"inactive",highlighted:!1,hidden:!0},"zone-988926d01c1911ecbe2600155d1a70a2":{shape:"cube",name:"Human Corridor Occupancy Zone",frame:"world",position:{x:0,y:-1,z:.4},rotation:{x:0,y:0,z:0,w:1},color:{r:233,g:53,b:152,a:.2},scale:{x:2,y:1,z:.8},transformMode:"inactive",highlighted:!1,hidden:!0},"location-c540bea6-a0a8-40c2-8fcc-cb6ae772697c-tag":{uuid:"location-c540bea6-a0a8-40c2-8fcc-cb6ae772697c-tag",frame:"world",name:"Initial Location",shape:"flag",position:{x:.20400124405192815,y:.15340864650572777,z:.15008560705897595},rotation:{w:1,x:0,y:0,z:0},scale:{x:-.25,y:.25,z:.25},highlighted:!1,showName:!1,color:{r:233,g:53,b:152,a:1},hidden:!0,transformMode:"inactive"},"location-c540bea6-a0a8-40c2-8fcc-cb6ae772697c-pointer":{uuid:"location-c540bea6-a0a8-40c2-8fcc-cb6ae772697c-pointer",frame:"world",shape:"package://app/meshes/LocationMarker.stl",position:{x:.20400124405192815,y:.15340864650572777,z:.15008560705897595},rotation:{x:0,y:0,z:.6763577452496884,w:.7365732824646558},scale:{x:1,y:1,z:1},highlighted:!1,showName:!1,color:{r:233,g:53,b:152,a:1},hidden:!0,transformMode:"inactive"},"location-b7daabbd-6e24-4b8f-9c8e-5ea22d727ad0-tag":{uuid:"location-b7daabbd-6e24-4b8f-9c8e-5ea22d727ad0-tag",frame:"world",name:"Deposit Location",shape:"flag",position:{x:.40801871379516913,y:-.2369200947241372,z:.30206792720062714},rotation:{w:1,x:0,y:0,z:0},scale:{x:-.25,y:.25,z:.25},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"location-b7daabbd-6e24-4b8f-9c8e-5ea22d727ad0-pointer":{uuid:"location-b7daabbd-6e24-4b8f-9c8e-5ea22d727ad0-pointer",frame:"world",shape:"package://app/meshes/LocationMarker.stl",position:{x:.40801871379516913,y:-.2369200947241372,z:.30206792720062714},rotation:{x:.7133230578218721,y:-.03940528263686746,z:-.03668088697820589,w:-.6987645894079457},scale:{x:1,y:1,z:1},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"location-47238d9d-5241-4bdb-8b29-877f78cb124d-tag":{uuid:"location-47238d9d-5241-4bdb-8b29-877f78cb124d-tag",frame:"world",name:"Blade Fetch Location",shape:"flag",position:{x:-.4501325157748985,y:-.25541537076762655,z:-.02822078016538941},rotation:{w:1,x:0,y:0,z:0},scale:{x:-.25,y:.25,z:.25},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"location-47238d9d-5241-4bdb-8b29-877f78cb124d-pointer":{uuid:"location-47238d9d-5241-4bdb-8b29-877f78cb124d-pointer",frame:"world",shape:"package://app/meshes/LocationMarker.stl",position:{x:-.4501325157748985,y:-.25541537076762655,z:-.02822078016538941},rotation:{x:-.006622068142399432,y:-.6857443017700521,z:.7277784747239732,w:-.007027982062342742},scale:{x:1,y:1,z:1},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"waypoint-e7a63a7c-1df8-4ca6-9ffc-4f9b1e008aa4-tag":{uuid:"waypoint-e7a63a7c-1df8-4ca6-9ffc-4f9b1e008aa4-tag",frame:"world",name:"WP 1",shape:"tag",position:{x:-.3319053491144722,y:-.006321044395614983,z:.3364538095102072},rotation:{w:1,x:0,y:0,z:0},scale:{x:-.25,y:.25,z:.25},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"waypoint-e7a63a7c-1df8-4ca6-9ffc-4f9b1e008aa4-pointer":{uuid:"waypoint-e7a63a7c-1df8-4ca6-9ffc-4f9b1e008aa4-pointer",frame:"world",shape:"package://app/meshes/OpenWaypointMarker.stl",position:{x:-.3319053491144722,y:-.006321044395614983,z:.3364538095102072},rotation:{x:0,y:0,z:.9907218933440319,w:.13590485660496693},scale:{x:1,y:1,z:1},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10":{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/MK2-Printer/MK2-Printer.stl",name:"3D Printer Machine",frame:"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10-collision":{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/MK2-Printer.stl",name:"3D Printer Machine Collision",frame:"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"toolType-assembly-jig":{shape:"assembly_jig",name:"Assembly Jig Machine",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",highlighted:!1},"toolType-assembly-jig-collision":{shape:"assembly_jig_collision",name:"Assembly Jig Machine Collision",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7":{shape:"conveyor",name:"Blade Conveyor",frame:"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7-collision":{shape:"conveyor_collision",name:"Blade Conveyor Collision",frame:"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b":{shape:"conveyor_receiver",name:"Blade Feeder",frame:"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b-collision":{shape:"conveyor_receiver_collision",name:"Blade Feeder Collision",frame:"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"machine-9133367a-f691-4d94-9764-50d9685db30a":{shape:"conveyor",name:"Knife Conveyor",frame:"machine-9133367a-f691-4d94-9764-50d9685db30a",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-9133367a-f691-4d94-9764-50d9685db30a-collision":{shape:"conveyor_collision",name:"Knife Conveyor Collision",frame:"machine-9133367a-f691-4d94-9764-50d9685db30a",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"machine-67d870e0-511d-4662-bf0d-8478f5e860f8":{shape:"conveyor_dispatcher",name:"Knife Feeder",frame:"machine-67d870e0-511d-4662-bf0d-8478f5e860f8",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-67d870e0-511d-4662-bf0d-8478f5e860f8-collision":{shape:"conveyor_dispatcher_collision",name:"Knife Feeder Collision",frame:"machine-67d870e0-511d-4662-bf0d-8478f5e860f8",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"toolType-transport-jig":{shape:"transport_jig",name:"Transport Jig",frame:"toolType-transport-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",highlighted:!1},"toolType-transport-jig-collision":{shape:"package://evd_ros_tasks/description/markers/tranport_jig.stl",name:"Transport Jig Collision",frame:"toolType-transport-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"inputOutput-ridn023-dz00-445jk-we90-e69tffb00845":{shape:"handle_l",frame:"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10",position:{x:-.2,y:.28,z:.074},rotation:{x:.707,y:0,z:0,w:.707},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-mnpdm09-ty00-445md-yjg09-rnvor905mfi1203d":{shape:"handle_r",frame:"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10",position:{x:-.3,y:.28,z:.078},rotation:{x:.707,y:0,z:0,w:.707},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-2d49b51b-dz37-488e-we56-e55ef6a0a8fc":{shape:"blade",frame:"world",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-3d50b62b-dz37-488e-we56-e65eo6f0a80b":{shape:"transport_jig",frame:"toolType-transport-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-sefse456-ty56-234g-gh67-fth4567hfth7":{shape:"blade_with_transport_jig",frame:"world",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-tjgnk5suei9-oo90-ruti0-gte0-u8cns9nc9s":{shape:"handle_l",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-tu8fnsiw0c-ie90-rcns89-tuy8-isnc9sa34s":{shape:"handle_r",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-eicns9ef9-sic9-eicns99-sey8-seo4s9dir9":{shape:"blade",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-tidvi23-tbn9-cjzd99-if98-of9nsnrc0s":{shape:"knife",frame:"thingType-98892bd01c1911ecbe2600155d1a70a2",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-45fsoe9-tjfg9-gurd89-thf9-09ghnsn234d":{shape:"handle_l",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-948fnsi23-odns9-fins89-irn1-fcnr94820s":{shape:"handle_r",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-asfsn90-vnxmo9-nmbj89-ii4w-vnlsf0sfkx0":{shape:"blade_with_transport_jig",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-94nss89-8vnsk9-7hdn9-wy89-fhsne8923":{shape:"knife_with_transport_jig",frame:"thingType-98892ce81c1911ecbe2600155d1a70a2",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},table:{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/Table/Table.stl",name:"Table",frame:"table",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},color:{r:10,g:10,b:10,a:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},pedestal:{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/ur3e-Pedestal/Pedestal.stl",name:"Pedestal",frame:"pedestal",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},color:{r:15,g:15,b:15,a:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},robotBase:{shape:"package://ur_description/meshes/ur3/visual/base.dae",name:"Robot Base",frame:"robotBase",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:1,w:0},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},robotShoulderLink:{shape:"package://ur_description/meshes/ur3/visual/shoulder.dae",name:"Shoulder Link",frame:"robotShoulderLink",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:1,w:0},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},robotUpperArmLink:{shape:"package://ur_description/meshes/ur3/visual/upperarm.dae",name:"Upper Arm Link",frame:"robotUpperArmLink",position:{x:0,y:0,z:.12},rotation:{x:.5,y:-.5,z:-.5,w:.5},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotUpperArmLink-collision":{shape:"package://ur_description/meshes/ur3/collision/upperarm.stl",name:"Upper Arm Link Collision",frame:"robotUpperArmLink",position:{x:0,y:0,z:.12},rotation:{x:.5,y:-.5,z:-.5,w:.5},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},robotForearmLink:{shape:"package://ur_description/meshes/ur3/visual/forearm.dae",name:"Forearm Link",frame:"robotForearmLink",position:{x:0,y:0,z:.027},rotation:{x:.5,y:-.5,z:-.5,w:.5},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotForearmLink-collision":{shape:"package://ur_description/meshes/ur3/collision/forearm.stl",name:"Forearm Link Collision",frame:"robotForearmLink",position:{x:0,y:0,z:.027},rotation:{x:.5,y:-.5,z:-.5,w:.5},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},robotWrist1Link:{shape:"package://ur_description/meshes/ur3/visual/wrist1.dae",name:"Wrist 1 Link",frame:"robotWrist1Link",position:{x:0,y:0,z:-.104},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotWrist1Link-collision":{shape:"package://ur_description/meshes/ur3/collision/wrist1.stl",name:"Wrist 1 Link Collision",frame:"robotWrist1Link",position:{x:0,y:0,z:-.104},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},robotWrist2Link:{shape:"package://ur_description/meshes/ur3/visual/wrist2.dae",name:"Wrist 2 Link",frame:"robotWrist2Link",position:{x:0,y:0,z:-.08535},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotWrist2Link-collision":{shape:"package://ur_description/meshes/ur3/collision/wrist1.stl",name:"Wrist 2 Link Collision",frame:"robotWrist2Link",position:{x:0,y:0,z:-.104},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},robotWrist3Link:{shape:"package://ur_description/meshes/ur3/visual/wrist3.dae",name:"Wrist 3 Link",frame:"robotWrist3Link",position:{x:0,y:0,z:-.0921},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotWrist3Link-collision":{shape:"package://ur_description/meshes/ur3/collision/wrist3.stl",name:"Wrist 3 Link Collision",frame:"robotWrist3Link",position:{x:0,y:0,z:-.0921},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},gripperBaseLink:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_base_link.dae",name:"Gripper Base",frame:"gripperBaseLink",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperLeftKnuckle:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_knuckle_link.dae",name:"Gripper Left Knuckle",frame:"gripperLeftKnuckle",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperRightKnuckle:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_knuckle_link.dae",name:"Gripper Right Knuckle",frame:"gripperRightKnuckle",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperLeftFinger:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_finger_link.dae",name:"Gripper Left Finger",frame:"gripperLeftFinger",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperRightFinger:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_finger_link.dae",name:"Gripper Right Finger",frame:"gripperRightFinger",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperLeftInnerKnuckle:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_inner_knuckle_link.dae",name:"Gripper Left Inner Knuckle",frame:"gripperLeftInnerKnuckle",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperRightInnerKnuckle:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_inner_knuckle_link.dae",name:"Gripper Right Inner Knuckle",frame:"gripperRightInnerKnuckle",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperLeftFingerTip:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_finger_tip_link.dae",name:"Gripper Left Finger Tip",frame:"gripperLeftFingerTip",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperRightFingerTip:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_finger_tip_link.dae",name:"Gripper Right Finger Tip",frame:"gripperRightFingerTip",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1}},lines:{},hulls:{usage:{name:"Robot Space Usage",frame:"world",vertices:[{x:-.5,y:-.5,z:0},{x:.5,y:-.5,z:0},{x:.5,y:.5,z:0},{x:-.5,y:.5,z:0},{x:-.5,y:.5,z:1},{x:-.5,y:-.5,z:1},{x:.5,y:-.5,z:1},{x:.5,y:.5,z:1},{x:-.75,y:0,z:.5},{x:.75,y:0,z:.5},{x:0,y:.75,z:.5},{x:0,y:-.75,z:.5}],color:{r:10,g:200,b:235,a:function a(time){return Math.sin(time/1e3)/6+.25}},wireframe:!1,highlighted:!0,showName:!1,hidden:!1}},texts:{workcellLabel:{value:"Work Cell",frame:"world",position:{x:0,y:0,z:1.3},color:{r:10,g:10,b:255,a:1}},miniworkcellLabel:{value:"Mini Work Cell",frame:"gizmo",position:{x:0,y:0,z:1.3},color:{r:10,g:10,b:255,a:1}}},displayTfs:!1,displayGrid:!0,isPolar:!1,backgroundColor:"#1e1e1e",planeColor:"#141414",highlightColor:"#ffffff",plane:-.75,fov:60,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},CoFrame.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return
\n}"}},CoFrame.parameters);var __namedExportsOrder=["CoFrame"]},"./src/stories/ItemMovement.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{ItemMovement:function(){return ItemMovement},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"ItemMovement",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var ItemMovement=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__.Z)(args,_excluded);return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("div",{style:{height:"calc(100vh - 2rem)",width:"calc(100vw - 2rem)"},children:(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2}))})}.bind({});ItemMovement.storyName="ItemMovement",ItemMovement.args={tfs:{moving:{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}},items:{immovable:{shape:"cube",name:"Immovable Cube",frame:"moving",position:{x:0,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!0},translateCube:{shape:"cube",name:"Translate Cube (Async)",frame:"moving",position:{x:1,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1,transformMode:"translate"},rotateCube:{shape:"cube",name:"Rotate Cube",frame:"moving",position:{x:1,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:255,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1,transformMode:"rotate"},scaleCube:{shape:"cube",name:"Scale Cube",frame:"moving",position:{x:0,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:255,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1,transformMode:"scale"}},lines:{},hulls:{},texts:{},displayTfs:!1,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,paused:!1,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},ItemMovement.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return
\n}"}},ItemMovement.parameters);var __namedExportsOrder=["ItemMovement"]},"./src/stories/MeshDebug.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{MeshDebug:function(){return MeshDebug},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./src/stories/meshes/MeshLookup.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"Mesh Debug",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var debugTfs={},debugItems={},debugTexts={},y=-10,x=-12;Object.keys(_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__.z).forEach((function(key,i){0===x?x+=2:x>0&&x%10==0?(y+=2,x=-10):x+=2,debugTfs["".concat(i)]={name:"".concat(i),position:{x:x,y:y,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},debugItems[key]={shape:key,name:key,frame:"".concat(i),position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:key.includes("robotiq_2f_85_gripper_visualization")?{x:.001,y:.001,z:.001}:{x:1,y:1,z:1},editMode:"inactive",highlighted:!1},debugTexts[key]={value:key,frame:"".concat(i),position:{x:0,y:0,z:.5},color:{r:10,g:10,b:255,a:1}}}));var MeshDebug=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_5__.Z)(args,_excluded);return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)("div",{style:{height:"calc(100vh - 2rem)",width:"calc(100vw - 2rem)"},children:(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2,meshLookup:_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__.z}))})}.bind({});MeshDebug.args={tfs:debugTfs,items:debugItems,texts:debugTexts,lines:{},hulls:{},displayTfs:!1,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},MeshDebug.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return
\n}"}},MeshDebug.parameters);var __namedExportsOrder=["MeshDebug"]},"./src/stories/Random.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{RandomShapes:function(){return RandomShapes},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/index.js"),_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/stories/meshes/MeshLookup.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"Random Shapes",component:_components__WEBPACK_IMPORTED_MODULE_1__.xs};var RandomShapes=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__.Z)(args,_excluded);return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_1__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("div",{style:{height:"calc(100vh - 2rem)",width:"calc(100vw - 2rem)"},children:(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(_components__WEBPACK_IMPORTED_MODULE_1__.xs,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_1__.x2,meshLookup:_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_2__.z}))})}.bind({});RandomShapes.args={tfs:{other1:{frame:"world",position:{x:1,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},other2:{name:"world",position:{x:-2,y:0,z:2},rotation:{w:.525322,x:.8509035,y:0,z:0},scale:{x:1,y:1,z:1}},other3:{name:"world",position:{x:2,y:0,z:1},rotation:{w:-.604,x:-.002,y:-.756,z:.252},scale:{x:1,y:1,z:1}}},items:{1:{shape:"cube",name:"My Cube",frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:50,b:10,a:.75},scale:{x:.5,y:.5,z:.5},highlighted:!0},2:{shape:"sphere",name:"My Sphere",frame:"world",position:{x:0,y:2,z:2},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:255,b:30,a:.35},scale:{x:1,y:2,z:1},highlighted:!0,showName:!0},3:{shape:"cylinder",name:"My Cylinder",frame:"other2",shapeParams:{height:1.25},position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:200,b:235,a:.5},scale:{x:1,y:1,z:1},highlighted:!1},a3:{shape:"capsule",name:"My Capsule",frame:"other2",shapeParams:{height:.25},position:{x:1.2,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:200,b:235,a:.5},scale:{x:1,y:1,z:1},highlighted:!1},4:{shape:"flatarrow",name:"My Arrow 1",frame:"world",position:{x:1,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:70,g:70,b:250,a:.5},scale:{x:1,y:1,z:1},highlighted:!0},5:{shape:"arrow",name:"My Arrow 2",frame:"other1",position:{x:1,y:0,z:0},rotation:{w:-.604,x:-.002,y:-.756,z:.252},color:{r:255,g:70,b:250,a:.5},scale:{x:1,y:1,z:1},highlighted:!0},6:{shape:"arrow",name:"My Arrow 3",frame:"other3",position:{x:1,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:70,b:250,a:.5},scale:{x:1,y:2,z:1},highlighted:!1},7:{shape:"blade_with_transport_jig",name:"Blade with Transport Jig",frame:"world",position:{x:0,y:2,z:1},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},showName:!0,colorOverlay:!0,color:{r:function r(time){return 255*(Math.sin(time/1e3)/2+.5)},g:255,b:0,a:function a(time){return Math.sin(time/1e3)/2+.5}},highlighted:!0},8:{shape:"warning",name:"Nao Ankle",frame:"world",position:{x:1,y:.5,z:1},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},colorOverlay:!0,color:{r:255,g:255,b:0,a:.5},highlighted:!1},9:{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/MK2-Printer/MK2-Printer.stl",name:"3d Printer",frame:"world",position:{x:-1,y:1,z:.3},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},colorOverlay:!0,color:{r:function r(time){return 255*(Math.sin(time/1e3)/2+.5)},g:0,b:0,a:.8},highlighted:!1},10:{frame:"world",name:"Tag",shape:"tag",position:{x:3,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},scale:{x:-1,y:1,z:1},highlighted:!1,showName:!0,color:{r:255,g:0,b:0,a:1}},11:{frame:"world",name:"flag",shape:"flag",position:{x:3,y:1.4,z:1},rotation:{w:1,x:0,y:0,z:0},scale:{x:-1,y:1,z:1},highlighted:!1,showName:!1,color:{r:255,g:0,b:0,a:1}}},lines:{line1:{name:"Line1",frame:"world",width:1,vertices:[{position:{x:1,y:2,z:0},color:{r:255,g:0,b:0}},{position:{x:2,y:1,z:1},color:{r:0,g:255,b:0}},{position:{x:2,y:2,z:1},color:{r:0,g:0,b:255}}],highlighted:!1},line2:{name:"Line1",frame:"other1",width:3,vertices:[{position:{x:1,y:0,z:0},color:{r:0,g:0,b:255}},{position:{x:1,y:0,z:1},color:{r:100,g:100,b:255}},{position:{x:2,y:1,z:1},color:{r:50,g:50,b:255}},{position:{x:2,y:2,z:1},color:{r:255,g:255,b:255}}],highlighted:!1}},hulls:{},texts:{},displayTfs:!0,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},RandomShapes.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return
\n}"}},RandomShapes.parameters);var __namedExportsOrder=["RandomShapes"]},"./src/stories/TFMovement.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{TFMovement:function(){return TFMovement},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/slicedToArray.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"TFMovement",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var TFMovement=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__.Z)(args,_excluded),setProperty=(0,_components__WEBPACK_IMPORTED_MODULE_2__.x2)((function(state){return state.setProperty})),_useState=(0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(0),_useState2=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__.Z)(_useState,2),translateSnap=_useState2[0],setTranslateSnap=_useState2[1],_useState3=(0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(0),_useState4=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__.Z)(_useState3,2),rotateSnap=_useState4[0],setRotateSnap=_useState4[1],_useState5=(0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(0),_useState6=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__.Z)(_useState5,2),scaleSnap=_useState6[0],setScaleSnap=_useState6[1];return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)("div",{style:{height:"calc(100vh - 3rem)",width:"calc(100vw - 2rem)"},children:[(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2,displayTfs:!0,translateSnap:translateSnap,rotateSnap:rotateSnap,scaleSnap:scaleSnap})),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)("div",{style:{textAlign:"center"},children:[(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setTranslateSnap(0),setProperty(["tfs","moving","transformMode"],"translate")},children:"Translate Free"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setTranslateSnap(.25),setProperty(["tfs","moving","transformMode"],"translate")},children:"Translate Snapping"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setRotateSnap(0),setProperty(["tfs","moving","transformMode"],"rotate")},children:"Rotate Free"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setRotateSnap(Math.PI/6),setProperty(["tfs","moving","transformMode"],"rotate")},children:"Rotate Snapping"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setScaleSnap(0),setProperty(["tfs","moving","transformMode"],"scale")},children:"Scale Free"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setScaleSnap(.1),setProperty(["tfs","moving","transformMode"],"scale")},children:"Scale Snapping"})]})]})}.bind({});TFMovement.storyName="TFMovement",TFMovement.args={tfs:{moving:{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},transformMode:"rotate"}},items:{immovable:{shape:"cube",name:"Immovable Cube",frame:"moving",position:{x:0,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5}},translateCube:{shape:"cube",name:"Translate Cube (Async)",frame:"moving",position:{x:1,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1},rotateCube:{shape:"cube",name:"Rotate Cube",frame:"moving",position:{x:1,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:255,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1},scaleCube:{shape:"cube",name:"Scale Cube",frame:"moving",position:{x:0,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:255,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1}},lines:{},hulls:{},texts:{},displayTfs:!1,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,paused:!1,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},TFMovement.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n\n const setProperty = useDefaultSceneStore(state => state.setProperty);\n const [translateSnap, setTranslateSnap] = useState(0);\n const [rotateSnap, setRotateSnap] = useState(0);\n const [scaleSnap, setScaleSnap] = useState(0);\n\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return (\n
\n \n
\n \n \n \n \n \n \n
\n
\n )\n}"}},TFMovement.parameters);var __namedExportsOrder=["TFMovement"]},"./.storybook/preview.js-generated-config-entry.js":function(__unused_webpack_module,__unused_webpack___webpack_exports__,__webpack_require__){"use strict";var preview_namespaceObject={};__webpack_require__.r(preview_namespaceObject),__webpack_require__.d(preview_namespaceObject,{__namedExportsOrder:function(){return __namedExportsOrder},parameters:function(){return parameters}});var ClientApi=__webpack_require__("./node_modules/@storybook/client-api/dist/esm/ClientApi.js"),parameters={docs:{theme:__webpack_require__("./node_modules/@storybook/theming/dist/esm/index.js").np.dark},actions:{argTypesRegex:"^on[A-Z].*"},controls:{matchers:{color:/(background|color)$/i,date:/Date$/}}},__namedExportsOrder=["parameters"];function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.keys(preview_namespaceObject).forEach((function(key){var value=preview_namespaceObject[key];switch(key){case"args":return(0,ClientApi.uc)(value);case"argTypes":return(0,ClientApi.v9)(value);case"decorators":return value.forEach((function(decorator){return(0,ClientApi.$9)(decorator,!1)}));case"loaders":return value.forEach((function(loader){return(0,ClientApi.HZ)(loader,!1)}));case"parameters":return(0,ClientApi.h1)(function _objectSpread(target){for(var i=1;i-1})),ambientLightRef=(0,react.useRef)(),pointLightRef=(0,react.useRef)(),directionalLightRef=(0,react.useRef)(),orbitControls=(0,react.useRef)(),planeRGB=function hexToRgb(hex){hex=hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(function(m,r,g,b){return r+r+g+g+b+b}));var result=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);return result?{r:parseInt(result[1],16),g:parseInt(result[2],16),b:parseInt(result[3],16)}:null}(planeColor||"a8a8a8"),planeRGBA=[planeRGB.r,planeRGB.g,planeRGB.b,.5];return(0,jsx_runtime.jsxs)(react.Fragment,{children:[(0,jsx_runtime.jsx)(OrbitControls.z,{ref:orbitControls,makeDefault:!0}),(0,jsx_runtime.jsx)("pointLight",{ref:pointLightRef,intensity:.5,position:[-1,-3,3],color:"#FFFAEE"}),(0,jsx_runtime.jsx)(AmbientLight,{ref:ambientLightRef,intensity:.7,color:"white"}),(0,jsx_runtime.jsx)(DirectionalLight,{ref:directionalLightRef,castShadow:!0,position:[5,15,15],intensity:.6,color:"#FFFAEE"}),(0,jsx_runtime.jsx)("spotLight",{penumbra:1,position:[-1,-1,4],intensity:.3,castShadow:!0,color:"#FFFAEE"}),(0,jsx_runtime.jsx)("color",{attach:"background",args:[backgroundColor||"#d0d0d0"]}),(0,jsx_runtime.jsx)("fogExp2",{attach:"fog",args:[backgroundColor||"#d0d0d0",.01]}),(0,jsx_runtime.jsx)(shapes.Cd,{receiveShadow:!0,scale:1e3,position:[0,0,plane?plane-.01:-.01],material:MaterialMaker.apply(void 0,planeRGBA)}),(0,jsx_runtime.jsxs)(dist.Y1,{children:[(0,jsx_runtime.jsx)(dist.xC,{autoClear:!1,children:(0,jsx_runtime.jsx)(dist.bw,{visibleEdgeColor:highlightColor,hiddenEdgeColor:highlightColor,blur:!0,kernelSize:1,edgeStrength:50,pulseSpeed:.25,xRay:!0})}),(0,jsx_runtime.jsx)(components_Tree,{activeTf:"world",displayTfs:displayTfs,allTfs:tfs,allItems:items,allLines:lines,allHulls:hulls,allTexts:texts,highlightColor:highlightColor})]}),(0,jsx_runtime.jsx)("group",{position:[0,0,plane||0],rotation:[Math.PI/2,0,0],up:[0,0,1],children:displayGrid&&(isPolar?(0,jsx_runtime.jsx)("polarGridHelper",{args:[10,16,8,64,"white","gray"]}):(0,jsx_runtime.jsx)("gridHelper",{args:[20,20,"white","gray"]}))}),movableStuff.map((function(movableObject,idx){return(0,jsx_runtime.jsx)(TransformableObject,{objectInfo:movableObject,mode:movableObject.transformMode,displayTfs:displayTfs,allTfs:tfs,allItems:items,allLines:lines,allHulls:hulls,allTexts:texts,translateSnap:translateSnap,rotateSnap:rotateSnap,scaleSnap:scaleSnap,highlightColor:highlightColor,onDragEnd:function onDragEnd(){orbitControls.current&&(orbitControls.current.enabled=!0)},onDragStart:function onDragStart(){orbitControls.current&&(orbitControls.current.enabled=!1)}},"movableObjectTransform-".concat(idx))}))]})}TransformableObject.__docgenInfo={description:"",methods:[],displayName:"TransformableObject"},"undefined"!=typeof STORYBOOK_REACT_CLASSES&&(STORYBOOK_REACT_CLASSES["src/components/Util/TransformControls.js"]={name:"TransformableObject",docgenInfo:TransformableObject.__docgenInfo,path:"src/components/Util/TransformControls.js"}),Content.__docgenInfo={description:"",methods:[],displayName:"Content"},"undefined"!=typeof STORYBOOK_REACT_CLASSES&&(STORYBOOK_REACT_CLASSES["src/components/Content.jsx"]={name:"Content",docgenInfo:Content.__docgenInfo,path:"src/components/Content.jsx"});var Scene_excluded=["backgroundColor","store","fov","onPointerMissed","meshLookup"];function Scene(_ref){var backgroundColor=_ref.backgroundColor,store=_ref.store,fov=_ref.fov,onPointerMissed=_ref.onPointerMissed,_ref$meshLookup=_ref.meshLookup,meshLookup=void 0===_ref$meshLookup?{}:_ref$meshLookup,otherProps=(0,objectWithoutProperties.Z)(_ref,Scene_excluded);return(0,jsx_runtime.jsx)(react_three_fiber_esm.Xz,{camera:{up:[0,0,1],fov:fov,position:[0,-3,3]},shadows:!0,style:{background:backgroundColor||"#d0d0d0"},resize:{polyfill:resize_observer.do},onPointerMissed:onPointerMissed||function(){},children:(0,jsx_runtime.jsx)(SceneProvider,{store:store,children:(0,jsx_runtime.jsx)(MeshProvider,{meshes:meshLookup,children:(0,jsx_runtime.jsx)(react.Suspense,{children:(0,jsx_runtime.jsx)(Content,(0,objectSpread2.Z)((0,objectSpread2.Z)({},otherProps),{},{backgroundColor:backgroundColor}))})})})})}three_module.Object3D.DefaultUp.set(0,0,1),Scene.__docgenInfo={description:"",methods:[],displayName:"Scene",props:{meshLookup:{defaultValue:{value:"{}",computed:!1},required:!1}}},"undefined"!=typeof STORYBOOK_REACT_CLASSES&&(STORYBOOK_REACT_CLASSES["src/components/Scene.jsx"]={name:"Scene",docgenInfo:Scene.__docgenInfo,path:"src/components/Scene.jsx"})},"./src/components/defaultStore.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{x2:function(){return useDefaultSceneStore}});var objectSpread2=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),esm=__webpack_require__("./node_modules/zustand/esm/index.js"),middleware=__webpack_require__("./node_modules/zustand/esm/middleware.js"),immer_esm=__webpack_require__("./node_modules/immer/dist/immer.esm.mjs"),classCallCheck=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"),createClass=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/createClass.js"),Timer=function(){function Timer(){(0,classCallCheck.Z)(this,Timer),this._previousTime=0,this._currentTime=0,this._delta=0,this._elapsed=0,this._timescale=1,this._useFixedDelta=!1,this._fixedDelta=16.67,this._usePageVisibilityAPI="undefined"!=typeof document&&void 0!==document.hidden,!0===this._usePageVisibilityAPI&&(this._pageVisibilityHandler=handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}return(0,createClass.Z)(Timer,[{key:"disableFixedDelta",value:function disableFixedDelta(){return this._useFixedDelta=!1,this}},{key:"dispose",value:function dispose(){return!0===this._usePageVisibilityAPI&&document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this}},{key:"enableFixedDelta",value:function enableFixedDelta(){return this._useFixedDelta=!0,this}},{key:"getDelta",value:function getDelta(){return this._delta/1e3}},{key:"getElapsed",value:function getElapsed(){return this._elapsed/1e3}},{key:"getFixedDelta",value:function getFixedDelta(){return this._fixedDelta/1e3}},{key:"getTimescale",value:function getTimescale(){return this._timescale}},{key:"reset",value:function reset(){return this._currentTime=this._now(),this}},{key:"setFixedDelta",value:function setFixedDelta(fixedDelta){return this._fixedDelta=1e3*fixedDelta,this}},{key:"setTimescale",value:function setTimescale(timescale){return this._timescale=timescale,this}},{key:"update",value:function update(){return!0===this._useFixedDelta?this._delta=this._fixedDelta:(this._previousTime=this._currentTime,this._currentTime=this._now(),this._delta=this._currentTime-this._previousTime),this._delta*=this._timescale,this._elapsed+=this._delta,this}},{key:"_now",value:function _now(){return("undefined"==typeof performance?Date:performance).now()}}]),Timer}();function handleVisibilityChange(){!1===document.hidden&&this.reset()}var lodash=__webpack_require__("./node_modules/lodash/lodash.js"),lodash_default=__webpack_require__.n(lodash),ImmerSceneSlice=function immer(config){return function(set,get,api){return config((function(partial,replace){var nextState="function"==typeof partial?(0,immer_esm.ZP)(partial):partial;return set(nextState,replace)}),get,api)}}((0,middleware.XR)((function SceneSlice(set,get){return{clock:new Timer,items:{},tfs:{},hulls:{},lines:{},texts:{},onMove:function onMove(id,source,worldTransform,localTransform){return set((function(state){console.log(localTransform),state[source][id].position=(0,objectSpread2.Z)({},localTransform.position),state[source][id].rotation=localTransform.quaternion,state[source][id].rotation.x=localTransform.quaternion.x,state[source][id].rotation.y=localTransform.quaternion.y,state[source][id].rotation.z=localTransform.quaternion.z,state[source][id].rotation.w=localTransform.quaternion.w,state[source][id].scale=(0,objectSpread2.Z)({},localTransform.scale)}))},onClick:function onClick(id,hidden,event){hidden||console.log("id: ".concat(id," clicked!")),get().items[id]&&!hidden&&event.stopPropagation()},onPointerOver:function onPointerOver(id,hidden,event){},onPointerOut:function onPointerOut(id,hidden,event){},pause:function pause(){return set((function(state){state.clock.setTimescale(0)}))},play:function play(speed){return set((function(state){state.clock.setTimescale(speed||1)}))},reset:function reset(time){return set((function(state){console.log("setting time to ".concat(time)),state.clock._elapsed=time?1e3*time:0}))},clearItems:function clearItems(){return set((function(_){return{items:{}}}))},clearLines:function clearLines(){return set((function(_){return{lines:{}}}))},clearTfs:function clearTfs(){return set((function(_){return{tfs:{}}}))},clearHulls:function clearHulls(){return set((function(_){return{hulls:{}}}))},clearTexts:function clearTexts(){return set((function(_){return{texts:{}}}))},setItems:function setItems(items){return set((function(_){return{items:items}}))},setLines:function setLines(lines){return set((function(_){return{lines:lines}}))},setTfs:function setTfs(tfs){return set((function(_){return{tfs:tfs}}))},setHulls:function setHulls(hulls){return set((function(_){return{hulls:hulls}}))},setTexts:function setTexts(texts){return set((function(_){return{texts:texts}}))},removeItem:function removeItem(key){return set((function(state){delete state.items[key]}))},removeLine:function removeLine(key){return set((function(state){delete state.lines[key]}))},removeTf:function removeTf(key){return set((function(state){delete state.tfs[key]}))},removeHull:function removeHull(key){return set((function(state){delete state.hulls[key]}))},removeText:function removeText(key){return set((function(state){delete state.texts[key]}))},setItem:function setItem(key,item){return set((function(state){state.items[key]=item}))},setLine:function setLine(key,line){return set((function(state){state.lines[key]=line}))},setTf:function setTf(key,tf){return set((function(state){state.tfs[key]=tf}))},setHull:function setHull(key,hull){return set((function(state){state.hulls[key]=hull}))},setText:function setText(key,text){return set((function(state){state.texts[key]=text}))},setProperty:function setProperty(path,value){return set((function(state){lodash_default().set(state,path,value)}))}}}))),useDefaultSceneStore=(0,esm.ZP)(ImmerSceneSlice)},"./src/components/index.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{x2:function(){return _defaultStore__WEBPACK_IMPORTED_MODULE_1__.x2},xs:function(){return _Scene__WEBPACK_IMPORTED_MODULE_0__.Z}});var _Scene__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./src/components/Scene.jsx"),_defaultStore__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/defaultStore.js")},"./src/stories/meshes/MeshLookup.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{z:function(){return MeshLookupTable}});var useGLTF=__webpack_require__("./node_modules/@react-three/drei/core/useGLTF.js"),finger_namespaceObject=__webpack_require__.p+"2722c36d578e421f844e.glb";useGLTF.L.preload(finger_namespaceObject);var hand_namespaceObject=__webpack_require__.p+"0cc02e26902c8f08652d.glb";useGLTF.L.preload(hand_namespaceObject);var link0_namespaceObject=__webpack_require__.p+"136c9bbc97ce0cf8c9e4.glb";useGLTF.L.preload(link0_namespaceObject);var link1_namespaceObject=__webpack_require__.p+"fe28c0ebac8e0ea9afe8.glb";useGLTF.L.preload(link1_namespaceObject);var link2_namespaceObject=__webpack_require__.p+"ef30ff8f8dd25ce66ec5.glb";useGLTF.L.preload(link2_namespaceObject);var link3_namespaceObject=__webpack_require__.p+"f2e4ed8f7af1fbfdecf5.glb";useGLTF.L.preload(link3_namespaceObject);var link4_namespaceObject=__webpack_require__.p+"95682f4fdb3ec78fec11.glb";useGLTF.L.preload(link4_namespaceObject);var link5_namespaceObject=__webpack_require__.p+"fbd75a9e7877d51a17a2.glb";useGLTF.L.preload(link5_namespaceObject);var link6_namespaceObject=__webpack_require__.p+"cb7a3a0d99d0829cf93e.glb";useGLTF.L.preload(link6_namespaceObject);var link7_namespaceObject=__webpack_require__.p+"f9d0a3a3c1f30e5fbc2a.glb";useGLTF.L.preload(link7_namespaceObject);var robotiq_arg2f_85_base_link_namespaceObject=__webpack_require__.p+"57a8381889016d086976.glb";useGLTF.L.preload(robotiq_arg2f_85_base_link_namespaceObject);var robotiq_arg2f_85_inner_finger_namespaceObject=__webpack_require__.p+"ff82f07a64794d907175.glb";useGLTF.L.preload(robotiq_arg2f_85_inner_finger_namespaceObject);var robotiq_arg2f_85_inner_knuckle_namespaceObject=__webpack_require__.p+"ef1021f46e8da14c361d.glb";useGLTF.L.preload(robotiq_arg2f_85_inner_knuckle_namespaceObject);var robotiq_arg2f_85_outer_finger_namespaceObject=__webpack_require__.p+"02e44a8f96b7e9e02975.glb";useGLTF.L.preload(robotiq_arg2f_85_outer_finger_namespaceObject);var robotiq_arg2f_85_outer_knuckle_namespaceObject=__webpack_require__.p+"371896c54d1f4992a6ac.glb";useGLTF.L.preload(robotiq_arg2f_85_outer_knuckle_namespaceObject);var robotiq_arg2f_base_link_namespaceObject=__webpack_require__.p+"2f5b68a16175d8d81764.glb";useGLTF.L.preload(robotiq_arg2f_base_link_namespaceObject);var visual_robotiq_arg2f_85_base_link_namespaceObject=__webpack_require__.p+"076e56969a0a8b094ff1.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_base_link_namespaceObject);var visual_robotiq_arg2f_85_inner_finger_namespaceObject=__webpack_require__.p+"5bfeb79449e49274457e.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_inner_finger_namespaceObject);var visual_robotiq_arg2f_85_inner_knuckle_namespaceObject=__webpack_require__.p+"dae460be3f40bc0ce893.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_inner_knuckle_namespaceObject);var visual_robotiq_arg2f_85_outer_finger_namespaceObject=__webpack_require__.p+"5dd9f4f9dfdb0c5c3150.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_outer_finger_namespaceObject);var visual_robotiq_arg2f_85_outer_knuckle_namespaceObject=__webpack_require__.p+"92254578081659ac659f.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_outer_knuckle_namespaceObject);var robotiq_arg2f_85_pad_namespaceObject=__webpack_require__.p+"409136b14a248efad6b8.glb";useGLTF.L.preload(robotiq_arg2f_85_pad_namespaceObject);var robotiq_gripper_coupling_namespaceObject=__webpack_require__.p+"27be9d0db69fe382c757.glb";useGLTF.L.preload(robotiq_gripper_coupling_namespaceObject);var robotiq_85_base_link_namespaceObject=__webpack_require__.p+"26073aebc36a91b39513.glb";useGLTF.L.preload(robotiq_85_base_link_namespaceObject);var robotiq_85_knuckle_link_namespaceObject=__webpack_require__.p+"b66b5363262a9aa5f792.glb";useGLTF.L.preload(robotiq_85_knuckle_link_namespaceObject);var robotiq_85_finger_link_namespaceObject=__webpack_require__.p+"096c095808e970978d7e.glb";useGLTF.L.preload(robotiq_85_finger_link_namespaceObject);var robotiq_85_finger_tip_link_namespaceObject=__webpack_require__.p+"f4fb12d64ccb2a59f525.glb";useGLTF.L.preload(robotiq_85_finger_tip_link_namespaceObject);var robotiq_85_inner_knuckle_link_namespaceObject=__webpack_require__.p+"ebc0934129953400b093.glb";useGLTF.L.preload(robotiq_85_inner_knuckle_link_namespaceObject);var collision_robotiq_85_base_link_namespaceObject=__webpack_require__.p+"631ba79e07c5de49aa5d.glb";useGLTF.L.preload(collision_robotiq_85_base_link_namespaceObject);var collision_robotiq_85_knuckle_link_namespaceObject=__webpack_require__.p+"fe9999e65cfc71c6125e.glb";useGLTF.L.preload(collision_robotiq_85_knuckle_link_namespaceObject);var collision_robotiq_85_finger_link_namespaceObject=__webpack_require__.p+"89e9b62e2d0faf15b18d.glb";useGLTF.L.preload(collision_robotiq_85_finger_link_namespaceObject);var collision_robotiq_85_finger_tip_link_namespaceObject=__webpack_require__.p+"5ab2515ce543ae06889b.glb";useGLTF.L.preload(collision_robotiq_85_finger_tip_link_namespaceObject);var collision_robotiq_85_inner_knuckle_link_namespaceObject=__webpack_require__.p+"20fe2374d4de6df4ae18.glb";useGLTF.L.preload(collision_robotiq_85_inner_knuckle_link_namespaceObject);var pedestal_link_collision_namespaceObject=__webpack_require__.p+"3a4c9af019b247a410e6.glb";useGLTF.L.preload(pedestal_link_collision_namespaceObject);var PEDESTAL_namespaceObject=__webpack_require__.p+"3350508bd5feca53933c.glb";useGLTF.L.preload(PEDESTAL_namespaceObject);var H0_namespaceObject=__webpack_require__.p+"320513d32ac0d233922e.glb";useGLTF.L.preload(H0_namespaceObject);var H1_namespaceObject=__webpack_require__.p+"a9891124232df7e7d220.glb";useGLTF.L.preload(H1_namespaceObject);var E1_namespaceObject=__webpack_require__.p+"07d914225a052f2106cf.glb";useGLTF.L.preload(E1_namespaceObject);var W1_namespaceObject=__webpack_require__.p+"c54a018e3050fede8431.glb";useGLTF.L.preload(W1_namespaceObject);var base_link_collision_namespaceObject=__webpack_require__.p+"ef58ff7faffbaf3ae1a7.glb";useGLTF.L.preload(base_link_collision_namespaceObject);var base_link_namespaceObject=__webpack_require__.p+"b4c1e98e1373558b0dd2.glb";useGLTF.L.preload(base_link_namespaceObject);var E0_namespaceObject=__webpack_require__.p+"5e5e5101d27a55c24335.glb";useGLTF.L.preload(E0_namespaceObject);var W0_namespaceObject=__webpack_require__.p+"62cf8f96fbc857097bd3.glb";useGLTF.L.preload(W0_namespaceObject);var S0_namespaceObject=__webpack_require__.p+"6fe8fc1a422b4b623e40.glb";useGLTF.L.preload(S0_namespaceObject);var S1_namespaceObject=__webpack_require__.p+"a856a881219916e800d4.glb";useGLTF.L.preload(S1_namespaceObject);var W2_namespaceObject=__webpack_require__.p+"08e26d6108d8b20727ee.glb";useGLTF.L.preload(W2_namespaceObject);var base_namespaceObject=__webpack_require__.p+"8b09376b2ef4290ba69b.glb";useGLTF.L.preload(base_namespaceObject);var forearm_namespaceObject=__webpack_require__.p+"94b55aa37445fe9a579e.glb";useGLTF.L.preload(forearm_namespaceObject);var shoulder_namespaceObject=__webpack_require__.p+"f5b5a7af44a2758c4a3c.glb";useGLTF.L.preload(shoulder_namespaceObject);var upperarm_namespaceObject=__webpack_require__.p+"16439484bb5a5ed3deea.glb";useGLTF.L.preload(upperarm_namespaceObject);var wrist1_namespaceObject=__webpack_require__.p+"f39e8d448aff9cf3642a.glb";useGLTF.L.preload(wrist1_namespaceObject);var wrist2_namespaceObject=__webpack_require__.p+"16d079d88e916105275d.glb";useGLTF.L.preload(wrist2_namespaceObject);var wrist3_namespaceObject=__webpack_require__.p+"9322571244f78b366da6.glb";useGLTF.L.preload(wrist3_namespaceObject);var collision_base_namespaceObject=__webpack_require__.p+"3bb49d6be1e5f5d19ad2.glb";useGLTF.L.preload(collision_base_namespaceObject);var collision_forearm_namespaceObject=__webpack_require__.p+"db7ffa352d8572453d8f.glb";useGLTF.L.preload(collision_forearm_namespaceObject);var collision_shoulder_namespaceObject=__webpack_require__.p+"303ffffc92c0e52be7f7.glb";useGLTF.L.preload(collision_shoulder_namespaceObject);var collision_upperarm_namespaceObject=__webpack_require__.p+"cf12f0ef8fad54942a4b.glb";useGLTF.L.preload(collision_upperarm_namespaceObject);var collision_wrist1_namespaceObject=__webpack_require__.p+"029ab32ddd8fb3feb7ed.glb";useGLTF.L.preload(collision_wrist1_namespaceObject);var collision_wrist2_namespaceObject=__webpack_require__.p+"a31e912a127fb8b1b0b4.glb";useGLTF.L.preload(collision_wrist2_namespaceObject);var collision_wrist3_namespaceObject=__webpack_require__.p+"f2536802541039524ba5.glb";useGLTF.L.preload(collision_wrist3_namespaceObject);var Ur5_base_namespaceObject=__webpack_require__.p+"725d30d0c3d0ad515609.glb";useGLTF.L.preload(Ur5_base_namespaceObject);var Ur5_forearm_namespaceObject=__webpack_require__.p+"f8a7f903b629254de810.glb";useGLTF.L.preload(Ur5_forearm_namespaceObject);var Ur5_shoulder_namespaceObject=__webpack_require__.p+"482ecbda26bc4349b49a.glb";useGLTF.L.preload(Ur5_shoulder_namespaceObject);var Ur5_upperarm_namespaceObject=__webpack_require__.p+"57aecbc1e995be15b4b3.glb";useGLTF.L.preload(Ur5_upperarm_namespaceObject);var Ur5_wrist1_namespaceObject=__webpack_require__.p+"dfc25a13e9a00769df7a.glb";useGLTF.L.preload(Ur5_wrist1_namespaceObject);var Ur5_wrist2_namespaceObject=__webpack_require__.p+"3d6ad85a4ca746fd0d18.glb";useGLTF.L.preload(Ur5_wrist2_namespaceObject);var Ur5_wrist3_namespaceObject=__webpack_require__.p+"cf67ce9ec8212bd5433a.glb";useGLTF.L.preload(Ur5_wrist3_namespaceObject);var Ur10_base_namespaceObject=__webpack_require__.p+"6726d5079a69c8d88807.glb";useGLTF.L.preload(Ur10_base_namespaceObject);var Ur10_forearm_namespaceObject=__webpack_require__.p+"1f61322fee40aaeb1761.glb";useGLTF.L.preload(Ur10_forearm_namespaceObject);var Ur10_shoulder_namespaceObject=__webpack_require__.p+"6f59e28be53805b69e0f.glb";useGLTF.L.preload(Ur10_shoulder_namespaceObject);var Ur10_upperarm_namespaceObject=__webpack_require__.p+"34fed34d9d4f5066e777.glb";useGLTF.L.preload(Ur10_upperarm_namespaceObject);var Ur10_wrist1_namespaceObject=__webpack_require__.p+"e699f773554012c1b20c.glb";useGLTF.L.preload(Ur10_wrist1_namespaceObject);var Ur10_wrist2_namespaceObject=__webpack_require__.p+"81a91f436af9672546aa.glb";useGLTF.L.preload(Ur10_wrist2_namespaceObject);var Ur10_wrist3_namespaceObject=__webpack_require__.p+"5be6578c637b92aec91c.glb";useGLTF.L.preload(Ur10_wrist3_namespaceObject);var _3DBenchy_namespaceObject=__webpack_require__.p+"fb95d18efb1487592267.glb";useGLTF.L.preload(_3DBenchy_namespaceObject);var Arrow_namespaceObject=__webpack_require__.p+"a0223b57679908adee61.glb";useGLTF.L.preload(Arrow_namespaceObject);var Box_namespaceObject=__webpack_require__.p+"4f094d970c93bb74cf3a.glb";useGLTF.L.preload(Box_namespaceObject);var Collision_Box_namespaceObject=__webpack_require__.p+"de2eef1e44d86e47561e.glb";useGLTF.L.preload(Collision_Box_namespaceObject);var Collision_MK2_Printer_namespaceObject=__webpack_require__.p+"c71730e124347337324c.glb";useGLTF.L.preload(Collision_MK2_Printer_namespaceObject);var Collision_Pedestal_namespaceObject=__webpack_require__.p+"ee5b929bb68f73f0bf60.glb";useGLTF.L.preload(Collision_Pedestal_namespaceObject);var Collision_Table_namespaceObject=__webpack_require__.p+"f23b732ffd6cbf33ddc2.glb";useGLTF.L.preload(Collision_Table_namespaceObject);var InfoPhycon_namespaceObject=__webpack_require__.p+"a794bd4ce6ac46e8baa5.glb";useGLTF.L.preload(InfoPhycon_namespaceObject);var LocationMarker_namespaceObject=__webpack_require__.p+"bcddcb066aa3df35e58a.glb";useGLTF.L.preload(LocationMarker_namespaceObject);var MK2Printer_namespaceObject=__webpack_require__.p+"1a0b36716b64aef46192.glb";useGLTF.L.preload(MK2Printer_namespaceObject);var OpenWaypointMarker_namespaceObject=__webpack_require__.p+"20bd53a93a51df5731eb.glb";useGLTF.L.preload(OpenWaypointMarker_namespaceObject);var Pedestal_namespaceObject=__webpack_require__.p+"724235985a56bc1d68aa.glb";useGLTF.L.preload(Pedestal_namespaceObject);var Table_namespaceObject=__webpack_require__.p+"218075b40bbfd12ae2dd.glb";useGLTF.L.preload(Table_namespaceObject);var WarningPhycon_namespaceObject=__webpack_require__.p+"bf2c04a3ba73a0b4bc68.glb";useGLTF.L.preload(WarningPhycon_namespaceObject);var Tag_namespaceObject=__webpack_require__.p+"bbf461324a8d5c817652.glb";useGLTF.L.preload(Tag_namespaceObject);var Flag_namespaceObject=__webpack_require__.p+"65ae7639ad8a8930d021.glb";useGLTF.L.preload(Flag_namespaceObject);var Blade_namespaceObject=__webpack_require__.p+"5c62f1d60b48c991ac0d.glb";function Blade_Model(props){var _useGLTF=(0,useGLTF.L)(Blade_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[Math.PI,0,0],children:[{type:"raw",geometry:nodes.Blade.geometry,material:materials["Blade.material"],scale:[5,5,5]}]}]}useGLTF.L.preload(Blade_namespaceObject);var HandleL_namespaceObject=__webpack_require__.p+"1e0c6314afdcd77610dc.glb";function HandleL_Model(props){var _useGLTF=(0,useGLTF.L)(HandleL_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[Math.PI,0,0],children:[{type:"raw",geometry:nodes.LHandle.geometry,material:materials.lmaterial,scale:[5,5,5]}]}]}useGLTF.L.preload(HandleL_namespaceObject);var HandleR_namespaceObject=__webpack_require__.p+"5b373faffe499e18adfc.glb";function HandleR_Model(props){var _useGLTF=(0,useGLTF.L)(HandleR_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[Math.PI,0,0],children:[{type:"raw",geometry:nodes.RHandle.geometry,material:materials.rmaterial,scale:[5,5,5]}]}]}useGLTF.L.preload(HandleR_namespaceObject);var toConsumableArray=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js");var Conveyor_namespaceObject=__webpack_require__.p+"4c82fd4edb0da5571bac.glb";useGLTF.L.preload(Conveyor_namespaceObject);var ConveyorCollision_namespaceObject=__webpack_require__.p+"50e19d9fb450ddcfb44c.glb";useGLTF.L.preload(ConveyorCollision_namespaceObject);var TransportJig_namespaceObject=__webpack_require__.p+"d87117eaa3cf819e7c0f.glb";function TransportJig_Model(props){var _useGLTF=(0,useGLTF.L)(TransportJig_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.TransportJig.geometry,material:materials["TransportJig.material"],scale:[5,5,5]}]}]}useGLTF.L.preload(TransportJig_namespaceObject);var AssemblyJig_namespaceObject=__webpack_require__.p+"eda331eb4f20b886f9a4.glb";useGLTF.L.preload(AssemblyJig_namespaceObject);var AssemblyJigCollision_namespaceObject=__webpack_require__.p+"459ae37e2741b7904a03.glb";useGLTF.L.preload(AssemblyJigCollision_namespaceObject);var ConveyorDispatcher_namespaceObject=__webpack_require__.p+"744b572852b0224cf81a.glb";useGLTF.L.preload(ConveyorDispatcher_namespaceObject);var ConveyorReceiver_namespaceObject=__webpack_require__.p+"6b20da764b5f46ad1281.glb";useGLTF.L.preload(ConveyorReceiver_namespaceObject);var ConveyorDispatcherCollision_namespaceObject=__webpack_require__.p+"b4cc0db00a306efa6441.glb";useGLTF.L.preload(ConveyorDispatcherCollision_namespaceObject);var ConveyorReceiverCollision_namespaceObject=__webpack_require__.p+"062eacab68de5ba90e76.glb";useGLTF.L.preload(ConveyorReceiverCollision_namespaceObject);var MeshLookupTable={flatarrow:function Arrow_Model(props){var _useGLTF=(0,useGLTF.L)(Arrow_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.Arrow.geometry,material:materials["Default OBJ"],scale:[1,1,1]}]},warning:function WarningPhycon_Model(props){var nodes=(0,useGLTF.L)(WarningPhycon_namespaceObject).nodes;return[{type:"group",scale:[.005,.005,.005],position:[-1.5,-.6,0],children:[{type:"raw",geometry:nodes.WarningPhycon.geometry,material:nodes.WarningPhycon.material}]}]},info:function InfoPhycon_Model(props){var nodes=(0,useGLTF.L)(InfoPhycon_namespaceObject).nodes;return[{type:"group",scale:[.005,.005,.005],position:[-1.25,1.25,0],children:[{type:"raw",geometry:nodes.InfoPhycon.geometry,material:nodes.InfoPhycon.material}]}]},tag:function Tag_Model(props){var _useGLTF=(0,useGLTF.L)(Tag_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.Tag.geometry,material:materials.Material}]}]},flag:function Flag_Model(props){var _useGLTF=(0,useGLTF.L)(Flag_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.Flag.geometry,material:materials.Material}]}]},blade:Blade_Model,knife:function Knife_Model(props){return[{type:"group",children:[].concat((0,toConsumableArray.Z)(Blade_Model()),(0,toConsumableArray.Z)(HandleL_Model()),(0,toConsumableArray.Z)(HandleR_Model()))}]},handle_l:HandleL_Model,handle_r:HandleR_Model,conveyor:function Conveyor_Model(props){var _useGLTF=(0,useGLTF.L)(Conveyor_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Belt.geometry,material:materials.BeltMaterial},{type:"raw",geometry:nodes.Conveyor.geometry,material:materials.ConveyorMaterial},{type:"raw",geometry:nodes.InsideBack.geometry,material:materials.InsideBackMaterial}]}]},conveyor_collision:function ConveyorCollision_Model(props){var nodes=(0,useGLTF.L)(ConveyorCollision_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.ConveyorCollision.geometry,material:nodes.ConveyorCollision.material}]}]},transport_jig:TransportJig_Model,assembly_jig:function AssemblyJig_Model(props){var _useGLTF=(0,useGLTF.L)(AssemblyJig_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.AssemblyJig.geometry,material:materials.AssemblyJigMaterial,scale:[5,5,5]}]}]},assembly_jig_collision:function AssemblyJigCollision_Model(props){var nodes=(0,useGLTF.L)(AssemblyJigCollision_namespaceObject).nodes;return[{type:"group",rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Mesh_0.geometry,material:nodes.Mesh_0.material,scale:[5,5,5]}]}]},blade_with_transport_jig:function BladeWithTransportJig_Model(props){return[{type:"group",children:[].concat((0,toConsumableArray.Z)(Blade_Model()),(0,toConsumableArray.Z)(TransportJig_Model()))}]},knife_with_transport_jig:function KnifeWithTransportJig_Model(props){return[{type:"group",children:[].concat((0,toConsumableArray.Z)(Blade_Model()),(0,toConsumableArray.Z)(HandleL_Model()),(0,toConsumableArray.Z)(HandleR_Model()),(0,toConsumableArray.Z)(TransportJig_Model()))}]},conveyor_dispatcher:function ConveyorDispatcher_Model(props){var _useGLTF=(0,useGLTF.L)(ConveyorDispatcher_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.ConveyorDispatcher.geometry,material:materials.ConveyorAddonMaterial}]}]},conveyor_receiver:function ConveyorReceiver_Model(props){var _useGLTF=(0,useGLTF.L)(ConveyorReceiver_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.ConveyorReceiver.geometry,material:materials.ConveyorAddonMaterial}]}]},conveyor_dispatcher_collision:function ConveyorDispatcherCollision_Model(props){var nodes=(0,useGLTF.L)(ConveyorDispatcherCollision_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.ConveyorDispatcherCollision.geometry,material:nodes.ConveyorDispatcherCollision.material}]}]},conveyor_receiver_collision:function ConveyorReceiverCollision_Model(props){var nodes=(0,useGLTF.L)(ConveyorReceiverCollision_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.ConveyorReceiverCollision.geometry,material:nodes.ConveyorReceiverCollision.material}]}]},"package://franka_ros/franka_description/meshes/visual/finger.dae":function Model(props){var _useGLTF=(0,useGLTF.L)(finger_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{geometry:nodes.node0.geometry,material:materials.Part__Feature_007},{geometry:nodes.node1.geometry,material:materials.Part__Feature001_006}]},"package://franka_ros/franka_description/meshes/visual/hand.dae":function hand_Model(props){var _useGLTF=(0,useGLTF.L)(hand_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature002_005_005},{type:"raw",geometry:nodes.node5.geometry,material:materials.Part__Feature005_001_005},{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature_009_005},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature001_008_005},{type:"raw",geometry:nodes.node5_001.geometry,material:materials.Part__Feature005_001_005_001}]},"package://franka_ros/franka_description/meshes/visual/link0.dae":function link0_Model(props){var _useGLTF=(0,useGLTF.L)(link0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature017_001},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature022_001},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature023_001},{type:"raw",geometry:nodes.node3.geometry,material:materials.Part__Feature019_001},{type:"raw",geometry:nodes.node4.geometry,material:materials.Part__Feature018_001},{type:"raw",geometry:nodes.node5.geometry,material:materials.Face636_001},{type:"raw",geometry:nodes.node6.geometry,material:materials.Shell001_001},{type:"raw",geometry:nodes.node7.geometry,material:materials.Shell002_001},{type:"raw",geometry:nodes.node8.geometry,material:materials.Shell_001},{type:"raw",geometry:nodes.node9.geometry,material:materials.Shell003_001},{type:"raw",geometry:nodes.node10.geometry,material:materials.Shell009_001},{type:"raw",geometry:nodes.node11.geometry,material:materials.Shell010_001}]},"package://franka_ros/franka_description/meshes/visual/link1.dae":function link1_Model(props){var _useGLTF=(0,useGLTF.L)(link1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature_001,position:[0,-.19,0]}]},"package://franka_ros/franka_description/meshes/visual/link2.dae":function link2_Model(props){var _useGLTF=(0,useGLTF.L)(link2_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature024}]},"package://franka_ros/franka_description/meshes/visual/link3.dae":function link3_Model(props){var _useGLTF=(0,useGLTF.L)(link3_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0_001.geometry,material:materials.Part__Feature_001_001_001_002,position:[0,-.12,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature001_010_001_002,position:[0,-.12,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature002_007_001_002,position:[0,-.12,0]},{type:"raw",geometry:nodes.node3.geometry,material:materials.Part__Feature003_004_001_002,position:[0,-.12,0]}]},"package://franka_ros/franka_description/meshes/visual/link4.dae":function link4_Model(props){var _useGLTF=(0,useGLTF.L)(link4_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature_002_003_001,position:[0,0,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature002_001_003_001,position:[0,0,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature003_001_003_001,position:[0,0,0]},{type:"raw",geometry:nodes.node3.geometry,material:materials.Part__Feature001_001_003_001,position:[0,0,0]}]},"package://franka_ros/franka_description/meshes/visual/link5.dae":function link5_Model(props){var _useGLTF=(0,useGLTF.L)(link5_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature_002_004_003,position:[0,-.26,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Shell_001_001_003,position:[0,-.26,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Shell001_001_001_003,position:[0,-.26,0]}]},"package://franka_ros/franka_description/meshes/visual/link6.dae":function link6_Model(props){var _useGLTF=(0,useGLTF.L)(link6_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Shell012_002_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature001_009_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature002_006_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node3.geometry,material:materials.Face064_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node4.geometry,material:materials.Face065_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node5.geometry,material:materials.Face374_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node6.geometry,material:materials.Shell_003_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node7.geometry,material:materials.Face539_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node8.geometry,material:materials.Union_001_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node9.geometry,material:materials.Union001_001_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node10.geometry,material:materials.Shell002_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node11.geometry,material:materials.Shell003_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node12.geometry,material:materials.Shell004_001_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node13.geometry,material:materials.Shell005_001_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node15.geometry,material:materials.Shell007_002_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node16.geometry,material:materials.Shell011_002_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node0_001.geometry,material:materials.Shell006_003_002_001}]},"package://franka_ros/franka_description/meshes/visual/link7.dae":function link7_Model(props){var _useGLTF=(0,useGLTF.L)(link7_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Mirroring_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Mirroring002_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node3.geometry,material:materials.Part__Mirroring003_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node5.geometry,material:materials.Part__Mirroring005_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node6.geometry,material:materials.Part__Mirroring006_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node7.geometry,material:materials.Part__Mirroring007_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Mirroring001_004_002,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node4.geometry,material:materials.Part__Mirroring004_004_002,position:[0,.05,0],rotation:[0,-Math.PI/4,0]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_base_link.stl":function robotiq_arg2f_85_base_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_base_link_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.Robotiq_Arg2F_85_Base_Link.geometry,material:nodes.Robotiq_Arg2F_85_Base_Link.material}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_inner_finger.dae":function robotiq_arg2f_85_inner_finger_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_inner_finger_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_inner_knuckle.dae":function robotiq_arg2f_85_inner_knuckle_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_inner_knuckle_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_outer_finger.dae":function robotiq_arg2f_85_outer_finger_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_outer_finger_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_outer_knuckle.dae":function robotiq_arg2f_85_outer_knuckle_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_outer_knuckle_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_base_link.stl":function robotiq_arg2f_base_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_base_link_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.Robotiq_Arg2F_Base_Link.geometry,material:nodes.Robotiq_Arg2F_Base_Link.material}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_base_link.dae":function visual_robotiq_arg2f_85_base_link_Model(props){var _useGLTF=(0,useGLTF.L)(visual_robotiq_arg2f_85_base_link_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:nodes.node0.material},{type:"raw",geometry:nodes.node1.geometry,material:nodes.node1.material},{type:"raw",geometry:nodes.node2.geometry,material:nodes.node2.material},{type:"raw",geometry:nodes.node3.geometry,material:nodes.node3.material},{type:"raw",geometry:nodes.node4.geometry,material:nodes.node4.material},{type:"raw",geometry:nodes.node100.geometry,material:materials["mymaterial.004"]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_inner_finger.dae":function visual_robotiq_arg2f_85_inner_finger_Model(props){var _useGLTF=(0,useGLTF.L)(visual_robotiq_arg2f_85_inner_finger_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials["mymaterial.003"]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_inner_knuckle.dae":function visual_robotiq_arg2f_85_inner_knuckle_Model(props){var _useGLTF=(0,useGLTF.L)(visual_robotiq_arg2f_85_inner_knuckle_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials["mymaterial.002"]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_outer_finger.dae":function visual_robotiq_arg2f_85_outer_finger_Model(props){var _useGLTF=(0,useGLTF.L)(visual_robotiq_arg2f_85_outer_finger_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials["mymaterial.001"]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_outer_knuckle.dae":function visual_robotiq_arg2f_85_outer_knuckle_Model(props){var nodes=(0,useGLTF.L)(visual_robotiq_arg2f_85_outer_knuckle_namespaceObject).nodes;return[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_pad.dae":function robotiq_arg2f_85_pad_Model(props){var _useGLTF=(0,useGLTF.L)(robotiq_arg2f_85_pad_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.mymaterial}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_gripper_coupling.stl":function robotiq_gripper_coupling_Model(props){var nodes=(0,useGLTF.L)(robotiq_gripper_coupling_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Robotiq_Gripper_Coupling.geometry,material:nodes.Robotiq_Gripper_Coupling.material}]},"package://robotiq_85_description/meshes/visual/robotiq_85_base_link.dae":function robotiq_85_base_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_base_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material},{type:"raw",geometry:nodes.mesh_0_2.geometry,material:nodes.mesh_0_2.material}]}]},"package://robotiq_85_description/meshes/visual/robotiq_85_knuckle_link.dae":function robotiq_85_knuckle_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_knuckle_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material}]}]},"package://robotiq_85_description/meshes/visual/robotiq_85_finger_link.dae":function robotiq_85_finger_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_finger_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material},{type:"raw",geometry:nodes.mesh_0_2.geometry,material:nodes.mesh_0_2.material}]}]},"package://robotiq_85_description/meshes/visual/robotiq_85_inner_knuckle_link.dae":function robotiq_85_inner_knuckle_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_inner_knuckle_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material}]}]},"package://robotiq_85_description/meshes/visual/robotiq_85_finger_tip_link.dae":function robotiq_85_finger_tip_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_finger_tip_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_base_link.stl":function collision_robotiq_85_base_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_base_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_knuckle_link.stl":function collision_robotiq_85_knuckle_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_knuckle_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_finger_link.stl":function collision_robotiq_85_finger_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_finger_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_inner_knuckle_link.stl":function collision_robotiq_85_inner_knuckle_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_inner_knuckle_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_finger_tip_link.stl":function collision_robotiq_85_finger_tip_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_finger_tip_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://baxter_common/baxter_description/meshes/base/PEDESTAL.DAE":function PEDESTAL_Model(props){var _useGLTF=(0,useGLTF.L)(PEDESTAL_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.PEDESTAL.geometry,material:materials.Material_001}]},"package://baxter_common/baxter_description/meshes/base/pedestal_link_collision.DAE":function Pedestal_link_collision_Model(props){var nodes=(0,useGLTF.L)(pedestal_link_collision_namespaceObject).nodes;return[{type:"raw",geometry:nodes["PEDESTAL-L"].geometry,material:nodes["PEDESTAL-L"].material}]},"package://baxter_common/baxter_description/meshes/head/H0.DAE":function H0_Model(props){var _useGLTF=(0,useGLTF.L)(H0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.H0.geometry,material:materials["Material_001.001"]}]},"package://baxter_common/baxter_description/meshes/head/H1.DAE":function H1_Model(props){var _useGLTF=(0,useGLTF.L)(H1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.H1_1.geometry,material:materials["Material.001"]},{type:"raw",geometry:nodes.H1_2.geometry,material:materials["Material_001.002"]}]},"package://baxter_common/baxter_description/meshes/lower_elbow/E1.DAE":function E1_Model(props){var _useGLTF=(0,useGLTF.L)(E1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.E1_1.geometry,material:materials["Material_001.003"]},{type:"raw",geometry:nodes.E1_2.geometry,material:materials.Material_002}]},"package://baxter_common/baxter_description/meshes/lower_forearm/W1.DAE":function W1_Model(props){var _useGLTF=(0,useGLTF.L)(W1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.W1_1.geometry,material:materials["Material_001.004"]},{type:"raw",geometry:nodes.W1_2.geometry,material:materials["Material_002.001"]}],rotation:[-Math.PI,0,0]}]},"package://baxter_common/baxter_description/meshes/lower_shoulder/S1.DAE":function S1_Model(props){var _useGLTF=(0,useGLTF.L)(S1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.S1.geometry,material:materials["Material_001.006"]}]},"package://baxter_common/baxter_description/meshes/torso/base_link.DAE":function Base_link_Model(props){var _useGLTF=(0,useGLTF.L)(base_link_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.base_link_1.geometry,material:materials.Material_004},{type:"raw",geometry:nodes.base_link_2.geometry,material:materials["Material_001.007"]},{type:"raw",geometry:nodes.base_link_3.geometry,material:materials.Material_003},{type:"raw",geometry:nodes.base_link_4.geometry,material:materials.Material_007},{type:"raw",geometry:nodes.base_link_5.geometry,material:materials.Material_005},{type:"raw",geometry:nodes.base_link_6.geometry,material:materials.Material_006}]},"package://baxter_common/baxter_description/meshes/torso/base_link_collision.DAE":function Base_link_collision_Model(props){var nodes=(0,useGLTF.L)(base_link_collision_namespaceObject).nodes;return[{type:"raw",geometry:nodes["TORSO-L"].geometry,material:nodes["TORSO-L"].material}]},"package://baxter_common/baxter_description/meshes/upper_elbow/E0.DAE":function E0_Model(props){var _useGLTF=(0,useGLTF.L)(E0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.E0_1.geometry,material:materials["Material_001.008"]},{type:"raw",geometry:nodes.E0_2.geometry,material:materials["Material_002.002"]}]},"package://baxter_common/baxter_description/meshes/upper_forearm/W0.DAE":function W0_Model(props){var _useGLTF=(0,useGLTF.L)(W0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.W0_1.geometry,material:materials["Material_001.009"]},{type:"raw",geometry:nodes.W0_2.geometry,material:materials["Material_002.003"]},{type:"raw",geometry:nodes.W0_3.geometry,material:materials["Material_003.001"]},{type:"raw",geometry:nodes.W0_4.geometry,material:materials["Material_005.001"]}]},"package://baxter_common/baxter_description/meshes/upper_shoulder/S0.DAE":function S0_Model(props){var _useGLTF=(0,useGLTF.L)(S0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",gemometry:nodes.S0_1.geometry,material:materials["Material_002.004"]},{type:"raw",geometry:nodes.S0_2.geometry,material:materials["Material_003.002"]}]},"package://baxter_common/baxter_description/meshes/wrist/W2.DAE":function W2_Model(props){var _useGLTF=(0,useGLTF.L)(W2_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.W2_1.geometry,material:materials["Material_001.010"]},{type:"raw",geometry:nodes.W2_2.geometry,material:materials["Material_002.005"]},{type:"raw",geometry:nodes.W2_3.geometry,material:materials["Material_003.003"]}]},"package://ur_description/meshes/ur3/visual/base.dae":function base_Model(props){var nodes=(0,useGLTF.L)(base_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_014.geometry,material:nodes.eSeries_UR3e_014.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_011.geometry,material:nodes.eSeries_UR3e_011.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/forearm.dae":function forearm_Model(props){var nodes=(0,useGLTF.L)(forearm_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_033.geometry,material:nodes.eSeries_UR3e_033.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_022.geometry,material:nodes.eSeries_UR3e_022.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_023.geometry,material:nodes.eSeries_UR3e_023.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_024.geometry,material:nodes.eSeries_UR3e_024.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_025.geometry,material:nodes.eSeries_UR3e_025.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_026.geometry,material:nodes.eSeries_UR3e_026.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_028.geometry,material:nodes.eSeries_UR3e_028.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/shoulder.dae":function shoulder_Model(props){var nodes=(0,useGLTF.L)(shoulder_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_029.geometry,material:nodes.eSeries_UR3e_029.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_012.geometry,material:nodes.eSeries_UR3e_012.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_013.geometry,material:nodes.eSeries_UR3e_013.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/upperarm.dae":function upperarm_Model(props){var nodes=(0,useGLTF.L)(upperarm_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_032.geometry,material:nodes.eSeries_UR3e_032.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_031.geometry,material:nodes.eSeries_UR3e_031.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_015.geometry,material:nodes.eSeries_UR3e_015.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_016.geometry,material:nodes.eSeries_UR3e_016.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_017.geometry,material:nodes.eSeries_UR3e_017.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_018.geometry,material:nodes.eSeries_UR3e_018.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_019.geometry,material:nodes.eSeries_UR3e_019.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_020.geometry,material:nodes.eSeries_UR3e_020.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_021.geometry,material:nodes.eSeries_UR3e_021.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/wrist1.dae":function wrist1_Model(props){var nodes=(0,useGLTF.L)(wrist1_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_034.geometry,material:nodes.eSeries_UR3e_034.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_027.geometry,material:nodes.eSeries_UR3e_027.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_035.geometry,material:nodes.eSeries_UR3e_035.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/wrist2.dae":function wrist2_Model(props){var nodes=(0,useGLTF.L)(wrist2_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e.geometry,material:nodes.eSeries_UR3e.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_036.geometry,material:nodes.eSeries_UR3e_036.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_037.geometry,material:nodes.eSeries_UR3e_037.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/wrist3.dae":function wrist3_Model(props){var nodes=(0,useGLTF.L)(wrist3_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_002.geometry,material:nodes.eSeries_UR3e_002.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/collision/base.stl":function collision_base_Model(props){var nodes=(0,useGLTF.L)(collision_base_namespaceObject).nodes;return[{type:"raw",geometry:nodes.base.geometry,material:nodes.base.material}]},"package://ur_description/meshes/ur3/collision/forearm.stl":function collision_forearm_Model(props){var nodes=(0,useGLTF.L)(collision_forearm_namespaceObject).nodes;return[{type:"raw",geometry:nodes.forearm.geometry,material:nodes.forearm.material}]},"package://ur_description/meshes/ur3/collision/shoulder.stl":function collision_shoulder_Model(props){var nodes=(0,useGLTF.L)(collision_shoulder_namespaceObject).nodes;return[{type:"raw",geometry:nodes.shoulder.geometry,material:nodes.shoulder.material}]},"package://ur_description/meshes/ur3/collision/upperarm.stl":function collision_upperarm_Model(props){var nodes=(0,useGLTF.L)(collision_upperarm_namespaceObject).nodes;return[{type:"raw",geometry:nodes.upperarm.geometry,material:nodes.upperarm.material}]},"package://ur_description/meshes/ur3/collision/wrist1.stl":function collision_wrist1_Model(props){var nodes=(0,useGLTF.L)(collision_wrist1_namespaceObject).nodes;return[{type:"raw",geometry:nodes.wrist1.geometry,material:nodes.wrist1.material}]},"package://ur_description/meshes/ur3/collision/wrist2.stl":function collision_wrist2_Model(props){var nodes=(0,useGLTF.L)(collision_wrist2_namespaceObject).nodes;return[{type:"raw",geometry:nodes.wrist2.geometry,material:nodes.wrist2.material}]},"package://ur_description/meshes/ur3/collision/wrist3.stl":function collision_wrist3_Model(props){var nodes=(0,useGLTF.L)(collision_wrist3_namespaceObject).nodes;return[{type:"raw",geometry:nodes.wrist3.geometry,material:nodes.wrist3.material}]},"package://ur_description/meshes/ur5/visual/base.dae":function Ur5_base_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_base_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh002"].geometry,material:materials["Rohr.005"]},{type:"raw",geometry:nodes["ActorShape0_0-Mesh002_1"].geometry,material:materials["Scheibe.002"]}]},"package://ur_description/meshes/ur5/visual/forearm.dae":function Ur5_forearm_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_forearm_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.Actor0_001.geometry,material:materials.blau_005},{type:"raw",geometry:nodes.Actor1.geometry,material:materials.Rohr_005},{type:"raw",geometry:nodes.Actor2.geometry,material:nodes.Actor2.material},{type:"raw",geometry:nodes.Actor3.geometry,material:nodes.Actor3.material}]},"package://ur_description/meshes/ur5/visual/shoulder.dae":function Ur5_shoulder_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_shoulder_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh023"].geometry,material:materials["verbindung.005"]},{type:"raw",geometry:nodes["ActorShape0_0-Mesh023_1"].geometry,material:materials["Scheibe.003"]},{type:"raw",geometry:nodes.Actor1.geometry,material:materials["blau.004"]}]},"package://ur_description/meshes/ur5/visual/upperarm.dae":function Ur5_upperarm_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_upperarm_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh024"].geometry,material:nodes["ActorShape0_0-Mesh024"].material},{type:"raw",geometry:nodes["ActorShape0_0-Mesh024_1"].geometry,material:nodes["ActorShape0_0-Mesh024_1"].material},{type:"raw",geometry:nodes.Actor1.geometry,material:nodes.Actor1.material},{type:"raw",geometry:nodes["ActorShape2_0-Mesh011"].geometry,material:nodes["ActorShape2_0-Mesh011"].material},{type:"raw",geometry:nodes["ActorShape2_0-Mesh011_1"].geometry,material:nodes["ActorShape2_0-Mesh011_1"].material},{type:"raw",geometry:nodes.Actor3.geometry,material:materials["Rohr.006"]},{type:"raw",geometry:nodes.Actor4.geometry,material:nodes.Actor4.material}]},"package://ur_description/meshes/ur5/visual/wrist1.dae":function Ur5_wrist1_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_wrist1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh025"].geometry,material:materials.Scheibe_001},{type:"raw",geometry:nodes["ActorShape0_0-Mesh025_1"].geometry,material:materials["verbindung_001.001"]},{type:"raw",geometry:nodes.Actor1.geometry,material:materials["blau_001.001"]}]},"package://ur_description/meshes/ur5/visual/wrist2.dae":function Ur5_wrist2_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_wrist2_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh026"].geometry,material:materials.Scheibe_002},{type:"raw",geometry:nodes["ActorShape0_0-Mesh026_1"].geometry,material:materials.verbindung_002},{type:"raw",geometry:nodes.Actor1.geometry,material:materials.blau_002}]},"package://ur_description/meshes/ur5/visual/wrist3.dae":function Ur5_wrist3_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_wrist3_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh003"].geometry,material:materials.Rohr_007_001},{type:"raw",geometry:nodes["ActorShape0_0-Mesh003_1"].geometry,material:materials["SWMaterial-1_004_002_001"]}]},"package://ur_description/meshes/ur10/visual/base.dae":function Ur10_base_Model(props){var nodes=(0,useGLTF.L)(Ur10_base_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Base.geometry,material:nodes.Base.material}]},"package://ur_description/meshes/ur10/visual/forearm.dae":function Ur10_forearm_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_forearm_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0.001"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1.001"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2.001"]},{type:"raw",geometry:nodes["node-shape3-name"].geometry,material:materials["SWMaterial-3.001"]},{type:"raw",geometry:nodes["node-shape4-name"].geometry,material:materials["SWMaterial-4.001"]}]},"package://ur_description/meshes/ur10/visual/shoulder.dae":function Ur10_shoulder_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_shoulder_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0.002"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1.002"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2.002"]}]},"package://ur_description/meshes/ur10/visual/upperarm.dae":function Ur10_upperarm_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_upperarm_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0.003"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1.003"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2.003"]},{type:"raw",geometry:nodes["node-shape3-name"].geometry,material:materials["SWMaterial-3.002"]}]},"package://ur_description/meshes/ur10/visual/wrist1.dae":function Ur10_wrist1_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_wrist1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0_001"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1_001"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2_001"]}]},"package://ur_description/meshes/ur10/visual/wrist2.dae":function Ur10_wrist2_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_wrist2_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0_002"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1_002"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2_002"]}]},"package://ur_description/meshes/ur10/visual/wrist3.dae":function Ur10_wrist3_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_wrist3_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-2_003"]}]},"package://app/meshes/3DBenchy.stl":function _3DBenchy_Model(props){var nodes=(0,useGLTF.L)(_3DBenchy_namespaceObject).nodes;return[{type:"raw",geometry:nodes["3DBenchy"].geometry,material:nodes["3DBenchy"].material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/MK2-Printer/MK2-Printer.stl":function MK2Printer_Model(_){var _useGLTF=(0,useGLTF.L)(MK2Printer_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"group",position:[.01,-.27,-.06],rotation:[Math.PI/2,0,0],scale:[.001,.001,.001],children:[{type:"group",position:[-185,0,0],children:[{type:"group",position:[159.75,16,-226.22],rotation:[0,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1152.geometry,material:nodes.Body1152.material,scale:[10,10,10]}]},{type:"group",position:[-7.5,-34,-168.5],rotation:[-Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1148.geometry,material:nodes.Body1148.material,scale:[10,10,10]},{type:"group",position:[114.5,50.5,-5],rotation:[-Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1150.geometry,material:nodes.Body1150.material,scale:[10,10,10]}]},{type:"group",position:[0,55,-92],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1149.geometry,material:nodes.Body1149.material,scale:[10,10,10]}]},{type:"group",position:[-.5,50.5,-5],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1151.geometry,material:nodes.Body1151.material,scale:[10,10,10]}]}]},{type:"group",position:[221.78,26.3,-236.47],rotation:[Math.PI,0,Math.PI],children:[{type:"group",position:[45.5,15,-28],rotation:[-Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1067.geometry,material:nodes.Body1067.material,scale:[10,10,10]}]},{type:"group",position:[8.5,14.5,21.5],rotation:[-Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1070.geometry,material:nodes.Body1070.material,scale:[10,10,10]}]},{type:"group",position:[8.5,14.95,21.5],children:[{type:"raw",geometry:nodes.Body1090.geometry,material:nodes.Body1090.material,scale:[10,10,10]}]},{type:"group",position:[17.5,15,-21.85],rotation:[Math.PI,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1066.geometry,material:materials["Opaque(232,163,0)"],scale:[10,10,10]}]},{type:"raw",geometry:nodes.Body1062.geometry,material:nodes.Body1062.material,scale:[10,10,10]},{type:"group",position:[12.98,30,-30.6],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1063.geometry,material:nodes.Body1063.material,scale:[10,10,10]}]},{type:"group",position:[1.5,16.75,30],rotation:[Math.PI,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1065.geometry,material:nodes.Body1065.material,scale:[10,10,10]}]},{type:"group",position:[1,22.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1091.geometry,material:nodes.Body1091.material,scale:[10,10,10]}]},{type:"group",position:[1,7.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1092.geometry,material:nodes.Body1092.material,scale:[10,10,10]}]},{type:"group",position:[18.6,47,-56],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1069.geometry,material:nodes.Body1069.material,scale:[10,10,10]}]},{type:"group",position:[6.58,45.4,-26.81],rotation:[-Math.PI/2,0,1.56],children:[{type:"raw",geometry:nodes.Body1064.geometry,material:nodes.Body1064.material,scale:[10,10,10]}]},{type:"group",position:[21,15,21],rotation:[-Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1103.geometry,material:nodes.Body1103.material,scale:[10,10,10]}]},{type:"group",position:[-5.5,6,-62],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1104.geometry,material:nodes.Body1104.material,scale:[10,10,10]}]},{type:"group",position:[21,45,21],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1068.geometry,material:nodes.Body1068.material,scale:[10,10,10]}]},{type:"group",position:[5.5,10,-6.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1078.geometry,material:nodes.Body1078.material,scale:[10,10,10]}]},{type:"group",position:[5.5,4,-6.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1079_1.geometry,material:nodes.Body1079_1.material,scale:[10,10,10]}]},{type:"group",position:[20.5,22.4,36.25],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1080_1.geometry,material:nodes.Body1080_1.material,scale:[10,10,10]}]},{type:"group",position:[20.5,7.4,36.25],rotation:[Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1081_1.geometry,material:nodes.Body1081_1.material,scale:[10,10,10]}]},{type:"group",position:[-13.25,26.2,-45],rotation:[Math.PI/2,0,2.62],children:[{type:"raw",geometry:nodes.Body1075_1.geometry,material:nodes.Body1075_1.material,scale:[10,10,10]}]},{type:"group",position:[29.5,28,-6.5],rotation:[-Math.PI/2,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1076_1.geometry,material:nodes.Body1076_1.material,scale:[10,10,10]}]},{type:"group",position:[29.5,12.8,-6.5],rotation:[-Math.PI/2,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1077.geometry,material:nodes.Body1077.material,scale:[10,10,10]}]},{type:"group",position:[-5.5,6,-62.16],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1105.geometry,material:nodes.Body1105.material,scale:[10,10,10]}]},{type:"group",position:[5.5,-12,-6.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1100.geometry,material:nodes.Body1100.material,scale:[10,10,10]}]},{type:"group",position:[5.5,27,-6.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1074_1.geometry,material:nodes.Body1074_1.material,scale:[10,10,10]}]},{type:"group",position:[45.5,3,-16],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1096.geometry,material:nodes.Body1096.material,scale:[10,10,10]}]},{type:"group",position:[45.5,27,-16],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1097.geometry,material:nodes.Body1097.material,scale:[10,10,10]}]},{type:"group",position:[45.5,3,-40],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1098.geometry,material:nodes.Body1098.material,scale:[10,10,10]}]},{type:"group",position:[45.5,27,-40],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1099.geometry,material:nodes.Body1099.material,scale:[10,10,10]}]},{type:"group",position:[29.39,45.4,-6.6],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1093.geometry,material:nodes.Body1093.material,scale:[10,10,10]}]},{type:"group",position:[-13.25,45.4,-45],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1094.geometry,material:nodes.Body1094.material,scale:[10,10,10]}]},{type:"group",position:[5,43.5,-56],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1095.geometry,material:nodes.Body1095.material,scale:[10,10,10]}]},{type:"group",position:[40.5,27,-4.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1073_1.geometry,material:nodes.Body1073_1.material,scale:[10,10,10]}]},{type:"group",position:[36.5,3.5,5.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1071.geometry,material:nodes.Body1071.material,scale:[10,10,10]}]},{type:"group",position:[5.5,3.5,5.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1072.geometry,material:nodes.Body1072.material,scale:[10,10,10]}]},{type:"group",position:[29.5,-12,-6.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1101.geometry,material:nodes.Body1101.material,scale:[10,10,10]}]},{type:"group",position:[-12,7.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1086.geometry,material:nodes.Body1086.material,scale:[10,10,10]}]},{type:"group",position:[-12,22.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1087.geometry,material:nodes.Body1087.material,scale:[10,10,10]}]},{type:"group",position:[36.5,-5,36.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1102.geometry,material:nodes.Body1102.material,scale:[10,10,10]}]},{type:"group",position:[1,7.4,36.25],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1082_1.geometry,material:nodes.Body1082_1.material,scale:[10,10,10]}]},{type:"group",position:[-11.5,7.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1083_1.geometry,material:nodes.Body1083_1.material,scale:[10,10,10]}]},{type:"group",position:[1,22.4,36.25],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1084_1.geometry,material:nodes.Body1084_1.material,scale:[10,10,10]}]},{type:"group",position:[-11.5,22.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1085.geometry,material:nodes.Body1085.material,scale:[10,10,10]}]},{type:"group",position:[8.5,17.75,21.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1088.geometry,material:nodes.Body1088.material,scale:[10,10,10]}]},{type:"group",position:[8.5,12.25,21.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1089.geometry,material:nodes.Body1089.material,scale:[10,10,10]}]}]},{type:"group",position:[322,-62,-17],rotation:[0,0,-Math.PI/2],children:[{type:"group",position:[64.5,57.5,-11.9],children:[{type:"raw",geometry:nodes.Body1138.geometry,material:nodes.Body1138.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1139.geometry,material:nodes.Body1139.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1140.geometry,material:nodes.Body1140.material,scale:[10,10,10]}]},{type:"group",position:[17,57.01,-8.45],children:[{type:"raw",geometry:nodes.Body1141.geometry,material:nodes.Body1141.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body10.geometry,material:nodes.Body10.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body100.geometry,material:nodes.Body100.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body101.geometry,material:nodes.Body101.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body102.geometry,material:nodes.Body102.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body103.geometry,material:nodes.Body103.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body104.geometry,material:nodes.Body104.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body105.geometry,material:nodes.Body105.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body106.geometry,material:nodes.Body106.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body107.geometry,material:nodes.Body107.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body108.geometry,material:nodes.Body108.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body109.geometry,material:nodes.Body109.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body11.geometry,material:nodes.Body11.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body110.geometry,material:nodes.Body110.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body111.geometry,material:nodes.Body111.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body112.geometry,material:nodes.Body112.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body113.geometry,material:nodes.Body113.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body114.geometry,material:nodes.Body114.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body115.geometry,material:nodes.Body115.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body116.geometry,material:nodes.Body116.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body117.geometry,material:nodes.Body117.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body118.geometry,material:nodes.Body118.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body119.geometry,material:nodes.Body119.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body12.geometry,material:nodes.Body12.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body120.geometry,material:nodes.Body120.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body121.geometry,material:nodes.Body121.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body122.geometry,material:nodes.Body122.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body123.geometry,material:nodes.Body123.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body124.geometry,material:nodes.Body124.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body125.geometry,material:nodes.Body125.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body126.geometry,material:nodes.Body126.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body127.geometry,material:nodes.Body127.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body128.geometry,material:nodes.Body128.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body129.geometry,material:nodes.Body129.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body13.geometry,material:nodes.Body13.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body130.geometry,material:nodes.Body130.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body131.geometry,material:nodes.Body131.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body132.geometry,material:nodes.Body132.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body133.geometry,material:nodes.Body133.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body134.geometry,material:nodes.Body134.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body135.geometry,material:nodes.Body135.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body136.geometry,material:nodes.Body136.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body137.geometry,material:nodes.Body137.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body138.geometry,material:nodes.Body138.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body139.geometry,material:nodes.Body139.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body14.geometry,material:nodes.Body14.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body140.geometry,material:nodes.Body140.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body141.geometry,material:nodes.Body141.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body142.geometry,material:nodes.Body142.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body143.geometry,material:nodes.Body143.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body144.geometry,material:nodes.Body144.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body145.geometry,material:nodes.Body145.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body146.geometry,material:nodes.Body146.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body147.geometry,material:nodes.Body147.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body148.geometry,material:nodes.Body148.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body149.geometry,material:nodes.Body149.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body15.geometry,material:nodes.Body15.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body150.geometry,material:nodes.Body150.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body151.geometry,material:nodes.Body151.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body152.geometry,material:nodes.Body152.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body153.geometry,material:nodes.Body153.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body154.geometry,material:nodes.Body154.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body155.geometry,material:nodes.Body155.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body156.geometry,material:nodes.Body156.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body157.geometry,material:nodes.Body157.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body158.geometry,material:nodes.Body158.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body159.geometry,material:nodes.Body159.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body16.geometry,material:nodes.Body16.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body160.geometry,material:nodes.Body160.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body161.geometry,material:nodes.Body161.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body162.geometry,material:nodes.Body162.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body163.geometry,material:nodes.Body163.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body164.geometry,material:nodes.Body164.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body165.geometry,material:nodes.Body165.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body17.geometry,material:nodes.Body17.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body18.geometry,material:nodes.Body18.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body19.geometry,material:nodes.Body19.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body2.geometry,material:nodes.Body2.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body20.geometry,material:nodes.Body20.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body21.geometry,material:nodes.Body21.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body22.geometry,material:nodes.Body22.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body23.geometry,material:nodes.Body23.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body24.geometry,material:nodes.Body24.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body25.geometry,material:nodes.Body25.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body26.geometry,material:nodes.Body26.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body27.geometry,material:nodes.Body27.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body28.geometry,material:nodes.Body28.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body29.geometry,material:nodes.Body29.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body3.geometry,material:nodes.Body3.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body30.geometry,material:nodes.Body30.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body31.geometry,material:nodes.Body31.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body32.geometry,material:nodes.Body32.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body33.geometry,material:nodes.Body33.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body34.geometry,material:nodes.Body34.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body35.geometry,material:nodes.Body35.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body36.geometry,material:nodes.Body36.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body37.geometry,material:nodes.Body37.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body38.geometry,material:nodes.Body38.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body39.geometry,material:nodes.Body39.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body4.geometry,material:nodes.Body4.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body40.geometry,material:nodes.Body40.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body41.geometry,material:nodes.Body41.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body42.geometry,material:nodes.Body42.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body43.geometry,material:nodes.Body43.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body44.geometry,material:nodes.Body44.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body45.geometry,material:nodes.Body45.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body46.geometry,material:nodes.Body46.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body47.geometry,material:nodes.Body47.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body48.geometry,material:nodes.Body48.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body49.geometry,material:nodes.Body49.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body5.geometry,material:nodes.Body5.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body50.geometry,material:nodes.Body50.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body51.geometry,material:nodes.Body51.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body52.geometry,material:nodes.Body52.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body53.geometry,material:nodes.Body53.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body54.geometry,material:nodes.Body54.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body55.geometry,material:nodes.Body55.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body56.geometry,material:nodes.Body56.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body57.geometry,material:nodes.Body57.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body58.geometry,material:nodes.Body58.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body59.geometry,material:nodes.Body59.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body6.geometry,material:nodes.Body6.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body60.geometry,material:nodes.Body60.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body61.geometry,material:nodes.Body61.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body62.geometry,material:nodes.Body62.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body63.geometry,material:nodes.Body63.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body64.geometry,material:nodes.Body64.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body65.geometry,material:nodes.Body65.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body66.geometry,material:nodes.Body66.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body67.geometry,material:nodes.Body67.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body68.geometry,material:nodes.Body68.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body69.geometry,material:nodes.Body69.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body7.geometry,material:nodes.Body7.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body70.geometry,material:nodes.Body70.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body71.geometry,material:nodes.Body71.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body72.geometry,material:nodes.Body72.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body73.geometry,material:nodes.Body73.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body74.geometry,material:nodes.Body74.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body75.geometry,material:nodes.Body75.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body76.geometry,material:nodes.Body76.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body77.geometry,material:nodes.Body77.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body78.geometry,material:nodes.Body78.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body79.geometry,material:nodes.Body79.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body8.geometry,material:nodes.Body8.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body80.geometry,material:nodes.Body80.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body81.geometry,material:nodes.Body81.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body82.geometry,material:nodes.Body82.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body83.geometry,material:nodes.Body83.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body84.geometry,material:nodes.Body84.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body85.geometry,material:nodes.Body85.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body86.geometry,material:nodes.Body86.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body87.geometry,material:nodes.Body87.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body88.geometry,material:nodes.Body88.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body89.geometry,material:nodes.Body89.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body9.geometry,material:nodes.Body9.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body90.geometry,material:nodes.Body90.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body91.geometry,material:nodes.Body91.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body92.geometry,material:nodes.Body92.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body93.geometry,material:nodes.Body93.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body94.geometry,material:nodes.Body94.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body95.geometry,material:nodes.Body95.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body96.geometry,material:nodes.Body96.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body97.geometry,material:nodes.Body97.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body98.geometry,material:nodes.Body98.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body99.geometry,material:nodes.Body99.material,scale:[10,10,10]}]},{type:"raw",geometry:nodes.Body1137.geometry,material:nodes.Body1137.material,scale:[10,10,10]},{type:"group",position:[-1.5,51,-34],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1142.geometry,material:materials["Opaque(245,245,246)"],scale:[10,10,10]}]}]},{type:"group",position:[0,0,-7.89],children:[{type:"group",position:[179.5,14.3,-242.58],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1027.geometry,material:nodes.Body1027.material,scale:[10,10,10]}]},{type:"group",position:[179.5,14.3,-197.58],rotation:[Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1028.geometry,material:nodes.Body1028.material,scale:[10,10,10]}]},{type:"group",position:[348.5,14.3,-218.33],children:[{type:"raw",geometry:nodes.Body1040.geometry,material:nodes.Body1040.material,scale:[10,10,10]}]},{type:"group",position:[367,29.3,-236.58],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1031.geometry,material:nodes.Body1031.material,scale:[10,10,10]}]},{type:"group",position:[367,29.3,-202.58],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1032.geometry,material:nodes.Body1032.material,scale:[10,10,10]}]},{type:"group",position:[3,29.3,-236.58],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1033.geometry,material:nodes.Body1033.material,scale:[10,10,10]}]},{type:"group",position:[3,29.3,-202.58],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1034.geometry,material:nodes.Body1034.material,scale:[10,10,10]}]},{type:"group",position:[217.28,14.3,-242.58],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1035.geometry,material:nodes.Body1035.material,scale:[10,10,10]}]},{type:"group",position:[191.28,14.3,-242.58],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1036.geometry,material:nodes.Body1036.material,scale:[10,10,10]}]},{type:"group",position:[204.78,14.3,-197.58],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1037.geometry,material:nodes.Body1037.material,scale:[10,10,10]}]},{type:"group",position:[-29,-9.2,-218.33],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1038.geometry,material:nodes.Body1038.material,scale:[10,10,10]}]},{type:"group",position:[348.5,7.8,-218.33],rotation:[-Math.PI/2,0,-Math.PI/6],children:[{type:"raw",geometry:nodes.Body1047.geometry,material:nodes.Body1047.material,scale:[10,10,10]}]},{type:"group",position:[370.5,14.3,-242.58],rotation:[-Math.PI,1.57,0],children:[{type:"raw",geometry:nodes.Body1056.geometry,material:nodes.Body1056.material,scale:[10,10,10]}]},{type:"group",position:[370.5,14.3,-197.58],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1057.geometry,material:nodes.Body1057.material,scale:[10,10,10]}]},{type:"group",position:[13.28,22.58,-240.78],rotation:[0,0,1.31],children:[{type:"raw",geometry:nodes.Body1048.geometry,material:nodes.Body1048.material,scale:[10,10,10]}]},{type:"group",position:[26.72,36.02,-240.78],rotation:[0,0,-.26],children:[{type:"raw",geometry:nodes.Body1049.geometry,material:nodes.Body1049.material,scale:[10,10,10]}]},{type:"group",position:[343.28,36.02,-240.78],rotation:[0,0,.26],children:[{type:"raw",geometry:nodes.Body1050.geometry,material:nodes.Body1050.material,scale:[10,10,10]}]},{type:"group",position:[356.72,22.58,-240.78],rotation:[0,0,1.83],children:[{type:"raw",geometry:nodes.Body1051.geometry,material:nodes.Body1051.material,scale:[10,10,10]}]},{type:"group",position:[-29,19.7,-218.33],children:[{type:"raw",geometry:nodes.Body1039.geometry,material:nodes.Body1039.material,scale:[10,10,10]}]},{type:"group",position:[24,19.05,-180.18],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1060.geometry,material:nodes.Body1060.material,scale:[10,10,10]}]},{type:"group",position:[24,9.55,-180.18],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1061.geometry,material:nodes.Body1061.material,scale:[10,10,10]}]},{type:"group",position:[374.5,14.3,-242.58],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1045.geometry,material:nodes.Body1045.material,scale:[10,10,10]}]},{type:"group",position:[374.5,14.3,-197.58],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1046.geometry,material:nodes.Body1046.material,scale:[10,10,10]}]},{type:"group",position:[13.28,22.58,-252.58],children:[{type:"raw",geometry:nodes.Body1052.geometry,material:nodes.Body1052.material,scale:[10,10,10]}]},{type:"group",position:[26.72,36.02,-252.58],children:[{type:"raw",geometry:nodes.Body1053.geometry,material:nodes.Body1053.material,scale:[10,10,10]}]},{type:"group",position:[356.72,22.58,-252.58],children:[{type:"raw",geometry:nodes.Body1054.geometry,material:nodes.Body1054.material,scale:[10,10,10]}]},{type:"group",position:[343.28,36.02,-252.58],children:[{type:"raw",geometry:nodes.Body1055.geometry,material:nodes.Body1055.material,scale:[10,10,10]}]},{type:"group",position:[-44.5,19.3,-233.83],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1041.geometry,material:nodes.Body1041.material,scale:[10,10,10]}]},{type:"group",position:[-13.5,19.3,-233.83],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1042.geometry,material:nodes.Body1042.material,scale:[10,10,10]}]},{type:"group",position:[-13.5,19.3,-202.83],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1043.geometry,material:nodes.Body1043.material,scale:[10,10,10]}]},{type:"group",position:[348.5,20.8,-218.33],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1044.geometry,material:nodes.Body1044.material,scale:[10,10,10]}]},{type:"group",position:[24,9.55,-183.38],rotation:[Math.PI/2,-Math.PI/2,0],children:[{type:"group",position:[-7.55,0,-9],children:[{type:"raw",geometry:nodes.Body1058.geometry,material:nodes.Body1058.material,scale:[10,10,10]}]},{type:"raw",geometry:nodes.Body1059.geometry,material:nodes.Body1059.material,scale:[10,10,10]}]},{type:"group",position:[187.78,26.3,-197.58],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1026.geometry,material:nodes.Body1026.material,scale:[10,10,10]}]},{type:"group",position:[367,29.3,-248.58],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1024.geometry,material:nodes.Body1024.material,scale:[10,10,10]}]},{type:"group",position:[3,29.3,-248.58],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1025.geometry,material:nodes.Body1025.material,scale:[10,10,10]}]},{type:"group",position:[20,29.3,-252.58],rotation:[0,0,Math.PI/4],children:[{type:"raw",geometry:nodes.Body1029.geometry,material:nodes.Body1029.material,scale:[10,10,10]}]},{type:"group",position:[350,29.3,-252.58],rotation:[0,0,-Math.PI/4],children:[{type:"raw",geometry:nodes.Body1030.geometry,material:nodes.Body1030.material,scale:[10,10,10]}]}]},{type:"group",position:[367,29.3,-210],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1.geometry,material:nodes.Body1.material,scale:[10,10,10]}]},{type:"group",position:[3,29.3,-210],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1001.geometry,material:nodes.Body1001.material,scale:[10,10,10]}]},{type:"group",position:[350,29.3,-35],rotation:[-Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1002.geometry,material:nodes.Body1002.material,scale:[10,10,10]}]},{type:"group",position:[20,29.3,-35],rotation:[-Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1003.geometry,material:nodes.Body1003.material,scale:[10,10,10]}]},{type:"group",position:[30,4,-360],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1004.geometry,material:nodes.Body1004.material,scale:[10,10,10]}]},{type:"group",position:[365.5,44.8,-55.5],children:[{type:"raw",geometry:nodes.Body1021.geometry,material:nodes.Body1021.material,scale:[10,10,10]}]},{type:"group",position:[340,4,-360],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1005.geometry,material:nodes.Body1005.material,scale:[10,10,10]}]},{type:"group",position:[4.5,13.8,-55.5],children:[{type:"raw",geometry:nodes.Body1014.geometry,material:nodes.Body1014.material,scale:[10,10,10]}]},{type:"group",position:[35.5,13.8,-55.5],children:[{type:"raw",geometry:nodes.Body1015.geometry,material:nodes.Body1015.material,scale:[10,10,10]}]},{type:"group",position:[4.5,44.8,-55.5],children:[{type:"raw",geometry:nodes.Body1016.geometry,material:nodes.Body1016.material,scale:[10,10,10]}]},{type:"group",position:[35.5,44.8,-55.5],children:[{type:"raw",geometry:nodes.Body1017.geometry,material:nodes.Body1017.material,scale:[10,10,10]}]},{type:"group",position:[334.5,13.8,-55.5],children:[{type:"raw",geometry:nodes.Body1018.geometry,material:nodes.Body1018.material,scale:[10,10,10]}]},{type:"group",position:[365.5,13.8,-55.5],children:[{type:"raw",geometry:nodes.Body1019.geometry,material:nodes.Body1019.material,scale:[10,10,10]}]},{type:"group",position:[334.5,44.8,-55.5],children:[{type:"raw",geometry:nodes.Body1020.geometry,material:nodes.Body1020.material,scale:[10,10,10]}]},{type:"group",position:[4.5,13.8,-55],children:[{type:"raw",geometry:nodes.Body1006.geometry,material:nodes.Body1006.material,scale:[10,10,10]}]},{type:"group",position:[35.5,13.8,-55],children:[{type:"raw",geometry:nodes.Body1007.geometry,material:nodes.Body1007.material,scale:[10,10,10]}]},{type:"group",position:[4.5,44.8,-55],children:[{type:"raw",geometry:nodes.Body1008.geometry,material:nodes.Body1008.material,scale:[10,10,10]}]},{type:"group",position:[35.5,44.8,-55],children:[{type:"raw",geometry:nodes.Body1009.geometry,material:nodes.Body1009.material,scale:[10,10,10]}]},{type:"group",position:[334.5,13.8,-55],children:[{type:"raw",geometry:nodes.Body1010.geometry,material:nodes.Body1010.material,scale:[10,10,10]}]},{type:"group",position:[365.5,13.8,-55],children:[{type:"raw",geometry:nodes.Body1011.geometry,material:nodes.Body1011.material,scale:[10,10,10]}]},{type:"group",position:[334.5,44.8,-55],children:[{type:"raw",geometry:nodes.Body1012.geometry,material:nodes.Body1012.material,scale:[10,10,10]}]},{type:"group",position:[365.5,44.8,-55.5],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1013.geometry,material:nodes.Body1013.material,scale:[10,10,10]}]},{type:"group",position:[350,29.3,-52],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1022.geometry,material:nodes.Body1022.material,scale:[10,10,10]}]},{type:"group",position:[20,29.3,-52],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1023.geometry,material:nodes.Body1023.material,scale:[10,10,10]}]},{type:"group",position:[184.6,273.14,-14.87],rotation:[2.36,0,0],children:[{type:"group",position:[59.23,-1.7,1.25],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1147.geometry,material:nodes.Body1147.material,scale:[10,10,10]}]},{type:"group",position:[.75,13.2,2.5],rotation:[-Math.PI,0,0],children:[{type:"group",scale:[10,10,10],children:[{type:"raw",geometry:nodes.Body1054_1.geometry,material:materials["Opaque(0,192,0)"]},{type:"raw",geometry:nodes.Body1054_2.geometry,material:materials["Opaque(31,251,255)"]}]}]},{type:"raw",geometry:nodes.Body1143.geometry,material:nodes.Body1143.material,scale:[10,10,10]},{type:"group",position:[-53.45,70.31,22.5],rotation:[2.36,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1145.geometry,material:nodes.Body1145.material,scale:[10,10,10]}]},{type:"group",position:[54.95,70.31,22.85],rotation:[2.36,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1146.geometry,material:nodes.Body1146.material,scale:[10,10,10]}]}]},{type:"group",position:[0,32,20],children:[{type:"group",position:[184.6,12,-29.28],rotation:[0,0,0],children:[{type:"raw",geometry:nodes.Body1136.geometry,material:nodes.Body1136.material,scale:[10,10,10]}]},{type:"group",position:[289.5,125.78,-52.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1125_1.geometry,material:nodes.Body1125_1.material,scale:[10,10,10]}]},{type:"group",position:[80.5,125.78,-52.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1126_1.geometry,material:nodes.Body1126_1.material,scale:[10,10,10]}]},{type:"group",position:[80.5,-83.22,-52.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1127.geometry,material:nodes.Body1127.material,scale:[10,10,10]}]},{type:"group",position:[289.5,-83.22,-52.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1128.geometry,material:nodes.Body1128.material,scale:[10,10,10]}]},{type:"group",position:[78,-103.72,-63.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1129.geometry,material:nodes.Body1129.material,scale:[10,10,10]}]},{type:"group",position:[78,-112.22,-70.59],rotation:[-Math.PI/2,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1116.geometry,material:nodes.Body1116.material,scale:[10,10,10]}]},{type:"group",position:[100,8.75,-47],children:[{type:"raw",geometry:nodes.Body1106.geometry,material:nodes.Body1106.material,scale:[10,10,10]}]},{type:"group",position:[270,8.75,-47],children:[{type:"raw",geometry:nodes.Body1107.geometry,material:nodes.Body1107.material,scale:[10,10,10]}]},{type:"group",position:[15,-193.72,-57.59],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1108.geometry,material:nodes.Body1108.material,scale:[10,10,10]}]},{type:"group",position:[184.6,144.25,-30],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1133.geometry,material:nodes.Body1133.material,scale:[10,10,10]}]},{type:"group",position:[270,22.28,-47],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1112.geometry,material:nodes.Body1112.material,scale:[10,10,10]}]},{type:"group",position:[100,-13.72,-47],children:[{type:"raw",geometry:nodes.Body1110.geometry,material:nodes.Body1110.material,scale:[10,10,10]}]},{type:"group",position:[100,56.28,-47],children:[{type:"raw",geometry:nodes.Body1111.geometry,material:nodes.Body1111.material,scale:[10,10,10]}]},{type:"group",position:[185,21.28,-63.59],children:[{type:"raw",geometry:nodes.Body1115.geometry,material:nodes.Body1115.material,scale:[10,10,10]}]},{type:"group",position:[216,-120.25,-28.96],rotation:[Math.PI,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1113.geometry,material:nodes.Body1113.material,scale:[10,10,10]}]},{type:"group",position:[174.6,144.25,-30],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1122_1.geometry,material:nodes.Body1122_1.material,scale:[10,10,10]}]},{type:"group",position:[78,-103.72,-68.59],children:[{type:"raw",geometry:nodes.Body1130.geometry,material:nodes.Body1130.material,scale:[10,10,10]}]},{type:"group",position:[188.5,-120.25,-28.96],rotation:[-Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1114.geometry,material:nodes.Body1114.material,scale:[10,10,10]}]},{type:"group",position:[186,-132,-48.34],children:[{type:"raw",geometry:nodes.Body1117.geometry,material:nodes.Body1117.material,scale:[10,10,10]}]},{type:"group",position:[176.5,-132,-48.34],children:[{type:"raw",geometry:nodes.Body1118.geometry,material:nodes.Body1118.material,scale:[10,10,10]}]},{type:"group",position:[196,-135.75,-44.46],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1131.geometry,material:nodes.Body1131.material,scale:[10,10,10]}]},{type:"group",position:[196,-135.75,-13.46],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1132.geometry,material:nodes.Body1132.material,scale:[10,10,10]}]},{type:"group",position:[185,41.28,-48.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1123_1.geometry,material:nodes.Body1123_1.material,scale:[10,10,10]}]},{type:"group",position:[185,.28,-48.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1124_1.geometry,material:nodes.Body1124_1.material,scale:[10,10,10]}]},{type:"group",position:[194.6,144.25,-30],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1121.geometry,material:nodes.Body1121.material,scale:[10,10,10]}]},{type:"group",position:[176.5,-132,-45.14],rotation:[Math.PI/2,0,Math.PI],children:[{type:"group",position:[-7.55,0,-9],children:[{type:"raw",geometry:nodes.Body1134.geometry,material:nodes.Body1134.material,scale:[10,10,10]}]},{type:"raw",geometry:nodes.Body1135.geometry,material:nodes.Body1135.material,scale:[10,10,10]}]},{type:"group",position:[174.6,144.25,-30],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1120.geometry,material:nodes.Body1120.material,scale:[10,10,10]}]},{type:"group",position:[194.6,144.25,-30],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1119.geometry,material:nodes.Body1119.material,scale:[10,10,10]}]},{type:"group",position:[177.5,38.78,-26.59],rotation:[0,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1109.geometry,material:nodes.Body1109.material,scale:[10,10,10]}]}]}]},{type:"group",position:[-170.6,1038.41,1090.43],rotation:[0,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1195.geometry,material:nodes.Body1195.material,scale:[10,10,10]}]},{type:"group",position:[170.6,541.82,1347.72],rotation:[-.96,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1194.geometry,material:nodes.Body1194.material,scale:[10,10,10]}]},{type:"group",position:[-164.2,-2.2,-360],rotation:[Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1242.geometry,material:nodes.Body1242.material,scale:[10,10,10]}]},{type:"group",position:[164.2,-2.2,-360],rotation:[Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1245.geometry,material:nodes.Body1245.material,scale:[10,10,10]}]},{type:"group",position:[-165.1,-2.2,-341],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1243.geometry,material:nodes.Body1243.material,scale:[10,10,10]}]},{type:"group",position:[165.1,-2.2,-341],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1244.geometry,material:nodes.Body1244.material,scale:[10,10,10]}]},{type:"group",position:[177.8,46,-2],rotation:[-Math.PI,1.57,0],children:[{type:"raw",geometry:nodes.Body1190.geometry,material:materials["Opaque(135,140,140)"],scale:[10,10,10]}]},{type:"group",position:[161,-60.5,-193],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1196.geometry,material:nodes.Body1196.material,scale:[10,10,10]}]},{type:"group",position:[161,-60.5,-76],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1197.geometry,material:nodes.Body1197.material,scale:[10,10,10]}]},{type:"group",position:[0,40.75,13],children:[{type:"group",position:[-165,150,-15],children:[{type:"raw",geometry:nodes.Body1153.geometry,material:nodes.Body1153.material,scale:[10,10,10]}]},{type:"group",position:[165,150,-15],children:[{type:"raw",geometry:nodes.Body1154.geometry,material:nodes.Body1154.material,scale:[10,10,10]}]},{type:"group",position:[180,165,-15],rotation:[0,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1155.geometry,material:nodes.Body1155.material,scale:[10,10,10]}]},{type:"group",position:[180,-165,-15],rotation:[0,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1156.geometry,material:nodes.Body1156.material,scale:[10,10,10]}]},{type:"group",position:[180,-55.75,-373],rotation:[-Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1159.geometry,material:nodes.Body1159.material,scale:[10,10,10]}]},{type:"group",position:[-165,-55.75,-30],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1157.geometry,material:nodes.Body1157.material,scale:[10,10,10]}]},{type:"group",position:[165,-55.75,-30],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1158.geometry,material:nodes.Body1158.material,scale:[10,10,10]}]},{type:"group",position:[-164,-74.75,-372],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1172.geometry,material:nodes.Body1172.material,scale:[10,10,10]}]},{type:"group",position:[164,-70.75,-372],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1173.geometry,material:nodes.Body1173.material,scale:[10,10,10]}]},{type:"group",position:[-180,-64.75,-6],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1166.geometry,material:nodes.Body1166.material,scale:[10,10,10]}]},{type:"group",position:[-150,-64.75,-6],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1167.geometry,material:nodes.Body1167.material,scale:[10,10,10]}]},{type:"group",position:[182,-64.75,-6],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1169.geometry,material:nodes.Body1169.material,scale:[10,10,10]}]},{type:"group",position:[148,-64.75,-6],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1170.geometry,material:nodes.Body1170.material,scale:[10,10,10]}]},{type:"group",position:[-165,165,5],rotation:[-Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1180.geometry,material:nodes.Body1180.material,scale:[10,10,10]}]},{type:"group",position:[-165,-165,5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1181.geometry,material:nodes.Body1181.material,scale:[10,10,10]}]},{type:"group",position:[165,165,5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1186.geometry,material:nodes.Body1186.material,scale:[10,10,10]}]},{type:"group",position:[165,-165,5],rotation:[-Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1187.geometry,material:nodes.Body1187.material,scale:[10,10,10]}]},{type:"group",position:[-165,165,5],rotation:[-Math.PI,0,2.56],children:[{type:"raw",geometry:nodes.Body1182.geometry,material:nodes.Body1182.material,scale:[10,10,10]}]},{type:"group",position:[-165,-165,5],rotation:[Math.PI,0,2.56],children:[{type:"raw",geometry:nodes.Body1183.geometry,material:nodes.Body1183.material,scale:[10,10,10]}]},{type:"group",position:[165,165,5],rotation:[Math.PI,0,-.58],children:[{type:"raw",geometry:nodes.Body1184.geometry,material:nodes.Body1184.material,scale:[10,10,10]}]},{type:"group",position:[165,-165,5],rotation:[Math.PI,0,-.58],children:[{type:"raw",geometry:nodes.Body1185.geometry,material:nodes.Body1185.material,scale:[10,10,10]}]},{type:"group",position:[-85,157.5,-38.5],children:[{type:"raw",geometry:nodes.Body1160.geometry,material:nodes.Body1160.material,scale:[10,10,10]}]},{type:"group",position:[85,157.5,-38.5],children:[{type:"raw",geometry:nodes.Body1161.geometry,material:nodes.Body1161.material,scale:[10,10,10]}]},{type:"group",position:[-85,-157.5,-38.5],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1162.geometry,material:nodes.Body1162.material,scale:[10,10,10]}]},{type:"group",position:[85,-157.5,-38.5],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1163.geometry,material:nodes.Body1163.material,scale:[10,10,10]}]},{type:"group",position:[-165,-70.75,-30],rotation:[0,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1168.geometry,material:nodes.Body1168.material,scale:[10,10,10]}]},{type:"group",position:[165,-70.75,-30],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1171.geometry,material:nodes.Body1171.material,scale:[10,10,10]}]},{type:"group",position:[-150,-55.75,-358],rotation:[Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1174.geometry,material:nodes.Body1174.material,scale:[10,10,10]}]},{type:"group",position:[150,-55.75,-358],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1175.geometry,material:nodes.Body1175.material,scale:[10,10,10]}]},{type:"group",position:[-150,150,-15],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1176.geometry,material:nodes.Body1176.material,scale:[10,10,10]}]},{type:"group",position:[-150,-150,-15],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1177.geometry,material:nodes.Body1177.material,scale:[10,10,10]}]},{type:"group",position:[150,150,-15],rotation:[-Math.PI,1.57,0],children:[{type:"raw",geometry:nodes.Body1178.geometry,material:nodes.Body1178.material,scale:[10,10,10]}]},{type:"group",position:[150,-150,-15],rotation:[Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1179.geometry,material:nodes.Body1179.material,scale:[10,10,10]}]},{type:"group",position:[-150.1,-34.75,-298],rotation:[0,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1164.geometry,material:nodes.Body1164.material,scale:[10,10,10]}]},{type:"group",position:[180.1,-34.75,-298],rotation:[0,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1165.geometry,material:nodes.Body1165.material,scale:[10,10,10]}]}]},{type:"group",position:[-192.5,-36.5,-168.5],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1238.geometry,material:nodes.Body1238.material,scale:[10,10,10]}]},{type:"group",position:[126.5,-139.25,-17],rotation:[-Math.PI/2,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1198.geometry,material:nodes.Body1198.material,scale:[10,10,10]}]},{type:"group",position:[194.25,24.3,-198.47],rotation:[Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1246.geometry,material:materials["Opaque(255,132,2)"],scale:[10,10,10]}]},{type:"group",position:[18,-117.25,19.96],rotation:[0,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1191.geometry,material:nodes.Body1191.material,scale:[10,10,10]}]},{type:"group",position:[-.4,191.15,-2],rotation:[-Math.PI/2,0,0],children:[{type:"group",position:[.02,-4.95,-14.3],rotation:[1.73,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1192.geometry,material:materials["Opaque(254,114,55)"],scale:[10,10,10]}]},{type:"group",rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1193.geometry,material:nodes.Body1193.material,scale:[10,10,10]}]}]},{type:"group",position:[85,46.08,-27],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1239.geometry,material:nodes.Body1239.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body2001.geometry,material:nodes.Body2001.material,scale:[10,10,10]}]},{type:"group",position:[-85,96.48,-27],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1240.geometry,material:nodes.Body1240.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body2002.geometry,material:nodes.Body2002.material,scale:[10,10,10]}]},{type:"group",position:[-85,10.08,-27],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1241.geometry,material:nodes.Body1241.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body2003.geometry,material:nodes.Body2003.material,scale:[10,10,10]}]},{type:"group",position:[-.75,-310.07,-900.2],rotation:[1.24,0,0],children:[{type:"raw",geometry:nodes.Body1218.geometry,material:nodes.Body1218.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1206.geometry,material:nodes.Body1206.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1233.geometry,material:nodes.Body1233.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1232.geometry,material:nodes.Body1232.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1222.geometry,material:nodes.Body1222.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1223.geometry,material:materials["Opaque(57,57,57)"],scale:[10,10,10]},{type:"raw",geometry:nodes.Body1237.geometry,material:nodes.Body1237.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1234.geometry,material:nodes.Body1234.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1221.geometry,material:nodes.Body1221.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1229.geometry,material:nodes.Body1229.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1217.geometry,material:nodes.Body1217.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1227.geometry,material:nodes.Body1227.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1213.geometry,material:nodes.Body1213.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1207.geometry,material:nodes.Body1207.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1212.geometry,material:nodes.Body1212.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1220.geometry,material:nodes.Body1220.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1216.geometry,material:nodes.Body1216.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1209.geometry,material:nodes.Body1209.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1211.geometry,material:nodes.Body1211.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1225.geometry,material:nodes.Body1225.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1228.geometry,material:nodes.Body1228.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1210.geometry,material:nodes.Body1210.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1235.geometry,material:nodes.Body1235.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1204.geometry,material:nodes.Body1204.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1231.geometry,material:nodes.Body1231.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1224.geometry,material:nodes.Body1224.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1201.geometry,material:nodes.Body1201.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1205.geometry,material:nodes.Body1205.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1226.geometry,material:nodes.Body1226.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1202.geometry,material:nodes.Body1202.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1236.geometry,material:nodes.Body1236.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1203.geometry,material:nodes.Body1203.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1215.geometry,material:nodes.Body1215.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1214.geometry,material:nodes.Body1214.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1208.geometry,material:nodes.Body1208.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1230.geometry,material:nodes.Body1230.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1219.geometry,material:nodes.Body1219.material,scale:[10,10,10]}]},{type:"group",position:[-138.5,25,-55],rotation:[-Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1188.geometry,material:nodes.Body1188.material,scale:[10,10,10]}]},{type:"group",position:[138.5,25,-55],rotation:[-Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1189.geometry,material:nodes.Body1189.material,scale:[10,10,10]}]},{type:"group",position:[191.7,19,-370],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1199.geometry,material:nodes.Body1199.material,scale:[10,10,10]}]},{type:"group",position:[-191.7,19,-370],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1200.geometry,material:nodes.Body1200.material,scale:[10,10,10]}]}]}]}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/MK2-Printer.stl":function Collision_Mk2_Printer_Model(props){var nodes=(0,useGLTF.L)(Collision_MK2_Printer_namespaceObject).nodes;return[{type:"raw",geometry:nodes["Collision-MK2-Printer"].geometry,material:nodes["Collision-MK2-Printer"].material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/Box/Box.stl":function Box_Model(props){var nodes=(0,useGLTF.L)(Box_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Box.geometry,material:nodes.Box.material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/Box.stl":function Collision_Box_Model(props){var nodes=(0,useGLTF.L)(Collision_Box_namespaceObject).nodes;return[{type:"raw",geometry:nodes["Collision-Box"].geometry,material:nodes["Collision-Box"].material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/ur3e-Pedestal/Pedestal.stl":function Pedestal_Model(props){var nodes=(0,useGLTF.L)(Pedestal_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Pedestal.geometry,material:nodes.Pedestal.material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/Pedestal.stl":function Collision_Pedestal_Model(props){var nodes=(0,useGLTF.L)(Collision_Pedestal_namespaceObject).nodes;return[{type:"raw",geometry:nodes["Collision-Pedestal"].geometry,material:nodes["Collision-Pedestal"].material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/Table/Table.stl":function Table_Model(props){var nodes=(0,useGLTF.L)(Table_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Table.geometry,material:nodes.Table.material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/Table.stl":function Collision_Table_Model(props){var nodes=(0,useGLTF.L)(Collision_Table_namespaceObject).nodes;return[{type:"raw",geometry:nodes["Collision-Table"].geometry,material:nodes["Collision-Table"].material}]},"package://app/meshes/LocationMarker.stl":function LocationMarker_Model(props){var nodes=(0,useGLTF.L)(LocationMarker_namespaceObject).nodes;return[{type:"group",children:[{type:"raw",geometry:nodes.LocationMarker.geometry,material:nodes.LocationMarker.material}]}]},"package://app/meshes/OpenWaypointMarker.stl":function OpenWaypointMarker_Model(props){var nodes=(0,useGLTF.L)(OpenWaypointMarker_namespaceObject).nodes;return[{type:"group",children:[{type:"raw",geometry:nodes.OpenWaypointMarker.geometry,material:nodes.OpenWaypointMarker.material}]}]}},MeshLookup=function MeshLookup(path){return MeshLookupTable[path]()};MeshLookup.__docgenInfo={description:"",methods:[],displayName:"MeshLookup"},"undefined"!=typeof STORYBOOK_REACT_CLASSES&&(STORYBOOK_REACT_CLASSES["src/stories/meshes/MeshLookup.js"]={name:"MeshLookup",docgenInfo:MeshLookup.__docgenInfo,path:"src/stories/meshes/MeshLookup.js"})},"./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.(js%7Cjsx%7Cts%7Ctsx))$":function(module,__unused_webpack_exports,__webpack_require__){var map={"./stories/Animation.stories.js":"./src/stories/Animation.stories.js","./stories/CoFrame.stories.js":"./src/stories/CoFrame.stories.js","./stories/ItemMovement.stories.js":"./src/stories/ItemMovement.stories.js","./stories/MeshDebug.stories.js":"./src/stories/MeshDebug.stories.js","./stories/Random.stories.js":"./src/stories/Random.stories.js","./stories/TFMovement.stories.js":"./src/stories/TFMovement.stories.js"};function webpackContext(req){var id=webpackContextResolve(req);return __webpack_require__(id)}function webpackContextResolve(req){if(!__webpack_require__.o(map,req)){var e=new Error("Cannot find module '"+req+"'");throw e.code="MODULE_NOT_FOUND",e}return map[req]}webpackContext.keys=function webpackContextKeys(){return Object.keys(map)},webpackContext.resolve=webpackContextResolve,module.exports=webpackContext,webpackContext.id="./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.(js%7Cjsx%7Cts%7Ctsx))$"},"./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.mdx)$":function(module){function webpackEmptyContext(req){var e=new Error("Cannot find module '"+req+"'");throw e.code="MODULE_NOT_FOUND",e}webpackEmptyContext.keys=function(){return[]},webpackEmptyContext.resolve=webpackEmptyContext,webpackEmptyContext.id="./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.mdx)$",module.exports=webpackEmptyContext},"./storybook-init-framework-entry.js":function(__unused_webpack_module,__unused_webpack___webpack_exports__,__webpack_require__){"use strict";__webpack_require__("./node_modules/@storybook/react/dist/esm/client/index.js")},"?4f7e":function(){},"./generated-stories-entry.cjs":function(module,__unused_webpack_exports,__webpack_require__){"use strict";module=__webpack_require__.nmd(module),(0,__webpack_require__("./node_modules/@storybook/react/dist/esm/client/index.js").configure)([__webpack_require__("./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.mdx)$"),__webpack_require__("./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.(js%7Cjsx%7Cts%7Ctsx))$")],module,!1)}},function(__webpack_require__){var __webpack_exec__=function(moduleId){return __webpack_require__(__webpack_require__.s=moduleId)};__webpack_require__.O(0,[819],(function(){return __webpack_exec__("./node_modules/@storybook/core-client/dist/esm/globals/polyfills.js"),__webpack_exec__("./node_modules/@storybook/core-client/dist/esm/globals/globals.js"),__webpack_exec__("./storybook-init-framework-entry.js"),__webpack_exec__("./node_modules/@storybook/react/dist/esm/client/docs/config-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/react/dist/esm/client/preview/config-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-links/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-docs/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-actions/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-backgrounds/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-measure/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-outline/preview.js-generated-config-entry.js"),__webpack_exec__("./.storybook/preview.js-generated-config-entry.js"),__webpack_exec__("./generated-stories-entry.cjs")}));__webpack_require__.O()}]); \ No newline at end of file diff --git a/docs/main.8b8d1320.iframe.bundle.js b/docs/main.8b8d1320.iframe.bundle.js deleted file mode 100644 index 9e01666..0000000 --- a/docs/main.8b8d1320.iframe.bundle.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunkrobot_scene=self.webpackChunkrobot_scene||[]).push([[179],{"./src/stories/Animation.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{Animation:function(){return Animation},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/slicedToArray.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"Animation",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var Animation=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__.Z)(args,_excluded),_useDefaultSceneStore=(0,_components__WEBPACK_IMPORTED_MODULE_2__.x2)((function(state){return[state.play,state.pause,state.reset]})),_useDefaultSceneStore2=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__.Z)(_useDefaultSceneStore,3),play=_useDefaultSceneStore2[0],pause=_useDefaultSceneStore2[1],reset=_useDefaultSceneStore2[2];return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)("div",{style:{height:"calc(100vh - 3rem)",width:"calc(100vw - 2rem)"},children:[(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2})),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)("div",{style:{textAlign:"center"},children:[(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return play()},children:"Play"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return play(.5)},children:"Play (0.5x)"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return play(2)},children:"Play (2x)"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return pause()},children:"Pause"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return reset(0)},children:"Reset"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return reset(Math.PI/2)},children:"Reset (0.25)"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return reset(Math.PI)},children:"Reset (0.5)"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){return reset(3*Math.PI/2)},children:"Reset (0.75)"})]})]})}.bind({});Animation.args={tfs:{movingFrame:{frame:"world",position:{x:function x(time){return Math.cos(time/1e3)},y:function y(time){return Math.sin(time/1e3)},z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:function x(time){return.25*Math.cos(time/1e3)+1},y:1,z:1}}},items:{colorshiftlift:{shape:"cube",name:"ColorShift/Lift",frame:"movingFrame",position:{x:0,y:0,z:function z(time){return Math.sin(time/1e3)+1}},rotation:{w:1,x:0,y:0,z:0},color:{r:function r(time){return 255*(Math.sin(time/1e3)/2+.5)},g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!0},opacity:{shape:"cube",name:"Opacity",frame:"movingFrame",position:{x:1,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:10,a:function a(time){return Math.sin(time/1e3)/2+.5}},scale:{x:.5,y:.5,z:.5},highlighted:!1},scale:{shape:"cube",name:"Scale",frame:"movingFrame",position:{x:1,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:255,b:10,a:1},scale:{x:.5,y:function y(time){return Math.sin(time/1e3)/2+1},z:.5},highlighted:!1},hidden:{shape:"cube",name:"Hidden",frame:"movingFrame",position:{x:0,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:255,a:1},scale:{x:.5,y:.5,z:.5},hidden:function hidden(time){return Math.sin(time/1e3)>0}}},lines:{},hulls:{},texts:{colorshiftlift:{value:"ColorShift/Lift",frame:"movingFrame",position:{x:0,y:0,z:function z(time){return Math.sin(time/1e3)+1.5}},color:{r:function r(time){return 255*(Math.sin(time/1e3)/2+.5)},g:10,b:10,a:1}},opacity:{value:"Opacity",frame:"movingFrame",position:{x:1,y:1,z:1.5},color:{r:10,g:10,b:10,a:function a(time){return Math.sin(time/1e3)/2+.5}}},scale:{value:"Scale",frame:"movingFrame",position:{x:1,y:0,z:1.5},color:{r:10,g:255,b:10,a:1}},hidden:{value:"Hidden",frame:"movingFrame",position:{x:0,y:1,z:1.5},color:{r:10,g:10,b:255,a:1},hidden:function hidden(time){return Math.sin(time/1e3)>0}}},displayTfs:!0,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},Animation.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n\n const [play, pause, reset] = useDefaultSceneStore(state=>[state.play,state.pause,state.reset]);\n\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n\n return (\n
\n \n
\n \n \n \n \n \n \n \n \n
\n
)\n}"}},Animation.parameters);var __namedExportsOrder=["Animation"]},"./src/stories/CoFrame.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{CoFrame:function(){return CoFrame},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./src/stories/meshes/MeshLookup.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"CoFrame",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var CoFrame=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_5__.Z)(args,_excluded);return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)("div",{style:{height:"calc(100vh - 2rem)",width:"calc(100vw - 2rem)"},children:(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2,meshLookup:_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__.z}))})}.bind({});CoFrame.storyName="CoFrame",CoFrame.args={tfs:{"thingType-98892a7c1c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892b3a1c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892bd01c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892ce81c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892d7e1c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"thingType-98892e001c1911ecbe2600155d1a70a2":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"robot-agent-988926121c1911eccbe2600155d1a70a2":{frame:"pedestal",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"human-agent-ccbe2600155d1a70a2988926121c1911e":{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10":{frame:"table",position:{x:-.28,y:-.04,z:.67},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},"toolType-assembly-jig":{frame:"world",position:{x:.2,y:.28,z:.14},rotation:{w:-.5,x:.5,y:-.5,z:-.5},scale:{x:1,y:1,z:1}},"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7":{frame:"world",position:{x:-.85,y:-.25,z:-.75},rotation:{w:.707,x:0,y:0,z:.707},scale:{x:1,y:1,z:1},transformMode:"translate"},"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b":{frame:"world",position:{x:-.85,y:-.25,z:-.75},rotation:{w:.707,x:0,y:0,z:.707},scale:{x:1,y:1,z:1}},"machine-9133367a-f691-4d94-9764-50d9685db30a":{frame:"world",position:{x:.85,y:-.25,z:-.75},rotation:{w:.707,x:0,y:0,z:-.707},scale:{x:1,y:1,z:1}},"machine-67d870e0-511d-4662-bf0d-8478f5e860f8":{frame:"world",position:{x:.85,y:-.25,z:-.75},rotation:{w:.707,x:0,y:0,z:-.707},scale:{x:1,y:1,z:1}},"toolType-transport-jig":{frame:"world",position:{x:.3,y:.28,z:.14},rotation:{w:-.5,x:.5,y:-.5,z:-.5},scale:{x:1,y:1,z:1}},table:{frame:"world",position:{x:0,y:.36,z:-.37},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},pedestal:{frame:"world",position:{x:0,y:-.15,z:-.38},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},simulatedTool0:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:.11666648089885712,y:.2694645017385483,z:.6366749751567841},rotation:{w:-.37005797028541565,x:.9280606508255005,y:-.01538957841694355,z:.039035625755786896},scale:{x:1,y:1,z:1}},robotBase:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:0,y:0,z:.38},rotation:{w:0,x:0,y:0,z:1},scale:{x:1,y:1,z:1}},robotShoulderLink:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:0,y:0,z:.53185},rotation:{w:.6669439077377319,x:0,y:0,z:.745107889175415},scale:{x:1,y:1,z:1}},robotUpperArmLink:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:0,y:0,z:.53185},rotation:{w:-.4478497803211212,x:.5932892560958862,y:-.3847179114818573,z:.5472025871276855},scale:{x:1,y:1,z:1}},robotForearmLink:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:-.02560272067785263,y:.23055101335048675,z:.45763859629631043},rotation:{w:.6748411655426025,x:.1353885531425476,y:.694024384021759,z:.2111620008945465},scale:{x:1,y:1,z:1}},robotWrist1Link:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:.11584359407424927,y:.14418705981224775,z:.6451554048061371},rotation:{w:-.29463568329811096,x:.6713905930519104,y:-.22188881039619446,z:.6427983641624451},scale:{x:1,y:1,z:1}},robotWrist2Link:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:.1089443638920784,y:.20631420761346816,z:.7032694268226624},rotation:{w:.9164819121360779,x:-.39580079913139343,y:-.05381776764988899,z:-.022500555962324142},scale:{x:1,y:1,z:1}},robotWrist3Link:{frame:"robot-agent-988926121c1911eccbe2600155d1a70a2",position:{x:.11666648089885712,y:.2694645017385483,z:.6366749751567841},rotation:{w:-.37005797028541565,x:.9280606508255005,y:-.01538957841694355,z:.039035625755786896},scale:{x:1,y:1,z:1}},gripperBaseLink:{frame:"simulatedTool0",position:{x:0,y:0,z:0},rotation:{w:.5,x:.5,y:-.5,z:.5},scale:{x:1,y:1,z:1}},gripperLeftKnuckle:{frame:"gripperBaseLink",position:{x:.05490451627,y:.03060114443,z:0},rotation:{w:0,x:1,y:0,z:0},scale:{x:1,y:1,z:1}},gripperRightKnuckle:{frame:"gripperBaseLink",position:{x:.05490451627,y:-.03060114443,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperLeftFinger:{frame:"gripperLeftKnuckle",position:{x:-.00408552455,y:-.03148604435,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperRightFinger:{frame:"gripperRightKnuckle",position:{x:-.00408552455,y:-.03148604435,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperLeftInnerKnuckle:{frame:"gripperBaseLink",position:{x:.06142,y:.0127,z:0},rotation:{w:0,x:1,y:0,z:0},scale:{x:1,y:1,z:1}},gripperRightInnerKnuckle:{frame:"gripperBaseLink",position:{x:.06142,y:-.0127,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperLeftFingerTip:{frame:"gripperLeftInnerKnuckle",position:{x:.04303959807,y:-.03759940821,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},gripperRightFingerTip:{frame:"gripperRightInnerKnuckle",position:{x:.04303959807,y:-.03759940821,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}},items:{"zone-988926121c1911ecbe2600155d1a70a2":{shape:"cube",name:"Human Workspace Occupancy Zone",frame:"world",position:{x:0,y:1,z:.4},rotation:{x:0,y:0,z:0,w:1},color:{r:233,g:53,b:152,a:.2},scale:{x:2,y:1,z:.8},transformMode:"inactive",highlighted:!1,hidden:!0},"zone-988926d01c1911ecbe2600155d1a70a2":{shape:"cube",name:"Human Corridor Occupancy Zone",frame:"world",position:{x:0,y:-1,z:.4},rotation:{x:0,y:0,z:0,w:1},color:{r:233,g:53,b:152,a:.2},scale:{x:2,y:1,z:.8},transformMode:"inactive",highlighted:!1,hidden:!0},"location-c540bea6-a0a8-40c2-8fcc-cb6ae772697c-tag":{uuid:"location-c540bea6-a0a8-40c2-8fcc-cb6ae772697c-tag",frame:"world",name:"Initial Location",shape:"flag",position:{x:.20400124405192815,y:.15340864650572777,z:.15008560705897595},rotation:{w:1,x:0,y:0,z:0},scale:{x:-.25,y:.25,z:.25},highlighted:!1,showName:!1,color:{r:233,g:53,b:152,a:1},hidden:!0,transformMode:"inactive"},"location-c540bea6-a0a8-40c2-8fcc-cb6ae772697c-pointer":{uuid:"location-c540bea6-a0a8-40c2-8fcc-cb6ae772697c-pointer",frame:"world",shape:"package://app/meshes/LocationMarker.stl",position:{x:.20400124405192815,y:.15340864650572777,z:.15008560705897595},rotation:{x:0,y:0,z:.6763577452496884,w:.7365732824646558},scale:{x:1,y:1,z:1},highlighted:!1,showName:!1,color:{r:233,g:53,b:152,a:1},hidden:!0,transformMode:"inactive"},"location-b7daabbd-6e24-4b8f-9c8e-5ea22d727ad0-tag":{uuid:"location-b7daabbd-6e24-4b8f-9c8e-5ea22d727ad0-tag",frame:"world",name:"Deposit Location",shape:"flag",position:{x:.40801871379516913,y:-.2369200947241372,z:.30206792720062714},rotation:{w:1,x:0,y:0,z:0},scale:{x:-.25,y:.25,z:.25},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"location-b7daabbd-6e24-4b8f-9c8e-5ea22d727ad0-pointer":{uuid:"location-b7daabbd-6e24-4b8f-9c8e-5ea22d727ad0-pointer",frame:"world",shape:"package://app/meshes/LocationMarker.stl",position:{x:.40801871379516913,y:-.2369200947241372,z:.30206792720062714},rotation:{x:.7133230578218721,y:-.03940528263686746,z:-.03668088697820589,w:-.6987645894079457},scale:{x:1,y:1,z:1},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"location-47238d9d-5241-4bdb-8b29-877f78cb124d-tag":{uuid:"location-47238d9d-5241-4bdb-8b29-877f78cb124d-tag",frame:"world",name:"Blade Fetch Location",shape:"flag",position:{x:-.4501325157748985,y:-.25541537076762655,z:-.02822078016538941},rotation:{w:1,x:0,y:0,z:0},scale:{x:-.25,y:.25,z:.25},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"location-47238d9d-5241-4bdb-8b29-877f78cb124d-pointer":{uuid:"location-47238d9d-5241-4bdb-8b29-877f78cb124d-pointer",frame:"world",shape:"package://app/meshes/LocationMarker.stl",position:{x:-.4501325157748985,y:-.25541537076762655,z:-.02822078016538941},rotation:{x:-.006622068142399432,y:-.6857443017700521,z:.7277784747239732,w:-.007027982062342742},scale:{x:1,y:1,z:1},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"waypoint-e7a63a7c-1df8-4ca6-9ffc-4f9b1e008aa4-tag":{uuid:"waypoint-e7a63a7c-1df8-4ca6-9ffc-4f9b1e008aa4-tag",frame:"world",name:"WP 1",shape:"tag",position:{x:-.3319053491144722,y:-.006321044395614983,z:.3364538095102072},rotation:{w:1,x:0,y:0,z:0},scale:{x:-.25,y:.25,z:.25},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"waypoint-e7a63a7c-1df8-4ca6-9ffc-4f9b1e008aa4-pointer":{uuid:"waypoint-e7a63a7c-1df8-4ca6-9ffc-4f9b1e008aa4-pointer",frame:"world",shape:"package://app/meshes/OpenWaypointMarker.stl",position:{x:-.3319053491144722,y:-.006321044395614983,z:.3364538095102072},rotation:{x:0,y:0,z:.9907218933440319,w:.13590485660496693},scale:{x:1,y:1,z:1},highlighted:!1,showName:!1,color:{r:100,g:18,b:128,a:1},hidden:!0,transformMode:"inactive"},"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10":{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/MK2-Printer/MK2-Printer.stl",name:"3D Printer Machine",frame:"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10-collision":{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/MK2-Printer.stl",name:"3D Printer Machine Collision",frame:"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"toolType-assembly-jig":{shape:"assembly_jig",name:"Assembly Jig Machine",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",highlighted:!1},"toolType-assembly-jig-collision":{shape:"assembly_jig_collision",name:"Assembly Jig Machine Collision",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7":{shape:"conveyor",name:"Blade Conveyor",frame:"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7-collision":{shape:"conveyor_collision",name:"Blade Conveyor Collision",frame:"machine-0c804bb3-f341-4b82-b9f0-e5aab536e4d7",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b":{shape:"conveyor_receiver",name:"Blade Feeder",frame:"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b-collision":{shape:"conveyor_receiver_collision",name:"Blade Feeder Collision",frame:"machine-0914222f-03e0-4b4c-a8c4-03146867ba7b",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"machine-9133367a-f691-4d94-9764-50d9685db30a":{shape:"conveyor",name:"Knife Conveyor",frame:"machine-9133367a-f691-4d94-9764-50d9685db30a",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-9133367a-f691-4d94-9764-50d9685db30a-collision":{shape:"conveyor_collision",name:"Knife Conveyor Collision",frame:"machine-9133367a-f691-4d94-9764-50d9685db30a",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"machine-67d870e0-511d-4662-bf0d-8478f5e860f8":{shape:"conveyor_dispatcher",name:"Knife Feeder",frame:"machine-67d870e0-511d-4662-bf0d-8478f5e860f8",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"machine-67d870e0-511d-4662-bf0d-8478f5e860f8-collision":{shape:"conveyor_dispatcher_collision",name:"Knife Feeder Collision",frame:"machine-67d870e0-511d-4662-bf0d-8478f5e860f8",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"toolType-transport-jig":{shape:"transport_jig",name:"Transport Jig",frame:"toolType-transport-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",highlighted:!1},"toolType-transport-jig-collision":{shape:"package://evd_ros_tasks/description/markers/tranport_jig.stl",name:"Transport Jig Collision",frame:"toolType-transport-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1,color:{r:250,g:0,b:0,a:.6},wireframe:!0,hidden:!0},"inputOutput-ridn023-dz00-445jk-we90-e69tffb00845":{shape:"handle_l",frame:"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10",position:{x:-.2,y:.28,z:.074},rotation:{x:.707,y:0,z:0,w:.707},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-mnpdm09-ty00-445md-yjg09-rnvor905mfi1203d":{shape:"handle_r",frame:"machine-ac5a063a-9ff9-4c0a-8fa6-81d3983f4a10",position:{x:-.3,y:.28,z:.078},rotation:{x:.707,y:0,z:0,w:.707},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-2d49b51b-dz37-488e-we56-e55ef6a0a8fc":{shape:"blade",frame:"world",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-3d50b62b-dz37-488e-we56-e65eo6f0a80b":{shape:"transport_jig",frame:"toolType-transport-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-sefse456-ty56-234g-gh67-fth4567hfth7":{shape:"blade_with_transport_jig",frame:"world",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-tjgnk5suei9-oo90-ruti0-gte0-u8cns9nc9s":{shape:"handle_l",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-tu8fnsiw0c-ie90-rcns89-tuy8-isnc9sa34s":{shape:"handle_r",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-eicns9ef9-sic9-eicns99-sey8-seo4s9dir9":{shape:"blade",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-tidvi23-tbn9-cjzd99-if98-of9nsnrc0s":{shape:"knife",frame:"thingType-98892bd01c1911ecbe2600155d1a70a2",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-45fsoe9-tjfg9-gurd89-thf9-09ghnsn234d":{shape:"handle_l",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-948fnsi23-odns9-fins89-irn1-fcnr94820s":{shape:"handle_r",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-asfsn90-vnxmo9-nmbj89-ii4w-vnlsf0sfkx0":{shape:"blade_with_transport_jig",frame:"toolType-assembly-jig",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},"inputOutput-94nss89-8vnsk9-7hdn9-wy89-fhsne8923":{shape:"knife_with_transport_jig",frame:"thingType-98892ce81c1911ecbe2600155d1a70a2",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:.2,y:.2,z:.2},transformMode:"inactive",color:{r:0,g:200,b:0,a:.2},highlighted:!1,hidden:!0},table:{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/Table/Table.stl",name:"Table",frame:"table",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},color:{r:10,g:10,b:10,a:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},pedestal:{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/ur3e-Pedestal/Pedestal.stl",name:"Pedestal",frame:"pedestal",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},color:{r:15,g:15,b:15,a:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},robotBase:{shape:"package://ur_description/meshes/ur3/visual/base.dae",name:"Robot Base",frame:"robotBase",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:1,w:0},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},robotShoulderLink:{shape:"package://ur_description/meshes/ur3/visual/shoulder.dae",name:"Shoulder Link",frame:"robotShoulderLink",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:1,w:0},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},robotUpperArmLink:{shape:"package://ur_description/meshes/ur3/visual/upperarm.dae",name:"Upper Arm Link",frame:"robotUpperArmLink",position:{x:0,y:0,z:.12},rotation:{x:.5,y:-.5,z:-.5,w:.5},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotUpperArmLink-collision":{shape:"package://ur_description/meshes/ur3/collision/upperarm.stl",name:"Upper Arm Link Collision",frame:"robotUpperArmLink",position:{x:0,y:0,z:.12},rotation:{x:.5,y:-.5,z:-.5,w:.5},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},robotForearmLink:{shape:"package://ur_description/meshes/ur3/visual/forearm.dae",name:"Forearm Link",frame:"robotForearmLink",position:{x:0,y:0,z:.027},rotation:{x:.5,y:-.5,z:-.5,w:.5},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotForearmLink-collision":{shape:"package://ur_description/meshes/ur3/collision/forearm.stl",name:"Forearm Link Collision",frame:"robotForearmLink",position:{x:0,y:0,z:.027},rotation:{x:.5,y:-.5,z:-.5,w:.5},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},robotWrist1Link:{shape:"package://ur_description/meshes/ur3/visual/wrist1.dae",name:"Wrist 1 Link",frame:"robotWrist1Link",position:{x:0,y:0,z:-.104},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotWrist1Link-collision":{shape:"package://ur_description/meshes/ur3/collision/wrist1.stl",name:"Wrist 1 Link Collision",frame:"robotWrist1Link",position:{x:0,y:0,z:-.104},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},robotWrist2Link:{shape:"package://ur_description/meshes/ur3/visual/wrist2.dae",name:"Wrist 2 Link",frame:"robotWrist2Link",position:{x:0,y:0,z:-.08535},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotWrist2Link-collision":{shape:"package://ur_description/meshes/ur3/collision/wrist1.stl",name:"Wrist 2 Link Collision",frame:"robotWrist2Link",position:{x:0,y:0,z:-.104},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},robotWrist3Link:{shape:"package://ur_description/meshes/ur3/visual/wrist3.dae",name:"Wrist 3 Link",frame:"robotWrist3Link",position:{x:0,y:0,z:-.0921},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},"robotWrist3Link-collision":{shape:"package://ur_description/meshes/ur3/collision/wrist3.stl",name:"Wrist 3 Link Collision",frame:"robotWrist3Link",position:{x:0,y:0,z:-.0921},rotation:{x:.7071068,y:0,z:0,w:.7071068},scale:{x:1,y:1,z:1},color:{r:250,g:0,b:0,a:.6},transformMode:"inactive",highlighted:!1,wireframe:!0,hidden:!0},gripperBaseLink:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_base_link.dae",name:"Gripper Base",frame:"gripperBaseLink",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperLeftKnuckle:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_knuckle_link.dae",name:"Gripper Left Knuckle",frame:"gripperLeftKnuckle",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperRightKnuckle:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_knuckle_link.dae",name:"Gripper Right Knuckle",frame:"gripperRightKnuckle",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperLeftFinger:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_finger_link.dae",name:"Gripper Left Finger",frame:"gripperLeftFinger",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperRightFinger:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_finger_link.dae",name:"Gripper Right Finger",frame:"gripperRightFinger",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperLeftInnerKnuckle:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_inner_knuckle_link.dae",name:"Gripper Left Inner Knuckle",frame:"gripperLeftInnerKnuckle",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperRightInnerKnuckle:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_inner_knuckle_link.dae",name:"Gripper Right Inner Knuckle",frame:"gripperRightInnerKnuckle",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperLeftFingerTip:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_finger_tip_link.dae",name:"Gripper Left Finger Tip",frame:"gripperLeftFingerTip",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1},gripperRightFingerTip:{shape:"package://robotiq_85_description/meshes/visual/robotiq_85_finger_tip_link.dae",name:"Gripper Right Finger Tip",frame:"gripperRightFingerTip",position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},transformMode:"inactive",highlighted:!1}},lines:{},hulls:{usage:{name:"Robot Space Usage",frame:"world",vertices:[{x:-.5,y:-.5,z:0},{x:.5,y:-.5,z:0},{x:.5,y:.5,z:0},{x:-.5,y:.5,z:0},{x:-.5,y:.5,z:1},{x:-.5,y:-.5,z:1},{x:.5,y:-.5,z:1},{x:.5,y:.5,z:1},{x:-.75,y:0,z:.5},{x:.75,y:0,z:.5},{x:0,y:.75,z:.5},{x:0,y:-.75,z:.5}],color:{r:10,g:200,b:235,a:function a(time){return Math.sin(time/1e3)/6+.25}},wireframe:!1,highlighted:!0,showName:!1,hidden:!1}},texts:{workcellLabel:{value:"Work Cell",frame:"world",position:{x:0,y:0,z:1.3},color:{r:10,g:10,b:255,a:1}},miniworkcellLabel:{value:"Mini Work Cell",frame:"gizmo",position:{x:0,y:0,z:1.3},color:{r:10,g:10,b:255,a:1}}},displayTfs:!1,displayGrid:!0,isPolar:!1,backgroundColor:"#1e1e1e",planeColor:"#141414",highlightColor:"#ffffff",plane:-.75,fov:60,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},CoFrame.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return
\n}"}},CoFrame.parameters);var __namedExportsOrder=["CoFrame"]},"./src/stories/ItemMovement.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{ItemMovement:function(){return ItemMovement},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"ItemMovement",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var ItemMovement=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__.Z)(args,_excluded);return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("div",{style:{height:"calc(100vh - 2rem)",width:"calc(100vw - 2rem)"},children:(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2}))})}.bind({});ItemMovement.storyName="ItemMovement",ItemMovement.args={tfs:{moving:{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}},items:{immovable:{shape:"cube",name:"Immovable Cube",frame:"moving",position:{x:0,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!0},translateCube:{shape:"cube",name:"Translate Cube (Async)",frame:"moving",position:{x:1,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1,transformMode:"translate"},rotateCube:{shape:"cube",name:"Rotate Cube",frame:"moving",position:{x:1,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:255,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1,transformMode:"rotate"},scaleCube:{shape:"cube",name:"Scale Cube",frame:"moving",position:{x:0,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:255,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1,transformMode:"scale"}},lines:{},hulls:{},texts:{},displayTfs:!1,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,paused:!1,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},ItemMovement.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return
\n}"}},ItemMovement.parameters);var __namedExportsOrder=["ItemMovement"]},"./src/stories/MeshDebug.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{MeshDebug:function(){return MeshDebug},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./src/stories/meshes/MeshLookup.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"Mesh Debug",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var debugTfs={},debugItems={},debugTexts={},y=-10,x=-12;Object.keys(_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__.z).forEach((function(key,i){0===x?x+=2:x>0&&x%10==0?(y+=2,x=-10):x+=2,debugTfs["".concat(i)]={name:"".concat(i),position:{x:x,y:y,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},debugItems[key]={shape:key,name:key,frame:"".concat(i),position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:key.includes("robotiq_2f_85_gripper_visualization")?{x:.001,y:.001,z:.001}:{x:1,y:1,z:1},editMode:"inactive",highlighted:!1},debugTexts[key]={value:key,frame:"".concat(i),position:{x:0,y:0,z:.5},color:{r:10,g:10,b:255,a:1}}}));var MeshDebug=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_5__.Z)(args,_excluded);return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)("div",{style:{height:"calc(100vh - 2rem)",width:"calc(100vw - 2rem)"},children:(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2,meshLookup:_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_3__.z}))})}.bind({});MeshDebug.args={tfs:debugTfs,items:debugItems,texts:debugTexts,lines:{},hulls:{},displayTfs:!1,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},MeshDebug.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return
\n}"}},MeshDebug.parameters);var __namedExportsOrder=["MeshDebug"]},"./src/stories/Random.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{RandomShapes:function(){return RandomShapes},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/index.js"),_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/stories/meshes/MeshLookup.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"Random Shapes",component:_components__WEBPACK_IMPORTED_MODULE_1__.xs};var RandomShapes=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__.Z)(args,_excluded);return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_1__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("div",{style:{height:"calc(100vh - 2rem)",width:"calc(100vw - 2rem)"},children:(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(_components__WEBPACK_IMPORTED_MODULE_1__.xs,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_1__.x2,meshLookup:_meshes_MeshLookup__WEBPACK_IMPORTED_MODULE_2__.z}))})}.bind({});RandomShapes.args={tfs:{other1:{frame:"world",position:{x:1,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}},other2:{name:"world",position:{x:-2,y:0,z:2},rotation:{w:.525322,x:.8509035,y:0,z:0},scale:{x:1,y:1,z:1}},other3:{name:"world",position:{x:2,y:0,z:1},rotation:{w:-.604,x:-.002,y:-.756,z:.252},scale:{x:1,y:1,z:1}}},items:{1:{shape:"cube",name:"My Cube",frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:50,b:10,a:.75},scale:{x:.5,y:.5,z:.5},highlighted:!0},2:{shape:"sphere",name:"My Sphere",frame:"world",position:{x:0,y:2,z:2},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:255,b:30,a:.35},scale:{x:1,y:2,z:1},highlighted:!0,showName:!0},3:{shape:"cylinder",name:"My Cylinder",frame:"other2",shapeParams:{height:1.25},position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:200,b:235,a:.5},scale:{x:1,y:1,z:1},highlighted:!1},a3:{shape:"capsule",name:"My Capsule",frame:"other2",shapeParams:{height:.25},position:{x:1.2,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:200,b:235,a:.5},scale:{x:1,y:1,z:1},highlighted:!1},4:{shape:"flatarrow",name:"My Arrow 1",frame:"world",position:{x:1,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:70,g:70,b:250,a:.5},scale:{x:1,y:1,z:1},highlighted:!0},5:{shape:"arrow",name:"My Arrow 2",frame:"other1",position:{x:1,y:0,z:0},rotation:{w:-.604,x:-.002,y:-.756,z:.252},color:{r:255,g:70,b:250,a:.5},scale:{x:1,y:1,z:1},highlighted:!0},6:{shape:"arrow",name:"My Arrow 3",frame:"other3",position:{x:1,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:70,b:250,a:.5},scale:{x:1,y:2,z:1},highlighted:!1},7:{shape:"blade_with_transport_jig",name:"Blade with Transport Jig",frame:"world",position:{x:0,y:2,z:1},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},showName:!0,colorOverlay:!0,color:{r:function r(time){return 255*(Math.sin(time/1e3)/2+.5)},g:255,b:0,a:function a(time){return Math.sin(time/1e3)/2+.5}},highlighted:!0},8:{shape:"warning",name:"Nao Ankle",frame:"world",position:{x:1,y:.5,z:1},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},colorOverlay:!0,color:{r:255,g:255,b:0,a:.5},highlighted:!1},9:{shape:"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/MK2-Printer/MK2-Printer.stl",name:"3d Printer",frame:"world",position:{x:-1,y:1,z:.3},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},colorOverlay:!0,color:{r:function r(time){return 255*(Math.sin(time/1e3)/2+.5)},g:0,b:0,a:.8},highlighted:!1},10:{frame:"world",name:"Tag",shape:"tag",position:{x:3,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},scale:{x:-1,y:1,z:1},highlighted:!1,showName:!0,color:{r:255,g:0,b:0,a:1}},11:{frame:"world",name:"flag",shape:"flag",position:{x:3,y:1.4,z:1},rotation:{w:1,x:0,y:0,z:0},scale:{x:-1,y:1,z:1},highlighted:!1,showName:!1,color:{r:255,g:0,b:0,a:1}}},lines:{line1:{name:"Line1",frame:"world",width:1,vertices:[{position:{x:1,y:2,z:0},color:{r:255,g:0,b:0}},{position:{x:2,y:1,z:1},color:{r:0,g:255,b:0}},{position:{x:2,y:2,z:1},color:{r:0,g:0,b:255}}],highlighted:!1},line2:{name:"Line1",frame:"other1",width:3,vertices:[{position:{x:1,y:0,z:0},color:{r:0,g:0,b:255}},{position:{x:1,y:0,z:1},color:{r:100,g:100,b:255}},{position:{x:2,y:1,z:1},color:{r:50,g:50,b:255}},{position:{x:2,y:2,z:1},color:{r:255,g:255,b:255}}],highlighted:!1}},hulls:{},texts:{},displayTfs:!0,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},RandomShapes.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_5__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return
\n}"}},RandomShapes.parameters);var __namedExportsOrder=["RandomShapes"]},"./src/stories/TFMovement.stories.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{TFMovement:function(){return TFMovement},__namedExportsOrder:function(){return __namedExportsOrder}});var _Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/slicedToArray.js"),_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./node_modules/react/index.js"),_components_Scene__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/Scene.jsx"),_components__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("./src/components/index.js"),react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__("./node_modules/react/jsx-runtime.js"),_excluded=["tfs","items","hulls","lines","texts"];__webpack_exports__.default={title:"TFMovement",component:_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z};var TFMovement=function Template(args){var tfs=args.tfs,items=args.items,hulls=args.hulls,lines=args.lines,texts=args.texts,otherArgs=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectWithoutProperties_js__WEBPACK_IMPORTED_MODULE_4__.Z)(args,_excluded),setProperty=(0,_components__WEBPACK_IMPORTED_MODULE_2__.x2)((function(state){return state.setProperty})),_useState=(0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(0),_useState2=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__.Z)(_useState,2),translateSnap=_useState2[0],setTranslateSnap=_useState2[1],_useState3=(0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(0),_useState4=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__.Z)(_useState3,2),rotateSnap=_useState4[0],setRotateSnap=_useState4[1],_useState5=(0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(0),_useState6=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_slicedToArray_js__WEBPACK_IMPORTED_MODULE_5__.Z)(_useState5,2),scaleSnap=_useState6[0],setScaleSnap=_useState6[1];return(0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)((function(){_components__WEBPACK_IMPORTED_MODULE_2__.x2.setState({tfs:tfs,items:items,hulls:hulls,lines:lines,texts:texts})}),[tfs,items,hulls,lines,texts]),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)("div",{style:{height:"calc(100vh - 3rem)",width:"calc(100vw - 2rem)"},children:[(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(_components_Scene__WEBPACK_IMPORTED_MODULE_1__.Z,(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)((0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({},otherArgs),{},{store:_components__WEBPACK_IMPORTED_MODULE_2__.x2,displayTfs:!0,translateSnap:translateSnap,rotateSnap:rotateSnap,scaleSnap:scaleSnap})),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)("div",{style:{textAlign:"center"},children:[(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setTranslateSnap(0),setProperty(["tfs","moving","transformMode"],"translate")},children:"Translate Free"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setTranslateSnap(.25),setProperty(["tfs","moving","transformMode"],"translate")},children:"Translate Snapping"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setRotateSnap(0),setProperty(["tfs","moving","transformMode"],"rotate")},children:"Rotate Free"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setRotateSnap(Math.PI/6),setProperty(["tfs","moving","transformMode"],"rotate")},children:"Rotate Snapping"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setScaleSnap(0),setProperty(["tfs","moving","transformMode"],"scale")},children:"Scale Free"}),(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)("button",{onClick:function onClick(){setScaleSnap(.1),setProperty(["tfs","moving","transformMode"],"scale")},children:"Scale Snapping"})]})]})}.bind({});TFMovement.storyName="TFMovement",TFMovement.args={tfs:{moving:{frame:"world",position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},transformMode:"rotate"}},items:{immovable:{shape:"cube",name:"Immovable Cube",frame:"moving",position:{x:0,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:255,g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5}},translateCube:{shape:"cube",name:"Translate Cube (Async)",frame:"moving",position:{x:1,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1},rotateCube:{shape:"cube",name:"Rotate Cube",frame:"moving",position:{x:1,y:0,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:255,b:10,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1},scaleCube:{shape:"cube",name:"Scale Cube",frame:"moving",position:{x:0,y:1,z:1},rotation:{w:1,x:0,y:0,z:0},color:{r:10,g:10,b:255,a:1},scale:{x:.5,y:.5,z:.5},highlighted:!1}},lines:{},hulls:{},texts:{},displayTfs:!1,displayGrid:!0,isPolar:!1,backgroundColor:"#d0d0d0",planeColor:"#a8a8a8",highlightColor:"#ffffff",plane:-.75,fov:60,paused:!1,ar:!1,vr:!1,onPointerMissed:function onPointerMissed(){return console.log("Missed Click")}},TFMovement.parameters=(0,_Users_schoen_Projects_robot_scene_node_modules_babel_runtime_helpers_esm_objectSpread2_js__WEBPACK_IMPORTED_MODULE_6__.Z)({storySource:{source:"(args) => {\n const { tfs, items, hulls, lines, texts, ...otherArgs } = args;\n\n const setProperty = useDefaultSceneStore(state => state.setProperty);\n const [translateSnap, setTranslateSnap] = useState(0);\n const [rotateSnap, setRotateSnap] = useState(0);\n const [scaleSnap, setScaleSnap] = useState(0);\n\n useLayoutEffect(() => {\n useDefaultSceneStore.setState({ tfs, items, hulls, lines, texts })\n }, [tfs, items, hulls, lines, texts])\n return (\n
\n \n
\n \n \n \n \n \n \n
\n
\n )\n}"}},TFMovement.parameters);var __namedExportsOrder=["TFMovement"]},"./.storybook/preview.js-generated-config-entry.js":function(__unused_webpack_module,__unused_webpack___webpack_exports__,__webpack_require__){"use strict";var preview_namespaceObject={};__webpack_require__.r(preview_namespaceObject),__webpack_require__.d(preview_namespaceObject,{__namedExportsOrder:function(){return __namedExportsOrder},parameters:function(){return parameters}});var ClientApi=__webpack_require__("./node_modules/@storybook/client-api/dist/esm/ClientApi.js"),parameters={docs:{theme:__webpack_require__("./node_modules/@storybook/theming/dist/esm/index.js").np.dark},actions:{argTypesRegex:"^on[A-Z].*"},controls:{matchers:{color:/(background|color)$/i,date:/Date$/}}},__namedExportsOrder=["parameters"];function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.keys(preview_namespaceObject).forEach((function(key){var value=preview_namespaceObject[key];switch(key){case"args":return(0,ClientApi.uc)(value);case"argTypes":return(0,ClientApi.v9)(value);case"decorators":return value.forEach((function(decorator){return(0,ClientApi.$9)(decorator,!1)}));case"loaders":return value.forEach((function(loader){return(0,ClientApi.HZ)(loader,!1)}));case"parameters":return(0,ClientApi.h1)(function _objectSpread(target){for(var i=1;i-1})),ambientLightRef=(0,react.useRef)(),pointLightRef=(0,react.useRef)(),directionalLightRef=(0,react.useRef)(),orbitControls=(0,react.useRef)(),planeRGB=function hexToRgb(hex){hex=hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(function(m,r,g,b){return r+r+g+g+b+b}));var result=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);return result?{r:parseInt(result[1],16),g:parseInt(result[2],16),b:parseInt(result[3],16)}:null}(planeColor||"a8a8a8"),planeRGBA=[planeRGB.r,planeRGB.g,planeRGB.b,.5];return(0,jsx_runtime.jsxs)(react.Fragment,{children:[(0,jsx_runtime.jsx)(OrbitControls.z,{ref:orbitControls,makeDefault:!0}),(0,jsx_runtime.jsx)("pointLight",{ref:pointLightRef,intensity:.5,position:[-1,-3,3],color:"#FFFAEE"}),(0,jsx_runtime.jsx)(AmbientLight,{ref:ambientLightRef,intensity:.7,color:"white"}),(0,jsx_runtime.jsx)(DirectionalLight,{ref:directionalLightRef,castShadow:!0,position:[5,15,15],intensity:.6,color:"#FFFAEE"}),(0,jsx_runtime.jsx)("spotLight",{penumbra:1,position:[-1,-1,4],intensity:.3,castShadow:!0,color:"#FFFAEE"}),(0,jsx_runtime.jsx)("color",{attach:"background",args:[backgroundColor||"#d0d0d0"]}),(0,jsx_runtime.jsx)("fogExp2",{attach:"fog",args:[backgroundColor||"#d0d0d0",.01]}),(0,jsx_runtime.jsx)(shapes.Cd,{receiveShadow:!0,scale:1e3,position:[0,0,plane?plane-.01:-.01],material:MaterialMaker.apply(void 0,planeRGBA)}),(0,jsx_runtime.jsxs)(dist.Y1,{children:[(0,jsx_runtime.jsx)(dist.xC,{autoClear:!1,children:(0,jsx_runtime.jsx)(dist.bw,{visibleEdgeColor:highlightColor,hiddenEdgeColor:highlightColor,blur:!0,kernelSize:1,edgeStrength:50,pulseSpeed:.25,xRay:!0})}),(0,jsx_runtime.jsx)(components_Tree,{activeTf:"world",displayTfs:displayTfs,allTfs:tfs,allItems:items,allLines:lines,allHulls:hulls,allTexts:texts,highlightColor:highlightColor})]}),(0,jsx_runtime.jsx)("group",{position:[0,0,plane||0],rotation:[Math.PI/2,0,0],up:[0,0,1],children:displayGrid&&(isPolar?(0,jsx_runtime.jsx)("polarGridHelper",{args:[10,16,8,64,"white","gray"]}):(0,jsx_runtime.jsx)("gridHelper",{args:[20,20,"white","gray"]}))}),movableStuff.map((function(movableObject,idx){return(0,jsx_runtime.jsx)(TransformableObject,{objectInfo:movableObject,mode:movableObject.transformMode,displayTfs:displayTfs,allTfs:tfs,allItems:items,allLines:lines,allHulls:hulls,allTexts:texts,translateSnap:translateSnap,rotateSnap:rotateSnap,scaleSnap:scaleSnap,highlightColor:highlightColor,onDragEnd:function onDragEnd(){orbitControls.current&&(orbitControls.current.enabled=!0)},onDragStart:function onDragStart(){orbitControls.current&&(orbitControls.current.enabled=!1)}},"movableObjectTransform-".concat(idx))}))]})}TransformableObject.__docgenInfo={description:"",methods:[],displayName:"TransformableObject"},"undefined"!=typeof STORYBOOK_REACT_CLASSES&&(STORYBOOK_REACT_CLASSES["src/components/Util/TransformControls.js"]={name:"TransformableObject",docgenInfo:TransformableObject.__docgenInfo,path:"src/components/Util/TransformControls.js"}),Content.__docgenInfo={description:"",methods:[],displayName:"Content"},"undefined"!=typeof STORYBOOK_REACT_CLASSES&&(STORYBOOK_REACT_CLASSES["src/components/Content.jsx"]={name:"Content",docgenInfo:Content.__docgenInfo,path:"src/components/Content.jsx"});var Scene_excluded=["backgroundColor","store","fov","onPointerMissed","meshLookup"];function Scene(_ref){var backgroundColor=_ref.backgroundColor,store=_ref.store,fov=_ref.fov,onPointerMissed=_ref.onPointerMissed,_ref$meshLookup=_ref.meshLookup,meshLookup=void 0===_ref$meshLookup?{}:_ref$meshLookup,otherProps=(0,objectWithoutProperties.Z)(_ref,Scene_excluded);return(0,jsx_runtime.jsx)(react_three_fiber_esm.Xz,{camera:{up:[0,0,1],fov:fov,position:[0,-3,3]},shadows:!0,style:{background:backgroundColor||"#d0d0d0"},resize:{polyfill:resize_observer.do},onPointerMissed:onPointerMissed||function(){},children:(0,jsx_runtime.jsx)(SceneProvider,{store:store,children:(0,jsx_runtime.jsx)(MeshProvider,{meshes:meshLookup,children:(0,jsx_runtime.jsx)(react.Suspense,{children:(0,jsx_runtime.jsx)(Content,(0,objectSpread2.Z)((0,objectSpread2.Z)({},otherProps),{},{backgroundColor:backgroundColor}))})})})})}three_module.Object3D.DefaultUp.set(0,0,1),Scene.__docgenInfo={description:"",methods:[],displayName:"Scene",props:{meshLookup:{defaultValue:{value:"{}",computed:!1},required:!1}}},"undefined"!=typeof STORYBOOK_REACT_CLASSES&&(STORYBOOK_REACT_CLASSES["src/components/Scene.jsx"]={name:"Scene",docgenInfo:Scene.__docgenInfo,path:"src/components/Scene.jsx"})},"./src/components/defaultStore.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{x2:function(){return useDefaultSceneStore}});var objectSpread2=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectSpread2.js"),esm=__webpack_require__("./node_modules/zustand/esm/index.js"),middleware=__webpack_require__("./node_modules/zustand/esm/middleware.js"),immer_esm=__webpack_require__("./node_modules/immer/dist/immer.esm.mjs"),classCallCheck=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"),createClass=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/createClass.js"),Timer=function(){function Timer(){(0,classCallCheck.Z)(this,Timer),this._previousTime=0,this._currentTime=0,this._delta=0,this._elapsed=0,this._timescale=1,this._useFixedDelta=!1,this._fixedDelta=16.67,this._usePageVisibilityAPI="undefined"!=typeof document&&void 0!==document.hidden,!0===this._usePageVisibilityAPI&&(this._pageVisibilityHandler=handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}return(0,createClass.Z)(Timer,[{key:"disableFixedDelta",value:function disableFixedDelta(){return this._useFixedDelta=!1,this}},{key:"dispose",value:function dispose(){return!0===this._usePageVisibilityAPI&&document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this}},{key:"enableFixedDelta",value:function enableFixedDelta(){return this._useFixedDelta=!0,this}},{key:"getDelta",value:function getDelta(){return this._delta/1e3}},{key:"getElapsed",value:function getElapsed(){return this._elapsed/1e3}},{key:"getFixedDelta",value:function getFixedDelta(){return this._fixedDelta/1e3}},{key:"getTimescale",value:function getTimescale(){return this._timescale}},{key:"reset",value:function reset(){return this._currentTime=this._now(),this}},{key:"setFixedDelta",value:function setFixedDelta(fixedDelta){return this._fixedDelta=1e3*fixedDelta,this}},{key:"setTimescale",value:function setTimescale(timescale){return this._timescale=timescale,this}},{key:"update",value:function update(){return!0===this._useFixedDelta?this._delta=this._fixedDelta:(this._previousTime=this._currentTime,this._currentTime=this._now(),this._delta=this._currentTime-this._previousTime),this._delta*=this._timescale,this._elapsed+=this._delta,this}},{key:"_now",value:function _now(){return("undefined"==typeof performance?Date:performance).now()}}]),Timer}();function handleVisibilityChange(){!1===document.hidden&&this.reset()}var lodash=__webpack_require__("./node_modules/lodash/lodash.js"),lodash_default=__webpack_require__.n(lodash),ImmerSceneSlice=function immer(config){return function(set,get,api){return config((function(partial,replace){var nextState="function"==typeof partial?(0,immer_esm.ZP)(partial):partial;return set(nextState,replace)}),get,api)}}((0,middleware.XR)((function SceneSlice(set,get){return{clock:new Timer,items:{},tfs:{},hulls:{},lines:{},texts:{},onMove:function onMove(id,source,worldTransform,localTransform){return set((function(state){console.log(localTransform),state[source][id].position=(0,objectSpread2.Z)({},localTransform.position),state[source][id].rotation=localTransform.quaternion,state[source][id].rotation.x=localTransform.quaternion.x,state[source][id].rotation.y=localTransform.quaternion.y,state[source][id].rotation.z=localTransform.quaternion.z,state[source][id].rotation.w=localTransform.quaternion.w,state[source][id].scale=(0,objectSpread2.Z)({},localTransform.scale)}))},onClick:function onClick(id,hidden,event){hidden||console.log("id: ".concat(id," clicked!")),get().items[id]&&!hidden&&event.stopPropagation()},onPointerOver:function onPointerOver(id,hidden,event){},onPointerOut:function onPointerOut(id,hidden,event){},pause:function pause(){return set((function(state){state.clock.setTimescale(0)}))},play:function play(speed){return set((function(state){state.clock.setTimescale(speed||1)}))},reset:function reset(time){return set((function(state){console.log("setting time to ".concat(time)),state.clock._elapsed=time?1e3*time:0}))},clearItems:function clearItems(){return set((function(_){return{items:{}}}))},clearLines:function clearLines(){return set((function(_){return{lines:{}}}))},clearTfs:function clearTfs(){return set((function(_){return{tfs:{}}}))},clearHulls:function clearHulls(){return set((function(_){return{hulls:{}}}))},clearTexts:function clearTexts(){return set((function(_){return{texts:{}}}))},setItems:function setItems(items){return set((function(_){return{items:items}}))},setLines:function setLines(lines){return set((function(_){return{lines:lines}}))},setTfs:function setTfs(tfs){return set((function(_){return{tfs:tfs}}))},setHulls:function setHulls(hulls){return set((function(_){return{hulls:hulls}}))},setTexts:function setTexts(texts){return set((function(_){return{texts:texts}}))},removeItem:function removeItem(key){return set((function(state){delete state.items[key]}))},removeLine:function removeLine(key){return set((function(state){delete state.lines[key]}))},removeTf:function removeTf(key){return set((function(state){delete state.tfs[key]}))},removeHull:function removeHull(key){return set((function(state){delete state.hulls[key]}))},removeText:function removeText(key){return set((function(state){delete state.texts[key]}))},setItem:function setItem(key,item){return set((function(state){state.items[key]=item}))},setLine:function setLine(key,line){return set((function(state){state.lines[key]=line}))},setTf:function setTf(key,tf){return set((function(state){state.tfs[key]=tf}))},setHull:function setHull(key,hull){return set((function(state){state.hulls[key]=hull}))},setText:function setText(key,text){return set((function(state){state.texts[key]=text}))},setProperty:function setProperty(path,value){return set((function(state){lodash_default().set(state,path,value)}))}}}))),useDefaultSceneStore=(0,esm.ZP)(ImmerSceneSlice)},"./src/components/index.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{x2:function(){return _defaultStore__WEBPACK_IMPORTED_MODULE_1__.x2},xs:function(){return _Scene__WEBPACK_IMPORTED_MODULE_0__.Z}});var _Scene__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("./src/components/Scene.jsx"),_defaultStore__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("./src/components/defaultStore.js")},"./src/stories/meshes/MeshLookup.js":function(__unused_webpack_module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,{z:function(){return MeshLookupTable}});var useGLTF=__webpack_require__("./node_modules/@react-three/drei/core/useGLTF.js"),finger_namespaceObject=__webpack_require__.p+"2722c36d578e421f844e.glb";useGLTF.L.preload(finger_namespaceObject);var hand_namespaceObject=__webpack_require__.p+"0cc02e26902c8f08652d.glb";useGLTF.L.preload(hand_namespaceObject);var link0_namespaceObject=__webpack_require__.p+"136c9bbc97ce0cf8c9e4.glb";useGLTF.L.preload(link0_namespaceObject);var link1_namespaceObject=__webpack_require__.p+"fe28c0ebac8e0ea9afe8.glb";useGLTF.L.preload(link1_namespaceObject);var link2_namespaceObject=__webpack_require__.p+"ef30ff8f8dd25ce66ec5.glb";useGLTF.L.preload(link2_namespaceObject);var link3_namespaceObject=__webpack_require__.p+"f2e4ed8f7af1fbfdecf5.glb";useGLTF.L.preload(link3_namespaceObject);var link4_namespaceObject=__webpack_require__.p+"95682f4fdb3ec78fec11.glb";useGLTF.L.preload(link4_namespaceObject);var link5_namespaceObject=__webpack_require__.p+"fbd75a9e7877d51a17a2.glb";useGLTF.L.preload(link5_namespaceObject);var link6_namespaceObject=__webpack_require__.p+"cb7a3a0d99d0829cf93e.glb";useGLTF.L.preload(link6_namespaceObject);var link7_namespaceObject=__webpack_require__.p+"f9d0a3a3c1f30e5fbc2a.glb";useGLTF.L.preload(link7_namespaceObject);var robotiq_arg2f_85_base_link_namespaceObject=__webpack_require__.p+"57a8381889016d086976.glb";useGLTF.L.preload(robotiq_arg2f_85_base_link_namespaceObject);var robotiq_arg2f_85_inner_finger_namespaceObject=__webpack_require__.p+"ff82f07a64794d907175.glb";useGLTF.L.preload(robotiq_arg2f_85_inner_finger_namespaceObject);var robotiq_arg2f_85_inner_knuckle_namespaceObject=__webpack_require__.p+"ef1021f46e8da14c361d.glb";useGLTF.L.preload(robotiq_arg2f_85_inner_knuckle_namespaceObject);var robotiq_arg2f_85_outer_finger_namespaceObject=__webpack_require__.p+"02e44a8f96b7e9e02975.glb";useGLTF.L.preload(robotiq_arg2f_85_outer_finger_namespaceObject);var robotiq_arg2f_85_outer_knuckle_namespaceObject=__webpack_require__.p+"371896c54d1f4992a6ac.glb";useGLTF.L.preload(robotiq_arg2f_85_outer_knuckle_namespaceObject);var robotiq_arg2f_base_link_namespaceObject=__webpack_require__.p+"2f5b68a16175d8d81764.glb";useGLTF.L.preload(robotiq_arg2f_base_link_namespaceObject);var visual_robotiq_arg2f_85_base_link_namespaceObject=__webpack_require__.p+"076e56969a0a8b094ff1.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_base_link_namespaceObject);var visual_robotiq_arg2f_85_inner_finger_namespaceObject=__webpack_require__.p+"5bfeb79449e49274457e.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_inner_finger_namespaceObject);var visual_robotiq_arg2f_85_inner_knuckle_namespaceObject=__webpack_require__.p+"dae460be3f40bc0ce893.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_inner_knuckle_namespaceObject);var visual_robotiq_arg2f_85_outer_finger_namespaceObject=__webpack_require__.p+"5dd9f4f9dfdb0c5c3150.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_outer_finger_namespaceObject);var visual_robotiq_arg2f_85_outer_knuckle_namespaceObject=__webpack_require__.p+"92254578081659ac659f.glb";useGLTF.L.preload(visual_robotiq_arg2f_85_outer_knuckle_namespaceObject);var robotiq_arg2f_85_pad_namespaceObject=__webpack_require__.p+"409136b14a248efad6b8.glb";useGLTF.L.preload(robotiq_arg2f_85_pad_namespaceObject);var robotiq_gripper_coupling_namespaceObject=__webpack_require__.p+"27be9d0db69fe382c757.glb";useGLTF.L.preload(robotiq_gripper_coupling_namespaceObject);var robotiq_85_base_link_namespaceObject=__webpack_require__.p+"26073aebc36a91b39513.glb";useGLTF.L.preload(robotiq_85_base_link_namespaceObject);var robotiq_85_knuckle_link_namespaceObject=__webpack_require__.p+"b66b5363262a9aa5f792.glb";useGLTF.L.preload(robotiq_85_knuckle_link_namespaceObject);var robotiq_85_finger_link_namespaceObject=__webpack_require__.p+"096c095808e970978d7e.glb";useGLTF.L.preload(robotiq_85_finger_link_namespaceObject);var robotiq_85_finger_tip_link_namespaceObject=__webpack_require__.p+"f4fb12d64ccb2a59f525.glb";useGLTF.L.preload(robotiq_85_finger_tip_link_namespaceObject);var robotiq_85_inner_knuckle_link_namespaceObject=__webpack_require__.p+"ebc0934129953400b093.glb";useGLTF.L.preload(robotiq_85_inner_knuckle_link_namespaceObject);var collision_robotiq_85_base_link_namespaceObject=__webpack_require__.p+"631ba79e07c5de49aa5d.glb";useGLTF.L.preload(collision_robotiq_85_base_link_namespaceObject);var collision_robotiq_85_knuckle_link_namespaceObject=__webpack_require__.p+"fe9999e65cfc71c6125e.glb";useGLTF.L.preload(collision_robotiq_85_knuckle_link_namespaceObject);var collision_robotiq_85_finger_link_namespaceObject=__webpack_require__.p+"89e9b62e2d0faf15b18d.glb";useGLTF.L.preload(collision_robotiq_85_finger_link_namespaceObject);var collision_robotiq_85_finger_tip_link_namespaceObject=__webpack_require__.p+"5ab2515ce543ae06889b.glb";useGLTF.L.preload(collision_robotiq_85_finger_tip_link_namespaceObject);var collision_robotiq_85_inner_knuckle_link_namespaceObject=__webpack_require__.p+"20fe2374d4de6df4ae18.glb";useGLTF.L.preload(collision_robotiq_85_inner_knuckle_link_namespaceObject);var pedestal_link_collision_namespaceObject=__webpack_require__.p+"3a4c9af019b247a410e6.glb";useGLTF.L.preload(pedestal_link_collision_namespaceObject);var PEDESTAL_namespaceObject=__webpack_require__.p+"3350508bd5feca53933c.glb";useGLTF.L.preload(PEDESTAL_namespaceObject);var H0_namespaceObject=__webpack_require__.p+"320513d32ac0d233922e.glb";useGLTF.L.preload(H0_namespaceObject);var H1_namespaceObject=__webpack_require__.p+"a9891124232df7e7d220.glb";useGLTF.L.preload(H1_namespaceObject);var E1_namespaceObject=__webpack_require__.p+"07d914225a052f2106cf.glb";useGLTF.L.preload(E1_namespaceObject);var W1_namespaceObject=__webpack_require__.p+"c54a018e3050fede8431.glb";useGLTF.L.preload(W1_namespaceObject);var base_link_collision_namespaceObject=__webpack_require__.p+"ef58ff7faffbaf3ae1a7.glb";useGLTF.L.preload(base_link_collision_namespaceObject);var base_link_namespaceObject=__webpack_require__.p+"b4c1e98e1373558b0dd2.glb";useGLTF.L.preload(base_link_namespaceObject);var E0_namespaceObject=__webpack_require__.p+"5e5e5101d27a55c24335.glb";useGLTF.L.preload(E0_namespaceObject);var W0_namespaceObject=__webpack_require__.p+"62cf8f96fbc857097bd3.glb";useGLTF.L.preload(W0_namespaceObject);var S0_namespaceObject=__webpack_require__.p+"6fe8fc1a422b4b623e40.glb";useGLTF.L.preload(S0_namespaceObject);var S1_namespaceObject=__webpack_require__.p+"a856a881219916e800d4.glb";useGLTF.L.preload(S1_namespaceObject);var W2_namespaceObject=__webpack_require__.p+"08e26d6108d8b20727ee.glb";useGLTF.L.preload(W2_namespaceObject);var base_namespaceObject=__webpack_require__.p+"8b09376b2ef4290ba69b.glb";useGLTF.L.preload(base_namespaceObject);var forearm_namespaceObject=__webpack_require__.p+"94b55aa37445fe9a579e.glb";useGLTF.L.preload(forearm_namespaceObject);var shoulder_namespaceObject=__webpack_require__.p+"f5b5a7af44a2758c4a3c.glb";useGLTF.L.preload(shoulder_namespaceObject);var upperarm_namespaceObject=__webpack_require__.p+"16439484bb5a5ed3deea.glb";useGLTF.L.preload(upperarm_namespaceObject);var wrist1_namespaceObject=__webpack_require__.p+"f39e8d448aff9cf3642a.glb";useGLTF.L.preload(wrist1_namespaceObject);var wrist2_namespaceObject=__webpack_require__.p+"16d079d88e916105275d.glb";useGLTF.L.preload(wrist2_namespaceObject);var wrist3_namespaceObject=__webpack_require__.p+"9322571244f78b366da6.glb";useGLTF.L.preload(wrist3_namespaceObject);var collision_base_namespaceObject=__webpack_require__.p+"3bb49d6be1e5f5d19ad2.glb";useGLTF.L.preload(collision_base_namespaceObject);var collision_forearm_namespaceObject=__webpack_require__.p+"db7ffa352d8572453d8f.glb";useGLTF.L.preload(collision_forearm_namespaceObject);var collision_shoulder_namespaceObject=__webpack_require__.p+"303ffffc92c0e52be7f7.glb";useGLTF.L.preload(collision_shoulder_namespaceObject);var collision_upperarm_namespaceObject=__webpack_require__.p+"cf12f0ef8fad54942a4b.glb";useGLTF.L.preload(collision_upperarm_namespaceObject);var collision_wrist1_namespaceObject=__webpack_require__.p+"029ab32ddd8fb3feb7ed.glb";useGLTF.L.preload(collision_wrist1_namespaceObject);var collision_wrist2_namespaceObject=__webpack_require__.p+"a31e912a127fb8b1b0b4.glb";useGLTF.L.preload(collision_wrist2_namespaceObject);var collision_wrist3_namespaceObject=__webpack_require__.p+"f2536802541039524ba5.glb";useGLTF.L.preload(collision_wrist3_namespaceObject);var Ur5_base_namespaceObject=__webpack_require__.p+"725d30d0c3d0ad515609.glb";useGLTF.L.preload(Ur5_base_namespaceObject);var Ur5_forearm_namespaceObject=__webpack_require__.p+"f8a7f903b629254de810.glb";useGLTF.L.preload(Ur5_forearm_namespaceObject);var Ur5_shoulder_namespaceObject=__webpack_require__.p+"482ecbda26bc4349b49a.glb";useGLTF.L.preload(Ur5_shoulder_namespaceObject);var Ur5_upperarm_namespaceObject=__webpack_require__.p+"57aecbc1e995be15b4b3.glb";useGLTF.L.preload(Ur5_upperarm_namespaceObject);var Ur5_wrist1_namespaceObject=__webpack_require__.p+"dfc25a13e9a00769df7a.glb";useGLTF.L.preload(Ur5_wrist1_namespaceObject);var Ur5_wrist2_namespaceObject=__webpack_require__.p+"3d6ad85a4ca746fd0d18.glb";useGLTF.L.preload(Ur5_wrist2_namespaceObject);var Ur5_wrist3_namespaceObject=__webpack_require__.p+"cf67ce9ec8212bd5433a.glb";useGLTF.L.preload(Ur5_wrist3_namespaceObject);var Ur10_base_namespaceObject=__webpack_require__.p+"6726d5079a69c8d88807.glb";useGLTF.L.preload(Ur10_base_namespaceObject);var Ur10_forearm_namespaceObject=__webpack_require__.p+"1f61322fee40aaeb1761.glb";useGLTF.L.preload(Ur10_forearm_namespaceObject);var Ur10_shoulder_namespaceObject=__webpack_require__.p+"6f59e28be53805b69e0f.glb";useGLTF.L.preload(Ur10_shoulder_namespaceObject);var Ur10_upperarm_namespaceObject=__webpack_require__.p+"34fed34d9d4f5066e777.glb";useGLTF.L.preload(Ur10_upperarm_namespaceObject);var Ur10_wrist1_namespaceObject=__webpack_require__.p+"e699f773554012c1b20c.glb";useGLTF.L.preload(Ur10_wrist1_namespaceObject);var Ur10_wrist2_namespaceObject=__webpack_require__.p+"81a91f436af9672546aa.glb";useGLTF.L.preload(Ur10_wrist2_namespaceObject);var Ur10_wrist3_namespaceObject=__webpack_require__.p+"5be6578c637b92aec91c.glb";useGLTF.L.preload(Ur10_wrist3_namespaceObject);var _3DBenchy_namespaceObject=__webpack_require__.p+"fb95d18efb1487592267.glb";useGLTF.L.preload(_3DBenchy_namespaceObject);var Arrow_namespaceObject=__webpack_require__.p+"a0223b57679908adee61.glb";useGLTF.L.preload(Arrow_namespaceObject);var Box_namespaceObject=__webpack_require__.p+"4f094d970c93bb74cf3a.glb";useGLTF.L.preload(Box_namespaceObject);var Collision_Box_namespaceObject=__webpack_require__.p+"de2eef1e44d86e47561e.glb";useGLTF.L.preload(Collision_Box_namespaceObject);var Collision_MK2_Printer_namespaceObject=__webpack_require__.p+"c71730e124347337324c.glb";useGLTF.L.preload(Collision_MK2_Printer_namespaceObject);var Collision_Pedestal_namespaceObject=__webpack_require__.p+"ee5b929bb68f73f0bf60.glb";useGLTF.L.preload(Collision_Pedestal_namespaceObject);var Collision_Table_namespaceObject=__webpack_require__.p+"f23b732ffd6cbf33ddc2.glb";useGLTF.L.preload(Collision_Table_namespaceObject);var InfoPhycon_namespaceObject=__webpack_require__.p+"a794bd4ce6ac46e8baa5.glb";useGLTF.L.preload(InfoPhycon_namespaceObject);var LocationMarker_namespaceObject=__webpack_require__.p+"bcddcb066aa3df35e58a.glb";useGLTF.L.preload(LocationMarker_namespaceObject);var MK2Printer_namespaceObject=__webpack_require__.p+"1a0b36716b64aef46192.glb";useGLTF.L.preload(MK2Printer_namespaceObject);var OpenWaypointMarker_namespaceObject=__webpack_require__.p+"20bd53a93a51df5731eb.glb";useGLTF.L.preload(OpenWaypointMarker_namespaceObject);var Pedestal_namespaceObject=__webpack_require__.p+"724235985a56bc1d68aa.glb";useGLTF.L.preload(Pedestal_namespaceObject);var Table_namespaceObject=__webpack_require__.p+"218075b40bbfd12ae2dd.glb";useGLTF.L.preload(Table_namespaceObject);var WarningPhycon_namespaceObject=__webpack_require__.p+"bf2c04a3ba73a0b4bc68.glb";useGLTF.L.preload(WarningPhycon_namespaceObject);var Tag_namespaceObject=__webpack_require__.p+"bbf461324a8d5c817652.glb";useGLTF.L.preload(Tag_namespaceObject);var Flag_namespaceObject=__webpack_require__.p+"65ae7639ad8a8930d021.glb";useGLTF.L.preload(Flag_namespaceObject);var Blade_namespaceObject=__webpack_require__.p+"5c62f1d60b48c991ac0d.glb";function Blade_Model(props){var _useGLTF=(0,useGLTF.L)(Blade_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[Math.PI,0,0],children:[{type:"raw",geometry:nodes.Blade.geometry,material:materials["Blade.material"],scale:[5,5,5]}]}]}useGLTF.L.preload(Blade_namespaceObject);var HandleL_namespaceObject=__webpack_require__.p+"1e0c6314afdcd77610dc.glb";function HandleL_Model(props){var _useGLTF=(0,useGLTF.L)(HandleL_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[Math.PI,0,0],children:[{type:"raw",geometry:nodes.LHandle.geometry,material:materials.lmaterial,scale:[5,5,5]}]}]}useGLTF.L.preload(HandleL_namespaceObject);var HandleR_namespaceObject=__webpack_require__.p+"5b373faffe499e18adfc.glb";function HandleR_Model(props){var _useGLTF=(0,useGLTF.L)(HandleR_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[Math.PI,0,0],children:[{type:"raw",geometry:nodes.RHandle.geometry,material:materials.rmaterial,scale:[5,5,5]}]}]}useGLTF.L.preload(HandleR_namespaceObject);var toConsumableArray=__webpack_require__("./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js");var Conveyor_namespaceObject=__webpack_require__.p+"4c82fd4edb0da5571bac.glb";useGLTF.L.preload(Conveyor_namespaceObject);var ConveyorCollision_namespaceObject=__webpack_require__.p+"50e19d9fb450ddcfb44c.glb";useGLTF.L.preload(ConveyorCollision_namespaceObject);var TransportJig_namespaceObject=__webpack_require__.p+"d87117eaa3cf819e7c0f.glb";function TransportJig_Model(props){var _useGLTF=(0,useGLTF.L)(TransportJig_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.TransportJig.geometry,material:materials["TransportJig.material"],scale:[5,5,5]}]}]}useGLTF.L.preload(TransportJig_namespaceObject);var AssemblyJig_namespaceObject=__webpack_require__.p+"eda331eb4f20b886f9a4.glb";useGLTF.L.preload(AssemblyJig_namespaceObject);var AssemblyJigCollision_namespaceObject=__webpack_require__.p+"459ae37e2741b7904a03.glb";useGLTF.L.preload(AssemblyJigCollision_namespaceObject);var ConveyorDispatcher_namespaceObject=__webpack_require__.p+"744b572852b0224cf81a.glb";useGLTF.L.preload(ConveyorDispatcher_namespaceObject);var ConveyorReceiver_namespaceObject=__webpack_require__.p+"6b20da764b5f46ad1281.glb";useGLTF.L.preload(ConveyorReceiver_namespaceObject);var ConveyorDispatcherCollision_namespaceObject=__webpack_require__.p+"b4cc0db00a306efa6441.glb";useGLTF.L.preload(ConveyorDispatcherCollision_namespaceObject);var ConveyorReceiverCollision_namespaceObject=__webpack_require__.p+"062eacab68de5ba90e76.glb";useGLTF.L.preload(ConveyorReceiverCollision_namespaceObject);var MeshLookupTable={flatarrow:function Arrow_Model(props){var _useGLTF=(0,useGLTF.L)(Arrow_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.Arrow.geometry,material:materials["Default OBJ"],scale:[1,1,1]}]},warning:function WarningPhycon_Model(props){var nodes=(0,useGLTF.L)(WarningPhycon_namespaceObject).nodes;return[{type:"group",scale:[.005,.005,.005],position:[-1.5,-.6,0],children:[{type:"raw",geometry:nodes.WarningPhycon.geometry,material:nodes.WarningPhycon.material}]}]},info:function InfoPhycon_Model(props){var nodes=(0,useGLTF.L)(InfoPhycon_namespaceObject).nodes;return[{type:"group",scale:[.005,.005,.005],position:[-1.25,1.25,0],children:[{type:"raw",geometry:nodes.InfoPhycon.geometry,material:nodes.InfoPhycon.material}]}]},tag:function Tag_Model(props){var _useGLTF=(0,useGLTF.L)(Tag_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.Tag.geometry,material:materials.Material}]}]},flag:function Flag_Model(props){var _useGLTF=(0,useGLTF.L)(Flag_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.Flag.geometry,material:materials.Material}]}]},blade:Blade_Model,knife:function Knife_Model(props){return[{type:"group",children:[].concat((0,toConsumableArray.Z)(Blade_Model()),(0,toConsumableArray.Z)(HandleL_Model()),(0,toConsumableArray.Z)(HandleR_Model()))}]},handle_l:HandleL_Model,handle_r:HandleR_Model,conveyor:function Conveyor_Model(props){var _useGLTF=(0,useGLTF.L)(Conveyor_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Belt.geometry,material:materials.BeltMaterial},{type:"raw",geometry:nodes.Conveyor.geometry,material:materials.ConveyorMaterial},{type:"raw",geometry:nodes.InsideBack.geometry,material:materials.InsideBackMaterial}]}]},conveyor_collision:function ConveyorCollision_Model(props){var nodes=(0,useGLTF.L)(ConveyorCollision_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.ConveyorCollision.geometry,material:nodes.ConveyorCollision.material}]}]},transport_jig:TransportJig_Model,assembly_jig:function AssemblyJig_Model(props){var _useGLTF=(0,useGLTF.L)(AssemblyJig_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.AssemblyJig.geometry,material:materials.AssemblyJigMaterial,scale:[5,5,5]}]}]},assembly_jig_collision:function AssemblyJigCollision_Model(props){var nodes=(0,useGLTF.L)(AssemblyJigCollision_namespaceObject).nodes;return[{type:"group",rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Mesh_0.geometry,material:nodes.Mesh_0.material,scale:[5,5,5]}]}]},blade_with_transport_jig:function BladeWithTransportJig_Model(props){return[{type:"group",children:[].concat((0,toConsumableArray.Z)(Blade_Model()),(0,toConsumableArray.Z)(TransportJig_Model()))}]},knife_with_transport_jig:function KnifeWithTransportJig_Model(props){return[{type:"group",children:[].concat((0,toConsumableArray.Z)(Blade_Model()),(0,toConsumableArray.Z)(HandleL_Model()),(0,toConsumableArray.Z)(HandleR_Model()),(0,toConsumableArray.Z)(TransportJig_Model()))}]},conveyor_dispatcher:function ConveyorDispatcher_Model(props){var _useGLTF=(0,useGLTF.L)(ConveyorDispatcher_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.ConveyorDispatcher.geometry,material:materials.ConveyorAddonMaterial}]}]},conveyor_receiver:function ConveyorReceiver_Model(props){var _useGLTF=(0,useGLTF.L)(ConveyorReceiver_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.ConveyorReceiver.geometry,material:materials.ConveyorAddonMaterial}]}]},conveyor_dispatcher_collision:function ConveyorDispatcherCollision_Model(props){var nodes=(0,useGLTF.L)(ConveyorDispatcherCollision_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.ConveyorDispatcherCollision.geometry,material:nodes.ConveyorDispatcherCollision.material}]}]},conveyor_receiver_collision:function ConveyorReceiverCollision_Model(props){var nodes=(0,useGLTF.L)(ConveyorReceiverCollision_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.ConveyorReceiverCollision.geometry,material:nodes.ConveyorReceiverCollision.material}]}]},"package://franka_ros/franka_description/meshes/visual/finger.dae":function Model(props){var _useGLTF=(0,useGLTF.L)(finger_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{geometry:nodes.node0.geometry,material:materials.Part__Feature_007},{geometry:nodes.node1.geometry,material:materials.Part__Feature001_006}]},"package://franka_ros/franka_description/meshes/visual/hand.dae":function hand_Model(props){var _useGLTF=(0,useGLTF.L)(hand_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature002_005_005},{type:"raw",geometry:nodes.node5.geometry,material:materials.Part__Feature005_001_005},{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature_009_005},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature001_008_005},{type:"raw",geometry:nodes.node5_001.geometry,material:materials.Part__Feature005_001_005_001}]},"package://franka_ros/franka_description/meshes/visual/link0.dae":function link0_Model(props){var _useGLTF=(0,useGLTF.L)(link0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature017_001},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature022_001},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature023_001},{type:"raw",geometry:nodes.node3.geometry,material:materials.Part__Feature019_001},{type:"raw",geometry:nodes.node4.geometry,material:materials.Part__Feature018_001},{type:"raw",geometry:nodes.node5.geometry,material:materials.Face636_001},{type:"raw",geometry:nodes.node6.geometry,material:materials.Shell001_001},{type:"raw",geometry:nodes.node7.geometry,material:materials.Shell002_001},{type:"raw",geometry:nodes.node8.geometry,material:materials.Shell_001},{type:"raw",geometry:nodes.node9.geometry,material:materials.Shell003_001},{type:"raw",geometry:nodes.node10.geometry,material:materials.Shell009_001},{type:"raw",geometry:nodes.node11.geometry,material:materials.Shell010_001}]},"package://franka_ros/franka_description/meshes/visual/link1.dae":function link1_Model(props){var _useGLTF=(0,useGLTF.L)(link1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature_001,position:[0,-.19,0]}]},"package://franka_ros/franka_description/meshes/visual/link2.dae":function link2_Model(props){var _useGLTF=(0,useGLTF.L)(link2_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature024}]},"package://franka_ros/franka_description/meshes/visual/link3.dae":function link3_Model(props){var _useGLTF=(0,useGLTF.L)(link3_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0_001.geometry,material:materials.Part__Feature_001_001_001_002,position:[0,-.12,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature001_010_001_002,position:[0,-.12,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature002_007_001_002,position:[0,-.12,0]},{type:"raw",geometry:nodes.node3.geometry,material:materials.Part__Feature003_004_001_002,position:[0,-.12,0]}]},"package://franka_ros/franka_description/meshes/visual/link4.dae":function link4_Model(props){var _useGLTF=(0,useGLTF.L)(link4_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature_002_003_001,position:[0,0,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature002_001_003_001,position:[0,0,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature003_001_003_001,position:[0,0,0]},{type:"raw",geometry:nodes.node3.geometry,material:materials.Part__Feature001_001_003_001,position:[0,0,0]}]},"package://franka_ros/franka_description/meshes/visual/link5.dae":function link5_Model(props){var _useGLTF=(0,useGLTF.L)(link5_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Feature_002_004_003,position:[0,-.26,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Shell_001_001_003,position:[0,-.26,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Shell001_001_001_003,position:[0,-.26,0]}]},"package://franka_ros/franka_description/meshes/visual/link6.dae":function link6_Model(props){var _useGLTF=(0,useGLTF.L)(link6_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Shell012_002_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Feature001_009_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Feature002_006_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node3.geometry,material:materials.Face064_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node4.geometry,material:materials.Face065_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node5.geometry,material:materials.Face374_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node6.geometry,material:materials.Shell_003_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node7.geometry,material:materials.Face539_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node8.geometry,material:materials.Union_001_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node9.geometry,material:materials.Union001_001_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node10.geometry,material:materials.Shell002_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node11.geometry,material:materials.Shell003_002_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node12.geometry,material:materials.Shell004_001_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node13.geometry,material:materials.Shell005_001_001_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node15.geometry,material:materials.Shell007_002_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node16.geometry,material:materials.Shell011_002_002_001,position:[0,-.01,0]},{type:"raw",geometry:nodes.node0_001.geometry,material:materials.Shell006_003_002_001}]},"package://franka_ros/franka_description/meshes/visual/link7.dae":function link7_Model(props){var _useGLTF=(0,useGLTF.L)(link7_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.Part__Mirroring_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node2.geometry,material:materials.Part__Mirroring002_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node3.geometry,material:materials.Part__Mirroring003_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node5.geometry,material:materials.Part__Mirroring005_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node6.geometry,material:materials.Part__Mirroring006_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node7.geometry,material:materials.Part__Mirroring007_004_001,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node1.geometry,material:materials.Part__Mirroring001_004_002,position:[0,.05,0],rotation:[0,-Math.PI/4,0]},{type:"raw",geometry:nodes.node4.geometry,material:materials.Part__Mirroring004_004_002,position:[0,.05,0],rotation:[0,-Math.PI/4,0]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_base_link.stl":function robotiq_arg2f_85_base_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_base_link_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.Robotiq_Arg2F_85_Base_Link.geometry,material:nodes.Robotiq_Arg2F_85_Base_Link.material}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_inner_finger.dae":function robotiq_arg2f_85_inner_finger_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_inner_finger_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_inner_knuckle.dae":function robotiq_arg2f_85_inner_knuckle_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_inner_knuckle_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_outer_finger.dae":function robotiq_arg2f_85_outer_finger_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_outer_finger_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_85_outer_knuckle.dae":function robotiq_arg2f_85_outer_knuckle_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_85_outer_knuckle_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/collision/robotiq_arg2f_base_link.stl":function robotiq_arg2f_base_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_arg2f_base_link_namespaceObject).nodes;return[{type:"group",scale:[.001,.001,.001],children:[{type:"raw",geometry:nodes.Robotiq_Arg2F_Base_Link.geometry,material:nodes.Robotiq_Arg2F_Base_Link.material}]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_base_link.dae":function visual_robotiq_arg2f_85_base_link_Model(props){var _useGLTF=(0,useGLTF.L)(visual_robotiq_arg2f_85_base_link_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:nodes.node0.material},{type:"raw",geometry:nodes.node1.geometry,material:nodes.node1.material},{type:"raw",geometry:nodes.node2.geometry,material:nodes.node2.material},{type:"raw",geometry:nodes.node3.geometry,material:nodes.node3.material},{type:"raw",geometry:nodes.node4.geometry,material:nodes.node4.material},{type:"raw",geometry:nodes.node100.geometry,material:materials["mymaterial.004"]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_inner_finger.dae":function visual_robotiq_arg2f_85_inner_finger_Model(props){var _useGLTF=(0,useGLTF.L)(visual_robotiq_arg2f_85_inner_finger_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials["mymaterial.003"]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_inner_knuckle.dae":function visual_robotiq_arg2f_85_inner_knuckle_Model(props){var _useGLTF=(0,useGLTF.L)(visual_robotiq_arg2f_85_inner_knuckle_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials["mymaterial.002"]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_outer_finger.dae":function visual_robotiq_arg2f_85_outer_finger_Model(props){var _useGLTF=(0,useGLTF.L)(visual_robotiq_arg2f_85_outer_finger_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials["mymaterial.001"]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_outer_knuckle.dae":function visual_robotiq_arg2f_85_outer_knuckle_Model(props){var nodes=(0,useGLTF.L)(visual_robotiq_arg2f_85_outer_knuckle_namespaceObject).nodes;return[{type:"raw",geometry:nodes.node.geometry,material:nodes.node.material,rotation:[Math.PI/2,0,0]}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_arg2f_85_pad.dae":function robotiq_arg2f_85_pad_Model(props){var _useGLTF=(0,useGLTF.L)(robotiq_arg2f_85_pad_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.node0.geometry,material:materials.mymaterial}]},"package://robotiq/robotiq_2f_85_gripper_visualization/meshes/visual/robotiq_gripper_coupling.stl":function robotiq_gripper_coupling_Model(props){var nodes=(0,useGLTF.L)(robotiq_gripper_coupling_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Robotiq_Gripper_Coupling.geometry,material:nodes.Robotiq_Gripper_Coupling.material}]},"package://robotiq_85_description/meshes/visual/robotiq_85_base_link.dae":function robotiq_85_base_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_base_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material},{type:"raw",geometry:nodes.mesh_0_2.geometry,material:nodes.mesh_0_2.material}]}]},"package://robotiq_85_description/meshes/visual/robotiq_85_knuckle_link.dae":function robotiq_85_knuckle_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_knuckle_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material}]}]},"package://robotiq_85_description/meshes/visual/robotiq_85_finger_link.dae":function robotiq_85_finger_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_finger_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material},{type:"raw",geometry:nodes.mesh_0_2.geometry,material:nodes.mesh_0_2.material}]}]},"package://robotiq_85_description/meshes/visual/robotiq_85_inner_knuckle_link.dae":function robotiq_85_inner_knuckle_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_inner_knuckle_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material}]}]},"package://robotiq_85_description/meshes/visual/robotiq_85_finger_tip_link.dae":function robotiq_85_finger_tip_link_Model(props){var nodes=(0,useGLTF.L)(robotiq_85_finger_tip_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material},{type:"raw",geometry:nodes.mesh_0_1.geometry,material:nodes.mesh_0_1.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_base_link.stl":function collision_robotiq_85_base_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_base_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_knuckle_link.stl":function collision_robotiq_85_knuckle_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_knuckle_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_finger_link.stl":function collision_robotiq_85_finger_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_finger_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_inner_knuckle_link.stl":function collision_robotiq_85_inner_knuckle_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_inner_knuckle_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://robotiq_85_description/meshes/collision/robotiq_85_finger_tip_link.stl":function collision_robotiq_85_finger_tip_link_Model(props){var nodes=(0,useGLTF.L)(collision_robotiq_85_finger_tip_link_namespaceObject).nodes;return[{type:"group",rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.mesh_0.geometry,material:nodes.mesh_0.material}]}]},"package://baxter_common/baxter_description/meshes/base/PEDESTAL.DAE":function PEDESTAL_Model(props){var _useGLTF=(0,useGLTF.L)(PEDESTAL_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.PEDESTAL.geometry,material:materials.Material_001}]},"package://baxter_common/baxter_description/meshes/base/pedestal_link_collision.DAE":function Pedestal_link_collision_Model(props){var nodes=(0,useGLTF.L)(pedestal_link_collision_namespaceObject).nodes;return[{type:"raw",geometry:nodes["PEDESTAL-L"].geometry,material:nodes["PEDESTAL-L"].material}]},"package://baxter_common/baxter_description/meshes/head/H0.DAE":function H0_Model(props){var _useGLTF=(0,useGLTF.L)(H0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.H0.geometry,material:materials["Material_001.001"]}]},"package://baxter_common/baxter_description/meshes/head/H1.DAE":function H1_Model(props){var _useGLTF=(0,useGLTF.L)(H1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.H1_1.geometry,material:materials["Material.001"]},{type:"raw",geometry:nodes.H1_2.geometry,material:materials["Material_001.002"]}]},"package://baxter_common/baxter_description/meshes/lower_elbow/E1.DAE":function E1_Model(props){var _useGLTF=(0,useGLTF.L)(E1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.E1_1.geometry,material:materials["Material_001.003"]},{type:"raw",geometry:nodes.E1_2.geometry,material:materials.Material_002}]},"package://baxter_common/baxter_description/meshes/lower_forearm/W1.DAE":function W1_Model(props){var _useGLTF=(0,useGLTF.L)(W1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"raw",geometry:nodes.W1_1.geometry,material:materials["Material_001.004"]},{type:"raw",geometry:nodes.W1_2.geometry,material:materials["Material_002.001"]}],rotation:[-Math.PI,0,0]}]},"package://baxter_common/baxter_description/meshes/lower_shoulder/S1.DAE":function S1_Model(props){var _useGLTF=(0,useGLTF.L)(S1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.S1.geometry,material:materials["Material_001.006"]}]},"package://baxter_common/baxter_description/meshes/torso/base_link.DAE":function Base_link_Model(props){var _useGLTF=(0,useGLTF.L)(base_link_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.base_link_1.geometry,material:materials.Material_004},{type:"raw",geometry:nodes.base_link_2.geometry,material:materials["Material_001.007"]},{type:"raw",geometry:nodes.base_link_3.geometry,material:materials.Material_003},{type:"raw",geometry:nodes.base_link_4.geometry,material:materials.Material_007},{type:"raw",geometry:nodes.base_link_5.geometry,material:materials.Material_005},{type:"raw",geometry:nodes.base_link_6.geometry,material:materials.Material_006}]},"package://baxter_common/baxter_description/meshes/torso/base_link_collision.DAE":function Base_link_collision_Model(props){var nodes=(0,useGLTF.L)(base_link_collision_namespaceObject).nodes;return[{type:"raw",geometry:nodes["TORSO-L"].geometry,material:nodes["TORSO-L"].material}]},"package://baxter_common/baxter_description/meshes/upper_elbow/E0.DAE":function E0_Model(props){var _useGLTF=(0,useGLTF.L)(E0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.E0_1.geometry,material:materials["Material_001.008"]},{type:"raw",geometry:nodes.E0_2.geometry,material:materials["Material_002.002"]}]},"package://baxter_common/baxter_description/meshes/upper_forearm/W0.DAE":function W0_Model(props){var _useGLTF=(0,useGLTF.L)(W0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.W0_1.geometry,material:materials["Material_001.009"]},{type:"raw",geometry:nodes.W0_2.geometry,material:materials["Material_002.003"]},{type:"raw",geometry:nodes.W0_3.geometry,material:materials["Material_003.001"]},{type:"raw",geometry:nodes.W0_4.geometry,material:materials["Material_005.001"]}]},"package://baxter_common/baxter_description/meshes/upper_shoulder/S0.DAE":function S0_Model(props){var _useGLTF=(0,useGLTF.L)(S0_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",gemometry:nodes.S0_1.geometry,material:materials["Material_002.004"]},{type:"raw",geometry:nodes.S0_2.geometry,material:materials["Material_003.002"]}]},"package://baxter_common/baxter_description/meshes/wrist/W2.DAE":function W2_Model(props){var _useGLTF=(0,useGLTF.L)(W2_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.W2_1.geometry,material:materials["Material_001.010"]},{type:"raw",geometry:nodes.W2_2.geometry,material:materials["Material_002.005"]},{type:"raw",geometry:nodes.W2_3.geometry,material:materials["Material_003.003"]}]},"package://ur_description/meshes/ur3/visual/base.dae":function base_Model(props){var nodes=(0,useGLTF.L)(base_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_014.geometry,material:nodes.eSeries_UR3e_014.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_011.geometry,material:nodes.eSeries_UR3e_011.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/forearm.dae":function forearm_Model(props){var nodes=(0,useGLTF.L)(forearm_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_033.geometry,material:nodes.eSeries_UR3e_033.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_022.geometry,material:nodes.eSeries_UR3e_022.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_023.geometry,material:nodes.eSeries_UR3e_023.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_024.geometry,material:nodes.eSeries_UR3e_024.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_025.geometry,material:nodes.eSeries_UR3e_025.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_026.geometry,material:nodes.eSeries_UR3e_026.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_028.geometry,material:nodes.eSeries_UR3e_028.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/shoulder.dae":function shoulder_Model(props){var nodes=(0,useGLTF.L)(shoulder_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_029.geometry,material:nodes.eSeries_UR3e_029.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_012.geometry,material:nodes.eSeries_UR3e_012.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_013.geometry,material:nodes.eSeries_UR3e_013.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/upperarm.dae":function upperarm_Model(props){var nodes=(0,useGLTF.L)(upperarm_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_032.geometry,material:nodes.eSeries_UR3e_032.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_031.geometry,material:nodes.eSeries_UR3e_031.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_015.geometry,material:nodes.eSeries_UR3e_015.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_016.geometry,material:nodes.eSeries_UR3e_016.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_017.geometry,material:nodes.eSeries_UR3e_017.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_018.geometry,material:nodes.eSeries_UR3e_018.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_019.geometry,material:nodes.eSeries_UR3e_019.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_020.geometry,material:nodes.eSeries_UR3e_020.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_021.geometry,material:nodes.eSeries_UR3e_021.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/wrist1.dae":function wrist1_Model(props){var nodes=(0,useGLTF.L)(wrist1_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_034.geometry,material:nodes.eSeries_UR3e_034.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_027.geometry,material:nodes.eSeries_UR3e_027.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_035.geometry,material:nodes.eSeries_UR3e_035.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/wrist2.dae":function wrist2_Model(props){var nodes=(0,useGLTF.L)(wrist2_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e.geometry,material:nodes.eSeries_UR3e.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_036.geometry,material:nodes.eSeries_UR3e_036.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]},{type:"raw",geometry:nodes.eSeries_UR3e_037.geometry,material:nodes.eSeries_UR3e_037.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/visual/wrist3.dae":function wrist3_Model(props){var nodes=(0,useGLTF.L)(wrist3_namespaceObject).nodes;return[{type:"raw",geometry:nodes.eSeries_UR3e_002.geometry,material:nodes.eSeries_UR3e_002.material,scale:[.001,.001,.001],rotation:[Math.PI/2,0,0]}]},"package://ur_description/meshes/ur3/collision/base.stl":function collision_base_Model(props){var nodes=(0,useGLTF.L)(collision_base_namespaceObject).nodes;return[{type:"raw",geometry:nodes.base.geometry,material:nodes.base.material}]},"package://ur_description/meshes/ur3/collision/forearm.stl":function collision_forearm_Model(props){var nodes=(0,useGLTF.L)(collision_forearm_namespaceObject).nodes;return[{type:"raw",geometry:nodes.forearm.geometry,material:nodes.forearm.material}]},"package://ur_description/meshes/ur3/collision/shoulder.stl":function collision_shoulder_Model(props){var nodes=(0,useGLTF.L)(collision_shoulder_namespaceObject).nodes;return[{type:"raw",geometry:nodes.shoulder.geometry,material:nodes.shoulder.material}]},"package://ur_description/meshes/ur3/collision/upperarm.stl":function collision_upperarm_Model(props){var nodes=(0,useGLTF.L)(collision_upperarm_namespaceObject).nodes;return[{type:"raw",geometry:nodes.upperarm.geometry,material:nodes.upperarm.material}]},"package://ur_description/meshes/ur3/collision/wrist1.stl":function collision_wrist1_Model(props){var nodes=(0,useGLTF.L)(collision_wrist1_namespaceObject).nodes;return[{type:"raw",geometry:nodes.wrist1.geometry,material:nodes.wrist1.material}]},"package://ur_description/meshes/ur3/collision/wrist2.stl":function collision_wrist2_Model(props){var nodes=(0,useGLTF.L)(collision_wrist2_namespaceObject).nodes;return[{type:"raw",geometry:nodes.wrist2.geometry,material:nodes.wrist2.material}]},"package://ur_description/meshes/ur3/collision/wrist3.stl":function collision_wrist3_Model(props){var nodes=(0,useGLTF.L)(collision_wrist3_namespaceObject).nodes;return[{type:"raw",geometry:nodes.wrist3.geometry,material:nodes.wrist3.material}]},"package://ur_description/meshes/ur5/visual/base.dae":function Ur5_base_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_base_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh002"].geometry,material:materials["Rohr.005"]},{type:"raw",geometry:nodes["ActorShape0_0-Mesh002_1"].geometry,material:materials["Scheibe.002"]}]},"package://ur_description/meshes/ur5/visual/forearm.dae":function Ur5_forearm_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_forearm_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes.Actor0_001.geometry,material:materials.blau_005},{type:"raw",geometry:nodes.Actor1.geometry,material:materials.Rohr_005},{type:"raw",geometry:nodes.Actor2.geometry,material:nodes.Actor2.material},{type:"raw",geometry:nodes.Actor3.geometry,material:nodes.Actor3.material}]},"package://ur_description/meshes/ur5/visual/shoulder.dae":function Ur5_shoulder_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_shoulder_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh023"].geometry,material:materials["verbindung.005"]},{type:"raw",geometry:nodes["ActorShape0_0-Mesh023_1"].geometry,material:materials["Scheibe.003"]},{type:"raw",geometry:nodes.Actor1.geometry,material:materials["blau.004"]}]},"package://ur_description/meshes/ur5/visual/upperarm.dae":function Ur5_upperarm_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_upperarm_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh024"].geometry,material:nodes["ActorShape0_0-Mesh024"].material},{type:"raw",geometry:nodes["ActorShape0_0-Mesh024_1"].geometry,material:nodes["ActorShape0_0-Mesh024_1"].material},{type:"raw",geometry:nodes.Actor1.geometry,material:nodes.Actor1.material},{type:"raw",geometry:nodes["ActorShape2_0-Mesh011"].geometry,material:nodes["ActorShape2_0-Mesh011"].material},{type:"raw",geometry:nodes["ActorShape2_0-Mesh011_1"].geometry,material:nodes["ActorShape2_0-Mesh011_1"].material},{type:"raw",geometry:nodes.Actor3.geometry,material:materials["Rohr.006"]},{type:"raw",geometry:nodes.Actor4.geometry,material:nodes.Actor4.material}]},"package://ur_description/meshes/ur5/visual/wrist1.dae":function Ur5_wrist1_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_wrist1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh025"].geometry,material:materials.Scheibe_001},{type:"raw",geometry:nodes["ActorShape0_0-Mesh025_1"].geometry,material:materials["verbindung_001.001"]},{type:"raw",geometry:nodes.Actor1.geometry,material:materials["blau_001.001"]}]},"package://ur_description/meshes/ur5/visual/wrist2.dae":function Ur5_wrist2_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_wrist2_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh026"].geometry,material:materials.Scheibe_002},{type:"raw",geometry:nodes["ActorShape0_0-Mesh026_1"].geometry,material:materials.verbindung_002},{type:"raw",geometry:nodes.Actor1.geometry,material:materials.blau_002}]},"package://ur_description/meshes/ur5/visual/wrist3.dae":function Ur5_wrist3_Model(props){var _useGLTF=(0,useGLTF.L)(Ur5_wrist3_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["ActorShape0_0-Mesh003"].geometry,material:materials.Rohr_007_001},{type:"raw",geometry:nodes["ActorShape0_0-Mesh003_1"].geometry,material:materials["SWMaterial-1_004_002_001"]}]},"package://ur_description/meshes/ur10/visual/base.dae":function Ur10_base_Model(props){var nodes=(0,useGLTF.L)(Ur10_base_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Base.geometry,material:nodes.Base.material}]},"package://ur_description/meshes/ur10/visual/forearm.dae":function Ur10_forearm_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_forearm_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0.001"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1.001"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2.001"]},{type:"raw",geometry:nodes["node-shape3-name"].geometry,material:materials["SWMaterial-3.001"]},{type:"raw",geometry:nodes["node-shape4-name"].geometry,material:materials["SWMaterial-4.001"]}]},"package://ur_description/meshes/ur10/visual/shoulder.dae":function Ur10_shoulder_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_shoulder_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0.002"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1.002"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2.002"]}]},"package://ur_description/meshes/ur10/visual/upperarm.dae":function Ur10_upperarm_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_upperarm_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0.003"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1.003"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2.003"]},{type:"raw",geometry:nodes["node-shape3-name"].geometry,material:materials["SWMaterial-3.002"]}]},"package://ur_description/meshes/ur10/visual/wrist1.dae":function Ur10_wrist1_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_wrist1_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0_001"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1_001"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2_001"]}]},"package://ur_description/meshes/ur10/visual/wrist2.dae":function Ur10_wrist2_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_wrist2_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-0_002"]},{type:"raw",geometry:nodes["node-shape1-name"].geometry,material:materials["SWMaterial-1_002"]},{type:"raw",geometry:nodes["node-shape2-name"].geometry,material:materials["SWMaterial-2_002"]}]},"package://ur_description/meshes/ur10/visual/wrist3.dae":function Ur10_wrist3_Model(props){var _useGLTF=(0,useGLTF.L)(Ur10_wrist3_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"raw",geometry:nodes["node-shape0-name"].geometry,material:materials["SWMaterial-2_003"]}]},"package://app/meshes/3DBenchy.stl":function _3DBenchy_Model(props){var nodes=(0,useGLTF.L)(_3DBenchy_namespaceObject).nodes;return[{type:"raw",geometry:nodes["3DBenchy"].geometry,material:nodes["3DBenchy"].material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/MK2-Printer/MK2-Printer.stl":function MK2Printer_Model(_){var _useGLTF=(0,useGLTF.L)(MK2Printer_namespaceObject),nodes=_useGLTF.nodes,materials=_useGLTF.materials;return[{type:"group",children:[{type:"group",position:[.01,-.27,-.06],rotation:[Math.PI/2,0,0],scale:[.001,.001,.001],children:[{type:"group",position:[-185,0,0],children:[{type:"group",position:[159.75,16,-226.22],rotation:[0,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1152.geometry,material:nodes.Body1152.material,scale:[10,10,10]}]},{type:"group",position:[-7.5,-34,-168.5],rotation:[-Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1148.geometry,material:nodes.Body1148.material,scale:[10,10,10]},{type:"group",position:[114.5,50.5,-5],rotation:[-Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1150.geometry,material:nodes.Body1150.material,scale:[10,10,10]}]},{type:"group",position:[0,55,-92],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1149.geometry,material:nodes.Body1149.material,scale:[10,10,10]}]},{type:"group",position:[-.5,50.5,-5],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1151.geometry,material:nodes.Body1151.material,scale:[10,10,10]}]}]},{type:"group",position:[221.78,26.3,-236.47],rotation:[Math.PI,0,Math.PI],children:[{type:"group",position:[45.5,15,-28],rotation:[-Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1067.geometry,material:nodes.Body1067.material,scale:[10,10,10]}]},{type:"group",position:[8.5,14.5,21.5],rotation:[-Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1070.geometry,material:nodes.Body1070.material,scale:[10,10,10]}]},{type:"group",position:[8.5,14.95,21.5],children:[{type:"raw",geometry:nodes.Body1090.geometry,material:nodes.Body1090.material,scale:[10,10,10]}]},{type:"group",position:[17.5,15,-21.85],rotation:[Math.PI,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1066.geometry,material:materials["Opaque(232,163,0)"],scale:[10,10,10]}]},{type:"raw",geometry:nodes.Body1062.geometry,material:nodes.Body1062.material,scale:[10,10,10]},{type:"group",position:[12.98,30,-30.6],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1063.geometry,material:nodes.Body1063.material,scale:[10,10,10]}]},{type:"group",position:[1.5,16.75,30],rotation:[Math.PI,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1065.geometry,material:nodes.Body1065.material,scale:[10,10,10]}]},{type:"group",position:[1,22.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1091.geometry,material:nodes.Body1091.material,scale:[10,10,10]}]},{type:"group",position:[1,7.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1092.geometry,material:nodes.Body1092.material,scale:[10,10,10]}]},{type:"group",position:[18.6,47,-56],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1069.geometry,material:nodes.Body1069.material,scale:[10,10,10]}]},{type:"group",position:[6.58,45.4,-26.81],rotation:[-Math.PI/2,0,1.56],children:[{type:"raw",geometry:nodes.Body1064.geometry,material:nodes.Body1064.material,scale:[10,10,10]}]},{type:"group",position:[21,15,21],rotation:[-Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1103.geometry,material:nodes.Body1103.material,scale:[10,10,10]}]},{type:"group",position:[-5.5,6,-62],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1104.geometry,material:nodes.Body1104.material,scale:[10,10,10]}]},{type:"group",position:[21,45,21],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1068.geometry,material:nodes.Body1068.material,scale:[10,10,10]}]},{type:"group",position:[5.5,10,-6.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1078.geometry,material:nodes.Body1078.material,scale:[10,10,10]}]},{type:"group",position:[5.5,4,-6.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1079_1.geometry,material:nodes.Body1079_1.material,scale:[10,10,10]}]},{type:"group",position:[20.5,22.4,36.25],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1080_1.geometry,material:nodes.Body1080_1.material,scale:[10,10,10]}]},{type:"group",position:[20.5,7.4,36.25],rotation:[Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1081_1.geometry,material:nodes.Body1081_1.material,scale:[10,10,10]}]},{type:"group",position:[-13.25,26.2,-45],rotation:[Math.PI/2,0,2.62],children:[{type:"raw",geometry:nodes.Body1075_1.geometry,material:nodes.Body1075_1.material,scale:[10,10,10]}]},{type:"group",position:[29.5,28,-6.5],rotation:[-Math.PI/2,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1076_1.geometry,material:nodes.Body1076_1.material,scale:[10,10,10]}]},{type:"group",position:[29.5,12.8,-6.5],rotation:[-Math.PI/2,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1077.geometry,material:nodes.Body1077.material,scale:[10,10,10]}]},{type:"group",position:[-5.5,6,-62.16],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1105.geometry,material:nodes.Body1105.material,scale:[10,10,10]}]},{type:"group",position:[5.5,-12,-6.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1100.geometry,material:nodes.Body1100.material,scale:[10,10,10]}]},{type:"group",position:[5.5,27,-6.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1074_1.geometry,material:nodes.Body1074_1.material,scale:[10,10,10]}]},{type:"group",position:[45.5,3,-16],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1096.geometry,material:nodes.Body1096.material,scale:[10,10,10]}]},{type:"group",position:[45.5,27,-16],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1097.geometry,material:nodes.Body1097.material,scale:[10,10,10]}]},{type:"group",position:[45.5,3,-40],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1098.geometry,material:nodes.Body1098.material,scale:[10,10,10]}]},{type:"group",position:[45.5,27,-40],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1099.geometry,material:nodes.Body1099.material,scale:[10,10,10]}]},{type:"group",position:[29.39,45.4,-6.6],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1093.geometry,material:nodes.Body1093.material,scale:[10,10,10]}]},{type:"group",position:[-13.25,45.4,-45],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1094.geometry,material:nodes.Body1094.material,scale:[10,10,10]}]},{type:"group",position:[5,43.5,-56],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1095.geometry,material:nodes.Body1095.material,scale:[10,10,10]}]},{type:"group",position:[40.5,27,-4.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1073_1.geometry,material:nodes.Body1073_1.material,scale:[10,10,10]}]},{type:"group",position:[36.5,3.5,5.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1071.geometry,material:nodes.Body1071.material,scale:[10,10,10]}]},{type:"group",position:[5.5,3.5,5.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1072.geometry,material:nodes.Body1072.material,scale:[10,10,10]}]},{type:"group",position:[29.5,-12,-6.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1101.geometry,material:nodes.Body1101.material,scale:[10,10,10]}]},{type:"group",position:[-12,7.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1086.geometry,material:nodes.Body1086.material,scale:[10,10,10]}]},{type:"group",position:[-12,22.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1087.geometry,material:nodes.Body1087.material,scale:[10,10,10]}]},{type:"group",position:[36.5,-5,36.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1102.geometry,material:nodes.Body1102.material,scale:[10,10,10]}]},{type:"group",position:[1,7.4,36.25],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1082_1.geometry,material:nodes.Body1082_1.material,scale:[10,10,10]}]},{type:"group",position:[-11.5,7.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1083_1.geometry,material:nodes.Body1083_1.material,scale:[10,10,10]}]},{type:"group",position:[1,22.4,36.25],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1084_1.geometry,material:nodes.Body1084_1.material,scale:[10,10,10]}]},{type:"group",position:[-11.5,22.4,36.25],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1085.geometry,material:nodes.Body1085.material,scale:[10,10,10]}]},{type:"group",position:[8.5,17.75,21.5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1088.geometry,material:nodes.Body1088.material,scale:[10,10,10]}]},{type:"group",position:[8.5,12.25,21.5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1089.geometry,material:nodes.Body1089.material,scale:[10,10,10]}]}]},{type:"group",position:[322,-62,-17],rotation:[0,0,-Math.PI/2],children:[{type:"group",position:[64.5,57.5,-11.9],children:[{type:"raw",geometry:nodes.Body1138.geometry,material:nodes.Body1138.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1139.geometry,material:nodes.Body1139.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1140.geometry,material:nodes.Body1140.material,scale:[10,10,10]}]},{type:"group",position:[17,57.01,-8.45],children:[{type:"raw",geometry:nodes.Body1141.geometry,material:nodes.Body1141.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body10.geometry,material:nodes.Body10.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body100.geometry,material:nodes.Body100.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body101.geometry,material:nodes.Body101.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body102.geometry,material:nodes.Body102.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body103.geometry,material:nodes.Body103.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body104.geometry,material:nodes.Body104.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body105.geometry,material:nodes.Body105.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body106.geometry,material:nodes.Body106.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body107.geometry,material:nodes.Body107.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body108.geometry,material:nodes.Body108.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body109.geometry,material:nodes.Body109.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body11.geometry,material:nodes.Body11.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body110.geometry,material:nodes.Body110.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body111.geometry,material:nodes.Body111.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body112.geometry,material:nodes.Body112.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body113.geometry,material:nodes.Body113.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body114.geometry,material:nodes.Body114.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body115.geometry,material:nodes.Body115.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body116.geometry,material:nodes.Body116.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body117.geometry,material:nodes.Body117.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body118.geometry,material:nodes.Body118.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body119.geometry,material:nodes.Body119.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body12.geometry,material:nodes.Body12.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body120.geometry,material:nodes.Body120.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body121.geometry,material:nodes.Body121.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body122.geometry,material:nodes.Body122.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body123.geometry,material:nodes.Body123.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body124.geometry,material:nodes.Body124.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body125.geometry,material:nodes.Body125.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body126.geometry,material:nodes.Body126.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body127.geometry,material:nodes.Body127.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body128.geometry,material:nodes.Body128.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body129.geometry,material:nodes.Body129.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body13.geometry,material:nodes.Body13.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body130.geometry,material:nodes.Body130.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body131.geometry,material:nodes.Body131.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body132.geometry,material:nodes.Body132.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body133.geometry,material:nodes.Body133.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body134.geometry,material:nodes.Body134.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body135.geometry,material:nodes.Body135.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body136.geometry,material:nodes.Body136.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body137.geometry,material:nodes.Body137.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body138.geometry,material:nodes.Body138.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body139.geometry,material:nodes.Body139.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body14.geometry,material:nodes.Body14.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body140.geometry,material:nodes.Body140.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body141.geometry,material:nodes.Body141.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body142.geometry,material:nodes.Body142.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body143.geometry,material:nodes.Body143.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body144.geometry,material:nodes.Body144.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body145.geometry,material:nodes.Body145.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body146.geometry,material:nodes.Body146.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body147.geometry,material:nodes.Body147.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body148.geometry,material:nodes.Body148.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body149.geometry,material:nodes.Body149.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body15.geometry,material:nodes.Body15.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body150.geometry,material:nodes.Body150.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body151.geometry,material:nodes.Body151.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body152.geometry,material:nodes.Body152.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body153.geometry,material:nodes.Body153.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body154.geometry,material:nodes.Body154.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body155.geometry,material:nodes.Body155.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body156.geometry,material:nodes.Body156.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body157.geometry,material:nodes.Body157.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body158.geometry,material:nodes.Body158.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body159.geometry,material:nodes.Body159.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body16.geometry,material:nodes.Body16.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body160.geometry,material:nodes.Body160.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body161.geometry,material:nodes.Body161.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body162.geometry,material:nodes.Body162.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body163.geometry,material:nodes.Body163.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body164.geometry,material:nodes.Body164.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body165.geometry,material:nodes.Body165.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body17.geometry,material:nodes.Body17.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body18.geometry,material:nodes.Body18.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body19.geometry,material:nodes.Body19.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body2.geometry,material:nodes.Body2.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body20.geometry,material:nodes.Body20.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body21.geometry,material:nodes.Body21.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body22.geometry,material:nodes.Body22.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body23.geometry,material:nodes.Body23.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body24.geometry,material:nodes.Body24.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body25.geometry,material:nodes.Body25.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body26.geometry,material:nodes.Body26.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body27.geometry,material:nodes.Body27.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body28.geometry,material:nodes.Body28.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body29.geometry,material:nodes.Body29.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body3.geometry,material:nodes.Body3.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body30.geometry,material:nodes.Body30.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body31.geometry,material:nodes.Body31.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body32.geometry,material:nodes.Body32.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body33.geometry,material:nodes.Body33.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body34.geometry,material:nodes.Body34.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body35.geometry,material:nodes.Body35.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body36.geometry,material:nodes.Body36.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body37.geometry,material:nodes.Body37.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body38.geometry,material:nodes.Body38.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body39.geometry,material:nodes.Body39.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body4.geometry,material:nodes.Body4.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body40.geometry,material:nodes.Body40.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body41.geometry,material:nodes.Body41.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body42.geometry,material:nodes.Body42.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body43.geometry,material:nodes.Body43.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body44.geometry,material:nodes.Body44.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body45.geometry,material:nodes.Body45.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body46.geometry,material:nodes.Body46.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body47.geometry,material:nodes.Body47.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body48.geometry,material:nodes.Body48.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body49.geometry,material:nodes.Body49.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body5.geometry,material:nodes.Body5.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body50.geometry,material:nodes.Body50.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body51.geometry,material:nodes.Body51.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body52.geometry,material:nodes.Body52.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body53.geometry,material:nodes.Body53.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body54.geometry,material:nodes.Body54.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body55.geometry,material:nodes.Body55.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body56.geometry,material:nodes.Body56.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body57.geometry,material:nodes.Body57.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body58.geometry,material:nodes.Body58.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body59.geometry,material:nodes.Body59.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body6.geometry,material:nodes.Body6.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body60.geometry,material:nodes.Body60.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body61.geometry,material:nodes.Body61.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body62.geometry,material:nodes.Body62.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body63.geometry,material:nodes.Body63.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body64.geometry,material:nodes.Body64.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body65.geometry,material:nodes.Body65.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body66.geometry,material:nodes.Body66.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body67.geometry,material:nodes.Body67.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body68.geometry,material:nodes.Body68.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body69.geometry,material:nodes.Body69.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body7.geometry,material:nodes.Body7.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body70.geometry,material:nodes.Body70.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body71.geometry,material:nodes.Body71.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body72.geometry,material:nodes.Body72.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body73.geometry,material:nodes.Body73.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body74.geometry,material:nodes.Body74.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body75.geometry,material:nodes.Body75.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body76.geometry,material:nodes.Body76.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body77.geometry,material:nodes.Body77.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body78.geometry,material:nodes.Body78.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body79.geometry,material:nodes.Body79.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body8.geometry,material:nodes.Body8.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body80.geometry,material:nodes.Body80.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body81.geometry,material:nodes.Body81.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body82.geometry,material:nodes.Body82.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body83.geometry,material:nodes.Body83.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body84.geometry,material:nodes.Body84.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body85.geometry,material:nodes.Body85.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body86.geometry,material:nodes.Body86.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body87.geometry,material:nodes.Body87.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body88.geometry,material:nodes.Body88.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body89.geometry,material:nodes.Body89.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body9.geometry,material:nodes.Body9.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body90.geometry,material:nodes.Body90.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body91.geometry,material:nodes.Body91.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body92.geometry,material:nodes.Body92.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body93.geometry,material:nodes.Body93.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body94.geometry,material:nodes.Body94.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body95.geometry,material:nodes.Body95.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body96.geometry,material:nodes.Body96.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body97.geometry,material:nodes.Body97.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body98.geometry,material:nodes.Body98.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body99.geometry,material:nodes.Body99.material,scale:[10,10,10]}]},{type:"raw",geometry:nodes.Body1137.geometry,material:nodes.Body1137.material,scale:[10,10,10]},{type:"group",position:[-1.5,51,-34],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1142.geometry,material:materials["Opaque(245,245,246)"],scale:[10,10,10]}]}]},{type:"group",position:[0,0,-7.89],children:[{type:"group",position:[179.5,14.3,-242.58],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1027.geometry,material:nodes.Body1027.material,scale:[10,10,10]}]},{type:"group",position:[179.5,14.3,-197.58],rotation:[Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1028.geometry,material:nodes.Body1028.material,scale:[10,10,10]}]},{type:"group",position:[348.5,14.3,-218.33],children:[{type:"raw",geometry:nodes.Body1040.geometry,material:nodes.Body1040.material,scale:[10,10,10]}]},{type:"group",position:[367,29.3,-236.58],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1031.geometry,material:nodes.Body1031.material,scale:[10,10,10]}]},{type:"group",position:[367,29.3,-202.58],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1032.geometry,material:nodes.Body1032.material,scale:[10,10,10]}]},{type:"group",position:[3,29.3,-236.58],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1033.geometry,material:nodes.Body1033.material,scale:[10,10,10]}]},{type:"group",position:[3,29.3,-202.58],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1034.geometry,material:nodes.Body1034.material,scale:[10,10,10]}]},{type:"group",position:[217.28,14.3,-242.58],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1035.geometry,material:nodes.Body1035.material,scale:[10,10,10]}]},{type:"group",position:[191.28,14.3,-242.58],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1036.geometry,material:nodes.Body1036.material,scale:[10,10,10]}]},{type:"group",position:[204.78,14.3,-197.58],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1037.geometry,material:nodes.Body1037.material,scale:[10,10,10]}]},{type:"group",position:[-29,-9.2,-218.33],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1038.geometry,material:nodes.Body1038.material,scale:[10,10,10]}]},{type:"group",position:[348.5,7.8,-218.33],rotation:[-Math.PI/2,0,-Math.PI/6],children:[{type:"raw",geometry:nodes.Body1047.geometry,material:nodes.Body1047.material,scale:[10,10,10]}]},{type:"group",position:[370.5,14.3,-242.58],rotation:[-Math.PI,1.57,0],children:[{type:"raw",geometry:nodes.Body1056.geometry,material:nodes.Body1056.material,scale:[10,10,10]}]},{type:"group",position:[370.5,14.3,-197.58],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1057.geometry,material:nodes.Body1057.material,scale:[10,10,10]}]},{type:"group",position:[13.28,22.58,-240.78],rotation:[0,0,1.31],children:[{type:"raw",geometry:nodes.Body1048.geometry,material:nodes.Body1048.material,scale:[10,10,10]}]},{type:"group",position:[26.72,36.02,-240.78],rotation:[0,0,-.26],children:[{type:"raw",geometry:nodes.Body1049.geometry,material:nodes.Body1049.material,scale:[10,10,10]}]},{type:"group",position:[343.28,36.02,-240.78],rotation:[0,0,.26],children:[{type:"raw",geometry:nodes.Body1050.geometry,material:nodes.Body1050.material,scale:[10,10,10]}]},{type:"group",position:[356.72,22.58,-240.78],rotation:[0,0,1.83],children:[{type:"raw",geometry:nodes.Body1051.geometry,material:nodes.Body1051.material,scale:[10,10,10]}]},{type:"group",position:[-29,19.7,-218.33],children:[{type:"raw",geometry:nodes.Body1039.geometry,material:nodes.Body1039.material,scale:[10,10,10]}]},{type:"group",position:[24,19.05,-180.18],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1060.geometry,material:nodes.Body1060.material,scale:[10,10,10]}]},{type:"group",position:[24,9.55,-180.18],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1061.geometry,material:nodes.Body1061.material,scale:[10,10,10]}]},{type:"group",position:[374.5,14.3,-242.58],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1045.geometry,material:nodes.Body1045.material,scale:[10,10,10]}]},{type:"group",position:[374.5,14.3,-197.58],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1046.geometry,material:nodes.Body1046.material,scale:[10,10,10]}]},{type:"group",position:[13.28,22.58,-252.58],children:[{type:"raw",geometry:nodes.Body1052.geometry,material:nodes.Body1052.material,scale:[10,10,10]}]},{type:"group",position:[26.72,36.02,-252.58],children:[{type:"raw",geometry:nodes.Body1053.geometry,material:nodes.Body1053.material,scale:[10,10,10]}]},{type:"group",position:[356.72,22.58,-252.58],children:[{type:"raw",geometry:nodes.Body1054.geometry,material:nodes.Body1054.material,scale:[10,10,10]}]},{type:"group",position:[343.28,36.02,-252.58],children:[{type:"raw",geometry:nodes.Body1055.geometry,material:nodes.Body1055.material,scale:[10,10,10]}]},{type:"group",position:[-44.5,19.3,-233.83],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1041.geometry,material:nodes.Body1041.material,scale:[10,10,10]}]},{type:"group",position:[-13.5,19.3,-233.83],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1042.geometry,material:nodes.Body1042.material,scale:[10,10,10]}]},{type:"group",position:[-13.5,19.3,-202.83],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1043.geometry,material:nodes.Body1043.material,scale:[10,10,10]}]},{type:"group",position:[348.5,20.8,-218.33],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1044.geometry,material:nodes.Body1044.material,scale:[10,10,10]}]},{type:"group",position:[24,9.55,-183.38],rotation:[Math.PI/2,-Math.PI/2,0],children:[{type:"group",position:[-7.55,0,-9],children:[{type:"raw",geometry:nodes.Body1058.geometry,material:nodes.Body1058.material,scale:[10,10,10]}]},{type:"raw",geometry:nodes.Body1059.geometry,material:nodes.Body1059.material,scale:[10,10,10]}]},{type:"group",position:[187.78,26.3,-197.58],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1026.geometry,material:nodes.Body1026.material,scale:[10,10,10]}]},{type:"group",position:[367,29.3,-248.58],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1024.geometry,material:nodes.Body1024.material,scale:[10,10,10]}]},{type:"group",position:[3,29.3,-248.58],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1025.geometry,material:nodes.Body1025.material,scale:[10,10,10]}]},{type:"group",position:[20,29.3,-252.58],rotation:[0,0,Math.PI/4],children:[{type:"raw",geometry:nodes.Body1029.geometry,material:nodes.Body1029.material,scale:[10,10,10]}]},{type:"group",position:[350,29.3,-252.58],rotation:[0,0,-Math.PI/4],children:[{type:"raw",geometry:nodes.Body1030.geometry,material:nodes.Body1030.material,scale:[10,10,10]}]}]},{type:"group",position:[367,29.3,-210],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1.geometry,material:nodes.Body1.material,scale:[10,10,10]}]},{type:"group",position:[3,29.3,-210],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1001.geometry,material:nodes.Body1001.material,scale:[10,10,10]}]},{type:"group",position:[350,29.3,-35],rotation:[-Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1002.geometry,material:nodes.Body1002.material,scale:[10,10,10]}]},{type:"group",position:[20,29.3,-35],rotation:[-Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1003.geometry,material:nodes.Body1003.material,scale:[10,10,10]}]},{type:"group",position:[30,4,-360],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1004.geometry,material:nodes.Body1004.material,scale:[10,10,10]}]},{type:"group",position:[365.5,44.8,-55.5],children:[{type:"raw",geometry:nodes.Body1021.geometry,material:nodes.Body1021.material,scale:[10,10,10]}]},{type:"group",position:[340,4,-360],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1005.geometry,material:nodes.Body1005.material,scale:[10,10,10]}]},{type:"group",position:[4.5,13.8,-55.5],children:[{type:"raw",geometry:nodes.Body1014.geometry,material:nodes.Body1014.material,scale:[10,10,10]}]},{type:"group",position:[35.5,13.8,-55.5],children:[{type:"raw",geometry:nodes.Body1015.geometry,material:nodes.Body1015.material,scale:[10,10,10]}]},{type:"group",position:[4.5,44.8,-55.5],children:[{type:"raw",geometry:nodes.Body1016.geometry,material:nodes.Body1016.material,scale:[10,10,10]}]},{type:"group",position:[35.5,44.8,-55.5],children:[{type:"raw",geometry:nodes.Body1017.geometry,material:nodes.Body1017.material,scale:[10,10,10]}]},{type:"group",position:[334.5,13.8,-55.5],children:[{type:"raw",geometry:nodes.Body1018.geometry,material:nodes.Body1018.material,scale:[10,10,10]}]},{type:"group",position:[365.5,13.8,-55.5],children:[{type:"raw",geometry:nodes.Body1019.geometry,material:nodes.Body1019.material,scale:[10,10,10]}]},{type:"group",position:[334.5,44.8,-55.5],children:[{type:"raw",geometry:nodes.Body1020.geometry,material:nodes.Body1020.material,scale:[10,10,10]}]},{type:"group",position:[4.5,13.8,-55],children:[{type:"raw",geometry:nodes.Body1006.geometry,material:nodes.Body1006.material,scale:[10,10,10]}]},{type:"group",position:[35.5,13.8,-55],children:[{type:"raw",geometry:nodes.Body1007.geometry,material:nodes.Body1007.material,scale:[10,10,10]}]},{type:"group",position:[4.5,44.8,-55],children:[{type:"raw",geometry:nodes.Body1008.geometry,material:nodes.Body1008.material,scale:[10,10,10]}]},{type:"group",position:[35.5,44.8,-55],children:[{type:"raw",geometry:nodes.Body1009.geometry,material:nodes.Body1009.material,scale:[10,10,10]}]},{type:"group",position:[334.5,13.8,-55],children:[{type:"raw",geometry:nodes.Body1010.geometry,material:nodes.Body1010.material,scale:[10,10,10]}]},{type:"group",position:[365.5,13.8,-55],children:[{type:"raw",geometry:nodes.Body1011.geometry,material:nodes.Body1011.material,scale:[10,10,10]}]},{type:"group",position:[334.5,44.8,-55],children:[{type:"raw",geometry:nodes.Body1012.geometry,material:nodes.Body1012.material,scale:[10,10,10]}]},{type:"group",position:[365.5,44.8,-55.5],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1013.geometry,material:nodes.Body1013.material,scale:[10,10,10]}]},{type:"group",position:[350,29.3,-52],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1022.geometry,material:nodes.Body1022.material,scale:[10,10,10]}]},{type:"group",position:[20,29.3,-52],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1023.geometry,material:nodes.Body1023.material,scale:[10,10,10]}]},{type:"group",position:[184.6,273.14,-14.87],rotation:[2.36,0,0],children:[{type:"group",position:[59.23,-1.7,1.25],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1147.geometry,material:nodes.Body1147.material,scale:[10,10,10]}]},{type:"group",position:[.75,13.2,2.5],rotation:[-Math.PI,0,0],children:[{type:"group",scale:[10,10,10],children:[{type:"raw",geometry:nodes.Body1054_1.geometry,material:materials["Opaque(0,192,0)"]},{type:"raw",geometry:nodes.Body1054_2.geometry,material:materials["Opaque(31,251,255)"]}]}]},{type:"raw",geometry:nodes.Body1143.geometry,material:nodes.Body1143.material,scale:[10,10,10]},{type:"group",position:[-53.45,70.31,22.5],rotation:[2.36,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1145.geometry,material:nodes.Body1145.material,scale:[10,10,10]}]},{type:"group",position:[54.95,70.31,22.85],rotation:[2.36,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1146.geometry,material:nodes.Body1146.material,scale:[10,10,10]}]}]},{type:"group",position:[0,32,20],children:[{type:"group",position:[184.6,12,-29.28],rotation:[0,0,0],children:[{type:"raw",geometry:nodes.Body1136.geometry,material:nodes.Body1136.material,scale:[10,10,10]}]},{type:"group",position:[289.5,125.78,-52.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1125_1.geometry,material:nodes.Body1125_1.material,scale:[10,10,10]}]},{type:"group",position:[80.5,125.78,-52.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1126_1.geometry,material:nodes.Body1126_1.material,scale:[10,10,10]}]},{type:"group",position:[80.5,-83.22,-52.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1127.geometry,material:nodes.Body1127.material,scale:[10,10,10]}]},{type:"group",position:[289.5,-83.22,-52.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1128.geometry,material:nodes.Body1128.material,scale:[10,10,10]}]},{type:"group",position:[78,-103.72,-63.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1129.geometry,material:nodes.Body1129.material,scale:[10,10,10]}]},{type:"group",position:[78,-112.22,-70.59],rotation:[-Math.PI/2,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1116.geometry,material:nodes.Body1116.material,scale:[10,10,10]}]},{type:"group",position:[100,8.75,-47],children:[{type:"raw",geometry:nodes.Body1106.geometry,material:nodes.Body1106.material,scale:[10,10,10]}]},{type:"group",position:[270,8.75,-47],children:[{type:"raw",geometry:nodes.Body1107.geometry,material:nodes.Body1107.material,scale:[10,10,10]}]},{type:"group",position:[15,-193.72,-57.59],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1108.geometry,material:nodes.Body1108.material,scale:[10,10,10]}]},{type:"group",position:[184.6,144.25,-30],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1133.geometry,material:nodes.Body1133.material,scale:[10,10,10]}]},{type:"group",position:[270,22.28,-47],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1112.geometry,material:nodes.Body1112.material,scale:[10,10,10]}]},{type:"group",position:[100,-13.72,-47],children:[{type:"raw",geometry:nodes.Body1110.geometry,material:nodes.Body1110.material,scale:[10,10,10]}]},{type:"group",position:[100,56.28,-47],children:[{type:"raw",geometry:nodes.Body1111.geometry,material:nodes.Body1111.material,scale:[10,10,10]}]},{type:"group",position:[185,21.28,-63.59],children:[{type:"raw",geometry:nodes.Body1115.geometry,material:nodes.Body1115.material,scale:[10,10,10]}]},{type:"group",position:[216,-120.25,-28.96],rotation:[Math.PI,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1113.geometry,material:nodes.Body1113.material,scale:[10,10,10]}]},{type:"group",position:[174.6,144.25,-30],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1122_1.geometry,material:nodes.Body1122_1.material,scale:[10,10,10]}]},{type:"group",position:[78,-103.72,-68.59],children:[{type:"raw",geometry:nodes.Body1130.geometry,material:nodes.Body1130.material,scale:[10,10,10]}]},{type:"group",position:[188.5,-120.25,-28.96],rotation:[-Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1114.geometry,material:nodes.Body1114.material,scale:[10,10,10]}]},{type:"group",position:[186,-132,-48.34],children:[{type:"raw",geometry:nodes.Body1117.geometry,material:nodes.Body1117.material,scale:[10,10,10]}]},{type:"group",position:[176.5,-132,-48.34],children:[{type:"raw",geometry:nodes.Body1118.geometry,material:nodes.Body1118.material,scale:[10,10,10]}]},{type:"group",position:[196,-135.75,-44.46],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1131.geometry,material:nodes.Body1131.material,scale:[10,10,10]}]},{type:"group",position:[196,-135.75,-13.46],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1132.geometry,material:nodes.Body1132.material,scale:[10,10,10]}]},{type:"group",position:[185,41.28,-48.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1123_1.geometry,material:nodes.Body1123_1.material,scale:[10,10,10]}]},{type:"group",position:[185,.28,-48.59],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1124_1.geometry,material:nodes.Body1124_1.material,scale:[10,10,10]}]},{type:"group",position:[194.6,144.25,-30],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1121.geometry,material:nodes.Body1121.material,scale:[10,10,10]}]},{type:"group",position:[176.5,-132,-45.14],rotation:[Math.PI/2,0,Math.PI],children:[{type:"group",position:[-7.55,0,-9],children:[{type:"raw",geometry:nodes.Body1134.geometry,material:nodes.Body1134.material,scale:[10,10,10]}]},{type:"raw",geometry:nodes.Body1135.geometry,material:nodes.Body1135.material,scale:[10,10,10]}]},{type:"group",position:[174.6,144.25,-30],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1120.geometry,material:nodes.Body1120.material,scale:[10,10,10]}]},{type:"group",position:[194.6,144.25,-30],rotation:[0,1.57,0],children:[{type:"raw",geometry:nodes.Body1119.geometry,material:nodes.Body1119.material,scale:[10,10,10]}]},{type:"group",position:[177.5,38.78,-26.59],rotation:[0,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1109.geometry,material:nodes.Body1109.material,scale:[10,10,10]}]}]}]},{type:"group",position:[-170.6,1038.41,1090.43],rotation:[0,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1195.geometry,material:nodes.Body1195.material,scale:[10,10,10]}]},{type:"group",position:[170.6,541.82,1347.72],rotation:[-.96,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1194.geometry,material:nodes.Body1194.material,scale:[10,10,10]}]},{type:"group",position:[-164.2,-2.2,-360],rotation:[Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1242.geometry,material:nodes.Body1242.material,scale:[10,10,10]}]},{type:"group",position:[164.2,-2.2,-360],rotation:[Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1245.geometry,material:nodes.Body1245.material,scale:[10,10,10]}]},{type:"group",position:[-165.1,-2.2,-341],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1243.geometry,material:nodes.Body1243.material,scale:[10,10,10]}]},{type:"group",position:[165.1,-2.2,-341],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1244.geometry,material:nodes.Body1244.material,scale:[10,10,10]}]},{type:"group",position:[177.8,46,-2],rotation:[-Math.PI,1.57,0],children:[{type:"raw",geometry:nodes.Body1190.geometry,material:materials["Opaque(135,140,140)"],scale:[10,10,10]}]},{type:"group",position:[161,-60.5,-193],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1196.geometry,material:nodes.Body1196.material,scale:[10,10,10]}]},{type:"group",position:[161,-60.5,-76],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1197.geometry,material:nodes.Body1197.material,scale:[10,10,10]}]},{type:"group",position:[0,40.75,13],children:[{type:"group",position:[-165,150,-15],children:[{type:"raw",geometry:nodes.Body1153.geometry,material:nodes.Body1153.material,scale:[10,10,10]}]},{type:"group",position:[165,150,-15],children:[{type:"raw",geometry:nodes.Body1154.geometry,material:nodes.Body1154.material,scale:[10,10,10]}]},{type:"group",position:[180,165,-15],rotation:[0,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1155.geometry,material:nodes.Body1155.material,scale:[10,10,10]}]},{type:"group",position:[180,-165,-15],rotation:[0,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1156.geometry,material:nodes.Body1156.material,scale:[10,10,10]}]},{type:"group",position:[180,-55.75,-373],rotation:[-Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1159.geometry,material:nodes.Body1159.material,scale:[10,10,10]}]},{type:"group",position:[-165,-55.75,-30],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1157.geometry,material:nodes.Body1157.material,scale:[10,10,10]}]},{type:"group",position:[165,-55.75,-30],rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1158.geometry,material:nodes.Body1158.material,scale:[10,10,10]}]},{type:"group",position:[-164,-74.75,-372],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1172.geometry,material:nodes.Body1172.material,scale:[10,10,10]}]},{type:"group",position:[164,-70.75,-372],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1173.geometry,material:nodes.Body1173.material,scale:[10,10,10]}]},{type:"group",position:[-180,-64.75,-6],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1166.geometry,material:nodes.Body1166.material,scale:[10,10,10]}]},{type:"group",position:[-150,-64.75,-6],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1167.geometry,material:nodes.Body1167.material,scale:[10,10,10]}]},{type:"group",position:[182,-64.75,-6],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1169.geometry,material:nodes.Body1169.material,scale:[10,10,10]}]},{type:"group",position:[148,-64.75,-6],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1170.geometry,material:nodes.Body1170.material,scale:[10,10,10]}]},{type:"group",position:[-165,165,5],rotation:[-Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1180.geometry,material:nodes.Body1180.material,scale:[10,10,10]}]},{type:"group",position:[-165,-165,5],rotation:[Math.PI/2,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1181.geometry,material:nodes.Body1181.material,scale:[10,10,10]}]},{type:"group",position:[165,165,5],rotation:[-Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1186.geometry,material:nodes.Body1186.material,scale:[10,10,10]}]},{type:"group",position:[165,-165,5],rotation:[-Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1187.geometry,material:nodes.Body1187.material,scale:[10,10,10]}]},{type:"group",position:[-165,165,5],rotation:[-Math.PI,0,2.56],children:[{type:"raw",geometry:nodes.Body1182.geometry,material:nodes.Body1182.material,scale:[10,10,10]}]},{type:"group",position:[-165,-165,5],rotation:[Math.PI,0,2.56],children:[{type:"raw",geometry:nodes.Body1183.geometry,material:nodes.Body1183.material,scale:[10,10,10]}]},{type:"group",position:[165,165,5],rotation:[Math.PI,0,-.58],children:[{type:"raw",geometry:nodes.Body1184.geometry,material:nodes.Body1184.material,scale:[10,10,10]}]},{type:"group",position:[165,-165,5],rotation:[Math.PI,0,-.58],children:[{type:"raw",geometry:nodes.Body1185.geometry,material:nodes.Body1185.material,scale:[10,10,10]}]},{type:"group",position:[-85,157.5,-38.5],children:[{type:"raw",geometry:nodes.Body1160.geometry,material:nodes.Body1160.material,scale:[10,10,10]}]},{type:"group",position:[85,157.5,-38.5],children:[{type:"raw",geometry:nodes.Body1161.geometry,material:nodes.Body1161.material,scale:[10,10,10]}]},{type:"group",position:[-85,-157.5,-38.5],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1162.geometry,material:nodes.Body1162.material,scale:[10,10,10]}]},{type:"group",position:[85,-157.5,-38.5],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1163.geometry,material:nodes.Body1163.material,scale:[10,10,10]}]},{type:"group",position:[-165,-70.75,-30],rotation:[0,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1168.geometry,material:nodes.Body1168.material,scale:[10,10,10]}]},{type:"group",position:[165,-70.75,-30],rotation:[0,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1171.geometry,material:nodes.Body1171.material,scale:[10,10,10]}]},{type:"group",position:[-150,-55.75,-358],rotation:[Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1174.geometry,material:nodes.Body1174.material,scale:[10,10,10]}]},{type:"group",position:[150,-55.75,-358],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1175.geometry,material:nodes.Body1175.material,scale:[10,10,10]}]},{type:"group",position:[-150,150,-15],rotation:[-Math.PI,-1.57,0],children:[{type:"raw",geometry:nodes.Body1176.geometry,material:nodes.Body1176.material,scale:[10,10,10]}]},{type:"group",position:[-150,-150,-15],rotation:[Math.PI/2,0,-Math.PI/2],children:[{type:"raw",geometry:nodes.Body1177.geometry,material:nodes.Body1177.material,scale:[10,10,10]}]},{type:"group",position:[150,150,-15],rotation:[-Math.PI,1.57,0],children:[{type:"raw",geometry:nodes.Body1178.geometry,material:nodes.Body1178.material,scale:[10,10,10]}]},{type:"group",position:[150,-150,-15],rotation:[Math.PI/2,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1179.geometry,material:nodes.Body1179.material,scale:[10,10,10]}]},{type:"group",position:[-150.1,-34.75,-298],rotation:[0,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1164.geometry,material:nodes.Body1164.material,scale:[10,10,10]}]},{type:"group",position:[180.1,-34.75,-298],rotation:[0,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1165.geometry,material:nodes.Body1165.material,scale:[10,10,10]}]}]},{type:"group",position:[-192.5,-36.5,-168.5],rotation:[0,-1.57,0],children:[{type:"raw",geometry:nodes.Body1238.geometry,material:nodes.Body1238.material,scale:[10,10,10]}]},{type:"group",position:[126.5,-139.25,-17],rotation:[-Math.PI/2,0,-Math.PI],children:[{type:"raw",geometry:nodes.Body1198.geometry,material:nodes.Body1198.material,scale:[10,10,10]}]},{type:"group",position:[194.25,24.3,-198.47],rotation:[Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1246.geometry,material:materials["Opaque(255,132,2)"],scale:[10,10,10]}]},{type:"group",position:[18,-117.25,19.96],rotation:[0,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1191.geometry,material:nodes.Body1191.material,scale:[10,10,10]}]},{type:"group",position:[-.4,191.15,-2],rotation:[-Math.PI/2,0,0],children:[{type:"group",position:[.02,-4.95,-14.3],rotation:[1.73,0,Math.PI/2],children:[{type:"raw",geometry:nodes.Body1192.geometry,material:materials["Opaque(254,114,55)"],scale:[10,10,10]}]},{type:"group",rotation:[Math.PI/2,0,0],children:[{type:"raw",geometry:nodes.Body1193.geometry,material:nodes.Body1193.material,scale:[10,10,10]}]}]},{type:"group",position:[85,46.08,-27],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1239.geometry,material:nodes.Body1239.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body2001.geometry,material:nodes.Body2001.material,scale:[10,10,10]}]},{type:"group",position:[-85,96.48,-27],rotation:[-Math.PI,0,0],children:[{type:"raw",geometry:nodes.Body1240.geometry,material:nodes.Body1240.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body2002.geometry,material:nodes.Body2002.material,scale:[10,10,10]}]},{type:"group",position:[-85,10.08,-27],rotation:[Math.PI,0,Math.PI],children:[{type:"raw",geometry:nodes.Body1241.geometry,material:nodes.Body1241.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body2003.geometry,material:nodes.Body2003.material,scale:[10,10,10]}]},{type:"group",position:[-.75,-310.07,-900.2],rotation:[1.24,0,0],children:[{type:"raw",geometry:nodes.Body1218.geometry,material:nodes.Body1218.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1206.geometry,material:nodes.Body1206.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1233.geometry,material:nodes.Body1233.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1232.geometry,material:nodes.Body1232.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1222.geometry,material:nodes.Body1222.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1223.geometry,material:materials["Opaque(57,57,57)"],scale:[10,10,10]},{type:"raw",geometry:nodes.Body1237.geometry,material:nodes.Body1237.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1234.geometry,material:nodes.Body1234.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1221.geometry,material:nodes.Body1221.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1229.geometry,material:nodes.Body1229.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1217.geometry,material:nodes.Body1217.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1227.geometry,material:nodes.Body1227.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1213.geometry,material:nodes.Body1213.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1207.geometry,material:nodes.Body1207.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1212.geometry,material:nodes.Body1212.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1220.geometry,material:nodes.Body1220.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1216.geometry,material:nodes.Body1216.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1209.geometry,material:nodes.Body1209.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1211.geometry,material:nodes.Body1211.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1225.geometry,material:nodes.Body1225.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1228.geometry,material:nodes.Body1228.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1210.geometry,material:nodes.Body1210.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1235.geometry,material:nodes.Body1235.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1204.geometry,material:nodes.Body1204.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1231.geometry,material:nodes.Body1231.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1224.geometry,material:nodes.Body1224.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1201.geometry,material:nodes.Body1201.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1205.geometry,material:nodes.Body1205.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1226.geometry,material:nodes.Body1226.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1202.geometry,material:nodes.Body1202.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1236.geometry,material:nodes.Body1236.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1203.geometry,material:nodes.Body1203.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1215.geometry,material:nodes.Body1215.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1214.geometry,material:nodes.Body1214.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1208.geometry,material:nodes.Body1208.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1230.geometry,material:nodes.Body1230.material,scale:[10,10,10]},{type:"raw",geometry:nodes.Body1219.geometry,material:nodes.Body1219.material,scale:[10,10,10]}]},{type:"group",position:[-138.5,25,-55],rotation:[-Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1188.geometry,material:nodes.Body1188.material,scale:[10,10,10]}]},{type:"group",position:[138.5,25,-55],rotation:[-Math.PI/2,-Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1189.geometry,material:nodes.Body1189.material,scale:[10,10,10]}]},{type:"group",position:[191.7,19,-370],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1199.geometry,material:nodes.Body1199.material,scale:[10,10,10]}]},{type:"group",position:[-191.7,19,-370],rotation:[Math.PI/2,Math.PI/2,0],children:[{type:"raw",geometry:nodes.Body1200.geometry,material:nodes.Body1200.material,scale:[10,10,10]}]}]}]}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/MK2-Printer.stl":function Collision_Mk2_Printer_Model(props){var nodes=(0,useGLTF.L)(Collision_MK2_Printer_namespaceObject).nodes;return[{type:"raw",geometry:nodes["Collision-MK2-Printer"].geometry,material:nodes["Collision-MK2-Printer"].material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/Box/Box.stl":function Box_Model(props){var nodes=(0,useGLTF.L)(Box_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Box.geometry,material:nodes.Box.material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/Box.stl":function Collision_Box_Model(props){var nodes=(0,useGLTF.L)(Collision_Box_namespaceObject).nodes;return[{type:"raw",geometry:nodes["Collision-Box"].geometry,material:nodes["Collision-Box"].material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/ur3e-Pedestal/Pedestal.stl":function Pedestal_Model(props){var nodes=(0,useGLTF.L)(Pedestal_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Pedestal.geometry,material:nodes.Pedestal.material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/Pedestal.stl":function Collision_Pedestal_Model(props){var nodes=(0,useGLTF.L)(Collision_Pedestal_namespaceObject).nodes;return[{type:"raw",geometry:nodes["Collision-Pedestal"].geometry,material:nodes["Collision-Pedestal"].material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/models/Table/Table.stl":function Table_Model(props){var nodes=(0,useGLTF.L)(Table_namespaceObject).nodes;return[{type:"raw",geometry:nodes.Table.geometry,material:nodes.Table.material}]},"package://evd_ros_tasks/tasks/3d_printer_machine_tending/collision_meshes/Table.stl":function Collision_Table_Model(props){var nodes=(0,useGLTF.L)(Collision_Table_namespaceObject).nodes;return[{type:"raw",geometry:nodes["Collision-Table"].geometry,material:nodes["Collision-Table"].material}]},"package://app/meshes/LocationMarker.stl":function LocationMarker_Model(props){var nodes=(0,useGLTF.L)(LocationMarker_namespaceObject).nodes;return[{type:"group",children:[{type:"raw",geometry:nodes.LocationMarker.geometry,material:nodes.LocationMarker.material}]}]},"package://app/meshes/OpenWaypointMarker.stl":function OpenWaypointMarker_Model(props){var nodes=(0,useGLTF.L)(OpenWaypointMarker_namespaceObject).nodes;return[{type:"group",children:[{type:"raw",geometry:nodes.OpenWaypointMarker.geometry,material:nodes.OpenWaypointMarker.material}]}]}},MeshLookup=function MeshLookup(path){return MeshLookupTable[path]()};MeshLookup.__docgenInfo={description:"",methods:[],displayName:"MeshLookup"},"undefined"!=typeof STORYBOOK_REACT_CLASSES&&(STORYBOOK_REACT_CLASSES["src/stories/meshes/MeshLookup.js"]={name:"MeshLookup",docgenInfo:MeshLookup.__docgenInfo,path:"src/stories/meshes/MeshLookup.js"})},"./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.(js%7Cjsx%7Cts%7Ctsx))$":function(module,__unused_webpack_exports,__webpack_require__){var map={"./stories/Animation.stories.js":"./src/stories/Animation.stories.js","./stories/CoFrame.stories.js":"./src/stories/CoFrame.stories.js","./stories/ItemMovement.stories.js":"./src/stories/ItemMovement.stories.js","./stories/MeshDebug.stories.js":"./src/stories/MeshDebug.stories.js","./stories/Random.stories.js":"./src/stories/Random.stories.js","./stories/TFMovement.stories.js":"./src/stories/TFMovement.stories.js"};function webpackContext(req){var id=webpackContextResolve(req);return __webpack_require__(id)}function webpackContextResolve(req){if(!__webpack_require__.o(map,req)){var e=new Error("Cannot find module '"+req+"'");throw e.code="MODULE_NOT_FOUND",e}return map[req]}webpackContext.keys=function webpackContextKeys(){return Object.keys(map)},webpackContext.resolve=webpackContextResolve,module.exports=webpackContext,webpackContext.id="./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.(js%7Cjsx%7Cts%7Ctsx))$"},"./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.mdx)$":function(module){function webpackEmptyContext(req){var e=new Error("Cannot find module '"+req+"'");throw e.code="MODULE_NOT_FOUND",e}webpackEmptyContext.keys=function(){return[]},webpackEmptyContext.resolve=webpackEmptyContext,webpackEmptyContext.id="./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.mdx)$",module.exports=webpackEmptyContext},"./storybook-init-framework-entry.js":function(__unused_webpack_module,__unused_webpack___webpack_exports__,__webpack_require__){"use strict";__webpack_require__("./node_modules/@storybook/react/dist/esm/client/index.js")},"?4f7e":function(){},"./generated-stories-entry.cjs":function(module,__unused_webpack_exports,__webpack_require__){"use strict";module=__webpack_require__.nmd(module),(0,__webpack_require__("./node_modules/@storybook/react/dist/esm/client/index.js").configure)([__webpack_require__("./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.mdx)$"),__webpack_require__("./src sync recursive ^\\.(?:(?:^%7C\\/%7C(?:(?:(?%21(?:^%7C\\/)\\.).)*?)\\/)(?%21\\.)(?=.)[^/]*?\\.stories\\.(js%7Cjsx%7Cts%7Ctsx))$")],module,!1)}},function(__webpack_require__){var __webpack_exec__=function(moduleId){return __webpack_require__(__webpack_require__.s=moduleId)};__webpack_require__.O(0,[617],(function(){return __webpack_exec__("./node_modules/@storybook/core-client/dist/esm/globals/polyfills.js"),__webpack_exec__("./node_modules/@storybook/core-client/dist/esm/globals/globals.js"),__webpack_exec__("./storybook-init-framework-entry.js"),__webpack_exec__("./node_modules/@storybook/react/dist/esm/client/docs/config-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/react/dist/esm/client/preview/config-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-links/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-docs/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-actions/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-backgrounds/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-measure/preview.js-generated-config-entry.js"),__webpack_exec__("./node_modules/@storybook/addon-outline/preview.js-generated-config-entry.js"),__webpack_exec__("./.storybook/preview.js-generated-config-entry.js"),__webpack_exec__("./generated-stories-entry.cjs")}));__webpack_require__.O()}]); \ No newline at end of file diff --git a/docs/project.json b/docs/project.json index fea74bb..1528813 100644 --- a/docs/project.json +++ b/docs/project.json @@ -1 +1 @@ -{"generatedAt":1657155687007,"builder":{"name":"webpack5"},"hasCustomBabel":false,"hasCustomWebpack":false,"hasStaticDirs":false,"hasStorybookEslint":false,"refCount":0,"metaFramework":{"name":"CRA","packageName":"react-scripts","version":"5.0.1"},"packageManager":{"type":"yarn","version":"1.22.18"},"storybookVersion":"6.5.9","language":"javascript","storybookPackages":{"@storybook/addon-actions":{"version":"6.5.9"},"@storybook/addon-interactions":{"version":"6.5.9"},"@storybook/builder-webpack5":{"version":"6.5.9"},"@storybook/manager-webpack5":{"version":"6.5.9"},"@storybook/node-logger":{"version":"6.5.9"},"@storybook/preset-create-react-app":{"version":"4.1.2"},"@storybook/react":{"version":"6.5.9"},"@storybook/testing-library":{"version":"0.0.13"}},"framework":{"name":"react"},"addons":{"@storybook/addon-links":{"version":"6.5.9"},"@storybook/addon-essentials":{"version":"6.5.9"},"@storybook-create-react-app":{"version":null}}} +{"generatedAt":1657157189215,"builder":{"name":"webpack5"},"hasCustomBabel":false,"hasCustomWebpack":false,"hasStaticDirs":false,"hasStorybookEslint":false,"refCount":0,"metaFramework":{"name":"CRA","packageName":"react-scripts","version":"5.0.1"},"packageManager":{"type":"yarn","version":"1.22.18"},"storybookVersion":"6.5.9","language":"javascript","storybookPackages":{"@storybook/addon-actions":{"version":"6.5.9"},"@storybook/addon-interactions":{"version":"6.5.9"},"@storybook/builder-webpack5":{"version":"6.5.9"},"@storybook/manager-webpack5":{"version":"6.5.9"},"@storybook/node-logger":{"version":"6.5.9"},"@storybook/preset-create-react-app":{"version":"4.1.2"},"@storybook/react":{"version":"6.5.9"},"@storybook/testing-library":{"version":"0.0.13"}},"framework":{"name":"react"},"addons":{"@storybook/addon-links":{"version":"6.5.9"},"@storybook/addon-essentials":{"version":"6.5.9"},"@storybook-create-react-app":{"version":null}}} diff --git a/package.json b/package.json index 5006c72..c0db7a0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "robot-scene", - "version": "0.8.0", + "version": "0.8.1", "main": "dist/index.js", "module": "dist/index.es.js", "private": false, @@ -18,9 +18,6 @@ }, "dependencies": { "@juggle/resize-observer": "^3.3.1", - "@react-three/drei": "^9.2.0", - "@react-three/fiber": "^8.0.10", - "@react-three/postprocessing": "^2.3.2", "@testing-library/jest-dom": "^5.16.4", "@testing-library/react": "^13.3.0", "@testing-library/user-event": "^13.5.0", @@ -29,8 +26,10 @@ "number-precision": "^1.5.2", "postprocessing": "^6.26.2", "react-scripts": "5.0.1", - "three": "^0.139.0", - "three-stdlib": "^2.12.1", + "@react-three/drei": "^9.2.0", + "@react-three/fiber": "^8.0.10", + "@react-three/postprocessing": "^2.3.2", + "three": "^0.142.0", "web-vitals": "^2.1.4", "zustand": "^4.0.0-rc.1" }, @@ -73,7 +72,8 @@ }, "peerDependencies": { "react": "^18.2.0", - "react-dom": "^18.2.0" + "react-dom": "^18.2.0", + "three-stdlib": "^2.12.1" }, "devDependencies": { "@babel/cli": "^7.17.10", @@ -97,6 +97,7 @@ "react-dom": "^18.2.0", "rollup-plugin-peer-deps-external": "^2.2.4", "rollup-plugin-terser": "^7.0.2", - "webpack": "^5.73.0" + "webpack": "^5.73.0", + "three-stdlib": "^2.12.1" } } diff --git a/src/components/Util/StandardMeshes.js b/src/components/Util/StandardMeshes.js index 8632746..6e3edcc 100644 --- a/src/components/Util/StandardMeshes.js +++ b/src/components/Util/StandardMeshes.js @@ -6,7 +6,7 @@ import { Vector3 } from "three"; -// import { RoundedBoxGeometry } from 'three-stdlib'; +import { RoundedBoxGeometry } from 'three-stdlib'; import { mergeBufferGeometries } from "three-stdlib/utils/BufferGeometryUtils"; @@ -32,9 +32,8 @@ export const BOX_GEOM = (params) => { x = x === undefined ? boxGeomDefaultDim : x; y = y === undefined ? boxGeomDefaultDim : y; z = z === undefined ? boxGeomDefaultDim : z; - // RoundedBoxGeometry() - // return new RoundedBoxGeometry(x, y, z, 2, 0.05) - return new BoxBufferGeometry(x,y,z) + + return new RoundedBoxGeometry(x, y, z, 2, 0.05) } /* * Sphere Mesh diff --git a/yarn.lock b/yarn.lock index ac25fbc..55ba2ff 100644 --- a/yarn.lock +++ b/yarn.lock @@ -13683,10 +13683,10 @@ three-stdlib@^2.10.2, three-stdlib@^2.12.1, three-stdlib@^2.8.11: potpack "^1.0.1" zstddec "^0.0.2" -three@^0.139.0: - version "0.139.2" - resolved "https://registry.yarnpkg.com/three/-/three-0.139.2.tgz#b110799a15736df673b9293e31653a4ac73648dd" - integrity sha512-gV7q7QY8rogu7HLFZR9cWnOQAUedUhu2WXAnpr2kdXZP9YDKsG/0ychwQvWkZN5PlNw9mv5MoCTin6zNTXoONg== +three@^0.142.0: + version "0.142.0" + resolved "https://registry.yarnpkg.com/three/-/three-0.142.0.tgz#89e226a16221f212eb1d40f0786604b711f28aed" + integrity sha512-ESjPO+3geFr+ZUfVMpMnF/eVU2uJPOh0e2ZpMFqjNca1wApS9lJb7E4MjwGIczgt9iuKd8PEm6Pfgp2bJ92Xtg== throat@^6.0.1: version "6.0.1"